From d7c130fca9ad04f912caa4c9b552229cac0b6b50 Mon Sep 17 00:00:00 2001
From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com>
Date: Wed, 5 Aug 2026 12:03:12 +0100
Subject: [PATCH 01/99] Serve SPA shell for deep frontend routes (#7145)
# Description of Changes
stops the /new urls crashing page on f5
---
## Checklist
### General
- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings
### Documentation
- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)
### Translations (if applicable)
- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)
### UI Changes (if applicable)
- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)
### Testing (if applicable)
- [ ] I have run `task check` to verify linters, typechecks, and tests
pass
- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
---------
Co-authored-by: Reece Browne <74901996+reecebrowne@users.noreply.github.com>
---
.../web/ReactRoutingController.java | 89 +++++++++++++++++++
.../web/ReactRoutingControllerTest.java | 89 +++++++++++++++++++
frontend/editor/scripts/lint/theme-lint.mjs | 6 +-
3 files changed, 183 insertions(+), 1 deletion(-)
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/web/ReactRoutingController.java b/app/core/src/main/java/stirling/software/SPDF/controller/web/ReactRoutingController.java
index 1e05ec17b2..7689d109fe 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/web/ReactRoutingController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/web/ReactRoutingController.java
@@ -5,17 +5,26 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.List;
+import java.util.Set;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.core.Ordered;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.servlet.function.RouterFunction;
+import org.springframework.web.servlet.function.RouterFunctions;
+import org.springframework.web.servlet.function.ServerResponse;
+import org.springframework.web.servlet.function.support.RouterFunctionMapping;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.JavaScriptUtils;
@@ -32,6 +41,33 @@ public class ReactRoutingController {
private static final Pattern BASE_HREF_PATTERN =
Pattern.compile("");
+ // First path segments owned by the backend or static assets, never SPA routes.
+ // Mirrors the exclusion regexes on forwardRootPaths/forwardNestedPaths below.
+ private static final Set NON_SPA_FIRST_SEGMENTS =
+ Set.of(
+ "api",
+ "static",
+ "pipeline",
+ "pdfjs",
+ "pdfjs-legacy",
+ "pdfium",
+ "vendor",
+ "fonts",
+ "images",
+ "css",
+ "js",
+ "assets",
+ "locales",
+ "modern-logo",
+ "classic-logo",
+ "Login",
+ "og_images",
+ "samples");
+
+ // After the annotated controllers (order 0), before the resource chain
+ // (LOWEST_PRECEDENCE - 1).
+ private static final int SPA_FALLBACK_ORDER = Ordered.LOWEST_PRECEDENCE - 2;
+
@Value("${server.servlet.context-path:/}")
private String contextPath;
@@ -256,6 +292,59 @@ public class ReactRoutingController {
return serveIndexHtml(request);
}
+ // The regex mappings above only cover 1- and 2-segment paths (Spring path variables cannot
+ // span '/'), so deep SPA links like /processor/pipelines/new 404d on direct navigation.
+ //
+ // Registered as its own mapping rather than exposed as a bare RouterFunction @Bean:
+ // Spring's own RouterFunctionMapping is ordered -1, ahead of the annotated controllers at
+ // order 0, so a plain bean would shadow every dot-free backend route the denylist below
+ // does not name (/v1/api-docs, /error, /actuator, ...). LOWEST_PRECEDENCE - 2 puts it after
+ // the controllers and before the resource chain (LOWEST_PRECEDENCE - 1), which is the only
+ // position where a catch-all fallback is safe.
+ @Bean
+ public RouterFunctionMapping spaDeepLinkFallbackMapping() {
+ RouterFunction fallback =
+ RouterFunctions.route(
+ request -> {
+ HttpServletRequest servletRequest = request.servletRequest();
+ return "GET".equals(servletRequest.getMethod())
+ && isSpaFallbackRoute(
+ stripContextPath(
+ servletRequest.getContextPath(),
+ servletRequest.getRequestURI()));
+ },
+ request ->
+ ServerResponse.ok()
+ .cacheControl(CacheControl.noCache().mustRevalidate())
+ .contentType(MediaType.TEXT_HTML)
+ .body(serveIndexHtml(request.servletRequest()).getBody()));
+ RouterFunctionMapping mapping = new RouterFunctionMapping(fallback);
+ mapping.setOrder(SPA_FALLBACK_ORDER);
+ mapping.setMessageConverters(
+ List.of(new StringHttpMessageConverter(StandardCharsets.UTF_8)));
+ return mapping;
+ }
+
+ // Dot-free paths only, so requests for real files still fall through to the resource
+ // handlers. This is a denylist, so it is only safe because the mapping above runs after
+ // the annotated controllers - see spaDeepLinkFallbackMapping.
+ static boolean isSpaFallbackRoute(String path) {
+ if (path == null || path.isEmpty() || "/".equals(path) || path.indexOf('.') >= 0) {
+ return false;
+ }
+ String[] segments = (path.startsWith("/") ? path.substring(1) : path).split("/");
+ return segments.length > 0
+ && !segments[0].isEmpty()
+ && !NON_SPA_FIRST_SEGMENTS.contains(segments[0]);
+ }
+
+ private static String stripContextPath(String contextPath, String uri) {
+ if (contextPath != null && !contextPath.isBlank() && uri.startsWith(contextPath)) {
+ return uri.substring(contextPath.length());
+ }
+ return uri;
+ }
+
private String buildFallbackHtml() {
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/web/ReactRoutingControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/web/ReactRoutingControllerTest.java
index 2df3fb5587..41909e3e0a 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/web/ReactRoutingControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/web/ReactRoutingControllerTest.java
@@ -4,12 +4,24 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.StringHttpMessageConverter;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.web.servlet.function.EntityResponse;
+import org.springframework.web.servlet.function.HandlerFunction;
+import org.springframework.web.servlet.function.RouterFunction;
+import org.springframework.web.servlet.function.ServerRequest;
+import org.springframework.web.servlet.function.ServerResponse;
+import org.springframework.web.servlet.function.support.RouterFunctionMapping;
+import org.springframework.web.util.ServletRequestPathUtils;
import jakarta.servlet.http.HttpServletRequest;
@@ -175,6 +187,83 @@ class ReactRoutingControllerTest {
assertNotNull(response.getBody());
}
+ // --- deep-link SPA fallback (router function) ---
+
+ @Test
+ void isSpaFallbackRoute_acceptsDeepSpaPaths() {
+ assertTrue(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/new"));
+ assertTrue(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/123/runs/456"));
+ assertTrue(ReactRoutingController.isSpaFallbackRoute("/workflow/sign/some-token"));
+ assertTrue(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/new/"));
+ // "pipelines" must not be swallowed by the "pipeline" exclusion
+ assertTrue(ReactRoutingController.isSpaFallbackRoute("/pipelines"));
+ }
+
+ @Test
+ void isSpaFallbackRoute_rejectsBackendStaticAndFilePaths() {
+ assertFalse(ReactRoutingController.isSpaFallbackRoute("/api/v1/some/endpoint"));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute("/pipeline"));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute("/pipeline/anything"));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute("/assets/deep/path"));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute("/processor/pipelines/file.js"));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute("/branding/sub/logo.png"));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute("/"));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute(""));
+ assertFalse(ReactRoutingController.isSpaFallbackRoute(null));
+ }
+
+ @Test
+ void spaDeepLinkFallback_servesIndexForDeepRoute() throws Exception {
+ controller.init();
+ RouterFunction router = routerOf(controller.spaDeepLinkFallbackMapping());
+
+ ServerRequest deepRequest = serverRequest("GET", "/processor/pipelines/new");
+ Optional> handler = router.route(deepRequest);
+ assertTrue(handler.isPresent());
+
+ ServerResponse response = handler.get().handle(deepRequest);
+ assertEquals(HttpStatus.OK, response.statusCode());
+ assertInstanceOf(EntityResponse.class, response);
+ Object body = ((EntityResponse>) response).entity();
+ assertTrue(body.toString().contains("Stirling PDF"));
+ }
+
+ @Test
+ void spaDeepLinkFallback_ignoresApiFilesAndNonGet() {
+ controller.init();
+ RouterFunction router = routerOf(controller.spaDeepLinkFallbackMapping());
+
+ assertTrue(router.route(serverRequest("GET", "/api/v1/policies/run")).isEmpty());
+ assertTrue(router.route(serverRequest("GET", "/branding/sub/logo.png")).isEmpty());
+ assertTrue(router.route(serverRequest("POST", "/processor/pipelines/new")).isEmpty());
+ }
+
+ @Test
+ void spaDeepLinkFallback_runsAfterControllersAndBeforeResources() {
+ controller.init();
+ int order = controller.spaDeepLinkFallbackMapping().getOrder();
+
+ // A catch-all denylist is only safe below every annotated controller; Spring's own
+ // RouterFunctionMapping sits at -1, which would shadow /v1/api-docs, /error and friends.
+ assertTrue(order > 0, "SPA fallback must run after annotated controllers");
+ assertTrue(
+ order < Ordered.LOWEST_PRECEDENCE - 1,
+ "SPA fallback must run before the static-resource chain");
+ }
+
+ private static RouterFunction routerOf(RouterFunctionMapping mapping) {
+ @SuppressWarnings("unchecked")
+ RouterFunction router =
+ (RouterFunction) mapping.getRouterFunction();
+ return router;
+ }
+
+ private static ServerRequest serverRequest(String method, String uri) {
+ MockHttpServletRequest servletRequest = new MockHttpServletRequest(method, uri);
+ ServletRequestPathUtils.parseAndCache(servletRequest);
+ return ServerRequest.create(servletRequest, List.of(new StringHttpMessageConverter()));
+ }
+
// --- context path handling ---
@Test
diff --git a/frontend/editor/scripts/lint/theme-lint.mjs b/frontend/editor/scripts/lint/theme-lint.mjs
index 0ae53a3ce9..42f6153119 100644
--- a/frontend/editor/scripts/lint/theme-lint.mjs
+++ b/frontend/editor/scripts/lint/theme-lint.mjs
@@ -314,6 +314,10 @@ function check() {
const violations = [];
const primitiveValues = new Map();
const lineOf = (text, index) => text.slice(0, index).split("\n").length;
+ // path.relative emits backslashes on Windows; normalize so the PRIMITIVES
+ // comparison below matches and printed paths stay POSIX-style.
+ const posixRel = (name) =>
+ relative(process.cwd(), join(THEME, name)).replaceAll("\\", "/");
// Fail if a theme .css exists that isn't registered above (readdir is only
// compared here — never used to build a path passed to readFileSync).
@@ -321,7 +325,7 @@ function check() {
for (const name of readdirSync(THEME)) {
if (name.endsWith(".css") && !known.has(name)) {
violations.push({
- file: relative(process.cwd(), join(THEME, name)),
+ file: posixRel(name),
line: 1,
msg: `unregistered theme CSS — add "${name}" to THEME_FILES in theme-lint.mjs`,
});
From 62e5e28039d9e3cad1e101daf175c0774dd8aa33 Mon Sep 17 00:00:00 2001
From: Anthony Stirling <77850077+Frooodle@users.noreply.github.com>
Date: Wed, 5 Aug 2026 13:10:28 +0100
Subject: [PATCH 02/99] Avoid renderer OOM when adding large PDFs to the
workbench (#7175)
# Description of Changes
- "Out of Memory" tab crash on merge with big PDFs (Discord report) is a
WebView2 renderer OOM, not system RAM; adding files did 2 full parses +
a parallel full read per file
- IndexedDB now stores files as Blobs (by reference, no JS-side copy);
old ArrayBuffer records stay readable
- Both thumbnail variants now come from one PDFium parse instead of two
- PDFs over 100MB never get a full client-side parse: 2MB
linearized-prefix attempt, placeholder icon otherwise
- Follow-ups if placeholders aren't enough: backend-rendered thumbnails,
PDFium ranged reads in a worker
---
## Checklist
### General
- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings
### Documentation
- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)
### Translations (if applicable)
- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)
### UI Changes (if applicable)
- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)
### Testing (if applicable)
- [ ] I have run `task check` to verify linters, typechecks, and tests
pass
- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
---------
Co-authored-by: Reece Browne <74901996+reecebrowne@users.noreply.github.com>
---
.../fileEditor/FileEditorThumbnail.tsx | 4 +
.../src/core/components/shared/FileCard.tsx | 10 +-
.../src/core/contexts/file/fileActions.ts | 19 +-
.../editor/src/core/services/fileAnalyzer.ts | 81 ++++++--
.../editor/src/core/services/fileStorage.ts | 9 +-
.../src/core/utils/thumbnailUtils.test.ts | 53 ++++++
.../editor/src/core/utils/thumbnailUtils.ts | 180 +++++++++++++++++-
7 files changed, 324 insertions(+), 32 deletions(-)
create mode 100644 frontend/editor/src/core/utils/thumbnailUtils.test.ts
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
index e183e45d6e..ccf07e9dea 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -45,6 +45,7 @@ import { VersionHistoryModal } from "@app/components/filesPage/VersionHistoryMod
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
import { truncateCenter } from "@app/utils/textUtils";
import { FileEditorStatusDot } from "@app/components/fileEditor/FileEditorStatusDot";
@@ -553,6 +554,9 @@ const FileEditorThumbnail = ({
isLoading={
!isEncrypted &&
!displayThumbnail &&
+ // No thumbnail is ever produced at/above the parse limit, so
+ // without this the spinner has no terminal state.
+ file.size < LARGE_PDF_PARSE_LIMIT &&
(isThumbGenerating ||
file.type?.startsWith("application/pdf") ||
file.type?.startsWith("image/"))
diff --git a/frontend/editor/src/core/components/shared/FileCard.tsx b/frontend/editor/src/core/components/shared/FileCard.tsx
index e43dbeeb1c..495a76a53b 100644
--- a/frontend/editor/src/core/components/shared/FileCard.tsx
+++ b/frontend/editor/src/core/components/shared/FileCard.tsx
@@ -11,6 +11,7 @@ import { StirlingFileStub } from "@app/types/fileContext";
import { getFileSize, getFileDate } from "@app/utils/fileUtils";
import { useFileThumbnail } from "@app/hooks/useFileThumbnail";
import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";
+import { LARGE_PDF_PARSE_LIMIT } from "@app/utils/thumbnailUtils";
interface FileCardProps {
file: File;
@@ -44,7 +45,14 @@ const FileCard = ({
const [isHovered, setIsHovered] = useState(false);
const isPdf = file.type === "application/pdf";
- const isHydrating = isPdf && !isEncrypted && !thumb && !isGenerating;
+ // Files at/above the parse limit never get a thumbnail, so without the size
+ // check their spinner has no terminal state and runs forever.
+ const isHydrating =
+ isPdf &&
+ file.size < LARGE_PDF_PARSE_LIMIT &&
+ !isEncrypted &&
+ !thumb &&
+ !isGenerating;
return (
{
+ const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
+ if (bufferHasEncryptMarker(await file.slice(tailStart).arrayBuffer())) {
+ return true;
+ }
+ if (tailStart === 0) return false;
+ return bufferHasEncryptMarker(
+ await file.slice(0, ENCRYPT_PROBE_BYTES).arrayBuffer(),
+ );
+}
+
export class FileAnalyzer {
private static readonly SIZE_THRESHOLDS = {
SMALL: 10 * 1024 * 1024, // 10MB
@@ -80,32 +96,57 @@ export class FileAnalyzer {
/**
* Cheap encryption-only probe for the upload-time detection path.
*
- * Looks for a /Encrypt entry in the last 8KB of the file (where the PDF
- * trailer lives). If absent, the file is definitely not encrypted and we
- * can skip a full pdf.js parse. If present, falls back to pdf.js so we can
- * distinguish user-password (blocks open) from owner-password-only (opens
- * fine) — only the former should prompt.
+ * Looks for a /Encrypt entry in a bounded window at either end of the file
+ * (where PDF trailers live). If absent, the file is definitely not encrypted
+ * and we can skip a full pdf.js parse. If present, falls back to pdf.js so we
+ * can distinguish user-password (blocks open) from owner-password-only (opens
+ * fine); only the former should prompt.
+ *
+ * Runs inside the addFiles mutex, so it must always settle: an unbounded
+ * parse here stalls every later upload as well as this one.
*/
static async isPDFUserPasswordProtected(file: File): Promise {
- const arrayBuffer = await file.arrayBuffer();
- if (!hasEncryptMarker(arrayBuffer)) return false;
+ if (!(await hasEncryptMarker(file))) return false;
- let pdf: PDFDocumentProxy | undefined;
- try {
- pdf = await pdfWorkerManager.createDocument(arrayBuffer, {
- stopAtErrors: false,
- verbosity: 0,
+ // Too big to hand pdf.js: that full-buffer parse is the renderer OOM the
+ // large-file path exists to avoid, so trust the marker instead of it.
+ if (file.size >= LARGE_PDF_PARSE_LIMIT) return true;
+
+ const arrayBuffer = await file.arrayBuffer();
+ let timedOut = false;
+ let timer: ReturnType | undefined;
+ const opening = pdfWorkerManager
+ .createDocument(arrayBuffer, { stopAtErrors: false, verbosity: 0 })
+ .then((pdf) => {
+ // Arrived after the timeout won the race - nothing else frees it.
+ if (timedOut) pdfWorkerManager.destroyDocument(pdf);
+ return pdf;
});
+
+ try {
+ const pdf = await Promise.race([
+ opening,
+ new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ timedOut = true;
+ reject(new Error(PROBE_TIMEOUT));
+ }, PROBE_TIMEOUT_MS);
+ }),
+ ]);
+ pdfWorkerManager.destroyDocument(pdf);
// pdf.js opened it — owner-password-only case, no prompt needed.
return false;
} catch (error) {
const errorMessage =
error instanceof Error ? error.message.toLowerCase() : "";
+ // Unconfirmed either way; the /Encrypt marker is the better guess, and a
+ // spurious prompt beats a card that never stops spinning.
+ if (errorMessage === PROBE_TIMEOUT) return true;
return (
errorMessage.includes("password") || errorMessage.includes("encrypted")
);
} finally {
- if (pdf) pdfWorkerManager.destroyDocument(pdf);
+ clearTimeout(timer);
}
}
diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.ts
index 4cdecca9f1..4f82af3a8f 100644
--- a/frontend/editor/src/core/services/fileStorage.ts
+++ b/frontend/editor/src/core/services/fileStorage.ts
@@ -23,7 +23,9 @@ import {
const THUMBNAIL_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
export interface StoredStirlingFileRecord extends BaseFileMetadata {
- data: ArrayBuffer;
+ // Blob since the large-file OOM fix (stored by reference, no JS-side copy);
+ // ArrayBuffer records predate it and are still readable.
+ data: ArrayBuffer | Blob;
fileId: FileId; // Matches runtime StirlingFile.fileId exactly
quickKey: string; // Matches runtime StirlingFile.quickKey exactly
thumbnail?: string;
@@ -118,7 +120,6 @@ class FileStorageService {
stub: StirlingFileStub,
): Promise {
const db = await this.getDatabase();
- const arrayBuffer = await stirlingFile.arrayBuffer();
const record: StoredStirlingFileRecord = {
id: stirlingFile.fileId,
@@ -129,7 +130,9 @@ class FileStorageService {
size: stirlingFile.size,
lastModified: stirlingFile.lastModified,
createdAt: stub.createdAt,
- data: arrayBuffer,
+ // Store the File (a Blob) itself: IndexedDB persists it by reference and
+ // streams to disk, so multi-GB files never materialize in JS memory.
+ data: stirlingFile,
thumbnail: stub.thumbnailUrl,
thumbnailStoredAt: stub.thumbnailUrl ? Date.now() : undefined,
isLeaf: stub.isLeaf ?? true,
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.test.ts b/frontend/editor/src/core/utils/thumbnailUtils.test.ts
new file mode 100644
index 0000000000..c47bd05bdf
--- /dev/null
+++ b/frontend/editor/src/core/utils/thumbnailUtils.test.ts
@@ -0,0 +1,53 @@
+import { describe, it, expect } from "vitest";
+import { containsEncryptMarker } from "@app/utils/thumbnailUtils";
+
+/**
+ * The only signal that a PDF too large to fully parse is password-protected.
+ * Tested over raw bytes because jsdom's Blob does not return its own contents
+ * from arrayBuffer(), so the slicing wrapper cannot be exercised here.
+ */
+
+/** PDF-shaped bytes with `trailer` written at the very end. */
+function bytesEndingWith(trailer: string, size: number): Uint8Array {
+ const bytes = new Uint8Array(size).fill(0x20); // padding
+ const tail = new TextEncoder().encode(trailer);
+ bytes.set(tail, size - tail.length);
+ return bytes;
+}
+
+describe("containsEncryptMarker — trailer probe for large PDFs", () => {
+ it("detects /Encrypt in a trailer dictionary", () => {
+ const bytes = bytesEndingWith(
+ "trailer\n<< /Size 9 /Root 1 0 R /Encrypt 8 0 R >>\nstartxref\n1234\n%%EOF\n",
+ 4096,
+ );
+ expect(containsEncryptMarker(bytes)).toBe(true);
+ });
+
+ it("leaves an unencrypted document alone", () => {
+ const bytes = bytesEndingWith(
+ "trailer\n<< /Size 9 /Root 1 0 R >>\nstartxref\n1234\n%%EOF\n",
+ 4096,
+ );
+ expect(containsEncryptMarker(bytes)).toBe(false);
+ });
+
+ it("does not match longer keys that merely start the same way", () => {
+ const bytes = bytesEndingWith("<< /EncryptionAware true >>\n%%EOF\n", 512);
+ expect(containsEncryptMarker(bytes)).toBe(false);
+ });
+
+ it("survives binary bytes around the marker", () => {
+ // Under UTF-8 these become replacement characters and consume the marker.
+ const prefix = new Uint8Array([0xff, 0xfe, 0x80, 0x00, 0x9d]);
+ const marker = new TextEncoder().encode(" /Encrypt 8 0 R >>");
+ const bytes = new Uint8Array(prefix.length + marker.length);
+ bytes.set(prefix);
+ bytes.set(marker, prefix.length);
+ expect(containsEncryptMarker(bytes)).toBe(true);
+ });
+
+ it("reports nothing for an empty read", () => {
+ expect(containsEncryptMarker(new Uint8Array(0))).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/utils/thumbnailUtils.ts b/frontend/editor/src/core/utils/thumbnailUtils.ts
index 838992e38b..b356b26db9 100644
--- a/frontend/editor/src/core/utils/thumbnailUtils.ts
+++ b/frontend/editor/src/core/utils/thumbnailUtils.ts
@@ -31,6 +31,37 @@ export function calculateScaleFromFileSize(fileSize: number): number {
/** PDFium error code 4 = password required (encrypted PDF). */
const PDFIUM_ERR_PASSWORD = 4;
+/** PDFs at or above this size never get a full-buffer client-side parse
+ * (renderer OOM) - only the linearized-prefix attempt below. */
+export const LARGE_PDF_PARSE_LIMIT = 100 * 1024 * 1024;
+
+/** Linearized PDFs keep page 1 + hint tables in the first bytes, so a small
+ * prefix is often enough to render a thumbnail without reading the file. */
+const LINEARIZED_PREFIX_BYTES = 2 * 1024 * 1024;
+
+/** Window at each end of the file searched for an /Encrypt entry. */
+const ENCRYPT_PROBE_BYTES = 64 * 1024;
+
+/** Decoded latin1 because the input is binary - UTF-8 replacement characters
+ * can swallow the marker. \b excludes longer keys like /Encryption. */
+export function containsEncryptMarker(bytes: Uint8Array): boolean {
+ return /\/Encrypt\b/.test(new TextDecoder("latin1").decode(bytes));
+}
+
+/** /Encrypt is referenced from a trailer, never from the page data the prefix
+ * parse sees. Linearized PDFs (most large ones) keep their first-page trailer at
+ * the head and the main one at the tail, so both windows have to be probed.
+ * Heuristic: a false positive offers unlock on a file that did not need it, a
+ * false negative leaves it unopenable. */
+async function looksEncryptedFromTrailer(file: File): Promise {
+ const tailStart = Math.max(0, file.size - ENCRYPT_PROBE_BYTES);
+ const tail = await file.slice(tailStart).arrayBuffer();
+ if (containsEncryptMarker(new Uint8Array(tail))) return true;
+ if (tailStart === 0) return false;
+ const head = await file.slice(0, ENCRYPT_PROBE_BYTES).arrayBuffer();
+ return containsEncryptMarker(new Uint8Array(head));
+}
+
interface PdfiumRenderResult {
thumbnail: string;
pageCount: number;
@@ -112,6 +143,72 @@ async function renderPdfThumbnailPdfium(
}
}
+/**
+ * Render both thumbnail variants (upright + rotation-baked) from a single
+ * document open - halves the parse and memory cost of the add-files path.
+ */
+async function renderPdfThumbnailPairPdfium(
+ data: ArrayBuffer,
+ scale: number,
+ collectAllPagesMetadata: boolean,
+): Promise<{ unrotated: PdfiumRenderResult; rotated: PdfiumRenderResult }> {
+ const m = await getPdfiumModule();
+ let docPtr: number;
+ try {
+ docPtr = await openRawDocumentSafe(data);
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ new RegExp(`error ${PDFIUM_ERR_PASSWORD}`).test(error.message)
+ ) {
+ const encrypted: PdfiumRenderResult = {
+ thumbnail: "",
+ pageCount: 1,
+ pageRotations: [],
+ pageDimensions: [],
+ isEncrypted: true,
+ };
+ return { unrotated: encrypted, rotated: { ...encrypted } };
+ }
+ throw error;
+ }
+
+ try {
+ const pageCount = m.FPDF_GetPageCount(docPtr);
+ const unrotatedThumb = await renderPdfiumPageDataUrl(docPtr, 0, scale, {
+ applyRotation: false,
+ });
+ const rotatedThumb = await renderPdfiumPageDataUrl(docPtr, 0, scale, {
+ applyRotation: true,
+ });
+ if (!unrotatedThumb || !rotatedThumb) {
+ throw new Error("PDFium: failed to render page 0");
+ }
+
+ const firstMeta = await readPdfiumPageMetadata(docPtr, 0);
+ const pageRotations: number[] = [firstMeta?.rotation ?? 0];
+ const pageDimensions: Array<{ width: number; height: number }> = [
+ { width: firstMeta?.width ?? 0, height: firstMeta?.height ?? 0 },
+ ];
+ if (collectAllPagesMetadata) {
+ for (let i = 1; i < pageCount; i++) {
+ const meta = await readPdfiumPageMetadata(docPtr, i);
+ if (!meta) continue;
+ pageRotations[i] = meta.rotation;
+ pageDimensions[i] = { width: meta.width, height: meta.height };
+ }
+ }
+
+ const base = { pageCount, pageRotations, pageDimensions };
+ return {
+ unrotated: { thumbnail: unrotatedThumb, ...base },
+ rotated: { thumbnail: rotatedThumb, ...base },
+ };
+ } finally {
+ await closeRawDocument(docPtr);
+ }
+}
+
async function generatePDFThumbnail(
arrayBuffer: ArrayBuffer,
scale: number,
@@ -133,7 +230,7 @@ async function generatePDFThumbnail(
*/
export async function generateThumbnailForFile(file: File): Promise {
// Very large PDFs skip thumbnail generation — SVG icon shown in UI instead
- if (file.size >= 100 * 1024 * 1024) {
+ if (file.size >= LARGE_PDF_PARSE_LIMIT) {
return "";
}
@@ -152,8 +249,7 @@ export async function generateThumbnailForFile(file: File): Promise {
const scale = calculateScaleFromFileSize(file.size);
// Only read first 2MB for thumbnail generation to save memory
- const chunkSize = 2 * 1024 * 1024; // 2MB
- const chunk = file.slice(0, Math.min(chunkSize, file.size));
+ const chunk = file.slice(0, Math.min(LINEARIZED_PREFIX_BYTES, file.size));
const arrayBuffer = await chunk.arrayBuffer();
try {
@@ -193,6 +289,36 @@ export async function generateThumbnailWithMetadata(
const scale = calculateScaleFromFileSize(file.size);
+ // Never full-parse huge PDFs client-side - the renderer process OOMs long
+ // before system RAM runs out. The prefix succeeds for linearized PDFs.
+ if (file.size >= LARGE_PDF_PARSE_LIMIT) {
+ // Probe inside the try: an unreadable file must still resolve, or the
+ // caller leaves the card with no metadata and a spinner that never stops.
+ try {
+ if (await looksEncryptedFromTrailer(file)) {
+ return { thumbnail: "", pageCount: 1, isEncrypted: true };
+ }
+ const chunk = await file.slice(0, LINEARIZED_PREFIX_BYTES).arrayBuffer();
+ const result = await renderPdfThumbnailPdfium(
+ chunk,
+ scale,
+ applyRotation,
+ false,
+ );
+ if (result.isEncrypted) {
+ return { thumbnail: "", pageCount: 1, isEncrypted: true };
+ }
+ return {
+ thumbnail: result.thumbnail,
+ pageCount: result.pageCount,
+ pageRotations: result.pageRotations,
+ pageDimensions: result.pageDimensions,
+ };
+ } catch {
+ return { thumbnail: "", pageCount: 0 };
+ }
+ }
+
try {
const arrayBuffer = await file.arrayBuffer();
// Always read per-page rotation: PageEditor renders thumbnails upright and
@@ -222,3 +348,51 @@ export async function generateThumbnailWithMetadata(
return { thumbnail: "", pageCount: 1 };
}
}
+
+/**
+ * Both thumbnail variants + page metadata from ONE full parse instead of two.
+ * Large PDFs only get the linearized-prefix attempt; if that fails, both
+ * variants are empty placeholders and page metadata is omitted.
+ */
+export async function generateThumbnailPairWithMetadata(file: File): Promise<{
+ unrotated: ThumbnailWithMetadata;
+ rotated: ThumbnailWithMetadata;
+}> {
+ const scale = calculateScaleFromFileSize(file.size);
+ const isLarge = file.size >= LARGE_PDF_PARSE_LIMIT;
+ try {
+ // Probe inside the try: an unreadable file must still resolve, or the
+ // caller leaves the card with no metadata and a spinner that never stops.
+ if (isLarge && (await looksEncryptedFromTrailer(file))) {
+ const encrypted: ThumbnailWithMetadata = {
+ thumbnail: "",
+ pageCount: 1,
+ isEncrypted: true,
+ };
+ return { unrotated: encrypted, rotated: { ...encrypted } };
+ }
+ const buffer = isLarge
+ ? await file.slice(0, LINEARIZED_PREFIX_BYTES).arrayBuffer()
+ : await file.arrayBuffer();
+ const pair = await renderPdfThumbnailPairPdfium(buffer, scale, !isLarge);
+
+ const toPublic = (r: PdfiumRenderResult): ThumbnailWithMetadata =>
+ r.isEncrypted
+ ? { thumbnail: "", pageCount: 1, isEncrypted: true }
+ : {
+ thumbnail: r.thumbnail,
+ pageCount: r.pageCount,
+ pageRotations: r.pageRotations,
+ pageDimensions: r.pageDimensions,
+ };
+ return {
+ unrotated: toPublic(pair.unrotated),
+ rotated: toPublic(pair.rotated),
+ };
+ } catch {
+ return {
+ unrotated: { thumbnail: "", pageCount: 0 },
+ rotated: { thumbnail: "", pageCount: 0 },
+ };
+ }
+}
From 8f5344ec7da36ff153432652ddc6c9c1c4c7d4c2 Mon Sep 17 00:00:00 2001
From: Ludy
Date: Wed, 5 Aug 2026 16:25:44 +0200
Subject: [PATCH 03/99] build(tool-models): separate API model generation from
Swagger setup (#7300)
# Description of Changes
- Added internal `_generate` tasks for frontend and engine tool-model
generation.
- Kept the public `tool-models` tasks responsible for dependency
installation and Swagger generation.
- Separated environment preparation from the actual model generation
commands.
- This allows higher-level tasks to prepare the OpenAPI specification
once and invoke both generators without repeating the backend setup.
---
## Checklist
### General
- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings
### Documentation
- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)
### Translations (if applicable)
- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)
### UI Changes (if applicable)
- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)
### Testing (if applicable)
- [ ] I have run `task check` to verify linters, typechecks, and tests
pass
- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/DeveloperGuide.md#7-testing)
for more details.
---
.taskfiles/backend.yml | 1 +
1 file changed, 1 insertion(+)
diff --git a/.taskfiles/backend.yml b/.taskfiles/backend.yml
index fbabd783a3..63773f61fc 100644
--- a/.taskfiles/backend.yml
+++ b/.taskfiles/backend.yml
@@ -146,6 +146,7 @@ tasks:
swagger:
desc: "Generate OpenAPI docs"
+ run: once
cmds:
- cmd: cmd /c ".\gradlew.bat :stirling-pdf:copySwaggerDoc"
platforms: [windows]
From d0d197f09f84a5609aa8191dc08187f4c873b12d Mon Sep 17 00:00:00 2001
From: ConnorYoh <40631091+ConnorYoh@users.noreply.github.com>
Date: Wed, 5 Aug 2026 16:23:50 +0100
Subject: [PATCH 04/99] Procurement: draft Enterprise Agreement + signature,
legal pages & consent, quote/agreement split (#7021)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Consolidates the enterprise procurement and legal work into one PR off
`main`. Supersedes #7020 (closed; every commit from it is contained
here). Sits on top of PAYG prepaid bundles (#7032) and the `--color-*` →
`--c-*` portal token rename.
## Why
Enterprise procurement was a mock. The stage screens read from a fake
state machine, the "agreement" was prose hardcoded in a component, and
nothing a buyer did was recorded anywhere. To actually sell to an
enterprise we need three things it didn't have: a real document they can
read and sign, a record that proves they signed that exact version, and
a licence that flips when they pay.
## What
**The agreement is a real versioned document**
- Registry at `resources/legal/manifest.json` +
`legal///*.md`. Publishing a new version is a markdown file
and a manifest bump, no code change. `@`-prefixed parts are generated
sections.
- `AgreementAssembler` builds MSA (Part A) + generated Order Form (Part
B) + DPA (Part C) as one document. Only the Order Form varies per deal.
- `AgreementPdfRenderer` goes through our own pipeline (commonmark →
`FileToPdf`/WeasyPrint), so we dogfood it.
- Immutable signature record pinning document id and version, a SHA-256
of the exact rendered markdown, the variable snapshot, typed signatory
details, timestamp and IP.
**Legal document pages and consent logging**
- `GET /api/v1/legal/{docId}` serves any registry document; a viewer
modal renders it with a draft badge. The SLA exhibit is viewable for the
first time.
- `legal_consent` + `POST /api/v1/legal/consent`. EULA clickwrap is
recorded once: at trial start, or at the quote step only if there was no
trial.
**Quote and Agreement are separate steps**
The quote step is a plain itemised review (figures, renewal, PO) with
download and "Accept quote". Accepting advances to the agreement and
does not charge Stripe. Signing the agreement is still the commitment
point.
**One quote number**
We no longer mint our own reference. The Stripe quote number is the
identifier everywhere, so the UI and the memo can't disagree.
`quote_number` is nullable until Stripe assigns it at finalisation
(`20260808000000`).
**Payment takes the deal live**
`invoice.paid` on the stripe-webhook moves the deal to live and the UI
reflects it. Nothing watched for payment before, so a paid customer sat
in "payment" forever. Needs `invoice.paid` enabled on the webhook
endpoint in the Stripe dashboard.
**Security**
Any signup could self-issue a $0 enterprise licence, from three things
compounding: leader-on-signup, no entitlement gate, and no ACV floor.
So: `startTrial` now has a stage guard (it was replacing committed
licences), the offline `.lic` is gated on entitlement, the ACV floor is
enforced before the quote persists, and the air-gap check reads the
quote's deployment rather than the deal's. Invitee emails are redacted
in logs. Dev and Storybook were hitting real Stripe; both now route
through `resolveDemoResponse`.
**Removed the dead procurement island**
The original stage-by-stage page survived the rebuild with no route and
no consumer, so it was invisible to review but still cost a reader's
time. 16 unreferenced files, 182 lines of superseded API, 53 orphaned
en-US keys, and `Procurement.css` from 1665 to 968 lines. Nothing
deleted had a live consumer.
## Screenshots
Home, deal underway (hero card footer):
Quote builder, step 1:
Agreement, ready to sign:
Payment and live:
## How to test
**Storybook** covers every state without a backend:
```bash
cd frontend && npm run storybook
```
Then `Portal/Procurement/*`:
| Story | What to look at |
| --- | --- |
| `DealStatusHero` — Trial / Quote / Agreement / Payment / Live | One
hero per stage: progress band, one-line status, stage CTA |
| `QuoteBuilder` — Default | 4 steps. Users + volume drive the price;
Governance and PDF size are multipliers; step 4 is the itemised review |
| `ProcurementAgreement` — Default / Signing | Header actions,
always-visible scrollbar on the paper, one-line signature row |
| `ProcurementStages` — Payment / Live / License | "View & pay invoice"
opens Stripe directly; licence key and `.lic` download |
| `Views/Home` — Subscribed In Procurement | The hero in real page
context |
Note: `ProcurementAgreement` renders "Could not load the agreement" in
Storybook because it fetches the document from the backend. The chrome
is accurate, the paper body needs the app.
**Full flow** needs SaaS running and a linked team:
1. Home → **Explore enterprise** → trial setup (deployment + seats).
EULA is recorded here.
2. **Build your quote** → 4 steps → Generate. Buyer details are required
first.
3. Review the itemised quote → **Accept quote**. Confirm Stripe was
*not* charged.
4. Agreement → tick, fill signatory, **Sign agreement**. Check
`procurement_signature` for the version and content hash.
5. **View & pay invoice** → pay in Stripe test mode → deal should move
to live on the `invoice.paid` webhook.
Worth reviewing specifically: the licence cannot be issued without
entitlement (step 3 before payment), and `startTrial` on an
already-committed deal is rejected rather than overwriting.
## Verification
- `:saas compileJava` + `spotlessJavaCheck`
- `task frontend:check:all` green end to end: 9 typecheck variants,
eslint at zero warnings, `theme-lint`, `lint:css`, prettier, build,
**1656 tests across 188 files**
- 7 deno tests on the `invoice.paid` handler, covering all four shapes
Stripe uses for the subscription reference
## Open, not addressed here
- **The commercial model contradicts itself in three places.** The Order
Form says annual-in-advance, the MSA §2.3/§3.2 implies otherwise, the
quote engine computes `tcv = annualNet × termYears` flat, and Stripe
only invoices one year. Needs a decision before this is customer-facing.
- The 25 MB data-processing increments vs the ×1.4/×2.4 size multiplier,
deferred pending Matt.
- All legal text is **draft**. It renders with a draft badge and is not
presented as executed; counsel's read is still a publish gate.
- `{{subprocessor_url}}` / `{{eula_url}}` awaiting marketing's final
links.
- `frontend-a11y` is red on pre-existing portal contrast debt, deferred
by decision.
## Schema notes
Two migrations land on the SaaS side (`v3`), both applied by that repo's
PR CI:
- `20260808000000` drops the NOT NULL on
`procurement_quote.quote_number`, which is required rather than cosmetic
— the number now comes from Stripe at finalisation, so a draft holds
NULL, and `ddl-auto` cannot drop an existing NOT NULL itself.
- `20260809000000` adds `procurement_deal.last_paid_invoice_id`,
nullable.
Nothing here needs a migration in this repo: Flyway is not on the
classpath, so the Java side only ever adds via `ddl-auto`, and Postgres
migrations run ahead of the app deploy.
---
app/saas/build.gradle | 5 +
.../software/saas/config/SaasJpaConfig.java | 6 +-
.../software/saas/legal/LegalConsent.java | 62 +
.../saas/legal/LegalConsentRepository.java | 5 +
.../saas/legal/LegalConsentService.java | 47 +
.../software/saas/legal/LegalController.java | 133 ++
.../saas/legal/LegalDocumentMeta.java | 27 +
.../saas/legal/LegalDocumentRegistry.java | 151 ++
.../saas/payg/bundle/PrepaidBundle.java | 15 +-
.../api/ProcurementController.java | 247 ++-
.../ProcurementConfigurationProperties.java | 13 +
.../procurement/legal/AgreementAssembler.java | 278 ++++
.../legal/AgreementPdfRenderer.java | 71 +
.../procurement/legal/AgreementSigning.java | 12 +
.../procurement/legal/AssembledAgreement.java | 16 +
.../model/ProcurementAgreementSignature.java | 86 +
.../procurement/model/ProcurementDeal.java | 33 +
.../procurement/model/ProcurementQuote.java | 6 +-
.../pricing/ProcurementPricingService.java | 49 +-
...ocurementAgreementSignatureRepository.java | 29 +
.../service/ProcurementService.java | 390 ++++-
.../legal/enterprise-agreement/0.9.1/dpa.md | 53 +
.../legal/enterprise-agreement/0.9.1/msa.md | 119 ++
.../main/resources/legal/eula/1.0.0/eula.md | 75 +
.../src/main/resources/legal/manifest.json | 38 +
.../src/main/resources/legal/sla/1.0.0/sla.md | 37 +
.../subprocessors/1.0.0/subprocessors.md | 19 +
.../ProcurementTrialRestartPolicyTest.java | 44 +
frontend/.storybook/a11y-baseline.json | 22 +-
.../public/locales/en-US/translation.toml | 241 ++-
frontend/editor/src/portal/ViewRouter.tsx | 2 -
.../editor/src/portal/api/externalUrl.test.ts | 51 +
frontend/editor/src/portal/api/externalUrl.ts | 25 +
frontend/editor/src/portal/api/procurement.ts | 369 ++---
.../portal/components/EditorStatusCard.css | 99 +-
.../components/EditorStatusCard.stories.tsx | 30 +-
.../portal/components/EditorStatusCard.tsx | 179 +--
.../portal/components/HomeHero.stories.tsx | 21 +-
.../editor/src/portal/components/HomeHero.tsx | 72 +-
.../src/portal/components/SetupChecklist.css | 122 --
.../components/SetupChecklist.stories.tsx | 66 -
.../src/portal/components/SetupChecklist.tsx | 150 --
.../src/portal/components/WelcomeBanner.css | 103 --
.../components/WelcomeBanner.stories.tsx | 41 -
.../src/portal/components/WelcomeBanner.tsx | 97 --
.../billing/BundleCheckoutModal.tsx | 4 +-
.../components/billing/EnterpriseUpsell.tsx | 13 +-
.../components/billing/FreePlanView.tsx | 1 -
.../components/billing/LinkAccountPrompt.tsx | 6 +-
.../components/billing/PrepayModalHeader.tsx | 100 +-
.../components/billing/SpendLimitCard.tsx | 2 +-
.../billing/StripeCheckoutModal.tsx | 1 -
.../src/portal/components/billing/billing.css | 53 -
.../editor/src/portal/components/icons.tsx | 29 +
.../procurement/ActionModal.stories.tsx | 51 -
.../components/procurement/ActionModal.tsx | 166 --
.../procurement/DealJourney.stories.tsx | 30 -
.../components/procurement/DealJourney.tsx | 99 --
.../procurement/DealStatusHero.stories.tsx | 6 +-
.../components/procurement/DealStatusHero.tsx | 311 ++--
.../components/procurement/DocRow.stories.tsx | 62 -
.../portal/components/procurement/DocRow.tsx | 89 --
.../procurement/DocumentLedger.stories.tsx | 30 -
.../components/procurement/DocumentLedger.tsx | 160 --
.../procurement/LockedState.stories.tsx | 18 -
.../components/procurement/LockedState.tsx | 36 -
.../ProcurementAgreement.stories.tsx | 14 +-
.../procurement/ProcurementAgreement.tsx | 369 +++--
.../procurement/ProcurementBanner.stories.tsx | 79 -
.../procurement/ProcurementBanner.tsx | 65 +-
.../procurement/ProcurementExtras.stories.tsx | 7 +-
.../procurement/ProcurementExtras.tsx | 542 +++++--
.../procurement/ProcurementFlow.stories.tsx | 10 +-
.../procurement/ProcurementFlow.tsx | 110 +-
.../procurement/ProcurementHome.stories.tsx | 18 -
.../procurement/ProcurementHome.tsx | 22 -
.../procurement/ProcurementModal.stories.tsx | 4 +-
.../procurement/ProcurementModal.tsx | 115 +-
.../procurement/ProcurementStages.tsx | 102 +-
.../components/procurement/QuoteBuilder.tsx | 377 ++++-
.../procurement/StageStepper.stories.tsx | 20 -
.../components/procurement/StageStepper.tsx | 52 -
.../portal/components/procurement/format.ts | 32 +-
.../procurement/useProcurement.test.tsx | 137 ++
.../components/procurement/useProcurement.ts | 165 +-
.../portal/components/shared/FlowModal.css | 52 +
.../components/shared/FlowModal.test.tsx | 94 ++
.../portal/components/shared/FlowModal.tsx | 52 +
.../components/shared/StepModalHeader.css | 92 ++
.../components/shared/StepModalHeader.tsx | 127 ++
.../src/portal/contexts/UIContext.test.tsx | 47 +
.../editor/src/portal/contexts/UIContext.tsx | 16 +
.../src/portal/contexts/ViewContext.tsx | 2 -
.../src/portal/hooks/useOnboardingProgress.ts | 63 -
.../editor/src/portal/mocks/handlers/index.ts | 3 -
.../src/portal/mocks/handlers/procurement.ts | 92 --
.../portal/mocks/handlers/procurementSaas.ts | 122 +-
.../editor/src/portal/mocks/procurement.ts | 307 ----
.../portal/mocks/procurementMachine.test.ts | 86 -
.../src/portal/mocks/procurementMachine.ts | 114 --
frontend/editor/src/portal/queries/keys.ts | 3 +
frontend/editor/src/portal/queries/users.ts | 5 +-
.../editor/src/portal/views/Home.stories.tsx | 1 +
frontend/editor/src/portal/views/Home.tsx | 2 +-
.../editor/src/portal/views/Procurement.css | 1383 ++++++-----------
.../editor/src/portal/views/Procurement.tsx | 15 -
frontend/eslint.config.mjs | 7 +-
107 files changed, 5347 insertions(+), 4601 deletions(-)
create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalController.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java
create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java
create mode 100644 app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md
create mode 100644 app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md
create mode 100644 app/saas/src/main/resources/legal/eula/1.0.0/eula.md
create mode 100644 app/saas/src/main/resources/legal/manifest.json
create mode 100644 app/saas/src/main/resources/legal/sla/1.0.0/sla.md
create mode 100644 app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md
create mode 100644 app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java
create mode 100644 frontend/editor/src/portal/api/externalUrl.test.ts
create mode 100644 frontend/editor/src/portal/api/externalUrl.ts
delete mode 100644 frontend/editor/src/portal/components/SetupChecklist.css
delete mode 100644 frontend/editor/src/portal/components/SetupChecklist.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/SetupChecklist.tsx
delete mode 100644 frontend/editor/src/portal/components/WelcomeBanner.css
delete mode 100644 frontend/editor/src/portal/components/WelcomeBanner.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/WelcomeBanner.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/ActionModal.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/ActionModal.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/DealJourney.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/DealJourney.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/DocRow.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/DocRow.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/DocumentLedger.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/DocumentLedger.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/LockedState.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/LockedState.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/ProcurementBanner.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/ProcurementHome.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/ProcurementHome.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/StageStepper.stories.tsx
delete mode 100644 frontend/editor/src/portal/components/procurement/StageStepper.tsx
create mode 100644 frontend/editor/src/portal/components/procurement/useProcurement.test.tsx
create mode 100644 frontend/editor/src/portal/components/shared/FlowModal.css
create mode 100644 frontend/editor/src/portal/components/shared/FlowModal.test.tsx
create mode 100644 frontend/editor/src/portal/components/shared/FlowModal.tsx
create mode 100644 frontend/editor/src/portal/components/shared/StepModalHeader.css
create mode 100644 frontend/editor/src/portal/components/shared/StepModalHeader.tsx
create mode 100644 frontend/editor/src/portal/contexts/UIContext.test.tsx
delete mode 100644 frontend/editor/src/portal/hooks/useOnboardingProgress.ts
delete mode 100644 frontend/editor/src/portal/mocks/handlers/procurement.ts
delete mode 100644 frontend/editor/src/portal/mocks/procurement.ts
delete mode 100644 frontend/editor/src/portal/mocks/procurementMachine.test.ts
delete mode 100644 frontend/editor/src/portal/mocks/procurementMachine.ts
delete mode 100644 frontend/editor/src/portal/views/Procurement.tsx
diff --git a/app/saas/build.gradle b/app/saas/build.gradle
index 495f583a74..a954e6d05a 100644
--- a/app/saas/build.gradle
+++ b/app/saas/build.gradle
@@ -6,6 +6,11 @@ dependencies {
implementation project(':common')
implementation project(':proprietary')
+ // Markdown -> HTML for rendering versioned legal documents (agreement) to PDF via the
+ // shared FileToPdf/WeasyPrint path in :common. Same library the core Markdown-to-PDF tool uses.
+ implementation "org.commonmark:commonmark:$commonmarkVersion"
+ implementation "org.commonmark:commonmark-ext-gfm-tables:$commonmarkVersion"
+
api 'org.springframework.boot:spring-boot-starter-security'
api 'org.springframework.boot:spring-boot-starter-data-jpa'
api 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java
index cd991cc44e..612c6e3171 100644
--- a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java
+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java
@@ -20,7 +20,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
"stirling.software.saas.ai.repository",
"stirling.software.saas.payg.repository",
"stirling.software.saas.payg.bundle",
- "stirling.software.saas.procurement.repository"
+ "stirling.software.saas.procurement.repository",
+ "stirling.software.saas.legal"
})
@EntityScan({
"stirling.software.saas.accountlink",
@@ -28,6 +29,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
"stirling.software.saas.billing.model",
"stirling.software.saas.ai.model",
"stirling.software.saas.payg",
- "stirling.software.saas.procurement.model"
+ "stirling.software.saas.procurement.model",
+ "stirling.software.saas.legal"
})
public class SaasJpaConfig {}
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java
new file mode 100644
index 0000000000..5698133fe8
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java
@@ -0,0 +1,62 @@
+package stirling.software.saas.legal;
+
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+import org.hibernate.annotations.CreationTimestamp;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+/**
+ * An append-only record that a user accepted a versioned legal document at a particular moment in
+ * the product. Distinct from a signed agreement (which is a negotiated, signature-bearing artifact,
+ * see {@code ProcurementAgreementSignature}); this captures the lighter clickwrap consents — the
+ * EULA accepted at trial start and at quote generation — with the exact document version, so what
+ * was agreed is auditable even after the document versions up.
+ */
+@Entity
+@Table(name = "legal_consent")
+@NoArgsConstructor
+@Getter
+@Setter
+public class LegalConsent implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "consent_id")
+ private Long consentId;
+
+ @Column(name = "team_id")
+ private Long teamId;
+
+ @Column(name = "user_id")
+ private Long userId;
+
+ @Column(name = "document_id", nullable = false, length = 64)
+ private String documentId;
+
+ @Column(name = "document_version", nullable = false, length = 32)
+ private String documentVersion;
+
+ // Where in the product the consent was given: "trial", "quote", etc.
+ @Column(name = "context", nullable = false, length = 32)
+ private String context;
+
+ @Column(name = "signer_ip", length = 64)
+ private String signerIp;
+
+ @CreationTimestamp
+ @Column(name = "consented_at", nullable = false, updatable = false)
+ private LocalDateTime consentedAt;
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java
new file mode 100644
index 0000000000..9d79640cd0
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java
@@ -0,0 +1,5 @@
+package stirling.software.saas.legal;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+
+public interface LegalConsentRepository extends JpaRepository {}
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java
new file mode 100644
index 0000000000..c6377f35b7
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java
@@ -0,0 +1,47 @@
+package stirling.software.saas.legal;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+/** Records clickwrap consents to versioned legal documents (see {@link LegalConsent}). */
+@Slf4j
+@Service
+@Profile("saas")
+@RequiredArgsConstructor
+public class LegalConsentService {
+
+ private final LegalDocumentRegistry registry;
+ private final LegalConsentRepository consents;
+
+ /**
+ * Record that the given user accepted the current version of {@code documentId} in {@code
+ * context} (e.g. "trial", "quote"). No-op for an unknown document. Best-effort: callers treat a
+ * failure as non-fatal so it never blocks the flow the consent accompanies.
+ */
+ @Transactional
+ public void record(Long teamId, Long userId, String documentId, String context, String ip) {
+ LegalDocumentMeta meta = registry.meta(documentId).orElse(null);
+ if (meta == null) {
+ log.warn("[legal] consent for unknown document '{}' ignored", documentId);
+ return;
+ }
+ LegalConsent consent = new LegalConsent();
+ consent.setTeamId(teamId);
+ consent.setUserId(userId);
+ consent.setDocumentId(meta.id());
+ consent.setDocumentVersion(meta.version());
+ consent.setContext(context);
+ consent.setSignerIp(ip);
+ consents.save(consent);
+ log.info(
+ "[legal] consent recorded team={} doc={} v{} context={}",
+ teamId,
+ meta.id(),
+ meta.version(),
+ context);
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalController.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalController.java
new file mode 100644
index 0000000000..308b3e99bd
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalController.java
@@ -0,0 +1,133 @@
+package stirling.software.saas.legal;
+
+import java.util.Optional;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.core.Authentication;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import io.swagger.v3.oas.annotations.Hidden;
+
+import jakarta.servlet.http.HttpServletRequest;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.proprietary.model.TeamMembership;
+import stirling.software.proprietary.security.database.repository.UserRepository;
+import stirling.software.proprietary.security.model.User;
+import stirling.software.proprietary.security.repository.TeamMembershipRepository;
+import stirling.software.saas.util.AuthenticationUtils;
+
+/**
+ * Serves the versioned legal documents (EULA, SLA exhibit, subprocessors) for in-product viewing,
+ * and records the lighter clickwrap consents. The enterprise agreement itself is served + signed
+ * through the procurement controller, since it needs a quote to fill its Order Form.
+ */
+@Slf4j
+@Hidden
+@RestController
+@RequestMapping("/api/v1/legal")
+@Profile("saas")
+@RequiredArgsConstructor
+public class LegalController {
+
+ private final LegalDocumentRegistry registry;
+ private final LegalConsentService consents;
+ private final TeamMembershipRepository memberRepo;
+ private final UserRepository userRepository;
+
+ /** A legal document rendered for viewing: registry metadata + the static markdown body. */
+ public record LegalDocumentResponse(
+ String docId,
+ String version,
+ String versionLabel,
+ String displayName,
+ String effectiveDate,
+ String status,
+ String markdown) {}
+
+ public record ConsentRequest(String documentId, String context) {}
+
+ /** Fetch a legal document's current version as markdown. 404 for an unknown document. */
+ @GetMapping("/{docId}")
+ @PreAuthorize("isAuthenticated()")
+ public ResponseEntity document(@PathVariable String docId) {
+ return registry.meta(docId)
+ .>map(
+ meta ->
+ ResponseEntity.ok(
+ new LegalDocumentResponse(
+ meta.id(),
+ meta.version(),
+ meta.versionLabel(),
+ meta.displayName(),
+ meta.effectiveDate(),
+ meta.status(),
+ registry.staticMarkdown(docId))))
+ .orElseGet(() -> ResponseEntity.notFound().build());
+ }
+
+ /**
+ * Record a clickwrap consent (e.g. the EULA accepted at trial start or quote generation).
+ * Best-effort — a teamless caller still returns 200 so the accompanying flow is never blocked.
+ */
+ @PostMapping("/consent")
+ @PreAuthorize("isAuthenticated()")
+ public ResponseEntity consent(
+ @RequestBody ConsentRequest request, Authentication auth, HttpServletRequest http) {
+ if (request == null || request.documentId() == null || request.context() == null) {
+ return ResponseEntity.badRequest().build();
+ }
+ Optional membership = primaryMembership(auth);
+ Long teamId = membership.map(m -> m.getTeam().getId()).orElse(null);
+ Long userId = membership.map(m -> m.getUser().getId()).orElse(null);
+ // Best-effort for real: consent is audit metadata, not an authorisation gate, so a failed
+ // write must not fail the trial start or quote generation this call accompanies. Previously
+ // that only held because the caller happened to swallow the 500.
+ try {
+ consents.record(
+ teamId, userId, request.documentId(), request.context(), clientIp(http));
+ } catch (RuntimeException e) {
+ log.warn(
+ "[legal] consent not recorded doc={} context={}: {}",
+ request.documentId(),
+ request.context(),
+ e.getMessage());
+ }
+ return ResponseEntity.ok().build();
+ }
+
+ private Optional primaryMembership(Authentication auth) {
+ User user;
+ try {
+ user = AuthenticationUtils.getCurrentUser(auth, userRepository);
+ } catch (SecurityException e) {
+ return Optional.empty();
+ }
+ return memberRepo.findPrimaryMembership(user.getId()).stream().findFirst();
+ }
+
+ /**
+ * Best guess at the caller's address, for the audit record.
+ *
+ *
Informational only, and must stay that way: the first {@code X-Forwarded-For} hop is set
+ * by the client, so a stored address is trivially spoofable and is not evidence of where a
+ * consent or signature came from. Treat it as a hint when reconstructing events, never as
+ * proof.
+ */
+ private static String clientIp(HttpServletRequest request) {
+ String forwarded = request.getHeader("X-Forwarded-For");
+ if (forwarded != null && !forwarded.isBlank()) {
+ return forwarded.split(",")[0].trim();
+ }
+ return request.getRemoteAddr();
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java
new file mode 100644
index 0000000000..9f35e42053
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java
@@ -0,0 +1,27 @@
+package stirling.software.saas.legal;
+
+import java.util.List;
+
+/**
+ * One legal document's registry entry, as declared in {@code legal/manifest.json}. Immutable
+ * snapshot loaded at startup by {@link LegalDocumentRegistry}.
+ *
+ *
{@code parts} lists the pieces, in render order, that make up the document. A plain entry
+ * (e.g. {@code "msa.md"}) is a static markdown file under {@code legal///}; an entry
+ * prefixed with {@code "@"} (e.g. {@code "@order-form"}) is a dynamic section that a document
+ * assembler generates at render time.
+ */
+public record LegalDocumentMeta(
+ String id,
+ String label,
+ String displayName,
+ String version,
+ String effectiveDate,
+ String status,
+ List parts) {
+
+ /** Fully-qualified version label shown to users and stored on signatures, e.g. "SEA v0.9.1". */
+ public String versionLabel() {
+ return label + " v" + version;
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java
new file mode 100644
index 0000000000..ffbe030863
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java
@@ -0,0 +1,151 @@
+package stirling.software.saas.legal;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.stereotype.Service;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import jakarta.annotation.PostConstruct;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Loads the versioned legal-document registry from {@code legal/manifest.json} on startup and
+ * serves document metadata + rendered markdown from the classpath.
+ *
+ *
Publishing a new version of any document is a content-only change: drop the markdown under
+ * {@code legal///} and bump that document's {@code version} in the manifest — no
+ * code change. Signatures pin the exact {@code {id, version, contentHash}} they were signed against
+ * (see the procurement agreement flow), so historical documents stay reproducible.
+ *
+ *
Token slots of the form {{name}} in the markdown are filled at render time. This
+ * registry fills the document-level common tokens ({@code version}, {@code version_date}, {@code
+ * subprocessor_url}, {@code eula_url}); callers that need per-quote tokens (the enterprise
+ * agreement's Order Form) fill the rest.
+ */
+@Slf4j
+@Service
+public class LegalDocumentRegistry {
+
+ private static final String MANIFEST = "legal/manifest.json";
+ private static final Pattern TOKEN = Pattern.compile("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*}}");
+
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ private final Map documents = new LinkedHashMap<>();
+ private String subprocessorUrl = "";
+ private String eulaUrl = "";
+
+ @PostConstruct
+ void load() throws IOException {
+ JsonNode root;
+ try (InputStream in = new ClassPathResource(MANIFEST).getInputStream()) {
+ root = objectMapper.readTree(in);
+ }
+ subprocessorUrl = root.path("subprocessorUrl").asText("");
+ eulaUrl = root.path("eulaUrl").asText("");
+ JsonNode docs = root.path("documents");
+ docs.fieldNames()
+ .forEachRemaining(
+ id -> {
+ JsonNode d = docs.get(id);
+ List parts =
+ objectMapper.convertValue(
+ d.path("parts"),
+ objectMapper
+ .getTypeFactory()
+ .constructCollectionType(
+ List.class, String.class));
+ documents.put(
+ id,
+ new LegalDocumentMeta(
+ id,
+ d.path("label").asText(id),
+ d.path("displayName").asText(id),
+ d.path("version").asText("0"),
+ d.path("effectiveDate").asText(""),
+ d.path("status").asText("draft"),
+ parts == null ? List.of() : parts));
+ });
+ log.info("[legal] loaded {} document(s) from {}", documents.size(), MANIFEST);
+ }
+
+ public Optional meta(String docId) {
+ return Optional.ofNullable(documents.get(docId));
+ }
+
+ public String subprocessorUrl() {
+ return subprocessorUrl;
+ }
+
+ public String eulaUrl() {
+ return eulaUrl;
+ }
+
+ /** Document-level tokens available to every document (before any per-quote tokens). */
+ public Map commonTokens(LegalDocumentMeta meta) {
+ Map t = new LinkedHashMap<>();
+ t.put("version", meta.version());
+ t.put("version_date", meta.effectiveDate());
+ t.put("subprocessor_url", subprocessorUrl);
+ t.put("eula_url", eulaUrl);
+ return t;
+ }
+
+ /** Read one static markdown part of a document from the classpath. */
+ public String readPart(LegalDocumentMeta meta, String partFile) {
+ String path = "legal/" + meta.id() + "/" + meta.version() + "/" + partFile;
+ try (InputStream in = new ClassPathResource(path).getInputStream()) {
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ throw new IllegalStateException("Missing legal document part: " + path, e);
+ }
+ }
+
+ /**
+ * The concatenated static parts of a document (dynamic {@code @}-parts skipped), with only the
+ * common tokens filled. Use for fully-static documents (EULA, SLA, subprocessors).
+ */
+ public String staticMarkdown(String docId) {
+ LegalDocumentMeta meta =
+ meta(docId)
+ .orElseThrow(
+ () -> new IllegalArgumentException("Unknown document: " + docId));
+ Map tokens = commonTokens(meta);
+ StringBuilder sb = new StringBuilder();
+ for (String part : meta.parts()) {
+ if (part.startsWith("@")) continue; // dynamic section — not part of the static body
+ if (sb.length() > 0) sb.append("\n\n");
+ sb.append(fill(readPart(meta, part), tokens));
+ }
+ return sb.toString();
+ }
+
+ /** Replace {@code {{token}}} slots; unknown tokens are left intact so gaps are visible. */
+ public static String fill(String markdown, Map tokens) {
+ Matcher m = TOKEN.matcher(markdown);
+ StringBuilder out = new StringBuilder();
+ while (m.find()) {
+ String key = m.group(1);
+ String value = tokens.get(key);
+ m.appendReplacement(
+ out,
+ value == null
+ ? Matcher.quoteReplacement(m.group(0))
+ : Matcher.quoteReplacement(value));
+ }
+ m.appendTail(out);
+ return out.toString();
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java
index e2dff403a7..f864bf4d98 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java
@@ -34,17 +34,22 @@ import lombok.Setter;
@Entity
@Table(
name = "payg_prepaid_bundle",
- // Declared here for ddl-auto (fresh schemas) and to document intent. The authoritative creator
- // in production is the Supabase CLI migration 20260720000000_payg_prepaid_bundle, which builds
+ // Declared here for ddl-auto (fresh schemas) and to document intent. The authoritative
+ // creator
+ // in production is the Supabase CLI migration 20260720000000_payg_prepaid_bundle, which
+ // builds
// the partial forms (WHERE units_remaining > 0 / WHERE stripe_ref IS NOT NULL). Flyway was
// retired for SaaS (#7100), so there is no migration twin — names match the CLI migration.
indexes = {
- // Hot-path FIFO draw lookup — findDrawableForUpdate runs a locked read on every billable
- // charge past the free grant; without it that degrades to a locked scan as the table grows.
+ // Hot-path FIFO draw lookup — findDrawableForUpdate runs a locked read on every
+ // billable
+ // charge past the free grant; without it that degrades to a locked scan as the table
+ // grows.
@Index(
name = "idx_payg_prepaid_bundle_team_expiry",
columnList = "team_id, expires_at"),
- // One pool per Stripe payment — the idempotency guard so a redelivered invoice.paid can't
+ // One pool per Stripe payment — the idempotency guard so a redelivered invoice.paid
+ // can't
// credit the same purchase twice.
@Index(
name = "uq_payg_prepaid_bundle_stripe_ref",
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java b/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java
index d67a0fddbf..1c495b3afd 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java
@@ -22,6 +22,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Hidden;
+import jakarta.servlet.http.HttpServletRequest;
+
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.enumeration.TeamRole;
@@ -30,6 +32,8 @@ import stirling.software.proprietary.security.database.repository.UserRepository
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.procurement.config.ProcurementConfigurationProperties;
+import stirling.software.saas.procurement.legal.AgreementSigning;
+import stirling.software.saas.procurement.model.ProcurementAgreementSignature;
import stirling.software.saas.procurement.model.ProcurementDeal;
import stirling.software.saas.procurement.model.ProcurementQuote;
import stirling.software.saas.procurement.model.QuoteDetails;
@@ -178,7 +182,17 @@ public class ProcurementController {
String taxId) {}
/** Trial setup captured before the trial starts: deployment target + seat count. */
- public record StartTrialRequest(String deployment, int users) {}
+ /**
+ * Setup step 2 collects the buying entity; all of it is optional so an older client still
+ * starts.
+ */
+ public record StartTrialRequest(
+ String deployment,
+ int users,
+ String businessName,
+ String contactName,
+ String contactEmail,
+ String inviteEmails) {}
public record SnapshotResponse(
Long dealId,
@@ -190,8 +204,33 @@ public class ProcurementController {
int trialExtensionsUsed,
boolean licensed,
String licenseKey,
+ // Version label of the signed agreement PDF available for download, else null.
+ String agreementSignedVersion,
+ // Buying entity captured at trial setup; null on deals started before that step.
+ String businessName,
+ String contactName,
+ String contactEmail,
QuoteResponse latestQuote) {}
+ /** The filled agreement for review: registry metadata + the rendered markdown body. */
+ public record AgreementDocumentResponse(
+ String docId,
+ String version,
+ String versionLabel,
+ String displayName,
+ String effectiveDate,
+ String status,
+ String markdown) {}
+
+ /** Buyer-supplied signing inputs from the agreement stage. */
+ public record SignAgreementRequest(
+ String customerLegalName,
+ String signatoryName,
+ String signatoryTitle,
+ boolean authorityConfirmed) {}
+
+ public record SignAgreementResponse(Long signatureId, String versionLabel, boolean pdfStored) {}
+
// ---- endpoints ----------------------------------------------------------
/**
@@ -213,7 +252,8 @@ public class ProcurementController {
}
private static final SnapshotResponse EMPTY_SNAPSHOT =
- new SnapshotResponse(null, null, null, 0, null, null, 0, false, null, null);
+ new SnapshotResponse(
+ null, null, null, 0, null, null, 0, false, null, null, null, null, null, null);
/**
* Download the offline / air-gapped licence file (.lic) for the team — available for an
@@ -239,6 +279,15 @@ public class ProcurementController {
.orElseGet(() -> ResponseEntity.notFound().build());
}
+ /** Mark the account as looking at enterprise. Idempotent; never disturbs an existing deal. */
+ @PostMapping("/interest")
+ @PreAuthorize("isAuthenticated()")
+ public ResponseEntity recordInterest(Authentication auth) {
+ Long teamId = requireLeader(auth);
+ if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
+ return ResponseEntity.ok(toSnapshot(procurement.recordInterest(teamId), true));
+ }
+
@PostMapping("/trial/start")
@PreAuthorize("isAuthenticated()")
public ResponseEntity startTrial(
@@ -248,8 +297,30 @@ public class ProcurementController {
// Body is optional so an older client (no setup step) still starts a cloud trial.
String deployment = request != null ? request.deployment() : null;
int seats = request != null ? request.users() : 0;
- return ResponseEntity.ok(
- toSnapshot(procurement.startTrial(teamId, deployment, seats), true));
+ ProcurementDeal deal;
+ try {
+ deal =
+ procurement.startTrial(
+ teamId,
+ deployment,
+ seats,
+ request != null ? request.businessName() : null,
+ request != null ? request.contactName() : null,
+ request != null ? request.contactEmail() : null,
+ request != null ? request.inviteEmails() : null);
+ } catch (IllegalStateException e) {
+ // Past the trial the deal holds a committed licence; restarting would replace it.
+ log.warn("[procurement] trial start rejected team={}: {}", teamId, e.getMessage());
+ return ResponseEntity.status(HttpStatus.CONFLICT).build();
+ }
+ // After the trial exists, so a rejected invite can never stop it starting.
+ if (request != null) {
+ procurement.sendTrialInvites(
+ teamId,
+ primaryMembership(auth).map(TeamMembership::getUser).orElse(null),
+ request.inviteEmails());
+ }
+ return ResponseEntity.ok(toSnapshot(deal, true));
}
@PostMapping("/trial/extend")
@@ -270,8 +341,17 @@ public class ProcurementController {
@RequestBody QuoteRequest request, Authentication auth) {
Long teamId = requireLeader(auth);
if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
- return ResponseEntity.ok(
- toQuote(procurement.buildQuote(teamId, request.toConfig(), request.toDetails())));
+ try {
+ return ResponseEntity.ok(
+ toQuote(
+ procurement.buildQuote(
+ teamId, request.toConfig(), request.toDetails())));
+ } catch (IllegalStateException e) {
+ // Below the minimum deal size, or the deal is already live. A client error, not a
+ // fault.
+ log.warn("[procurement] quote rejected team={}: {}", teamId, e.getMessage());
+ return ResponseEntity.status(HttpStatus.CONFLICT).build();
+ }
}
// Issue + accept are Supabase edge functions (they own Stripe): issue-procurement-quote turns a
@@ -293,6 +373,111 @@ public class ProcurementController {
}
}
+ /**
+ * The filled Stirling Enterprise Agreement (MSA + Order Form + DPA) for the team's current
+ * quote, as markdown, for the buyer to review before signing. 404 when there's no quote yet.
+ */
+ @GetMapping("/agreement/document")
+ @PreAuthorize("isAuthenticated()")
+ public ResponseEntity agreementDocument(Authentication auth) {
+ Long teamId = requireLeader(auth);
+ if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
+ return procurement
+ .agreementDocument(teamId)
+ .>map(
+ a ->
+ ResponseEntity.ok(
+ new AgreementDocumentResponse(
+ a.docId(),
+ a.version(),
+ a.versionLabel(),
+ a.displayName(),
+ a.effectiveDate(),
+ a.status(),
+ a.markdown())))
+ .orElseGet(() -> ResponseEntity.notFound().build());
+ }
+
+ /**
+ * Record a signed agreement: capture the typed legal name / signatory / title / authority, pin
+ * the exact document version + content hash + variable snapshot, and store the rendered PDF
+ * (best-effort). The caller then proceeds to accept the quote as before.
+ */
+ @PostMapping("/agreement/sign")
+ @PreAuthorize("isAuthenticated()")
+ public ResponseEntity signAgreement(
+ @RequestBody SignAgreementRequest request,
+ Authentication auth,
+ HttpServletRequest http) {
+ Long teamId = requireLeader(auth);
+ if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
+ if (request == null
+ || request.signatoryName() == null
+ || request.signatoryName().isBlank()
+ || !request.authorityConfirmed()) {
+ return ResponseEntity.badRequest().build();
+ }
+ try {
+ ProcurementAgreementSignature sig =
+ procurement.signAgreement(
+ teamId,
+ new AgreementSigning(
+ request.customerLegalName(),
+ request.signatoryName(),
+ request.signatoryTitle(),
+ request.authorityConfirmed()),
+ clientIp(http));
+ return ResponseEntity.ok(
+ new SignAgreementResponse(
+ sig.getSignatureId(), sig.getDocumentLabel(), sig.getPdf() != null));
+ } catch (IllegalStateException e) {
+ return ResponseEntity.status(HttpStatus.CONFLICT).build();
+ }
+ }
+
+ /** Download the stored signed-agreement PDF for the team. 404 if none was rendered/stored. */
+ @GetMapping("/agreement/signature/pdf")
+ @PreAuthorize("isAuthenticated()")
+ public ResponseEntity signaturePdf(Authentication auth) {
+ Long teamId = requireLeader(auth);
+ if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
+ return procurement
+ .signedAgreementPdf(teamId)
+ .>map(
+ pdf ->
+ ResponseEntity.ok()
+ .header(
+ HttpHeaders.CONTENT_DISPOSITION,
+ "attachment;"
+ + " filename=\"stirling-enterprise-agreement.pdf\"")
+ .contentType(MediaType.APPLICATION_PDF)
+ .body(pdf))
+ .orElseGet(() -> ResponseEntity.notFound().build());
+ }
+
+ /**
+ * Download the current (unsigned) agreement as a PDF — the document shown at the sign step. 404
+ * when there's no quote yet or the render runtime is unavailable.
+ */
+ @GetMapping("/agreement/document/pdf")
+ @PreAuthorize("isAuthenticated()")
+ public ResponseEntity agreementDocumentPdf(Authentication auth) {
+ Long teamId = requireLeader(auth);
+ if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
+ return procurement
+ .agreementDocumentPdf(teamId)
+ .>map(
+ pdf ->
+ ResponseEntity.ok()
+ .header(
+ HttpHeaders.CONTENT_DISPOSITION,
+ "attachment;"
+ + " filename=\"stirling-enterprise-agreement.pdf\"")
+ .contentType(MediaType.APPLICATION_PDF)
+ .body(pdf))
+ .orElseGet(() -> ResponseEntity.notFound().build());
+ }
+
/**
* Provision on accept: upgrade the team's licence to the committed annual term, valid
* immediately. Called server-side by the accept edge function (ROLE_ADMIN via X-API-Key) once
@@ -311,9 +496,38 @@ public class ProcurementController {
}
}
+ /**
+ * Go live once payment settles: advance the deal to active and re-affirm the annual licence.
+ * Called server-side by the {@code invoice.paid} webhook (ROLE_ADMIN via X-API-Key), alongside
+ * {@code /provision}, which runs earlier at accept and deliberately leaves the stage alone.
+ *
+ *
Answers 200 when the team has no deal at all, rather than erroring: a committed
+ * subscription can be closed directly in Stripe by sales with no portal deal behind it, and a
+ * non-2xx would have Stripe retry a webhook that can never succeed.
+ *
+ *
{@code invoiceId} is what makes this idempotent without swallowing renewals: the same
+ * invoice twice is a redelivery, a different one is next year's payment and has to re-issue the
+ * licence. Optional so an older caller still works, at the cost of that distinction.
+ */
+ @PostMapping("/activate")
+ @PreAuthorize("hasRole('ADMIN')")
+ public ResponseEntity activate(
+ @RequestParam("teamId") long teamId,
+ @RequestParam(value = "invoiceId", required = false) String invoiceId) {
+ try {
+ procurement.markLive(teamId, invoiceId);
+ } catch (IllegalStateException e) {
+ log.info(
+ "[procurement] activate skipped, no deal for team={}: {}",
+ teamId,
+ e.getMessage());
+ }
+ return ResponseEntity.ok().build();
+ }
+
/**
* Demo/manual stand-in for the {@code invoice.paid} webhook: mark the deal live (issue the
- * annual licence, advance to active). The real go-live is webhook-driven once payment settles.
+ * annual licence, advance to active). Production go-live runs through {@code /activate}.
*/
@PostMapping("/go-live")
@PreAuthorize("isAuthenticated()")
@@ -360,6 +574,21 @@ public class ProcurementController {
.orElse(null);
}
+ /**
+ * Best-effort client IP for the signature record: first X-Forwarded-For hop, else the peer.
+ *
+ *
Informational only. That header is client-set, so {@code signer_ip} is spoofable and is
+ * not evidence of where a signature came from — the document hash and version are what make the
+ * record trustworthy. Treat the address as a hint, never as proof.
+ */
+ private static String clientIp(HttpServletRequest request) {
+ String forwarded = request.getHeader("X-Forwarded-For");
+ if (forwarded != null && !forwarded.isBlank()) {
+ return forwarded.split(",")[0].trim();
+ }
+ return request.getRemoteAddr();
+ }
+
/**
* Build the snapshot for a deal. {@code includeLicenseKey} is true only for the team leader; a
* member sees {@code licensed} but not the key itself (see {@link #snapshot}). Mutation
@@ -381,6 +610,10 @@ public class ProcurementController {
deal.getTrialExtensionsUsed(),
deal.getLicenseRef() != null,
includeLicenseKey ? deal.getLicenseRef() : null,
+ procurement.signedAgreementLabel(deal.getDealId()).orElse(null),
+ deal.getBusinessName(),
+ deal.getContactName(),
+ deal.getContactEmail(),
latest);
}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java b/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java
index 98ec0cd573..ad745cf5bc 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java
@@ -30,4 +30,17 @@ public class ProcurementConfigurationProperties {
* /go-live is a stand-in for the invoice.paid webhook and would let a leader activate unpaid.
*/
private boolean demoControlsEnabled = false;
+
+ /**
+ * Smallest annual fee, in minor units, that may be quoted. The pricing curve has no natural
+ * floor — a small enough committed volume rounds the meter to zero — and every registered user
+ * is the leader of their own team, so without this any signup could price a $0 enterprise
+ * quote, accept it, and be provisioned a committed licence. 12_000_00 is USD 12,000/yr, the
+ * self-hosted deploy fee, chosen so the floor cannot sit below a line item the quote itself can
+ * contain.
+ *
+ *
This is a commercial number, not a technical one: set it to whatever the smallest
+ * enterprise deal you will actually sign is. Zero disables the check.
+ */
+ private long minAnnualNetMinor = 12_000_00L;
}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java
new file mode 100644
index 0000000000..c641f2e596
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java
@@ -0,0 +1,278 @@
+package stirling.software.saas.procurement.legal;
+
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import org.springframework.stereotype.Service;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.saas.legal.LegalDocumentMeta;
+import stirling.software.saas.legal.LegalDocumentRegistry;
+import stirling.software.saas.procurement.model.ProcurementQuote;
+import stirling.software.saas.procurement.pricing.ProcurementPricingService;
+import stirling.software.saas.procurement.pricing.QuoteConfig;
+import stirling.software.saas.procurement.pricing.QuoteLineItem;
+
+/**
+ * Builds the full Stirling Enterprise Agreement for a specific quote: the static MSA (Part A) and
+ * DPA (Part C) from the {@link LegalDocumentRegistry}, with the dynamic Order Form (Part B)
+ * generated from the quote and slotted where the manifest's {@code @order-form} part sits.
+ *
+ *
Only the Order Form varies per deal; the MSA and DPA bodies are rendered verbatim with token
+ * substitution. The set of values used is returned as {@code variablesJson} so a signature can pin
+ * exactly what was rendered.
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class AgreementAssembler {
+
+ public static final String DOC_ID = "enterprise-agreement";
+
+ private static final DateTimeFormatter DATE =
+ DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.US);
+ private static final String BLANK = "\\_\\_\\_\\_\\_\\_\\_\\_\\_\\_";
+
+ private final LegalDocumentRegistry registry;
+ private final ProcurementPricingService pricing;
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ /**
+ * Render the agreement for a quote. {@code signing} is null for a preview (before signing) —
+ * the effective date and signature block then read as blanks / "On signature".
+ */
+ public AssembledAgreement assemble(ProcurementQuote quote, AgreementSigning signing) {
+ LegalDocumentMeta meta =
+ registry.meta(DOC_ID)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "Enterprise agreement not registered"));
+
+ Map tokens = tokens(quote, signing, meta);
+
+ StringBuilder md = new StringBuilder();
+ for (String part : meta.parts()) {
+ if (md.length() > 0) md.append("\n\n");
+ if ("@order-form".equals(part)) {
+ md.append(LegalDocumentRegistry.fill(orderForm(quote, tokens), tokens));
+ } else {
+ md.append(LegalDocumentRegistry.fill(registry.readPart(meta, part), tokens));
+ }
+ }
+
+ String variablesJson;
+ try {
+ variablesJson = objectMapper.writeValueAsString(tokens);
+ } catch (Exception e) {
+ variablesJson = "{}";
+ }
+
+ return new AssembledAgreement(
+ meta.id(),
+ meta.version(),
+ meta.versionLabel(),
+ meta.displayName(),
+ meta.effectiveDate(),
+ meta.status(),
+ md.toString(),
+ variablesJson);
+ }
+
+ private Map tokens(
+ ProcurementQuote quote, AgreementSigning signing, LegalDocumentMeta meta) {
+ QuoteConfig cfg = toConfig(quote);
+ boolean signed = signing != null;
+
+ String legalName =
+ signed && notBlank(signing.customerLegalName())
+ ? signing.customerLegalName().trim()
+ : (notBlank(quote.getBusinessName())
+ ? quote.getBusinessName().trim()
+ : "Customer");
+
+ Map t = new LinkedHashMap<>(registry.commonTokens(meta));
+ t.put("effective_date", signed ? LocalDate.now().format(DATE) : "On signature");
+ t.put("customer_legal_name", cell(legalName));
+ t.put("quote_ref", nz(quote.getQuoteNumber()));
+ t.put("deployment", ProcurementPricingService.deploymentName(quote.getDeployment()));
+ t.put("committed_pdfs_yr", String.format(Locale.US, "%,d", Math.max(0, quote.getVolume())));
+ t.put("posture", ProcurementPricingService.postureName(quote.getIntensity()));
+ t.put("processes_per_pdf", String.valueOf(Math.max(1, quote.getIntensity())));
+ t.put("rate_per_pdf", String.format(Locale.US, "$%.4f", pricing.effectiveRatePerPdf(cfg)));
+ t.put("term_years", String.valueOf(quote.getTermYears()));
+ t.put("term_discount_pct", pricing.termDiscountPct(quote.getTermYears()) + "%");
+ t.put("sla_tier", slaTier(quote.getServiceLevel()));
+ t.put("annual_fee_y1", money(quote.getAnnualNetMinor()));
+ t.put("contract_total", money(quote.getTcvMinor()));
+ t.put("elected_or_not", quote.isIndemnification() ? "Elected" : "Not elected");
+ t.put("po_number", notBlank(quote.getPoNumber()) ? cell(quote.getPoNumber()) : "—");
+ t.put(
+ "customer_signatory",
+ signed && notBlank(signing.signatoryName())
+ ? cell(signing.signatoryName())
+ : BLANK);
+ t.put(
+ "customer_signatory_title",
+ signed && notBlank(signing.signatoryTitle())
+ ? cell(signing.signatoryTitle())
+ : BLANK);
+ return t;
+ }
+
+ /**
+ * Make a buyer-supplied value safe to slot into a markdown table cell.
+ *
+ *
An unescaped {@code |} or newline splits the cell and breaks the Order Form's table. That
+ * matters beyond appearance: this markdown is what gets hashed into the signature record, so a
+ * value that restructures the table means the SHA-256 we keep as proof covers a document
+ * reading differently from the one the signatory saw.
+ */
+ private static String cell(String raw) {
+ return raw.trim().replace("|", "\\|").replaceAll("\\s*\\R+\\s*", " ");
+ }
+
+ /** Part B — the Order Form. Generated from the quote; the only per-deal section. */
+ private String orderForm(ProcurementQuote quote, Map t) {
+ String date = t.get("effective_date");
+ String signatory = t.get("customer_signatory");
+ String signatoryTitle = t.get("customer_signatory_title");
+
+ StringBuilder sb = new StringBuilder();
+ sb.append("## Part B — Order Form · {{quote_ref}}\n\n");
+ sb.append("| Term | Value |\n| --- | --- |\n");
+ row(sb, "Customer", "{{customer_legal_name}}");
+ row(sb, "Subscription", "Enterprise · {{deployment}}");
+ row(sb, "Purchase order", "{{po_number}}");
+ row(sb, "Committed Volume", "{{committed_pdfs_yr}} PDFs / year at the {{posture}} posture");
+ row(sb, "Committed rate", "{{rate_per_pdf}} per PDF");
+ row(sb, "Service level", "{{sla_tier}} (per SLA Exhibit)");
+ row(
+ sb,
+ "Term",
+ "{{term_years}} year(s) · term discount {{term_discount_pct}} on committed processing");
+ row(sb, "Itemized services", itemizedServices(quote));
+ row(sb, "Annual Fee (year 1)", "{{annual_fee_y1}}");
+ row(sb, "Total (paid in advance)", "{{contract_total}}");
+ row(sb, "Escalator", "+3% at each anniversary during the Term");
+ row(
+ sb,
+ "Payment",
+ "Full {{term_years}}-year term invoiced in advance on acceptance · net 30 · ACH,"
+ + " wire, or check");
+ row(sb, "Overage", "Committed rate, billed quarterly in arrears");
+ row(
+ sb,
+ "Data schedule",
+ "First 25 MB per file included; each additional 25 MB or part thereof (decimal MB,"
+ + " rounded up per file, measured once at ingestion) draws down 1 PDF Process."
+ + " Frozen for the Term (MSA §3.5).");
+ row(
+ sb,
+ "Drawdown schedule",
+ "{{posture}}: {{processes_per_pdf}} PDF Processes per PDF (MSA §3.3, frozen for the Term)");
+ row(
+ sb,
+ "Enhanced IP Protection",
+ "{{elected_or_not}} — extends §7.3 to patent claims at the §8.2 super-cap");
+ row(sb, "Standard terms", "SSO, SCIM, RBAC, and audit logs included.");
+
+ sb.append(
+ "\n**Itemized services menu (include as elected):** Self-hosted deployment $12,000/yr"
+ + " · Air-gapped deployment $36,000/yr · Dedicated SE/CSM $30,000/yr · Enhanced IP"
+ + " Protection (patent coverage, Section 7.3) 5% of committed processing fees ·"
+ + " Onboarding & training $7,500 one-time · Quarterly business reviews $8,000/yr."
+ + " Baseline IP indemnification (copyright, trademark, trade secret) is included at"
+ + " no charge.\n\n");
+ sb.append(
+ "**Signatures.** By signing, each signatory represents they have authority to bind"
+ + " their Party. Signatures delivered electronically or in counterparts are"
+ + " effective as originals.\n\n");
+ sb.append("| Provider | Customer |\n| --- | --- |\n");
+ sb.append("| Stirling PDF, Inc. | {{customer_legal_name}} |\n");
+ sb.append("| Name: Matt Joseph | Name: ").append(signatory).append(" |\n");
+ sb.append("| Title: CEO | Title: ").append(signatoryTitle).append(" |\n");
+ sb.append("| Date: ").append(date).append(" | Date: ").append(date).append(" |\n");
+ return sb.toString();
+ }
+
+ /**
+ * The elected add-on lines, taken from the quote's stored breakdown (excludes the base meter).
+ */
+ private String itemizedServices(ProcurementQuote quote) {
+ List lines = parseLineItems(quote.getLineItemsJson());
+ List elected = new ArrayList<>();
+ for (QuoteLineItem li : lines) {
+ if (li.key().equals("usage")
+ || li.key().equals("seats")
+ || li.key().equals("multi-year")) {
+ continue;
+ }
+ String suffix = li.kind() == QuoteLineItem.Kind.ONE_TIME ? " (one-time)" : "/yr";
+ elected.add(li.label() + " " + money(li.amountMinor()) + suffix);
+ }
+ return elected.isEmpty() ? "None elected" : String.join(" · ", elected);
+ }
+
+ private List parseLineItems(String json) {
+ if (json == null || json.isBlank()) return List.of();
+ try {
+ return objectMapper.readValue(
+ json,
+ objectMapper
+ .getTypeFactory()
+ .constructCollectionType(List.class, QuoteLineItem.class));
+ } catch (Exception e) {
+ log.warn("[legal] could not parse quote line items for the order form", e);
+ return List.of();
+ }
+ }
+
+ private static QuoteConfig toConfig(ProcurementQuote q) {
+ int users = q.getSeats() == null ? 0 : q.getSeats();
+ return new QuoteConfig(
+ q.getVolume(),
+ users,
+ q.getIntensity(),
+ q.getSizeMult(),
+ q.getDeployment(),
+ q.getTermYears(),
+ q.getServiceLevel(),
+ q.isIndemnification(),
+ q.isTraining(),
+ q.isQbr(),
+ q.getCurrency());
+ }
+
+ private static void row(StringBuilder sb, String term, String value) {
+ sb.append("| ").append(term).append(" | ").append(value).append(" |\n");
+ }
+
+ private static String slaTier(String serviceLevel) {
+ if ("dedicated".equalsIgnoreCase(serviceLevel)) return "Dedicated";
+ if ("priority".equalsIgnoreCase(serviceLevel)) return "Priority";
+ return "Standard";
+ }
+
+ /** Minor units (cents) → whole-dollar display; the quote figures are whole dollars. */
+ private static String money(long minor) {
+ return String.format(Locale.US, "$%,d", minor / 100L);
+ }
+
+ private static boolean notBlank(String s) {
+ return s != null && !s.isBlank();
+ }
+
+ private static String nz(String s) {
+ return s == null ? "" : s;
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java
new file mode 100644
index 0000000000..8204df6514
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java
@@ -0,0 +1,71 @@
+package stirling.software.saas.procurement.legal;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import org.commonmark.Extension;
+import org.commonmark.ext.gfm.tables.TablesExtension;
+import org.commonmark.node.Node;
+import org.commonmark.parser.Parser;
+import org.commonmark.renderer.html.HtmlRenderer;
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.common.configuration.RuntimePathConfig;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.CustomHtmlSanitizer;
+import stirling.software.common.util.FileToPdf;
+import stirling.software.common.util.TempFileManager;
+
+/**
+ * Renders an assembled agreement's markdown to a PDF, dogfooding Stirling's own conversion path:
+ * commonmark (markdown → HTML) then {@link FileToPdf#convertHtmlToPdf} (HTML → PDF via WeasyPrint),
+ * the same pipeline as the product's Markdown-to-PDF tool.
+ *
+ *
The signed PDF is a stored artifact, but it must never block signing: {@link #tryRender}
+ * returns {@code null} if the conversion runtime (WeasyPrint) is unavailable, so the signature is
+ * still recorded and the buyer keeps the on-the-fly download.
+ */
+@Service
+@RequiredArgsConstructor
+public class AgreementPdfRenderer {
+
+ private final RuntimePathConfig runtimePathConfig;
+ private final TempFileManager tempFileManager;
+ private final CustomHtmlSanitizer customHtmlSanitizer;
+ private final CustomPDFDocumentFactory pdfDocumentFactory;
+
+ private static final List EXTENSIONS = List.of(TablesExtension.create());
+
+ /** Render to PDF, or return null if the conversion runtime isn't available. */
+ public byte[] tryRender(String markdown) {
+ try {
+ return render(markdown);
+ } catch (Exception e) {
+ org.slf4j.LoggerFactory.getLogger(AgreementPdfRenderer.class)
+ .warn(
+ "[legal] agreement PDF render unavailable; recording signature without a"
+ + " stored PDF: {}",
+ e.getMessage());
+ return null;
+ }
+ }
+
+ private byte[] render(String markdown) throws Exception {
+ Parser parser = Parser.builder().extensions(EXTENSIONS).build();
+ Node document = parser.parse(markdown);
+ HtmlRenderer renderer = HtmlRenderer.builder().extensions(EXTENSIONS).build();
+ String html = renderer.render(document);
+
+ byte[] pdfBytes =
+ FileToPdf.convertHtmlToPdf(
+ runtimePathConfig.getWeasyPrintPath(),
+ null,
+ html.getBytes(StandardCharsets.UTF_8),
+ "agreement.html",
+ tempFileManager,
+ customHtmlSanitizer);
+ return pdfDocumentFactory.createNewBytesBasedOnOldDocument(pdfBytes);
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java
new file mode 100644
index 0000000000..600ecda415
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java
@@ -0,0 +1,12 @@
+package stirling.software.saas.procurement.legal;
+
+/**
+ * The buyer-supplied inputs captured at the moment of signing the enterprise agreement: the legal
+ * entity name, the signatory's typed name and title, and their representation of authority to bind.
+ * Null when the agreement is rendered for preview (before signing).
+ */
+public record AgreementSigning(
+ String customerLegalName,
+ String signatoryName,
+ String signatoryTitle,
+ boolean authorityConfirmed) {}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java
new file mode 100644
index 0000000000..3e88cf555a
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java
@@ -0,0 +1,16 @@
+package stirling.software.saas.procurement.legal;
+
+/**
+ * A rendered enterprise agreement: the full markdown the buyer sees (MSA + Order Form + DPA, tokens
+ * filled), plus the registry metadata that pins it. {@code variablesJson} is the exact set of
+ * Order-Form values as rendered, stored alongside a signature so the document is reproducible.
+ */
+public record AssembledAgreement(
+ String docId,
+ String version,
+ String versionLabel,
+ String displayName,
+ String effectiveDate,
+ String status,
+ String markdown,
+ String variablesJson) {}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java
new file mode 100644
index 0000000000..425b100ba9
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java
@@ -0,0 +1,86 @@
+package stirling.software.saas.procurement.model;
+
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+import org.hibernate.annotations.CreationTimestamp;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+/**
+ * An immutable record of a signed enterprise agreement. Each signature pins the exact legal
+ * document it was signed against — {@code documentId} + {@code documentVersion} + a SHA-256 {@code
+ * contentHash} of the rendered markdown — plus the Order-Form variable snapshot and the typed
+ * signatory details, so the agreement stays reproducible even after the templates version up. The
+ * rendered PDF is stored when the conversion runtime is available.
+ */
+@Entity
+@Table(name = "procurement_agreement_signature")
+@NoArgsConstructor
+@Getter
+@Setter
+public class ProcurementAgreementSignature implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "signature_id")
+ private Long signatureId;
+
+ @Column(name = "deal_id", nullable = false)
+ private Long dealId;
+
+ @Column(name = "quote_id", nullable = false)
+ private Long quoteId;
+
+ // Which legal document, and which version of it, was signed.
+ @Column(name = "document_id", nullable = false, length = 64)
+ private String documentId;
+
+ @Column(name = "document_version", nullable = false, length = 32)
+ private String documentVersion;
+
+ @Column(name = "document_label", length = 64)
+ private String documentLabel;
+
+ // SHA-256 (hex) of the exact rendered agreement markdown the buyer accepted.
+ @Column(name = "content_hash", nullable = false, length = 64)
+ private String contentHash;
+
+ // The Order-Form variable values as rendered, so the document can be reproduced.
+ @Column(name = "variables_json", columnDefinition = "text")
+ private String variablesJson;
+
+ @Column(name = "customer_legal_name", length = 255)
+ private String customerLegalName;
+
+ @Column(name = "signatory_name", nullable = false, length = 255)
+ private String signatoryName;
+
+ @Column(name = "signatory_title", length = 255)
+ private String signatoryTitle;
+
+ @Column(name = "authority_confirmed", nullable = false)
+ private boolean authorityConfirmed;
+
+ @Column(name = "signer_ip", length = 64)
+ private String signerIp;
+
+ // The rendered PDF artifact; null when the conversion runtime was unavailable at signing.
+ @Column(name = "pdf")
+ private byte[] pdf;
+
+ @CreationTimestamp
+ @Column(name = "signed_at", nullable = false, updatable = false)
+ private LocalDateTime signedAt;
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java
index 3a5d3db902..f0db2fb6db 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java
@@ -34,6 +34,13 @@ public class ProcurementDeal implements Serializable {
private static final long serialVersionUID = 1L;
+ /**
+ * Interest, before any commitment: the account asked about enterprise but has not started a
+ * trial. Kept as a real stage so intent survives a refresh, so the enterprise surface is only
+ * shown to accounts that asked for it, and so drop-off at the cheapest step is measurable.
+ */
+ public static final String STAGE_EXPLORING = "exploring";
+
public static final String STAGE_TRIAL = "trial";
public static final String STAGE_QUOTE = "quote";
public static final String STAGE_AGREEMENT = "security";
@@ -69,12 +76,38 @@ public class ProcurementDeal implements Serializable {
@Column(name = "trial_extensions_used", nullable = false)
private int trialExtensionsUsed;
+ // Captured at trial setup, so the buying entity is known before any quote exists — the quote's
+ // own copies seed from these and may then diverge (a deal can change hands mid-cycle).
+ // Nullable: trials started before this step, and older clients, supply none.
+ @Column(name = "business_name", length = 255)
+ private String businessName;
+
+ @Column(name = "contact_name", length = 255)
+ private String contactName;
+
+ @Column(name = "contact_email", length = 320)
+ private String contactEmail;
+
+ // Addresses the buyer named at setup. Kept as the record of what was asked for; the invitations
+ // themselves go out through the team-invite path when the trial starts.
+ @Column(name = "invite_emails", length = 2000)
+ private String inviteEmails;
+
@Column(name = "license_ref", length = 128)
private String licenseRef;
@Column(name = "subscription_id", length = 255)
private String subscriptionId;
+ /**
+ * The last Stripe invoice whose payment was applied to this deal. Distinguishes a redelivered
+ * {@code invoice.paid} for a payment already handled from a genuine renewal, which has to
+ * re-issue: the committed licence expires term years from issue, so a renewal that doesn't
+ * re-issue leaves the licence lapsing after the customer has paid.
+ */
+ @Column(name = "last_paid_invoice_id", length = 255)
+ private String lastPaidInvoiceId;
+
@Column(name = "accepted_quote_id")
private Long acceptedQuoteId;
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java
index aa94128172..19e9e01004 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java
@@ -47,7 +47,11 @@ public class ProcurementQuote implements Serializable {
@Column(name = "deal_id", nullable = false)
private Long dealId;
- @Column(name = "quote_number", nullable = false, length = 64)
+ /**
+ * Stripe's quote number, the deal's one buyer-facing reference. Null until the quote is issued:
+ * Stripe assigns it at finalisation, and the issue edge function writes it back then.
+ */
+ @Column(name = "quote_number", length = 64)
private String quoteNumber;
@Column(name = "status", nullable = false, length = 24)
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.java b/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.java
index 08ade5a157..5d1234e9fc 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.java
@@ -60,12 +60,7 @@ public class ProcurementPricingService {
rates.discountPerDoubling()
* (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2))
: 0.0;
- double rate = Math.max(rates.floorRatePerRun(), rates.listRatePerRun() * (1.0 - volDisc));
- // File-size multiplier (D93): larger, image-heavy PDFs cost more OCR/compute/storage. Folds
- // into the per-run rate after the floor, so it flows through the meter, TCV and renewal.
- // QuoteConfig has already snapped it to a known tier, so a tampered request can't sneak a
- // cheaper factor in.
- rate *= cfg.sizeMult();
+ double rate = perRunRate(cfg, rates);
double termDisc = rates.termDiscount(cfg.termYears());
// The meter is a whole-dollar figure (the quote reads in dollars), then minor units.
@@ -160,6 +155,48 @@ public class ProcurementPricingService {
return new QuoteBreakdown(lines, annualNet, tcv, renewalAnnual, cfg.currency());
}
+ /**
+ * The per-run rate after the committed-volume curve, the half-cent floor, and the file-size
+ * multiplier — the same value {@link #price} meters against. Extracted so read-only callers
+ * (the Order Form) can quote it without re-deriving the curve.
+ */
+ private static double perRunRate(QuoteConfig cfg, PricingRates rates) {
+ long runVol = Math.max(0, cfg.volume()) * (long) Math.max(1, cfg.intensity());
+ double volDisc =
+ runVol > RUN_CURVE_KNEE
+ ? Math.min(
+ 0.5,
+ rates.discountPerDoubling()
+ * (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2))
+ : 0.0;
+ return Math.max(rates.floorRatePerRun(), rates.listRatePerRun() * (1.0 - volDisc))
+ * cfg.sizeMult();
+ }
+
+ /**
+ * The effective per-PDF rate at the chosen posture, in dollars (4-decimal quote figure). This
+ * is what the Order Form and quote copy speak in — never the per-run rate. Read-only; does not
+ * affect billing.
+ */
+ public double effectiveRatePerPdf(QuoteConfig cfg) {
+ return perRunRate(cfg, PricingRates.defaults()) * Math.max(1, cfg.intensity());
+ }
+
+ /** The multi-year term discount as a whole-percent figure for the Order Form (0.05 → 5). */
+ public int termDiscountPct(int termYears) {
+ return (int) Math.round(PricingRates.defaults().termDiscount(termYears) * 100.0);
+ }
+
+ /** Buyer-facing posture name (Essentials / Governed / Regulated) for the given intensity. */
+ public static String postureName(int intensity) {
+ return postureLabel(intensity);
+ }
+
+ /** Buyer-facing deployment name (Stirling Cloud / Self-hosted / Air-gapped). */
+ public static String deploymentName(String deployment) {
+ return deploymentLabel(deployment);
+ }
+
/** The default CPI escalator (fraction) applied to the annual fee on each post-term renewal. */
public double cpiEscalator() {
return PricingRates.defaults().cpiEscalator();
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java
new file mode 100644
index 0000000000..419189617e
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java
@@ -0,0 +1,29 @@
+package stirling.software.saas.procurement.repository;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
+
+import stirling.software.saas.procurement.model.ProcurementAgreementSignature;
+
+public interface ProcurementAgreementSignatureRepository
+ extends JpaRepository {
+
+ Optional findFirstByDealIdOrderBySignedAtDesc(Long dealId);
+
+ Optional findFirstByQuoteIdOrderBySignedAtDesc(Long quoteId);
+
+ /**
+ * Version labels of a deal's signatures, newest first. Projects just the label column so the
+ * frequently-polled snapshot never loads the PDF bytes. A signature means the agreement is
+ * signed; the PDF is resolved (stored or re-rendered) at download time.
+ */
+ @Query(
+ "SELECT s.documentLabel FROM ProcurementAgreementSignature s"
+ + " WHERE s.dealId = :dealId"
+ + " ORDER BY s.signedAt DESC")
+ List findSignedLabels(@Param("dealId") Long dealId);
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java
index cae1cf36fb..a739e538b2 100644
--- a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java
+++ b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java
@@ -5,7 +5,6 @@ import java.time.LocalDateTime;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
-import java.util.UUID;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
@@ -20,16 +19,24 @@ import stirling.software.common.model.enumeration.TeamRole;
import stirling.software.proprietary.model.TeamMembership;
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.saas.procurement.config.ProcurementConfigurationProperties;
+import stirling.software.saas.procurement.legal.AgreementAssembler;
+import stirling.software.saas.procurement.legal.AgreementPdfRenderer;
+import stirling.software.saas.procurement.legal.AgreementSigning;
+import stirling.software.saas.procurement.legal.AssembledAgreement;
import stirling.software.saas.procurement.license.EnterpriseLicenseService;
import stirling.software.saas.procurement.license.LicenseEntitlements;
+import stirling.software.saas.procurement.model.ProcurementAgreementSignature;
import stirling.software.saas.procurement.model.ProcurementDeal;
import stirling.software.saas.procurement.model.ProcurementQuote;
import stirling.software.saas.procurement.model.QuoteDetails;
import stirling.software.saas.procurement.pricing.ProcurementPricingService;
import stirling.software.saas.procurement.pricing.QuoteBreakdown;
import stirling.software.saas.procurement.pricing.QuoteConfig;
+import stirling.software.saas.procurement.repository.ProcurementAgreementSignatureRepository;
import stirling.software.saas.procurement.repository.ProcurementDealRepository;
import stirling.software.saas.procurement.repository.ProcurementQuoteRepository;
+import stirling.software.saas.service.SaasTeamService;
+import stirling.software.saas.util.LogRedactionUtils;
/**
* Orchestrates a linked team's procurement journey: start a (mock-licensed) trial, build a
@@ -52,6 +59,12 @@ public class ProcurementService {
private final EnterpriseLicenseService licenses;
private final ProcurementConfigurationProperties config;
private final TeamMembershipRepository memberRepo;
+ private final AgreementAssembler agreementAssembler;
+ private final AgreementPdfRenderer agreementPdfRenderer;
+ private final ProcurementAgreementSignatureRepository signatureRepo;
+ // Trial-setup invitations run through the team-invite path, with its seat, role and
+ // rate-limit rules rather than a second implementation here.
+ private final SaasTeamService teams;
public ProcurementService(
ProcurementDealRepository dealRepo,
@@ -59,13 +72,21 @@ public class ProcurementService {
ProcurementPricingService pricing,
EnterpriseLicenseService licenses,
ProcurementConfigurationProperties config,
- TeamMembershipRepository memberRepo) {
+ TeamMembershipRepository memberRepo,
+ AgreementAssembler agreementAssembler,
+ AgreementPdfRenderer agreementPdfRenderer,
+ ProcurementAgreementSignatureRepository signatureRepo,
+ SaasTeamService teams) {
this.dealRepo = dealRepo;
this.quoteRepo = quoteRepo;
this.pricing = pricing;
this.licenses = licenses;
this.config = config;
this.memberRepo = memberRepo;
+ this.agreementAssembler = agreementAssembler;
+ this.agreementPdfRenderer = agreementPdfRenderer;
+ this.signatureRepo = signatureRepo;
+ this.teams = teams;
}
/**
@@ -89,11 +110,45 @@ public class ProcurementService {
return dealRepo.findByTeamId(teamId);
}
+ /**
+ * Starting a trial is only legitimate before one exists, while the buyer is still exploring, or
+ * to restart within the trial itself. A null stage is a deal that has just been constructed.
+ *
+ *
Package-private so the policy can be tested without the service's ten dependencies. Adding
+ * a later stage here would let a leader replace a paying customer's committed licence.
+ */
+ static boolean canStartTrial(String stage) {
+ return stage == null
+ || ProcurementDeal.STAGE_EXPLORING.equals(stage)
+ || ProcurementDeal.STAGE_TRIAL.equals(stage);
+ }
+
@Transactional(readOnly = true)
public List quotesForDeal(Long dealId) {
return quoteRepo.findByDealIdOrderByCreatedAtDesc(dealId);
}
+ /**
+ * Record that the account is looking at enterprise. Creates the deal at {@code exploring} when
+ * there is none; an existing deal is returned untouched, so this can never walk a live deal
+ * backwards or restart a trial.
+ */
+ @Transactional
+ public ProcurementDeal recordInterest(Long teamId) {
+ return dealRepo.findByTeamId(teamId)
+ .orElseGet(
+ () -> {
+ ProcurementDeal deal = new ProcurementDeal(teamId);
+ deal.setStage(ProcurementDeal.STAGE_EXPLORING);
+ ProcurementDeal saved = dealRepo.save(deal);
+ log.info(
+ "[procurement] interest recorded team={} deal={}",
+ teamId,
+ saved.getDealId());
+ return saved;
+ });
+ }
+
/**
* Start (or restart) the free trial for a team: issue a mock trial licence and stamp the trial
* window on the deal. No Stripe: a no-card trial has no subscription; the entitlement is the
@@ -101,10 +156,40 @@ public class ProcurementService {
* ({@code cloud}/{@code selfhost}/{@code airgap}) and seat count are captured here so the quote
* builder opens seeded to their environment; both are still editable when the quote is built.
*/
- @Transactional
public ProcurementDeal startTrial(Long teamId, String deployment, int seats) {
+ return startTrial(teamId, deployment, seats, null, null, null, null);
+ }
+
+ /**
+ * Start (or restart) the trial, capturing the buying entity if the setup step collected it.
+ * Blank details are ignored rather than written, so a re-run without them keeps what is there.
+ *
+ *
Only from before the trial or during it. Past that, {@code licenseRef} points at the
+ * committed annual licence, and this method would replace it with a fresh 14-day trial key
+ * while Stripe kept billing — the same hazard {@link #extendTrial} guards against, one step
+ * worse because it re-issues rather than re-dates. It would also rewind the stage and reset the
+ * extension counter.
+ *
+ *
The transaction is declared here rather than on the 3-arg overload: that one only
+ * delegates, and Spring's proxy cannot intercept a self-invocation, so an annotation there does
+ * nothing for either path. This is the method the controller calls, and it reaches out to
+ * Keygen between the read and the write.
+ */
+ @Transactional
+ public ProcurementDeal startTrial(
+ Long teamId,
+ String deployment,
+ int seats,
+ String businessName,
+ String contactName,
+ String contactEmail,
+ String inviteEmails) {
ProcurementDeal deal =
dealRepo.findByTeamId(teamId).orElseGet(() -> new ProcurementDeal(teamId));
+ if (!canStartTrial(deal.getStage())) {
+ throw new IllegalStateException(
+ "Trial cannot be started from stage " + deal.getStage());
+ }
LocalDateTime now = LocalDateTime.now();
LocalDateTime ends = now.plusDays(config.getTrialDurationDays());
deal.setStage(ProcurementDeal.STAGE_TRIAL);
@@ -113,6 +198,10 @@ public class ProcurementService {
deal.setTrialStartedAt(now);
deal.setTrialEndsAt(ends);
deal.setTrialExtensionsUsed(0);
+ if (isNotBlank(businessName)) deal.setBusinessName(businessName.trim());
+ if (isNotBlank(contactName)) deal.setContactName(contactName.trim());
+ if (isNotBlank(contactEmail)) deal.setContactEmail(contactEmail.trim());
+ if (isNotBlank(inviteEmails)) deal.setInviteEmails(inviteEmails.trim());
deal.setLicenseRef(licenses.issueTrialLicense(teamId, leaderEmail(teamId), ends));
deal = dealRepo.save(deal);
log.info(
@@ -128,6 +217,45 @@ public class ProcurementService {
/**
* Constrain a caller-supplied deployment to the known set; anything else falls back to cloud.
*/
+ /**
+ * Send the invitations named at trial setup. Best-effort per address: a rejection (already a
+ * member, an invitee with their own paid plan, the hourly rate limit) must not fail the trial,
+ * so each is logged and skipped rather than propagated.
+ *
+ *
Note the first accepted invitation converts a personal team into a shared one with
+ * unlimited seats — that is {@code inviteUserToTeam}'s own rule, and naming teammates here is
+ * the buyer asking for exactly that.
+ */
+ public void sendTrialInvites(
+ Long teamId, stirling.software.proprietary.security.model.User inviter, String emails) {
+ if (inviter == null || !isNotBlank(emails)) return;
+ for (String raw : emails.split("[,;\s]+")) {
+ String email = raw.trim();
+ if (email.isEmpty()) continue;
+ try {
+ teams.inviteUserToTeam(teamId, email, inviter);
+ // Redacted: an invitee list is third-party PII, and these logs are the one place it
+ // would otherwise be written in full. LogRedactionUtils is what the rest of the
+ // SaaS
+ // module uses for the same reason.
+ log.info(
+ "[procurement] trial invite sent team={} to={}",
+ teamId,
+ LogRedactionUtils.redactEmail(email));
+ } catch (Exception e) {
+ log.warn(
+ "[procurement] trial invite skipped team={} to={}: {}",
+ teamId,
+ LogRedactionUtils.redactEmail(email),
+ e.getMessage());
+ }
+ }
+ }
+
+ private static boolean isNotBlank(String value) {
+ return value != null && !value.isBlank();
+ }
+
private static String normalizeDeployment(String deployment) {
if (deployment == null) return "cloud";
String d = deployment.trim().toLowerCase(Locale.ROOT);
@@ -172,16 +300,32 @@ public class ProcurementService {
}
// (Re)building a quote returns the deal to the quote stage and drops any prior acceptance,
// so a rebuild from security/payment can't leave a stale stage or accepted-quote pointer.
+ QuoteBreakdown breakdown = pricing.price(cfg);
+ // Enforced before anything is persisted, and server-side rather than in the builder: the
+ // pricing curve has no natural floor (a small enough committed volume rounds the meter to
+ // zero) and every registered user leads their own team, so without this any signup could
+ // price a $0 enterprise quote, accept it, and be provisioned a committed licence.
+ long floor = config.getMinAnnualNetMinor();
+ if (floor > 0 && breakdown.annualNetMinor() < floor) {
+ throw new IllegalStateException(
+ "Quoted annual fee "
+ + breakdown.annualNetMinor()
+ + " is below the minimum enterprise deal size "
+ + floor);
+ }
+
deal.setStage(ProcurementDeal.STAGE_QUOTE);
deal.setAcceptedQuoteId(null);
deal = dealRepo.save(deal);
- QuoteBreakdown breakdown = pricing.price(cfg);
-
ProcurementQuote quote = new ProcurementQuote();
quote.setDealId(deal.getDealId());
- quote.setQuoteNumber(nextQuoteNumber(deal.getDealId()));
- // Priced but not yet issued: the edge fn creates the Stripe Quote and flips this to SENT.
+ // No quote number here: the deal's one reference is Stripe's, and Stripe does not assign it
+ // until the quote is finalised. The edge fn creates the Stripe Quote, flips this to SENT,
+ // and
+ // writes the number back. Nothing displays a reference in between — the builder only shows
+ // one
+ // for an issued quote, and the agreement is not assembled until after issue.
quote.setStatus(ProcurementQuote.STATUS_DRAFT);
quote.setCurrency(cfg.currency());
quote.setVolume(cfg.volume());
@@ -210,10 +354,11 @@ public class ProcurementService {
quote.setLineItemsJson(writeLineItems(breakdown));
quote.setValidUntil(LocalDate.now().plusDays(30));
quote = quoteRepo.save(quote);
+ // Logged by id, not reference: a draft has no reference until Stripe issues it.
log.info(
"[procurement] quote built team={} quote={} annualNet={} tcv={}",
teamId,
- quote.getQuoteNumber(),
+ quote.getQuoteId(),
quote.getAnnualNetMinor(),
quote.getTcvMinor());
return quote;
@@ -241,6 +386,164 @@ public class ProcurementService {
return deal;
}
+ /** The quote a team is currently transacting on: its accepted quote, else the most recent. */
+ @Transactional(readOnly = true)
+ public Optional currentQuote(Long teamId) {
+ return dealRepo.findByTeamId(teamId)
+ .flatMap(
+ deal -> {
+ if (deal.getAcceptedQuoteId() != null) {
+ Optional accepted =
+ quoteRepo.findById(deal.getAcceptedQuoteId());
+ if (accepted.isPresent()) return accepted;
+ }
+ return quoteRepo
+ .findByDealIdOrderByCreatedAtDesc(deal.getDealId())
+ .stream()
+ .findFirst();
+ });
+ }
+
+ /**
+ * The filled enterprise agreement for a team's current quote, rendered for review (unsigned).
+ */
+ @Transactional(readOnly = true)
+ public Optional agreementDocument(Long teamId) {
+ return currentQuote(teamId).map(q -> agreementAssembler.assemble(q, null));
+ }
+
+ /**
+ * The current (unsigned) agreement rendered to PDF, for download at the sign step. Empty when
+ * there's no quote yet or the render runtime is unavailable. The signed PDF (with the signature
+ * block filled) is a separate artifact recorded at signing (see {@link #latestSignature}).
+ */
+ @Transactional(readOnly = true)
+ public Optional agreementDocumentPdf(Long teamId) {
+ return currentQuote(teamId)
+ .map(q -> agreementAssembler.assemble(q, null))
+ .map(a -> agreementPdfRenderer.tryRender(a.markdown()));
+ }
+
+ /**
+ * Record a signed enterprise agreement: assemble the final document, hash it, render + store
+ * the PDF (best-effort), and persist an immutable signature pinned to the exact document
+ * version. Does not itself accept the quote into a subscription — the caller proceeds to accept
+ * as before.
+ *
+ *
Deliberately not {@code @Transactional}: rendering the PDF shells out to WeasyPrint, and
+ * holding the deal's row lock across an external process buys nothing here. The only write is a
+ * single insert, which {@code save} makes atomic on its own.
+ */
+ public ProcurementAgreementSignature signAgreement(
+ Long teamId, AgreementSigning signing, String signerIp) {
+ ProcurementDeal deal =
+ dealRepo.findByTeamId(teamId)
+ .orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));
+ ProcurementQuote quote =
+ currentQuote(teamId)
+ .orElseThrow(
+ () ->
+ new IllegalStateException(
+ "No quote to sign for team " + teamId));
+
+ // Signing is only meaningful against an issued quote at the agreement stage. Without this a
+ // direct API call could record a signature over a draft (whose quote_ref is still empty),
+ // or
+ // re-sign a deal that has already moved on.
+ if (!ProcurementDeal.STAGE_AGREEMENT.equals(deal.getStage())) {
+ throw new IllegalStateException(
+ "Deal is not at the agreement stage for team " + teamId);
+ }
+ if (!ProcurementQuote.STATUS_SENT.equals(quote.getStatus())) {
+ throw new IllegalStateException("Quote is not issued for team " + teamId);
+ }
+
+ AssembledAgreement assembled = agreementAssembler.assemble(quote, signing);
+
+ ProcurementAgreementSignature sig = new ProcurementAgreementSignature();
+ sig.setDealId(deal.getDealId());
+ sig.setQuoteId(quote.getQuoteId());
+ sig.setDocumentId(assembled.docId());
+ sig.setDocumentVersion(assembled.version());
+ sig.setDocumentLabel(assembled.versionLabel());
+ sig.setContentHash(sha256(assembled.markdown()));
+ sig.setVariablesJson(assembled.variablesJson());
+ sig.setCustomerLegalName(signing.customerLegalName());
+ sig.setSignatoryName(signing.signatoryName());
+ sig.setSignatoryTitle(signing.signatoryTitle());
+ sig.setAuthorityConfirmed(signing.authorityConfirmed());
+ sig.setSignerIp(signerIp);
+ sig.setPdf(agreementPdfRenderer.tryRender(assembled.markdown()));
+ sig = signatureRepo.save(sig);
+ log.info(
+ "[procurement] agreement signed team={} quote={} doc={} pdf={}",
+ teamId,
+ quote.getQuoteId(),
+ assembled.versionLabel(),
+ sig.getPdf() != null);
+ return sig;
+ }
+
+ /** The latest recorded signature for a team's deal, if any (for the signed-PDF download). */
+ @Transactional(readOnly = true)
+ public Optional latestSignature(Long teamId) {
+ return dealRepo.findByTeamId(teamId)
+ .flatMap(
+ deal ->
+ signatureRepo.findFirstByDealIdOrderBySignedAtDesc(
+ deal.getDealId()));
+ }
+
+ /**
+ * The version label of the deal's latest signed agreement, if any. Used to surface the
+ * "download signed agreement" action once a signature exists; the snapshot polls this, so it
+ * deliberately avoids loading the PDF bytes.
+ *
+ *
Deliberately not conditional on a stored PDF: download re-renders from the pinned document
+ * version on demand, so the action works whether or not the render succeeded at signing time.
+ */
+ @Transactional(readOnly = true)
+ public Optional signedAgreementLabel(Long dealId) {
+ return signatureRepo.findSignedLabels(dealId).stream().findFirst();
+ }
+
+ /**
+ * The signed agreement as a PDF for download: the artifact stored at signing, or — if the
+ * render runtime was unavailable then — re-rendered now from the signature's details. Empty
+ * when the team has no signature or the render runtime is still unavailable.
+ */
+ @Transactional(readOnly = true)
+ public Optional signedAgreementPdf(Long teamId) {
+ return latestSignature(teamId)
+ .flatMap(
+ sig -> {
+ if (sig.getPdf() != null) return Optional.of(sig.getPdf());
+ return quoteRepo
+ .findById(sig.getQuoteId())
+ .map(
+ q ->
+ agreementAssembler.assemble(
+ q,
+ new AgreementSigning(
+ sig.getCustomerLegalName(),
+ sig.getSignatoryName(),
+ sig.getSignatoryTitle(),
+ sig.isAuthorityConfirmed())))
+ .map(a -> agreementPdfRenderer.tryRender(a.markdown()));
+ });
+ }
+
+ private static String sha256(String s) {
+ try {
+ byte[] digest =
+ java.security.MessageDigest.getInstance("SHA-256")
+ .digest(s.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ return java.util.HexFormat.of().formatHex(digest);
+ } catch (java.security.NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 unavailable", e);
+ }
+ }
+
/**
* Provision on accept: upgrade the team's licence to the committed annual term (valid
* immediately), so the buyer can get going the moment they accept — before the invoice is paid.
@@ -260,22 +563,58 @@ public class ProcurementService {
}
/**
- * Mark the deal fully live (advance to the active stage) once payment settles. In production
- * this is the {@code invoice.paid} webhook; here it's the demo/manual stand-in. Re-affirms the
+ * Mark the deal fully live (advance to the active stage) once payment settles — driven by the
+ * {@code invoice.paid} webhook, and by the demo control when those are enabled. Re-affirms the
* annual licence in case provisioning didn't run at accept.
+ *
+ *
Idempotent per invoice rather than per stage, which matters because {@code invoice.paid}
+ * carries two different meanings. Stripe redelivers events, so the same invoice
+ * arriving twice must do nothing. But the renewal payment a year later is also an {@code
+ * invoice.paid}, and the committed licence expires term years from issue — so a
+ * different invoice has to re-issue, moving the expiry out, or the customer's licence
+ * lapses after they have paid. Keying on the stage alone couldn't tell those apart and treated
+ * every renewal as a duplicate.
+ *
+ * @param paidInvoiceId the Stripe invoice that was paid, or null when the caller has no invoice
+ * to identify the payment by (the demo control). Null keeps the old conservative behaviour:
+ * a live deal short-circuits, since there is nothing to tell a renewal from a repeat.
*/
@Transactional
- public ProcurementDeal markLive(Long teamId) {
+ public ProcurementDeal markLive(Long teamId, String paidInvoiceId) {
ProcurementDeal deal =
dealRepo.findByTeamId(teamId)
.orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));
+ if (ProcurementDeal.STAGE_LIVE.equals(deal.getStage())
+ && (paidInvoiceId == null || paidInvoiceId.equals(deal.getLastPaidInvoiceId()))) {
+ log.debug(
+ "[procurement] invoice.paid already applied team={} deal={} invoice={}",
+ teamId,
+ deal.getDealId(),
+ paidInvoiceId);
+ return deal;
+ }
+ boolean renewal = ProcurementDeal.STAGE_LIVE.equals(deal.getStage());
deal.setLicenseRef(issueOrUpgradeAnnual(deal));
+ if (paidInvoiceId != null) deal.setLastPaidInvoiceId(paidInvoiceId);
deal.setStage(ProcurementDeal.STAGE_LIVE);
deal = dealRepo.save(deal);
- log.info("[procurement] deal live team={} deal={}", teamId, deal.getDealId());
+ log.info(
+ "[procurement] deal live team={} deal={} renewal={} invoice={}",
+ teamId,
+ deal.getDealId(),
+ renewal,
+ paidInvoiceId);
return deal;
}
+ /**
+ * Go live with no invoice reference — the demo control. See {@link #markLive(Long, String)}.
+ */
+ @Transactional
+ public ProcurementDeal markLive(Long teamId) {
+ return markLive(teamId, null);
+ }
+
/**
* Issue or upgrade the committed annual licence from the deal's accepted (else latest) quote,
* stamping the full entitlement snapshot onto it and upgrading the trial licence in place when
@@ -327,15 +666,34 @@ public class ProcurementService {
* before paying — that's bounded: the trial licence carries {@code expiry = trialEndsAt}, so
* the file the verifier accepts self-expires at trial end. The buyer must re-download after
* provisioning to get the committed-term file (the portal warns about this).
+ *
+ *
Once a quote exists, the quote's deployment decides — not the deal's. They are two
+ * different values: the deal's is chosen free at trial setup, the quote's is the one carrying
+ * the air-gap deploy fee. Reading the deal's here meant selecting air-gapped in the trial and
+ * then buying a cloud quote still yielded the offline file, and after provisioning it was
+ * checked out against the committed annual licence — so the self-expiry above no longer bounded
+ * it.
*/
@Transactional(readOnly = true)
public Optional offlineLicenseFile(Long teamId) {
ProcurementDeal deal = dealRepo.findByTeamId(teamId).orElse(null);
if (deal == null || deal.getLicenseRef() == null) return Optional.empty();
- if (!"airgap".equalsIgnoreCase(deal.getDeployment())) return Optional.empty();
+ if (!"airgap".equalsIgnoreCase(entitledDeployment(deal))) return Optional.empty();
return Optional.of(licenses.checkOutLicenseFile(deal.getLicenseRef()));
}
+ /**
+ * The deployment the team is actually entitled to: the priced quote's once one exists,
+ * otherwise the trial's self-selected target. Paid entitlements must follow what was quoted.
+ */
+ private String entitledDeployment(ProcurementDeal deal) {
+ ProcurementQuote quote = currentQuote(deal.getTeamId()).orElse(null);
+ if (quote != null && quote.getDeployment() != null && !quote.getDeployment().isBlank()) {
+ return quote.getDeployment();
+ }
+ return deal.getDeployment();
+ }
+
/**
* Reset a team's procurement: delete the deal (quotes + activity cascade). For
* re-demos/testing.
@@ -346,12 +704,6 @@ public class ProcurementService {
log.info("[procurement] deal reset team={}", teamId);
}
- private String nextQuoteNumber(Long dealId) {
- int seq = quoteRepo.findByDealIdOrderByCreatedAtDesc(dealId).size() + 1;
- String token = UUID.randomUUID().toString().substring(0, 4).toUpperCase(Locale.ROOT);
- return String.format(Locale.ROOT, "QT-%s-%04d", token, seq);
- }
-
private String writeLineItems(QuoteBreakdown breakdown) {
try {
return OBJECT_MAPPER.writeValueAsString(breakdown.lineItems());
diff --git a/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md
new file mode 100644
index 0000000000..12cceaef65
--- /dev/null
+++ b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md
@@ -0,0 +1,53 @@
+## Part C — Data Processing Addendum
+
+This DPA forms part of the Agreement and applies where Provider processes Personal Data on Customer's behalf.
+
+### C1. Roles; scope; instructions
+
+Customer is the controller (or a processor on behalf of its own controllers); Provider is a processor (or subprocessor, as applicable). Provider processes Personal Data only on Customer's documented instructions — including processing initiated by Customer's users, policies, pipelines, and API calls — unless required by law (in which case Provider informs Customer unless legally prohibited). **Provider will inform Customer without undue delay if, in Provider's opinion, an instruction infringes the GDPR, UK GDPR, or other applicable data-protection law.** Customer is responsible for the lawfulness of the Personal Data it submits and the instructions it gives; Customer's rights under this DPA include instruction, audit (C9), objection to subprocessors (C5), assistance (C6), and return or deletion of data (C10).
+
+### C2. Details of processing
+
+**Subject matter/nature:** PDF processing and governance (classification, redaction, routing, retention, conversion, signing, extraction, AI-assisted analysis). **Duration:** the Term plus the deletion period. **Categories of data:** any Personal Data contained in Customer files and metadata (names, contact details, identifiers, financial or health data if present in Customer files), account data of Customer users. **Data subjects:** Customer's employees, users, customers, and other persons appearing in Customer files. **Sensitive data:** may be present in Customer files at Customer's discretion; Customer is responsible for the lawful basis.
+
+### C3. Confidentiality; personnel
+
+Provider ensures persons authorized to process Personal Data are bound by confidentiality and receive security training. Zero-standing-access applies: content access is just-in-time, logged, and audited (MSA Section 4.2).
+
+### C4. Security measures (Annex II summary)
+
+Encryption in transit (TLS 1.2+) and at rest (AES-256); zero-standing-access with audited JIT elevation; role-based access control; SSO/SCIM; tenant isolation; vulnerability management and penetration testing; audit logging of processing events (including file name, hash, size, and operations); backup and recovery. For Self-hosted and Air-gapped deployments, Customer operates the runtime environment and is responsible for infrastructure-level controls; Provider's measures apply to license/metering services and support access.
+
+### C5. Subprocessors
+
+Customer generally authorizes the subprocessors listed at {{subprocessor_url}}: cloud infrastructure (Amazon Web Services), payment processing (Stripe, as independent controller for payment data), email delivery (Google), account infrastructure (Supabase), product telemetry (PostHog, EU-hosted; pseudonymous usage events, never file content), and AI model providers: **Anthropic** (Claude models — receives prompts and the document text or excerpts needed for the requested AI feature) and **Voyage AI** (embedding models — receives extracted text excerpts solely to generate embeddings where Customer enables Ingestion/RAG features). AI features are optional and may be disabled; where used, AI providers receive only the content needed for the requested feature. **Whole Customer files are never transmitted to any AI provider.** Neither AI provider trains on Customer data (verified against the signed provider agreements, Jul 10, 2026). Provider gives thirty (30) days' notice of new subprocessors; Customer may object on reasonable data-protection grounds, and if unresolved, may terminate the affected Services with a pro-rata refund. **Provider imposes data-protection obligations on each subprocessor by written contract that are at least as protective as this DPA, and remains fully responsible to Customer for each subprocessor's performance.**
+
+### C6. Data subject requests; assistance
+
+Taking into account the nature of the processing, Provider provides reasonable assistance (including through the Processor's search, redaction, and audit tools) for Customer's obligations under GDPR Articles 32–36: security of processing, breach notification to authorities and data subjects, data protection impact assessments, and prior consultations with supervisory authorities, as well as responses to data subject requests. Provider forwards requests received directly to Customer and does not respond except as legally required. **Provider makes available to Customer all information necessary to demonstrate compliance with this DPA and allows for and contributes to audits, including inspections, per Section C9.**
+
+### C7. Breach notification
+
+Per MSA Section 5.3: without undue delay after becoming aware of a Personal Data Breach, and in any event within forty-eight (48) hours of awareness, with information provided in phases as available — including the nature of the breach, categories and approximate volumes affected, likely consequences, and measures taken or proposed.
+
+### C8. International transfers
+
+Where Personal Data subject to GDPR/UK GDPR is transferred to countries without adequacy, the Parties incorporate the EU Standard Contractual Clauses (Commission Decision 2021/914): **Module 2** (controller-to-processor) where Customer is a controller, and **Module 3** (processor-to-processor) where Customer acts as a processor, with the following selections — Clause 7 (docking): included; Clause 9(a): Option 2 (general written authorization, 30 days' notice per C5); Clause 11(a) optional language: not used; Clause 17: the law of Ireland; Clause 18: the courts of Ireland; competent supervisory authority: the Irish Data Protection Commission (per Annex I.C). Annex I (parties, description of transfer: as per Section C2), Annex II (technical and organizational measures: as per Section C4), and Annex III (subprocessors: as per Section C5 and {{subprocessor_url}}) are completed by reference to this DPA. For UK transfers, the UK International Data Transfer Addendum applies with its Tables completed by reference to the foregoing. Provider is not certified under the EU-U.S. Data Privacy Framework; the SCCs are the transfer mechanism.
+
+**Note:** Provider does not currently offer contractual EU data residency for Stirling Cloud; residency is achieved via Self-hosted or Air-gapped deployment.
+
+### C9. Audits
+
+Provider's security reports and documentation (Section 5.1) are the ordinary means of demonstrating compliance. Customer may additionally audit — by itself or a mandated auditor — once per year on thirty (30) days' notice, and at any time where: (a) a security incident affecting Customer Personal Data has occurred; (b) provided documentation reveals a material deficiency; (c) a competent supervisory authority requires it; or (d) Customer reasonably suspects material noncompliance with this DPA. Audits are conducted during business hours, under confidentiality, at Customer's cost, with reasonable notice, without unreasonable interference with Provider's operations, and without access to other customers' data.
+
+### C10. Return & deletion
+
+On termination, at Customer's choice, Provider returns Customer file content and Personal Data (export of Customer files and the governed-record metadata) and/or deletes them — from live systems within thirty (30) days and from backups within ninety (90) days — except as retention is required by law, and certifies deletion on request. Where Customer uses HYOK, key destruction by Customer renders content cryptographically inaccessible immediately.
+
+### C11. CCPA/CPRA
+
+Provider is a "service provider" under the CCPA/CPRA. Provider: (a) processes Personal Information only for the business purposes specified in this Agreement — providing, securing, metering, and supporting the Services described in Section C2; (b) shall not sell or share Personal Information; (c) shall not retain, use, or disclose it for any purpose other than those business purposes, or outside the direct business relationship between the Parties; (d) shall not combine it with Personal Information received from other sources, except as permitted by CCPA regulations for the business purposes; (e) provides the same level of privacy protection required of businesses by the CCPA; (f) will notify Customer if it determines it can no longer meet its CCPA obligations; (g) grants Customer the right, upon reasonable notice, to take reasonable and appropriate steps to ensure Provider's use of Personal Information is consistent with Customer's obligations, and to stop and remediate any unauthorized use; and (h) flows these requirements down to its subprocessors per Section C5. Provider certifies that it understands these restrictions and will comply with them.
+
+### C12. Liability
+
+Liability under this DPA is subject to the MSA's limitations (Section 8).
diff --git a/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md
new file mode 100644
index 0000000000..cd3f6742eb
--- /dev/null
+++ b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md
@@ -0,0 +1,119 @@
+# Stirling Enterprise Agreement
+
+One signature executes all three parts: the Master Services Agreement (Part A), the Order Form (Part B), and the Data Processing Addendum (Part C). The Stirling EULA & Commercial Terms is incorporated by reference.
+
+## Part A — Master Services Agreement
+
+This Master Services Agreement (the "Agreement") is entered into as of {{effective_date}} (the "Effective Date") by and between **Stirling PDF, Inc.**, a Delaware corporation with offices at 548 Market Street PMB 887643, San Francisco, CA 94104 ("Provider"), and **{{customer_legal_name}}** ("Customer"). Each a "Party," together the "Parties."
+
+### 1. Services & License
+
+1.1 **The Services.** Provider will provide the Stirling PDF Processor (the "Processor") — the hosted or customer-deployed platform for distributing PDF editors and governing PDF processing, including policies, pipelines, the Stirling Agent, API access, and the administrative console — and the Stirling PDF Editor (the "Editor"), as described in the Order Form.
+
+1.2 **License grants.** Provider grants Customer, for the Term: (a) a non-exclusive, non-transferable right to access and use the Processor for Customer's internal business operations, up to the Committed Volume; and (b) a non-exclusive right to deploy and distribute the Editor to Customer's authorized users without limit on user count. Open-source components of the Editor remain governed by their own licenses, which control for those components.
+
+1.3 **Deployment.** The Services are delivered via the deployment stated in the Order Form (Stirling Cloud, Self-hosted, or Air-gapped). Self-hosted deployments validate their license and report metering data online; Air-gapped deployments verify a signed activation bundle offline and reconcile usage periodically as described in the Documentation. Customer shall not disable, circumvent, or falsify license validation or usage metering. **The metered rate does not vary by deployment**; deployment-specific services are priced as line items in the Order Form.
+
+1.4 **Restrictions.** Customer shall not: resell or provide the Services to third parties as a service bureau; reverse engineer non-open-source components; use the Services to violate law; or exceed the scope of the Order Form other than through Overage (Section 3.4).
+
+### 2. Term & Renewal
+
+2.1 **Initial Term.** {{term_years}} year(s) from the Effective Date.
+
+2.2 **Renewal.** The Agreement auto-renews for successive periods equal to the Initial Term unless either Party gives sixty (60) days' written notice of non-renewal before the end of the then-current term. The Annual Fee for each renewal year equals the immediately preceding year's Annual Fee increased by three percent (3%) — the same formula as Section 2.3. Itemized services escalate at the same rate unless restated in a superseding Order Form.
+
+2.3 **In-term escalator.** The Annual Fee (including itemized services) increases by a fixed three percent (3%) at each anniversary of the Effective Date during the Term.
+
+### 3. Fees & Payment
+
+3.1 **Annual Fee.** Customer shall pay the Annual Fee stated in the Order Form, calculated as the Committed Volume ({{committed_pdfs_yr}} PDFs per year) at {{rate_per_pdf}} per PDF at the {{posture}} governance posture, plus the itemized services in the Order Form, less the term discount stated there.
+
+3.2 **Invoicing.** Fees are invoiced annually in advance, due net thirty (30) days. Late amounts accrue interest at 1.5% per month or the maximum permitted by law, whichever is less. Fees are exclusive of taxes; Customer is responsible for all taxes other than Provider's income taxes.
+
+3.3 **Committed Volume; measurement.** The Committed Volume is denominated in PDFs processed per year at the stated posture, and converts to a drawdown allowance in PDF Processes at the fixed conversion schedule below, which is frozen for the Term:
+
+| Posture | PDF Processes per PDF |
+| --- | --- |
+| Essentials | 2 |
+| Governed | 4 |
+| Regulated | 7 |
+
+A **"PDF Process"** is one policy execution, one pipeline run, or one Stirling Agent returned artifact, applied to one file, plus Data Processing increments under Section 3.5. For clarity: a pipeline run counts as one PDF Process regardless of the number of operations in its chain; a Stirling Agent artifact counts as one regardless of the number of messages that produced it; failed processes (those that do not complete) are not counted; reprocessing the same file and duplicate submissions are counted; counts are whole numbers (no rounding). The Processor's audit log records each PDF Process and is the system of record, subject to Section 3.7. Provider will make a per-file usage statement (file identifier, size, processes, drawdown) available for audit.
+
+**Worked example.** At the Governed posture, a commitment of 90,000,000 PDFs/year provides a drawdown allowance of 360,000,000 PDF Processes. A 60 MB file that runs the four Governed policies draws down 4 PDF Processes plus 2 Data Processing increments (Section 3.5) = 6 PDF Processes. The allowance is a purchased quantity, not a feature limit: Customer may run any number of policies or pipelines; actual consumption simply draws the allowance down faster, and consumption beyond it bills as Overage (Section 3.4).
+
+3.4 **Overage.** Consumption beyond the Committed Volume in a contract year is billed quarterly in arrears at the committed rate stated in the Order Form. Overage does not increase subsequent years' Committed Volume.
+
+3.5 **Data Processing.** Each file includes its first twenty-five (25) megabytes (decimal, 1 MB = 1,000,000 bytes) at no additional drawdown. Each additional twenty-five (25) megabytes or part thereof (rounded up per file) draws down one (1) additional PDF Process. File size is measured once per file at ingestion, on the file as submitted. This schedule is stated here in full, is frozen for the Term, and is not subject to alteration through the Documentation.
+
+3.6 **No refunds.** Except as expressly stated (Sections 7.1, 7.3, 10.3, and DPA Section C5), fees are non-refundable and Committed Volume does not roll over between contract years.
+
+3.7 **Billing disputes.** Customer may dispute any invoice or metering record in good faith within sixty (60) days of the invoice date. Provider will investigate promptly, provide the relevant audit-log extracts and usage statements, and correct confirmed errors by credit or refund. The audit log is presumptively accurate but not conclusive; Customer may rebut it with reasonable evidence. Undisputed amounts remain payable when due.
+
+### 4. Data Protection
+
+4.1 The Data Processing Addendum at Part C (the "DPA") is incorporated into this Agreement and governs Provider's processing of Customer Personal Data, in compliance with the GDPR, UK GDPR, and CCPA/CPRA to the extent applicable.
+
+4.2 **Zero-standing-access.** Customer file content is encrypted in transit and at rest. Provider personnel have no standing access to Customer file content; access is granted just-in-time under audited elevation, solely as necessary to provide the Services or as instructed by Customer. Document metadata is maintained to operate the governed record. Where the Order Form includes BYOK or HYOK key management, the key terms in the Documentation apply.
+
+### 5. Security & Availability
+
+5.1 **Security program.** Provider maintains a written information security program including access controls, encryption (TLS 1.2+ in transit, AES-256 at rest), audit logging, vulnerability management, and personnel security. Provider will provide its available security documentation (including its security program overview and penetration-test attestation) upon request under confidentiality.
+
+5.2 **Availability.** For Stirling Cloud deployments, Provider targets 99.9% monthly uptime, excluding scheduled maintenance announced at least 48 hours in advance. The uptime figure is a target, not a credited commitment, and no service credits apply. Support response commitments for the {{sla_tier}} tier are set out in the SLA Exhibit referenced by the Order Form.
+
+5.3 **Breach notice.** Provider will notify Customer without undue delay after becoming aware of a Personal Data Breach affecting Customer Personal Data, and in any event within forty-eight (48) hours of awareness. Provider may provide information in phases as it becomes available and will supplement its notice as investigation proceeds.
+
+5.4 **Updates.** Provider will make security patches and product upgrades available to Customer at no additional charge for supported versions.
+
+### 6. Confidentiality
+
+6.1 Each Party shall protect the other's Confidential Information with at least the care it uses for its own similar information and no less than reasonable care, use it solely to perform under this Agreement, and disclose it only to personnel and advisors with a need to know who are bound by confidentiality obligations at least as protective. Confidential Information excludes information that is public without breach, independently developed, or rightfully received from a third party.
+
+6.2 Compelled disclosure is permitted with prompt notice (where lawful) and reasonable cooperation to seek protective treatment.
+
+6.3 Obligations survive three (3) years after termination; trade secrets survive as long as they remain trade secrets.
+
+### 7. Warranties & Indemnification
+
+7.1 **Performance warranty.** Provider warrants the Services will perform materially in accordance with the Documentation. Customer's exclusive remedy for breach is re-performance or, if Provider cannot re-perform within thirty (30) days, termination of the affected Services and a pro-rata refund of prepaid, unused fees for those Services.
+
+7.2 **Mutual warranties.** Each Party warrants it has the authority to enter this Agreement and will comply with applicable law in its performance.
+
+7.3 **IP indemnification.** Provider shall defend Customer against third-party claims that the Services, as provided and used per this Agreement, infringe a copyright or trademark or misappropriate a trade secret, and shall indemnify Customer for resulting damages finally awarded or agreed in settlement. Where **Enhanced IP Protection** is elected on the Order Form, this obligation extends to patent claims and carries the enhanced cap stated in Section 8.2. Exclusions: combinations with non-Provider materials, Customer content, modifications not made by Provider, and use after notice to stop. Provider may procure rights, modify, or replace the Services; if none is practicable, Provider may terminate the affected Services and refund prepaid, unused fees. This section states Customer's exclusive remedy for IP claims.
+
+7.4 **Customer indemnification.** Customer shall defend and indemnify Provider against third-party claims arising from Customer content, Customer's breach of Section 1.4, or Customer's violation of law.
+
+7.5 **Disclaimer.** EXCEPT AS EXPRESSLY STATED, THE SERVICES ARE PROVIDED WITHOUT OTHER WARRANTIES, EXPRESS OR IMPLIED, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. AI-ASSISTED OUTPUTS (INCLUDING CLASSIFICATION, EXTRACTION, AND AGENT ARTIFACTS) ARE PROBABILISTIC; CUSTOMER IS RESPONSIBLE FOR HUMAN REVIEW WHERE OUTPUTS HAVE LEGAL OR REGULATORY EFFECT.
+
+### 8. Limitation of Liability
+
+8.1 NEITHER PARTY IS LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR LOST PROFITS OR REVENUE.
+
+8.2 **General cap.** EACH PARTY'S AGGREGATE LIABILITY IS CAPPED AT THE FEES PAID OR PAYABLE UNDER THIS AGREEMENT IN THE TWELVE (12) MONTHS PRECEDING THE FIRST EVENT GIVING RISE TO LIABILITY. **Super-cap:** for breaches of Section 6 (Confidentiality), breaches of the DPA or Section 4–5 security obligations, and IP indemnification under Section 7.3, the cap is TWO TIMES (2x) such fees. **Uncapped:** fraud, willful misconduct, Customer's payment obligations, and Customer's indemnification under Section 7.4 for claims arising from Customer's willful violation of law.
+
+8.3 All claims arising from the same event or series of connected events count as a single claim for the purposes of the caps in Section 8.2.
+
+### 9. General
+
+9.1 **Entire agreement; precedence.** This Agreement (Parts A–C, the Order Form, the SLA Exhibit, and the Standard Contractual Clauses where applicable) is the entire agreement and supersedes prior proposals and quotes, including {{quote_ref}}. Only the following provisions of the Stirling EULA & Commercial Terms are incorporated: Section 3 (Definitions), Section 8 (AI features), Section 10 (Self-hosted and desktop software), and Section 11 (Fair use). The website Terms of Service do not apply to this Agreement; without limitation, their arbitration and class-waiver provisions, online auto-renewal rules, unilateral-amendment provision, self-serve pricing, and clickwrap acceptance mechanism are expressly excluded. Precedence: Order Form → Standard Contractual Clauses (for international transfers) → DPA → MSA → SLA Exhibit → incorporated EULA sections → Documentation.
+
+9.2 **Governing law; venue.** Delaware law, excluding conflicts rules. Exclusive jurisdiction and venue in the state or federal courts located in San Francisco County, California, and the Parties consent to personal jurisdiction there.
+
+9.3 **Assignment.** Neither Party may assign without the other's consent, except to a successor in a merger, acquisition, or sale of substantially all assets, with notice.
+
+9.4 **Notices.** Written notices to the addresses on the Order Form; email permitted with confirmation of receipt.
+
+9.5 **Force majeure; independent contractors; waiver; severability.** Standard terms apply: neither Party is liable for delay caused by events beyond reasonable control; the Parties are independent contractors; failure to enforce is not waiver; unenforceable provisions are severed with the remainder in effect.
+
+9.6 **Publicity.** Neither Party may use the other's name or marks publicly without prior written consent, except Provider may identify Customer as a customer with Customer's prior approval of the specific use.
+
+9.7 **Suspension.** Provider may suspend the Services for material breach that threatens the security or integrity of the Services, with notice and opportunity to cure where practicable. Undisputed unpaid fees more than thirty (30) days late are grounds for suspension after ten (10) days' notice.
+
+### 10. Termination
+
+10.1 Either Party may terminate for material breach uncured thirty (30) days after written notice, or immediately upon the other's insolvency.
+
+10.2 On termination: Customer's access ends (self-hosted licenses expire per the license mechanism); each Party returns or destroys the other's Confidential Information; the DPA's deletion terms govern Customer Personal Data; Sections 3 (accrued fees), 6, 7, 8, 9, and 10 survive.
+
+10.3 If Customer terminates for Provider's uncured material breach, Provider refunds prepaid fees for the unused remainder of the then-current contract year.
diff --git a/app/saas/src/main/resources/legal/eula/1.0.0/eula.md b/app/saas/src/main/resources/legal/eula/1.0.0/eula.md
new file mode 100644
index 0000000000..f6dd32d5e1
--- /dev/null
+++ b/app/saas/src/main/resources/legal/eula/1.0.0/eula.md
@@ -0,0 +1,75 @@
+# Stirling EULA & Commercial Terms
+
+This document fills the EULA slot the website Terms of Service §5 already contemplates ("If a separate end-user license (EULA) accompanies software, that license governs to the extent of any conflict"). It carries the commercial terms of the actual product: the PDF Process meter, spend limits, prepaid capacity, the free allotment, trials, self-hosted licensing, and AI features. For customers under a signed Stirling Enterprise Agreement, that agreement controls.
+
+**Effective:** {{version_date}} · **Version:** {{version}}
+
+## 1. Agreement; precedence
+
+These EULA & Commercial Terms ("EULA") supplement the Stirling Terms of Service (stirling.com/legal/terms-of-service). If they conflict, this EULA controls for the software and the commercial terms below. Open-source components are governed by their own licenses, which control for those components. By clicking accept, creating a workspace, or using the software, you agree on behalf of yourself and, if applicable, the organization you represent ("you").
+
+## 2. The products
+
+**The Stirling PDF Editor** is free: manual editing, the tool catalog, and team administration (including SSO) carry no subscription fee or per-seat charge, whether used in the browser, as a desktop application, or self-hosted. Usage limits on automated processing, fair-use rules (Section 11), support levels, and the feature set may change over time, and third-party costs (such as your own hosting) are yours. The Editor's open-source components remain available under their own licenses independently of this EULA. **The Stirling PDF Processor** is the paid platform that processes PDFs automatically — policies, pipelines, the Stirling Agent, and API processing — billed on the meter below.
+
+## 3. Definitions
+
+**"PDF Process"** — one policy execution, one pipeline run (regardless of the number of operations in its chain), or one Stirling Agent returned artifact (a processed file or summary, regardless of the number of messages that produced it), applied to one file. **"Data Processing"** — the data-volume component of the meter: files carry their first 25 MB included per file; volume past that is billed per Section 4. **"file"** — a document processed by the Processor. Chatting with the Stirling Agent is free; only returned artifacts meter.
+
+## 4. Metered billing (pay as you go)
+
+4.1 **Rates.** 1¢ per PDF Process, plus Data Processing at 1¢ per 25 MB increment past the first 25 MB of each file. Megabytes are decimal (1 MB = 1,000,000 bytes); size is measured once per file as submitted; increments round up ("part thereof" counts — a 26 MB file incurs one Data Processing increment, a 60 MB file incurs two). Rates may change on thirty (30) days' notice; changes apply prospectively. **Example:** two policies on a 3 MB contract = 2¢; two policies on a 60 MB scan set = 2¢ + 2¢ data = 4¢.
+
+4.2 **Free allotment.** New workspaces receive a one-time allotment of 500 PDF Processes. A file processed by two processes consumes two of the 500. When the allotment is exhausted, processing pauses until the Processor is switched on.
+
+4.3 **Invoices.** Usage is invoiced monthly on the 1st for the prior cycle, charged to your payment method on file (card or ACH debit). You authorize these charges.
+
+4.4 **Usage records.** The Processor's audit log is the system of record, subject to Section 4.5. Your Usage & Billing page shows consumption, and a per-file usage statement (name, size, processes, charge) is available for download.
+
+4.5 **Billing disputes.** You may dispute a charge or metering record in good faith within sixty (60) days of the invoice or charge date. We will investigate, provide the relevant usage-statement detail, and correct confirmed errors by credit or refund. The audit log is presumptively accurate but not conclusive; reasonable contrary evidence will be considered. Undisputed amounts remain payable.
+
+## 5. Spend limits
+
+5.1 You may set a monthly spend limit. By default, processing pauses when usage reaches the limit; queued documents resume when you raise the limit or the cycle resets. Nothing already processed is lost.
+
+5.2 If you enable **keep-processing** ("Keep processing if you hit your limit"), usage past the limit continues to accrue and be billed per Section 4; the limit then functions as a notification threshold. You can change the limit or the toggle at any time in Usage & Billing.
+
+## 6. Cancellation; downgrade
+
+You may revert to the free Editor plan at any time from Usage & Billing. Accrued usage remains payable. Your policies, configuration, and history are retained per the Terms of Service data-retention practices.
+
+## 7. Prepaid capacity (self-serve annual)
+
+7.1 **Offer.** You may prepay twelve (12) months of processing capacity for the price of ten (10) (the "12-for-10 rate"), sized at purchase. Payment by card, or by bank transfer against a generated invoice (net 30); prepaid capacity activates when payment clears.
+
+7.2 **No renewal of prepaid capacity; automatic transition to pay-as-you-go.** Prepaid capacity does not renew for another prepaid term. At purchase, you affirmatively consent to the following transition, which is disclosed before you pay: when the term ends, metered billing (Section 4) applies automatically at then-current rates so processing does not pause. We remind you thirty (30) days before term end; the reminder states the metered rates that will apply and how to cancel or revert to the free Editor plan (one click in Usage & Billing).
+
+7.3 **Consumption; overage; expiry.** Capacity draws down in PDF Processes. If you exhaust capacity mid-term, you may top up at the same 12-for-10 rate, or metered billing applies at list rates (with a card on file) or processing pauses (without one). Unused capacity expires at term end and is not refunded and does not roll over.
+
+7.4 **Cap.** Self-serve prepaid capacity is limited to 1,000,000 PDF Processes per year; larger commitments are available under a Stirling Enterprise Agreement.
+
+## 8. AI features
+
+AI features — classification, extraction, redaction-assist, and the Stirling Agent — are optional. They run only when you invoke a feature that uses them, and an administrator can disable them for the workspace; the rest of the Processor works without them. When used, they call machine-learning models from the providers listed at {{subprocessor_url}}. Currently: **Anthropic** (Claude models), which receives prompts and the document text or excerpts needed to perform the requested task; and **Voyage AI** (embedding models), which receives extracted text excerpts solely to generate embeddings when you enable Ingestion/RAG features. Only the document text or excerpts needed for the requested feature are sent — not your whole files — and only when that feature runs. AI charges are included in the price of whatever runs — there is no separate AI surcharge. Your content is not used to train models, by us or by these providers (verified against our signed provider agreements). AI outputs are probabilistic; review outputs before relying on them where accuracy has legal effect.
+
+## 9. Evaluations and trials
+
+Enterprise trials run fourteen (14) days, require no payment method, and are provided for evaluation only, AS IS, without service level commitments. Either party may end an evaluation at any time; on expiry your workspace continues on the free Editor plan.
+
+## 10. Self-hosted and desktop software
+
+10.1 **License.** We grant you a non-exclusive, non-transferable license to install and run the Editor and, with an active plan, the self-hosted Processor, for your internal business use. Open-source components remain under their own licenses.
+
+10.2 **License validation and metering.** Self-hosted Processor deployments validate their license online and transmit usage metering data (process counts, file sizes, and file hashes for billing integrity, and diagnostic data — never file content or file names) to Stirling. File names used for unique PDF identification remain on your server and are not transmitted. Air-gapped deployments verify a signed activation bundle offline and reconcile usage periodically. You will not disable, circumvent, or falsify validation or metering. **The meter is the same regardless of where the software runs.**
+
+10.3 **Updates.** Security patches and upgrades are made available for supported versions; some updates may install automatically per Terms of Service §5.
+
+10.4 **Authorized users and administration.** "Authorized Users" are your employees, and the employees of your affiliates and contractors working on your behalf, whom you provision through your workspace. You are responsible for your users' credentials, your administrators' actions, and your users' compliance with this EULA. One workspace serves one legal entity and its affiliates; serving unrelated third parties requires a separate agreement. You may not redistribute the Processor or offer it as a hosted service to others. On termination or downgrade, self-hosted Processor licenses expire per the license mechanism; installed Editor copies remain usable under the free plan. We may verify license compliance through the validation mechanism in Section 10.2.
+
+## 11. Fair use
+
+Free-tier and flat-price features are subject to fair use: we may throttle or decline usage patterns that abuse free processing (for example, automation disguised as manual editing) after notice where practicable.
+
+## 12. Changes to this EULA
+
+We may update this EULA. Material changes take effect thirty (30) days after notice. Changes that materially increase your price or reduce your rights take effect at your next billing cycle or prepaid term start, or upon your affirmative acceptance — whichever comes first — except changes strictly necessary for legal compliance or security, which may take effect sooner with notice. Continued use after the effective date is acceptance. Version history is available at {{eula_url}}.
diff --git a/app/saas/src/main/resources/legal/manifest.json b/app/saas/src/main/resources/legal/manifest.json
new file mode 100644
index 0000000000..c34559275d
--- /dev/null
+++ b/app/saas/src/main/resources/legal/manifest.json
@@ -0,0 +1,38 @@
+{
+ "subprocessorUrl": "https://www.stirlingpdf.com/legal/subprocessors",
+ "eulaUrl": "https://www.stirlingpdf.com/legal/eula",
+ "documents": {
+ "enterprise-agreement": {
+ "label": "SEA",
+ "displayName": "Stirling Enterprise Agreement",
+ "version": "0.9.1",
+ "effectiveDate": "2026-07-10",
+ "status": "draft",
+ "parts": ["msa.md", "@order-form", "dpa.md"]
+ },
+ "eula": {
+ "label": "EULA",
+ "displayName": "Stirling EULA & Commercial Terms",
+ "version": "1.0.0",
+ "effectiveDate": "2026-07-10",
+ "status": "draft",
+ "parts": ["eula.md"]
+ },
+ "sla": {
+ "label": "SLA",
+ "displayName": "Stirling SLA Exhibit",
+ "version": "1.0.0",
+ "effectiveDate": "2026-07-10",
+ "status": "draft",
+ "parts": ["sla.md"]
+ },
+ "subprocessors": {
+ "label": "SUBP",
+ "displayName": "Stirling Subprocessors",
+ "version": "1.0.0",
+ "effectiveDate": "2026-07-10",
+ "status": "draft",
+ "parts": ["subprocessors.md"]
+ }
+ }
+}
diff --git a/app/saas/src/main/resources/legal/sla/1.0.0/sla.md b/app/saas/src/main/resources/legal/sla/1.0.0/sla.md
new file mode 100644
index 0000000000..42271171d5
--- /dev/null
+++ b/app/saas/src/main/resources/legal/sla/1.0.0/sla.md
@@ -0,0 +1,37 @@
+# SLA Exhibit — Stirling Enterprise Agreement
+
+Referenced by the Order Form's service-level row and MSA §5.2. One document, three tiers; the Order Form's tier selection determines the applicable column. Uptime is a target, not a credited commitment: no service credits apply at any tier. Tiers differentiate support response, channels, and people.
+
+## 1. Availability
+
+For Stirling Cloud deployments, Provider targets **99.9% monthly uptime**, measured at the API and console endpoints, excluding scheduled maintenance announced at least 48 hours in advance and events beyond Provider's reasonable control. Current and historical status is published at the system status page. No service credits apply; persistent material failure to meet the target is addressed through MSA §7.1 (performance warranty and remedies) and §10 (termination for material breach).
+
+Self-hosted and Air-gapped deployments: availability of the runtime is Customer's responsibility; this Section applies to Provider's license, metering, and update services.
+
+## 2. Support tiers
+
+| | **Standard** | **Priority** | **Dedicated** |
+| --- | --- | --- | --- |
+| Included with | Every Enterprise Agreement | Every Enterprise Agreement | The Dedicated SE/CSM line item ($30,000/yr) |
+| Hours | Business hours (Mon–Fri, 9:00–18:00 US Eastern, excl. US holidays) | Business hours + extended (7:00–21:00 US Eastern) | 24×7 for Severity 1 |
+| Channels | Email, in-product | Email, in-product, private Slack/Teams channel | All Priority channels + named Solutions Engineer and CSM |
+| Severity 1 first response (production down / processing halted org-wide) | 8 business hours | 4 hours | 1 hour, 24×7 |
+| Severity 2 (major feature degraded, no workaround) | Next business day | 8 business hours | 4 hours |
+| Severity 3 (minor defect, workaround exists) | 3 business days | 2 business days | Next business day |
+| Severity 4 (question, cosmetic) | 5 business days | 3 business days | 2 business days |
+| Escalation path | Support queue | Support lead | Named SE → CSM → Provider executive |
+| Business reviews | — | — | Quarterly, where the QBR line item is elected |
+
+First response = a qualified human engaging with the issue, not an acknowledgment autoresponder. Resolution times are not committed; Provider works Severity 1 issues continuously within the tier's hours until resolved or downgraded.
+
+## 3. Severity is set by Customer, subject to reasonable reclassification
+
+Customer designates severity at filing; Provider may reclassify with explanation. Severity 1 requires production impact in a live (non-evaluation) environment.
+
+## 4. Maintenance and updates
+
+Scheduled maintenance is announced at least 48 hours ahead and targeted at low-usage windows. Security patches for supported versions ship to all tiers at no charge (MSA §5.4). Trials and evaluations are provided AS IS and are outside this Exhibit (EULA §9).
+
+## 5. Exclusions
+
+This Exhibit does not apply to: issues caused by Customer's environment, modifications, or third-party systems; usage exceeding the fair-use provisions; Preview/Beta features; or Force Majeure events (MSA §9.5).
diff --git a/app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md b/app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md
new file mode 100644
index 0000000000..670ae53150
--- /dev/null
+++ b/app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md
@@ -0,0 +1,19 @@
+# Stirling PDF — Subprocessors
+
+Referenced by DPA §C5 and Annex III, and by EULA §8. Changes to this list carry 30 days' notice per DPA §C5. Last updated: {{version_date}}.
+
+Stirling PDF, Inc. uses the following subprocessors to provide the Services. Customer files are processed within Stirling's own infrastructure. AI features are optional and can be disabled; where they are used, AI providers receive only the document text or excerpts needed for the requested feature, never whole customer files.
+
+| Subprocessor | Purpose | Data processed | Location |
+| --- | --- | --- | --- |
+| **Amazon Web Services (AWS)** | Cloud infrastructure and storage for Stirling Cloud | Customer files (encrypted at rest), account and usage data | United States (EU region availability per deployment — see DPA §C8 note) |
+| **Stripe** | Payment processing | Billing contact and transaction data. Payment card details go directly to Stripe, which acts as an independent controller for them | United States |
+| **Supabase** | Account and workspace data infrastructure | Account, workspace, and configuration data | United States |
+| **Google** | Transactional and operational email delivery | Names, email addresses, message content of service emails | United States |
+| **Anthropic** | AI models (Claude) powering the Stirling Agent and AI-assisted features | Prompts and the document text or excerpts needed for the requested feature — never whole files; only where AI features are used | United States |
+| **Voyage AI** | Embedding models for Ingestion/RAG features | Extracted text excerpts, only where the customer enables Ingestion/RAG, solely to generate embeddings — never customer files | United States |
+| **PostHog** | Product telemetry and usage analytics | Pseudonymous usage events and diagnostic data — never file content | European Union (EU-hosted) |
+
+Neither AI provider uses customer data for model training (contractually confirmed).
+
+Self-hosted and air-gapped deployments: customer files remain in the customer's environment; Stirling receives license-validation and metering data only (process counts, file sizes, file hashes — never file names or content).
diff --git a/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java b/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java
new file mode 100644
index 0000000000..86f361ff87
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java
@@ -0,0 +1,44 @@
+package stirling.software.saas.procurement.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import stirling.software.saas.procurement.model.ProcurementDeal;
+
+/**
+ * Which stages may (re)start a trial is a security policy, not a convenience.
+ *
+ *
From the agreement stage onward a deal's {@code licenseRef} points at the committed annual
+ * licence. Starting a trial replaces it with a fresh 14-day key, rewinds the stage and resets the
+ * extension counter — so an unguarded restart would downgrade a paying customer's entitlement while
+ * Stripe kept billing them. This pins the allowed set so widening it has to be deliberate.
+ */
+class ProcurementTrialRestartPolicyTest {
+
+ @Test
+ @DisplayName("allowed before a deal exists, while exploring, and within the trial")
+ void allowsOnlyPreCommitmentStages() {
+ assertThat(ProcurementService.canStartTrial(null)).isTrue();
+ assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_EXPLORING)).isTrue();
+ assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_TRIAL)).isTrue();
+ }
+
+ @Test
+ @DisplayName("refused once the deal is quoting or beyond")
+ void refusesCommittedStages() {
+ assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_QUOTE)).isFalse();
+ assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_AGREEMENT)).isFalse();
+ assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_PAYMENT)).isFalse();
+ assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_LIVE)).isFalse();
+ }
+
+ @Test
+ @DisplayName("an unrecognised stage is refused, not waved through")
+ void refusesUnknownStages() {
+ // A stage added later, or a hand-edited row, must fail closed.
+ assertThat(ProcurementService.canStartTrial("renewal")).isFalse();
+ assertThat(ProcurementService.canStartTrial("")).isFalse();
+ }
+}
diff --git a/frontend/.storybook/a11y-baseline.json b/frontend/.storybook/a11y-baseline.json
index 10fc530c77..a31d84613b 100644
--- a/frontend/.storybook/a11y-baseline.json
+++ b/frontend/.storybook/a11y-baseline.json
@@ -1707,6 +1707,9 @@
"editor/src/portal/components/billing/InvoicesList.stories.tsx :: Default": [
"color-contrast"
],
+ "editor/src/portal/components/billing/LinkAccountPrompt.stories.tsx :: Default": [
+ "color-contrast"
+ ],
"editor/src/portal/components/billing/PrepaidCapacityCard.stories.tsx :: Bundle Healthy": [
"aria-progressbar-name",
"color-contrast"
@@ -2107,22 +2110,15 @@
"color-contrast"
],
"editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: License": [
- "aria-dialog-name"
+ "color-contrast"
],
"editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: License Trial": [
- "aria-dialog-name"
- ],
- "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Schedule Call": [
- "aria-dialog-name"
+ "color-contrast"
],
"editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Trial Manage": [
- "aria-dialog-name"
- ],
- "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Trial Manage Maxed": [
- "aria-dialog-name"
+ "color-contrast"
],
"editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Trial Setup": [
- "aria-dialog-name",
"color-contrast"
],
"editor/src/portal/components/procurement/ProcurementFlow.stories.tsx :: Default": [
@@ -2135,6 +2131,9 @@
"editor/src/portal/components/procurement/ProcurementHome.stories.tsx :: Default": [
"color-contrast"
],
+ "editor/src/portal/components/procurement/ProcurementModal.stories.tsx :: Open": [
+ "color-contrast"
+ ],
"editor/src/portal/components/procurement/ProcurementStages.stories.tsx :: License": [
"color-contrast"
],
@@ -2144,6 +2143,9 @@
"editor/src/portal/components/procurement/ProcurementStages.stories.tsx :: License Online Only": [
"color-contrast"
],
+ "editor/src/portal/components/procurement/ProcurementStages.stories.tsx :: Payment": [
+ "color-contrast"
+ ],
"editor/src/portal/components/procurement/QuoteBuilder.stories.tsx :: Default": [
"color-contrast"
],
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index bf00cfd08d..33cf0ee8e1 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7331,13 +7331,16 @@ tagline = "Native app for Microsoft Windows"
title = "Windows"
[portal.home.editor]
-activeUsers = "{{n}} active"
-install = "Install the editor"
-invite = "Invite teammates"
-name = "Stirling PDF Editor"
+activeOfDeployed = "{{active}} of {{total}} active this month"
+name = "PDF Editor"
open = "Open in browser"
updated = "updated {{time}}"
+[portal.home.editor.deploy]
+finish = "Finish deployment"
+options = "View deployment options"
+start = "Deploy the Editor"
+
[portal.home.editor.target]
cloud = "Managed Cloud"
docker = "Self-hosted · Docker"
@@ -7348,25 +7351,6 @@ afternoon = "Good afternoon"
evening = "Good evening"
morning = "Good morning"
-[portal.home.onboarding.enterprise]
-body = "Org-wide SSO + SCIM + RBAC, committed volume pricing, and air-gapped deployment."
-cta = "Start Trial"
-ctaQuote = "Get Quote"
-lead = "For 250+ employees."
-tag = "Enterprise"
-
-[portal.home.onboarding.steps.editor]
-blurb = "Install the desktop app or self-host"
-title = "Download the editor"
-
-[portal.home.onboarding.steps.invite]
-blurb = "Bring your team into the secure workspace"
-title = "Invite teammates"
-
-[portal.home.onboarding.steps.policies]
-blurb = "{{active}} active · {{recommended}} recommended"
-title = "Confirm your policies"
-
[portal.infrastructure]
manageEditorDeployment = "Manage Editor deployment"
sectionsAriaLabel = "Infrastructure sections"
@@ -7767,6 +7751,12 @@ pipelines = "Pipelines"
policies = "Policies"
sources = "Sources"
+[portal.legal]
+draft = "{{label}} · draft"
+loadError = "Could not load this document. Please try again."
+loading = "Loading…"
+title = "Legal document"
+
[portal.nav]
agent-builder = "Agent Builder"
components = "Components"
@@ -8430,19 +8420,27 @@ email = "Email intake"
subtitle = "Get your team evaluated, contracted, and onboarded. Every document in one place."
title = "Procurement"
-[portal.procurement.action]
-download = "Download"
-pay = "Pay now"
-request = "Request"
-sign = "Review & sign"
-upload = "Upload"
-
[portal.procurement.agreement]
-agreeCta = "Agree & subscribe"
-confirm = "I have read and agree to the Stirling Enterprise Agreement."
-eyebrow = "Agreement"
-intro = "One combined agreement covers your deal: Master Service Agreement, Order Form, EULA, and Data Processing Agreement. Review it, then agree to accept the quote into a committed subscription."
-title = "Review your enterprise agreement"
+agreeCta = "Sign agreement"
+confidential = "Confidential"
+confirm = "I have read and agree to this Agreement, and I represent that I am authorized to sign it on behalf of the organization named above."
+docName = "Stirling Enterprise Agreement"
+docSub = "MSA, Order Form, EULA and DPA, combined into one signature."
+download = "Download"
+downloadDraftError = "Could not generate the agreement PDF - the document renderer is unavailable. Please try again shortly or contact support."
+downloadError = "Could not download the signed agreement. Please try again."
+legalName = "Legal entity name"
+legalNamePlaceholder = "The legal entity that will sign"
+loadError = "Could not load the agreement. Please try again."
+loading = "Loading the agreement..."
+ref = "Ref {{ref}} · {{version}}"
+requestChanges = "Request changes"
+scrollHint = "Scroll to review"
+signatory = "Signatory name"
+signatoryPlaceholder = "Full name"
+signatoryTitle = "Signatory title"
+signatoryTitlePlaceholder = "e.g. General Counsel"
+signError = "Could not record your signature. Please try again."
[portal.procurement.builder]
addons = "Add-ons"
@@ -8455,16 +8453,19 @@ businessName = "Business name"
businessNamePlaceholder = "Your company"
city = "City"
cityPlaceholder = "San Francisco"
+completeRequired = "Please complete the required fields (marked *) with a valid email before generating the quote."
contactEmail = "Contact email"
contactEmailPlaceholder = "jane@acme.com"
contactName = "Contact name"
contactNamePlaceholder = "Jane Doe"
continue = "Continue"
+done = "Done"
eula = "I have read and agree to the Stirling Enterprise EULA. It governs the agreement generated from this quote."
generate = "Generate quote"
-included = "Included"
-indemnification = "IP indemnification"
-indemnificationSub = "We defend qualifying IP claims, per the EULA"
+indemnification = "Enhanced IP Protection"
+indemnificationSub = "Extends our IP defense to patent claims. Baseline copyright, trademark and trade-secret indemnification is included free."
+paperEyebrow = "Enterprise quote"
+paperFor = "Prepared for"
pdfSize = "PDF size"
poNumber = "PO number"
poNumberPlaceholder = "Optional"
@@ -8512,6 +8513,7 @@ training = "Onboarding & training"
trainingSub = "Live sessions to get your team running"
users = "Total users"
usersPlaceholder = "e.g. 250"
+viewEula = "Read it"
volEstimated = "Estimated from {{count}} users (~2,000 PDFs each, including automation). Edit if you know better."
volManual = "Using your figure. Re-estimate from your team size any time."
volNoUsers = "Not sure? Enter your team size and we'll estimate it."
@@ -8520,54 +8522,55 @@ volumePlaceholder = "e.g. 1,000,000"
years_one = "{{count}} year"
years_other = "{{count}} years"
-[portal.procurement.docs]
-count_one = "{{count}} doc"
-count_other = "{{count}} docs"
-done = "Done"
-here = "You're here"
-hide = "Hide"
-optional = "Optional"
-paidAddon = "Paid add-on"
-show = "Show"
-subtitle = "Everything you need at each step of the journey, surfaced as the deal moves through it."
-supportingSubtitle = "SOC 2, security reviews, tax forms and more, ready when your security or procurement team asks. Some carry a one-time fee."
-supportingTitle = "Supporting your evaluation"
+[portal.procurement.documents]
+agreement = "Enterprise Agreement"
+agreementSub = "MSA, Order Form and DPA in one signature."
+download = "Download"
+eula = "EULA & Commercial Terms"
+eulaSub = "The software and self-serve commercial terms."
+invoice = "Invoice"
+invoiceSub = "Your first subscription invoice."
+laterInvoice = "Available after you accept"
+laterQuote = "Available once your quote is issued"
+quote = "Quote"
+quoteSub = "Your itemised enterprise quote."
+sla = "SLA Exhibit"
+slaSub = "Support tiers and response targets."
+subprocessors = "Subprocessors"
+subprocessorsSub = "Third parties that process data on your behalf."
+subtitle = "Your deal paperwork, available any time."
title = "Documents"
-upcoming = "Upcoming"
+view = "View"
[portal.procurement.error]
title = "Something went wrong"
[portal.procurement.hero]
-company = "Your enterprise deal"
-ctaLive = "You're live"
-ctaPayment = "Add payment"
+barAria = "Stage {{current}} of {{total}}"
+ctaAgreement = "Review & sign agreement"
+ctaExploring = "Set up your trial"
ctaQuote = "Review your quote"
+ctaReviewQuote = "Review quote"
ctaTrial = "Build your quote"
-eyebrow = "Enterprise procurement"
+documents = "Documents"
+eyebrow = "Enterprise"
+eyebrowCompany = "{{company}} Enterprise"
inviteTeammates = "Invite teammates"
licenseKey = "Licence key"
-nextStep = "Next step: {{action}}"
-notStarted = "Not started"
+liveSub = "Your organization is provisioned and your licence is active."
+liveTitle = "You are live on Stirling Enterprise"
+next = "Next: {{stage}}"
open = "Open procurement"
scheduleCall = "Schedule a call"
-setup1Sub = "Invite your teammates"
-setup1Title = "Deploy the PDF Editor"
-setup2Sub = "Turn on processing across editors and other sources"
-setup2Title = "Connect the PDF Processor"
-setup3Sub = "Turn on Security, Compliance, Routing, or Retention when you need them"
-setup3Title = "Add recommended policies"
+sentenceAgreement = "review and sign the agreement"
+sentenceLive = "provisioning and rollout"
+sentencePayment = "purchase order and payment"
+sentenceQuote = "review and accept your quote"
+sentenceTrial = "set up your trial workspace"
[portal.procurement.journey]
daysLeft_one = "{{count}} day left"
daysLeft_other = "{{count}} days left"
-engineerLabel = "Your solutions engineer"
-eyebrow = "Your rollout"
-live = "You're live on Stirling Enterprise"
-nextStep = "Next step: {{action}}"
-subtitle = "Your solutions engineer is on every step. One next action at a time; the full checklist is below."
-title = "From trial to live, one guided path"
-trialTitle = "Enterprise trial"
[portal.procurement.journeySteps.agreement]
blurb = "One signature covers MSA, order form, EULA and DPA."
@@ -8616,45 +8619,26 @@ description = "Your subscription is active and your licence is issued. Your team
eyebrow = "Live"
title = "You're live on Stirling Enterprise"
-[portal.procurement.locked]
-description = "Trial keys, committed-volume quotes, the one-signature agreement, payment, and your document ledger all live here once you start an enterprise evaluation."
-eyebrow = "Enterprise only"
-talkToSales = "Talk to sales"
-title = "The procurement track opens with Enterprise"
-
[portal.procurement.milestone]
-download = "Download PDF"
downloadError = "Could not download the quote PDF just yet — please try again in a moment."
-edit = "Edit quote"
-
-[portal.procurement.modal]
-cancel = "Cancel"
-chooseFile = "Choose file"
-close = "Close"
-downloadBody = "Your download will begin shortly."
-downloadCta = "Download"
-downloadTitle = "Download"
-noFile = "No file selected"
-payBody = "Pay your committed contract by card or bank transfer through Stripe. Your workspace provisions as soon as payment clears."
-payCta = "Continue to Stripe"
-payTitle = "Confirm payment"
-requestBodyFree = "We generate this on demand. Confirm and your solutions engineer will send it across shortly."
-requestBodyPaid = "This is a paid add-on. Confirm and your solutions engineer will scope it and send the paperwork."
-requestCta = "Request"
-requestTitle = "Request this document"
-signBody = "Opens the Stirling Enterprise Agreement for e-signature: one signature covers the MSA, order form, EULA and DPA. We countersign automatically and you advance to payment."
-signCta = "Open for signature"
-signTitle = "Review and sign your agreement"
-uploadBody = "Send us your PO and we invoice against it on your terms. Drag in the PDF or pick a file below."
-uploadCta = "Upload purchase order"
-uploadTitle = "Upload your purchase order"
[portal.procurement.payment]
description = "Your quote is accepted and your licence is already active — your team can start right away. Pay the first invoice when you're ready; you can pay or download it here, no email needed."
+downloadAgreement = "Download signed agreement"
downloadInvoice = "Download invoice"
+eyebrow = "Payment"
title = "Subscription created"
viewInvoice = "View & pay invoice"
+[portal.procurement.review]
+acceptCta = "Accept quote"
+annual = "Annual fee (year 1)"
+downloadCta = "Download quote"
+poNumber = "Purchase order: {{po}}"
+renewal = "Renews at {{amount}}/year after the term (+{{pct}}% CPI)"
+tcv = "{{years}}-year term, paid in full up front: {{tcv}}"
+validUntil = "Valid until {{date}}"
+
[portal.procurement.schedule]
fallback = "Couldn't load the scheduler."
fallbackLink = "Open scheduling in a new tab"
@@ -8664,25 +8648,33 @@ title = "Schedule a call"
[portal.procurement.setup]
airgap = "Air-gapped"
-airgapSub = "Fully offline, isolated network. Includes a downloadable licence file."
-cloud = "Cloud"
-cloudSub = "Fully managed by Stirling. Nothing for you to run."
-deployment = "Where will you run Stirling?"
-seats = "Team size"
-seatsHint = "Roughly how many people will use it. You can refine this when you build your quote."
-seatsPlaceholder = "e.g. 250"
+airgapSub = "Sealed, no outbound"
+back = "Back"
+businessName = "Business name"
+businessNamePlaceholder = "Acme Corp"
+cloud = "Stirling Cloud"
+cloudSub = "Managed, fastest start"
+continue = "Continue"
+deployment = "Where should it deploy?"
+eula = "I agree to the Stirling EULA & Commercial Terms."
+fullName = "Full name"
+fullNamePlaceholder = "Your name"
+invites = "Invite teammates · optional"
+invitesPlaceholder = "sam@acme.com, lee@acme.com"
+scheduleCall = "Schedule a call"
+seats = "People testing"
+seatsPlaceholder = "e.g. 15"
selfhost = "Self-hosted"
-selfhostSub = "Run it in your own cloud or data centre."
+selfhostSub = "Docker or Kubernetes"
start = "Start trial"
-subtitle = "Tell us how you plan to run Stirling so we can tailor your trial and quote. No card required."
+stepOf = "Step {{n}} of {{total}}"
+subtitle = "Free for 14 days, no card required."
+subtitleDetails = "A few details for your quote and agreement."
+talkFirst = "Prefer to talk first?"
title = "Set up your trial"
-
-[portal.procurement.status]
-action = "Action needed"
-available = "Available"
-complete = "Complete"
-pending = "Pending"
-request = "On request"
+viewEula = "Read it"
+workEmail = "Work email"
+workEmailPlaceholder = "you@company.com"
[portal.procurement.trial]
body = "Extending adds 7 days and notifies your solutions engineer."
@@ -8693,12 +8685,6 @@ maxed = "Maxed out"
subtitle = "Your free trial runs through {{date}}. No card required."
title = "Enterprise trial"
-[portal.procurement.upsell]
-homeBadge = "Enterprise"
-homeBody = "Committed volume pricing, org-wide SSO + SCIM + RBAC, 90-day immutable audit, and a dedicated SE."
-homeCta = "Start Trial →"
-homeHeadline = "Process millions of PDFs."
-
[portal.search]
ariaLabel = "Search"
placeholder = "Search Stirling — endpoints, pipelines, docs…"
@@ -8923,6 +8909,9 @@ name = "Name"
namePlaceholder = "e.g. Claims intake"
type = "Type"
+[portal.stepModal]
+close = "Close"
+
[portal.usage]
managePayment = "Manage Payment"
subtitle = "Consumption, invoices, and plan management for every PDF Stirling has billed, in one console."
@@ -8985,14 +8974,6 @@ summary = "Owns a team — manages its members' resources and shared configs."
limited = "{{used}} / {{limit}}"
unlimited = "{{used}} · Unlimited"
-[portal.welcome]
-ariaLabel = "Welcome to Stirling PDF"
-install = "Install the editor"
-invite = "Invite teammates"
-openInBrowser = "Open in browser"
-productName = "PDF Editor"
-stats = "30M downloads · 60+ PDF operations · Free forever"
-
[printFile]
title = "Print File"
diff --git a/frontend/editor/src/portal/ViewRouter.tsx b/frontend/editor/src/portal/ViewRouter.tsx
index 76adc1ad1d..8e77c20830 100644
--- a/frontend/editor/src/portal/ViewRouter.tsx
+++ b/frontend/editor/src/portal/ViewRouter.tsx
@@ -11,7 +11,6 @@ import { Policies } from "@portal/views/Policies";
import { EditorAdmin } from "@portal/views/EditorAdmin";
import { Infrastructure } from "@portal/views/Infrastructure";
import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";
-import { Procurement } from "@portal/views/Procurement";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
// Lazy so the generated docs manifest (bundled JSON) lands in its own chunk.
@@ -62,7 +61,6 @@ export function ViewRouter() {
element={}
/>
} />
- } />
null);
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("openApiUrl", () => {
+ it("opens an https URL in a new tab with noopener", () => {
+ const open = spyOpen();
+ openApiUrl("https://invoice.stripe.com/i/abc123");
+ expect(open).toHaveBeenCalledWith(
+ "https://invoice.stripe.com/i/abc123",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ });
+
+ it("opens a relative URL by resolving it against the origin", () => {
+ const open = spyOpen();
+ openApiUrl("/invoices/abc.pdf");
+ expect(open).toHaveBeenCalledWith(
+ `${window.location.origin}/invoices/abc.pdf`,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ });
+
+ // The reason this module exists: a navigation sink must not evaluate script.
+ it.each([
+ "javascript:alert(document.domain)",
+ "JavaScript:alert(1)",
+ "data:text/html,",
+ "vbscript:msgbox(1)",
+ "file:///etc/passwd",
+ ])("refuses %s", (hostile) => {
+ const open = spyOpen();
+ openApiUrl(hostile);
+ expect(open).not.toHaveBeenCalled();
+ });
+
+ it("does nothing for an empty or missing URL", () => {
+ const open = spyOpen();
+ openApiUrl(null);
+ openApiUrl(undefined);
+ openApiUrl("");
+ expect(open).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/portal/api/externalUrl.ts b/frontend/editor/src/portal/api/externalUrl.ts
new file mode 100644
index 0000000000..10919e1544
--- /dev/null
+++ b/frontend/editor/src/portal/api/externalUrl.ts
@@ -0,0 +1,25 @@
+/**
+ * Open a URL that arrived from the API — a Stripe hosted-invoice page or invoice
+ * PDF — in a new tab, after checking its scheme.
+ *
+ * These values are relayed from Stripe through our own edge functions, so they
+ * are not attacker-controlled today. But a `javascript:` or `data:` URL reaching
+ * a navigation sink is an XSS primitive, and nothing between Stripe and this call
+ * promises the field can only ever hold a web address. Anything that is not plain
+ * http(s) is dropped instead of opened.
+ */
+export function openApiUrl(url: string | null | undefined): void {
+ if (!url) return;
+ let parsed: URL;
+ try {
+ parsed = new URL(url, window.location.origin);
+ } catch {
+ console.warn("[portal] refusing to open an unparseable URL");
+ return;
+ }
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
+ console.warn(`[portal] refusing to open a ${parsed.protocol} URL`);
+ return;
+ }
+ window.open(parsed.href, "_blank", "noopener,noreferrer");
+}
diff --git a/frontend/editor/src/portal/api/procurement.ts b/frontend/editor/src/portal/api/procurement.ts
index 4d8a28e057..b49de2f6b6 100644
--- a/frontend/editor/src/portal/api/procurement.ts
+++ b/frontend/editor/src/portal/api/procurement.ts
@@ -1,12 +1,12 @@
import { apiClient } from "@portal/api/http";
+import { resolveDemoResponse } from "@portal/api/demoData";
+import { saasApiBase } from "@portal/api/saasApiBase";
import { getSupabaseClient } from "@app/auth/supabase/supabaseClient";
-import type { Tier } from "@portal/contexts/TierContext";
/*
- * Procurement models the enterprise commercial journey, trial → quote →
- * agreement → payment → implementation, plus the paperwork ledger that rides
- * alongside it. The journey is enterprise-only; free/pro tiers receive a
- * minimal locked payload the view renders as an upgrade prompt.
+ * Procurement models the enterprise commercial journey: trial → quote → agreement → payment →
+ * implementation. It is surfaced by the deal-status hero on Home and the takeover flow beside it;
+ * there is no separate procurement route.
*/
/* ──────────────────────────────────────────────────────────────────────── */
@@ -19,11 +19,8 @@ import type { Tier } from "@portal/contexts/TierContext";
* Payment read more plainly than the internal `security` / `procurement`).
*/
export type DealStage =
- | "trial"
- | "quote"
- | "security"
- | "procurement"
- | "active";
+ /** Asked about enterprise, nothing committed yet. Precedes the journey rather than joining it. */
+ "exploring" | "trial" | "quote" | "security" | "procurement" | "active";
export interface JourneyStep {
stage: DealStage;
@@ -38,9 +35,14 @@ export interface JourneyStep {
gatingAction: string;
}
-/** Ordered journey definition, the stepper renders this verbatim. */
-/** `label`/`blurb`/`gatingAction` values are i18n keys — render with t(). */
-export const JOURNEY: JourneyStep[] = [
+/**
+ * The commercial flow's stages, rendered verbatim as the hero's progress band. Quote and Agreement
+ * are distinct: the buyer accepts the quote first (no Stripe), then signs the agreement, which is
+ * what accepts into a committed subscription.
+ *
+ *
`label`/`blurb`/`gatingAction` are i18n keys — render with t().
+ */
+export const FLOW_JOURNEY: JourneyStep[] = [
{
stage: "trial",
label: "portal.procurement.journeySteps.trial.label",
@@ -73,204 +75,9 @@ export const JOURNEY: JourneyStep[] = [
},
];
-/**
- * The commercial flow's stepper stages. The real backend collapses quote + agreement into one
- * accept step (accepting the issued quote is accepting the agreement), so the flow shows one fewer
- * step than the mock ledger's {@link JOURNEY} — the separate "Agreement" step is dropped. Reuses
- * JOURNEY's i18n keys.
- */
-export const FLOW_JOURNEY: JourneyStep[] = JOURNEY.filter(
- (s) => s.stage !== "security",
-);
-
-/* ──────────────────────────────────────────────────────────────────────── */
-/* Deal header */
-/* ──────────────────────────────────────────────────────────────────────── */
-
-export interface SolutionsEngineer {
- name: string;
- title: string;
- email: string;
-}
-
-export interface TrialInfo {
- /** License key seeded for the evaluation. */
- key: string;
- /** ISO date the trial began. */
- startedOn: string;
- /** ISO date the trial expires. */
- endsOn: string;
- /** Whole days remaining (derived in the fixture for a stable demo number). */
- daysLeft: number;
- extensionsUsed: number;
- maxExtensions: number;
-}
-
-export interface QuoteInfo {
- number: string;
- /** Annual contract value, in USD. */
- amount: number;
- /** Contract term, e.g. "12 months". */
- term: string;
- /** ISO date the quote expires. */
- validUntil: string;
-}
-
-export interface Deal {
- company: string;
- currentStage: DealStage;
- engineer: SolutionsEngineer;
- trial: TrialInfo;
- quote: QuoteInfo;
-}
-
-/* ──────────────────────────────────────────────────────────────────────── */
-/* Document ledger + supporting pool */
-/* ──────────────────────────────────────────────────────────────────────── */
-
-/**
- * Lifecycle of a single document.
- * available: ready to grab now (download/sign/pay/upload as the action says)
- * action: waiting on the buyer to act (the gating paperwork of a stage)
- * pending: issued, awaiting the other side / a system step
- * request: not generated yet; the buyer asks for it (some carry a fee)
- * complete: done, kept for the record
- */
-export type DocStatus =
- | "available"
- | "action"
- | "pending"
- | "request"
- | "complete";
-
-/** What pressing the document's button does. */
-export type DocAction = "download" | "sign" | "pay" | "upload" | "request";
-
-export interface LedgerDoc {
- id: string;
- name: string;
- /** Sub-line describing what the document is / what it covers. */
- sub: string;
- status: DocStatus;
- action: DocAction;
- /** Buyer-skippable paperwork (e.g. paid onboarding). */
- optional?: boolean;
- /** One-off fee in USD when the document/service is a paid add-on. */
- fee?: number;
-}
-
-/** Document ledger grouped by the journey stage the paperwork belongs to. */
-export interface LedgerGroup {
- stage: DealStage;
- /** Buyer-facing stage name (matches JourneyStep.label). */
- label: string;
- docs: LedgerDoc[];
-}
-
-/** Categories the stage-agnostic supporting pool is grouped under. */
-export type SupportingCategory =
- | "security"
- | "legal"
- | "corporate"
- | "procurement";
-
-export interface SupportingGroup {
- category: SupportingCategory;
- label: string;
- docs: LedgerDoc[];
-}
-
-/* ──────────────────────────────────────────────────────────────────────── */
-/* Full procurement payload */
-/* ──────────────────────────────────────────────────────────────────────── */
-
-export interface ProcurementResponse {
- tier: Tier;
- /** True only for enterprise, gates the whole journey + ledger. */
- unlocked: boolean;
- /** Present only when unlocked. */
- deal: Deal | null;
- journey: JourneyStep[];
- ledger: LedgerGroup[];
- supporting: SupportingGroup[];
-}
-
-/** GET /v1/procurement?tier=…, the deal, journey, ledger and supporting pool. */
-export async function fetchProcurement(
- tier: Tier,
-): Promise {
- return apiClient.local.json(
- `/v1/procurement?tier=${encodeURIComponent(tier)}`,
- );
-}
-
-/*
- * Commercial actions. Each mutates the deal server-side and returns the updated
- * ProcurementResponse, the new canonical state, which the view applies so the
- * journey progresses. The MSW layer answers these today; a real backend honours
- * the same contracts unchanged.
- */
-
-/** Advance the deal to the next stage (the journey's primary CTA). */
-export async function advanceStage(
- fromStage: DealStage,
-): Promise {
- return apiClient.local.json("/v1/procurement/advance", {
- method: "POST",
- body: { fromStage },
- });
-}
-
-/** Sign the Stirling Enterprise Agreement (MSA + order form + EULA + DPA). */
-export async function signAgreement(
- docId: string,
-): Promise {
- // A real backend opens an e-signature envelope and completes on callback;
- // here it completes immediately and advances the deal.
- return apiClient.local.json("/v1/procurement/sign", {
- method: "POST",
- body: { docId },
- });
-}
-
-/** Pay the contract online (card / bank transfer via Stripe). */
-export async function payOnline(): Promise {
- return apiClient.local.json("/v1/procurement/pay", {
- method: "POST",
- });
-}
-
-/** Upload a purchase order to invoice against (an alternate payment path). */
-export async function uploadPurchaseOrder(
- file: File,
-): Promise {
- // A real backend takes the PO as multipart; the mock only needs the name.
- return apiClient.local.json(
- "/v1/procurement/purchase-order",
- {
- method: "POST",
- body: { fileName: file.name },
- },
- );
-}
-
-/** Request a document that is generated on demand (some carry a one-off fee). */
-export async function requestDocument(
- docId: string,
- action: DocAction,
-): Promise {
- return apiClient.local.json(
- `/v1/procurement/documents/${encodeURIComponent(docId)}/request`,
- { method: "POST", body: { action } },
- );
-}
-
// ============================================================================
-// Enterprise procurement — real SaaS backend (/api/v1/procurement).
-//
-// The journey/ledger visuals above still ride the MSW mock; the commercial spine
-// below (trial, server-priced quote, accept -> Stripe checkout) is the real thing,
-// served by the saas Java backend and gated on a linked account.
+// Enterprise procurement — the real SaaS backend (/api/v1/procurement): trial,
+// server-priced quote, agreement, accept -> Stripe. Gated on a linked account.
// ============================================================================
export type QuoteLineItemKind =
@@ -288,7 +95,11 @@ export interface QuoteLineItem {
export interface QuoteResult {
quoteId: number;
- quoteNumber: string;
+ /**
+ * Stripe's quote number — the deal's one reference, shown on the quote, the agreement and the
+ * invoice. Null while the quote is a local draft: Stripe assigns it only at finalisation.
+ */
+ quoteNumber: string | null;
/** draft (priced, editable) | sent (issued Stripe quote — PDF + shareable) | accepted | expired. */
status: string;
currency: string;
@@ -332,6 +143,12 @@ export interface ProcurementSnapshot {
licensed: boolean;
/** The team's Keygen licence key (present once licensed); shown in the portal to copy/install. */
licenseKey: string | null;
+ /** Version label of the signed agreement PDF available to download (e.g. "SEA v0.9.1"), else null. */
+ agreementSignedVersion: string | null;
+ /** Buying entity captured at trial setup; null on deals started before that step existed. */
+ businessName: string | null;
+ contactName: string | null;
+ contactEmail: string | null;
latestQuote: QuoteResult | null;
}
@@ -385,13 +202,37 @@ export function fetchLicenseFile(): Promise {
* Start the trial with the buyer's chosen deployment target and seat count (captured in the setup
* step). These seed the quote builder; both remain editable when the quote is built.
*/
+/** Details collected by trial setup's second step; every field optional server-side. */
+export interface TrialSetupDetails {
+ businessName?: string;
+ contactName?: string;
+ contactEmail?: string;
+ /**
+ * Raw comma/space/semicolon separated addresses. Recorded on the deal AND sent through the
+ * team-invite path once the trial starts; a rejected address is skipped, never fatal.
+ */
+ inviteEmails?: string;
+}
+
export function startTrial(
deployment: string,
seats: number,
+ details?: TrialSetupDetails,
): Promise {
return apiClient.saas.json(
"/api/v1/procurement/trial/start",
- { method: "POST", body: { deployment, users: seats } },
+ { method: "POST", body: { deployment, users: seats, ...details } },
+ );
+}
+
+/**
+ * Record that this account is looking at enterprise. Idempotent, and never disturbs an existing
+ * deal — so it is safe to call on every entry into the flow.
+ */
+export function recordInterest(): Promise {
+ return apiClient.saas.json(
+ "/api/v1/procurement/interest",
+ { method: "POST" },
);
}
@@ -418,12 +259,114 @@ export function buildQuote(cfg: QuoteConfigInput): Promise {
});
}
+/** The filled enterprise agreement (MSA + Order Form + DPA) for the current quote, as markdown. */
+export interface AgreementDocument {
+ docId: string;
+ version: string;
+ /** e.g. "SEA v0.9.1" — the exact document version a signature will be pinned to. */
+ versionLabel: string;
+ displayName: string;
+ effectiveDate: string;
+ /** "draft" until counsel clears it — the UI badges drafts. */
+ status: string;
+ markdown: string;
+}
+
+/** Buyer-supplied signing inputs captured on the agreement stage. */
+export interface SignAgreementInput {
+ customerLegalName: string;
+ signatoryName: string;
+ signatoryTitle: string;
+ authorityConfirmed: boolean;
+}
+
+export interface SignAgreementResult {
+ signatureId: number;
+ versionLabel: string;
+ /** Whether the signed PDF was rendered + stored (false when the render runtime was unavailable). */
+ pdfStored: boolean;
+}
+
+/** Fetch the filled agreement to review before signing. */
+export function fetchAgreementDocument(): Promise {
+ return apiClient.saas.json(
+ "/api/v1/procurement/agreement/document",
+ );
+}
+
+/** Record the signed agreement (pins version + hash + variable snapshot + signatory + PDF). */
+export function recordAgreementSignature(
+ input: SignAgreementInput,
+): Promise {
+ return apiClient.saas.json(
+ "/api/v1/procurement/agreement/sign",
+ { method: "POST", body: input },
+ );
+}
+
+/** Fetch a static legal document (eula, sla, subprocessors) by id for in-product viewing. */
+export function fetchLegalDocument(docId: string): Promise {
+ return apiClient.saas.json(`/api/v1/legal/${docId}`);
+}
+
+/** Download the stored, signed enterprise-agreement PDF for the team (post-signing). */
+export function fetchSignedAgreementPdf(): Promise {
+ return apiClient.saas.blob("/api/v1/procurement/agreement/signature/pdf");
+}
+
+/** Download the current (unsigned) enterprise-agreement PDF — the document shown at the sign step. */
+export function fetchAgreementPdf(): Promise {
+ return apiClient.saas.blob("/api/v1/procurement/agreement/document/pdf");
+}
+
+/**
+ * Record a clickwrap consent to a legal document (e.g. the EULA at trial start / quote generation).
+ * Best-effort — never block the flow it accompanies on a consent-logging failure.
+ */
+export function recordLegalConsent(
+ documentId: string,
+ context: string,
+): Promise {
+ return apiClient.saas
+ .json("/api/v1/legal/consent", {
+ method: "POST",
+ body: { documentId, context },
+ })
+ .catch(() => undefined);
+}
+
// ---- Stripe Quote operations (Supabase edge functions) ---------------------
// Java has no Stripe SDK, so issuing/accepting the quote and fetching its PDF run in edge functions
// that own Stripe; they persist results back through SECURITY DEFINER RPCs. The portal invokes them
// directly (same pattern the PAYG checkout uses).
+/**
+ * Fixture response for an edge function while demo data is on.
+ *
+ * These calls go out through the Supabase client rather than {@code apiClient}, which is where demo
+ * data is normally intercepted — so until this existed they were never mocked. The portal has no
+ * service worker: the MSW handlers are matched by URL inside {@link resolveDemoResponse}, so the URL
+ * has to be reconstructed here to match what mocks/handlers/procurementSaas.ts registers.
+ *
+ * This mattered rather more than a missing fixture: issue and accept create a real Stripe Quote and a
+ * real committed subscription. With a live session — the normal state when developing against the
+ * shared project — pressing "Generate quote" in dev billed nothing but left real objects behind.
+ */
+async function demoEdgeResponse(
+ fn: string,
+ quoteId: number,
+): Promise {
+ const base = saasApiBase();
+ if (!base) return undefined;
+ return resolveDemoResponse(new URL(`${base}/functions/v1/${fn}`), {
+ method: "POST",
+ body: { quote_id: quoteId },
+ });
+}
+
async function invokeEdge(fn: string, quoteId: number): Promise {
+ const demo = await demoEdgeResponse(fn, quoteId);
+ if (demo) return (await demo.json()) as T;
const supabase = getSupabaseClient();
if (!supabase) throw new Error("No SaaS session");
const { data, error } = await supabase.functions.invoke(fn, {
@@ -446,6 +389,8 @@ export function acceptQuote(quoteId: number): Promise {
/** Fetch the Stripe-generated quote PDF as a blob (for download / share). */
export async function fetchQuotePdf(quoteId: number): Promise {
+ const demo = await demoEdgeResponse("get-procurement-quote-pdf", quoteId);
+ if (demo) return await demo.blob();
const supabase = getSupabaseClient();
if (!supabase) throw new Error("No SaaS session");
const { data, error } = await supabase.functions.invoke(
diff --git a/frontend/editor/src/portal/components/EditorStatusCard.css b/frontend/editor/src/portal/components/EditorStatusCard.css
index e71a50bac3..692d08adc3 100644
--- a/frontend/editor/src/portal/components/EditorStatusCard.css
+++ b/frontend/editor/src/portal/components/EditorStatusCard.css
@@ -13,20 +13,18 @@
.portal-editor-hero__row {
display: flex;
align-items: center;
- gap: 1.25rem;
- padding: 1rem 1.25rem;
- background: color-mix(in srgb, var(--c-primary) 22%, var(--c-hero-dark));
+ gap: 0.75rem;
+ padding: 0.625rem 0.875rem;
+ background: var(--c-surface);
}
.portal-editor-hero__logo {
- width: 3.5rem;
- height: 3.5rem;
- border-radius: 0.875rem;
+ width: 2rem;
+ height: 2rem;
+ border-radius: 0.5rem;
overflow: hidden;
flex-shrink: 0;
- box-shadow:
- 0 2px 8px rgba(0, 0, 0, 0.1),
- 0 0 0 1px rgba(0, 0, 0, 0.06);
+ box-shadow: var(--shadow-sm);
}
.portal-editor-hero__mark {
width: 100%;
@@ -39,7 +37,7 @@
min-width: 0;
display: flex;
flex-direction: column;
- gap: 0.5rem;
+ gap: 0.25rem;
}
.portal-editor-hero__title-row {
@@ -50,31 +48,36 @@
}
.portal-editor-hero__name {
- font-size: 1.125rem;
+ font-size: 0.9375rem;
font-weight: 700;
- color: #fff;
+ color: var(--c-text);
margin-right: 0.125rem;
}
-.portal-editor-hero__chip {
- display: inline-flex;
- align-items: center;
- gap: 0.3125rem;
- padding: 0.25rem 0.6875rem;
- border-radius: var(--radius-pill);
- border: 1px solid rgba(255, 255, 255, 0.16);
- background: rgba(255, 255, 255, 0.08);
- color: rgba(255, 255, 255, 0.85);
- font-size: 0.71875rem;
- font-weight: 600;
- cursor: pointer;
- transition: background var(--motion-fast);
+/* The deployment host, sat inline with the name as the rail's subject. */
+.portal-editor-hero__host {
+ font-family: var(--font-mono);
+ font-size: 0.8125rem;
+ font-weight: 500;
+ color: var(--c-text-muted);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
-.portal-editor-hero__chip:hover {
- background: rgba(255, 255, 255, 0.16);
+
+/* Quiet separator between the host and the adoption count. */
+.portal-editor-hero__dot {
+ width: 0.3125rem;
+ height: 0.3125rem;
+ border-radius: 999px;
+ background: var(--c-border);
+ flex-shrink: 0;
}
-.portal-editor-hero__chip svg {
- color: rgba(255, 255, 255, 0.6);
+
+.portal-editor-hero__actives {
+ font-size: 0.75rem;
+ color: var(--c-text-muted);
+ white-space: nowrap;
}
.portal-editor-hero__meta {
@@ -83,15 +86,10 @@
gap: 0.5rem;
flex-wrap: wrap;
font-size: 0.75rem;
- color: rgba(255, 255, 255, 0.5);
-}
-.portal-editor-hero__host {
- color: rgba(255, 255, 255, 0.92);
- font-family: var(--font-mono);
- font-weight: 500;
+ color: var(--c-text-subtle);
}
.portal-editor-hero__meta-sep {
- color: rgba(255, 255, 255, 0.3);
+ color: var(--c-border);
}
.portal-editor-hero__action {
@@ -101,35 +99,6 @@
gap: 0.5rem;
}
-/* Icon-only actions (e.g. install) on the dark header. */
-.portal-editor-hero__icon-btn {
- display: grid;
- place-items: center;
- width: 2.25rem;
- height: 2.25rem;
- flex-shrink: 0;
- border-radius: var(--radius-md);
- border: 1px solid rgba(255, 255, 255, 0.16);
- background: rgba(255, 255, 255, 0.08);
- color: #fff;
- cursor: pointer;
- transition: background var(--motion-fast);
-}
-.portal-editor-hero__icon-btn:hover {
- background: rgba(255, 255, 255, 0.16);
-}
-
-/* White CTA on the dark header, matching the marketing card. */
-.portal-editor-hero__action .portal-editor-hero__cta.sui-btn {
- background: #ffffff;
- border-color: #ffffff;
- color: var(--c-hero-dark-cta-text);
-}
-.portal-editor-hero__action .portal-editor-hero__cta.sui-btn:hover {
- background: rgba(255, 255, 255, 0.88);
- border-color: rgba(255, 255, 255, 0.88);
-}
-
@media (max-width: 48rem) {
.portal-editor-hero__row {
flex-wrap: wrap;
diff --git a/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx b/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx
index 9e73983026..144ded6dc4 100644
--- a/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx
+++ b/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx
@@ -1,19 +1,6 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { http, HttpResponse } from "msw";
import { EditorStatusCard } from "@portal/components/EditorStatusCard";
-import { SetupChecklist } from "@portal/components/SetupChecklist";
-import type { OnboardingProgress } from "@portal/hooks/useOnboardingProgress";
-
-const progress: OnboardingProgress = {
- loading: false,
- deployed: true,
- editorDone: true,
- policiesDone: true,
- inviteDone: false,
- policiesActive: 3,
- policiesRecommended: 4,
- allComplete: false,
-};
const meta: Meta = {
title: "Portal/Home/EditorStatusCard",
@@ -31,25 +18,14 @@ const meta: Meta = {
export default meta;
type Story = StoryObj;
-/** The deployed-Editor status card on its own. */
+/** The deployment rail, reporting a live deployment. */
export const Default: Story = {};
-/** As it renders on the subscribed home: the setup checklist attached as the footer. */
-export const WithSetupChecklist: Story = {
- args: {
- footer: ,
- },
-};
-
/**
- * Backend without the editor-deployment endpoint (404): the status row is
- * skipped and the card falls back to just the footer (setup checklist). It
- * lights up automatically once /v1/editor/deployment is served.
+ * Backend without the editor-deployment endpoint (404): the rail keeps its identity and the neutral
+ * deploy ask, and states no host or adoption figure, since neither can be read.
*/
export const DeploymentUnavailable: Story = {
- args: {
- footer: ,
- },
parameters: {
msw: {
handlers: [
diff --git a/frontend/editor/src/portal/components/EditorStatusCard.tsx b/frontend/editor/src/portal/components/EditorStatusCard.tsx
index 9726cc1009..b506a0a366 100644
--- a/frontend/editor/src/portal/components/EditorStatusCard.tsx
+++ b/frontend/editor/src/portal/components/EditorStatusCard.tsx
@@ -3,15 +3,12 @@ import { Fragment, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button, Skeleton } from "@app/ui";
import { useTier } from "@portal/contexts/TierContext";
-import { useView } from "@portal/contexts/ViewContext";
-import { useEditorDeployment } from "@portal/queries/infrastructure";
-import { type EditorInstance } from "@portal/api/editorDeploy";
+import { EDITOR_URL } from "@portal/auth/editorUrl";
import {
- DownloadIcon,
- ExternalLinkIcon,
- UsersIcon,
- UserPlusIcon,
-} from "@portal/components/icons";
+ useEditorDeployment,
+ useFleetStats,
+} from "@portal/queries/infrastructure";
+import { type EditorInstance } from "@portal/api/editorDeploy";
import { DownloadEditorModal } from "@portal/components/DownloadEditorModal";
import "@portal/components/EditorStatusCard.css";
@@ -48,41 +45,64 @@ function primaryInstance(instances: EditorInstance[]): EditorInstance | null {
);
}
+/**
+ * The rail's primary action matures with adoption rather than deployment alone (marketing note
+ * D243): the loud ask only stands while the org is still one person on an undeployed editor. Once
+ * a deployment is in flight, finishing it takes over; once teammates are in, the ask goes quiet.
+ */
+type DeployAsk = "finish" | "start" | "options";
+
+function deployAsk(
+ instances: EditorInstance[],
+ activeUsers: number,
+): DeployAsk {
+ const deployed = instances.some((i) => i.status === "healthy");
+ if (!deployed && instances.some((i) => i.status === "pairing"))
+ return "finish";
+ if (!deployed && activeUsers <= 1) return "start";
+ return "options";
+}
+
interface EditorStatusCardProps {
- /**
- * Rendered as an attached footer strip inside the card (e.g. the "Finish
- * setting up" checklist), matching the free-tier hero's footer seam.
- */
+ /** Attached footer strip inside the card — the deal-status hero while a deal is underway. */
footer?: ReactNode;
- /**
- * Hide the active-users / invite chips. Used on enterprise, where the
- * attached procurement deal hero already owns the invite action.
- */
- hideChips?: boolean;
}
/**
- * Subscribed/enterprise home hero: a status card for the org's deployed PDF
- * Editor. Reads the same `/v1/editor/deployment` data as the Editor admin view
- * (host, version, live users, deployment shape) and headlines the busiest
- * instance, with a single "Open in browser" action to the workspace URL.
+ * The Home hero: the deployment rail for the org's PDF Editor. Host and build meta come from the
+ * same `/v1/editor/deployment` data as the Editor admin view, headlining the busiest instance; the
+ * adoption count is the figure Usage & Billing reports. The rail always renders — it carries the
+ * deploy ask itself — and each figure stands down independently when its source can't supply it.
*/
-export function EditorStatusCard({ footer, hideChips }: EditorStatusCardProps) {
+export function EditorStatusCard({ footer }: EditorStatusCardProps) {
const { t } = useTranslation();
const { tier } = useTier();
- const { setActiveView } = useView();
const [installOpen, setInstallOpen] = useState(false);
const { data, loading } = useEditorDeployment(tier);
+ // The adoption figure is the same one Usage & Billing reports, read through the shared cache so
+ // the two agree and only one request is made. Either field is null when the backend can't compute
+ // it (e.g. EE auditing off), in which case the rail states no figure rather than a misleading 0.
+ const { data: fleet } = useFleetStats();
+ const adoption =
+ fleet?.activeThisMonth != null && fleet.editorsDeployed != null
+ ? { active: fleet.activeThisMonth, total: fleet.editorsDeployed }
+ : null;
const view = useMemo(() => {
if (!data) return null;
- const primary = primaryInstance(data.instances);
- if (!primary) return null;
const activeUsers = data.instances.reduce((s, i) => s + i.activeUsers, 0);
+ const ask = deployAsk(data.instances, activeUsers);
+ const primary = primaryInstance(data.instances);
+ // Nothing deployed yet: the rail still shows, carrying the deploy ask. Only the host and
+ // build meta are instance-derived, so they simply stand down.
+ if (!primary) {
+ return { host: null, activeUsers, ask, meta: [] as string[] };
+ }
const targetLabel = t(`portal.home.editor.target.${primary.target}`);
return {
host: primary.host,
activeUsers,
+ ask,
workspaceUrl: data.summary.workspaceUrl,
meta: [
// Skip the deployment label when it just repeats the host (e.g. the
@@ -95,21 +115,8 @@ export function EditorStatusCard({ footer, hideChips }: EditorStatusCardProps) {
};
}, [data, t]);
- const ready = !loading && !!view;
- // The editor-deployment endpoint isn't implemented on every backend yet.
- // When it's unavailable (finished loading with no data — e.g. a 404), skip
- // the status row entirely and fall back to just the footer (the setup
- // checklist, which reads supported endpoints). It lights up automatically
- // once the backend serves /v1/editor/deployment.
- const unavailable = !loading && !view;
-
- if (unavailable) {
- return footer ? (
-
- {footer}
-
- ) : null;
- }
+ // Only the deploy ask can go loud; unknown deployment state keeps it quiet.
+ const loudAsk = !!view && view.ask !== "options";
return (
- {!ready || !view ? (
+ {/* Each figure stands down on its own: the host and build meta need the deployment
+ endpoint, the adoption count needs fleet stats. Neither absence blanks the rail, and
+ nothing is asserted that its own source could not supply. */}
+ {loading ? (
<>
@@ -133,65 +143,60 @@ export function EditorStatusCard({ footer, hideChips }: EditorStatusCardProps) {
{t("portal.home.editor.name")}
- {!hideChips && (
-
+ {view?.host && (
+ {view.host}
+ )}
+ {adoption && (
+ <>
+
+
+ {t("portal.home.editor.activeOfDeployed", adoption)}
+
+ >
)}
+ )}
>
)}
+ {/* Open in browser is a left-seated secondary in every state, and carries no arrow
+ (marketing note D244); the deploy ask beside it is the only button that can go loud.
+ Reaching the editor never depends on deployment data — it falls back to the configured
+ editor URL — so this stays live even when the deployment endpoint is unavailable. */}
diff --git a/frontend/editor/src/portal/components/HomeHero.stories.tsx b/frontend/editor/src/portal/components/HomeHero.stories.tsx
index dd1ea07c04..8784bde97a 100644
--- a/frontend/editor/src/portal/components/HomeHero.stories.tsx
+++ b/frontend/editor/src/portal/components/HomeHero.stories.tsx
@@ -16,17 +16,10 @@ const meta = {
export default meta;
type Story = StoryObj;
-/** Pay-as-you-go tier: welcome header + setup checklist until onboarding completes. */
-export const Default: Story = {
- args: { tier: "pro" },
-};
-
-/** Free tier renders the same welcome-header composition as pro. */
-export const FreeTier: Story = {
- args: { tier: "free" },
-};
-
-/** Enterprise tier hides the status chips — the procurement deal hero owns the invite step. */
-export const EnterpriseTier: Story = {
- args: { tier: "enterprise" },
-};
+/**
+ * The hero is the Editor deployment rail on every tier and in both editions — it reports its own
+ * deployment state and deploy ask, so there is nothing tier-specific left to compose. A live
+ * procurement deal attaches the deal-status hero as the rail's footer; that comes from
+ * useProcurement, so it follows the mocked backend rather than a story arg.
+ */
+export const Default: Story = {};
diff --git a/frontend/editor/src/portal/components/HomeHero.tsx b/frontend/editor/src/portal/components/HomeHero.tsx
index 03bcc17ed0..e81d42dfef 100644
--- a/frontend/editor/src/portal/components/HomeHero.tsx
+++ b/frontend/editor/src/portal/components/HomeHero.tsx
@@ -1,60 +1,50 @@
-import type { Tier } from "@portal/contexts/TierContext";
+import { useEffect } from "react";
+import { Skeleton } from "@app/ui";
import { useUI } from "@portal/contexts/UIContext";
-import { WelcomeBanner } from "@portal/components/WelcomeBanner";
import { EditorStatusCard } from "@portal/components/EditorStatusCard";
-import { SetupChecklist } from "@portal/components/SetupChecklist";
-import { useOnboardingProgress } from "@portal/hooks/useOnboardingProgress";
import { ControlledDealStatusHero } from "@portal/components/procurement/ProcurementBanner";
import { ProcurementFlow } from "@portal/components/procurement/ProcurementFlow";
import { useProcurement } from "@portal/components/procurement/useProcurement";
/**
- * The Home hero, composed with a procurement-aware, progress-aware footer:
- *
- * - no live deployment → welcome header (+ setup steps until complete)
- * - deployment live → deployed-Editor status header (+ steps until complete)
- * - onboarding complete → header only; the setup steps collapse away
- * - enterprise → status header with chips hidden (the deal hero owns invite)
- *
- * The footer is the deal-status hero while a procurement deal is underway
- * (procurement is a bolt-on to any tier); otherwise the setup checklist, until
- * every step is done — then it collapses to just the header, matching the
- * deployed-status card. The procurement takeover modals render alongside.
+ * The Home hero: always the Editor deployment rail, carrying the deal-status hero as its footer
+ * while a procurement deal is underway (procurement is a bolt-on to any tier). The rail states its
+ * own deployment status and deploy ask, so there is nothing for a tier to choose between. The
+ * procurement takeover modals render alongside.
*/
-export function HomeHero({ tier }: { tier: Tier }) {
- const { openLinkModal } = useUI();
+export function HomeHero() {
const procurement = useProcurement();
- const progress = useOnboardingProgress();
+ const { trialSetupRequested, clearTrialSetupRequest } = useUI();
const dealActive =
procurement.isLinked && procurement.started && !!procurement.data;
- // Start the enterprise flow right here on Home: open the trial-setup modal when the account is
- // linked, otherwise prompt to link first — no navigating off to the procurement view.
- const onStartEnterprise = () => {
- if (procurement.isLinked) procurement.onStartTrial();
- else openLinkModal();
- };
-
- // Steps collapse once onboarding is complete; a live deal always keeps its
- // hero. Otherwise the setup checklist carries the (progress-aware) steps.
- const footer = dealActive ? (
-
- ) : progress.allComplete ? undefined : (
-
- );
-
- // The live-status header (EditorStatusCard) needs a real deployment to show;
- // without one it renders nothing, so route to it only when actually deployed.
- // Everything else — including a step completed via the local download flag —
- // keeps the always-present welcome header, so the card never vanishes.
- const showStatus = progress.deployed;
+ // Someone said yes to enterprise elsewhere (the billing upsell, a sales link). Open trial setup
+ // once the snapshot has landed, so a buyer who already has a deal is not asked to start another.
+ useEffect(() => {
+ if (!trialSetupRequested || procurement.loading) return;
+ clearTrialSetupRequest();
+ if (!procurement.started) procurement.onExploreEnterprise();
+ }, [trialSetupRequested, procurement, clearTrialSetupRequest]);
return (
<>
- {showStatus ? (
-
+ {procurement.loading ? (
+ // Hold the rail's shape rather than committing to a footer: branching before the snapshot
+ // lands paints the no-deal rail first, flashing on every refresh of an active deal.
+
+
}
-
- setInstallOpen(false)}
- />
-
- );
-}
diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
index b5d0d58a3b..7d322a7be6 100644
--- a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
@@ -665,7 +665,6 @@ export function BundleCheckoutModal({
{t("portal.billing.prepaid.buy.cancel", "Cancel")}
-
diff --git a/frontend/editor/src/portal/components/billing/EnterpriseUpsell.tsx b/frontend/editor/src/portal/components/billing/EnterpriseUpsell.tsx
index 161b3bea72..55aaf89b5b 100644
--- a/frontend/editor/src/portal/components/billing/EnterpriseUpsell.tsx
+++ b/frontend/editor/src/portal/components/billing/EnterpriseUpsell.tsx
@@ -1,5 +1,6 @@
import { useTranslation } from "react-i18next";
import { Button, Card } from "@app/ui";
+import { useUI } from "@portal/contexts/UIContext";
import { useView } from "@portal/contexts/ViewContext";
interface Props {
@@ -9,12 +10,13 @@ interface Props {
/**
* Volume-discount / Enterprise upsell, shared by the free and subscribed billing
- * views. The CTA opens the procurement journey (/procurement auto-opens the quote
- * builder in the takeover modal).
+ * views. The CTA lands the buyer on Home with the trial-setup step raised — the deal lives there,
+ * so there is nowhere else to send them.
*/
export function EnterpriseUpsell({ bare = false }: Props) {
const { t } = useTranslation();
const { setActiveView } = useView();
+ const { requestTrialSetup } = useUI();
const body = (
<>
@@ -38,7 +40,12 @@ export function EnterpriseUpsell({ bare = false }: Props) {
setActiveView("procurement")}
+ onClick={() => {
+ // The deal lives on Home; raise the request there rather than sending the buyer to a
+ // separate view that only mirrors it.
+ requestTrialSetup();
+ setActiveView("home");
+ }}
>
{t("portal.billing.enterpriseUpsell.cta", "Explore Enterprise")}
diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
index d3a1baf036..e2bbb24a34 100644
--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx
+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
@@ -85,7 +85,6 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
const switchOnAction = isLeader ? (
diff --git a/frontend/editor/src/portal/components/billing/LinkAccountPrompt.tsx b/frontend/editor/src/portal/components/billing/LinkAccountPrompt.tsx
index e21fec3591..394668c56b 100644
--- a/frontend/editor/src/portal/components/billing/LinkAccountPrompt.tsx
+++ b/frontend/editor/src/portal/components/billing/LinkAccountPrompt.tsx
@@ -23,11 +23,7 @@ export function LinkAccountPrompt() {
"Manual PDF editing — view, sign, merge, split, watermark, compress, convert, manual OCR — is always free, linked or not. Link to claim 500 free PDFs of metered processing (automation, AI, and the API); when you need more, turn on the Processor plan and only pay for what you use.",
)}
actions={
- openLinkModal()}
- >
+ openLinkModal()}>
{t("portal.billing.linkPrompt.cta", "Link Stirling account")}
}
diff --git a/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx b/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx
index c099836ee4..f07083f215 100644
--- a/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx
+++ b/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx
@@ -1,15 +1,14 @@
import { useTranslation } from "react-i18next";
-import { Button } from "@app/ui";
-// The trademarked Stirling wordmark — the font is baked into the SVG (no brand webfont is loaded), so
-// we render the same asset the portal nav uses rather than styled text. Theme-switched in CSS.
-import wordmarkLight from "@app/assets/brand/modern-logo/StirlingProcessorLogoBlackText.svg";
-import wordmarkDark from "@app/assets/brand/modern-logo/StirlingProcessorLogoWhiteText.svg";
+import { StepModalHeader } from "@portal/components/shared/StepModalHeader";
/**
- * Shared header for the prepay-flow modals — the prepaid wizard (activation → calculator → pay, of 3)
- * and the metered checkout (spend limit → payment, of 2): Stirling brand + "Step N of M" badge + close,
- * an M-segment progress bar, and the step title. Pass {@code step=undefined} to hide the badge +
- * progress (e.g. a terminal confirmation).
+ * The prepay flows' stepped header — the prepaid wizard (activation → calculator → pay, of 3) and
+ * the metered checkout (spend limit → payment, of 2).
+ *
+ * Chrome and copy only: the layout is the shared {@link StepModalHeader}, so this flow reads the
+ * same as every other stepped modal. Keeps the billing root class, which the framed-checkout rule
+ * targets to own the header's padding. Pass {@code step=undefined} to hide the badge + progress
+ * (e.g. a terminal confirmation).
*/
export function PrepayModalHeader({
step,
@@ -24,68 +23,27 @@ export function PrepayModalHeader({
onClose: () => void;
}) {
const { t } = useTranslation();
- const showSteps = step != null;
- const filled = step ?? 0;
return (
-
-
- );
-}
diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx
index 9421de28bb..77c008ce41 100644
--- a/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx
+++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx
@@ -12,6 +12,10 @@ const base: ProcurementSnapshot = {
trialExtensionsUsed: 0,
licensed: false,
licenseKey: null,
+ businessName: null,
+ contactName: null,
+ contactEmail: null,
+ agreementSignedVersion: null,
latestQuote: null,
};
@@ -23,11 +27,11 @@ const meta: Meta = {
args: {
canSchedule: true,
onExpand: () => {},
+ onAcceptQuote: () => {},
onLicense: () => {},
onInvite: () => {},
onSchedule: () => {},
onManageTrial: () => {},
- onNavigate: () => {},
},
};
export default meta;
diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
index 092e259bb3..ef2172bb27 100644
--- a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
+++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx
@@ -1,31 +1,62 @@
-import { useEffect } from "react";
+import { useEffect, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@app/ui";
-import type { ViewId } from "@portal/contexts/ViewContext";
import {
FLOW_JOURNEY,
+ type DealStage,
type ProcurementSnapshot,
} from "@portal/api/procurement";
-import { StageStepper } from "@portal/components/procurement/StageStepper";
+import {
+ CalendarIcon,
+ CheckIcon,
+ DocumentsIcon,
+ KeyIcon,
+ UserPlusIcon,
+} from "@portal/components/icons";
import { warmCalendly } from "@portal/components/procurement/CalendlyInline";
+import { openApiUrl } from "@portal/api/externalUrl";
import "@portal/views/Procurement.css";
+/** What each stage asks of the buyer, read out in the stage sentence. */
+const STAGE_SENTENCE: Record = {
+ // Exploring sits on the Trial rung: same sentence, since the ask is what differs.
+ exploring: "portal.procurement.hero.sentenceTrial",
+ trial: "portal.procurement.hero.sentenceTrial",
+ quote: "portal.procurement.hero.sentenceQuote",
+ security: "portal.procurement.hero.sentenceAgreement",
+ procurement: "portal.procurement.hero.sentencePayment",
+ active: "portal.procurement.hero.sentenceLive",
+};
+
+/** The primary action for each stage; expanding the flow runs it. */
+const STAGE_CTA: Record = {
+ exploring: "portal.procurement.hero.ctaExploring",
+ trial: "portal.procurement.hero.ctaTrial",
+ quote: "portal.procurement.hero.ctaQuote",
+ security: "portal.procurement.hero.ctaAgreement",
+ // Same label whether it links straight to Stripe or, lacking an invoice URL, opens the stage dialog
+ // where the invoice actions live — the buyer is being sent to the invoice either way.
+ procurement: "portal.procurement.payment.viewInvoice",
+ active: "portal.procurement.hero.open",
+};
+
/**
- * The enterprise deal-status hero on Home (procurement lives here, not as a nav tab). Adapts to the
- * deal stage: quick-action chips (trial countdown → manage, licence key, invite teammates,
- * schedule a call), a rollout checklist during the trial, and a stage-specific primary CTA that
- * expands the flow into the takeover modal. Matches the marketing prototype.
+ * The enterprise deal-status hero on Home (procurement lives here, not as a nav tab) — this card IS
+ * the procurement surface. It carries the journey as a segmented progress band plus a stage
+ * sentence, and one primary action with quiet icon buttons beside it; the flow itself opens in the
+ * takeover modal. Rollout setup lives in the non-procurement setup checklist, not here.
*/
export function DealStatusHero({
snapshot,
busy = false,
canSchedule,
onExpand,
+ onAcceptQuote,
onLicense,
onInvite,
onSchedule,
onManageTrial,
- onNavigate,
+ onDocuments,
}: {
snapshot: ProcurementSnapshot;
busy?: boolean;
@@ -33,11 +64,17 @@ export function DealStatusHero({
* "Schedule a call" action only appears when the org has linked its account. */
canSchedule: boolean;
onExpand: () => void;
+ /**
+ * Accept the issued quote, which advances the deal to the agreement. Offered here rather than
+ * inside the quote review so the buyer can circulate the quote and come back to decide.
+ */
+ onAcceptQuote: () => void;
onLicense: () => void;
onInvite: () => void;
onSchedule: () => void;
onManageTrial: () => void;
- onNavigate: (view: ViewId) => void;
+ /** Open the Documents reference (agreement, quote, invoice, EULA, SLA, subprocessors). */
+ onDocuments: () => void;
}) {
const { t } = useTranslation();
@@ -49,129 +86,181 @@ export function DealStatusHero({
const stage = snapshot.stage ?? "trial";
const inTrial = stage === "trial";
- const cta =
- stage === "trial"
- ? t("portal.procurement.hero.ctaTrial")
- : stage === "quote"
- ? t("portal.procurement.hero.ctaQuote")
- : stage === "procurement"
- ? t("portal.procurement.hero.ctaPayment")
- : t("portal.procurement.hero.ctaLive");
+ const isLive = stage === "active";
+ // A live quote is sitting with the buyer. A draft (or an expired/cancelled one) is not something to
+ // accept — that stage still means "finish building it".
+ const quoteAwaitingDecision =
+ stage === "quote" &&
+ (snapshot.latestQuote?.status === "sent" ||
+ snapshot.latestQuote?.status === "open");
+ // Paying happens on Stripe, so the card links straight there rather than opening a dialog whose only
+ // real action was the same link. Without an invoice URL there is nothing to link to, so the stage
+ // falls back to its dialog, where the signed agreement is still reachable.
+ const invoiceUrl =
+ stage === "procurement" ? snapshot.latestQuote?.invoiceUrl : null;
+ // Known from trial setup onward. The quote's own copy wins when present, since the buyer may have
+ // corrected it there; before either exists the eyebrow stands alone rather than inventing a name.
+ const company =
+ snapshot.latestQuote?.config.businessName?.trim() ||
+ snapshot.businessName?.trim();
- const setupSteps: { title: string; sub: string; view: ViewId }[] = [
- {
- title: t("portal.procurement.hero.setup1Title"),
- sub: t("portal.procurement.hero.setup1Sub"),
- view: "users",
- },
- {
- title: t("portal.procurement.hero.setup2Title"),
- sub: t("portal.procurement.hero.setup2Sub"),
- view: "sources",
- },
- {
- title: t("portal.procurement.hero.setup3Title"),
- sub: t("portal.procurement.hero.setup3Sub"),
- view: "policies",
- },
- ];
+ // Exploring is presented as the Trial rung — same position, sentence and next step — because the
+ // buyer has entered the journey; only the ask differs, since no trial has actually started.
+ const journeyStage = stage === "exploring" ? "trial" : stage;
+ const currentIdx = Math.max(
+ 0,
+ FLOW_JOURNEY.findIndex((s) => s.stage === journeyStage),
+ );
+ const nextStage = FLOW_JOURNEY[currentIdx + 1];
return (
+ {/* An issued quote is a decision point, so the card carries both halves of it: accept it, or
+ open it again to read and circulate first. Every other stage has one next step. */}
+ {quoteAwaitingDecision ? (
+ <>
+
+ {t("portal.procurement.review.acceptCta")}
+
+
+ {t("portal.procurement.hero.ctaReviewQuote")}
+
+ >
+ ) : invoiceUrl ? (
+ openApiUrl(invoiceUrl)}>
+ {t("portal.procurement.payment.viewInvoice")}
+ ) : (
+
+ {t(STAGE_CTA[stage])}
+
+ )}
+
- );
-}
diff --git a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx
index a6ca8dfcf5..fd47d867c6 100644
--- a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx
+++ b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx
@@ -69,10 +69,9 @@ const meta: Meta = {
args: {
quote,
busy: false,
- downloading: false,
onAgree: () => {},
- onDownload: () => {},
- onEdit: () => {},
+ onRequestChanges: () => {},
+ onClose: () => {},
},
};
export default meta;
@@ -81,12 +80,7 @@ type Story = StoryObj;
export const Default: Story = {};
-// Agreeing: the primary CTA shows its loading state while the accept call is in flight.
-export const Agreeing: Story = {
+// Signing: the primary CTA shows its loading state while the accept call is in flight.
+export const Signing: Story = {
args: { busy: true },
};
-
-// Downloading: the secondary action shows its loading state instead.
-export const Downloading: Story = {
- args: { downloading: true },
-};
diff --git a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx
index 336b6af5cb..318f23aca5 100644
--- a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx
+++ b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx
@@ -1,152 +1,267 @@
-import { useState } from "react";
+import { useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { Button, Card } from "@app/ui";
-import type { QuoteResult } from "@portal/api/procurement";
-import { money } from "@portal/components/procurement/format";
+import Markdown from "react-markdown";
+import remarkGfm from "remark-gfm";
+import { Button } from "@app/ui";
+import {
+ fetchAgreementDocument,
+ fetchAgreementPdf,
+ recordAgreementSignature,
+ type QuoteResult,
+} from "@portal/api/procurement";
+import { DownloadIcon } from "@portal/components/icons";
+import { StepModalHeader } from "@portal/components/shared/StepModalHeader";
+import { useAsync } from "@portal/hooks/useAsync";
import "@portal/views/Procurement.css";
/**
- * The agreement (security) step: a single combined Stirling Enterprise Agreement — Master Service
- * Agreement + Order Form (from the issued quote) + EULA + Data Processing Agreement — that the buyer
- * reviews and agrees to before it's accepted into a subscription. No e-signature for now: an explicit
- * "I agree" click stands in (the terms reference the accepted quote). Document body is static legal
- * copy; the surrounding UI is translated.
+ * The agreement (security) step: the buyer reviews the full Stirling Enterprise Agreement — Master
+ * Services Agreement + Order Form (from the quote) + Data Processing Addendum, one signature — then
+ * signs it. The document body is served by the backend from the versioned legal registry (static
+ * legal copy, English only); this component renders it, gates signing behind a scroll-through, and
+ * captures the typed legal name, signatory, title, and authority. On sign it records the signature
+ * (pinned to the exact document version + a hash) and then accepts the quote into a subscription.
+ *
+ * Presented as the document itself rather than a card about it: this step names the agreement in the
+ * dialog's own header and carries its download there, so the terms are read on paper-like stock
+ * instead of in app chrome. That is why it draws its own header — see ProcurementFlow.
*/
export function ProcurementAgreement({
quote,
busy,
- downloading,
onAgree,
- onDownload,
- onEdit,
+ onRequestChanges,
+ onClose,
}: {
quote: QuoteResult;
busy: boolean;
- downloading: boolean;
- /** Accept the quote straight into a committed subscription (this is also the agreement). */
+ /** Accept the quote straight into a committed subscription (runs after the signature is saved). */
onAgree: () => void;
- onDownload: () => void;
- onEdit: () => void;
+ /** Hand the buyer to their SE to negotiate terms: closes this and opens scheduling. */
+ onRequestChanges: () => void;
+ /** This step draws the dialog's header, so it carries the close too. */
+ onClose?: () => void;
}) {
const { t } = useTranslation();
- const [checked, setChecked] = useState(false);
- const annual = money(quote.annualNetMinor, quote.currency);
- const tcv = money(quote.tcvMinor, quote.currency);
- const renewal = money(quote.renewalAnnualNetMinor, quote.currency);
- const years = quote.config.termYears;
+ const { data: doc, loading } = useAsync(fetchAgreementDocument, []);
+
+ const [legalName, setLegalName] = useState(quote.config.businessName ?? "");
+ const [signatory, setSignatory] = useState(quote.config.contactName ?? "");
+ const [title, setTitle] = useState("");
+ const [confirmed, setConfirmed] = useState(false);
+ const [scrolledToEnd, setScrolledToEnd] = useState(false);
+ const [signing, setSigning] = useState(false);
+ const [downloadingMsa, setDownloadingMsa] = useState(false);
+ const [error, setError] = useState(false);
+ const [downloadError, setDownloadError] = useState(false);
+ const docRef = useRef(null);
+
+ const downloadMsa = async () => {
+ setDownloadingMsa(true);
+ setDownloadError(false);
+ try {
+ const blob = await fetchAgreementPdf();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "stirling-enterprise-agreement.pdf";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 60_000);
+ } catch {
+ // Surface the failure — the PDF is rendered server-side, so a failure here means the
+ // render service is unavailable rather than something the buyer can retry around.
+ setDownloadError(true);
+ } finally {
+ setDownloadingMsa(false);
+ }
+ };
+
+ const onScroll = () => {
+ const el = docRef.current;
+ if (!el) return;
+ if (el.scrollTop + el.clientHeight >= el.scrollHeight - 24) {
+ setScrolledToEnd(true);
+ }
+ };
+
+ const ready =
+ scrolledToEnd &&
+ confirmed &&
+ legalName.trim().length > 0 &&
+ signatory.trim().length > 0;
+
+ const sign = async () => {
+ setError(false);
+ setSigning(true);
+ try {
+ await recordAgreementSignature({
+ customerLegalName: legalName.trim(),
+ signatoryName: signatory.trim(),
+ signatoryTitle: title.trim(),
+ authorityConfirmed: confirmed,
+ });
+ onAgree(); // proceed into the committed subscription
+ } catch {
+ setError(true);
+ } finally {
+ // In `finally`, not only on failure: accepting can fail after the signature is recorded, and
+ // the controller deliberately keeps this dialog open on failure so the error is readable. With
+ // the flag left set, the button span the rest of the session and there was no way to retry.
+ setSigning(false);
+ }
+ };
return (
-
-
- {t("portal.procurement.agreement.eyebrow")}
-
-
- {t("portal.procurement.agreement.title")}
-
-
- {t("portal.procurement.agreement.intro")}
-
+
+
+ {/* On the document, like the quote's: it downloads what is on screen. */}
+ }
+ loading={downloadingMsa}
+ onClick={downloadMsa}
+ >
+ {t("portal.procurement.agreement.download")}
+
+ {/* Redlines are a conversation, not a form: this hands the buyer to their SE rather than
+ pretending the terms can be amended in the app. */}
+
+ {t("portal.procurement.agreement.requestChanges")}
+
+
+ }
+ />
-
-
1. Master Service Agreement
-
- This Stirling Enterprise Agreement ("Agreement") is entered into
- between Stirling PDF Inc. ("Stirling") and the customer identified on
- the Order Form ("Customer"). It governs Customer's access to and use
- of the Stirling enterprise platform and related services (the
- "Service"). Stirling will provide the Service with commercially
- reasonable skill and care and in accordance with the service levels
- set out in the Order Form.
-
+ {/* The tray scrolls, not the paper. The paper is its natural height inside it, so mid-document it
+ runs flush to the footer with no grey beneath, and the tray's bottom padding only comes into
+ view once the buyer reaches the end — the page ending is what shows they got there. */}
+
+
+ {loading &&
{t("portal.procurement.agreement.loading")}
}
+ {!loading && !doc && (
+
{t("portal.procurement.agreement.loadError")}
+ )}
+ {doc && (
+ <>
+ {/* Letterhead: the reference ties the terms to the quote they price, and the version
+ label pins what was signed. The document's own heading follows, so this adds a
+ masthead rather than repeating the title. */}
+
- Quote {quote.quoteNumber} forms the Order Form for
- this Agreement. Customer commits to a {years}-year term at{" "}
- {annual} per year (total contract value{" "}
- {tcv}), billed annually in advance by invoice. Fees
- are exclusive of taxes. The committed volume, service level, and
- add-ons are itemised below:
+ {error && (
+
+ )}
+
+ {/* The signature block: who is bound, who signs, and the act of signing, on one line — the
+ shape of a paper signature block rather than a form above a button. The consent sits
+ directly under the fields it qualifies, with no rule between them: it is part of signing,
+ not a separate section, and boxing it cost the document a quarter of its height. */}
+
- This Agreement runs for the committed {years}-year term set out in the
- Order Form. It then renews automatically for successive one-year terms
- unless either party gives written notice of non-renewal at least 30
- days before the end of the then-current term. On each renewal the
- annual fee increases by {quote.cpiRatePct}%, a fixed CPI adjustment.
- Based on this quote, the first renewal year would be approximately{" "}
- {renewal} per year; the committed term above is
- billed at the rate in the Order Form and is not affected.
-
-
-
4. End-User License Agreement
-
- Subject to the terms of this Agreement, Stirling grants Customer a
- non-exclusive, non-transferable right to use the Service for its
- internal business purposes during the term. Customer is responsible
- for its users' compliance and for the content it processes. The
- Service, and all intellectual property in it, remains Stirling's.
-
-
-
5. Data Processing Agreement
-
- Where Stirling processes personal data on Customer's behalf, it does
- so only on Customer's documented instructions and applies appropriate
- technical and organisational measures. Sub-processors, international
- transfers, and security commitments are as described in Stirling's
- Data Processing Agreement and Trust Center, incorporated here by
- reference.
-
-
-
6. Acceptance
-
- By agreeing below, Customer accepts this Agreement and the Order Form.
- On acceptance, Stirling will issue the committed annual subscription
- and its first invoice. This preview stands in for e-signature during
- the pilot.
-
+ {/* Consent under the fields it qualifies; the gate's state under the button it gates, so the
+ reason signing is unavailable sits beside the unavailable thing. */}
+
,
- document.body,
+ {children}
+
);
}
diff --git a/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx b/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx
index 35460a7ba5..fcf926f481 100644
--- a/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx
+++ b/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx
@@ -1,61 +1,92 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
-import { Button, Card } from "@app/ui";
+import { Button } from "@app/ui";
+import { openApiUrl } from "@portal/api/externalUrl";
import "@portal/views/Procurement.css";
/**
- * The stage-specific cards shown inside the procurement takeover modal once a quote exists: the
- * issued-quote milestone, the subscription-created payment step, and the live confirmation. Each is
- * a pure presentational view driven by props; ProcurementHome owns the state and the actions.
+ * The stage-specific views shown inside the procurement takeover modal once the agreement is signed:
+ * the subscription-created payment step and the live confirmation. Each is a pure presentational view
+ * driven by props; the controller owns the state and the actions.
+ *
+ * Neither is wrapped in a Card: the dialog is already the surface, and a card inside it drew a second
+ * border around content that filled it. Both wear the same eyebrow/title/description stack and put
+ * their actions in the flow's footer bar, so the last two steps of the journey read like the ones
+ * before them rather than like panels that wandered in.
*/
-/** The subscription-created step: pay or download the first invoice. */
+/** The subscription-created step: pay or download the first invoice, and the signed agreement. */
export function PaymentStageCard({
invoiceUrl,
invoicePdf,
+ signedAgreementVersion,
+ downloadingAgreement,
+ onDownloadSignedAgreement,
}: {
invoiceUrl?: string | null;
invoicePdf?: string | null;
+ /** Version label of the signed agreement PDF, if one is available to download. */
+ signedAgreementVersion?: string | null;
+ downloadingAgreement?: boolean;
+ onDownloadSignedAgreement?: () => void;
}) {
const { t } = useTranslation();
return (
-
+
);
}
diff --git a/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx b/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx
index b392247563..98fcbd4f04 100644
--- a/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx
+++ b/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx
@@ -3,18 +3,24 @@ import { useTranslation } from "react-i18next";
import { Button } from "@app/ui";
import {
DocumentsIcon,
+ DownloadIcon,
PoliciesIcon,
UsersIcon,
} from "@portal/components/icons";
import { money } from "@portal/components/procurement/format";
import {
buildQuote,
+ recordLegalConsent,
type QuoteConfigInput,
type QuoteResult,
} from "@portal/api/procurement";
+import { LegalDocumentModal } from "@portal/components/procurement/ProcurementExtras";
+import { StepModalHeader } from "@portal/components/shared/StepModalHeader";
import "@portal/views/Procurement.css";
-const STEPS = ["volume", "plan", "details"] as const;
+const STEPS = ["volume", "plan", "details", "review"] as const;
+const DETAILS_STEP = 2;
+const REVIEW_STEP = 3;
const TERM_DISCOUNT = [0, 0.03, 0.05, 0.06, 0.07]; // 1..5 years — meter-only discount (D71)
// Governance posture: the intensity (runs per PDF) fed to the committed-volume curve.
const POSTURES = [
@@ -30,22 +36,57 @@ const SIZE_TIERS = [
] as const;
/**
- * The enterprise quote builder — volume → commitment & service → details. A client-side preview
- * drives the live footer total; the backend is authoritative. Completing the form generates the
- * quote directly (build + issue in one step) — the issued quote is then shown as the milestone, so
- * there's no redundant in-builder preview.
+ * The enterprise quote builder — volume → commitment & service → details → review. A client-side
+ * preview drives the live footer total; the backend is authoritative. Generating builds and issues in
+ * one go, and the issued quote comes back as the fourth step: the buyer reads the real itemised paper
+ * and can download it, but does not accept here. Accepting is a decision taken from the deal card,
+ * deliberately, so circulating the quote internally is not a dead end in a modal.
*/
export function QuoteBuilder({
deployment,
seats = 0,
+ email,
+ onClose,
+ dealDetails,
initial,
+ eulaAlreadyAgreed = false,
onGenerate,
+ issued,
+ downloading = false,
+ onDownload,
}: {
deployment: string;
/** Seat count from the trial setup; seeds the users field + volume estimate on a fresh quote. */
seats?: number;
+ /** Linked-account email; prefills the contact email on a fresh quote's details step. */
+ email?: string | null;
+ /** Dismiss the dialog. The builder draws its own header, so it carries the close too. */
+ onClose?: () => void;
+ /**
+ * The buying entity captured at trial setup. Seeds a fresh quote's details step so it confirms
+ * what is already known rather than asking twice; the buyer can still correct it here, since a
+ * deal can change hands between trial and quote.
+ */
+ dealDetails?: {
+ businessName?: string | null;
+ contactName?: string | null;
+ contactEmail?: string | null;
+ };
/** Seed the builder from an existing quote's config (re-editing a quote). */
initial?: QuoteConfigInput;
+ /**
+ * The issued quote, which is what the review step shows. Its arrival is also what opens that step:
+ * the parent issues the quote and it lands by snapshot refresh, so there is no synchronous result
+ * to advance on. Null while re-editing, so editing reopens the form rather than the paper.
+ */
+ issued?: QuoteResult | null;
+ downloading?: boolean;
+ onDownload?: () => void;
+ /**
+ * The buyer already accepted the EULA (e.g. at trial start). When true, the EULA clickwrap is
+ * hidden here and no consent is recorded at quote time — it's only collected once.
+ */
+ eulaAlreadyAgreed?: boolean;
/** Called with the priced DRAFT quote; the parent issues it as a Stripe Quote. */
onGenerate: (quote: QuoteResult) => void;
}) {
@@ -65,9 +106,9 @@ export function QuoteBuilder({
indemnification: false,
training: false,
qbr: false,
- businessName: "",
- contactName: "",
- contactEmail: "",
+ businessName: dealDetails?.businessName ?? "",
+ contactName: dealDetails?.contactName ?? "",
+ contactEmail: dealDetails?.contactEmail ?? email ?? "",
addressLine1: "",
addressLine2: "",
city: "",
@@ -79,29 +120,81 @@ export function QuoteBuilder({
);
// A seeded quote carries a volume but no user count, so treat it as manually set.
const [manualVolume, setManualVolume] = useState(initial != null);
- const [eula, setEula] = useState(initial != null);
+ // Never pre-ticked, even when re-editing a quote: a consent the buyer did not tick in this session
+ // is not a consent, and recordLegalConsent would have logged one as though they had.
+ const [eula, setEula] = useState(false);
+ const [legalDoc, setLegalDoc] = useState(null);
const [busy, setBusy] = useState(false);
+ // Only surface field errors once the buyer tries to generate — no red fields on first sight.
+ const [showErrors, setShowErrors] = useState(false);
function set(k: K, v: QuoteConfigInput[K]) {
setCfg((c) => ({ ...c, [k]: v }));
}
- // Re-editing an existing quote: everything is seeded, so jump to the last step (details) with the
+ // Required buyer details before a quote can be generated (Order Form / invoice need these).
+ const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(
+ (cfg.contactEmail ?? "").trim(),
+ );
+ const valid = {
+ businessName: cfg.businessName.trim().length > 0,
+ contactName: (cfg.contactName ?? "").trim().length > 0,
+ contactEmail: emailOk,
+ addressLine1: (cfg.addressLine1 ?? "").trim().length > 0,
+ city: (cfg.city ?? "").trim().length > 0,
+ region: (cfg.region ?? "").trim().length > 0,
+ postalCode: (cfg.postalCode ?? "").trim().length > 0,
+ };
+ const detailsValid = Object.values(valid).every(Boolean);
+ const eulaOk = eulaAlreadyAgreed || eula;
+ const canGenerate = detailsValid && eulaOk;
+
+ // Re-editing an existing quote: everything is seeded, so jump to the details step with the
// agreement pre-accepted — one click re-generates, or Back to change a field. No walking from step 1.
// Mount-only: seed the step from `initial` once (deliberately no deps).
useEffect(() => {
- if (initial) setStep(STEPS.length - 1);
+ if (initial) setStep(DETAILS_STEP);
}, []);
+ // Issuing lands by snapshot refresh rather than as a return value, so the arrival of the issued
+ // quote is what opens the review step. Keyed on the quote's id, not the object: React Query hands
+ // back a fresh object on every refetch, which would yank a buyer who had walked Back to the form.
+ useEffect(() => {
+ if (issued) setStep(REVIEW_STEP);
+ }, [issued?.quoteId]);
+
const preview = previewAnnualMinor(cfg);
const tcvPreview = preview * cfg.termYears + (cfg.training ? 750_000 : 0);
+ // On the review step the footer quotes the issued figures rather than the client-side preview, so
+ // the running total never disagrees with the paper directly above it.
+ const onPaper = issued != null && step === REVIEW_STEP;
+ const running = onPaper
+ ? {
+ annual: money(issued.annualNetMinor, issued.currency),
+ years: issued.config.termYears,
+ tcv: money(issued.tcvMinor, issued.currency),
+ }
+ : {
+ annual: money(preview),
+ years: cfg.termYears,
+ tcv: money(tcvPreview),
+ };
+
// Fully filled → price + hand the draft to the parent to issue as a Stripe Quote (which then shows
// as the milestone). No separate in-builder preview step.
async function generate() {
+ if (!canGenerate) {
+ setShowErrors(true);
+ return;
+ }
setBusy(true);
try {
- onGenerate(await buildQuote(cfg));
+ const quote = await buildQuote(cfg);
+ // Record the EULA clickwrap only when it's collected here — i.e. the buyer didn't already
+ // accept it at trial start. Best-effort.
+ if (!eulaAlreadyAgreed) void recordLegalConsent("eula", "quote");
+ onGenerate(quote);
} finally {
setBusy(false);
}
@@ -109,22 +202,16 @@ export function QuoteBuilder({
return (
+ )}
)}
+
+ {/* No step heading here, unlike the form steps: the quote is the content, and a heading over
+ it only repeats what the paper already says. The real issued figures, not the footer's
+ client-side preview — this is the document the buyer circulates, so it has to match the
+ PDF and the Stripe quote exactly. */}
+ {step === REVIEW_STEP && issued && (
+
+ {t("portal.procurement.review.validUntil", {
+ date: new Date(issued.validUntil).toLocaleDateString(),
+ })}
+
+ )}
+ {/* On the document rather than in the footer: it downloads this paper, so it
+ belongs to it, and the footer stays the flow's own Back/Done. */}
+ }
+ loading={downloading}
+ onClick={onDownload}
+ >
+ {t("portal.procurement.review.downloadCta")}
+
+
);
diff --git a/frontend/editor/src/portal/views/Procurement.css b/frontend/editor/src/portal/views/Procurement.css
index e26fd74a31..b721768952 100644
--- a/frontend/editor/src/portal/views/Procurement.css
+++ b/frontend/editor/src/portal/views/Procurement.css
@@ -1,34 +1,10 @@
-.portal-proc {
- display: flex;
- flex-direction: column;
- gap: 1.25rem;
- padding: 1.5rem;
- max-width: 84rem;
- margin: 0 auto;
-}
-
-/* Page header */
-.portal-proc__header {
- display: flex;
- align-items: flex-start;
- justify-content: space-between;
- gap: 1rem;
-}
-
-.portal-proc__title {
- margin: 0;
- font-size: 1.375rem;
- font-weight: 600;
- color: var(--c-text);
-}
-
.portal-proc__subtitle {
margin: 0.25rem 0 0;
font-size: 0.8125rem;
color: var(--c-text-subtle);
}
-/* Eyebrow label shared by the journey header + SE block */
+/* Eyebrow label above a stage panel's heading */
.portal-proc__eyebrow {
display: block;
font-size: 0.6875rem;
@@ -38,613 +14,33 @@
color: var(--c-text-subtle);
margin-bottom: 0.25rem;
}
-
-/* ── Journey card ─────────────────────────────────────────────────────── */
-/* Stacked, border-divided sections: header / stepper / trial / next step. */
-.portal-proc__journey-head {
- display: flex;
- align-items: flex-start;
- justify-content: space-between;
- gap: 1rem;
- padding: 1.25rem 1.5rem;
- border-bottom: 1px solid var(--c-border-subtle);
- flex-wrap: wrap;
-}
-
-.portal-proc__journey-title {
- margin: 0;
- font-size: 1.0625rem;
- font-weight: 700;
- color: var(--c-text);
-}
-
-.portal-proc__journey-sub {
- margin: 0.25rem 0 0;
- max-width: 36rem;
- font-size: 0.8125rem;
- line-height: 1.5;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__se {
- display: flex;
- flex-direction: column;
- text-align: right;
- flex-shrink: 0;
-}
-
-.portal-proc__se .portal-proc__eyebrow {
- margin-bottom: 0.25rem;
-}
-
-.portal-proc__se-name {
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-text);
-}
-
-.portal-proc__se-email {
- font-size: 0.75rem;
- color: var(--c-primary);
- text-decoration: none;
-}
-
-.portal-proc__se-email:hover {
- text-decoration: underline;
-}
-
-/* Stepper band */
-.portal-proc__journey-stepper {
- padding: 1.125rem 1.5rem;
- border-bottom: 1px solid var(--c-border-subtle);
-}
-
-.portal-proc__steps {
- display: flex;
- align-items: flex-start;
-}
-
-.portal-proc__steps--locked {
- opacity: 0.55;
- filter: grayscale(0.4);
- pointer-events: none;
-}
-
-.portal-proc__step {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 0.4rem;
- min-width: 4rem;
-}
-
-.portal-proc__step-dot {
- width: 0.875rem;
- height: 0.875rem;
- border-radius: 50%;
- background: var(--c-border);
-}
-
-.portal-proc__step--complete .portal-proc__step-dot {
- background: var(--color-green);
-}
-
-.portal-proc__step--current .portal-proc__step-dot {
- background: var(--color-purple);
- box-shadow: 0 0 0 4px var(--color-purple-light);
-}
-
-.portal-proc__step-label {
- font-size: 0.6875rem;
- font-weight: 500;
- text-align: center;
- white-space: nowrap;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__step--complete .portal-proc__step-label {
- color: var(--c-text-subtle);
-}
-
-.portal-proc__step--current .portal-proc__step-label {
- font-weight: 700;
- color: var(--c-text);
-}
-
-/* Connector aligns with the 0.875rem dots: (14px − 2px) / 2 = 6px down */
-.portal-proc__step-line {
- flex: 1;
- height: 2px;
- margin: 0.375rem 0.375rem 0;
- background: var(--c-border-subtle);
-}
-
-.portal-proc__step-line[data-filled="true"] {
- background: var(--color-green);
-}
-
-/* Trial status strip (shown while evaluating) */
-.portal-proc__trial {
- display: flex;
- align-items: center;
- gap: 0.625rem;
- flex-wrap: wrap;
- padding: 0.75rem 1.5rem;
- border-bottom: 1px solid var(--c-border-subtle);
- background: var(--color-bg-code);
-}
-
-.portal-proc__trial-title {
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-text);
-}
-
-.portal-proc__trial-dim {
- font-size: 0.78125rem;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__trial-key {
- font-family:
- ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
- font-size: 0.6875rem;
- color: var(--c-text-subtle);
- background: var(--c-surface);
- border: 1px solid var(--c-border);
- border-radius: 0.375rem;
- padding: 0.1875rem 0.5rem;
-}
-
-/* Next-step row: one primary action at a time */
-.portal-proc__next {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 1rem;
- flex-wrap: wrap;
- padding: 1rem 1.5rem;
-}
-
-.portal-proc__next-label {
- display: flex;
- align-items: center;
- gap: 0.625rem;
- font-size: 0.84375rem;
- font-weight: 600;
- color: var(--c-text);
-}
-
-.portal-proc__next-dot {
- width: 0.5rem;
- height: 0.5rem;
- border-radius: 50%;
- background: var(--color-amber);
- flex-shrink: 0;
-}
-
-.portal-proc__next-dot[data-live="true"] {
- background: var(--color-green);
-}
-
-/* ── Documents card ───────────────────────────────────────────────────── */
-.portal-proc__docs-head {
- padding: 1.125rem 1.5rem;
- border-bottom: 1px solid var(--c-border-subtle);
-}
-
-.portal-proc__docs-title {
- margin: 0;
- font-size: 0.9375rem;
- font-weight: 700;
- color: var(--c-text);
-}
-
-.portal-proc__docs-sub {
- margin: 0.25rem 0 0;
- font-size: 0.78125rem;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__docs-body {
- padding: 0.375rem 1.5rem 1.125rem;
-}
-
-/* Accordion spacing — the disclosure chrome itself lives in shared Collapsible
- (.sui-collapsible); here we only space the stacked sections. */
-.portal-proc__docs-body .sui-collapsible {
- margin-top: 0.875rem;
-}
-
-/* Stage header bits */
-.portal-proc__stage-dot {
- width: 0.4375rem;
- height: 0.4375rem;
- border-radius: 50%;
- flex-shrink: 0;
-}
-
-.portal-proc__stage-dot[data-state="done"] {
- background: var(--color-green);
-}
-
-.portal-proc__stage-dot[data-state="current"] {
- background: var(--color-purple);
-}
-
-.portal-proc__stage-dot[data-state="upcoming"] {
- background: var(--c-border);
-}
-
-.portal-proc__stage-label {
- font-size: 0.75rem;
- font-weight: 700;
- letter-spacing: 0.03em;
- text-transform: uppercase;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__stage-label[data-current] {
- color: var(--c-text);
-}
-
-.portal-proc__stage-hint {
- font-size: 0.71875rem;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__stage-count {
- font-size: 0.6875rem;
- color: var(--c-text-subtle);
-}
-
-/* Document lists inside the accordion */
-.portal-proc__doc-list {
- border-top: 1px solid var(--c-border-subtle);
-}
-
-.portal-proc__doc-list--boxed {
- border: 1px solid var(--c-border-subtle);
- border-radius: 0.5rem;
- overflow: hidden;
-}
-
-/* Supporting section — extra separation from the stage accordion above it.
- Scoped to match the general .sui-collapsible spacing rule's specificity. */
-.portal-proc__docs-body .portal-proc__supporting-acc {
- margin-top: 1.5rem;
-}
-
-.portal-proc__supporting-head {
- display: flex;
- flex-direction: column;
- gap: 0.125rem;
- min-width: 0;
-}
-
-.portal-proc__supporting-sub {
- font-size: 0.71875rem;
- font-weight: 400;
- line-height: 1.45;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__acc-toggle-label {
- font-size: 0.75rem;
- font-weight: 600;
- color: var(--c-primary);
-}
-
-.portal-proc__supporting-groups {
- display: flex;
- flex-direction: column;
- gap: 1rem;
- border-top: 1px solid var(--c-border-subtle);
- padding: 0.875rem;
-}
-
-.portal-proc__group-label {
- font-size: 0.6875rem;
- font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: var(--c-text-subtle);
- margin-bottom: 0.5rem;
-}
-
-/* ── Document rows (ledger + supporting) ──────────────────────────────── */
-.portal-proc__doc {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 1rem;
- padding: 0.75rem 0.875rem;
- border-bottom: 1px solid var(--c-border-subtle);
-}
-
-.portal-proc__doc:last-child {
- border-bottom: none;
-}
-
-.portal-proc__doc[data-locked] {
- opacity: 0.6;
-}
-
-.portal-proc__doc-text {
- min-width: 0;
-}
-
-.portal-proc__doc-name-row {
- display: flex;
- align-items: center;
- gap: 0.5rem;
- flex-wrap: wrap;
-}
-
-.portal-proc__doc-name {
- font-size: 0.84375rem;
- font-weight: 600;
- color: var(--c-text);
-}
-
-.portal-proc__doc-sub {
- margin: 0.0625rem 0 0;
- font-size: 0.71875rem;
- line-height: 1.4;
- color: var(--c-text-subtle);
-}
-
-.portal-proc__doc-actions {
- display: flex;
- align-items: center;
- gap: 0.75rem;
- flex-shrink: 0;
-}
-
-/* ── Locked state ─────────────────────────────────────────────────────── */
-.portal-proc__locked {
- display: flex;
- flex-direction: column;
- gap: 1.25rem;
-}
-
-/* ── Action modal ─────────────────────────────────────────────────────── */
-.portal-proc__modal-body {
- margin: 0 0 1rem;
- font-size: 0.875rem;
- line-height: 1.55;
- color: var(--c-text-muted);
-}
-
-.portal-proc__modal-actions {
- display: flex;
- align-items: center;
- justify-content: flex-end;
- gap: 0.625rem;
-}
-
-.portal-proc__upload {
- display: flex;
- align-items: center;
- gap: 0.75rem;
-}
-
-.portal-proc__upload-input {
- display: none;
-}
-
-.portal-proc__upload-name {
- font-size: 0.75rem;
- color: var(--c-text-subtle);
-}
-
-@media (max-width: 48rem) {
- .portal-proc__journey-head {
- flex-direction: column;
- }
-
- .portal-proc__se {
- text-align: left;
- }
-
- .portal-proc__steps {
- overflow-x: auto;
- }
-}
-
-/* ── Enterprise upsell CTA (Home / Usage on-ramp) ─────────────────────────── */
-.portal-proc__upsell {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 1rem;
- flex-wrap: wrap;
-}
-.portal-proc__upsell-badge {
- display: inline-block;
- font-size: 0.625rem;
- font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 0.06em;
- color: var(--c-primary);
- background: var(--c-primary-subtle);
- padding: 0.15rem 0.5rem;
- border-radius: 0.375rem;
- margin-bottom: 0.4rem;
-}
-.portal-proc__upsell-copy {
- margin: 0;
- font-size: 0.8125rem;
- line-height: 1.45;
- color: var(--c-text-subtle);
- max-width: 44rem;
-}
-.portal-proc__upsell-copy strong {
- color: var(--c-text);
-}
-
-/* ── Quote builder ────────────────────────────────────────────────────────── */
-.portal-proc__builder-head {
- display: flex;
- align-items: baseline;
- justify-content: space-between;
- margin-bottom: 1rem;
-}
.portal-proc__builder-title {
margin: 0;
font-size: 1rem;
font-weight: 650;
color: var(--c-text);
}
-.portal-proc__builder-step {
- font-size: 0.75rem;
- color: var(--c-text-subtle);
-}
-.portal-proc__builder-body {
- display: flex;
- flex-direction: column;
- gap: 0.85rem;
-}
-.portal-proc__field {
- display: flex;
- flex-direction: column;
- gap: 0.3rem;
- font-size: 0.8125rem;
- color: var(--c-text-subtle);
-}
-.portal-proc__field input,
-.portal-proc__field select {
- padding: 0.45rem 0.6rem;
- border: 1px solid var(--c-border);
- border-radius: 0.5rem;
- font-size: 0.875rem;
- background: var(--c-input-bg);
- color: var(--c-text);
-}
-.portal-proc__builder-addons {
- display: flex;
- flex-direction: column;
- gap: 0.4rem;
- font-size: 0.8125rem;
- color: var(--c-text-muted);
-}
-.portal-proc__builder-addons label {
- display: flex;
- align-items: center;
- gap: 0.5rem;
-}
-.portal-proc__builder-actions {
- display: flex;
- justify-content: flex-end;
- gap: 0.6rem;
- margin-top: 0.5rem;
-}
-.portal-proc__quote-head {
- display: flex;
- align-items: baseline;
- justify-content: space-between;
- border-bottom: 1px solid var(--c-border);
- padding-bottom: 0.5rem;
-}
-.portal-proc__quote-number {
- font-weight: 650;
- color: var(--c-text);
-}
-.portal-proc__quote-valid {
- font-size: 0.75rem;
- color: var(--c-text-subtle);
-}
-.portal-proc__quote-lines {
- list-style: none;
- margin: 0;
- padding: 0;
-}
-.portal-proc__quote-lines li {
- display: flex;
- justify-content: space-between;
- padding: 0.4rem 0;
- font-size: 0.8125rem;
- color: var(--c-text-muted);
- border-bottom: 1px solid var(--c-border-subtle);
-}
-.portal-proc__quote-lines li[data-kind="DISCOUNT"] {
- color: var(--c-success);
-}
-.portal-proc__quote-total {
- display: flex;
- justify-content: space-between;
- align-items: baseline;
- padding: 0.6rem 0 0.2rem;
- font-size: 0.9375rem;
-}
-.portal-proc__quote-total strong {
- font-size: 1.25rem;
- color: var(--c-text);
-}
-.portal-proc__quote-tcv {
- font-size: 0.75rem;
- color: var(--c-text-subtle);
-}
/* ══ Quote builder — copied from the marketing prototype (tight density) ═════ */
.portal-qb {
- background: var(--c-surface);
- border: 1px solid var(--c-border);
- border-radius: 14px;
- box-shadow: inset 0 0 0 1px var(--c-border-subtle);
- overflow: hidden;
-}
-.portal-qb__head {
display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 18px 24px 14px;
- border-bottom: 1px solid var(--c-border-subtle);
- background: linear-gradient(
- 180deg,
- color-mix(in srgb, var(--c-primary) 5.5%, transparent) 0%,
- transparent 100%
- );
-}
-.portal-qb__title {
- margin: 0;
- font-size: 16px;
- font-weight: 700;
- color: var(--c-text);
-}
-.portal-qb__stepchip {
- font-size: 11px;
- font-weight: 700;
- color: var(--c-text-subtle);
- background: var(--c-surface-sunken);
- padding: 3px 10px;
- border-radius: 999px;
-}
-.portal-qb__progress {
- display: flex;
- gap: 6px;
- padding: 12px 24px 0;
-}
-.portal-qb__progress span {
- flex: 1;
- height: 6px;
- border-radius: 999px;
- background: var(--c-surface-sunken);
- transition: background 0.3s;
-}
-.portal-qb__progress span[data-on] {
- background: var(--c-primary);
+ flex-direction: column;
}
+/* No padding or scroll of its own: FlowModal's panel supplies both, and nesting a second scroll
+ container inside a scrolling panel gave the builder two scrollbars. */
+/* This gap is the builder's only vertical rhythm: the blocks inside carry no bottom margins of their
+ own, so spacing cannot double up the way a margin plus a gap did. The top margin is the breathing
+ room under the stepped header, which deliberately has no bottom margin so its host sets this. */
.portal-qb__body {
- padding: 20px 24px;
- max-height: 56vh;
- overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ margin-top: 1.05rem;
}
.portal-qb__intro {
display: flex;
align-items: center;
gap: 12px;
- margin-bottom: 18px;
}
.portal-qb__intro-icon {
width: 38px;
@@ -667,9 +63,10 @@
color: var(--c-text-subtle);
margin-top: 1px;
}
+/* No bottom margin: inside .portal-qb__body the gap spaces these, and inside .portal-qb__row a
+ margin only reserved dead space under the inputs. */
.portal-qb__field {
display: block;
- margin-bottom: 18px;
}
.portal-qb__field-label {
display: block;
@@ -691,6 +88,18 @@
background: var(--c-input-bg);
color: var(--c-text);
}
+.portal-qb__req {
+ color: var(--c-danger);
+}
+.portal-qb__field[data-invalid] input,
+.portal-qb__field[data-invalid] select {
+ border-color: var(--c-danger);
+}
+.portal-qb__error {
+ margin: 10px 0 0;
+ font-size: 12px;
+ color: var(--c-danger);
+}
.portal-qb__row {
display: flex;
gap: 14px;
@@ -701,7 +110,7 @@
min-width: 190px;
}
.portal-qb__hint {
- margin: 7px 0 0;
+ margin: 0;
font-size: 11.5px;
color: var(--c-text-subtle);
line-height: 1.4;
@@ -736,11 +145,22 @@
gap: 10px;
flex-wrap: wrap;
}
+/* Short-label options that should sit across one row rather than wrapping 2 + 1. Tighter padding
+ and label size so each caption fits on a single line at three-across. Deliberately no `nowrap`:
+ a longer translation should wrap rather than clip or push the card out of the row. */
+.portal-qb__opts--across .portal-qb__opt {
+ min-width: 0;
+ padding: 11px 12px;
+}
+.portal-qb__opts--across .portal-qb__opt-sub {
+ font-size: 11px;
+ line-height: 1.35;
+}
.portal-qb__opt {
text-align: left;
flex: 1;
min-width: 150px;
- padding: 12px 14px;
+ padding: 9px 11px;
border-radius: 9px;
border: 1px solid var(--c-border);
background: var(--c-surface);
@@ -834,7 +254,11 @@
align-items: center;
justify-content: space-between;
gap: 12px;
- padding: 14px 24px;
+ /* Bleeds to the panel's edges by reading the shell's own inset, so changing FlowModal's padding
+ can no longer leave this footer stopping short of them. */
+ margin: 0.85rem calc(-1 * var(--flowmodal-inset))
+ calc(-1 * var(--flowmodal-body-end));
+ padding: 0.8rem var(--flowmodal-inset) 0.9rem;
border-top: 1px solid var(--c-border-subtle);
flex-wrap: wrap;
}
@@ -846,13 +270,13 @@
display: flex;
gap: 10px;
}
-/* Step 4 — the itemised quote paper */
+/* Step 4 — the itemised quote paper, on a sunken tray that runs to the panel's edges. No scroll of
+ its own: the dialog body already scrolls, and nesting a second scroller gave the builder two
+ scrollbars. The bleed reads the shell's inset rather than hard-coding a copy of it. */
.portal-qb__papertray {
background: var(--c-surface-sunken);
- padding: 18px;
- max-height: 56vh;
- overflow-y: auto;
- margin: -20px -24px;
+ padding: 14px var(--flowmodal-inset);
+ margin: 0 calc(-1 * var(--flowmodal-inset));
}
.portal-qb__paper {
background: var(--c-surface);
@@ -880,6 +304,11 @@
.portal-qb__paper-meta {
text-align: right;
}
+/* Reads as a link on the document rather than a button in a toolbar: right-aligned under the quote's
+ own metadata, with the row's padding trimmed so it sits tight to the date above it. */
+.portal-qb__paper-download {
+ margin: 0.2rem -0.5rem -0.25rem 0;
+}
.portal-qb__quote-number {
font-size: 12.5px;
font-weight: 700;
@@ -955,27 +384,24 @@
margin-top: 3px;
}
-/* ── Enterprise upsell text wrapper (Home on-ramp) ────────────────────────── */
-.portal-proc__upsell-text {
- flex: 1 1 20rem;
-}
-
/* ── Deal-status hero (Home, active deal) ─────────────────────────────────── */
.portal-hero {
border: 1px solid var(--c-border);
border-radius: 12px;
padding: 1.1rem 1.25rem;
- background:
- radial-gradient(
- 120% 140% at 100% 0%,
- color-mix(in srgb, var(--c-hue-violet) 8%, transparent),
- transparent 55%
- ),
- var(--c-surface);
+ background: var(--c-surface);
display: flex;
flex-direction: column;
gap: 1rem;
}
+
+/* Attached under the editor rail the two read as one card, so the hero drops its standalone frame
+ and lets the footer's top border be the only seam. It keeps the frame on the procurement view,
+ where it stands alone. */
+.portal-editor-hero__footer .portal-hero {
+ border: none;
+ border-radius: 0;
+}
.portal-hero__top {
display: flex;
align-items: flex-start;
@@ -983,25 +409,56 @@
gap: 1rem;
flex-wrap: wrap;
}
+.portal-hero__ident {
+ flex: 1;
+ min-width: 0;
+}
.portal-hero__eyebrow {
display: block;
font-size: 0.6875rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.06em;
- color: var(--c-primary);
+ color: var(--c-text-subtle);
+ margin-bottom: 0.55rem;
}
-.portal-hero__company {
- display: block;
- font-size: 1.0625rem;
- font-weight: 650;
+/* The journey band: one segment per stage, filled through the current one. A progress indicator,
+ so it lives inside the block whose progress it reports and deliberately does not pulse. */
+.portal-hero__bar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 0.625rem;
+}
+.portal-hero__bar span {
+ flex: 1;
+ height: 6px;
+ border-radius: 999px;
+ background: var(--c-hover);
+ transition: background 0.3s ease;
+}
+.portal-hero__bar span[data-on] {
+ background: var(--c-primary);
+}
+/* The hero's one-line status: bold stage · what it asks, then Next: … */
+.portal-hero__sentence {
+ margin: 0;
+ font-size: 0.84375rem;
+ line-height: 1.5;
+ color: var(--c-text-muted);
+}
+.portal-hero__sentence strong {
+ font-weight: 700;
color: var(--c-text);
- margin-top: 0.2rem;
+}
+.portal-hero__sentence-next {
+ color: var(--c-text-subtle);
}
.portal-hero__chips {
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
+ margin-top: 0.5rem;
}
.portal-hero__chip {
font-size: 0.6875rem;
@@ -1011,88 +468,74 @@
border-radius: 999px;
padding: 0.2rem 0.6rem;
}
-.portal-hero__stepper {
- overflow-x: auto;
-}
-.portal-hero__next {
+/* One action row: the stage's primary CTA leads, quiet icon actions sit beside it. No dividers. */
+.portal-hero__cta {
display: flex;
align-items: center;
- justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
- padding-top: 0.85rem;
- border-top: 1px solid var(--c-border-subtle);
}
-.portal-hero__next-label {
+.portal-hero__icons {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+.portal-hero__iconbtn {
+ width: 34px;
+ height: 34px;
display: inline-flex;
align-items: center;
- gap: 0.45rem;
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-text-muted);
-}
-.portal-hero__next-dot {
- width: 0.5rem;
- height: 0.5rem;
- border-radius: 999px;
- background: var(--c-primary);
- box-shadow: 0 0 0 3px var(--c-primary-subtle);
-}
-
-/* ── Full-screen takeover modal (procurement flow) ────────────────────────── */
-.portal-procmodal {
- position: fixed;
- inset: 0;
- z-index: 1000;
- display: flex;
- align-items: flex-start;
justify-content: center;
- padding: clamp(0.5rem, 4vh, 3rem) 1rem;
- overflow-y: auto;
- background: var(--c-overlay);
- backdrop-filter: blur(6px) saturate(160%);
- -webkit-backdrop-filter: blur(6px) saturate(160%);
- animation: portal-procmodal-fade 0.15s ease-out;
-}
-@keyframes portal-procmodal-fade {
- from {
- opacity: 0;
- }
- to {
- opacity: 1;
- }
-}
-.portal-procmodal__panel {
- position: relative;
- width: 100%;
- max-width: 62rem;
- background: var(--c-surface);
+ border-radius: 9px;
border: 1px solid var(--c-border);
- border-radius: 14px;
- box-shadow: 0 24px 64px rgba(0, 0, 0, 0.28);
- padding: 1.5rem 1.5rem 1.75rem;
-}
-.portal-procmodal__close {
- position: absolute;
- top: 0.85rem;
- right: 0.85rem;
- border: none;
- background: var(--c-border-subtle);
- color: var(--c-text-subtle);
- width: 1.9rem;
- height: 1.9rem;
- border-radius: 8px;
- font-size: 0.85rem;
+ background: var(--c-surface);
+ color: var(--c-text-muted);
cursor: pointer;
+ transition:
+ background 0.15s ease,
+ border-color 0.15s ease,
+ color 0.15s ease;
}
-.portal-procmodal__close:hover {
- background: var(--c-border);
+.portal-hero__iconbtn:hover {
+ background: var(--c-hover);
+ border-color: var(--c-border-strong);
color: var(--c-text);
}
-.portal-procmodal__header {
- margin-bottom: 1.25rem;
- padding-right: 2.5rem;
+/* Terminal state: the deal is done, so the row reports rather than asks. */
+.portal-hero__live {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
}
+.portal-hero__live-tile {
+ width: 40px;
+ height: 40px;
+ flex-shrink: 0;
+ border-radius: 11px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ /* Holds a CheckIcon, which takes its stroke from `color` and its size from its own prop. */
+ color: var(--c-success);
+ background: var(--c-success-subtle);
+}
+.portal-hero__live-text {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+}
+.portal-hero__live-title {
+ font-size: 0.90625rem;
+ font-weight: 700;
+ color: var(--c-text);
+}
+.portal-hero__live-sub {
+ font-size: 0.78125rem;
+ color: var(--c-text-subtle);
+ margin-top: 1px;
+}
+
+/* ── Procurement takeover: heading type only, the shell is the shared Modal ── */
.portal-procmodal__title {
margin: 0;
font-size: 1.35rem;
@@ -1104,15 +547,6 @@
font-size: 0.875rem;
color: var(--c-text-subtle);
}
-.portal-procmodal__body {
- display: flex;
- flex-direction: column;
- gap: 1.25rem;
-}
-
-.portal-proc__modal-stepper {
- overflow-x: auto;
-}
.portal-proc__payment-actions {
display: flex;
gap: 0.6rem;
@@ -1124,7 +558,7 @@
padding: 1rem;
border: 1px solid var(--c-border);
border-radius: 0.6rem;
- background: var(--color-surface-2, rgba(0, 0, 0, 0.02));
+ background: var(--c-surface-sunken);
}
.portal-proc__license-label {
display: block;
@@ -1139,7 +573,7 @@
margin-top: 0.4rem;
padding: 0.55rem 0.7rem;
border-radius: 0.4rem;
- background: var(--color-surface-3, rgba(0, 0, 0, 0.05));
+ background: var(--c-surface-raised);
font-family: var(--font-mono, monospace);
font-size: 0.85rem;
word-break: break-all;
@@ -1150,45 +584,9 @@
font-size: 0.75rem;
color: var(--c-text-subtle, var(--c-text-muted));
}
-.portal-proc__milestone-for {
- margin: 0.15rem 0 0;
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-text-muted);
-}
-.portal-proc__milestone-lines {
- margin: 0.85rem 0 0.5rem;
-}
-.portal-proc__milestone-totals {
- display: flex;
- align-items: baseline;
- gap: 1rem;
- flex-wrap: wrap;
- margin: 0.75rem 0 0.25rem;
-}
-.portal-proc__milestone-annual {
- font-size: 1.75rem;
- font-weight: 700;
- color: var(--c-text);
-}
-.portal-proc__milestone-annual small {
- font-size: 0.8125rem;
- font-weight: 500;
- color: var(--c-text-subtle);
-}
-.portal-proc__milestone-tcv {
- font-size: 0.8125rem;
- color: var(--c-text-subtle);
-}
/* Hero next-step action row (primary CTA + optional extend-trial). */
-.portal-hero__next-actions {
- display: flex;
- gap: 0.5rem;
- flex-wrap: wrap;
-}
-
-/* Hero quick-action chips (clickable pills next to the company name). */
+/* Hero quick-action chips (the trial countdown pill under the stage sentence). */
.portal-hero__chip--action {
border: 1px solid var(--c-border);
cursor: pointer;
@@ -1203,101 +601,8 @@
transform: translateY(-1px);
}
-/* Hero rollout checklist (trial): the "do this now" setup steps. */
-.portal-hero__checklist {
- list-style: none;
- margin: 0;
- padding: 0;
- border-top: 1px solid var(--c-border-subtle);
-}
-.portal-hero__checklist li {
- border-bottom: 1px solid var(--c-border-subtle);
-}
-.portal-hero__checklist button {
- display: flex;
- align-items: center;
- gap: 0.85rem;
- width: 100%;
- padding: 0.7rem 0.25rem;
- background: none;
- border: none;
- cursor: pointer;
- text-align: left;
-}
-.portal-hero__checklist button:hover {
- background: var(--c-hover, var(--c-border-subtle));
-}
-.portal-hero__check-dot {
- width: 0.5rem;
- height: 0.5rem;
- border-radius: 999px;
- background: var(--c-border);
- flex-shrink: 0;
-}
-.portal-hero__check-text {
- flex: 1;
- min-width: 0;
-}
-.portal-hero__check-title {
- display: block;
- font-size: 0.85rem;
- font-weight: 600;
- color: var(--c-text);
-}
-.portal-hero__check-sub {
- display: block;
- font-size: 0.75rem;
- color: var(--c-text-subtle);
- margin-top: 0.05rem;
-}
-.portal-hero__check-pill {
- font-size: 0.6875rem;
- font-weight: 600;
- color: var(--c-text-subtle);
- background: var(--c-border-subtle);
- border-radius: 999px;
- padding: 0.15rem 0.55rem;
- flex-shrink: 0;
-}
-
/* ── Side dialogs (Key documents / Schedule a call / Trial) ───────────────── */
-.portal-sidemodal {
- position: fixed;
- inset: 0;
- z-index: 1100;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 1rem;
- overflow-y: auto;
- background: var(--c-overlay);
- backdrop-filter: blur(4px);
- -webkit-backdrop-filter: blur(4px);
- animation: portal-procmodal-fade 0.15s ease-out;
- /* Portaled to , outside .portal-scope, so set the portal UI font explicitly. */
- font-family: var(--font-sans);
-}
-.portal-sidemodal__panel {
- position: relative;
- width: 100%;
- max-width: 30rem;
- background: var(--c-surface);
- border: 1px solid var(--c-border);
- border-radius: 14px;
- box-shadow: 0 24px 64px rgba(0, 0, 0, 0.28);
- padding: 1.35rem 1.4rem 1.4rem;
- max-height: 86vh;
- overflow-y: auto;
-}
-/* Wide enough for Calendly's two-pane layout (its single-column layout below ~680px inner width is
- tall and scrolls); paired with the embed's taller fixed height so the time view needs no scroll. */
-.portal-sidemodal__panel--wide {
- max-width: 52rem;
-}
-.portal-sidemodal__header {
- margin-bottom: 1rem;
- padding-right: 2rem;
-}
+/* Chrome and width come from the shared Modal via FlowModal; only type and content live here. */
.portal-sidemodal__title {
margin: 0;
font-size: 1.05rem;
@@ -1316,15 +621,6 @@
color: var(--c-text-subtle);
line-height: 1.55;
}
-.portal-sidemodal__footer {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 0.75rem;
- margin-top: 1.1rem;
- padding-top: 0.9rem;
- border-top: 1px solid var(--c-border-subtle);
-}
.portal-sidemodal__ghost {
border: none;
background: none;
@@ -1336,63 +632,6 @@
color: var(--c-text-muted);
}
-/* Key documents ledger. */
-.portal-docs__group + .portal-docs__group {
- margin-top: 1rem;
-}
-.portal-docs__group-title {
- font-size: 0.6875rem;
- font-weight: 700;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: var(--c-text-subtle);
- margin-bottom: 0.4rem;
-}
-.portal-docs__list {
- list-style: none;
- margin: 0;
- padding: 0;
-}
-.portal-docs__row {
- display: flex;
- align-items: center;
- gap: 0.75rem;
- padding: 0.55rem 0;
- border-top: 1px solid var(--c-border-subtle);
-}
-.portal-docs__row-text {
- flex: 1;
- min-width: 0;
-}
-.portal-docs__row-name {
- display: block;
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--c-text);
-}
-.portal-docs__row-sub {
- display: block;
- font-size: 0.72rem;
- color: var(--c-text-subtle);
- margin-top: 0.05rem;
-}
-.portal-docs__row-action {
- font-size: 0.6875rem;
- font-weight: 600;
- border-radius: 999px;
- padding: 0.2rem 0.6rem;
- flex-shrink: 0;
- color: var(--c-text-subtle);
- background: var(--c-border-subtle);
-}
-.portal-docs__row-action[data-status="action"] {
- color: var(--c-primary);
- background: var(--c-primary-subtle);
-}
-.portal-docs__row-action[data-status="request"] {
- color: var(--c-text-subtle);
-}
-
/* Calendly scheduler embed (Schedule a call). The widget is always light (Calendly renders inputs on
white), so give it a white surface — it reads as a clean card even inside the dark-mode modal. */
.portal-calendly {
@@ -1418,17 +657,173 @@
}
/* ── Agreement (security) step ────────────────────────────────────────────── */
-.portal-agreement__doc {
- margin: 1rem 0;
- max-height: 22rem;
- overflow-y: auto;
- padding: 1rem 1.1rem;
- border: 1px solid var(--c-border);
- border-radius: 10px;
- background: var(--color-bg-subtle, var(--c-bg));
- font-size: 0.8125rem;
- line-height: 1.55;
+/* The terminal steps (payment, live): a stacked eyebrow/title/description with the flow's own footer
+ bar beneath. No card of their own — the dialog is already the surface. */
+.portal-procstage {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4rem;
+}
+/* Nothing to report on the left of these, so the actions take the whole bar. */
+.portal-procstage__foot {
+ justify-content: flex-end;
+}
+
+/* The two document actions read as a pair, close together and set apart from the close beside them. */
+.portal-agreement__actions {
+ display: flex;
+ align-items: center;
+ gap: 0.1rem;
+}
+
+/* The signature block: the three fields that name the bound party and its signatory, on the same line
+ as the act of signing, with the consent directly beneath them and no rule between. Fields shrink
+ below the row's usual floor so all three plus the button hold one line at the takeover's width;
+ they wrap rather than clip if a translation runs long. */
+/* No rule above it: the tray's grey ends where the signature block begins, which is boundary enough,
+ and a border there cut the document off from the page it sits on. */
+.portal-agreement__signbar {
+ flex-direction: column;
+ align-items: stretch;
+ gap: 0.6rem;
+ border-top: none;
+}
+/* Bottom-aligned: a field is a label above an input, so aligning to the block's centre or its top
+ leaves the button off the input row. Sharing the input's bottom edge puts its centre on theirs, both
+ being 37px. The gate note is deliberately NOT in this row — hanging it off the button would make the
+ column taller than the fields and drag the button back up off the row. */
+.portal-agreement__signrow {
+ display: flex;
+ align-items: flex-end;
+ gap: 0.9rem;
+}
+/* Consent on the left, the gate's state on the right so it lands under the button it explains. */
+.portal-agreement__signfoot {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 1rem;
+}
+.portal-agreement__gate {
+ flex: 0 0 auto;
+ font-size: 0.6875rem;
color: var(--c-text-subtle);
+ white-space: nowrap;
+}
+.portal-agreement__signrow .portal-agreement__signfields {
+ flex: 1;
+ gap: 0.6rem;
+ min-width: 0;
+}
+.portal-agreement__signrow .portal-qb__field {
+ min-width: 8.5rem;
+}
+/* Unboxed: a line of small print under the fields, not a panel competing with the document. */
+.portal-agreement__accept {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.5rem;
+ font-size: 0.75rem;
+ line-height: 1.45;
+ color: var(--c-text-subtle);
+ cursor: pointer;
+}
+.portal-agreement__accept input {
+ margin: 0.1rem 0 0;
+ flex: 0 0 auto;
+}
+
+/* The agreement is presented as paper, not as app copy in a box: a sunken tray running to the panel's
+ edges, with the terms on white stock in a serif face. Signing is the most consequential thing a
+ buyer does here, so the document should read like the document it is. */
+/* The document takes every pixel the dialog can spare: it is what the buyer is here to read, and a
+ fixed height left it a small white box floating in a tall panel. The chain has to carry the fill —
+ each link needs min-height:0 or a flex child refuses to shrink below its content. */
+.portal-agreement {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ flex: 1 1 auto;
+ min-height: 0;
+}
+/* The tray is the scroll container, so the paper inside it behaves like a page being scrolled past a
+ window: flush to the footer while there is more to read, and revealing the tray's bottom padding
+ only at the end. Scrolling the paper instead left a permanent grey band under it, which read as a
+ box with contents rather than a document. */
+/* `scroll`, not `auto`, and an explicitly styled bar: signing is gated on reaching the end of the
+ document, so the buyer has to be able to see there is more of it and how far through they are.
+ Overlay scrollbars fade out when idle, which hid both. Styling the bar also opts Chromium out of
+ overlay behaviour, so it stays put. Matches the treatment on the files page. */
+.portal-agreement__tray {
+ background: var(--c-surface-sunken);
+ padding: 14px var(--flowmodal-inset);
+ margin: 0 calc(-1 * var(--flowmodal-inset));
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: scroll;
+ scrollbar-width: thin;
+ scrollbar-color: var(--c-text-subtle) var(--c-border-subtle);
+}
+.portal-agreement__tray::-webkit-scrollbar {
+ width: 0.625rem;
+}
+.portal-agreement__tray::-webkit-scrollbar-track {
+ background: var(--c-border-subtle);
+ border-radius: 999px;
+}
+.portal-agreement__tray::-webkit-scrollbar-thumb {
+ background: var(--c-text-subtle);
+ border-radius: 999px;
+ border: 2px solid transparent;
+ background-clip: content-box;
+}
+.portal-agreement__tray::-webkit-scrollbar-thumb:hover {
+ background: var(--c-text-muted);
+ background-clip: content-box;
+}
+.portal-agreement__doc {
+ /* A floor so a short document still reads as a page; no ceiling, so a long one runs on and the tray
+ does the scrolling. */
+ min-height: 16rem;
+ padding: 1.35rem 1.6rem;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: 12px;
+ background: var(--c-surface);
+ box-shadow: var(--shadow-sm);
+ /* No serif token exists in the theme — the serif is specific to rendering legal terms as paper. */
+ font-family: Georgia, "Times New Roman", "Liberation Serif", serif;
+ font-size: 0.84rem;
+ line-height: 1.62;
+ color: var(--c-text-muted);
+}
+/* Masthead above the document's own heading: confidentiality on the left, the quote reference and
+ signed version on the right, over the rule that opens the terms. */
+.portal-agreement__letterhead {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 1rem;
+ flex-wrap: wrap;
+ padding-bottom: 0.6rem;
+ margin-bottom: 1rem;
+ border-bottom: 2px solid var(--c-text);
+ font-family: var(--font-sans);
+ font-size: 0.6875rem;
+ letter-spacing: 0.04em;
+ color: var(--c-text-subtle);
+}
+.portal-agreement__confidential {
+ font-weight: 700;
+ text-transform: uppercase;
+}
+/* The document's own title, centred like an executed agreement's. */
+.portal-agreement__md > h1:first-child,
+.portal-agreement__md > h2:first-child {
+ text-align: center;
+ font-size: 1.05rem;
+ letter-spacing: 0.02em;
+ text-transform: uppercase;
+ margin-bottom: 1rem;
}
.portal-agreement__doc h4 {
margin: 1rem 0 0.35rem;
@@ -1445,29 +840,129 @@
.portal-agreement__doc strong {
color: var(--c-text);
}
-.portal-agreement__accept {
- margin-top: 0.25rem;
+.portal-agreement__md h1 {
+ font-size: 0.95rem;
+ font-weight: 700;
+ color: var(--c-text);
+ margin: 1.1rem 0 0.5rem;
}
-.portal-agreement__lines {
- margin: 0.4rem 0 0.6rem;
+.portal-agreement__md h2 {
+ font-size: 0.875rem;
+ font-weight: 650;
+ color: var(--c-text);
+ margin: 1rem 0 0.4rem;
}
-.portal-proc__reset {
- display: flex;
- justify-content: center;
- padding-top: 0.5rem;
+.portal-agreement__md h3 {
+ font-size: 0.8125rem;
+ font-weight: 650;
+ color: var(--c-text);
+ margin: 0.9rem 0 0.3rem;
}
-.portal-proc__reset button {
+.portal-agreement__md h1:first-child,
+.portal-agreement__md h2:first-child {
+ margin-top: 0;
+}
+.portal-agreement__md p {
+ margin: 0 0 0.55rem;
+}
+.portal-agreement__md strong {
+ color: var(--c-text);
+}
+.portal-agreement__md ul {
+ margin: 0 0 0.6rem;
+ padding-left: 1.1rem;
+}
+.portal-agreement__md li {
+ margin-bottom: 0.2rem;
+}
+.portal-agreement__md table {
+ border-collapse: collapse;
+ width: 100%;
+ margin: 0.4rem 0 0.8rem;
+ font-size: 0.78rem;
+}
+.portal-agreement__md th,
+.portal-agreement__md td {
+ border: 1px solid var(--c-border);
+ padding: 0.35rem 0.5rem;
+ text-align: left;
+ vertical-align: top;
+}
+.portal-agreement__md th {
+ background: var(--c-bg);
+ font-weight: 650;
+ color: var(--c-text);
+}
+.portal-agreement__signfields {
+ margin-top: 0.75rem;
+}
+.portal-proc__error {
+ color: var(--c-danger);
+ font-size: 0.8125rem;
+ margin: 0.5rem 0 0;
+}
+.portal-legal__link {
border: none;
background: none;
+ padding: 0;
+ font: inherit;
+ color: var(--c-text);
+ text-decoration: underline;
+ cursor: pointer;
+}
+.portal-legal__link:hover {
+ color: var(--c-text);
+}
+.portal-docmodal {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+}
+.portal-docmodal__row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ padding: 0.85rem 0;
+ border-bottom: 1px solid var(--c-border);
+}
+.portal-docmodal__row:last-child {
+ border-bottom: none;
+}
+.portal-docmodal__text {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ min-width: 0;
+}
+.portal-docmodal__name {
+ font-weight: 650;
+ font-size: 0.875rem;
+ color: var(--c-text);
+}
+.portal-docmodal__sub {
+ font-size: 0.75rem;
+ color: var(--c-text-muted);
+}
+.portal-docmodal__later {
+ flex-shrink: 0;
font-size: 0.75rem;
color: var(--c-text-subtle);
- cursor: pointer;
- text-decoration: underline;
+ white-space: nowrap;
}
-.portal-proc__reset button:hover:not(:disabled) {
+
+/* Title row: the step badge rides beside the heading, not on a line of its own. */
+.portal-sidemodal__title-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+}
+
+/* Quiet hint sat opposite the primary action in a dialog footer. */
+.portal-sidemodal__foot-hint {
+ font-size: 0.75rem;
color: var(--c-text-subtle);
}
-.portal-proc__reset button:disabled {
- opacity: 0.5;
- cursor: default;
-}
diff --git a/frontend/editor/src/portal/views/Procurement.tsx b/frontend/editor/src/portal/views/Procurement.tsx
deleted file mode 100644
index 1f6e2329a9..0000000000
--- a/frontend/editor/src/portal/views/Procurement.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { ProcurementHome } from "@portal/components/procurement/ProcurementHome";
-import "@portal/views/Procurement.css";
-
-/**
- * /procurement — procurement is no longer a nav tab; it lives on Home as the deal-status hero.
- * This route is kept for deep links (and the Usage "Build your quote" CTA): it renders the same
- * surface, opening the takeover modal once a deal is underway.
- */
-export function Procurement() {
- return (
-
-
-
- );
-}
diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjs
index d2853d8f1e..256bdf640a 100644
--- a/frontend/eslint.config.mjs
+++ b/frontend/eslint.config.mjs
@@ -258,12 +258,7 @@ export default defineConfig(
// can't represent. Exempt ONLY the raw- rule; the Mantine import bans
// stay. Migrate these alongside the procurement buttons.
{
- files: [
- "editor/src/portal/components/EditorStatusCard.tsx",
- "editor/src/portal/components/SetupChecklist.tsx",
- "editor/src/portal/components/WelcomeBanner.tsx",
- "editor/src/portal/components/DownloadEditorModal.tsx",
- ],
+ files: ["editor/src/portal/components/DownloadEditorModal.tsx"],
rules: {
"no-restricted-syntax": ["error", ...mantineComponentImportRestrictions],
},
From 789be2d3519d205073711882ca89d1fa2ce4431b Mon Sep 17 00:00:00 2001
From: EthanHealy01 <80844253+EthanHealy01@users.noreply.github.com>
Date: Wed, 5 Aug 2026 17:31:24 +0100
Subject: [PATCH 05/99] Non-blocking classification, pipelined batch
enforcement, and selector-based file-state re-renders (#7085)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Goal
Three related improvements to how policies and file state behave in the
editor: classification no longer blocks the user, policy enforcement
pipelines across a batch upload instead of waiting for the whole drop,
and file-state changes no longer re-render the entire UI.
## 1. Classification never blocks (and never versions)
Classification is metadata-only — it reads a document and records
labels; it never rewrites the file. Previously it ran like an
enforcement policy: it blocked viewing/editing behind the "Enforcing
policy…" overlay, forked a new versioned child (an `automate` entry in
version history), and could run before other policies — letting the user
in, then a later enforcement policy would fork a version and drop their
edits.
Now classification:
- **Never blocks.** A classification run never marks a file `enforcing`
(badge map + viewer overlay both skip it), so the file stays fully
viewable/editable while it runs.
- **No version bump, no history entry.** Its result is stamped onto the
file's existing stub in place (workspace + IndexedDB) — the labels just
appear as tags. It targets the document's *current leaf*, so an edit
made during the async run still gets the tags; a run that completes with
no outputs settles cleanly instead of pinning in-flight.
- **Always runs last** in an enforcement chain (regardless of configured
order, pinned at persist-time too), so every enforcement policy finishes
forking versions before the user is let in.
## 2. Pipeline policy enforcement across a batch upload
Dropping ~50 files enforced policies only *after the whole drop finished
scanning* — every file got the "Enforcing policy" overlay together, then
processing began. Root cause: the chunked `ADD_FILES` dispatches in
`addFiles` were never separated by an event-loop yield, so React batched
them into a single commit and the enforcement effect fired once over the
full list.
**Fix** (`core/contexts/file/fileActions.ts`): after each chunk, `await`
that chunk's IndexedDB writes, then yield a macrotask so React commits
the rows and runs the enforcement dispatch *before* the next chunk
scans. Files start enforcing as their rows land, overlapping with the
rest of the drop. Persistence is streamed per chunk (the policy auto-run
reads bytes from IndexedDB with no in-memory fallback).
**Second fix — bounded dispatch window**
(`proprietary/components/policies/usePolicyAutoRun.ts`): even with
streamed dispatch, the drop still *looked* serial — each dispatch POSTs
the file's bytes, and firing them all at once saturates the browser's
per-origin connection pool, so the status polls and output downloads of
already-running files queued behind the pending uploads; nothing visibly
progressed until the last upload drained. Dispatch is now gated behind a
small concurrency window (4), keeping connections free so early files
run, poll, and complete while later ones are still dispatching. The
first status poll also fires at 500ms (then the normal 2s cadence) so
fresh runs show real progress immediately. The batch test asserts the
window (dispatches overlap but never exceed 4).
## 3. Selector subscriptions for file state (no more whole-UI
re-renders)
`FileContext` published `{state, selectors}` through a plain React
context, so **every** consumer re-rendered on **every** state change —
one file's new version re-rendered the entire workspace.
**Phase 1 — infra** (`file/contexts.ts`, `file/fileHooks.ts`,
`FileContext.tsx`): the state context is replaced by a stable
subscription store (`FileStoreContext`); hooks are rebuilt on
`useSyncExternalStoreWithSelector` (the `use-sync-external-store` shim
react-redux uses — new direct dep, React 19 compatible). Each consumer
now re-renders only when its selected slice changes:
- `useStirlingFileStub(id)` → only that file's record
- `useAllFiles` → file-list changes only (immune to selection/UI churn)
- `useFileSelection`/`useSelectedFiles` → selection + the *selected*
files' records only
- `useFileUI` → its three UI scalars; `useFileContext` → files + pinned
slices
- `useFileState` keeps its whole-state contract for existing broad
consumers
A render-count test (`fileHooks.selector.test.tsx`) locks the bail-out
contract.
**Phase 2 — hot-path rows**: sidebar `FileItem` is memoized (with stable
empty-array props), so one file's change re-renders one row, not the
list. Active Files thumbnails were already memoized.
**Phase 3 — narrow the hottest consumers**: always-mounted whole-state
consumers migrated to slices — `Workbench`, `EmbedPdfViewer`, `Viewer`,
`NonPdfViewer`, `WorkbenchBar`, `ViewerContext`, `ViewerShareButton`,
`ZoomAPIBridge`, `ViewerAnnotationControls`, `ConvertSettings`,
`DismissAllErrorsButton`, `FileEditorThumbnail`,
`usePageEditorDropdownState`, `useSaveShortcut`, plus a new
non-subscribing `useFileSelectors()` for event-time reads
(`ReviewToolStep`, `useViewerReadAloud`, `useExitWarning`). Net effect:
selection/UI churn no longer re-renders the viewer/workbench, and a
version landing touches only components observing the files slice.
Broad readers (`FileSidebar`, `PageEditor`, `FileEditor`, `Redact`,
`FormFill`) deliberately stay on `useFileState` — they read most of the
state anyway.
**Hardening**: store notifications run in a layout effect (subscribers
re-render before paint — no stale frames), and outside production
`useFileSelectors()` wraps its selectors to `console.error` if one is
invoked during render (those reads don't subscribe, so render-time use
would silently go stale — not statically lintable, so it's guarded at
runtime; the full test suite passes under the guard).
## 4. Policy indicators: shared icons, non-blocking run chip, no pulse
- Badges and enforcement overlays now take their glyph from the shared
`policyCategoryIcon` map (the same source the processor's catalogue
uses) — label icon for classification, shield for security — instead of
a hardcoded shield everywhere.
- A non-blocking run (classification) shows a small accent-tinted pill
in the top-right of the Active Files card (category icon + loader) and
the normal spinning badge in the sidebar, via a new `background` badge
flag that nothing gates on. When the run finishes, the tagged files keep
a plain category badge.
- The post-run pulse/glow on sidebar badges is gone (with its `recent`
plumbing): spinner while running, static category icon when done.
## Verification
Full CI gate locally: `og:check`, `typecheck:all` (all variants),
`lint`, `format:check`, `build`, `test` (1366 — incl. the render-count
contract test, the classification-order/import unit tests, and the
61-file batch integration test driving the real dispatch → poll → import
→ chain effects), `storybook:build` — all green.
## Held for follow-up (not in this PR)
- **Reuse one PDFium engine across viewer file switches** (kills the
per-open "Loading PDF Engine" rebuild). Implemented on branch
`viewer/reuse-pdfium-engine`, but review found a confirmed leak
(orphaned PDFium handles when switching files mid-load); needs an
in-flight-load teardown before shipping.
---
.../public/locales/en-US/translation.toml | 1 +
.../fileEditor/FileEditorThumbnail.module.css | 13 +
.../fileEditor/FileEditorThumbnail.tsx | 43 ++-
.../src/core/components/layout/Workbench.tsx | 5 +-
.../hooks/usePageEditorDropdownState.ts | 20 +-
.../shared/DismissAllErrorsButton.tsx | 8 +-
.../core/components/shared/FileSidebar.tsx | 7 +-
.../components/shared/FileSidebarFileItem.tsx | 6 +-
.../core/components/shared/PolicyBadges.css | 19 --
.../shared/PolicyBadges.stories.tsx | 30 +-
.../core/components/shared/PolicyBadges.tsx | 77 +++--
.../shared/PolicyEnforcingOverlay.tsx | 2 +
.../core/components/shared/WorkbenchBar.tsx | 7 +-
.../tools/convert/ConvertSettings.tsx | 6 +-
.../tools/shared/ReviewToolStep.tsx | 4 +-
.../core/components/viewer/EmbedPdfViewer.tsx | 21 +-
.../core/components/viewer/NonPdfViewer.tsx | 5 +-
.../src/core/components/viewer/Viewer.tsx | 5 +-
.../viewer/ViewerAnnotationControls.tsx | 20 +-
.../components/viewer/ViewerShareButton.tsx | 6 +-
.../core/components/viewer/ZoomAPIBridge.tsx | 6 +-
.../components/viewer/useViewerReadAloud.ts | 4 +-
.../editor/src/core/contexts/FileContext.tsx | 45 ++-
.../src/core/contexts/ViewerContext.tsx | 22 +-
.../src/core/contexts/file/FileReducer.ts | 80 +++++
.../file/classificationToolRace.test.ts | 167 ++++++++++
.../editor/src/core/contexts/file/contexts.ts | 22 +-
.../src/core/contexts/file/fileActions.ts | 96 +++---
.../contexts/file/fileHooks.selector.test.tsx | 223 +++++++++++++
.../src/core/contexts/file/fileHooks.ts | 310 ++++++++++++++----
.../file/reducerIdentityGuard.test.ts | 78 +++++
.../core/contexts/file/useFileIndex.test.tsx | 128 ++++++++
frontend/editor/src/core/tools/Convert.tsx | 5 +-
.../src/desktop/hooks/useExitWarning.ts | 4 +-
.../src/desktop/hooks/useSaveShortcut.ts | 13 +-
.../classificationLabelTargets.test.ts | 44 +++
.../policies/dispatchSemaphore.test.ts | 47 +++
.../components/policies/dispatchSemaphore.ts | 42 +++
.../policies/usePolicyAutoRun.batch.test.tsx | 81 +++--
.../policies/usePolicyAutoRun.race.test.tsx | 293 +++++++++++++++++
.../policies/usePolicyAutoRun.retry.test.tsx | 22 +-
.../components/policies/usePolicyAutoRun.ts | 189 ++++++++++-
.../shared/PolicyEnforcingOverlay.tsx | 11 +-
.../viewer/PolicyEnforcementOverlay.tsx | 1 +
.../proprietary/components/viewer/Viewer.tsx | 3 +
.../proprietary/data/policyCategories.test.ts | 41 +++
.../src/proprietary/data/policyCategories.ts | 21 ++
.../src/proprietary/hooks/usePolicies.ts | 8 +-
.../hooks/usePolicyFileBadges.test.ts | 149 +++++++--
.../proprietary/hooks/usePolicyFileBadges.ts | 92 ++++--
frontend/package-lock.json | 2 +
frontend/package.json | 2 +
52 files changed, 2194 insertions(+), 362 deletions(-)
create mode 100644 frontend/editor/src/core/contexts/file/classificationToolRace.test.ts
create mode 100644 frontend/editor/src/core/contexts/file/fileHooks.selector.test.tsx
create mode 100644 frontend/editor/src/core/contexts/file/reducerIdentityGuard.test.ts
create mode 100644 frontend/editor/src/core/contexts/file/useFileIndex.test.tsx
create mode 100644 frontend/editor/src/proprietary/components/policies/classificationLabelTargets.test.ts
create mode 100644 frontend/editor/src/proprietary/components/policies/dispatchSemaphore.test.ts
create mode 100644 frontend/editor/src/proprietary/components/policies/dispatchSemaphore.ts
create mode 100644 frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx
create mode 100644 frontend/editor/src/proprietary/data/policyCategories.test.ts
create mode 100644 frontend/editor/src/proprietary/data/policyCategories.ts
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 33cf0ee8e1..feb42149f7 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6203,6 +6203,7 @@ ssn = "Social Security numbers"
[policy]
badgeEnforcing = "{{name}} enforcing..."
badgeRan = "{{name}} policy ran on this file"
+badgeRunning = "{{name}} running..."
blockingAction = "{{action}} blocked while enforcing policy, please wait..."
dismiss = "Dismiss overlay"
enforcingTitle = "Enforcing policy..."
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
index a148cc9fa8..1201402bf7 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.module.css
@@ -279,3 +279,16 @@
opacity: 0.5;
pointer-events: auto;
}
+
+/* Non-blocking policy run (e.g. classification tagging): small top-right pill
+ * with the policy's icon + a loader. Colour is set inline to the policy accent. */
+.backgroundPolicyPill {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 7px;
+ border-radius: 8px;
+ background: color-mix(in srgb, currentColor 14%, var(--c-surface));
+ box-shadow: var(--shadow-md);
+ pointer-events: auto;
+}
diff --git a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
index ccf07e9dea..1a55c53a90 100644
--- a/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
+++ b/frontend/editor/src/core/components/fileEditor/FileEditorThumbnail.tsx
@@ -22,6 +22,7 @@ import {
dropTargetForElements,
} from "@atlaskit/pragmatic-drag-and-drop/element/adapter";
import { StirlingFileStub } from "@app/types/fileContext";
+import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
import {
PolicyBadges,
type FileItemPolicyRef,
@@ -31,7 +32,10 @@ import { zipFileService } from "@app/services/zipFileService";
import styles from "@app/components/fileEditor/FileEditorThumbnail.module.css";
import { useFileContext } from "@app/contexts/FileContext";
-import { useFileState } from "@app/contexts/file/fileHooks";
+import {
+ useFileSelector,
+ useFileSelectors,
+} from "@app/contexts/file/fileHooks";
import { FileId } from "@app/types/file";
import ToolChain from "@app/components/shared/ToolChain";
import HoverActionMenu, {
@@ -90,7 +94,7 @@ const FileEditorThumbnail = ({
actions: fileActions,
openEncryptedUnlockPrompt,
} = useFileContext();
- const { state, selectors } = useFileState();
+ const selectors = useFileSelectors();
const isMobile = useIsMobile();
const actualFile = useMemo(
@@ -101,7 +105,7 @@ const FileEditorThumbnail = ({
const isZipFile = zipFileService.isZipFileStub(file);
- const hasError = state.ui.errorFileIds.includes(file.id);
+ const hasError = useFileSelector((s) => s.ui.errorFileIds.includes(file.id));
const pageCount = file.processedFile?.totalPages || 0;
const {
isEncrypted,
@@ -296,9 +300,12 @@ const FileEditorThumbnail = ({
const [showVersionHistory, setShowVersionHistory] = useState(false);
const policyEnforcing = policies.some((p) => p.enforcing);
- // Accent of the policy currently enforcing, so the overlay's icon/spinner match
- // that policy's badge instead of a fixed blue.
- const enforcingAccent = policies.find((p) => p.enforcing)?.accentColor;
+ // The policy currently enforcing, so the overlay's icon/spinner match that
+ // policy's badge instead of a fixed blue.
+ const enforcingPolicy = policies.find((p) => p.enforcing);
+ // A non-blocking run (e.g. classification tagging) — indicated by a small
+ // top-right chip instead of the blocking overlay.
+ const backgroundPolicy = policies.find((p) => p.background && !p.enforcing);
const hoverActions = useMemo(() => {
const uploadLabel = isUploaded
@@ -543,7 +550,8 @@ const FileEditorThumbnail = ({
{/* Thumbnail image or loading state */}
@@ -568,6 +576,27 @@ const FileEditorThumbnail = ({
}}
/>
+ {backgroundPolicy && (
+
+
+
+ {policyCategoryIcon(backgroundPolicy.id, {
+ fontSize: 14,
+ })}
+
+
+
+
+ )}
+
{/* Badges — top-left: version, pin, ownership, encrypted */}
diff --git a/frontend/editor/src/core/components/layout/Workbench.tsx b/frontend/editor/src/core/components/layout/Workbench.tsx
index fc5dd77226..96eb6b8d6f 100644
--- a/frontend/editor/src/core/components/layout/Workbench.tsx
+++ b/frontend/editor/src/core/components/layout/Workbench.tsx
@@ -2,7 +2,7 @@ import { useEffect, useState, Suspense, lazy } from "react";
import { Box, Loader, Center } from "@mantine/core";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useFileHandler } from "@app/hooks/useFileHandler";
-import { useFileState } from "@app/contexts/FileContext";
+import { useAllFiles } from "@app/contexts/FileContext";
import {
useNavigationState,
useNavigationActions,
@@ -41,11 +41,10 @@ export default function Workbench() {
useCookieConsent({ analyticsEnabled: config?.enableAnalytics === true });
// Use context-based hooks to eliminate all prop drilling
- const { selectors } = useFileState();
+ const { files: activeFiles } = useAllFiles();
const { workbench: currentView } = useNavigationState();
const { actions: navActions } = useNavigationActions();
const setCurrentView = navActions.setWorkbench;
- const activeFiles = selectors.getFiles();
const {
previewFile,
pageEditorFunctions,
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorDropdownState.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorDropdownState.ts
index ac26c142dc..94ed6590ce 100644
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorDropdownState.ts
+++ b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorDropdownState.ts
@@ -1,6 +1,6 @@
import { useMemo } from "react";
import { usePageEditor } from "@app/contexts/PageEditorContext";
-import { useFileState } from "@app/contexts/FileContext";
+import { shallowEqual, useFileSelector } from "@app/contexts/FileContext";
import { FileId } from "@app/types/file";
import { useFileColorMap } from "@app/components/pageEditor/hooks/useFileColorMap";
@@ -24,24 +24,32 @@ const isPdf = (name?: string | null) =>
typeof name === "string" && name.toLowerCase().endsWith(".pdf");
export function usePageEditorDropdownState(): PageEditorDropdownState {
- const { state, selectors } = useFileState();
+ const selectedFileIds = useFileSelector((s) => s.ui.selectedFileIds);
const { toggleFileSelection, reorderFiles, fileOrder } = usePageEditor();
+ // Subscribe to the stubs for the files in view so name/version changes
+ // re-render the dropdown. Reading via useFileSelectors() during render would
+ // not subscribe, so the displayed name/version could go stale.
+ const orderedStubs = useFileSelector(
+ (s) => fileOrder.map((fileId) => s.files.byId[fileId]),
+ shallowEqual,
+ );
+
const pageEditorFiles = useMemo(() => {
return fileOrder
- .map((fileId) => {
- const stub = selectors.getStirlingFileStub(fileId);
+ .map((fileId, index) => {
+ const stub = orderedStubs[index];
if (!isPdf(stub?.name)) return null;
return {
fileId,
name: stub?.name || "",
versionNumber: stub?.versionNumber,
- isSelected: state.ui.selectedFileIds.includes(fileId),
+ isSelected: selectedFileIds.includes(fileId),
};
})
.filter((file): file is PageEditorDropdownFile => file !== null);
- }, [fileOrder, selectors, state.ui.selectedFileIds]);
+ }, [fileOrder, orderedStubs, selectedFileIds]);
const fileColorMap = useFileColorMap(
pageEditorFiles.map((file) => file.fileId),
diff --git a/frontend/editor/src/core/components/shared/DismissAllErrorsButton.tsx b/frontend/editor/src/core/components/shared/DismissAllErrorsButton.tsx
index 5f3f4ada2a..ea28b78c5e 100644
--- a/frontend/editor/src/core/components/shared/DismissAllErrorsButton.tsx
+++ b/frontend/editor/src/core/components/shared/DismissAllErrorsButton.tsx
@@ -2,7 +2,7 @@ import React from "react";
import { Group } from "@mantine/core";
import { Button } from "@app/ui/Button";
import { useTranslation } from "react-i18next";
-import { useFileState } from "@app/contexts/FileContext";
+import { useFileSelector } from "@app/contexts/FileContext";
import { useFileActions } from "@app/contexts/file/fileHooks";
import { Z_INDEX_TOAST } from "@app/styles/zIndex";
@@ -14,11 +14,11 @@ const DismissAllErrorsButton: React.FC = ({
className,
}) => {
const { t } = useTranslation();
- const { state } = useFileState();
+ const errorFileIds = useFileSelector((s) => s.ui.errorFileIds);
const { actions } = useFileActions();
// Check if there are any files in error state
- const hasErrors = state.ui.errorFileIds.length > 0;
+ const hasErrors = errorFileIds.length > 0;
// Don't render if there are no errors
if (!hasErrors) {
@@ -45,7 +45,7 @@ const DismissAllErrorsButton: React.FC = ({
}}
>
{t("error.dismissAllErrors", "Dismiss All Errors")} (
- {state.ui.errorFileIds.length})
+ {errorFileIds.length})
);
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index 7d09261226..742334015c 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -81,9 +81,10 @@ const EXPANDED_WIDTH = "16.25rem"; // ~260px
const WATCHED_FOLDER_VIEW_ID = "watchedFolder";
const WATCHED_FOLDER_WORKBENCH_ID = "custom:watchedFolder";
-// Stable empty props for rows without folders, so the memoized FileItem
-// isn't re-rendered by a fresh `?? []` identity on every list render.
+// Stable empty props for rows without folders/policies, so the memoized
+// FileItem isn't re-rendered by a fresh `?? []` identity on every list render.
const NO_FOLDERS: never[] = [];
+const NO_POLICIES: never[] = [];
/** Only surface the "Adding files…" progress row for drops big enough that the
* pre-dispatch scan is user-visible; small adds finish before it would paint. */
@@ -790,7 +791,7 @@ const FileSidebar = forwardRef(
onDragStart={handleWatchedFolderDragStart}
folders={memberFolders}
onFolderClick={openWatchedFolder}
- policies={policyFileBadges.get(stub.id as string) ?? []}
+ policies={policyFileBadges.get(stub.id as string) ?? NO_POLICIES}
onDelete={isWatchedFoldersActive ? undefined : handleSidebarDelete}
onSaveToCloud={isWatchedFoldersActive ? undefined : handleSaveToCloud}
canSaveToCloud={storageEnabled && fileOrigin !== "shared-with-me"}
diff --git a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
index a289a245f1..c1a93594c5 100644
--- a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
@@ -167,7 +167,9 @@ export interface FileItemProps {
const MAX_VISIBLE_FOLDER_TAGS = 2;
-export function FileItem({
+// Memoized: sidebar rows bail out unless THEIR props change, so one file's
+// update (e.g. a new version landing) re-renders one row, not the whole list.
+export const FileItem = React.memo(function FileItem({
fileId,
name,
size,
@@ -509,4 +511,4 @@ export function FileItem({
)}
>
);
-}
+});
diff --git a/frontend/editor/src/core/components/shared/PolicyBadges.css b/frontend/editor/src/core/components/shared/PolicyBadges.css
index 3a919e24c9..8526de44c6 100644
--- a/frontend/editor/src/core/components/shared/PolicyBadges.css
+++ b/frontend/editor/src/core/components/shared/PolicyBadges.css
@@ -41,22 +41,3 @@
transform: rotate(360deg);
}
}
-
-.policy-badge--recent {
- animation: policy-badge-pulse 4.5s ease-in-out forwards;
-}
-@keyframes policy-badge-pulse {
- 0%,
- 24%,
- 48% {
- box-shadow: 0 0 0 0 transparent;
- }
- 12%,
- 36% {
- box-shadow: 0 0 5px 2px currentColor;
- }
- 60%,
- 100% {
- box-shadow: 0 0 0 0 transparent;
- }
-}
diff --git a/frontend/editor/src/core/components/shared/PolicyBadges.stories.tsx b/frontend/editor/src/core/components/shared/PolicyBadges.stories.tsx
index 81969bf615..c3646f774a 100644
--- a/frontend/editor/src/core/components/shared/PolicyBadges.stories.tsx
+++ b/frontend/editor/src/core/components/shared/PolicyBadges.stories.tsx
@@ -2,10 +2,14 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
import { PolicyBadges } from "@app/components/shared/PolicyBadges";
import type { FileItemPolicyRef } from "@app/components/shared/PolicyBadges";
+// Real catalog category ids, so each badge renders its own shared glyph
+// (policyCategoryIcon) rather than the unknown-category fallback. Accents mirror
+// policyAccentVar's mapping — that lives in the proprietary layer, which a core
+// story can't import.
const mockPolicies: FileItemPolicyRef[] = [
- { id: "policy-1", name: "Redact PII", accentColor: "#e03131", recent: true },
- { id: "policy-2", name: "Sanitize", accentColor: "#2f9e44", recent: false },
- { id: "policy-3", name: "Watermark", accentColor: "#4263eb", recent: false },
+ { id: "security", name: "Redact PII", accentColor: "var(--color-purple)" },
+ { id: "compliance", name: "Sanitize", accentColor: "var(--color-green)" },
+ { id: "ingestion", name: "Watermark", accentColor: "var(--color-blue)" },
];
const meta = {
@@ -22,15 +26,25 @@ export const Default: Story = {
},
};
+/** A blocking policy mid-run: spinner, and the file's exit points are gated. */
export const Enforcing: Story = {
+ args: {
+ policies: [
+ { ...mockPolicies[0], enforcing: true },
+ ...mockPolicies.slice(1),
+ ],
+ },
+};
+
+/** A non-blocking run (classification tagging): same spinner, nothing gated. */
+export const Background: Story = {
args: {
policies: [
{
- id: "policy-1",
- name: "Redact PII",
- accentColor: "#e03131",
- recent: false,
- enforcing: true,
+ id: "classification",
+ name: "Classification",
+ accentColor: "var(--color-orange)",
+ background: true,
},
...mockPolicies.slice(1),
],
diff --git a/frontend/editor/src/core/components/shared/PolicyBadges.tsx b/frontend/editor/src/core/components/shared/PolicyBadges.tsx
index f8661b9176..1fa57ca70a 100644
--- a/frontend/editor/src/core/components/shared/PolicyBadges.tsx
+++ b/frontend/editor/src/core/components/shared/PolicyBadges.tsx
@@ -1,6 +1,6 @@
import { Tooltip } from "@mantine/core";
-import ShieldOutlinedIcon from "@mui/icons-material/ShieldOutlined";
import AutorenewIcon from "@mui/icons-material/Autorenew";
+import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
import { useTranslation } from "react-i18next";
import "@app/components/shared/PolicyBadges.css";
@@ -10,20 +10,20 @@ export interface FileItemPolicyRef {
name: string;
/** CSS colour for the badge (matches the policy's accent). */
accentColor: string;
- /** True only just after the policy was applied — drives the one-off glow, so
- * it doesn't replay on every reload of an already-enforced file. */
- recent: boolean;
- /** True while the policy run is actively in-flight on this file. */
+ /** True while a BLOCKING policy run is in-flight on this file (gates actions). */
enforcing?: boolean;
+ /** True while a non-blocking run (e.g. classification) is in-flight — shows
+ * the same spinner but never gates anything. */
+ background?: boolean;
}
const MAX_VISIBLE = 3;
/**
- * The canonical policy badge row: one accent-tinted shield per policy that has
- * run on a file, spinning while a run is in flight, glowing briefly after it
- * lands. Every surface that shows per-file policy badges (file sidebar, file
- * editor thumbnails, files page) renders this so they stay identical.
+ * The canonical policy badge row: one accent-tinted category icon per policy
+ * that has run on a file, spinning while a run is in flight. Every surface that
+ * shows per-file policy badges (file sidebar, file editor thumbnails, files
+ * page) renders this so they stay identical.
*/
export function PolicyBadges({
policies,
@@ -40,33 +40,40 @@ export function PolicyBadges({
className={`policy-badges${className ? ` ${className}` : ""}`}
data-no-select
>
- {policies.slice(0, MAX_VISIBLE).map((policy) => (
-
- {
+ const running = policy.enforcing || policy.background;
+ return (
+
- {policy.enforcing ? (
-
- ) : (
-
- )}
-
-
- ))}
+
+ {running ? (
+
+ ) : (
+ policyCategoryIcon(policy.id, { fontSize: "0.7rem" })
+ )}
+
+
+ );
+ })}
);
}
diff --git a/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsx b/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsx
index cb9e931e80..9d5d2475b3 100644
--- a/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsx
+++ b/frontend/editor/src/core/components/shared/PolicyEnforcingOverlay.tsx
@@ -4,6 +4,8 @@ export function PolicyEnforcingOverlay(_props: {
zIndex?: number;
/** CSS colour var for the enforcing policy's accent; tints the icon/spinner. */
accentVar?: string;
+ /** Category of the enforcing policy — picks its icon in the real overlay. */
+ categoryId?: string;
}) {
return null;
}
diff --git a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
index 5cc1e6cabd..55ca01d307 100644
--- a/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
+++ b/frontend/editor/src/core/components/shared/WorkbenchBar.tsx
@@ -19,7 +19,8 @@ import {
} from "@app/components/filesPage/filesPageReturnRoute";
import { useWorkbenchBar } from "@app/contexts/WorkbenchBarContext";
import {
- useFileState,
+ useAllFiles,
+ useFileSelectors,
useFileSelection,
useFileActions,
} from "@app/contexts/FileContext";
@@ -121,10 +122,10 @@ export default function WorkbenchBar({
const { sharingEnabled } = useSharingEnabled();
const viewerContext = React.useContext(ViewerContext);
- const { selectors } = useFileState();
+ const selectors = useFileSelectors();
const { selectedFiles, selectedFileIds } = useFileSelection();
const { actions: fileActions } = useFileActions();
- const activeFiles = selectors.getFiles();
+ const { files: activeFiles } = useAllFiles();
const { activeFileId, setActiveFileId } = useViewer();
const policyFileBadges = usePolicyFileBadges();
// Block print/export while any file the export would touch is under active
diff --git a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx
index cc33ccbbb4..fe4a6f8e48 100644
--- a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx
+++ b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx
@@ -11,7 +11,7 @@ import {
} from "@app/utils/convertUtils";
import { getConversionEndpoints } from "@app/data/toolsTaxonomy";
import { useFileSelection } from "@app/contexts/FileContext";
-import { useFileState } from "@app/contexts/FileContext";
+import { useFileSelector, useFileSelectors } from "@app/contexts/FileContext";
import { detectFileExtension } from "@app/utils/fileUtils";
import { usePreferences } from "@app/contexts/PreferencesContext";
import { useConversionCloudStatus } from "@app/hooks/useConversionCloudStatus";
@@ -62,8 +62,8 @@ const ConvertSettings = ({
const { t } = useTranslation();
const theme = useMantineTheme();
const { setSelectedFiles } = useFileSelection();
- const { state, selectors } = useFileState();
- const activeFiles = state.files.ids;
+ const selectors = useFileSelectors();
+ const activeFiles = useFileSelector((s) => s.files.ids);
const { preferences } = usePreferences();
const allEndpoints = useMemo(() => {
diff --git a/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsx b/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsx
index 8c89029913..7918bac7ca 100644
--- a/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsx
+++ b/frontend/editor/src/core/components/tools/shared/ReviewToolStep.tsx
@@ -11,7 +11,7 @@ import { Tooltip } from "@app/components/shared/Tooltip";
import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";
import { useFileActionIcons } from "@app/hooks/useFileActionIcons";
import { saveOperationResults } from "@app/services/operationResultsSaveService";
-import { useFileActions, useFileState } from "@app/contexts/FileContext";
+import { useFileActions, useFileSelectors } from "@app/contexts/FileContext";
import { FileId } from "@app/types/fileContext";
import i18n from "@app/i18n";
@@ -40,7 +40,7 @@ function ReviewStepContent({
const DownloadIcon = icons.download;
const stepRef = useRef(null);
const { actions: fileActions } = useFileActions();
- const { selectors } = useFileState();
+ const selectors = useFileSelectors();
const handleUndo = async () => {
try {
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index cc4a04598e..be4a4a9971 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -12,7 +12,12 @@ import { ActionIcon } from "@app/ui/ActionIcon";
import CloseIcon from "@mui/icons-material/Close";
import LockIcon from "@mui/icons-material/Lock";
-import { useFileState, useFileActions } from "@app/contexts/FileContext";
+import {
+ useAllFiles,
+ useFileSelector,
+ useFileSelectors,
+ useFileActions,
+} from "@app/contexts/FileContext";
import { useFileWithUrl } from "@app/hooks/useFileWithUrl";
import { useViewer } from "@app/contexts/ViewerContext";
import { LocalEmbedPDF } from "@app/components/viewer/LocalEmbedPDF";
@@ -259,9 +264,9 @@ const EmbedPdfViewerContent = ({
const redactionTrackerRef = useRef(null);
// Get current file from FileContext
- const { selectors } = useFileState();
+ const selectors = useFileSelectors();
const { actions } = useFileActions();
- const activeFiles = selectors.getFiles();
+ const { files: activeFiles } = useAllFiles();
const activeFilesRef = useRef(activeFiles);
activeFilesRef.current = activeFiles;
const activeFileIds = activeFiles.map((f) => f.fileId);
@@ -392,11 +397,11 @@ const EmbedPdfViewerContent = ({
}, [previewFile, fileWithUrl]);
// Check if the current file is encrypted (gate the viewer to prevent PDFium crash)
- const isCurrentFileEncrypted = React.useMemo(() => {
- if (!currentFile || !isStirlingFile(currentFile)) return false;
- const stub = selectors.getStirlingFileStub(currentFile.fileId);
- return stub?.processedFile?.isEncrypted === true;
- }, [currentFile, selectors]);
+ const isCurrentFileEncrypted = useFileSelector((s) =>
+ currentFile && isStirlingFile(currentFile)
+ ? s.files.byId[currentFile.fileId]?.processedFile?.isEncrypted === true
+ : false,
+ );
const bookmarkCacheKey = React.useMemo(() => {
if (currentFile && isStirlingFile(currentFile)) {
diff --git a/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx b/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx
index ed4a2e2263..bd2704963a 100644
--- a/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/NonPdfViewer.tsx
@@ -4,7 +4,7 @@ import { Button } from "@app/ui/Button";
import ArticleIcon from "@mui/icons-material/Article";
import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf";
-import { useFileState } from "@app/contexts/FileContext";
+import { useAllFiles } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import {
@@ -126,8 +126,7 @@ export function NonPdfViewer({ file }: NonPdfViewerProps) {
// ─── Wrapper that resolves the active file from FileContext ───────────────────
export function NonPdfViewerWrapper(props: ViewerProps) {
- const { selectors } = useFileState();
- const activeFiles = selectors.getFiles();
+ const { files: activeFiles } = useAllFiles();
const { activeFileIndex } = useViewer();
const file =
diff --git a/frontend/editor/src/core/components/viewer/Viewer.tsx b/frontend/editor/src/core/components/viewer/Viewer.tsx
index 08103ca1f5..36a1080dbb 100644
--- a/frontend/editor/src/core/components/viewer/Viewer.tsx
+++ b/frontend/editor/src/core/components/viewer/Viewer.tsx
@@ -5,7 +5,7 @@ import {
NonPdfViewerWrapper,
type ViewerProps,
} from "@app/components/viewer/NonPdfViewer";
-import { useFileState } from "@app/contexts/FileContext";
+import { useAllFiles } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { isStirlingFile } from "@app/types/fileContext";
import { isPdfFile } from "@app/utils/fileUtils";
@@ -26,8 +26,7 @@ type SignatureOverlayPassThrough = Pick<
>;
const Viewer = (props: ViewerProps & SignatureOverlayPassThrough) => {
- const { selectors } = useFileState();
- const activeFiles = selectors.getFiles();
+ const { files: activeFiles } = useAllFiles();
const { activeFileId } = useViewer();
// Determine the active file — previewFile takes priority, then look up by stable ID
diff --git a/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx b/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx
index 32b4b1ce11..fda6c2d2a5 100644
--- a/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx
+++ b/frontend/editor/src/core/components/viewer/ViewerAnnotationControls.tsx
@@ -5,7 +5,11 @@ import { ActionIcon } from "@app/ui/ActionIcon";
import { Tooltip } from "@app/components/shared/Tooltip";
import { ViewerContext } from "@app/contexts/ViewerContext";
import { useSignature } from "@app/contexts/SignatureContext";
-import { useFileState, useFileContext } from "@app/contexts/FileContext";
+import {
+ useAllFiles,
+ useFileSelectors,
+ useFileContext,
+} from "@app/contexts/FileContext";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
import {
useNavigationState,
@@ -39,9 +43,9 @@ export default function ViewerAnnotationControls({
const { historyApiRef, isPlacementMode } = useSignature();
// File state for save functionality
- const { state, selectors } = useFileState();
+ const selectors = useFileSelectors();
+ const { files: activeFiles, fileIds } = useAllFiles();
const { actions: fileActions } = useFileContext();
- const activeFiles = selectors.getFiles();
// Check if we're in sign mode or redaction mode
const { selectedTool } = useNavigationState();
@@ -83,7 +87,7 @@ export default function ViewerAnnotationControls({
!historyApiRef?.current?.canUndo()
)
return;
- if (activeFiles.length === 0 || state.files.ids.length === 0) return;
+ if (activeFiles.length === 0 || fileIds.length === 0) return;
try {
const arrayBuffer = await viewerContext.exportActions.saveAsCopy();
@@ -92,7 +96,7 @@ export default function ViewerAnnotationControls({
const file = new File([new Blob([arrayBuffer])], activeFiles[0].name, {
type: "application/pdf",
});
- const parentStub = selectors.getStirlingFileStub(state.files.ids[0]);
+ const parentStub = selectors.getStirlingFileStub(fileIds[0]);
if (!parentStub) return;
const { stirlingFiles, stubs } = await createStirlingFilesAndStubs(
@@ -100,11 +104,7 @@ export default function ViewerAnnotationControls({
parentStub,
"redact",
);
- await fileActions.consumeFiles(
- [state.files.ids[0]],
- stirlingFiles,
- stubs,
- );
+ await fileActions.consumeFiles([fileIds[0]], stirlingFiles, stubs);
// Clear unsaved changes flags after successful save
setHasUnsavedChanges(false);
diff --git a/frontend/editor/src/core/components/viewer/ViewerShareButton.tsx b/frontend/editor/src/core/components/viewer/ViewerShareButton.tsx
index f063cbffe2..4ef4b30cda 100644
--- a/frontend/editor/src/core/components/viewer/ViewerShareButton.tsx
+++ b/frontend/editor/src/core/components/viewer/ViewerShareButton.tsx
@@ -9,7 +9,7 @@ import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import { Tooltip } from "@app/components/shared/Tooltip";
import ShareManagementModal from "@app/components/shared/ShareManagementModal";
import { useViewer } from "@app/contexts/ViewerContext";
-import { useFileState, useFileActions } from "@app/contexts/FileContext";
+import { useAllFiles, useFileActions } from "@app/contexts/FileContext";
import { uploadHistoryChain } from "@app/services/serverStorageUpload";
import { fileStorage } from "@app/services/fileStorage";
import { alert } from "@app/components/toast";
@@ -39,7 +39,7 @@ export default function ViewerShareButton({
}: ViewerShareButtonProps) {
const { t } = useTranslation();
const { activeFileId } = useViewer();
- const { selectors } = useFileState();
+ const { fileStubs } = useAllFiles();
const { actions } = useFileActions();
const [confirmOpen, setConfirmOpen] = useState(false);
const [saving, setSaving] = useState(false);
@@ -49,7 +49,7 @@ export default function ViewerShareButton({
// Resolve strictly to the file shown in the viewer. Never fall back to an
// arbitrary file — sharing the wrong document would be worse than not
// sharing. If there's no active file, the button is disabled (see isDisabled).
- const stubs = selectors.getStirlingFileStubs();
+ const stubs = fileStubs;
const stub = activeFileId
? stubs.find((s) => s.id === activeFileId)
: undefined;
diff --git a/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx b/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx
index 2501ddfb79..0cb11837cc 100644
--- a/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx
+++ b/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx
@@ -3,7 +3,7 @@ import { useZoom, ZoomMode } from "@embedpdf/plugin-zoom/react";
import { useSpread, SpreadMode } from "@embedpdf/plugin-spread/react";
import { useViewer } from "@app/contexts/ViewerContext";
import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
-import { useFileState } from "@app/contexts/FileContext";
+import { useAllFiles } from "@app/contexts/FileContext";
import {
determineAutoZoom,
DEFAULT_FALLBACK_ZOOM,
@@ -36,7 +36,7 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
const { provides: zoom, state: zoomState } = useZoom(documentId);
const { spreadMode } = useSpread(documentId);
const { registerBridge, triggerImmediateZoomUpdate } = useViewer();
- const { selectors } = useFileState();
+ const { fileStubs } = useAllFiles();
const hasSetInitialZoom = useRef(false);
const lastSpreadMode = useRef(spreadMode ?? SpreadMode.None);
@@ -62,7 +62,7 @@ function ZoomAPIBridgeInner({ documentId }: { documentId: string }) {
}
}, []);
- const stubs = selectors.getStirlingFileStubs();
+ const stubs = fileStubs;
const firstFileStub = stubs[0];
const firstFileId = firstFileStub?.id;
diff --git a/frontend/editor/src/core/components/viewer/useViewerReadAloud.ts b/frontend/editor/src/core/components/viewer/useViewerReadAloud.ts
index c2ccdec1be..5352ffc748 100644
--- a/frontend/editor/src/core/components/viewer/useViewerReadAloud.ts
+++ b/frontend/editor/src/core/components/viewer/useViewerReadAloud.ts
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { computeReadAloudHighlightRect } from "@app/components/viewer/readAloudHighlight";
-import { useFileState } from "@app/contexts/FileContext";
+import { useFileSelectors } from "@app/contexts/FileContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { useStopReadAloudOnNavigation } from "@app/components/viewer/useStopReadAloudOnNavigation";
import { pdfWorkerManager } from "@app/services/pdfWorkerManager";
@@ -60,7 +60,7 @@ function createHighlightElement(
export function useViewerReadAloud(defaultLanguage?: string) {
const viewer = useViewer();
- const { selectors } = useFileState();
+ const selectors = useFileSelectors();
const [isReadingAloud, setIsReadingAloud] = useState(false);
const [speechRate, setSpeechRate] = useState(1);
diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsx
index d0808665cd..a982c347ca 100644
--- a/frontend/editor/src/core/contexts/FileContext.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.tsx
@@ -16,6 +16,7 @@ import {
useReducer,
useCallback,
useEffect,
+ useLayoutEffect,
useRef,
useMemo,
useState,
@@ -23,7 +24,6 @@ import {
import {
FileContextProviderProps,
FileContextSelectors,
- FileContextStateValue,
FileContextActionsValue,
FileContextActions,
FileId,
@@ -36,6 +36,7 @@ import {
import {
fileContextReducer,
initialFileContextState,
+ withReducerIdentityGuard,
} from "@app/contexts/file/FileReducer";
import { createFileSelectors } from "@app/contexts/file/fileSelectors";
import {
@@ -49,8 +50,9 @@ import {
} from "@app/contexts/file/fileActions";
import { FileLifecycleManager } from "@app/contexts/file/lifecycle";
import {
- FileStateContext,
+ FileStoreContext,
FileActionsContext,
+ type FileStateStore,
} from "@app/contexts/file/contexts";
import {
IndexedDBProvider,
@@ -75,10 +77,13 @@ function FileContextInner({
children,
enablePersistence = true,
}: FileContextProviderProps) {
- const [state, dispatch] = useReducer(
- fileContextReducer,
- initialFileContextState,
+ // Guarded in dev: warns if a reducer case reallocates a slice without changing
+ // it, which would silently defeat the selector-subscription bail-out.
+ const guardedReducer = useMemo(
+ () => withReducerIdentityGuard(fileContextReducer),
+ [],
);
+ const [state, dispatch] = useReducer(guardedReducer, initialFileContextState);
// Always call the hook unconditionally to satisfy React's rules of hooks.
// IndexedDB context is only used when enablePersistence is true.
@@ -657,14 +662,28 @@ function FileContextInner({
],
);
- // Split context values to minimize re-renders
- const stateValue = useMemo(
+ // Subscription store bridge: the context value is STABLE, so consumers only
+ // re-render when the slice they select (via useFileSelector) changes — not on
+ // every state change. Listeners are notified after each committed state.
+ const listenersRef = useRef void>>(new Set());
+ const store = useMemo(
() => ({
- state,
+ getState: () => stateRef.current,
+ subscribe: (listener) => {
+ listenersRef.current.add(listener);
+ return () => {
+ listenersRef.current.delete(listener);
+ };
+ },
selectors,
}),
- [state, selectors],
+ [selectors],
);
+ // Layout effect (not passive): subscribers re-render before the browser
+ // paints, so a state change can never show a frame with stale consumers.
+ useLayoutEffect(() => {
+ for (const listener of listenersRef.current) listener();
+ }, [state]);
const actionsValue = useMemo(
() => ({
@@ -698,7 +717,7 @@ function FileContextInner({
}, [lifecycleManager]);
return (
-
+
{children}
-
+
);
}
@@ -758,6 +777,10 @@ export function FileContextProvider({
export {
useFileState,
useFileActions,
+ useFileSelector,
+ useFileSelectors,
+ useFileIndex,
+ shallowEqual,
useCurrentFile,
useFileSelection,
useFileManagement,
diff --git a/frontend/editor/src/core/contexts/ViewerContext.tsx b/frontend/editor/src/core/contexts/ViewerContext.tsx
index 22d95606c1..5e5d08dbb4 100644
--- a/frontend/editor/src/core/contexts/ViewerContext.tsx
+++ b/frontend/editor/src/core/contexts/ViewerContext.tsx
@@ -9,7 +9,11 @@ import React, {
useCallback,
} from "react";
import { useNavigation } from "@app/contexts/NavigationContext";
-import { useFileState } from "@app/contexts/FileContext";
+import {
+ useFileIndex,
+ useFileSelector,
+ useFileSelectors,
+} from "@app/contexts/FileContext";
import { isStirlingFile } from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
import { enforceExportPolicies } from "@app/services/policyExport";
@@ -244,25 +248,21 @@ export const ViewerProvider: React.FC = ({ children }) => {
const [activeFileId, setActiveFileId] = useState(null);
// activeFileIndex is derived from activeFileId so they can never desync.
- // ViewerProvider sits inside FileContextProvider so useFileState is valid here.
- const { selectors, state } = useFileState();
+ // ViewerProvider sits inside FileContextProvider so these hooks are valid here.
+ const selectors = useFileSelectors();
+ const fileIds = useFileSelector((s) => s.files.ids);
// Clear activeFileId when its file is removed from the workbench.
// Dep on state.files.ids so the effect re-runs on every add/remove.
useEffect(() => {
if (!activeFileId) return;
- const stillInWorkbench = state.files.ids.some(
+ const stillInWorkbench = fileIds.some(
(id) => (id as string) === activeFileId,
);
if (!stillInWorkbench) setActiveFileId(null);
- }, [activeFileId, state.files.ids]);
+ }, [activeFileId, fileIds]);
- const activeFileIndex = useMemo(() => {
- if (!activeFileId) return 0;
- const files = selectors.getFiles();
- const idx = files.findIndex((f) => f.fileId === activeFileId);
- return idx >= 0 ? idx : 0;
- }, [activeFileId, selectors]);
+ const activeFileIndex = useFileIndex(activeFileId);
const setActiveFileIndex = useCallback(
(index: number) => {
const files = selectors.getFiles();
diff --git a/frontend/editor/src/core/contexts/file/FileReducer.ts b/frontend/editor/src/core/contexts/file/FileReducer.ts
index 91bd62cf4d..2697974823 100644
--- a/frontend/editor/src/core/contexts/file/FileReducer.ts
+++ b/frontend/editor/src/core/contexts/file/FileReducer.ts
@@ -425,3 +425,83 @@ export function fileContextReducer(
return state;
}
}
+
+// ── Dev-only structural-sharing guard ──────────────────────────────────────
+//
+// The file hooks bail a consumer out of re-rendering when the slice it selects
+// keeps its object identity across a dispatch. That optimisation silently
+// breaks if a reducer case returns a NEW identity for a slice it didn't
+// actually change (e.g. an unnecessary `{ ...state.files }`): every consumer of
+// that slice re-renders for nothing, with no test failure. This wrapper warns
+// when that happens. No-op in production.
+
+function idsUnchanged(a: FileId[], b: FileId[]): boolean {
+ return a.length === b.length && a.every((id, i) => id === b[i]);
+}
+
+function byIdUnchanged(
+ a: Record,
+ b: Record,
+): boolean {
+ const keysA = Object.keys(a);
+ return (
+ keysA.length === Object.keys(b).length &&
+ keysA.every((id) => a[id as FileId] === b[id as FileId])
+ );
+}
+
+function uiUnchanged(
+ a: FileContextState["ui"],
+ b: FileContextState["ui"],
+): boolean {
+ return (Object.keys(a) as Array).every(
+ (k) => a[k] === b[k],
+ );
+}
+
+function setUnchanged(a: Set, b: Set): boolean {
+ if (a.size !== b.size) return false;
+ for (const v of a) if (!b.has(v)) return false;
+ return true;
+}
+
+/**
+ * Wrap a reducer so, outside production, it warns when an action reallocates a
+ * top-level state slice without changing its contents — which would defeat the
+ * selector-subscription bail-out in the file hooks.
+ */
+export function withReducerIdentityGuard(
+ reducer: (s: FileContextState, a: FileContextAction) => FileContextState,
+): (s: FileContextState, a: FileContextAction) => FileContextState {
+ if (process.env.NODE_ENV === "production") return reducer;
+ return (state, action) => {
+ const next = reducer(state, action);
+ if (next === state) return next;
+ if (
+ next.files !== state.files &&
+ idsUnchanged(next.files.ids, state.files.ids) &&
+ byIdUnchanged(next.files.byId, state.files.byId)
+ ) {
+ console.error(
+ `[FileReducer] '${action.type}' reallocated state.files without changing it — ` +
+ "this re-renders every file consumer for nothing. Return the existing slice unchanged.",
+ );
+ }
+ if (next.ui !== state.ui && uiUnchanged(next.ui, state.ui)) {
+ console.error(
+ `[FileReducer] '${action.type}' reallocated state.ui without changing it — ` +
+ "this re-renders every UI consumer for nothing. Return the existing slice unchanged.",
+ );
+ }
+ if (
+ next.pinnedFiles !== state.pinnedFiles &&
+ setUnchanged(next.pinnedFiles, state.pinnedFiles)
+ ) {
+ console.error(
+ `[FileReducer] '${action.type}' reallocated state.pinnedFiles without changing it — ` +
+ "this re-renders every pinned-files consumer for nothing.",
+ );
+ }
+ return next;
+ };
+}
diff --git a/frontend/editor/src/core/contexts/file/classificationToolRace.test.ts b/frontend/editor/src/core/contexts/file/classificationToolRace.test.ts
new file mode 100644
index 0000000000..faf6501a0c
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/classificationToolRace.test.ts
@@ -0,0 +1,167 @@
+import { describe, it, expect } from "vitest";
+import { fileContextReducer } from "@app/contexts/file/FileReducer";
+import type {
+ FileContextAction,
+ FileContextState,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+/**
+ * Classification is non-blocking: while it runs, the user can manually run a
+ * tool on the same file. Classification's only write is a metadata-only,
+ * shallow-merged UPDATE_FILE_RECORD stamping `classificationLabels`; a manual
+ * tool run produces a NEW document via CONSUME_FILES (new id + version). These
+ * tests drive the REAL reducer through every interleaving (classification lands
+ * before / during / after the tool run) and prove the invariant the design
+ * relies on: the tool's output document is byte-for-byte what the tool produced,
+ * regardless of when classification lands. (Label PLACEMENT in the mid-run race
+ * is the orchestration's job — usePolicyAutoRun resolves targets at write time;
+ * see usePolicyAutoRun.race.test.tsx. Here we lock the reducer backstop.)
+ */
+
+const stub = (
+ id: string,
+ extra: Partial = {},
+): StirlingFileStub =>
+ ({
+ id: id as FileId,
+ name: "doc.pdf",
+ versionNumber: 1,
+ ...extra,
+ }) as StirlingFileStub;
+
+function stateWith(...stubs: StirlingFileStub[]): FileContextState {
+ return {
+ files: {
+ ids: stubs.map((s) => s.id),
+ byId: Object.fromEntries(stubs.map((s) => [s.id, s])) as Record<
+ FileId,
+ StirlingFileStub
+ >,
+ },
+ pinnedFiles: new Set(),
+ ui: {
+ selectedFileIds: [],
+ selectedPageNumbers: [],
+ isProcessing: false,
+ processingProgress: 0,
+ hasUnsavedChanges: false,
+ errorFileIds: [],
+ },
+ };
+}
+
+const LABELS = ["Invoice"];
+
+// A manual tool run on `inputId` producing a new versioned document `outputId`.
+// Mirrors what useToolOperation dispatches: the reducer stamps provenance
+// (derivedFromTool, sourceFileIds) and inherits labels itself.
+const toolRun = (inputId: string, outputId: string): FileContextAction => ({
+ type: "CONSUME_FILES",
+ payload: {
+ inputFileIds: [inputId as FileId],
+ outputStirlingFileStubs: [stub(outputId, { versionNumber: 2 })],
+ silent: false,
+ },
+});
+
+// Classification stamping labels onto a target id (the reducer merges shallowly).
+const classify = (targetId: string): FileContextAction => ({
+ type: "UPDATE_FILE_RECORD",
+ payload: {
+ id: targetId as FileId,
+ updates: { classificationLabels: LABELS },
+ },
+});
+
+describe("classification landing vs a manually-run tool", () => {
+ it("PRE: classification lands first — tool output is correct AND inherits the label", () => {
+ let s = stateWith(stub("orig"));
+ s = fileContextReducer(s, classify("orig"));
+ s = fileContextReducer(s, toolRun("orig", "out"));
+
+ const out = s.files.byId["out" as FileId];
+ expect(out).toBeDefined();
+ expect(out.versionNumber).toBe(2); // the document the tool produced
+ expect(s.files.byId["orig" as FileId]).toBeUndefined(); // input consumed
+ // Label carried forward onto the tool's new version.
+ expect(out.classificationLabels).toEqual(LABELS);
+ });
+
+ it("POST: classification lands after the tool run, targeting the new leaf — output untouched, label applied, nothing else clobbered", () => {
+ let s = stateWith(stub("orig"));
+ s = fileContextReducer(s, toolRun("orig", "out"));
+
+ const before = s.files.byId["out" as FileId];
+ // classificationLabelTargets resolves the run's descendants: "out" matches
+ // because its sourceFileIds includes "orig".
+ expect(before.sourceFileIds).toContain("orig" as FileId);
+
+ s = fileContextReducer(s, classify("out"));
+ const after = s.files.byId["out" as FileId];
+
+ // The label write is a shallow merge: ONLY classificationLabels changes.
+ expect(after.classificationLabels).toEqual(LABELS);
+ expect({ ...after, classificationLabels: undefined }).toEqual({
+ ...before,
+ classificationLabels: undefined,
+ });
+ expect(after.versionNumber).toBe(2);
+ });
+
+ it("MID (the race): a label write aimed at an already-consumed id no-ops — output document is CORRECT, nothing is resurrected", () => {
+ // In production this stale-id write no longer happens: usePolicyAutoRun
+ // resolves the label targets AT WRITE TIME, so the labels land on the live
+ // leaf instead (see usePolicyAutoRun.race.test.tsx). This test locks the
+ // reducer-level BACKSTOP behind that: even if a stale id does get written,
+ // it cannot corrupt or resurrect anything.
+ let s = stateWith(stub("orig"));
+
+ const staleTargetId = "orig";
+
+ // During that window the user runs a tool: orig -> out. orig had no labels
+ // yet, so the new leaf inherits none.
+ s = fileContextReducer(s, toolRun("orig", "out"));
+ const out = s.files.byId["out" as FileId];
+ expect(out.versionNumber).toBe(2);
+ expect(out.classificationLabels).toBeUndefined();
+
+ // Classification's write finally lands — on the now-consumed snapshot id.
+ const beforeWrite = s;
+ s = fileContextReducer(s, classify(staleTargetId));
+
+ // No-op on a missing record: reducer returns the SAME state reference, so no
+ // zombie "orig" record is resurrected and nothing is corrupted.
+ expect(s).toBe(beforeWrite);
+ expect(s.files.byId["orig" as FileId]).toBeUndefined();
+
+ // The tool's output document is intact and exactly what the tool produced.
+ const finalOut = s.files.byId["out" as FileId];
+ expect(finalOut.versionNumber).toBe(2);
+ expect(finalOut.sourceFileIds).toContain("orig" as FileId);
+ // At the reducer level the stale write leaves the leaf unlabelled — which
+ // is why the orchestration resolves targets at write time instead. The
+ // DOCUMENT is unaffected either way.
+ expect(finalOut.classificationLabels).toBeUndefined();
+ });
+
+ it("classification can never overwrite a tool output's document fields (only the label)", () => {
+ // Tool output already carries its own state; classification must not disturb it.
+ let s = stateWith(
+ stub("out", {
+ versionNumber: 7,
+ thumbnailUrl: "blob:thumb",
+ isPinned: true,
+ } as Partial),
+ );
+
+ s = fileContextReducer(s, classify("out"));
+ const after = s.files.byId["out" as FileId];
+
+ expect(after.versionNumber).toBe(7);
+ expect(after.thumbnailUrl).toBe("blob:thumb");
+ expect((after as { isPinned?: boolean }).isPinned).toBe(true);
+ expect(after.classificationLabels).toEqual(LABELS);
+ });
+});
diff --git a/frontend/editor/src/core/contexts/file/contexts.ts b/frontend/editor/src/core/contexts/file/contexts.ts
index c17a178043..6bc74e11ae 100644
--- a/frontend/editor/src/core/contexts/file/contexts.ts
+++ b/frontend/editor/src/core/contexts/file/contexts.ts
@@ -4,14 +4,28 @@
import { createContext } from "react";
import {
+ FileContextState,
+ FileContextSelectors,
FileContextStateValue,
FileContextActionsValue,
} from "@app/types/fileContext";
-// Split contexts for performance
-export const FileStateContext = createContext<
- FileContextStateValue | undefined
->(undefined);
+/**
+ * Subscription store for file state. The context VALUE is stable — consumers
+ * subscribe and select slices (see useFileSelector), re-rendering only when
+ * their selected slice changes, instead of on every state change.
+ */
+export interface FileStateStore {
+ getState: () => FileContextState;
+ subscribe: (listener: () => void) => () => void;
+ /** Stable selector API (reads live state via refs). */
+ selectors: FileContextSelectors;
+}
+
+export const FileStoreContext = createContext(
+ undefined,
+);
+
export const FileActionsContext = createContext<
FileContextActionsValue | undefined
>(undefined);
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 77447003f6..db99e1c673 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -370,32 +370,57 @@ export async function addFiles(
// Collect hydrations to schedule after dispatch so updateStirlingFileStub finds files in state.
const pendingHydrations: Array<() => Promise> = [];
+ // Per-chunk persistence promises (kicked off as chunks flush, awaited before
+ // return). See flushChunk — we stream writes instead of one batch at the end.
+ const persistPromises: Array> = [];
- // Stream the batch into the workspace in chunks. The per-file pre-scan below
- // (dedupe, encryption sniff — which reads each PDF's bytes) takes real time
- // for a big folder drop; a single end-of-loop dispatch would leave the UI
- // frozen-looking for seconds and then dump hundreds of rows in one render.
- // Chunked dispatch keeps rows (and their thumbnail hydrations) streaming in,
- // and the progress store drives the sidebar's "Adding files…" indicator.
- const DISPATCH_CHUNK = 25;
+ // Dispatch stubs in chunks so rows (and thumbnail hydrations) stream in
+ // rather than dumping the whole drop in one render.
+ const DISPATCH_CHUNK = 5;
let flushedStubs = 0;
let flushedHydrations = 0;
- const flushChunk = () => {
- if (
- !options.skipWorkspaceDispatch &&
- stirlingFileStubs.length > flushedStubs
- ) {
- dispatch({
- type: "ADD_FILES",
- payload: { stirlingFileStubs: stirlingFileStubs.slice(flushedStubs) },
- });
+ // Flushes the pending chunk and returns this chunk's persistence promises,
+ // so the caller can await the writes (see the loop's yield) before the policy
+ // auto-run tries to read the file back from storage.
+ const flushChunk = (): Array> => {
+ const chunkWrites: Array> = [];
+ if (stirlingFileStubs.length > flushedStubs) {
+ const from = flushedStubs;
+ const newStubs = stirlingFileStubs.slice(from);
flushedStubs = stirlingFileStubs.length;
+ if (!options.skipWorkspaceDispatch) {
+ dispatch({
+ type: "ADD_FILES",
+ payload: { stirlingFileStubs: newStubs },
+ });
+ }
+ // Persist each chunk as it flushes, not one batch at the end: the policy
+ // auto-run reads files from IndexedDB with no in-memory fallback.
+ if (enablePersistence) {
+ const newFiles = stirlingFiles.slice(from);
+ for (let i = 0; i < newFiles.length; i++) {
+ const sf = newFiles[i];
+ const stub = newStubs[i];
+ const write = fileStorage
+ .storeStirlingFile(sf, stub)
+ .catch((error) => {
+ console.error(
+ "Failed to persist file to storage:",
+ sf.name,
+ error,
+ );
+ });
+ chunkWrites.push(write);
+ persistPromises.push(write);
+ }
+ }
}
// Hydrations only after their chunk is dispatched, so
// updateStirlingFileStub finds the files in state.
while (flushedHydrations < pendingHydrations.length) {
scheduleMetadataHydration(pendingHydrations[flushedHydrations++]);
}
+ return chunkWrites;
};
reportBulkAddProgress(0, filesToProcess.length);
@@ -554,38 +579,25 @@ export async function addFiles(
reportBulkAddProgress(++scannedCount, filesToProcess.length);
if (stirlingFileStubs.length - flushedStubs >= DISPATCH_CHUNK) {
- flushChunk();
+ const chunkWrites = flushChunk();
+ // Yield a MACROTASK so React commits this chunk and runs its effects
+ // (incl. the policy-enforcement dispatch) before the next chunk scans.
+ // The per-file awaits above are only microtasks, which don't give React
+ // a turn — without this, all dispatches batch and processing can't begin
+ // until the whole drop is scanned. Awaiting the chunk's writes first means
+ // the auto-run finds each file's bytes already committed in storage.
+ await Promise.all(chunkWrites);
+ await new Promise((resolve) => setTimeout(resolve));
}
}
// Flush the remainder (also the sole dispatch for small batches).
flushChunk();
- // Persist to storage if enabled using fileStorage service
- if (enablePersistence && stirlingFiles.length > 0) {
- await Promise.all(
- stirlingFiles.map(async (stirlingFile, index) => {
- try {
- // Get corresponding stub with all metadata
- const fileStub = stirlingFileStubs[index];
-
- // Store using the cleaner signature - pass StirlingFile + StirlingFileStub directly
- await fileStorage.storeStirlingFile(stirlingFile, fileStub);
-
- if (DEBUG)
- console.log(
- `📄 addFiles: Stored file ${stirlingFile.name} with metadata:`,
- fileStub,
- );
- } catch (error) {
- console.error(
- "Failed to persist file to storage:",
- stirlingFile.name,
- error,
- );
- }
- }),
- );
+ // Wait for the per-chunk writes (streamed in flushChunk) to commit, so
+ // addFiles only resolves once every file is durably stored.
+ if (enablePersistence && persistPromises.length > 0) {
+ await Promise.all(persistPromises);
}
if (!options.skipUploadTracking && stirlingFiles.length > 0) {
diff --git a/frontend/editor/src/core/contexts/file/fileHooks.selector.test.tsx b/frontend/editor/src/core/contexts/file/fileHooks.selector.test.tsx
new file mode 100644
index 0000000000..5a8f3243f9
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/fileHooks.selector.test.tsx
@@ -0,0 +1,223 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, act } from "@testing-library/react";
+import { useEffect } from "react";
+import { MantineProvider } from "@mantine/core";
+import { FileContextProvider } from "@app/contexts/FileContext";
+import {
+ useAllFiles,
+ useFileContext,
+ useFileSelection,
+ useFileSelectors,
+ useStirlingFileStub,
+ useFileActions,
+} from "@app/contexts/file/fileHooks";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+import type { FileContextAction } from "@app/types/fileContext";
+
+/**
+ * Proves the selector-subscription contract: a consumer re-renders only when
+ * the slice it selects changes — a single file's update doesn't re-render
+ * other files' consumers, and selection changes don't re-render list consumers.
+ */
+
+const stub = (id: string): StirlingFileStub =>
+ ({
+ id: id as FileId,
+ name: `${id}.pdf`,
+ type: "application/pdf",
+ size: 1,
+ lastModified: 0,
+ }) as StirlingFileStub;
+
+const renders: Record = {};
+let dispatchRef: React.Dispatch | null = null;
+
+function Controller() {
+ const { dispatch } = useFileActions();
+ dispatchRef = dispatch;
+ return null;
+}
+
+function StubWatcher({ fileId }: { fileId: string }) {
+ useStirlingFileStub(fileId as FileId);
+ renders[`stub-${fileId}`] = (renders[`stub-${fileId}`] ?? 0) + 1;
+ return null;
+}
+
+function ListWatcher() {
+ useAllFiles();
+ renders.list = (renders.list ?? 0) + 1;
+ return null;
+}
+
+function SelectionWatcher() {
+ useFileSelection();
+ renders.selection = (renders.selection ?? 0) + 1;
+ return null;
+}
+
+function setup() {
+ for (const key of Object.keys(renders)) delete renders[key];
+ dispatchRef = null;
+ render(
+
+
+
+
+
+
+
+
+ ,
+ );
+ act(() => {
+ dispatchRef!({
+ type: "ADD_FILES",
+ payload: { stirlingFileStubs: [stub("a"), stub("b")] },
+ });
+ });
+ return { ...renders };
+}
+
+describe("file hooks — selector subscriptions", () => {
+ it("updating one file re-renders that file's consumer, not the other's", () => {
+ const before = setup();
+ act(() => {
+ dispatchRef!({
+ type: "UPDATE_FILE_RECORD",
+ payload: { id: "b" as FileId, updates: { name: "renamed.pdf" } },
+ });
+ });
+ expect(renders["stub-b"]).toBeGreaterThan(before["stub-b"]);
+ expect(renders["stub-a"]).toBe(before["stub-a"]);
+ });
+
+ it("selection changes don't re-render file-list or per-file consumers", () => {
+ const before = setup();
+ act(() => {
+ dispatchRef!({
+ type: "SET_SELECTED_FILES",
+ payload: { fileIds: ["a" as FileId] },
+ });
+ });
+ expect(renders.selection).toBeGreaterThan(before.selection);
+ expect(renders.list).toBe(before.list);
+ expect(renders["stub-a"]).toBe(before["stub-a"]);
+ expect(renders["stub-b"]).toBe(before["stub-b"]);
+ });
+
+ it("file-list changes don't re-render selection-only consumers", () => {
+ const before = setup();
+ act(() => {
+ dispatchRef!({
+ type: "UPDATE_FILE_RECORD",
+ payload: { id: "a" as FileId, updates: { name: "x.pdf" } },
+ });
+ });
+ expect(renders.selection).toBe(before.selection);
+ });
+});
+
+describe("useFileSelectors — render-phase misuse guard", () => {
+ const guardErrors = (spy: ReturnType) =>
+ spy.mock.calls.filter((args) =>
+ String(args[0]).includes("[useFileSelectors]"),
+ );
+
+ function RenderTimeMisuse() {
+ const selectors = useFileSelectors();
+ selectors.getAllFileIds(); // during render — must be flagged
+ return null;
+ }
+
+ function EffectTimeUse() {
+ const selectors = useFileSelectors();
+ useEffect(() => {
+ selectors.getAllFileIds(); // after commit — legitimate
+ }, [selectors]);
+ return null;
+ }
+
+ it("flags a selector invoked during render", () => {
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
+ render(
+
+
+
+
+ ,
+ );
+ expect(guardErrors(spy).length).toBeGreaterThan(0);
+ spy.mockRestore();
+ });
+
+ it("does not flag selector reads from effects", () => {
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
+ render(
+
+
+
+
+ ,
+ );
+ expect(guardErrors(spy)).toHaveLength(0);
+ spy.mockRestore();
+ });
+});
+
+describe("useFileContext — render-phase misuse guard", () => {
+ // useFileContext subscribes to files + pinnedFiles only, so a render-time read
+ // of the SELECTION slice through its exposed selectors would silently go
+ // stale. The guard covers exactly those selectors and nothing else.
+ const guardErrors = (spy: ReturnType) =>
+ spy.mock.calls.filter((args) =>
+ String(args[0]).includes("[useFileContext]"),
+ );
+
+ const renderWithGuard = (node: React.ReactNode) => {
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
+ render(
+
+ {node}
+ ,
+ );
+ const errors = guardErrors(spy);
+ spy.mockRestore();
+ return errors;
+ };
+
+ function SelectionReadDuringRender() {
+ const { selectors } = useFileContext();
+ selectors.getSelectedFiles(); // unsubscribed slice — must be flagged
+ return null;
+ }
+
+ function FilesReadDuringRender() {
+ const { selectors } = useFileContext();
+ selectors.getStirlingFileStubs(); // files slice IS subscribed — legitimate
+ return null;
+ }
+
+ function SelectionReadFromEffect() {
+ const { selectors } = useFileContext();
+ useEffect(() => {
+ selectors.getSelectedFiles(); // after commit — legitimate
+ }, [selectors]);
+ return null;
+ }
+
+ it("flags a selection read during render", () => {
+ expect(
+ renderWithGuard().length,
+ ).toBeGreaterThan(0);
+ });
+
+ it("does not flag reads of a slice it subscribes to", () => {
+ expect(renderWithGuard()).toHaveLength(0);
+ });
+
+ it("does not flag selection reads from effects", () => {
+ expect(renderWithGuard()).toHaveLength(0);
+ });
+});
diff --git a/frontend/editor/src/core/contexts/file/fileHooks.ts b/frontend/editor/src/core/contexts/file/fileHooks.ts
index fcd3ba7ef7..f5c1bfc460 100644
--- a/frontend/editor/src/core/contexts/file/fileHooks.ts
+++ b/frontend/editor/src/core/contexts/file/fileHooks.ts
@@ -1,27 +1,187 @@
/**
- * Performant file hooks - Clean API using FileContext
+ * Performant file hooks — selector subscriptions over the FileStateStore.
+ * Each hook re-renders its consumer only when the slice it selects changes,
+ * not on every file-state change.
*/
-import { useContext, useMemo } from "react";
+import { useContext, useLayoutEffect, useMemo, useRef } from "react";
+import { useSyncExternalStoreWithSelector } from "use-sync-external-store/shim/with-selector.js";
import {
- FileStateContext,
+ FileStoreContext,
FileActionsContext,
+ FileStateStore,
FileContextStateValue,
FileContextActionsValue,
} from "@app/contexts/file/contexts";
-import { StirlingFileStub, StirlingFile } from "@app/types/fileContext";
+import {
+ StirlingFileStub,
+ StirlingFile,
+ FileContextState,
+ FileContextSelectors,
+} from "@app/types/fileContext";
import { FileId } from "@app/types/file";
+const GUARD_MISUSE = process.env.NODE_ENV !== "production";
+
+/** Shallow equality over object/array slices assembled by selectors. */
+export function shallowEqual(a: unknown, b: unknown): boolean {
+ if (Object.is(a, b)) return true;
+ if (
+ typeof a !== "object" ||
+ a === null ||
+ typeof b !== "object" ||
+ b === null
+ ) {
+ return false;
+ }
+ const keysA = Object.keys(a);
+ if (keysA.length !== Object.keys(b).length) return false;
+ return keysA.every((key) =>
+ Object.is(
+ (a as Record)[key],
+ (b as Record)[key],
+ ),
+ );
+}
+
+function useFileStore(): FileStateStore {
+ const store = useContext(FileStoreContext);
+ if (!store) {
+ throw new Error("File hooks must be used within a FileContextProvider");
+ }
+ return store;
+}
+
+/**
+ * Subscribe to a slice of file state. The component re-renders only when the
+ * selected value changes (Object.is by default; pass shallowEqual for slices
+ * assembled into fresh objects/arrays).
+ */
+export function useFileSelector(
+ selector: (state: FileContextState) => T,
+ isEqual?: (a: T, b: T) => boolean,
+): T {
+ const store = useFileStore();
+ return useSyncExternalStoreWithSelector(
+ store.subscribe,
+ store.getState,
+ store.getState,
+ selector,
+ isEqual,
+ );
+}
+
+/** Selectors that read `ui.selectedFileIds`. A hook that doesn't subscribe to
+ * that slice must not let consumers call these during render. */
+const SELECTION_SELECTORS: ReadonlyArray = [
+ "getSelectedFiles",
+ "getSelectedStirlingFileStubs",
+];
+
+/** Wrap selectors so a call made during render logs loudly (dev/test only).
+ * Render-time vs event-time isn't statically lintable, so this is the guard.
+ * `keys` limits the wrap to the selectors whose slice the calling hook does NOT
+ * subscribe to — the rest are safe to read during render and pass through. */
+function guardSelectors(
+ selectors: FileContextSelectors,
+ isRendering: () => boolean,
+ hookName: string,
+ keys?: ReadonlyArray,
+): FileContextSelectors {
+ const guardedKeys =
+ keys ?? (Object.keys(selectors) as Array);
+ const guarded: Record = { ...selectors };
+ for (const key of guardedKeys) {
+ const original = selectors[key] as unknown as (
+ ...args: unknown[]
+ ) => unknown;
+ guarded[key] = (...args: unknown[]) => {
+ if (isRendering()) {
+ console.error(
+ `[${hookName}] ${key}() was called during render. This read doesn't ` +
+ "subscribe to the state it depends on, so the UI can go stale — use " +
+ "useFileSelector / useFileSelection / useAllFiles for render-time data.",
+ );
+ }
+ return original(...args);
+ };
+ }
+ return guarded as unknown as FileContextSelectors;
+}
+
+/**
+ * Wrap a hook's exposed selectors in the render-phase misuse guard (no-op in
+ * production). `keys` names the selectors the calling hook doesn't subscribe to;
+ * omit it to guard every selector (for hooks that subscribe to nothing).
+ */
+function useGuardedSelectors(
+ selectors: FileContextSelectors,
+ hookName: string,
+ keys?: ReadonlyArray,
+): FileContextSelectors {
+ // True exactly while this consumer is rendering: set on every render, cleared
+ // by the layout effect once that render commits.
+ const renderPhase = useRef(false);
+ renderPhase.current = GUARD_MISUSE;
+ useLayoutEffect(() => {
+ renderPhase.current = false;
+ });
+ return useMemo(
+ () =>
+ GUARD_MISUSE
+ ? guardSelectors(selectors, () => renderPhase.current, hookName, keys)
+ : selectors,
+ [selectors, hookName, keys],
+ );
+}
+
+/**
+ * Stable selector API with NO state subscription — never re-renders. For
+ * event-time reads (callbacks/effects), which see live state when invoked.
+ * Render-time reads need a reactive hook (useAllFiles/useFileSelector) or
+ * they go stale — calling one during render logs an error outside production.
+ */
+export function useFileSelectors(): FileContextSelectors {
+ const { selectors } = useFileStore();
+ return useGuardedSelectors(selectors, "useFileSelectors");
+}
+
+/**
+ * Position of `fileId` in the resolved file list — the SAME array useAllFiles()
+ * returns, which drops ids whose bytes haven't hydrated into memory yet, so the
+ * index lines up with what consumers actually index into. 0 when unset/absent.
+ *
+ * Selects a NUMBER, so the consumer re-renders only when the index actually
+ * moves. useAllFiles() would do the job too, but it re-renders on every
+ * unrelated stub update (thumbnail hydration, labels, …) — too costly for a
+ * high-level provider whose context value isn't memoized.
+ */
+export function useFileIndex(fileId: string | null | undefined): number {
+ // Raw (unguarded) selectors: the read below runs inside the subscription
+ // selector, so it IS reactive and the render-phase guard doesn't apply.
+ const { selectors } = useFileStore();
+ return useFileSelector((s) => {
+ if (!fileId) return 0;
+ const index = selectors
+ .getFiles(s.files.ids)
+ .findIndex((file) => file.fileId === fileId);
+ return index >= 0 ? index : 0;
+ });
+}
+
/**
* Hook for accessing file state (will re-render on any state change)
* Use individual selector hooks below for better performance
*/
export function useFileState(): FileContextStateValue {
- const context = useContext(FileStateContext);
- if (!context) {
- throw new Error("useFileState must be used within a FileContextProvider");
- }
- return context;
+ const store = useFileStore();
+ const state = useFileSelector((s) => s);
+ // Selectors are exposed unguarded on purpose: this hook subscribes to the
+ // WHOLE state, so a render-time selector read can't go stale.
+ return useMemo(
+ () => ({ state, selectors: store.selectors }),
+ [state, store.selectors],
+ );
}
/**
@@ -39,21 +199,21 @@ export function useFileActions(): FileContextActionsValue {
* Hook for current/primary file (first in list)
*/
export function useCurrentFile(): { file?: File; record?: StirlingFileStub } {
- const { state, selectors } = useFileState();
-
- const primaryFileId = state.files.ids[0];
- const primaryFileRecord = primaryFileId
- ? state.files.byId[primaryFileId]
- : undefined;
+ const { selectors } = useFileStore();
+ const { primaryFileId, record } = useFileSelector(
+ (s) => ({
+ primaryFileId: s.files.ids[0],
+ record: s.files.ids[0] ? s.files.byId[s.files.ids[0]] : undefined,
+ }),
+ shallowEqual,
+ );
return useMemo(
() => ({
file: primaryFileId ? selectors.getFile(primaryFileId) : undefined,
- record: primaryFileId
- ? selectors.getStirlingFileStub(primaryFileId)
- : undefined,
+ record,
}),
- [primaryFileId, primaryFileRecord, selectors],
+ [primaryFileId, record, selectors],
);
}
@@ -61,27 +221,35 @@ export function useCurrentFile(): { file?: File; record?: StirlingFileStub } {
* Hook for file selection state and actions
*/
export function useFileSelection() {
- const { state, selectors } = useFileState();
+ const { selectors } = useFileStore();
const { actions } = useFileActions();
+ const selectedFileIds = useFileSelector((s) => s.ui.selectedFileIds);
+ const selectedPageNumbers = useFileSelector((s) => s.ui.selectedPageNumbers);
+ // Only the SELECTED files' records — an unrelated file's update never
+ // re-renders selection consumers.
+ const selectedStubs = useFileSelector(
+ (s) => s.ui.selectedFileIds.map((id) => s.files.byId[id]),
+ shallowEqual,
+ );
// Memoize selected files to avoid recreating arrays
const selectedFiles = useMemo(() => {
return selectors.getSelectedFiles();
- }, [state.ui.selectedFileIds, state.files.byId, selectors]);
+ }, [selectedFileIds, selectedStubs, selectors]);
return useMemo(
() => ({
selectedFiles,
- selectedFileIds: state.ui.selectedFileIds,
- selectedPageNumbers: state.ui.selectedPageNumbers,
+ selectedFileIds,
+ selectedPageNumbers,
setSelectedFiles: actions.setSelectedFiles,
setSelectedPages: actions.setSelectedPages,
clearSelections: actions.clearSelections,
}),
[
selectedFiles,
- state.ui.selectedFileIds,
- state.ui.selectedPageNumbers,
+ selectedFileIds,
+ selectedPageNumbers,
actions.setSelectedFiles,
actions.setSelectedPages,
actions.clearSelections,
@@ -111,57 +279,64 @@ export function useFileManagement() {
* Hook for UI state
*/
export function useFileUI() {
- const { state } = useFileState();
const { actions } = useFileActions();
+ const ui = useFileSelector(
+ (s) => ({
+ isProcessing: s.ui.isProcessing,
+ processingProgress: s.ui.processingProgress,
+ hasUnsavedChanges: s.ui.hasUnsavedChanges,
+ }),
+ shallowEqual,
+ );
return useMemo(
() => ({
- isProcessing: state.ui.isProcessing,
- processingProgress: state.ui.processingProgress,
- hasUnsavedChanges: state.ui.hasUnsavedChanges,
+ ...ui,
setProcessing: actions.setProcessing,
setUnsavedChanges: actions.setHasUnsavedChanges,
}),
- [state.ui, actions],
+ [ui, actions],
);
}
/**
- * Hook for specific file by ID (optimized for individual file access)
+ * Hook for specific file by ID (optimized for individual file access):
+ * re-renders only when THAT file's record changes.
*/
export function useStirlingFileStub(fileId: FileId): {
file?: File;
record?: StirlingFileStub;
} {
- const { state, selectors } = useFileState();
- const fileRecord = state.files.byId[fileId];
+ const { selectors } = useFileStore();
+ const record = useFileSelector((s) => s.files.byId[fileId]);
return useMemo(
() => ({
file: selectors.getFile(fileId),
- record: selectors.getStirlingFileStub(fileId),
+ record,
}),
- [fileId, fileRecord, selectors],
+ [fileId, record, selectors],
);
}
/**
- * Hook for all files (use sparingly - causes re-renders on file list changes)
+ * Hook for all files: re-renders on file-list changes only (not selection/UI).
*/
export function useAllFiles(): {
files: StirlingFile[];
fileStubs: StirlingFileStub[];
fileIds: FileId[];
} {
- const { state, selectors } = useFileState();
+ const { selectors } = useFileStore();
+ const files = useFileSelector((s) => s.files);
return useMemo(
() => ({
- files: selectors.getFiles(),
- fileStubs: selectors.getStirlingFileStubs(),
- fileIds: state.files.ids,
+ files: selectors.getFiles(files.ids),
+ fileStubs: selectors.getStirlingFileStubs(files.ids),
+ fileIds: files.ids,
}),
- [state.files.ids, state.files.byId, selectors],
+ [files, selectors],
);
}
@@ -173,30 +348,47 @@ export function useSelectedFiles(): {
selectedFileStubs: StirlingFileStub[];
selectedFileIds: FileId[];
} {
- const { state, selectors } = useFileState();
+ const { selectors } = useFileStore();
+ const selectedFileIds = useFileSelector((s) => s.ui.selectedFileIds);
+ // Only the SELECTED files' records — see useFileSelection.
+ const selectedStubs = useFileSelector(
+ (s) => s.ui.selectedFileIds.map((id) => s.files.byId[id]),
+ shallowEqual,
+ );
return useMemo(
() => ({
selectedFiles: selectors.getSelectedFiles(),
selectedFileStubs: selectors.getSelectedStirlingFileStubs(),
- selectedFileIds: state.ui.selectedFileIds,
+ selectedFileIds,
}),
- [state.ui.selectedFileIds, state.files.byId, selectors],
+ [selectedFileIds, selectedStubs, selectors],
);
}
-// Navigation management removed - moved to NavigationContext
-
/**
- * Primary API hook for file context operations
- * Used by tools for core file context functionality
+ * Primary API hook for file context operations. Used by tools for core file
+ * context functionality. Re-renders only when the slices it exposes reactively
+ * (files, pinned files) change — not on selection/UI changes.
*/
export function useFileContext() {
- const { state, selectors } = useFileState();
+ const store = useFileStore();
const { actions } = useFileActions();
+ const { files, pinnedFiles } = useFileSelector(
+ (s) => ({ files: s.files, pinnedFiles: s.pinnedFiles }),
+ shallowEqual,
+ );
+ // This hook subscribes to files + pinnedFiles, so those selectors are safe to
+ // read during render; the SELECTION ones aren't (no subscription to
+ // ui.selectedFileIds), so they carry the misuse guard.
+ const selectors = useGuardedSelectors(
+ store.selectors,
+ "useFileContext",
+ SELECTION_SELECTORS,
+ );
- return useMemo(
- () => ({
+ return useMemo(() => {
+ return {
// Lifecycle management
trackBlobUrl: actions.trackBlobUrl,
scheduleCleanup: actions.scheduleCleanup,
@@ -213,10 +405,11 @@ export function useFileContext() {
_operationId: string,
_error: string,
) => {}, // Operation tracking not implemented
- // File ID lookup
+ // File ID lookup (reads live state at call time)
findFileId: (file: File) => {
- return state.files.ids.find((id) => {
- const record = state.files.byId[id];
+ const { files: liveFiles } = store.getState();
+ return liveFiles.ids.find((id) => {
+ const record = liveFiles.byId[id];
return (
record &&
record.name === file.name &&
@@ -227,19 +420,18 @@ export function useFileContext() {
},
// Pinned files
- pinnedFiles: state.pinnedFiles,
+ pinnedFiles,
pinFile: actions.pinFile,
unpinFile: actions.unpinFile,
isFilePinned: selectors.isFilePinned,
// Active files
- activeFiles: selectors.getFiles(),
+ activeFiles: selectors.getFiles(files.ids),
openEncryptedUnlockPrompt: actions.openEncryptedUnlockPrompt,
// Direct access to actions and selectors (for advanced use cases)
actions,
selectors,
- }),
- [state, selectors, actions],
- );
+ };
+ }, [files, pinnedFiles, actions, store, selectors]);
}
diff --git a/frontend/editor/src/core/contexts/file/reducerIdentityGuard.test.ts b/frontend/editor/src/core/contexts/file/reducerIdentityGuard.test.ts
new file mode 100644
index 0000000000..c250c3e4dc
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/reducerIdentityGuard.test.ts
@@ -0,0 +1,78 @@
+import { describe, it, expect, vi, afterEach } from "vitest";
+import { withReducerIdentityGuard } from "@app/contexts/file/FileReducer";
+import type {
+ FileContextState,
+ FileContextAction,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+const stub = (id: string): StirlingFileStub =>
+ ({ id: id as FileId, name: `${id}.pdf` }) as StirlingFileStub;
+
+function baseState(): FileContextState {
+ return {
+ files: { ids: ["a" as FileId], byId: { ["a" as FileId]: stub("a") } },
+ pinnedFiles: new Set(),
+ ui: {
+ selectedFileIds: [],
+ selectedPageNumbers: [],
+ isProcessing: false,
+ processingProgress: 0,
+ hasUnsavedChanges: false,
+ errorFileIds: [],
+ },
+ };
+}
+
+const guardErrors = (spy: ReturnType) =>
+ spy.mock.calls.filter((a) => String(a[0]).includes("[FileReducer]"));
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("withReducerIdentityGuard", () => {
+ it("warns when a slice is reallocated but unchanged", () => {
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
+ // Bad reducer: rebuilds `files` (new ref) with identical contents.
+ const guarded = withReducerIdentityGuard((s) => ({
+ ...s,
+ files: { ids: [...s.files.ids], byId: { ...s.files.byId } },
+ }));
+ guarded(baseState(), { type: "NOOP" } as unknown as FileContextAction);
+ expect(guardErrors(spy)).toHaveLength(1);
+ expect(String(guardErrors(spy)[0][0])).toContain("state.files");
+ });
+
+ it("stays quiet when a slice genuinely changes", () => {
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const guarded = withReducerIdentityGuard((s) => ({
+ ...s,
+ files: {
+ ids: [...s.files.ids, "b" as FileId],
+ byId: { ...s.files.byId, ["b" as FileId]: stub("b") },
+ },
+ }));
+ guarded(baseState(), { type: "NOOP" } as unknown as FileContextAction);
+ expect(guardErrors(spy)).toHaveLength(0);
+ });
+
+ it("stays quiet when the reducer returns the same state reference", () => {
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const guarded = withReducerIdentityGuard((s) => s);
+ const state = baseState();
+ expect(
+ guarded(state, { type: "NOOP" } as unknown as FileContextAction),
+ ).toBe(state);
+ expect(guardErrors(spy)).toHaveLength(0);
+ });
+
+ it("flags a needless ui reallocation", () => {
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const guarded = withReducerIdentityGuard((s) => ({
+ ...s,
+ ui: { ...s.ui },
+ }));
+ guarded(baseState(), { type: "NOOP" } as unknown as FileContextAction);
+ expect(String(guardErrors(spy)[0][0])).toContain("state.ui");
+ });
+});
diff --git a/frontend/editor/src/core/contexts/file/useFileIndex.test.tsx b/frontend/editor/src/core/contexts/file/useFileIndex.test.tsx
new file mode 100644
index 0000000000..e10bfed517
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/useFileIndex.test.tsx
@@ -0,0 +1,128 @@
+import { describe, it, expect } from "vitest";
+import { render, act } from "@testing-library/react";
+import {
+ FileStoreContext,
+ type FileStateStore,
+} from "@app/contexts/file/contexts";
+import { useFileIndex } from "@app/contexts/file/fileHooks";
+import type {
+ FileContextSelectors,
+ FileContextState,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+/**
+ * useFileIndex replaced a render-time `selectors.getFiles()` read in
+ * ViewerContext, which never re-subscribed and so survived a file-list change
+ * that moved the active file. These tests drive a hand-built store (the real one
+ * needs IndexedDB to populate its File map) and lock the two properties the fix
+ * depends on: the index tracks the RESOLVED file list, and the consumer
+ * re-renders only when the index actually moves.
+ */
+
+function makeStore(ids: string[], resolved: string[]) {
+ let state: FileContextState = {
+ files: { ids: ids as FileId[], byId: {} },
+ } as FileContextState;
+ let resolvedIds = new Set(resolved);
+ const listeners = new Set<() => void>();
+
+ // Mirrors createFileSelectors.getFiles: maps ids through the in-memory File
+ // map and DROPS the ones whose bytes haven't landed yet.
+ const selectors = {
+ getFiles: (requested?: FileId[]) =>
+ (requested ?? state.files.ids)
+ .filter((id) => resolvedIds.has(id as string))
+ .map((id) => ({ fileId: id })),
+ } as unknown as FileContextSelectors;
+
+ const store: FileStateStore = {
+ getState: () => state,
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ selectors,
+ };
+
+ const update = (nextIds: string[], nextResolved: string[] = nextIds) => {
+ act(() => {
+ state = {
+ files: { ids: nextIds as FileId[], byId: {} },
+ } as FileContextState;
+ resolvedIds = new Set(nextResolved);
+ listeners.forEach((listener) => listener());
+ });
+ };
+
+ return { store, update };
+}
+
+function setup(ids: string[], resolved: string[], fileId: string | null) {
+ const { store, update } = makeStore(ids, resolved);
+ let renders = 0;
+ let index = -1;
+
+ function Probe() {
+ index = useFileIndex(fileId);
+ renders++;
+ return null;
+ }
+
+ render(
+
+
+ ,
+ );
+
+ return { update, get: () => index, renderCount: () => renders };
+}
+
+describe("useFileIndex", () => {
+ it("reports the active file's position in the resolved list", () => {
+ const { get } = setup(["a", "b", "c"], ["a", "b", "c"], "c");
+ expect(get()).toBe(2);
+ });
+
+ it("skips ids whose bytes haven't hydrated, matching what consumers index into", () => {
+ // "a" has no File yet, so getFiles() yields [b, c] — "c" sits at 1, not 2.
+ const { get } = setup(["a", "b", "c"], ["b", "c"], "c");
+ expect(get()).toBe(1);
+ });
+
+ it("updates when the list reorders under a stable active file", () => {
+ // The regression this fixes: activeFileId never changed, so the old
+ // useMemo kept returning the pre-reorder index.
+ const { get, update } = setup(["a", "b", "c"], ["a", "b", "c"], "c");
+ expect(get()).toBe(2);
+ update(["c", "a", "b"]);
+ expect(get()).toBe(0);
+ });
+
+ it("updates when a file ahead of the active one is removed", () => {
+ const { get, update } = setup(["a", "b", "c"], ["a", "b", "c"], "c");
+ update(["b", "c"]);
+ expect(get()).toBe(1);
+ });
+
+ it("falls back to 0 when the active file leaves the list", () => {
+ const { get, update } = setup(["a", "b"], ["a", "b"], "b");
+ update(["a"]);
+ expect(get()).toBe(0);
+ });
+
+ it("returns 0 with no active file", () => {
+ const { get } = setup(["a", "b"], ["a", "b"], null);
+ expect(get()).toBe(0);
+ });
+
+ it("does not re-render when a store change leaves the index alone", () => {
+ // Selecting a NUMBER is the point: appending after the active file, or any
+ // unrelated stub churn, must not re-render the consumer.
+ const { get, update, renderCount } = setup(["a", "b"], ["a", "b"], "a");
+ const before = renderCount();
+ update(["a", "b", "c"]);
+ expect(get()).toBe(0);
+ expect(renderCount()).toBe(before);
+ });
+});
diff --git a/frontend/editor/src/core/tools/Convert.tsx b/frontend/editor/src/core/tools/Convert.tsx
index de29e4ae94..b1d214f1a6 100644
--- a/frontend/editor/src/core/tools/Convert.tsx
+++ b/frontend/editor/src/core/tools/Convert.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { useEndpointEnabled } from "@app/hooks/useEndpointConfig";
-import { useFileState } from "@app/contexts/FileContext";
+import { useAllFiles } from "@app/contexts/FileContext";
import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";
import { createToolFlow } from "@app/components/tools/shared/createToolFlow";
@@ -14,8 +14,7 @@ import { BaseToolProps, ToolComponent } from "@app/types/tool";
const Convert = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
const { t } = useTranslation();
- const { selectors } = useFileState();
- const activeFiles = selectors.getFiles();
+ const { files: activeFiles } = useAllFiles();
const selectedFiles = useViewScopedFiles();
const scrollContainerRef = useRef(null);
diff --git a/frontend/editor/src/desktop/hooks/useExitWarning.ts b/frontend/editor/src/desktop/hooks/useExitWarning.ts
index 1e6b4423fc..4a5b16fb8f 100644
--- a/frontend/editor/src/desktop/hooks/useExitWarning.ts
+++ b/frontend/editor/src/desktop/hooks/useExitWarning.ts
@@ -1,14 +1,14 @@
import { useEffect, useRef } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { message } from "@tauri-apps/plugin-dialog";
-import { useFileState, useFileActions } from "@app/contexts/FileContext";
+import { useFileSelectors, useFileActions } from "@app/contexts/FileContext";
import { downloadFile } from "@app/services/downloadService";
import type { StirlingFileStub } from "@app/types/fileContext";
import { useTranslation } from "react-i18next";
export function useExitWarning() {
const { t } = useTranslation();
- const { selectors } = useFileState();
+ const selectors = useFileSelectors();
const { actions: fileActions } = useFileActions();
const selectorsRef = useRef(selectors);
const isClosingRef = useRef(false);
diff --git a/frontend/editor/src/desktop/hooks/useSaveShortcut.ts b/frontend/editor/src/desktop/hooks/useSaveShortcut.ts
index 927d5f06cf..b3faa64bb7 100644
--- a/frontend/editor/src/desktop/hooks/useSaveShortcut.ts
+++ b/frontend/editor/src/desktop/hooks/useSaveShortcut.ts
@@ -1,5 +1,9 @@
import { useEffect } from "react";
-import { useFileState, useFileActions } from "@app/contexts/FileContext";
+import {
+ useFileSelector,
+ useFileSelectors,
+ useFileActions,
+} from "@app/contexts/FileContext";
// Save through the export gateway so a "run on export" policy enforces before
// the file is written out (no-op when no such policy is active).
import { downloadFileWithPolicy as downloadFile } from "@app/services/exportWithPolicy";
@@ -10,7 +14,8 @@ import { downloadFileWithPolicy as downloadFile } from "@app/services/exportWith
* Matches WorkbenchBar button behavior: saves selected files if any, otherwise all files
*/
export function useSaveShortcut() {
- const { selectors, state } = useFileState();
+ const selectors = useFileSelectors();
+ const currentSelectedFileIds = useFileSelector((s) => s.ui.selectedFileIds);
const { actions: fileActions } = useFileActions();
useEffect(() => {
@@ -20,7 +25,7 @@ export function useSaveShortcut() {
event.preventDefault();
// Get selected files or all files if nothing selected
- const selectedFileIds = state.ui.selectedFileIds;
+ const selectedFileIds = currentSelectedFileIds;
const filesToSave =
selectedFileIds.length > 0
? selectors.getFiles(selectedFileIds)
@@ -63,5 +68,5 @@ export function useSaveShortcut() {
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
- }, [selectors, state.ui.selectedFileIds, fileActions]);
+ }, [selectors, currentSelectedFileIds, fileActions]);
}
diff --git a/frontend/editor/src/proprietary/components/policies/classificationLabelTargets.test.ts b/frontend/editor/src/proprietary/components/policies/classificationLabelTargets.test.ts
new file mode 100644
index 0000000000..74baf59006
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/classificationLabelTargets.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from "vitest";
+import { classificationLabelTargetStubs } from "@app/components/policies/usePolicyAutoRun";
+import type { StirlingFileStub } from "@app/types/fileContext";
+
+// Loosely-typed builder: FileId is a branded string, so accept plain string ids
+// in tests and cast — classificationLabelTargetStubs only reads id/parent/sources.
+const stub = (s: {
+ id: string;
+ parentFileId?: string;
+ sourceFileIds?: string[];
+}): StirlingFileStub => s as unknown as StirlingFileStub;
+
+const ids = (stubs: StirlingFileStub[]) => stubs.map((s) => s.id as string);
+
+describe("classificationLabelTargetStubs", () => {
+ it("targets the run's own file when it's still the leaf", () => {
+ const stubs = [stub({ id: "a" }), stub({ id: "b" })];
+ expect(ids(classificationLabelTargetStubs("a", stubs))).toEqual(["a"]);
+ });
+
+ it("targets a descendant leaf when the file was edited during the run", () => {
+ // "a" was consumed into leaf "a2" (edit forked a new version mid-run).
+ const stubs = [stub({ id: "a2", sourceFileIds: ["a"] })];
+ expect(ids(classificationLabelTargetStubs("a", stubs))).toEqual(["a2"]);
+ });
+
+ it("targets a direct child via parentFileId", () => {
+ const stubs = [stub({ id: "a2", parentFileId: "a" })];
+ expect(ids(classificationLabelTargetStubs("a", stubs))).toEqual(["a2"]);
+ });
+
+ it("returns the stubs themselves, so the caller can see what's already tagged", () => {
+ const target = stub({ id: "a" });
+ expect(classificationLabelTargetStubs("a", [target])[0]).toBe(target);
+ });
+
+ it("is empty when the document has left the workspace (file closed)", () => {
+ // No fallback to the run's own id: stamping a consumed id would no-op
+ // anyway, and an empty result lets the caller settle without downloading.
+ expect(classificationLabelTargetStubs("a", [stub({ id: "z" })])).toEqual(
+ [],
+ );
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/dispatchSemaphore.test.ts b/frontend/editor/src/proprietary/components/policies/dispatchSemaphore.test.ts
new file mode 100644
index 0000000000..355d8b5526
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/dispatchSemaphore.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect, beforeEach } from "vitest";
+import {
+ acquireDispatchSlot,
+ releaseDispatchSlot,
+ resetDispatchSemaphoreForTests,
+} from "@app/components/policies/dispatchSemaphore";
+
+// Drain the microtask queue so an acquire's await-resume AND the caller's .then
+// have both run.
+const flush = () => new Promise((r) => setTimeout(r, 0));
+
+beforeEach(() => resetDispatchSemaphoreForTests());
+
+describe("dispatchSemaphore", () => {
+ it("lets up to 4 acquire without waiting, then blocks the 5th", async () => {
+ for (let i = 0; i < 4; i++) await acquireDispatchSlot();
+ let fifthAcquired = false;
+ void acquireDispatchSlot().then(() => {
+ fifthAcquired = true;
+ });
+ await flush();
+ expect(fifthAcquired).toBe(false);
+ releaseDispatchSlot();
+ await flush();
+ expect(fifthAcquired).toBe(true);
+ });
+
+ it("serves a priority (chained) waiter before earlier normal waiters", async () => {
+ for (let i = 0; i < 4; i++) await acquireDispatchSlot(); // pool full
+ const order: string[] = [];
+ // Two normal (new-file) dispatches queue first…
+ void acquireDispatchSlot(false).then(() => order.push("normal-1"));
+ void acquireDispatchSlot(false).then(() => order.push("normal-2"));
+ // …then a chained dispatch arrives — it must jump ahead.
+ void acquireDispatchSlot(true).then(() => order.push("chained"));
+ await flush();
+
+ releaseDispatchSlot();
+ await flush();
+ releaseDispatchSlot();
+ await flush();
+ releaseDispatchSlot();
+ await flush();
+
+ expect(order).toEqual(["chained", "normal-1", "normal-2"]);
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/dispatchSemaphore.ts b/frontend/editor/src/proprietary/components/policies/dispatchSemaphore.ts
new file mode 100644
index 0000000000..d5119e5923
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/dispatchSemaphore.ts
@@ -0,0 +1,42 @@
+/**
+ * Bounded concurrency for policy run-dispatch uploads.
+ *
+ * Each dispatch POSTs a file's bytes; firing a whole drop at once saturates the
+ * browser's per-origin connection pool, so status polls and output downloads of
+ * already-running files queue behind the pending uploads and nothing visibly
+ * progresses. A small window keeps connections free.
+ *
+ * `priority` (a chained/downstream dispatch) jumps to the FRONT of the queue, so
+ * a file already mid-chain finishes its whole policy flow before a brand-new
+ * file's first policy starts. Without it a chained dispatch would sit behind the
+ * entire first-policy wave (FIFO) — e.g. classification wouldn't start on any
+ * file until security had finished on all of them.
+ */
+const MAX_CONCURRENT_DISPATCHES = 4;
+
+let slotsInUse = 0;
+const waiters: Array<() => void> = [];
+
+export async function acquireDispatchSlot(priority = false): Promise {
+ if (slotsInUse < MAX_CONCURRENT_DISPATCHES) {
+ slotsInUse++;
+ return;
+ }
+ await new Promise((resolve) => {
+ if (priority) waiters.unshift(resolve);
+ else waiters.push(resolve);
+ });
+}
+
+export function releaseDispatchSlot(): void {
+ const next = waiters.shift();
+ // Hand the slot straight to the next waiter, else free it.
+ if (next) next();
+ else slotsInUse--;
+}
+
+/** Test-only: reset module state between cases. */
+export function resetDispatchSemaphoreForTests(): void {
+ slotsInUse = 0;
+ waiters.length = 0;
+}
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
index 5837bfb285..bc4fa54dff 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.batch.test.tsx
@@ -2,21 +2,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderHook, act } from "@testing-library/react";
/**
- * Batch integration test for the policy auto-run orchestration, at the scale the
- * user hit the bug: 61 files uploaded at once, two active upload policies
- * (Classification → Security) chained. Drives the REAL policyRunStore + the REAL
- * hook effects (dispatch → poll → import → chain), mocking only the IO boundaries
- * (network, storage, thumbnail/stub creation).
- *
- * Proves the invariants the user asked for:
- * - 61 files ⇒ exactly 122 runs (61 classification, then 61 security).
- * - Delivery is SILENT + in place (consumeFiles called with { silent: true }),
- * never adding a second copy — the workspace never grows past 61.
- * - No runaway: if the loop guard regressed, the run count would blow past 122
- * (or the test would time out), so an exact 122 is a hard regression gate.
- * - Closing all files mid-run does NOT re-open them: with the workspace emptied,
- * outputs are delivered to storage (persistVersionedOutputs), never re-added
- * to the workspace via consumeFiles.
+ * Batch integration test (61 files, two chained upload policies) driving the real
+ * store + hook effects, IO mocked. Classification is forced last (see the sort).
*/
const FILE_COUNT = 61;
@@ -25,13 +12,15 @@ const FILE_COUNT = 61;
// the workbench, mirrored into useAllFiles. consumeFiles mutates it in place
// (input id → output id) exactly as the real silent reducer would.
const mocks = vi.hoisted(() => ({
- workspace: [] as Array<{ id: string }>,
+ workspace: [] as Array<{ id: string; classificationLabels?: string[] }>,
consumeSilentCalls: 0,
consumeNonSilentCalls: 0,
persistCalls: 0,
addFilesCalls: 0,
stubCounter: 0,
backendOutCounter: 0,
+ dispatchInFlight: 0,
+ maxDispatchInFlight: 0,
bumpRevision: vi.fn(),
runStoredPolicy: vi.fn(),
getPolicyRun: vi.fn(),
@@ -66,7 +55,8 @@ vi.mock("@app/contexts/IndexedDBContext", () => ({
vi.mock("@app/hooks/usePolicies", () => ({
usePolicies: () => ({
policies: {
- // Classification runs first (order 0), Security second (order 1).
+ // Classification is configured first (order 0) but is FORCED to run last
+ // by the orchestrator; Security (order 1) therefore runs first.
classification: {
configured: true,
status: "active",
@@ -107,7 +97,9 @@ vi.mock("@app/services/fileStubHelpers", () => ({
createStirlingFilesAndStubs: mocks.createStirlingFilesAndStubs,
}));
vi.mock("@app/services/fileClassification", () => ({
- readClassificationLabelsFromFile: vi.fn().mockResolvedValue(null),
+ // Classification always resolves labels here, so the metadata-only import path
+ // stamps them onto the stub.
+ readClassificationLabelsFromFile: vi.fn().mockResolvedValue(["Invoice"]),
}));
import { usePolicyAutoRun } from "@app/components/policies/usePolicyAutoRun";
@@ -141,6 +133,8 @@ beforeEach(() => {
mocks.addFilesCalls = 0;
mocks.stubCounter = 0;
mocks.backendOutCounter = 0;
+ mocks.dispatchInFlight = 0;
+ mocks.maxDispatchInFlight = 0;
mocks.workspace = Array.from({ length: FILE_COUNT }, (_, i) => ({
id: `file-${i}`,
@@ -155,15 +149,31 @@ beforeEach(() => {
mocks.persistVersionedOutputs.mockImplementation(async () => {
mocks.persistCalls += 1;
});
- mocks.updateFileMetadata.mockResolvedValue(false);
+ mocks.updateFileMetadata.mockResolvedValue(true);
mocks.downloadPolicyOutput.mockResolvedValue(
new Blob(["x"], { type: "application/pdf" }),
);
+ // Apply stub updates to the shared workspace, as the real reducer does — the
+ // label stamp's second pass reads them back to stay idempotent.
+ mocks.updateStirlingFileStub.mockImplementation(
+ (id: string, updates: Record) => {
+ const stub = mocks.workspace.find((s) => s.id === id);
+ if (stub) Object.assign(stub, updates);
+ },
+ );
// Each dispatch gets a unique run id; the run's single backend output likewise.
- mocks.runStoredPolicy.mockImplementation(
- async () => `run-${mocks.stubCounter++}`,
- );
+ // Takes real time so overlapping dispatches are measurable (the upload window).
+ mocks.runStoredPolicy.mockImplementation(async () => {
+ mocks.dispatchInFlight++;
+ mocks.maxDispatchInFlight = Math.max(
+ mocks.maxDispatchInFlight,
+ mocks.dispatchInFlight,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 2));
+ mocks.dispatchInFlight--;
+ return `run-${mocks.stubCounter++}`;
+ });
mocks.getPolicyRun.mockImplementation(async (runId: string) => ({
runId,
policyId: null,
@@ -225,8 +235,8 @@ async function runUntilSettled(expectedRuns: number) {
});
}
-describe("policy auto-run — 61-file batch through a Classification → Security chain", () => {
- it("produces exactly 122 runs (61 classification, then 61 security)", async () => {
+describe("policy auto-run — 61-file batch through a Security → Classification chain", () => {
+ it("produces exactly 122 runs (61 security, then 61 classification)", async () => {
await runUntilSettled(FILE_COUNT * 2);
const classification = latestRuns.filter(
@@ -239,15 +249,26 @@ describe("policy auto-run — 61-file batch through a Classification → Securit
expect(latestRuns).toHaveLength(FILE_COUNT * 2);
});
- it("delivers every output SILENTLY in place — workspace never grows past 61", async () => {
+ it("bounds concurrent dispatch uploads so polls/downloads keep connections", async () => {
+ await runUntilSettled(FILE_COUNT * 2);
+ expect(mocks.maxDispatchInFlight).toBeGreaterThan(1); // still parallel…
+ expect(mocks.maxDispatchInFlight).toBeLessThanOrEqual(4); // …but windowed
+ });
+
+ it("versions on Security in place, tags on Classification — workspace never grows past 61", async () => {
await runUntilSettled(FILE_COUNT * 2);
- // 122 deliveries, all silent (background), none via the disruptive path.
- expect(mocks.consumeSilentCalls).toBe(FILE_COUNT * 2);
+ // Only the 61 Security runs fork a version, and every one silently in place.
+ expect(mocks.consumeSilentCalls).toBe(FILE_COUNT);
expect(mocks.consumeNonSilentCalls).toBe(0);
+ // Classification never forks a version — it only stamps labels onto the stub.
+ expect(mocks.updateStirlingFileStub).toHaveBeenCalledTimes(FILE_COUNT);
+ for (const call of mocks.updateStirlingFileStub.mock.calls) {
+ expect(call[1]).toEqual({ classificationLabels: ["Invoice"] });
+ }
// Never added as brand-new files either.
expect(mocks.addFilesCalls).toBe(0);
- // In-place versioning: each file replaced twice, count unchanged.
+ // In-place versioning + metadata-only tagging: count unchanged.
expect(mocks.workspace).toHaveLength(FILE_COUNT);
});
@@ -273,8 +294,8 @@ describe("policy auto-run — 61-file batch through a Classification → Securit
);
});
- // Still fully processed (chain intact), but delivered to STORAGE, never
- // re-added to the workbench — the workspace stays empty.
+ // Still fully processed (chain intact), but Security's versions went to
+ // STORAGE, never re-added to the workbench — the workspace stays empty.
expect(latestRuns).toHaveLength(FILE_COUNT * 2);
expect(mocks.workspace).toHaveLength(0);
expect(mocks.consumeSilentCalls).toBe(0);
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx
new file mode 100644
index 0000000000..b67648e7fc
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.race.test.tsx
@@ -0,0 +1,293 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { renderHook, act } from "@testing-library/react";
+
+/**
+ * Mid-run race: classification is in flight (its labelled output is still
+ * downloading) when the user manually runs a tool on the same file — e.g.
+ * quickly redacting it — which consumes the input and forks a new leaf.
+ *
+ * The label targets must be resolved AT WRITE TIME (after the download/parse
+ * window), not snapshotted at run completion: a stale snapshot points at the
+ * consumed id, no-ops, and silently loses the labels — the file then shows the
+ * classification badge (provenance-resolved) but never gets its labels.
+ */
+
+const mocks = vi.hoisted(() => ({
+ workspace: [] as Array<{
+ id: string;
+ sourceFileIds?: string[];
+ derivedFromTool?: boolean;
+ classificationLabels?: string[];
+ }>,
+ runStoredPolicy: vi.fn(),
+ getPolicyRun: vi.fn(),
+ listPolicyRuns: vi.fn(),
+ downloadPolicyOutput: vi.fn(),
+ getStirlingFile: vi.fn(),
+ getStirlingFileStub: vi.fn(),
+ persistVersionedOutputs: vi.fn(),
+ updateFileMetadata: vi.fn(),
+ createStirlingFilesAndStubs: vi.fn(),
+ addFiles: vi.fn(),
+ updateStirlingFileStub: vi.fn(),
+ consumeFiles: vi.fn(),
+ bumpRevision: vi.fn(),
+}));
+
+// Classification chains server-side only when the AI engine is on (else it runs
+// client-side); this race is in the server import path, so force the engine on.
+vi.mock("@app/hooks/useAiEngineEnabled", () => ({
+ useAiEngineEnabled: () => true,
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useAllFiles: () => ({ fileStubs: mocks.workspace }),
+ useFileManagement: () => ({
+ addFiles: mocks.addFiles,
+ updateStirlingFileStub: mocks.updateStirlingFileStub,
+ }),
+ useFileContext: () => ({ consumeFiles: mocks.consumeFiles }),
+}));
+vi.mock("@app/contexts/IndexedDBContext", () => ({
+ useIndexedDB: () => ({ bumpRevision: mocks.bumpRevision }),
+}));
+vi.mock("@app/hooks/usePolicies", () => ({
+ usePolicies: () => ({
+ policies: {
+ classification: {
+ configured: true,
+ status: "active",
+ backendId: "backend-classification",
+ runOn: "upload",
+ order: 0,
+ outputMode: "new_version",
+ outputName: "",
+ },
+ },
+ }),
+}));
+vi.mock("@app/services/policyApi", () => ({
+ runStoredPolicy: mocks.runStoredPolicy,
+ getPolicyRun: mocks.getPolicyRun,
+ listPolicyRuns: mocks.listPolicyRuns,
+ downloadPolicyOutput: mocks.downloadPolicyOutput,
+ resolvePolicyRunTarget: () => "saas",
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile: mocks.getStirlingFile,
+ getStirlingFileStub: mocks.getStirlingFileStub,
+ persistVersionedOutputs: mocks.persistVersionedOutputs,
+ updateFileMetadata: mocks.updateFileMetadata,
+ },
+}));
+vi.mock("@app/services/fileStubHelpers", () => ({
+ createStirlingFilesAndStubs: mocks.createStirlingFilesAndStubs,
+}));
+vi.mock("@app/services/fileClassification", () => ({
+ readClassificationLabelsFromFile: vi.fn().mockResolvedValue(["Invoice"]),
+}));
+
+import { usePolicyAutoRun } from "@app/components/policies/usePolicyAutoRun";
+import {
+ usePolicyRuns,
+ resetPolicyRuns,
+} from "@app/components/policies/policyRunStore";
+import type { PolicyRunRecord } from "@app/components/policies/policyRunStore";
+
+let latestRuns: PolicyRunRecord[] = [];
+function Harness() {
+ usePolicyAutoRun();
+ latestRuns = usePolicyRuns();
+ return null;
+}
+
+function deferred() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ resetPolicyRuns();
+ vi.clearAllMocks();
+
+ mocks.workspace = [{ id: "file-0" }];
+
+ mocks.listPolicyRuns.mockResolvedValue([]);
+ mocks.getStirlingFile.mockResolvedValue(
+ new File(["x"], "doc.pdf", { type: "application/pdf" }),
+ );
+ mocks.getStirlingFileStub.mockResolvedValue(null);
+ mocks.updateFileMetadata.mockResolvedValue(true);
+ // Apply stub updates to the shared workspace, as the real reducer does — the
+ // label stamp's second pass reads them back to stay idempotent.
+ mocks.updateStirlingFileStub.mockImplementation(
+ (id: string, updates: Record) => {
+ const stub = mocks.workspace.find((s) => s.id === id);
+ if (stub) Object.assign(stub, updates);
+ },
+ );
+ mocks.runStoredPolicy.mockResolvedValue("run-0");
+ mocks.getPolicyRun.mockResolvedValue({
+ runId: "run-0",
+ policyId: null,
+ status: "COMPLETED",
+ currentStep: 1,
+ stepCount: 1,
+ error: null,
+ outputs: [{ fileId: "backend-out-0", fileName: "doc.pdf" }],
+ });
+});
+
+async function settleImport(timeout = 8000) {
+ await act(async () => {
+ await vi.waitFor(
+ () => {
+ expect(latestRuns.filter((r) => r.imported)).toHaveLength(1);
+ },
+ { timeout, interval: 20 },
+ );
+ });
+}
+
+describe("classification vs a mid-run manual tool edit", () => {
+ it("labels land on the forked leaf when a tool consumes the file during the label download", async () => {
+ // The classified output's download hangs until we release it — this is the
+ // async window the user's edit slips into.
+ const download = deferred();
+ mocks.downloadPolicyOutput.mockReturnValue(download.promise);
+
+ const { rerender } = renderHook(() => Harness());
+
+ // Run dispatched, completed, import started — now hanging in the window.
+ await act(async () => {
+ await vi.waitFor(
+ () => expect(mocks.downloadPolicyOutput).toHaveBeenCalled(),
+ { timeout: 8000, interval: 20 },
+ );
+ });
+
+ // User quickly redacts: the tool consumes file-0 and forks a new leaf.
+ // (derivedFromTool + sourceFileIds are what CONSUME_FILES stamps.)
+ act(() => {
+ mocks.workspace = [
+ {
+ id: "file-0~redacted",
+ sourceFileIds: ["file-0"],
+ derivedFromTool: true,
+ },
+ ];
+ rerender();
+ });
+
+ // The download finally lands.
+ download.resolve(new Blob(["x"], { type: "application/pdf" }));
+ await settleImport();
+
+ // Labels stamped onto the LIVE leaf, not no-oped on the consumed id.
+ const stampedIds = mocks.updateStirlingFileStub.mock.calls.map((c) => c[0]);
+ expect(stampedIds).toEqual(["file-0~redacted"]);
+ expect(mocks.updateStirlingFileStub).toHaveBeenCalledWith(
+ "file-0~redacted",
+ { classificationLabels: ["Invoice"] },
+ );
+ // Badge persists on the leaf: the run's outputFileIds are the tagged files.
+ expect(latestRuns[0].outputFileIds).toEqual(["file-0~redacted"]);
+ });
+
+ it("control: with no mid-run edit, labels land on the original file", async () => {
+ mocks.downloadPolicyOutput.mockResolvedValue(
+ new Blob(["x"], { type: "application/pdf" }),
+ );
+
+ renderHook(() => Harness());
+ await settleImport();
+
+ expect(mocks.updateStirlingFileStub).toHaveBeenCalledWith("file-0", {
+ classificationLabels: ["Invoice"],
+ });
+ expect(latestRuns[0].outputFileIds).toEqual(["file-0"]);
+ });
+
+ it("stamps the forked leaf when the consume lands in the same frame as the first stamp", async () => {
+ // Tighter than the case above: the consume is dispatched but hasn't rendered
+ // when the labels are stamped, so the workspace snapshot still shows file-0
+ // and that stamp no-ops against the real reducer. The post-commit second pass
+ // is what saves the labels.
+ mocks.downloadPolicyOutput.mockResolvedValue(
+ new Blob(["x"], { type: "application/pdf" }),
+ );
+ mocks.updateStirlingFileStub.mockImplementation((id: string) => {
+ // file-0 is already consumed, so its stamp is lost (no Object.assign) and
+ // the forked leaf only becomes visible afterwards. Mutate the workspace in
+ // place: the hook holds it by ref, which is what the second pass re-reads.
+ if (id === "file-0") {
+ mocks.workspace.splice(0, mocks.workspace.length, {
+ id: "file-0~redacted",
+ sourceFileIds: ["file-0"],
+ });
+ return;
+ }
+ const stub = mocks.workspace.find((s) => s.id === id);
+ if (stub) Object.assign(stub, { classificationLabels: ["Invoice"] });
+ });
+
+ renderHook(() => Harness());
+ await settleImport();
+
+ const stampedIds = mocks.updateStirlingFileStub.mock.calls.map((c) => c[0]);
+ expect(stampedIds).toEqual(["file-0", "file-0~redacted"]);
+ // The leaf becoming visible also queues its own classification run, so pick
+ // the settled one rather than assuming an index.
+ const imported = latestRuns.find((r) => r.imported);
+ expect(imported?.outputFileIds).toContain("file-0~redacted");
+ });
+});
+
+// The label read backs off between attempts (2s, then 4s), so these run on fake
+// timers — sleeping for real would hold a worker long enough to starve the suite.
+describe("classification label-read failures", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ async function settleOnFakeTime(maxMs = 30_000) {
+ for (let elapsed = 0; elapsed < maxMs; elapsed += 250) {
+ if (latestRuns.some((r) => r.imported)) return;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(250);
+ });
+ }
+ throw new Error("classification run never settled");
+ }
+
+ it("retries a transient failure instead of leaving the run unsettled", async () => {
+ // The import effect only re-runs when the run store changes, so bailing out
+ // on a transient failure would leave this run "running" forever.
+ mocks.downloadPolicyOutput
+ .mockRejectedValueOnce(new Error("network blip"))
+ .mockResolvedValue(new Blob(["x"], { type: "application/pdf" }));
+
+ renderHook(() => Harness());
+ await settleOnFakeTime();
+
+ expect(mocks.downloadPolicyOutput).toHaveBeenCalledTimes(2);
+ expect(mocks.updateStirlingFileStub).toHaveBeenCalledWith("file-0", {
+ classificationLabels: ["Invoice"],
+ });
+ });
+
+ it("settles a run whose labels never become readable", async () => {
+ // Permanent failure: give up after the retry budget and settle unlabelled,
+ // rather than spinning the file's "running" pill indefinitely.
+ mocks.downloadPolicyOutput.mockRejectedValue(new Error("network down"));
+
+ renderHook(() => Harness());
+ await settleOnFakeTime();
+
+ expect(mocks.updateStirlingFileStub).not.toHaveBeenCalled();
+ expect(latestRuns.find((r) => r.imported)?.outputFileIds).toEqual([]);
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
index c25f80ce65..3c54e5cc42 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.retry.test.tsx
@@ -69,8 +69,17 @@ afterEach(() => vi.useRealTimers());
describe("auto-run queue-rejection retry", () => {
it("relabels a queue-rejected run as retrying, then re-dispatches it in place", async () => {
- // The polled run comes back queue-rejected; the retry resolves the file + fires a fresh run.
- getRunApi.mockResolvedValue(queueFullView);
+ // The polled run comes back queue-rejected once; the retry resolves the file
+ // and fires a fresh run, whose own polls then see it genuinely running.
+ getRunApi.mockResolvedValueOnce(queueFullView).mockResolvedValue({
+ runId: "run-2",
+ status: "RUNNING",
+ currentStep: 1,
+ stepCount: 2,
+ error: null,
+ errorCode: null,
+ outputs: [],
+ } as never);
getFile.mockResolvedValue({ size: 1234 } as never);
runStored.mockResolvedValue("run-2");
@@ -92,19 +101,20 @@ describe("auto-run queue-rejection retry", () => {
return usePolicyRuns();
});
- // First poll (2s cadence) sees the rejection → relabel as a soft "retrying" row.
+ // First poll sees the rejection → relabel as a soft "retrying" row.
await act(async () => {
await vi.advanceTimersByTimeAsync(2000);
});
expect(getRun("run-1")?.retrying).toBe(true);
expect(runStored).not.toHaveBeenCalled();
- // After the first backoff window (BASE 4s) the rejected record is dropped and a fresh run fires.
+ // After the first backoff window (BASE 4s) the rejected record is dropped and
+ // a fresh run fires; its own first poll shows it genuinely running.
await act(async () => {
- await vi.advanceTimersByTimeAsync(4000);
+ await vi.advanceTimersByTimeAsync(6000);
});
expect(runStored).toHaveBeenCalledWith("backend-1", [{ size: 1234 }]);
expect(getRun("run-1")).toBeUndefined();
- expect(getRun("run-2")?.status).toBe("PENDING");
+ expect(getRun("run-2")?.status).toBe("RUNNING");
});
});
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
index ca096b6792..e475d784ea 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
@@ -39,6 +39,11 @@ import { dispatchPaygLimitReached } from "@app/services/usageLimitBridge";
import type { FileId } from "@app/types/file";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
import { readClassificationLabelsFromFile } from "@app/services/fileClassification";
+import { isClassificationCategory } from "@app/data/policyCategories";
+import {
+ acquireDispatchSlot,
+ releaseDispatchSlot,
+} from "@app/components/policies/dispatchSemaphore";
import type { StirlingFile, StirlingFileStub } from "@app/types/fileContext";
import type { PoliciesByCategory } from "@app/types/policies";
import { usePolicies } from "@app/hooks/usePolicies";
@@ -59,6 +64,10 @@ import {
/** Status poll cadence. */
const POLL_MS = 2000;
+/** First poll fires early so a fresh run shows real progress quickly instead of
+ * sitting on an indeterminate spinner for a full poll interval. */
+const FIRST_POLL_MS = 500;
+
/** The server aborts any single tool step that runs longer than its internal-API
* read timeout, then fails the run — so a run can legitimately stay in flight
* for up to this long per step. The client must keep polling at least that long,
@@ -175,7 +184,14 @@ export function usePolicyAutoRun(): void {
// Classification policy out of the server chain when the AI engine is off.
!(id === "classification" && !aiEnabled),
)
- .sort(([, a], [, b]) => (a.order ?? 0) - (b.order ?? 0))
+ // Classification runs last: it's non-blocking, so an enforcement policy
+ // running after it would fork a new version and drop the user's edits.
+ .sort(([idA, a], [idB, b]) => {
+ const ca = isClassificationCategory(idA) ? 1 : 0;
+ const cb = isClassificationCategory(idB) ? 1 : 0;
+ if (ca !== cb) return ca - cb;
+ return (a.order ?? 0) - (b.order ?? 0);
+ })
.map(([id]) => id),
[policies, aiEnabled],
);
@@ -310,6 +326,7 @@ export function usePolicyAutoRun(): void {
backendId,
outputId as FileId,
run.fileName,
+ true, // chained → jump the dispatch queue ahead of new files
).catch(() => {});
}
}
@@ -330,15 +347,33 @@ export function usePolicyAutoRun(): void {
// so the enforced file appears in the app rather than only on the backend.
useEffect(() => {
for (const run of runs) {
+ const classification = isClassificationCategory(run.categoryId);
if (
run.status !== "COMPLETED" ||
run.imported ||
- !run.outputs?.length ||
- importing.current.has(run.runId)
+ importing.current.has(run.runId) ||
+ // Classification settles even with no outputs (nothing to tag); other
+ // policies need an output to import.
+ (!run.outputs?.length && !classification)
) {
continue;
}
importing.current.add(run.runId);
+ // Classification is metadata-only: stamp labels onto the current leaf of
+ // the file it ran on (no version fork). See importClassificationLabels.
+ if (classification) {
+ // Targets are resolved by importClassificationLabels AT WRITE TIME (not
+ // snapshotted here): its download/parse is an async window during which
+ // a manual tool run can consume the input and fork a new leaf, and a
+ // stale snapshot would no-op on the dead id and lose the labels.
+ void importClassificationLabels(
+ run,
+ () =>
+ classificationLabelTargetStubs(run.fileId, fileStubsRef.current),
+ { updateStirlingFileStub, bumpRevision },
+ ).finally(() => importing.current.delete(run.runId));
+ continue;
+ }
// Honour the policy's output mode: a new file, or a new version of the
// input file it ran on (needs that input's stub, still in the workspace).
const outputMode = policies[run.categoryId]?.outputMode ?? "new_version";
@@ -501,6 +536,142 @@ function categoryForPolicy(
)?.[0];
}
+interface ClassificationImportContext {
+ updateStirlingFileStub: (
+ fileId: FileId,
+ updates: Partial,
+ ) => void;
+ bumpRevision: () => void;
+}
+
+/** Workspace stubs to tag with a classification run's labels: the file it ran
+ * on plus any live descendants, so an edit made during the async run (which
+ * forks a new leaf) still shows the tags. Empty once the document has left the
+ * workspace (closed, or a reconciled run with no local input link). */
+export function classificationLabelTargetStubs(
+ runFileId: string,
+ stubs: ReadonlyArray,
+): StirlingFileStub[] {
+ return stubs.filter(
+ (s) =>
+ (s.id as string) === runFileId ||
+ s.parentFileId === runFileId ||
+ s.sourceFileIds?.includes(runFileId as FileId),
+ );
+}
+
+/** Attempts to read a completed run's labels before giving up, and the backoff
+ * between them (delay × attempt). The import effect only re-runs when the run
+ * store changes, so a transient read failure has to be retried HERE: bailing
+ * out would leave the run unsettled and the file's "running" pill spinning
+ * until unrelated policy activity happened to nudge the effect. */
+const LABEL_READ_ATTEMPTS = 3;
+const LABEL_READ_RETRY_MS = 2000;
+
+/**
+ * Read classification labels out of a completed run's output PDF. A 404 means
+ * that output aged out, so it's skipped; any other failure is transient and
+ * retried with backoff. Returns null when there are genuinely no labels to
+ * apply (including a run with no outputs), so the caller can settle the run.
+ */
+async function readRunLabels(run: PolicyRunRecord): Promise {
+ for (let attempt = 0; attempt < LABEL_READ_ATTEMPTS; attempt++) {
+ if (attempt > 0) await delay(LABEL_READ_RETRY_MS * attempt);
+ let transientFailure = false;
+ for (const out of run.outputs) {
+ try {
+ const blob = await downloadPolicyOutput(out.fileId, run.target);
+ const file = new File([blob], out.fileName ?? run.fileName, {
+ type: blob.type || "application/pdf",
+ });
+ const labels = await readClassificationLabelsFromFile(file);
+ if (labels && labels.length > 0) return labels;
+ } catch (err) {
+ if (!isNotFoundError(err)) transientFailure = true;
+ }
+ }
+ // Every output was read (or had aged out): there are no labels to apply.
+ if (!transientFailure) return null;
+ }
+ // Out of attempts. Settle the run unlabelled rather than spin forever; the
+ // file keeps its classification badge, just without tags.
+ return null;
+}
+
+/**
+ * Stamp `labels` onto the run's live descendants in place (workspace + storage)
+ * — no versioned child, no history entry, only tags. Returns the tagged ids.
+ *
+ * Runs twice, because `resolveTargets` reads a rendered snapshot of the
+ * workspace: a CONSUME_FILES that was dispatched but not yet rendered when the
+ * first pass ran leaves its target already gone by the time UPDATE_FILE_RECORD
+ * is processed, so that stamp no-ops and the labels would be silently lost. The
+ * second pass sees the forked leaf and tags it. Each id is stamped at most once
+ * across both passes, so the pass costs nothing when no consume raced.
+ */
+async function stampClassificationLabels(
+ labels: string[],
+ resolveTargets: () => StirlingFileStub[],
+ ctx: ClassificationImportContext,
+): Promise {
+ const updates = { classificationLabels: labels };
+ const tagged = new Set();
+
+ for (let pass = 0; pass < 2; pass++) {
+ // Resolve and stamp the store in one synchronous block — no await between
+ // them, so a target can't be consumed in between. A consume AFTER the stamp
+ // is safe too: the CONSUME_FILES reducer carries classificationLabels onto
+ // the new leaf.
+ const fresh = resolveTargets().filter((s) => !tagged.has(s.id));
+ for (const stub of fresh) {
+ tagged.add(stub.id);
+ ctx.updateStirlingFileStub(stub.id, updates);
+ }
+
+ let mutated = false;
+ for (const stub of fresh) {
+ if (await fileStorage.updateFileMetadata(stub.id, updates))
+ mutated = true;
+ }
+ if (mutated) ctx.bumpRevision();
+
+ // Yield a macrotask so React processes this pass's stamps (and any consume
+ // that raced them) before the next pass re-resolves.
+ if (pass === 0) await new Promise((resolve) => setTimeout(resolve));
+ }
+ return Array.from(tagged);
+}
+
+/**
+ * Deliver a classification run: read its labels and tag the live document with
+ * them. Metadata-only — nothing is versioned.
+ */
+async function importClassificationLabels(
+ run: PolicyRunRecord,
+ resolveTargets: () => StirlingFileStub[],
+ ctx: ClassificationImportContext,
+): Promise {
+ if (resolveTargets().length === 0) {
+ // The document left the workspace (closed, or a server-reconciled run with
+ // no local input link) — nothing to tag.
+ updateRun(run.runId, { imported: true });
+ return;
+ }
+ const labels = await readRunLabels(run);
+ const targetIds =
+ labels && labels.length > 0
+ ? await stampClassificationLabels(labels, resolveTargets, ctx)
+ : [];
+ // Settle either way so it stops re-importing. outputFileIds are the TAGGED
+ // workspace files (no forked version), so their policy badge persists. Safe
+ // to chain-key on: classification is always last, so nothing chains off it.
+ updateRun(run.runId, {
+ imported: true,
+ importedFileIds: run.outputs.map((o) => o.fileId),
+ outputFileIds: targetIds,
+ });
+}
+
/**
* Fetch a completed run's not-yet-imported output files and deliver them to the
* workspace. Per-output, via allSettled: each output is tracked once delivered,
@@ -737,6 +908,9 @@ async function runPolicyOnFile(
backendId: string,
fileId: FileId,
fileName: string,
+ // Chained (downstream) dispatch — jumps the dispatch queue so a file mid-chain
+ // finishes its flow before new files start (see acquireDispatchSlot).
+ priority = false,
): Promise {
// A freshly-uploaded file's bytes are written to IndexedDB asynchronously, so
// its stub can appear in the file list a beat before getStirlingFile resolves
@@ -762,6 +936,9 @@ async function runPolicyOnFile(
markDispatched(categoryId, fileId);
return;
}
+ // Bounded upload window — see MAX_CONCURRENT_DISPATCHES. Only the POST is
+ // gated; the IDB wait above never holds a slot.
+ await acquireDispatchSlot(priority);
try {
const target = resolvePolicyRunTarget();
const runId = await runStoredPolicy(backendId, [file]);
@@ -783,6 +960,8 @@ async function runPolicyOnFile(
// the absent run simply won't appear in the activity feed. If the backend did
// start a run we never recorded, reconcileServerRuns rediscovers it.
markDispatched(categoryId, fileId);
+ } finally {
+ releaseDispatchSlot();
}
}
@@ -803,8 +982,10 @@ export async function poll(
// would quit while a long step is still legitimately running.
let budgetMs = DEFAULT_STEP_COUNT * STEP_TIMEOUT_MS + POLL_GRACE_MS;
const startedAt = Date.now();
+ let nextDelayMs = FIRST_POLL_MS;
while (Date.now() - startedAt < budgetMs) {
- await delay(POLL_MS);
+ await delay(nextDelayMs);
+ nextDelayMs = POLL_MS;
let view;
try {
view = await getPolicyRun(runId);
diff --git a/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsx b/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsx
index 45dea92070..048bca15ac 100644
--- a/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsx
+++ b/frontend/editor/src/proprietary/components/shared/PolicyEnforcingOverlay.tsx
@@ -11,6 +11,7 @@ import {
import { ActionIcon } from "@app/ui/ActionIcon";
import ShieldOutlinedIcon from "@mui/icons-material/ShieldOutlined";
import CloseIcon from "@mui/icons-material/Close";
+import { policyCategoryIcon } from "@app/components/policies/policyCategoryIcon";
import { useTranslation } from "react-i18next";
interface PolicyEnforcingOverlayProps {
@@ -23,6 +24,9 @@ interface PolicyEnforcingOverlayProps {
/** CSS colour var of the enforcing policy's accent (e.g. `var(--color-orange)`),
* so the icon/spinner match that policy's badge instead of a fixed blue. */
accentVar?: string;
+ /** Category of the enforcing policy — picks its shared icon (shield for
+ * security, label for classification, …); generic shield when unknown. */
+ categoryId?: string;
}
/**
@@ -35,6 +39,7 @@ export function PolicyEnforcingOverlay({
zIndex = 200,
onDismiss,
accentVar,
+ categoryId,
}: PolicyEnforcingOverlayProps) {
const { t } = useTranslation();
if (!enforcing) return null;
@@ -87,7 +92,11 @@ export function PolicyEnforcingOverlay({
: undefined
}
>
-
+ {categoryId ? (
+ policyCategoryIcon(categoryId, { fontSize: 26 })
+ ) : (
+
+ )}
{t("policy.enforcingTitle", "Enforcing policy…")}
diff --git a/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsx b/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsx
index 75fa9cb952..71d5294f2d 100644
--- a/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsx
+++ b/frontend/editor/src/proprietary/components/viewer/PolicyEnforcementOverlay.tsx
@@ -71,6 +71,7 @@ export function PolicyEnforcementOverlay({ runs }: Props) {
progress={progress}
onDismiss={() => setDismissed(true)}
accentVar={policyAccentVar(inFlight.categoryId)}
+ categoryId={inFlight.categoryId}
/>
);
}
diff --git a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx b/frontend/editor/src/proprietary/components/viewer/Viewer.tsx
index e1d0cd96ab..1f04ea22ca 100644
--- a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx
+++ b/frontend/editor/src/proprietary/components/viewer/Viewer.tsx
@@ -8,6 +8,7 @@ import {
usePolicyRuns,
type PolicyRunRecord,
} from "@app/components/policies/policyRunStore";
+import { isClassificationCategory } from "@app/data/policyCategories";
import { PolicyEnforcementOverlay } from "@app/components/viewer/PolicyEnforcementOverlay";
type SignatureOverlayPassThrough = Pick<
@@ -29,6 +30,8 @@ const Viewer = (props: ViewerProps & SignatureOverlayPassThrough) => {
? allRuns.filter(
(r: PolicyRunRecord) =>
r.fileId === activeFileId &&
+ // Classification runs async and must never block the viewer.
+ !isClassificationCategory(r.categoryId) &&
(POLICY_IN_FLIGHT_STATUSES.includes(r.status) || r.retrying === true),
)
: [];
diff --git a/frontend/editor/src/proprietary/data/policyCategories.test.ts b/frontend/editor/src/proprietary/data/policyCategories.test.ts
new file mode 100644
index 0000000000..4b4fca2b7e
--- /dev/null
+++ b/frontend/editor/src/proprietary/data/policyCategories.test.ts
@@ -0,0 +1,41 @@
+import { describe, it, expect } from "vitest";
+import {
+ isClassificationCategory,
+ pinClassificationLast,
+} from "@app/data/policyCategories";
+
+describe("isClassificationCategory", () => {
+ it("recognises the classification category and nothing else", () => {
+ expect(isClassificationCategory("classification")).toBe(true);
+ expect(isClassificationCategory("security")).toBe(false);
+ expect(isClassificationCategory("")).toBe(false);
+ });
+});
+
+describe("pinClassificationLast", () => {
+ it("moves classification to the end, preserving other order", () => {
+ expect(
+ pinClassificationLast(["classification", "security", "compliance"]),
+ ).toEqual(["security", "compliance", "classification"]);
+ });
+
+ it("leaves an order without classification untouched", () => {
+ expect(pinClassificationLast(["security", "compliance"])).toEqual([
+ "security",
+ "compliance",
+ ]);
+ });
+
+ it("is a no-op when classification is already last", () => {
+ expect(pinClassificationLast(["security", "classification"])).toEqual([
+ "security",
+ "classification",
+ ]);
+ });
+
+ it("handles classification as the only policy", () => {
+ expect(pinClassificationLast(["classification"])).toEqual([
+ "classification",
+ ]);
+ });
+});
diff --git a/frontend/editor/src/proprietary/data/policyCategories.ts b/frontend/editor/src/proprietary/data/policyCategories.ts
new file mode 100644
index 0000000000..820a93366b
--- /dev/null
+++ b/frontend/editor/src/proprietary/data/policyCategories.ts
@@ -0,0 +1,21 @@
+/** The classification policy's catalog category id. */
+export const CLASSIFICATION_CATEGORY_ID = "classification";
+
+/**
+ * Classification is metadata-only: it runs async (never blocks), never forks a
+ * version, and always runs last. This predicate gates that special handling.
+ */
+export function isClassificationCategory(categoryId: string): boolean {
+ return categoryId === CLASSIFICATION_CATEGORY_ID;
+}
+
+/**
+ * Move classification to the end of an execution order (others keep their order),
+ * so a persisted/displayed order can't place it anywhere but last.
+ */
+export function pinClassificationLast(orderedCategoryIds: string[]): string[] {
+ return [
+ ...orderedCategoryIds.filter((id) => !isClassificationCategory(id)),
+ ...orderedCategoryIds.filter((id) => isClassificationCategory(id)),
+ ];
+}
diff --git a/frontend/editor/src/proprietary/hooks/usePolicies.ts b/frontend/editor/src/proprietary/hooks/usePolicies.ts
index 8043e6b66a..389f98cd65 100644
--- a/frontend/editor/src/proprietary/hooks/usePolicies.ts
+++ b/frontend/editor/src/proprietary/hooks/usePolicies.ts
@@ -35,6 +35,7 @@ import {
removePolicy,
} from "@app/services/policyBackend";
import { reorderPolicies as reorderBackendPolicies } from "@app/services/policyApi";
+import { pinClassificationLast } from "@app/data/policyCategories";
import type { PolicyToStore } from "@app/services/policyPipeline";
import type {
PoliciesByCategory,
@@ -326,9 +327,12 @@ export function usePolicies() {
* first for an instant re-render; the next reconcile re-reads the server order.
*/
const reorderPolicies = useCallback((orderedCategoryIds: string[]) => {
- persistPolicyOrder(orderedCategoryIds);
+ // Pin classification last so the persisted/server order matches execution
+ // (it always runs last — see usePolicyAutoRun).
+ const ordered = pinClassificationLast(orderedCategoryIds);
+ persistPolicyOrder(ordered);
const current = loadPolicies();
- const backendIds = orderedCategoryIds
+ const backendIds = ordered
.map((categoryId) => current[categoryId]?.backendId)
.filter((id): id is string => !!id);
if (backendIds.length > 0) {
diff --git a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts
index c5d8b9952b..2364321213 100644
--- a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts
+++ b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.test.ts
@@ -1,11 +1,14 @@
import { describe, it, expect } from "vitest";
-import { buildPolicyBadgeMap } from "@app/hooks/usePolicyFileBadges";
+import {
+ buildPolicyBadgeMap,
+ reusePolicyBadgeArrays,
+} from "@app/hooks/usePolicyFileBadges";
import type { PolicyRunRecord } from "@app/components/policies/policyRunStore";
-const NOW = 1_000_000;
const labels = new Map([
["security", "Security"],
["watermark", "Watermark"],
+ ["classification", "Classification"],
]);
function run(overrides: Partial): PolicyRunRecord {
@@ -20,29 +23,24 @@ function run(overrides: Partial): PolicyRunRecord {
outputs: [],
outputFileIds: ["out"],
error: null,
- startedAt: NOW - 1_000, // recent by default
+ startedAt: 0,
...overrides,
};
}
describe("buildPolicyBadgeMap — badge follows the document onto derived files", () => {
- it("badges a policy's direct output, and marks it recent within the window", () => {
- const map = buildPolicyBadgeMap([run({})], [{ id: "out" }], labels, NOW);
- const badges = map.get("out") ?? [];
- expect(badges.map((b) => b.id)).toEqual(["security"]);
- expect(badges[0].recent).toBe(true);
+ it("badges a policy's direct output", () => {
+ const map = buildPolicyBadgeMap([run({})], [{ id: "out" }], labels);
+ expect((map.get("out") ?? []).map((b) => b.id)).toEqual(["security"]);
});
- it("a versioned edit inherits the badge via parentFileId (never glows)", () => {
+ it("a versioned edit inherits the badge via parentFileId", () => {
const map = buildPolicyBadgeMap(
[run({})],
[{ id: "out" }, { id: "edit", parentFileId: "out" }],
labels,
- NOW,
);
- const edit = map.get("edit") ?? [];
- expect(edit.map((b) => b.id)).toEqual(["security"]);
- expect(edit[0].recent).toBe(false);
+ expect((map.get("edit") ?? []).map((b) => b.id)).toEqual(["security"]);
});
it("SPLIT parts inherit the badge via sourceFileIds, though they have no parent", () => {
@@ -56,11 +54,9 @@ describe("buildPolicyBadgeMap — badge follows the document onto derived files"
{ id: "part2", sourceFileIds: ["out"] },
],
labels,
- NOW,
);
expect((map.get("part1") ?? []).map((b) => b.id)).toEqual(["security"]);
expect((map.get("part2") ?? []).map((b) => b.id)).toEqual(["security"]);
- expect((map.get("part1") ?? [])[0].recent).toBe(false);
});
it("resolves transitively when an intermediate edit was consumed/removed", () => {
@@ -70,7 +66,6 @@ describe("buildPolicyBadgeMap — badge follows the document onto derived files"
[run({})],
[{ id: "part", sourceFileIds: ["editGone", "out"] }],
labels,
- NOW,
);
expect((map.get("part") ?? []).map((b) => b.id)).toEqual(["security"]);
});
@@ -83,7 +78,6 @@ describe("buildPolicyBadgeMap — badge follows the document onto derived files"
],
[{ id: "merged", sourceFileIds: ["a", "b"] }],
labels,
- NOW,
);
expect((map.get("merged") ?? []).map((b) => b.id).sort()).toEqual([
"security",
@@ -96,24 +90,33 @@ describe("buildPolicyBadgeMap — badge follows the document onto derived files"
[run({})],
[{ id: "out" }, { id: "unrelated", sourceFileIds: ["someUpload"] }],
labels,
- NOW,
);
expect(map.has("unrelated")).toBe(false);
});
- it("inherited badges never glow even when the source run is recent", () => {
+ it("a completed classification run badges the files it tagged", () => {
+ // Classification is metadata-only: its outputFileIds are the tagged
+ // workspace files (no forked version), so the label badge persists there.
const map = buildPolicyBadgeMap(
- [run({ startedAt: NOW })], // maximally recent
- [{ id: "out" }, { id: "part", sourceFileIds: ["out"] }],
+ [
+ run({
+ categoryId: "classification",
+ fileId: "in",
+ outputFileIds: ["in"],
+ imported: true,
+ }),
+ ],
+ [{ id: "in" }],
labels,
- NOW,
);
- expect((map.get("out") ?? [])[0].recent).toBe(true);
- expect((map.get("part") ?? [])[0].recent).toBe(false);
+ const badges = map.get("in") ?? [];
+ expect(badges.map((b) => b.id)).toEqual(["classification"]);
+ expect(badges[0].enforcing).toBeUndefined();
+ expect(badges[0].background).toBeUndefined();
});
});
-describe("buildPolicyBadgeMap — enforcing spinner while a run is in flight", () => {
+describe("buildPolicyBadgeMap — in-flight indicators", () => {
const enforcingOn = (
map: Map,
id: string,
@@ -124,7 +127,6 @@ describe("buildPolicyBadgeMap — enforcing spinner while a run is in flight", (
[run({ status: "RUNNING", outputFileIds: [] })],
[{ id: "in" }],
labels,
- NOW,
);
expect(enforcingOn(map, "in")).toBe(true);
});
@@ -136,7 +138,6 @@ describe("buildPolicyBadgeMap — enforcing spinner while a run is in flight", (
[run({ status: "COMPLETED" })],
[{ id: "in" }],
labels,
- NOW,
);
expect(enforcingOn(before, "in")).toBe(true);
@@ -144,7 +145,6 @@ describe("buildPolicyBadgeMap — enforcing spinner while a run is in flight", (
[run({ status: "COMPLETED", imported: true })],
[{ id: "in" }],
labels,
- NOW,
);
expect(enforcingOn(after, "in")).toBe(false);
});
@@ -155,7 +155,6 @@ describe("buildPolicyBadgeMap — enforcing spinner while a run is in flight", (
[run({ status, outputFileIds: [] })],
[{ id: "in" }],
labels,
- NOW,
);
expect(enforcingOn(map, "in")).toBe(false);
}
@@ -166,7 +165,6 @@ describe("buildPolicyBadgeMap — enforcing spinner while a run is in flight", (
[run({ status: "FAILED", retrying: true, outputFileIds: [] })],
[{ id: "in" }],
labels,
- NOW,
);
expect(enforcingOn(map, "in")).toBe(true);
});
@@ -176,8 +174,97 @@ describe("buildPolicyBadgeMap — enforcing spinner while a run is in flight", (
[run({ status: "RUNNING", fileId: "", outputFileIds: [] })],
[{ id: "in" }],
labels,
- NOW,
);
expect(enforcingOn(map, "in")).toBe(false);
});
+
+ it("an in-flight classification run is background, never enforcing", () => {
+ // Non-blocking: shows a spinner but must never trip the enforcing flag
+ // that gates actions and overlays.
+ const map = buildPolicyBadgeMap(
+ [
+ run({
+ categoryId: "classification",
+ status: "RUNNING",
+ outputFileIds: [],
+ }),
+ ],
+ [{ id: "in" }],
+ labels,
+ );
+ const badges = map.get("in") ?? [];
+ expect(badges.map((b) => b.id)).toEqual(["classification"]);
+ expect(badges[0].background).toBe(true);
+ expect(enforcingOn(map, "in")).toBe(false);
+ });
+});
+
+describe("reusePolicyBadgeArrays — per-file identity across rebuilds", () => {
+ // buildPolicyBadgeMap allocates fresh arrays every call and the run store hands
+ // back a new `runs` array on every status poll, so without this the memoized
+ // sidebar rows get a new `policies` prop for EVERY badged file on each tick.
+ const build = (runs: PolicyRunRecord[], stubs: { id: string }[]) =>
+ buildPolicyBadgeMap(runs, stubs, labels);
+
+ const twoFiles = [{ id: "a" }, { id: "b" }];
+ // Settled + imported, so the badge is a plain one (a COMPLETED run keeps
+ // `enforcing` until its outputs land — see the in-flight tests above).
+ const settled = (id: string) =>
+ run({
+ runId: `r${id}`,
+ fileId: id,
+ outputFileIds: [id],
+ status: "COMPLETED",
+ imported: true,
+ });
+ const bothSettled = () => [settled("a"), settled("b")];
+
+ it("returns the same map when nothing changed", () => {
+ const first = build(bothSettled(), twoFiles);
+ const second = reusePolicyBadgeArrays(
+ first,
+ build(bothSettled(), twoFiles),
+ );
+ expect(second).toBe(first);
+ });
+
+ it("keeps the untouched file's array identity when another file changes", () => {
+ const first = build(bothSettled(), twoFiles);
+ // "a" goes in-flight; "b" is unaffected and must keep its exact array.
+ const next = build(
+ [
+ run({
+ runId: "ra",
+ fileId: "a",
+ outputFileIds: ["a"],
+ status: "RUNNING",
+ }),
+ settled("b"),
+ ],
+ twoFiles,
+ );
+ const second = reusePolicyBadgeArrays(first, next);
+ expect(second).not.toBe(first);
+ expect(second.get("b")).toBe(first.get("b"));
+ expect(second.get("a")).not.toBe(first.get("a"));
+ expect((second.get("a") ?? [])[0].enforcing).toBe(true);
+ expect((first.get("a") ?? [])[0].enforcing).toBeUndefined();
+ });
+
+ it("a new badged file doesn't disturb the existing files' arrays", () => {
+ const first = build(bothSettled(), twoFiles);
+ const next = build(
+ [...bothSettled(), settled("c")],
+ [...twoFiles, { id: "c" }],
+ );
+ const second = reusePolicyBadgeArrays(first, next);
+ expect(second.get("a")).toBe(first.get("a"));
+ expect(second.get("b")).toBe(first.get("b"));
+ expect((second.get("c") ?? []).map((b) => b.id)).toEqual(["security"]);
+ });
+
+ it("passes the fresh map straight through on the first build", () => {
+ const map = build(bothSettled(), twoFiles);
+ expect(reusePolicyBadgeArrays(null, map)).toBe(map);
+ });
});
diff --git a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts
index 40fcd0399e..52779b9cf8 100644
--- a/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts
+++ b/frontend/editor/src/proprietary/hooks/usePolicyFileBadges.ts
@@ -1,17 +1,12 @@
-import { useMemo } from "react";
+import { useMemo, useRef } from "react";
import { usePolicyRuns } from "@app/components/policies/policyRunStore";
import type { PolicyRunRecord } from "@app/components/policies/policyRunStore";
import { useAllFiles } from "@app/contexts/FileContext";
import { loadPolicyCatalog } from "@app/services/policyCatalog";
import { policyAccentVar } from "@app/components/policies/policyStatus";
+import { isClassificationCategory } from "@app/data/policyCategories";
import type { FileItemPolicyRef } from "@app/components/shared/PolicyBadges";
-/** How long after a run a badge counts as "recent" (drives the one-off glow).
- * Measured from run start — must exceed the longest realistic policy wall-clock
- * time so the glow still fires after a slow run completes and imports. Old or
- * reloaded runs fall outside this window, suppressing the glow on page reload. */
-const RECENT_MS = 5 * 60 * 1000;
-
/** Minimal provenance shape needed to resolve a file's inherited badges. */
type LineageStub = {
id: string;
@@ -19,14 +14,10 @@ type LineageStub = {
sourceFileIds?: string[];
};
-/** Merge a ref into a list, deduping by policy id. A direct (recent) hit wins
- * the glow over an inherited one for the same policy. */
+/** Merge a ref into a list, deduping by policy id. */
function mergeRef(list: FileItemPolicyRef[], ref: FileItemPolicyRef): void {
- const existing = list.find((p) => p.id === ref.id);
- if (!existing) {
+ if (!list.some((p) => p.id === ref.id)) {
list.push(ref);
- } else if (ref.recent) {
- existing.recent = true;
}
}
@@ -42,21 +33,18 @@ function mergeRef(list: FileItemPolicyRef[], ref: FileItemPolicyRef): void {
* from: its transitive `sourceFileIds` (recorded at the consume boundary, so it
* covers split/merge/convert too) plus, defensively, its `parentFileId`.
* Because `sourceFileIds` is transitive, a flat lookup suffices — no chain walk,
- * and it survives a consumed intermediate. Inherited badges never glow
- * (recent=false): only the original application does.
+ * and it survives a consumed intermediate.
*/
export function buildPolicyBadgeMap(
runs: ReadonlyArray,
stubs: ReadonlyArray,
labelById: ReadonlyMap,
- now: number,
): Map {
// Direct badges: a file that IS a policy run's output.
const directByFile = new Map();
for (const run of runs) {
const name = labelById.get(run.categoryId);
if (!name) continue;
- const recent = now - run.startedAt < RECENT_MS;
for (const fileId of run.outputFileIds ?? []) {
const list = directByFile.get(fileId) ?? [];
if (!list.some((p) => p.id === run.categoryId)) {
@@ -64,7 +52,6 @@ export function buildPolicyBadgeMap(
id: run.categoryId,
name,
accentColor: policyAccentVar(run.categoryId),
- recent,
});
directByFile.set(fileId, list);
}
@@ -86,7 +73,7 @@ export function buildPolicyBadgeMap(
// from. `sourceFileIds` is the transitive provenance set (so a flat lookup
// catches even ancestors whose intermediate edits were consumed), and
// `parentFileId` is included defensively for any child not created via a
- // consume. Inherited badges are marked recent=false (carried, not applied).
+ // consume.
for (const stub of stubs) {
const sources = new Set(stub.sourceFileIds ?? []);
if (stub.parentFileId) sources.add(stub.parentFileId);
@@ -94,14 +81,17 @@ export function buildPolicyBadgeMap(
const srcBadges = directByFile.get(src);
if (!srcBadges?.length) continue;
const list = result.get(stub.id) ?? [];
- for (const ref of srcBadges) mergeRef(list, { ...ref, recent: false });
+ for (const ref of srcBadges) mergeRef(list, { ...ref });
result.set(stub.id, list);
}
}
// In-flight pass: add (or upgrade) a badge on the input file for any run that
// is currently being processed, so the sidebar shows a spinning indicator
- // while the policy is actively enforcing — not just after it completes.
+ // while the policy is actively running — not just after it completes.
+ // Blocking policies set `enforcing` (which gates actions/overlays);
+ // classification is non-blocking, so it sets `background` instead — same
+ // spinner, but nothing is ever gated on it.
// Keep the spinner until `imported` is true: the status reaches COMPLETED
// before the output files are imported into the workspace, so gating on
// status alone would drop the badge during that async gap.
@@ -112,17 +102,19 @@ export function buildPolicyBadgeMap(
if (settled && !run.retrying) continue;
const name = labelById.get(run.categoryId);
if (!name) continue;
+ const inFlightFlag = isClassificationCategory(run.categoryId)
+ ? ("background" as const)
+ : ("enforcing" as const);
const list = result.get(run.fileId) ?? [];
const existing = list.find((p) => p.id === run.categoryId);
if (existing) {
- existing.enforcing = true;
+ existing[inFlightFlag] = true;
} else {
list.push({
id: run.categoryId,
name,
accentColor: policyAccentVar(run.categoryId),
- recent: false,
- enforcing: true,
+ [inFlightFlag]: true,
});
result.set(run.fileId, list);
}
@@ -131,20 +123,70 @@ export function buildPolicyBadgeMap(
return result;
}
+/** Field-wise equality for a badge ref — the whole shape `PolicyBadges` renders. */
+function sameRef(a: FileItemPolicyRef, b: FileItemPolicyRef): boolean {
+ return (
+ a.id === b.id &&
+ a.name === b.name &&
+ a.accentColor === b.accentColor &&
+ !!a.enforcing === !!b.enforcing &&
+ !!a.background === !!b.background
+ );
+}
+
+function sameRefs(a: FileItemPolicyRef[], b: FileItemPolicyRef[]): boolean {
+ return a.length === b.length && a.every((ref, i) => sameRef(ref, b[i]));
+}
+
+/**
+ * Carry the previous map's array references over to files whose badges didn't
+ * change, and return the previous MAP itself when none did.
+ *
+ * {@link buildPolicyBadgeMap} allocates a fresh array per badged file on every
+ * call, and the run store hands back a new `runs` array on every status poll —
+ * so without this, one file's poll tick gives EVERY badged file a new `policies`
+ * identity, and the memoized sidebar rows can never bail out (the case the
+ * memoization exists for). `NO_POLICIES` in FileSidebar only covers the rows
+ * with no badges at all.
+ */
+export function reusePolicyBadgeArrays(
+ previous: Map | null,
+ next: Map,
+): Map {
+ if (!previous) return next;
+ let changed = previous.size !== next.size;
+ for (const [fileId, refs] of next) {
+ const before = previous.get(fileId);
+ if (before && sameRefs(before, refs)) next.set(fileId, before);
+ else changed = true;
+ }
+ return changed ? next : previous;
+}
+
/**
* Distinct policies that have produced each file, keyed by fileId, derived from
* the reactive policy run store. Drives the file sidebar's shield badges. The
* badge follows a document down its tool-edit chain — see
* {@link buildPolicyBadgeMap}. Shadows the core stub via the {@code @app/*}
* alias cascade.
+ *
+ * Per-file array identity is preserved across rebuilds so memoized consumers
+ * (the sidebar rows) only re-render for the file that actually changed — see
+ * {@link reusePolicyBadgeArrays}.
*/
export function usePolicyFileBadges(): Map {
const runs = usePolicyRuns();
const { fileStubs } = useAllFiles();
+ const previous = useRef