#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Stirling Sign V1 (#8189)
ConnorYoh7b6fbfb58169
diff --git a/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java b/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.javaindex 642932edb3..837d6e7714 100644--- a/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java+++ b/app/common/src/main/java/stirling/software/common/configuration/ConfigInitializer.java@@ -82,10 +82,13 @@ public class ConfigInitializer {migrateProFeaturesKeyCasing(settingsFile, settingsTemplateFile);boolean ssoAutoLoginMigrated =migrateSsoAutoLoginToSecurity(settingsFile, settingsTemplateFile);+ boolean signingScopeMigrated =+ migrateSigningUserListScope(settingsFile, settingsTemplateFile);boolean changesMade =settingsTemplateFile.updateValuesFromYaml(settingsFile, settingsTemplateFile)- || ssoAutoLoginMigrated;+ || ssoAutoLoginMigrated+ || signingScopeMigrated;if (changesMade) {settingsTemplateFile.save(destPath);log.info("Settings file updated based on template changes.");@@ -154,6 +157,16 @@ public class ConfigInitializer {}}+ private boolean migrateSigningUserListScope(YamlHelper yaml, YamlHelper template) {+ if (yaml.getValueByExactKeyPath("storage", "signing", "userListScope") != null) {+ return false;+ }+ Object legacyScope = yaml.getValueByExactKeyPath("storage", "encryption", "userListScope");+ return legacyScope != null+ && template.updateValue(+ List.of("storage", "signing", "userListScope"), legacyScope);+ }+boolean migrateSsoAutoLoginToSecurity(YamlHelper yaml, YamlHelper template) {if (yaml.getValueByExactKeyPath("security", "ssoAutoLogin") != null) {return false;diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex 6d28fa1784..67eb901e45 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -1394,7 +1394,7 @@ public class ApplicationProperties {@Datapublic static class Storage {- private boolean enabled = false;+ private boolean enabled = true;private String provider = "local";private Local local = new Local();private S3 s3 = new S3();@@ -1496,7 +1496,7 @@ public class ApplicationProperties {@Datapublic static class Signing {- private boolean enabled = false;+ private boolean enabled = true;// Signing user-picker scope: 'org' (default) = whole instance, anything else =// caller's team only (fail-closed). The saas profile pins 'team'.diff --git a/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java b/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.javaindex 98e0e8ca21..d596c1b334 100644--- a/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java+++ b/app/common/src/test/java/stirling/software/common/model/ApplicationPropertiesLogicTest.java@@ -36,7 +36,7 @@ class ApplicationPropertiesLogicTest {// Self-host backward-compat: scope must default to "org" (saas profile pins "team").ApplicationProperties.Storage.Signing signing = new ApplicationProperties.Storage.Signing();- assertFalse(signing.isEnabled());+ assertTrue(signing.isEnabled());assertEquals("org", signing.getUserListScope());signing.setUserListScope("team");@@ -47,6 +47,17 @@ class ApplicationPropertiesLogicTest {"org", new ApplicationProperties().getStorage().getSigning().getUserListScope());}+ @Test+ void storageDefaultsEnableLocalStorageAndSigningWithoutSharingOrEncryption() {+ ApplicationProperties.Storage storage = new ApplicationProperties().getStorage();++ assertTrue(storage.isEnabled());+ assertTrue(storage.getSigning().isEnabled());+ assertEquals("local", storage.getProvider());+ assertFalse(storage.getSharing().isEnabled());+ assertFalse(storage.getEncryption().isEnabled());+ }+@Testvoid tempFileManagement_defaults_and_overrides() {Function<String, String> normalize = s -> Path.of(s).normalize().toString();diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 64f2176401..012822aee0 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -246,7 +246,7 @@ system:cron: "0 0 0 * * ?" # Cron expression for automatic database backups "0 0 0 * * ?" daily at midnightstorage:- enabled: false # set to 'true' to allow users to store files on the server (requires security.enableLogin) [ALPHA]+ enabled: true # set to 'false' to disable server-side file storage (requires security.enableLogin) [ALPHA]provider: local # storage provider: 'local' for filesystem storage, 'database' for DB-backed storagelocal:basePath: './storage' # base directory for stored files@@ -293,7 +293,8 @@ storage:emailEnabled: false # set to 'true' to allow sharing by email (requires mail.enabled)linkExpirationDays: 3 # Number of days before share links expiresigning:- enabled: false # set to 'true' to enable group signing workflow (requires storage.enabled) [ALPHA]+ enabled: true # set to 'false' to disable shared signing (requires storage.enabled and security.enableLogin) [ALPHA]+ userListScope: org # 'org' lists the whole instance; any other value limits the picker to the caller's team.# Encryption at rest for stored files (AES-256, per-team keys). Requires a Pro or# Enterprise licence. Key setup, cluster requirements, the encrypt-existing migration,# the revocation kill switch and master-key rotation are documented in@@ -303,7 +304,6 @@ storage:encryption:enabled: false # set to 'true' to encrypt stored files at restauditReads: true # audit every decrypt of an encrypted file (denied decrypts and key lifecycle events are always audited). NOTE: audit events require an Enterprise licence; encryption itself works on Pro.- userListScope: org # Signing user-picker scope: 'org' (default) = whole instance, else caller's team only.autoPipeline:outputFolder: "" # Output folder for processed pipeline files (leave empty for default)fileReadiness:diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.javaindex a37f1c3f97..25c36d3692 100644--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/ConfigControllerMoreTest.java@@ -12,6 +12,8 @@ import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.mockito.junit.jupiter.MockitoSettings;@@ -86,6 +88,31 @@ class ConfigControllerMoreTest {@DisplayName("getAppConfig")class GetAppConfig {+ @ParameterizedTest+ @CsvSource({+ "false,true,true,false,false",+ "true,true,true,true,true",+ "true,false,true,false,false",+ "true,true,false,true,false"+ })+ void storageAndSigningRespectLoginAndOptOuts(+ boolean login,+ boolean storage,+ boolean signing,+ boolean expectedStorage,+ boolean expectedSigning) {+ applicationProperties.getSecurity().setEnableLogin(login);+ if (!storage) applicationProperties.getStorage().setEnabled(false);+ if (!signing) applicationProperties.getStorage().getSigning().setEnabled(false);++ Map<String, Object> body =+ bodyOf(newController().getAppConfig(mock(HttpServletRequest.class)));++ assertThat(body).containsEntry("storageEnabled", expectedStorage);+ assertThat(body).containsEntry("storageGroupSigningEnabled", expectedSigning);+ assertThat(body).containsEntry("storageSharingEnabled", false);+ }+@Test@DisplayName("returns wired config values with all services present")void returnsConfigWithServices() {@@ -126,6 +153,8 @@ class ConfigControllerMoreTest {Map<String, Object> body = bodyOf(resp);assertThat(body).containsEntry("enableLogin", false);+ assertThat(body).containsEntry("storageEnabled", false);+ assertThat(body).containsEntry("storageGroupSigningEnabled", false);assertThat(body).containsEntry("isAdmin", false);assertThat(body).containsEntry("isNewUser", false);assertThat(body).containsEntry("serverCertificateEnabled", false);diff --git a/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.java b/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.javaindex e827d5824b..9093dbaa90 100644--- a/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.java+++ b/app/core/src/test/java/stirling/software/common/configuration/ConfigInitializerRestartTest.java@@ -11,6 +11,7 @@ import java.util.Map;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.junit.jupiter.params.provider.ValueSource;import org.mockito.MockedStatic;@@ -30,6 +31,59 @@ class ConfigInitializerRestartTest {return String.valueOf(new YamlHelper(settings).getValueByExactKeyPath(keyPath));}+ @Test+ void storageAndSigningDefaultOnAtFirstBoot(@TempDir Path tmp) throws Exception {+ Path settings = tmp.resolve("settings.yml");+ try (MockedStatic<InstallationPathConfig> paths =+ mockStatic(InstallationPathConfig.class)) {+ paths.when(InstallationPathConfig::getSettingsPath).thenReturn(settings.toString());+ paths.when(InstallationPathConfig::getCustomSettingsPath)+ .thenReturn(tmp.resolve("custom_settings.yml").toString());++ new ConfigInitializer().ensureConfigExists();++ assertEquals("true", read(settings, "storage", "enabled"));+ assertEquals("true", read(settings, "storage", "signing", "enabled"));+ assertEquals("local", read(settings, "storage", "provider"));+ assertEquals("false", read(settings, "storage", "sharing", "enabled"));+ }+ }++ @ParameterizedTest+ @CsvSource(+ value = {"-,-", "false,-", "-,false", "false,false", "true,false", "false,true"},+ nullValues = "-")+ void storageOptOutsSurviveUpgradeAndRestart(+ String storageEnabled, String signingEnabled, @TempDir Path tmp) throws Exception {+ Path settings = tmp.resolve("settings.yml");+ // Startup replaces files shorter than 31 lines instead of merging their settings.+ Files.writeString(+ settings,+ "# Existing installation\n".repeat(32)+ + "storage:\n provider: local\n"+ + (storageEnabled == null ? "" : " enabled: " + storageEnabled + "\n")+ + (signingEnabled == null+ ? ""+ : " signing:\n enabled: " + signingEnabled + "\n"));+ try (MockedStatic<InstallationPathConfig> paths =+ mockStatic(InstallationPathConfig.class)) {+ paths.when(InstallationPathConfig::getSettingsPath).thenReturn(settings.toString());+ paths.when(InstallationPathConfig::getCustomSettingsPath)+ .thenReturn(tmp.resolve("custom_settings.yml").toString());+ ConfigInitializer initializer = new ConfigInitializer();++ for (int restart = 0; restart < 2; restart++) {+ initializer.ensureConfigExists();+ assertEquals(+ storageEnabled == null ? "true" : storageEnabled,+ read(settings, "storage", "enabled"));+ assertEquals(+ signingEnabled == null ? "true" : signingEnabled,+ read(settings, "storage", "signing", "enabled"));+ }+ }+ }+@Testvoid ssoAutoLoginAndCustomMetadata_persistAcrossRestart(@TempDir Path tmp) throws Exception {Path settings = tmp.resolve("settings.yml");diff --git a/app/core/src/test/java/stirling/software/common/configuration/SigningScopeMigrationTest.java b/app/core/src/test/java/stirling/software/common/configuration/SigningScopeMigrationTest.javanew file mode 100644index 0000000000..d30eed0b37--- /dev/null+++ b/app/core/src/test/java/stirling/software/common/configuration/SigningScopeMigrationTest.java@@ -0,0 +1,68 @@+package stirling.software.common.configuration;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.mockito.Mockito.mockStatic;++import java.nio.file.Files;+import java.nio.file.Path;++import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.mockito.MockedStatic;++import stirling.software.common.util.YamlHelper;++class SigningScopeMigrationTest {+ @ParameterizedTest+ @CsvSource(+ value = {+ "team,-,team",+ "org,-,org",+ "team,org,org",+ "org,team,team",+ "-,team,team",+ "-,-,org"+ },+ nullValues = "-")+ void preservesScopeAndExplicitOverridesAcrossRestarts(+ String legacyScope, String signingScope, String expectedScope, @TempDir Path tmp)+ throws Exception {+ Path settings = tmp.resolve("settings.yml");+ Path custom = tmp.resolve("custom_settings.yml");+ String legacy =+ legacyScope == null+ ? ""+ : " encryption:\n userListScope: " + legacyScope + "\n";+ String current =+ signingScope == null ? "" : " signing:\n userListScope: " + signingScope + "\n";+ // Startup replaces files shorter than 31 lines instead of merging their settings.+ Files.writeString(+ settings,+ "# Existing installation\n".repeat(32)+ + "storage:\n enabled: true\n"+ + legacy+ + current);++ try (MockedStatic<InstallationPathConfig> paths =+ mockStatic(InstallationPathConfig.class)) {+ paths.when(InstallationPathConfig::getSettingsPath).thenReturn(settings.toString());+ paths.when(InstallationPathConfig::getCustomSettingsPath).thenReturn(custom.toString());+ ConfigInitializer initializer = new ConfigInitializer();+ initializer.ensureConfigExists();+ YamlHelper migrated = new YamlHelper(settings);+ assertEquals(+ expectedScope,+ migrated.getValueByExactKeyPath("storage", "signing", "userListScope"));+ assertNull(migrated.getValueByExactKeyPath("storage", "encryption", "userListScope"));++ initializer.ensureConfigExists();+ YamlHelper restarted = new YamlHelper(settings);+ assertEquals(+ expectedScope,+ restarted.getValueByExactKeyPath("storage", "signing", "userListScope"));+ assertEquals(migrated.getAllKeys(), restarted.getAllKeys());+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.javaindex d73550510f..2290522aea 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ServerCertificateService.java@@ -29,8 +29,6 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.configuration.InstallationPathConfig;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.ServerCertificateServiceInterface;-import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;-import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;@Service@Slf4j@@ -45,11 +43,7 @@ public class ServerCertificateService implements ServerCertificateServiceInterfaprivate int validityDays;private boolean regenerateOnStartup;- private final LicenseKeyChecker licenseKeyChecker;-- public ServerCertificateService(- LicenseKeyChecker licenseKeyChecker, ApplicationProperties applicationProperties) {- this.licenseKeyChecker = licenseKeyChecker;+ public ServerCertificateService(ApplicationProperties applicationProperties) {ApplicationProperties.System.ServerCertificate config =applicationProperties.getSystem().getServerCertificate();this.enabled = config.isEnabled();@@ -66,13 +60,8 @@ public class ServerCertificateService implements ServerCertificateServiceInterfareturn Path.of(InstallationPathConfig.getConfigPath(), KEYSTORE_FILENAME);}- private boolean hasProOrEnterpriseAccess() {- License license = licenseKeyChecker.premiumTier();- return license == License.SERVER || license == License.ENTERPRISE;- }-public boolean isEnabled() {- return enabled && hasProOrEnterpriseAccess();+ return enabled;}public boolean hasServerCertificate() {@@ -85,11 +74,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfareturn;}- if (!hasProOrEnterpriseAccess()) {- log.info("Server certificate feature requires Pro or Enterprise license");- return;- }-Path keystorePath = getKeystorePath();if (!Files.exists(keystorePath) || regenerateOnStartup) {@@ -105,11 +89,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa}public KeyStore getServerKeyStore() throws Exception {- if (!hasProOrEnterpriseAccess()) {- throw new IllegalStateException(- "Server certificate feature requires Pro or Enterprise license");- }-if (!enabled || !hasServerCertificate()) {throw new IllegalStateException("Server certificate is not available");}@@ -136,11 +115,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa}public void uploadServerCertificate(InputStream p12Stream, String password) throws Exception {- if (!hasProOrEnterpriseAccess()) {- throw new IllegalStateException(- "Server certificate feature requires Pro or Enterprise license");- }-// Validate the uploaded certificateKeyStore uploadedKeyStore = KeyStore.getInstance("PKCS12");uploadedKeyStore.load(p12Stream, password.toCharArray());@@ -201,11 +175,6 @@ public class ServerCertificateService implements ServerCertificateServiceInterfa}private void generateServerCertificate() throws Exception {- if (!hasProOrEnterpriseAccess()) {- throw new IllegalStateException(- "Server certificate feature requires Pro or Enterprise license");- }-// Generate key pairKeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");keyPairGenerator.initialize(2048, new SecureRandom());diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.javaindex f828dd4c2d..68ee0abc1b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.java@@ -22,7 +22,6 @@ public class ToolKeyRegistry {// CORE_REGULAR_TOOL_IDS"certSign","sign",- "sharedSign","addText","addPassword","removePassword",diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/SigningSessionController.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/SigningSessionController.javaindex 00044e9055..a07cbdfa85 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/SigningSessionController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/SigningSessionController.java@@ -22,6 +22,10 @@ import org.springframework.web.multipart.MultipartFile;import org.springframework.web.server.ResponseStatusException;import io.swagger.v3.oas.annotations.Operation;+import io.swagger.v3.oas.annotations.media.ArraySchema;+import io.swagger.v3.oas.annotations.media.Content;+import io.swagger.v3.oas.annotations.media.Schema;+import io.swagger.v3.oas.annotations.responses.ApiResponse;import io.swagger.v3.oas.annotations.tags.Tag;import jakarta.validation.constraints.NotBlank;@@ -37,11 +41,11 @@ import stirling.software.proprietary.security.service.UserService;import stirling.software.proprietary.workflow.dto.CertificateInfo;import stirling.software.proprietary.workflow.dto.CertificateValidationResponse;import stirling.software.proprietary.workflow.dto.ParticipantRequest;+import stirling.software.proprietary.workflow.dto.SignRequestSummaryDTO;import stirling.software.proprietary.workflow.dto.WorkflowCreationRequest;-import stirling.software.proprietary.workflow.model.WorkflowParticipant;import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.service.CertificateSubmissionValidator;-import stirling.software.proprietary.workflow.service.SigningFinalizationService;+import stirling.software.proprietary.workflow.service.SigningSessionFinalizationService;import stirling.software.proprietary.workflow.service.WorkflowSessionService;import tools.jackson.databind.ObjectMapper;@@ -58,7 +62,7 @@ public class SigningSessionController {private final WorkflowSessionService workflowSessionService;private final UserService userService;- private final SigningFinalizationService signingFinalizationService;+ private final SigningSessionFinalizationService signingSessionFinalizationService;private final CertificateSubmissionValidator certificateSubmissionValidator;private final ObjectMapper objectMapper = new ObjectMapper();@@ -154,6 +158,8 @@ public class SigningSessionController {User owner = getCurrentUser(principal);workflowSessionService.deleteSession(sessionId, owner);return ResponseEntity.noContent().build();+ } catch (ResponseStatusException e) {+ return ResponseEntity.status(e.getStatusCode()).body(e.getReason());} catch (Exception e) {log.error("Error deleting session {}", sessionId, e);return ResponseEntity.status(HttpStatus.FORBIDDEN)@@ -178,6 +184,8 @@ public class SigningSessionController {workflowSessionService.getSessionWithParticipantsForOwner(sessionId, owner);return ResponseEntity.ok(stirling.software.proprietary.workflow.util.WorkflowMapper.toResponse(session));+ } catch (ResponseStatusException e) {+ throw e;} catch (Exception e) {log.error("Error adding participants to session {}", sessionId, e);return ResponseEntity.status(HttpStatus.FORBIDDEN)@@ -242,38 +250,10 @@ public class SigningSessionController {try {User owner = getCurrentUser(principal);- WorkflowSession session =- workflowSessionService.getSessionWithParticipantsForOwner(sessionId, owner);-- byte[] originalPdf = workflowSessionService.getOriginalFile(sessionId);- byte[] pdf = signingFinalizationService.finalizeDocument(session, originalPdf);-- String filename = session.getDocumentName().replace(".pdf", "") + "_shared_signed.pdf";- workflowSessionService.storeProcessedFile(session, pdf, filename);- workflowSessionService.finalizeSession(sessionId, owner);- workflowSessionService.deleteOriginalFile(session);-- try {- signingFinalizationService.clearSensitiveMetadata(session);- } catch (Exception e) {- log.error(- "SECURITY: Failed to clear sensitive metadata for session {} "- + "(participants: {}). Keystore credentials may remain in the "- + "database until manual cleanup.",- sessionId,- session.getParticipants() != null- ? session.getParticipants().stream()- .map(WorkflowParticipant::getEmail)- .toList()- : "unknown",- e);- throw new ResponseStatusException(- HttpStatus.INTERNAL_SERVER_ERROR,- "Document signed successfully but post-signing cleanup failed. "- + "Contact your administrator to complete the cleanup.");- }-- return WebResponseUtils.bytesToWebResponse(pdf, filename);+ var document = signingSessionFinalizationService.finalizeSession(sessionId, owner);+ return WebResponseUtils.bytesToWebResponse(document.bytes(), document.filename());+ } catch (ResponseStatusException e) {+ throw e;} catch (Exception e) {log.error("Error finalizing session {}", sessionId, e);return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();@@ -309,6 +289,18 @@ public class SigningSessionController {// ===== SIGN REQUESTS (Participant View) =====@Operation(summary = "List sign requests for authenticated user")+ @ApiResponse(+ responseCode = "200",+ description = "Participant requests, including finalized, declined and expired access",+ content =+ @Content(+ mediaType = MediaType.APPLICATION_JSON_VALUE,+ array =+ @ArraySchema(+ schema =+ @Schema(+ implementation =+ SignRequestSummaryDTO.class))))@Transactional(readOnly = true)@GetMapping(value = "/cert-sign/sign-requests")public ResponseEntity<?> listSignRequests(Principal principal) {@@ -326,8 +318,18 @@ public class SigningSessionController {}}- @Transactional(readOnly = true)@Operation(summary = "Get sign request detail for participant")+ @ApiResponse(+ responseCode = "200",+ description = "Participant request with submitted signature previews and progress",+ content =+ @Content(+ mediaType = MediaType.APPLICATION_JSON_VALUE,+ schema =+ @Schema(+ implementation =+ stirling.software.proprietary.workflow.dto+ .SignRequestDetailDTO.class)))@GetMapping(value = "/cert-sign/sign-requests/{sessionId}")public ResponseEntity<?> getSignRequestDetail(@PathVariable("sessionId") @NotBlank String sessionId, Principal principal) {@@ -382,6 +384,8 @@ public class SigningSessionController {User user = getCurrentUser(principal);workflowSessionService.signDocument(sessionId, user, request);return ResponseEntity.noContent().build();+ } catch (ResponseStatusException e) {+ throw e;} catch (IllegalArgumentException e) {log.error("Invalid sign request for session {}", sessionId, e);return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());@@ -404,6 +408,8 @@ public class SigningSessionController {User user = getCurrentUser(principal);workflowSessionService.declineSignRequest(sessionId, user);return ResponseEntity.noContent().build();+ } catch (ResponseStatusException e) {+ throw e;} catch (Exception e) {log.error("Error declining sign request for session {}", sessionId, e);return ResponseEntity.status(HttpStatus.FORBIDDEN)@@ -425,6 +431,8 @@ public class SigningSessionController {@RequestParam("certType") String certType,@RequestParam(value = "password", required = false) String password,@RequestParam(value = "p12File", required = false) MultipartFile p12File,+ @RequestParam(value = "privateKeyFile", required = false) MultipartFile privateKeyFile,+ @RequestParam(value = "certFile", required = false) MultipartFile certFile,@RequestParam(value = "jksFile", required = false) MultipartFile jksFile,Principal principal) {@@ -433,7 +441,8 @@ public class SigningSessionController {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();}- if (!"SERVER".equalsIgnoreCase(certType)+ if (!"PEM".equalsIgnoreCase(certType)+ && !"SERVER".equalsIgnoreCase(certType)&& !"USER_CERT".equalsIgnoreCase(certType)&& (p12File == null || p12File.isEmpty())&& (jksFile == null || jksFile.isEmpty())) {@@ -443,7 +452,11 @@ public class SigningSessionController {try {byte[] keystoreBytes = null;- if (p12File != null && !p12File.isEmpty()) {+ if ("PEM".equalsIgnoreCase(certType)) {+ keystoreBytes =+ workflowSessionService.buildPkcs12FromPem(+ privateKeyFile, certFile, password);+ } else if (p12File != null && !p12File.isEmpty()) {keystoreBytes = p12File.getBytes();} else if (jksFile != null && !jksFile.isEmpty()) {keystoreBytes = jksFile.getBytes();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.javaindex 4df0c93e1d..ca155a9087 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantController.java@@ -13,6 +13,7 @@ import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;+import org.springframework.transaction.annotation.Transactional;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PostMapping;@@ -75,19 +76,13 @@ public class WorkflowParticipantController {summary = "Get workflow session details by participant token",description = "Allows participants to view session details using their share token")@GetMapping(value = "/session", produces = MediaType.APPLICATION_JSON_VALUE)+ @Transactionalpublic ResponseEntity<WorkflowSessionResponse> getSessionByToken(@RequestParam("token") @NotBlank String token) {workflowSessionService.ensureSigningEnabled();- WorkflowParticipant participant =- participantRepository- .findByShareToken(token)- .orElseThrow(- () ->- new ResponseStatusException(- HttpStatus.FORBIDDEN,- "Invalid or expired participant token"));+ WorkflowParticipant participant = workflowSessionService.lockParticipantByToken(token);// Check if participant is expiredif (participant.isExpired()) {@@ -95,8 +90,9 @@ public class WorkflowParticipantController {}// Mark as viewed if not already- if (participant.getStatus() == ParticipantStatus.PENDING- || participant.getStatus() == ParticipantStatus.NOTIFIED) {+ if (participant.getWorkflowSession().isActive()+ && (participant.getStatus() == ParticipantStatus.PENDING+ || participant.getStatus() == ParticipantStatus.NOTIFIED)) {workflowSessionService.updateParticipantStatus(participant.getId(), ParticipantStatus.VIEWED);}@@ -136,6 +132,7 @@ public class WorkflowParticipantController {value = "/submit-signature",consumes = MediaType.MULTIPART_FORM_DATA_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)+ @Transactionalpublic ResponseEntity<ParticipantResponse> submitSignature(@ModelAttribute SignatureSubmissionRequest request) {@@ -147,32 +144,21 @@ public class WorkflowParticipantController {}WorkflowParticipant participant =- participantRepository- .findByShareToken(request.getParticipantToken())- .orElseThrow(- () ->- new ResponseStatusException(- HttpStatus.FORBIDDEN,- "Invalid or expired participant token"));+ workflowSessionService.lockParticipantByToken(request.getParticipantToken());- // Check if participant can still submit- if (participant.isExpired()) {- throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Participant access expired");- }-- if (participant.hasCompleted()) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST, "Participant has already completed their action");- }-- if (!participant.getWorkflowSession().isActive()) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST, "Workflow session is no longer active");- }+ workflowSessionService.ensureParticipantCanRespond(participant);+ workflowSessionService.ensureCertificateTypeAllowed(request.getCertType());+ workflowSessionService.ensureCertificateFilesPresent(+ request.getCertType(),+ request.getP12File(),+ request.getJksFile(),+ request.getPrivateKeyFile(),+ request.getCertFile());try {// Build metadata map with certificate and wet signature data- Map<String, Object> metadata = buildSubmissionMetadata(request);+ Map<String, Object> metadata =+ buildSubmissionMetadata(request, participant.getWorkflowSession());participant.setParticipantMetadata(metadata);// Update status to SIGNED@@ -188,6 +174,9 @@ public class WorkflowParticipantController {} catch (ResponseStatusException e) {throw e;+ } catch (IllegalArgumentException | tools.jackson.core.JacksonException e) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Invalid signature submission", e);} catch (Exception e) {log.error("Error submitting signature for participant {}", participant.getEmail(), e);throw new ResponseStatusException(@@ -199,25 +188,16 @@ public class WorkflowParticipantController {summary = "Decline participation",description = "Participant declines to sign or participate in the workflow")@PostMapping(value = "/decline", produces = MediaType.APPLICATION_JSON_VALUE)+ @Transactionalpublic ResponseEntity<ParticipantResponse> declineParticipation(@RequestParam("token") @NotBlank String token,@RequestParam(value = "reason", required = false) @Size(max = 500) String reason) {workflowSessionService.ensureSigningEnabled();- WorkflowParticipant participant =- participantRepository- .findByShareToken(token)- .orElseThrow(- () ->- new ResponseStatusException(- HttpStatus.FORBIDDEN,- "Invalid or expired participant token"));+ WorkflowParticipant participant = workflowSessionService.lockParticipantByToken(token);- if (participant.hasCompleted()) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST, "Participant has already completed their action");- }+ workflowSessionService.ensureParticipantCanRespond(participant);// Update status to DECLINEDparticipant.setStatus(ParticipantStatus.DECLINED);@@ -298,6 +278,8 @@ public class WorkflowParticipantController {@RequestParam("certType") String certType,@RequestParam(value = "password", required = false) String password,@RequestParam(value = "p12File", required = false) MultipartFile p12File,+ @RequestParam(value = "privateKeyFile", required = false) MultipartFile privateKeyFile,+ @RequestParam(value = "certFile", required = false) MultipartFile certFile,@RequestParam(value = "jksFile", required = false) MultipartFile jksFile) {workflowSessionService.ensureSigningEnabled();@@ -313,7 +295,8 @@ public class WorkflowParticipantController {// Require a file for non-SERVER/non-USER_CERT types — this is a request error, not a// validation failure- if (!"SERVER".equalsIgnoreCase(certType)+ if (!"PEM".equalsIgnoreCase(certType)+ && !"SERVER".equalsIgnoreCase(certType)&& !"USER_CERT".equalsIgnoreCase(certType)&& (p12File == null || p12File.isEmpty())&& (jksFile == null || jksFile.isEmpty())) {@@ -323,7 +306,11 @@ public class WorkflowParticipantController {try {byte[] keystoreBytes = null;- if (p12File != null && !p12File.isEmpty()) {+ if ("PEM".equalsIgnoreCase(certType)) {+ keystoreBytes =+ workflowSessionService.buildPkcs12FromPem(+ privateKeyFile, certFile, password);+ } else if (p12File != null && !p12File.isEmpty()) {keystoreBytes = p12File.getBytes();} else if (jksFile != null && !jksFile.isEmpty()) {keystoreBytes = jksFile.getBytes();@@ -375,8 +362,8 @@ public class WorkflowParticipantController {* Builds metadata map from signature submission request. Includes certificate submission and* wet signature data.*/- private Map<String, Object> buildSubmissionMetadata(SignatureSubmissionRequest request)- throws IOException {+ private Map<String, Object> buildSubmissionMetadata(+ SignatureSubmissionRequest request, WorkflowSession session) throws IOException {Map<String, Object> metadata = new HashMap<>();// Validate certificate before storing — throws 400 if invalid, expired, or wrong password@@ -416,6 +403,17 @@ public class WorkflowParticipantController {"jksKeystore",metadataEncryptionService.encryptBytes(request.getJksFile().getBytes()));}+ if ("PEM".equalsIgnoreCase(request.getCertType())) {+ byte[] keystore =+ workflowSessionService.buildPkcs12FromPem(+ request.getPrivateKeyFile(),+ request.getCertFile(),+ request.getPassword());+ certificateSubmissionValidator.validateAndExtractInfo(+ keystore, "PKCS12", request.getPassword());+ certSubmission.put("certType", "PKCS12");+ certSubmission.put("p12Keystore", metadataEncryptionService.encryptBytes(keystore));+ }metadata.put("certificateSubmission", certSubmission);}@@ -426,15 +424,26 @@ public class WorkflowParticipantController {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Wet signatures data exceeds maximum allowed size");}- @SuppressWarnings("unchecked")- java.util.List<Map<String, Object>> wetSigs =+ List<WetSignatureMetadata> wetSigs =objectMapper.readValue(request.getWetSignaturesData(),- new TypeReference<List<Map<String, Object>>>() {});- if (wetSigs.size() > WetSignatureMetadata.MAX_SIGNATURES_PER_PARTICIPANT) {+ new TypeReference<List<WetSignatureMetadata>>() {});+ if (wetSigs == null+ || wetSigs.size() > WetSignatureMetadata.MAX_SIGNATURES_PER_PARTICIPANT) {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Too many wet signatures submitted");}+ for (WetSignatureMetadata signature : wetSigs) {+ if (signature == null)+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Wet signature is required");+ try {+ signature.validate();+ } catch (IllegalArgumentException e) {+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e);+ }+ }+ workflowSessionService.validateWetSignatures(session, wetSigs);metadata.put("wetSignatures", wetSigs);}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestDetailDTO.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestDetailDTO.javaindex 159623d858..ad68de96e6 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestDetailDTO.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestDetailDTO.java@@ -1,5 +1,7 @@package stirling.software.proprietary.workflow.dto;+import java.util.List;+import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@@ -18,6 +20,9 @@ public class SignRequestDetailDTO {private String dueDate;private String createdAt;private ParticipantStatus myStatus;+ private boolean finalized;+ private boolean canSign;+ private List<SigningParticipantPreview> participants = List.of();// Signature appearance settings (read-only, configured by owner)private Boolean showSignature;private Integer pageNumber;diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestSummaryDTO.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestSummaryDTO.javaindex 884cdb3843..71071acdb9 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestSummaryDTO.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignRequestSummaryDTO.java@@ -1,5 +1,7 @@package stirling.software.proprietary.workflow.dto;+import io.swagger.v3.oas.annotations.media.Schema;+import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@@ -17,4 +19,15 @@ public class SignRequestSummaryDTO {private String createdAt;private String dueDate;private ParticipantStatus myStatus;+ private boolean finalized;++ @Schema(+ description =+ "Whether the participant's access has expired; independent of the advisory due date")+ private boolean accessExpired;++ @Schema(+ description =+ "Closed for this participant: inactive workflow, expired access, declined request or non-signing role. Submitted signatures stay active until the workflow closes.")+ private boolean closed;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignatureSubmissionRequest.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignatureSubmissionRequest.javaindex c5d2e95c68..468ee8e79f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignatureSubmissionRequest.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SignatureSubmissionRequest.java@@ -20,6 +20,8 @@ public class SignatureSubmissionRequest {private String password;private MultipartFile p12File;private MultipartFile jksFile;+ private MultipartFile privateKeyFile;+ private MultipartFile certFile;private Boolean showSignature;private Integer pageNumber;private String location;diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SigningParticipantPreview.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SigningParticipantPreview.javanew file mode 100644index 0000000000..432a10ff75--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/SigningParticipantPreview.java@@ -0,0 +1,9 @@+package stirling.software.proprietary.workflow.dto;++import java.util.List;++import stirling.software.proprietary.workflow.model.ParticipantStatus;++/** Participant-visible progress and submitted marks, excluding credentials and share tokens. */+public record SigningParticipantPreview(+ Long id, String name, ParticipantStatus status, List<WetSignatureMetadata> wetSignatures) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadata.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadata.javaindex 3da7f5d17f..909a52c998 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadata.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadata.java@@ -1,5 +1,12 @@package stirling.software.proprietary.workflow.dto;+import java.io.ByteArrayInputStream;+import java.util.Base64;++import javax.imageio.ImageIO;+import javax.imageio.ImageReader;+import javax.imageio.stream.ImageInputStream;+import jakarta.validation.constraints.DecimalMax;import jakarta.validation.constraints.NotNull;import jakarta.validation.constraints.Pattern;@@ -32,8 +39,8 @@ public class WetSignatureMetadata {private String type;/**- * Base64-encoded image data or text content for the signature. For canvas/image types:- * data:image/png;base64,... format For text type: plain text string+ * Rasterized signature in data:image/...;base64,... format, including typed signatures.+ * Rasterizing text preserves the participant's chosen font at finalization.*/@NotNull(message = "Wet signature data is required")@Size(max = 5_000_000, message = "Wet signature data exceeds maximum size of 5MB")@@ -80,11 +87,45 @@ public class WetSignatureMetadata {* @throws IllegalArgumentException if validation fails*/public boolean validate() {- if (type.equals("canvas") || type.equals("image")) {- if (!data.startsWith("data:image/")) {- throw new IllegalArgumentException(- "Image wet signature data must start with data:image/ prefix");+ if (type == null || !java.util.Set.of("canvas", "image", "text").contains(type)) {+ throw new IllegalArgumentException("Wet signature type must be canvas, image, or text");+ }+ if (data == null+ || data.length() > 5_000_000+ || !data.startsWith("data:image/")+ || !data.contains(";base64,")) {+ throw new IllegalArgumentException(+ "All wet signatures, including typed text, require a base64 image data URL with data:image/ prefix");+ }+ if (page == null+ || page < 0+ || !fraction(x, true)+ || !fraction(y, true)+ || !fraction(width, false)+ || !fraction(height, false)) {+ throw new IllegalArgumentException(+ "Wet signature page and fractional coordinates are invalid");+ }+ try (ImageInputStream input =+ ImageIO.createImageInputStream(+ new ByteArrayInputStream(+ Base64.getDecoder().decode(extractBase64Data())))) {+ var readers = ImageIO.getImageReaders(input);+ if (!readers.hasNext())+ throw new IllegalArgumentException("Wet signature image is unreadable");+ ImageReader reader = readers.next();+ try {+ reader.setInput(input);+ if (reader.getWidth(0) > 4096 || reader.getHeight(0) > 4096) {+ throw new IllegalArgumentException(+ "Wet signature image must not exceed 4096 pixels per side");+ }+ reader.read(0).flush();+ } finally {+ reader.dispose();}+ } catch (java.io.IOException e) {+ throw new IllegalArgumentException("Wet signature image is unreadable", e);}if (x != null && width != null && x + width > 1.0) {throw new IllegalArgumentException(@@ -97,6 +138,13 @@ public class WetSignatureMetadata {return true;}+ private boolean fraction(Double value, boolean allowZero) {+ return value != null+ && Double.isFinite(value)+ && value <= 1+ && (allowZero ? value >= 0 : value > 0);+ }+/*** Extracts just the base64 data portion from a data URL. Removes the "data:image/png;base64,"* prefix.diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/model/UserServerCertificateEntity.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/model/UserServerCertificateEntity.javaindex aef781dd9b..27d25cfbbb 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/model/UserServerCertificateEntity.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/model/UserServerCertificateEntity.java@@ -37,7 +37,7 @@ public class UserServerCertificateEntity implements Serializable {@JsonIgnoreprivate User user;- @Lob+ // PostgreSQL bytea needs binary binding; @Lob binds a large-object OID instead.@Basic(fetch = FetchType.EAGER)@Column(name = "keystore_data", nullable = false, columnDefinition = "bytea")@JsonIgnorediff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowParticipantRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowParticipantRepository.javaindex ce18f6d373..71e67dc7a2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowParticipantRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowParticipantRepository.java@@ -16,6 +16,11 @@ import stirling.software.proprietary.workflow.model.WorkflowSession;public interface WorkflowParticipantRepository extends JpaRepository<WorkflowParticipant, Long> {+ /** Resolves the session without loading stale participant state before acquiring its lock. */+ @Query(+ "SELECT p.workflowSession.sessionId FROM WorkflowParticipant p WHERE p.shareToken = :token")+ Optional<String> findSessionIdByShareToken(@Param("token") String token);+/** Find participant by share token */Optional<WorkflowParticipant> findByShareToken(String shareToken);diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowSessionRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowSessionRepository.javaindex dd047032b4..49da4fd780 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowSessionRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/repository/WorkflowSessionRepository.java@@ -4,9 +4,12 @@ import java.util.List;import java.util.Optional;import org.springframework.data.jpa.repository.JpaRepository;+import org.springframework.data.jpa.repository.Lock;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.query.Param;+import jakarta.persistence.LockModeType;+import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.model.WorkflowStatus;@@ -17,6 +20,11 @@ public interface WorkflowSessionRepository extends JpaRepository<WorkflowSession/** Find workflow session by unique session ID */Optional<WorkflowSession> findBySessionId(String sessionId);+ /** Serializes session mutations until the caller's transaction completes. */+ @Lock(LockModeType.PESSIMISTIC_WRITE)+ @Query("SELECT ws FROM WorkflowSession ws WHERE ws.sessionId = :sessionId")+ Optional<WorkflowSession> findBySessionIdForUpdate(@Param("sessionId") String sessionId);+/** Find workflow session by unique session ID with participants and owner eagerly loaded */@Query("SELECT ws FROM WorkflowSession ws LEFT JOIN FETCH ws.participants LEFT JOIN FETCH"diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/SigningFinalizationService.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/SigningFinalizationService.javaindex 3fce8c69dd..d58cbe407c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/SigningFinalizationService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/SigningFinalizationService.java@@ -25,6 +25,7 @@ import org.apache.pdfbox.pdmodel.font.PDType1Font;import org.apache.pdfbox.pdmodel.font.Standard14Fonts.FontName;import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;+import org.apache.pdfbox.util.Matrix;import org.bouncycastle.asn1.x500.RDN;import org.bouncycastle.asn1.x500.X500Name;import org.bouncycastle.asn1.x500.style.BCStyle;@@ -49,6 +50,7 @@ import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;import tools.jackson.databind.ObjectMapper;+import tools.jackson.databind.node.ObjectNode;/*** Service responsible for finalizing a signing session. Encapsulates all PDF manipulation logic@@ -140,10 +142,9 @@ public class SigningFinalizationService {CertificateSubmission submission = extractCertificateSubmission(fresh);if (submission == null) {- log.warn(- "No certificate submission found for participant {}, skipping",- fresh.getEmail());- continue;+ throw new ResponseStatusException(+ HttpStatus.CONFLICT,+ "Missing certificate submission for participant " + fresh.getId());}ParticipantSignatureMetadata sigMeta =@@ -230,12 +231,9 @@ public class SigningFinalizationService {private void applyWetSignatureToPage(PDDocument document, WetSignatureMetadata wetSig)throws Exception {int pageIndex = wetSig.getPage();- if (pageIndex >= document.getNumberOfPages()) {- log.warn(- "Wet signature page {} exceeds document pages {}, skipping",- pageIndex,- document.getNumberOfPages());- return;+ if (pageIndex < 0 || pageIndex >= document.getNumberOfPages()) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Wet signature page does not exist");}PDPage page = document.getPage(pageIndex);@@ -255,18 +253,42 @@ public class SigningFinalizationService {PDImageXObject image =PDImageXObject.createFromByteArray(document, imageBytes, "signature");- // Coordinates are stored as fractions (0–1) of the page dimensions.- // Multiply by page size to get absolute PDF points, then convert Y from- // UI top-left origin to PDF bottom-left origin.- float pageWidth = page.getMediaBox().getWidth();- float pageHeight = page.getMediaBox().getHeight();+ // The viewer displays the rotated crop box, which can differ from the media box.+ PDRectangle crop = page.getCropBox();+ int rotation = Math.floorMod(page.getRotation(), 360);+ float pageWidth = rotation % 180 == 0 ? crop.getWidth() : crop.getHeight();+ float pageHeight = rotation % 180 == 0 ? crop.getHeight() : crop.getWidth();+ Matrix toPage =+ switch (rotation) {+ case 90 ->+ new Matrix(+ 0, 1, -1, 0, crop.getUpperRightX(), crop.getLowerLeftY());+ case 180 ->+ new Matrix(+ -1, 0, 0, -1, crop.getUpperRightX(), crop.getUpperRightY());+ case 270 ->+ new Matrix(+ 0, -1, 1, 0, crop.getLowerLeftX(), crop.getUpperRightY());+ default ->+ new Matrix(1, 0, 0, 1, crop.getLowerLeftX(), crop.getLowerLeftY());+ };+ contentStream.transform(toPage);float x = wetSig.getX().floatValue() * pageWidth;float y = wetSig.getY().floatValue() * pageHeight;float width = wetSig.getWidth().floatValue() * pageWidth;float height = wetSig.getHeight().floatValue() * pageHeight;float pdfY = pageHeight - y - height;- contentStream.drawImage(image, x, pdfY, width, height);+ // Match the preview's object-fit: contain instead of stretching the signature.+ float scale = Math.min(width / image.getWidth(), height / image.getHeight());+ float imageWidth = image.getWidth() * scale;+ float imageHeight = image.getHeight() * scale;+ contentStream.drawImage(+ image,+ x + (width - imageWidth) / 2,+ pdfY + (height - imageHeight) / 2,+ imageWidth,+ imageHeight);log.info("Applied wet signature at page {} coordinates ({}, {}) size {}x{}",@@ -1021,11 +1043,13 @@ public class SigningFinalizationService {}try {- var node = objectMapper.valueToTree(metadata);- if (node.has("certificateSubmission")) {+ var node = objectMapper.valueToTree(metadata.get("certificateSubmission"));+ if (node instanceof ObjectNode certNode) {+ // Persisted keystores are encrypted strings, not the DTO's Base64 byte arrays.+ var p12 = certNode.remove("p12Keystore");+ var jks = certNode.remove("jksKeystore");CertificateSubmission submission =- objectMapper.treeToValue(- node.get("certificateSubmission"), CertificateSubmission.class);+ objectMapper.treeToValue(certNode, CertificateSubmission.class);// Decrypt password (supports both legacy plaintext and encrypted values)if (submission.getPassword() != null) {@@ -1033,27 +1057,22 @@ public class SigningFinalizationService {metadataEncryptionService.decrypt(submission.getPassword()));}- // Decrypt + decode keystore bytes (supports both legacy plaintext base64 and- // encrypted values).- var certNode = node.get("certificateSubmission");- if (certNode.has("p12Keystore")) {+ if (p12 != null && !p12.isNull()) {submission.setP12Keystore(- metadataEncryptionService.decryptBytes(- certNode.get("p12Keystore").asString()));+ metadataEncryptionService.decryptBytes(p12.asString()));}- if (certNode.has("jksKeystore")) {+ if (jks != null && !jks.isNull()) {submission.setJksKeystore(- metadataEncryptionService.decryptBytes(- certNode.get("jksKeystore").asString()));+ metadataEncryptionService.decryptBytes(jks.asString()));}return submission;}} catch (Exception e) {- log.error(- "Failed to parse certificate submission for participant {}: {}",- participant.getEmail(),- e.getMessage(),- e);+ // Deserialization exceptions can contain certificate material; omit their payloads.+ log.warn("Cannot read certificate submission for participant {}", participant.getId());+ throw new ResponseStatusException(+ HttpStatus.CONFLICT,+ "Cannot read certificate submission for participant " + participant.getId());}return null;}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/SigningSessionFinalizationService.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/SigningSessionFinalizationService.javanew file mode 100644index 0000000000..f237b6e6d4--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/SigningSessionFinalizationService.java@@ -0,0 +1,60 @@+package stirling.software.proprietary.workflow.service;++import org.springframework.http.HttpStatus;+import org.springframework.stereotype.Service;+import org.springframework.transaction.annotation.Transactional;+import org.springframework.web.server.ResponseStatusException;++import lombok.RequiredArgsConstructor;++import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.workflow.model.ParticipantStatus;+import stirling.software.proprietary.workflow.model.WorkflowSession;++/**+ * Publishes the signed document and clears credentials atomically while holding the session lock.+ */+@Service+@RequiredArgsConstructor+public class SigningSessionFinalizationService {+ private final WorkflowSessionService workflowSessionService;+ private final SigningFinalizationService signingFinalizationService;++ /**+ * Requires at least one accepted signature; any failure leaves the session open for retry.+ * Retains the original PDF and its required database reference for session history.+ */+ @Transactional(rollbackFor = Exception.class)+ public FinalizedDocument finalizeSession(String sessionId, User owner) throws Exception {+ WorkflowSession session =+ workflowSessionService.lockActiveSessionForOwner(sessionId, owner);+ boolean hasSignature = false;+ for (var participant : session.getParticipants()) {+ if (participant.getStatus() == ParticipantStatus.SIGNED) {+ hasSignature = true;+ var metadata = participant.getParticipantMetadata();+ if (metadata != null+ && metadata.get("certificateSubmission")+ instanceof java.util.Map<?, ?> submission) {+ workflowSessionService.ensureCertificateTypeAllowed(+ (String) submission.get("certType"));+ }+ }+ }+ if (!hasSignature) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "At least one participant must sign before finalization");+ }+ byte[] original = workflowSessionService.getOriginalFile(sessionId);+ byte[] pdf = signingFinalizationService.finalizeDocument(session, original);+ String filename =+ session.getDocumentName().replaceFirst("(?i)\\.pdf$", "") + "_shared_signed.pdf";+ workflowSessionService.storeProcessedFile(session, pdf, filename);+ signingFinalizationService.clearSensitiveMetadata(session);+ workflowSessionService.finalizeSession(sessionId, owner);+ return new FinalizedDocument(pdf, filename);+ }++ /** The response is returned only after the finalization transaction commits. */+ public record FinalizedDocument(byte[] bytes, String filename) {}+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.javaindex a2db5deb5a..e7d5ae0173 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/service/WorkflowSessionService.java@@ -11,10 +11,14 @@ import java.security.cert.CertificateFactory;import java.time.LocalDateTime;import java.util.ArrayList;import java.util.HashMap;+import java.util.HashSet;import java.util.List;+import java.util.Locale;import java.util.Map;+import java.util.Set;import java.util.UUID;+import org.apache.pdfbox.pdmodel.PDDocument;import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;import org.bouncycastle.openssl.PEMDecryptorProvider;import org.bouncycastle.openssl.PEMEncryptedKeyPair;@@ -27,7 +31,10 @@ import org.bouncycastle.operator.InputDecryptorProvider;import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Service;+import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;+import org.springframework.transaction.support.TransactionSynchronization;+import org.springframework.transaction.support.TransactionSynchronizationManager;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.server.ResponseStatusException;@@ -35,6 +42,8 @@ import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.service.LicenseServiceInterface;import stirling.software.proprietary.security.database.repository.UserRepository;import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.storage.crypto.StorageEncryptionErrors;@@ -81,6 +90,146 @@ public class WorkflowSessionService {private final ApplicationProperties applicationProperties;private final MetadataEncryptionService metadataEncryptionService;private final CertificateSubmissionValidator certificateSubmissionValidator;+ private final LicenseServiceInterface licenseService;+ private final CustomPDFDocumentFactory pdfDocumentFactory;++ /**+ * Personal account certificates require a paid entitlement; organization certificates do not.+ */+ public void ensureCertificateTypeAllowed(String certType) {+ if ("USER_CERT".equalsIgnoreCase(certType) && !licenseService.isRunningProOrHigher()) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Personal signing certificates require a Pro license");+ }+ }++ /** Rejects incomplete uploaded certificates before a participant is marked as signed. */+ public void ensureCertificateFilesPresent(+ String certType,+ MultipartFile p12File,+ MultipartFile jksFile,+ MultipartFile privateKeyFile,+ MultipartFile certFile) {+ boolean present =+ switch (certType == null ? "" : certType.toUpperCase(Locale.ROOT)) {+ case "P12", "PKCS12", "PFX" -> p12File != null && !p12File.isEmpty();+ case "JKS" -> jksFile != null && !jksFile.isEmpty();+ case "PEM" ->+ privateKeyFile != null+ && !privateKeyFile.isEmpty()+ && certFile != null+ && !certFile.isEmpty();+ case "SERVER", "USER_CERT" -> true;+ default -> false;+ };+ if (!present)+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST,+ "Select a supported certificate type and provide its required files");+ }++ /** Checks visual marks against the original document before accepting a signing decision. */+ public void validateWetSignatures(+ WorkflowSession session, List<WetSignatureMetadata> signatures) {+ if (signatures == null+ || signatures.size() > WetSignatureMetadata.MAX_SIGNATURES_PER_PARTICIPANT) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Invalid number of wet signatures");+ }+ if (signatures.isEmpty()) return;+ try {+ for (WetSignatureMetadata signature : signatures) {+ if (signature == null)+ throw new IllegalArgumentException("Wet signature is required");+ signature.validate();+ }+ try (PDDocument document =+ pdfDocumentFactory.load(+ readBlob(session.getOriginalFile().getStorageKey()), true)) {+ if (signatures.stream()+ .anyMatch(+ signature -> signature.getPage() >= document.getNumberOfPages())) {+ throw new IllegalArgumentException("Wet signature page does not exist");+ }+ }+ } catch (IllegalArgumentException e) {+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e);+ } catch (IOException e) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Cannot read the signing document", e);+ }+ }++ /** Locks a session for the remainder of the caller's transaction. */+ @Transactional(propagation = Propagation.MANDATORY)+ public WorkflowSession lockSession(String sessionId) {+ return workflowSessionRepository+ .findBySessionIdForUpdate(sessionId)+ .orElseThrow(+ () ->+ new ResponseStatusException(+ HttpStatus.NOT_FOUND, "Workflow session not found"));+ }++ /** Locks an owner's session before checking whether it can still be changed. */+ @Transactional(propagation = Propagation.MANDATORY)+ public WorkflowSession lockActiveSessionForOwner(String sessionId, User owner) {+ WorkflowSession session = lockSession(sessionId);+ if (!session.getOwner().equals(owner)) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Not authorized to access this workflow session");+ }+ requireActiveSession(session);+ return session;+ }++ /**+ * Resolves a token under the same session lock used by authenticated signing and finalization.+ */+ @Transactional(propagation = Propagation.MANDATORY)+ public WorkflowParticipant lockParticipantByToken(String token) {+ String sessionId =+ workflowParticipantRepository+ .findSessionIdByShareToken(token)+ .orElseThrow(+ () ->+ new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Invalid participant token"));+ lockSession(sessionId);+ return workflowParticipantRepository+ .findByShareToken(token)+ .orElseThrow(+ () ->+ new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Invalid participant token"));+ }++ /** Requires an active session, unexpired editor access, and no previous signing decision. */+ public void ensureParticipantCanRespond(WorkflowParticipant participant) {+ requireActiveSession(participant.getWorkflowSession());+ requireUnexpiredAccess(participant);+ if (participant.getAccessRole() != ShareAccessRole.EDITOR) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Participant does not have signing permission");+ }+ if (participant.hasCompleted()) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "Participant has already signed or declined");+ }+ }++ private void requireActiveSession(WorkflowSession session) {+ if (!session.isActive()) {+ throw new ResponseStatusException(+ HttpStatus.CONFLICT, "Workflow session is no longer active");+ }+ }++ private void requireUnexpiredAccess(WorkflowParticipant participant) {+ if (participant.isExpired()) {+ throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Participant access expired");+ }+ }public void ensureSigningEnabled() {if (!applicationProperties.getStorage().isEnabled()@@ -109,7 +258,22 @@ public class WorkflowSessionService {throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Workflow type is required");}- // Store original file using StorageProvider+ if ((request.getParticipantUserIds() == null || request.getParticipantUserIds().isEmpty())+ && (request.getParticipantEmails() == null+ || request.getParticipantEmails().isEmpty())) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "At least one participant is required");+ }+ try (PDDocument document = pdfDocumentFactory.load(file, true)) {+ if (document.isEncrypted() || document.getNumberOfPages() == 0) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Upload an unprotected PDF with at least one page");+ }+ } catch (IOException e) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "The document must be a readable, unprotected PDF", e);+ }+StoredFile originalFile = storeWorkflowFile(owner, file, FilePurpose.SIGNING_ORIGINAL);// Create workflow session@@ -183,6 +347,11 @@ public class WorkflowSessionService {/** Adds participants to a workflow session. */private void addParticipantsToSession(WorkflowSession session, List<ParticipantRequest> participantRequests) {+ Set<String> identities = new HashSet<>();+ for (WorkflowParticipant existing : session.getParticipants()) {+ identities.add(existing.getEmail().strip().toLowerCase(Locale.ROOT));+ }+ List<WorkflowParticipant> additions = new ArrayList<>();for (ParticipantRequest request : participantRequests) {WorkflowParticipant participant = new WorkflowParticipant();participant.setShareToken(UUID.randomUUID().toString());@@ -238,8 +407,8 @@ public class WorkflowSessionService {participant.setUser(user);participant.setEmail(user.getUsername()); // User entity uses username, not emailparticipant.setName(user.getUsername());- } else if (request.getEmail() != null) {- participant.setEmail(request.getEmail());+ } else if (request.getEmail() != null && !request.getEmail().isBlank()) {+ participant.setEmail(request.getEmail().strip());participant.setName(request.getName() != null ? request.getName() : request.getEmail());} else {@@ -247,8 +416,15 @@ public class WorkflowSessionService {HttpStatus.BAD_REQUEST, "Participant must have either userId or email");}+ if (!identities.add(participant.getEmail().strip().toLowerCase(Locale.ROOT))) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Each participant may only be added once");+ }+ additions.add(participant);+ }+ for (WorkflowParticipant participant : additions) {session.addParticipant(participant);- participant = workflowParticipantRepository.save(participant);+ workflowParticipantRepository.save(participant);}}@@ -257,6 +433,23 @@ public class WorkflowSessionService {throws IOException {// Store file content (storage provider generates the key)StoredObject storedObject = storageProvider.store(owner, file);+ if (TransactionSynchronizationManager.isSynchronizationActive()) {+ TransactionSynchronizationManager.registerSynchronization(+ new TransactionSynchronization() {+ @Override+ public void afterCompletion(int status) {+ if (status == STATUS_ROLLED_BACK) {+ try {+ storageProvider.delete(storedObject.getStorageKey());+ } catch (Exception e) {+ log.error(+ "Failed to remove rolled-back workflow file {}",+ storedObject.getStorageKey());+ }+ }+ }+ });+ }// Create StoredFile entityStoredFile storedFile = new StoredFile();@@ -333,7 +526,7 @@ public class WorkflowSessionService {@Transactionalpublic void addParticipants(String sessionId, List<ParticipantRequest> participants, User owner) {- WorkflowSession session = getSessionForOwner(sessionId, owner);+ WorkflowSession session = lockActiveSessionForOwner(sessionId, owner);if (!session.isActive()) {throw new ResponseStatusException(@@ -347,7 +540,7 @@ public class WorkflowSessionService {/** Removes a participant from a workflow session. */@Transactionalpublic void removeParticipant(String sessionId, Long participantId, User owner) {- WorkflowSession session = getSessionForOwner(sessionId, owner);+ WorkflowSession session = lockActiveSessionForOwner(sessionId, owner);WorkflowParticipant participant =workflowParticipantRepository@@ -422,7 +615,7 @@ public class WorkflowSessionService {/** Marks a workflow session as finalized. */public void finalizeSession(String sessionId, User owner) {- WorkflowSession session = getSessionForOwner(sessionId, owner);+ WorkflowSession session = lockActiveSessionForOwner(sessionId, owner);if (session.isFinalized()) {throw new ResponseStatusException(@@ -478,7 +671,11 @@ public class WorkflowSessionService {/** Deletes a workflow session and associated files. */@Transactionalpublic void deleteSession(String sessionId, User owner) {- WorkflowSession session = getSessionForOwner(sessionId, owner);+ WorkflowSession session = lockSession(sessionId);+ if (!session.getOwner().equals(owner)) {+ throw new ResponseStatusException(+ HttpStatus.FORBIDDEN, "Not authorized to access this workflow session");+ }if (session.isFinalized()) {throw new ResponseStatusException(@@ -527,30 +724,6 @@ public class WorkflowSessionService {log.info("Deleted workflow session {}", sessionId);}- /**- * Deletes the original (presigned) file from storage after finalization. The original file is- * no longer needed once the signed document has been stored. Non-fatal: logs errors but does- * not fail finalization.- */- public void deleteOriginalFile(WorkflowSession session) {- if (session.getOriginalFile() == null) {- return;- }- try {- storageProvider.delete(session.getOriginalFile().getStorageKey());- StoredFile originalFile = session.getOriginalFile();- session.setOriginalFile(null);- workflowSessionRepository.save(session);- storedFileRepository.delete(originalFile);- log.info("Deleted original presigned file for session {}", session.getSessionId());- } catch (Exception e) {- log.error(- "Failed to delete original file for session {}: {}",- session.getSessionId(),- e.getMessage());- }- }-// ===== SIGN REQUEST METHODS (Participant View) =====/**@@ -581,6 +754,13 @@ public class WorkflowSessionService {? session.getDueDate().toString(): null);dto.setMyStatus(p.getStatus());+ dto.setFinalized(session.isFinalized());+ dto.setAccessExpired(p.isExpired());+ dto.setClosed(+ !session.isActive()+ || dto.isAccessExpired()+ || p.getStatus() == ParticipantStatus.DECLINED+ || p.getAccessRole() != ShareAccessRole.EDITOR);return dto;}).toList();@@ -593,11 +773,18 @@ public class WorkflowSessionService {* @param user The participant user* @return Sign request detail*/- @Transactional(readOnly = true)+ @Transactionalpublic stirling.software.proprietary.workflow.dto.SignRequestDetailDTO getSignRequestDetail(String sessionId, User user) {- WorkflowSession session = getSession(sessionId);+ WorkflowSession session = lockSession(sessionId);WorkflowParticipant participant = getParticipantForUser(session, user);+ requireUnexpiredAccess(participant);+ if (session.isActive()+ && (participant.getStatus() == ParticipantStatus.PENDING+ || participant.getStatus() == ParticipantStatus.NOTIFIED)) {+ participant.setStatus(ParticipantStatus.VIEWED);+ workflowParticipantRepository.save(participant);+ }stirling.software.proprietary.workflow.dto.SignRequestDetailDTO dto =new stirling.software.proprietary.workflow.dto.SignRequestDetailDTO();@@ -608,6 +795,14 @@ public class WorkflowSessionService {dto.setDueDate(session.getDueDate());dto.setCreatedAt(session.getCreatedAt().toString());dto.setMyStatus(participant.getStatus());+ dto.setFinalized(session.isFinalized());+ dto.setParticipants(+ stirling.software.proprietary.workflow.util.WorkflowMapper+ .toSigningParticipantPreviews(session, objectMapper));+ dto.setCanSign(+ session.isActive()+ && !participant.hasCompleted()+ && participant.getAccessRole() == ShareAccessRole.EDITOR);// Load signature appearance settings from workflow metadataMap<String, Object> metadata = session.getWorkflowMetadata();@@ -634,12 +829,6 @@ public class WorkflowSessionService {dto.setShowLogo(false);}- // Update status to VIEWED if it was NOTIFIED- if (participant.getStatus() == ParticipantStatus.NOTIFIED) {- participant.setStatus(ParticipantStatus.VIEWED);- workflowParticipantRepository.save(participant);- }-return dto;}@@ -656,7 +845,7 @@ public class WorkflowSessionService {@Transactional(readOnly = true)public byte[] getSignRequestDocument(String sessionId, User user) {WorkflowSession session = getSession(sessionId);- getParticipantForUser(session, user); // Verify participant access+ requireUnexpiredAccess(getParticipantForUser(session, user));// After finalization, serve the signed document instead of the originalStoredFile fileToServe =@@ -689,18 +878,16 @@ public class WorkflowSessionService {String sessionId,User user,stirling.software.proprietary.workflow.dto.SignDocumentRequest request) {- WorkflowSession session = getSession(sessionId);+ WorkflowSession session = lockSession(sessionId);WorkflowParticipant participant = getParticipantForUser(session, user);-- if (participant.getStatus() == ParticipantStatus.SIGNED) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST, "Document already signed by this user");- }-- if (participant.getStatus() == ParticipantStatus.DECLINED) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST, "Cannot sign after declining");- }+ ensureParticipantCanRespond(participant);+ ensureCertificateTypeAllowed(request.getCertType());+ ensureCertificateFilesPresent(+ request.getCertType(),+ request.getP12File(),+ request.getJksFile(),+ request.getPrivateKeyFile(),+ request.getCertFile());// Build metadata JSON containing certificate submission and wet signature data// Merge with existing metadata if present (preserves owner-configured appearance@@ -806,15 +993,16 @@ public class WorkflowSessionService {// 2. Parse wet signatures from JSON string if providedif (request.getWetSignaturesData() != null && !request.getWetSignaturesData().isBlank()) {+ if (request.getWetSignaturesData().length() > 5 * 1024 * 1024) {+ throw new ResponseStatusException(+ HttpStatus.BAD_REQUEST, "Wet signatures data exceeds maximum allowed size");+ }try {List<WetSignatureMetadata> wetSigs =objectMapper.readValue(request.getWetSignaturesData(),new TypeReference<List<WetSignatureMetadata>>() {});- if (wetSigs.size() > WetSignatureMetadata.MAX_SIGNATURES_PER_PARTICIPANT) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST, "Too many wet signatures submitted");- }+ validateWetSignatures(session, wetSigs);request.setWetSignatures(wetSigs);log.info("Parsed {} wet signatures from wetSignaturesData", wetSigs.size());} catch (JacksonException e) {@@ -878,13 +1066,9 @@ public class WorkflowSessionService {* @param user The participant user*/public void declineSignRequest(String sessionId, User user) {- WorkflowSession session = getSession(sessionId);+ WorkflowSession session = lockSession(sessionId);WorkflowParticipant participant = getParticipantForUser(session, user);-- if (participant.getStatus() == ParticipantStatus.SIGNED) {- throw new ResponseStatusException(- HttpStatus.BAD_REQUEST, "Cannot decline after signing");- }+ ensureParticipantCanRespond(participant);participant.setStatus(ParticipantStatus.DECLINED);workflowParticipantRepository.save(participant); // updatedAt is auto-updated@@ -915,7 +1099,7 @@ public class WorkflowSessionService {* Converts an uploaded PEM private key + certificate into a PKCS12 keystore (protected with the* supplied password) so finalization can sign via the standard PKCS12 path.*/- private byte[] buildPkcs12FromPem(+ public byte[] buildPkcs12FromPem(MultipartFile privateKeyFile, MultipartFile certFile, String password) {if (privateKeyFile == null|| privateKeyFile.isEmpty()diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/util/WorkflowMapper.java b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/util/WorkflowMapper.javaindex 8d61ae032c..7f216ed81b 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/workflow/util/WorkflowMapper.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/workflow/util/WorkflowMapper.java@@ -5,8 +5,10 @@ import java.util.List;import java.util.Map;import stirling.software.proprietary.workflow.dto.ParticipantResponse;+import stirling.software.proprietary.workflow.dto.SigningParticipantPreview;import stirling.software.proprietary.workflow.dto.WetSignatureMetadata;import stirling.software.proprietary.workflow.dto.WorkflowSessionResponse;+import stirling.software.proprietary.workflow.model.ParticipantStatus;import stirling.software.proprietary.workflow.model.WorkflowParticipant;import stirling.software.proprietary.workflow.model.WorkflowSession;@@ -18,6 +20,29 @@ import tools.jackson.databind.ObjectMapper;*/public class WorkflowMapper {+ /**+ * Returns progress without bearer tokens; finalized PDFs already contain the submitted marks.+ */+ public static List<SigningParticipantPreview> toSigningParticipantPreviews(+ WorkflowSession session, ObjectMapper objectMapper) {+ return session.getParticipants().stream()+ .map(+ p ->+ new SigningParticipantPreview(+ p.getId(),+ p.getName() != null+ ? p.getName()+ : p.getUser() != null+ ? p.getUser().getUsername()+ : "",+ p.getStatus(),+ !session.isFinalized()+ && p.getStatus() == ParticipantStatus.SIGNED+ ? extractWetSignatures(p, objectMapper)+ : List.of()))+ .toList();+ }+/** Converts a WorkflowSession entity to a response DTO. */public static WorkflowSessionResponse toResponse(WorkflowSession session) {return toResponse(session, null, true);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.javaindex acd0b8563b..fc226085d9 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ServerCertificateServiceTest.java@@ -2,9 +2,7 @@ package stirling.software.proprietary.service;import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;-import static org.mockito.Mockito.lenient;import static org.mockito.Mockito.mockStatic;-import static org.mockito.Mockito.when;import java.io.ByteArrayInputStream;import java.io.InputStream;@@ -17,27 +15,14 @@ import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;-import org.junit.jupiter.api.extension.ExtendWith;import org.junit.jupiter.api.io.TempDir;-import org.mockito.Mock;import org.mockito.MockedStatic;-import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.test.util.ReflectionTestUtils;import stirling.software.common.configuration.InstallationPathConfig;import stirling.software.common.model.ApplicationProperties;-import stirling.software.proprietary.security.configuration.ee.KeygenLicenseVerifier.License;-import stirling.software.proprietary.security.configuration.ee.LicenseKeyChecker;--/**- * Tests for {@link ServerCertificateService}. Uses a {@link TempDir} for the keystore location- * (mocked via {@link InstallationPathConfig}) and a mocked {@link LicenseKeyChecker} to drive the- * Pro/Enterprise license gating.- */-@ExtendWith(MockitoExtension.class)-class ServerCertificateServiceTest {- @Mock private LicenseKeyChecker licenseKeyChecker;+class ServerCertificateServiceTest {@TempDir Path tempDir;@@ -49,7 +34,7 @@ class ServerCertificateServiceTest {@BeforeEachvoid setUp() {- service = new ServerCertificateService(licenseKeyChecker, new ApplicationProperties());+ service = new ServerCertificateService(new ApplicationProperties());// default: feature enabled, validity 365, org Stirling-PDF, no regenerateReflectionTestUtils.setField(service, "enabled", true);ReflectionTestUtils.setField(service, "organizationName", "Stirling-PDF");@@ -64,49 +49,24 @@ class ServerCertificateServiceTest {return mocked;}- private void grantProLicense() {- lenient().when(licenseKeyChecker.premiumTier()).thenReturn(License.SERVER);- }-- private void denyLicense() {- lenient().when(licenseKeyChecker.premiumTier()).thenReturn(License.NORMAL);- }-- // -------------------------------------------------------------------------@Nested@DisplayName("isEnabled")class IsEnabled {@Test- @DisplayName("true when feature flag on and license is SERVER")- void enabledWithServerLicense() {- grantProLicense();- assertThat(service.isEnabled()).isTrue();- }-- @Test- @DisplayName("true when feature flag on and license is ENTERPRISE")- void enabledWithEnterpriseLicense() {- when(licenseKeyChecker.premiumTier()).thenReturn(License.ENTERPRISE);+ @DisplayName("true when the feature flag is on without a license")+ void enabledWithoutLicense() {assertThat(service.isEnabled()).isTrue();}@Test- @DisplayName("false when license is NORMAL")- void disabledWithNormalLicense() {- denyLicense();- assertThat(service.isEnabled()).isFalse();- }-- @Test- @DisplayName("false when feature flag off even with a valid license")+ @DisplayName("false when the feature flag is off")void disabledWhenFlagOff() {ReflectionTestUtils.setField(service, "enabled", false);assertThat(service.isEnabled()).isFalse();}}- // -------------------------------------------------------------------------@Nested@DisplayName("getServerCertificatePassword")class Password {@@ -118,7 +78,6 @@ class ServerCertificateServiceTest {}}- // -------------------------------------------------------------------------@Nested@DisplayName("hasServerCertificate")class HasCertificate {@@ -141,15 +100,13 @@ class ServerCertificateServiceTest {}}- // -------------------------------------------------------------------------@Nested@DisplayName("initializeServerCertificate")class Initialize {@Test- @DisplayName("generates a keystore when none exists and license granted")+ @DisplayName("generates a keystore without a license when none exists")void generatesWhenMissing() {- grantProLicense();try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {service.initializeServerCertificate();assertThat(Files.exists(tempDir.resolve(KEYSTORE_FILE))).isTrue();@@ -166,20 +123,9 @@ class ServerCertificateServiceTest {}}- @Test- @DisplayName("does nothing without a Pro/Enterprise license")- void noopWithoutLicense() {- denyLicense();- try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {- service.initializeServerCertificate();- assertThat(Files.exists(tempDir.resolve(KEYSTORE_FILE))).isFalse();- }- }-@Test@DisplayName("does not regenerate when keystore exists and regenerateOnStartup is false")void keepsExistingKeystore() throws Exception {- grantProLicense();try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {// First generationservice.initializeServerCertificate();@@ -194,7 +140,6 @@ class ServerCertificateServiceTest {@Test@DisplayName("regenerates when regenerateOnStartup is true")void regeneratesWhenFlagged() throws Exception {- grantProLicense();ReflectionTestUtils.setField(service, "regenerateOnStartup", true);try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {service.initializeServerCertificate();@@ -206,26 +151,25 @@ class ServerCertificateServiceTest {}}- // -------------------------------------------------------------------------@Nested@DisplayName("getServerKeyStore")class GetKeyStore {@Test- @DisplayName("throws when license is missing")- void throwsWithoutLicense() {- denyLicense();+ @DisplayName("blocks an existing certificate when the feature flag is off")+ void throwsWhenDisabled() {try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {+ service.initializeServerCertificate();+ ReflectionTestUtils.setField(service, "enabled", false);assertThatThrownBy(() -> service.getServerKeyStore()).isInstanceOf(IllegalStateException.class)- .hasMessageContaining("Pro or Enterprise license");+ .hasMessageContaining("not available");}}@Test@DisplayName("throws when no certificate is available")void throwsWhenNoCertificate() {- grantProLicense();try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {assertThatThrownBy(() -> service.getServerKeyStore()).isInstanceOf(IllegalStateException.class)@@ -236,7 +180,6 @@ class ServerCertificateServiceTest {@Test@DisplayName("loads the generated keystore with the default password")void loadsGeneratedKeystore() throws Exception {- grantProLicense();try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {service.initializeServerCertificate();KeyStore ks = service.getServerKeyStore();@@ -246,7 +189,6 @@ class ServerCertificateServiceTest {}}- // -------------------------------------------------------------------------@Nested@DisplayName("getServerCertificate / publicKey / info")class CertificateAccessors {@@ -254,7 +196,6 @@ class ServerCertificateServiceTest {@Test@DisplayName("returns the X509 certificate for the standard alias")void returnsCertificate() throws Exception {- grantProLicense();try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {service.initializeServerCertificate();X509Certificate cert = service.getServerCertificate();@@ -266,7 +207,6 @@ class ServerCertificateServiceTest {@Test@DisplayName("returns DER-encoded public key bytes")void returnsPublicKeyBytes() throws Exception {- grantProLicense();try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {service.initializeServerCertificate();byte[] der = service.getServerCertificatePublicKey();@@ -287,7 +227,6 @@ class ServerCertificateServiceTest {@Test@DisplayName("info reports subject/issuer/dates when a certificate exists")void infoPresentWhenAvailable() throws Exception {- grantProLicense();try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {service.initializeServerCertificate();var info = service.getServerCertificateInfo();@@ -300,7 +239,6 @@ class ServerCertificateServiceTest {}}- // -------------------------------------------------------------------------@Nested@DisplayName("uploadServerCertificate")class Upload {@@ -308,7 +246,6 @@ class ServerCertificateServiceTest {@Test@DisplayName("imports a private key entry from an uploaded P12 under the standard alias")void importsUploadedKeystore() throws Exception {- grantProLicense();byte[] uploaded = loadCert("valid-test.p12");try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {service.uploadServerCertificate(new ByteArrayInputStream(uploaded), "testpass");@@ -319,23 +256,9 @@ class ServerCertificateServiceTest {}}- @Test- @DisplayName("rejects upload without a Pro/Enterprise license")- void rejectsWithoutLicense() throws Exception {- denyLicense();- byte[] uploaded = loadCert("valid-test.p12");- try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {- InputStream in = new ByteArrayInputStream(uploaded);- assertThatThrownBy(() -> service.uploadServerCertificate(in, "testpass"))- .isInstanceOf(IllegalStateException.class)- .hasMessageContaining("Pro or Enterprise license");- }- }-@Test@DisplayName("throws on a wrong upload password")void rejectsWrongPassword() throws Exception {- grantProLicense();byte[] uploaded = loadCert("valid-test.p12");try (MockedStatic<InstallationPathConfig> ignored = mockConfigPath()) {InputStream in = new ByteArrayInputStream(uploaded);@@ -345,7 +268,6 @@ class ServerCertificateServiceTest {}}- // -------------------------------------------------------------------------@Nested@DisplayName("deleteServerCertificate")class Delete {@@ -370,7 +292,6 @@ class ServerCertificateServiceTest {}}- // -------------------------------------------------------------------------private static byte[] loadCert(String filename) throws Exception {try (InputStream in =ServerCertificateServiceTest.class.getResourceAsStream("/test-certs/" + filename)) {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/SigningSessionControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/SigningSessionControllerTest.javaindex 7fa3755371..e58876b454 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/SigningSessionControllerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/SigningSessionControllerTest.java@@ -35,7 +35,7 @@ import stirling.software.proprietary.workflow.dto.CertificateInfo;import stirling.software.proprietary.workflow.dto.WorkflowCreationRequest;import stirling.software.proprietary.workflow.model.WorkflowSession;import stirling.software.proprietary.workflow.service.CertificateSubmissionValidator;-import stirling.software.proprietary.workflow.service.SigningFinalizationService;+import stirling.software.proprietary.workflow.service.SigningSessionFinalizationService;import stirling.software.proprietary.workflow.service.WorkflowSessionService;// Direct handler invocations (no MockMvc) for SigningSessionController; previously 0% covered.@@ -45,7 +45,7 @@ class SigningSessionControllerTest {@Mock private WorkflowSessionService workflowSessionService;@Mock private UserService userService;- @Mock private SigningFinalizationService signingFinalizationService;+ @Mock private SigningSessionFinalizationService signingSessionFinalizationService;@Mock private CertificateSubmissionValidator certificateSubmissionValidator;private SigningSessionController controller;@@ -56,7 +56,7 @@ class SigningSessionControllerTest {new SigningSessionController(workflowSessionService,userService,- signingFinalizationService,+ signingSessionFinalizationService,certificateSubmissionValidator);}@@ -128,7 +128,7 @@ class SigningSessionControllerTest {void validateCertificate_unauthenticated() {assertThat(controller- .validateCertificate("P12", "pw", null, null, null)+ .validateCertificate("P12", "pw", null, null, null, null, null).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);}@@ -269,7 +269,7 @@ class SigningSessionControllerTest {}@Test- void serviceThrows_returnsForbidden() {+ void finalizedSession_preservesBadRequestAndReason() {User owner = user("alice");when(userService.findByUsernameIgnoreCase("alice")).thenReturn(Optional.of(owner));doThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "finalized"))@@ -278,7 +278,22 @@ class SigningSessionControllerTest {ResponseEntity<?> response = controller.deleteSession("s1", principal("alice"));+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);+ assertThat(response.getBody()).isEqualTo("finalized");+ }++ @Test+ void wrongOwner_preservesForbidden() {+ User owner = user("alice");+ when(userService.findByUsernameIgnoreCase("alice")).thenReturn(Optional.of(owner));+ doThrow(new ResponseStatusException(HttpStatus.FORBIDDEN, "Not authorized"))+ .when(workflowSessionService)+ .deleteSession("s1", owner);++ ResponseEntity<?> response = controller.deleteSession("s1", principal("alice"));+assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);+ assertThat(response.getBody()).isEqualTo("Not authorized");}}@@ -384,24 +399,22 @@ class SigningSessionControllerTest {User owner = user("alice");WorkflowSession session = ownedSession("s1", owner);when(userService.findByUsernameIgnoreCase("alice")).thenReturn(Optional.of(owner));- when(workflowSessionService.getSessionWithParticipantsForOwner("s1", owner))- .thenReturn(session);- when(workflowSessionService.getOriginalFile("s1")).thenReturn(new byte[] {1});- when(signingFinalizationService.finalizeDocument(eq(session), any()))- .thenReturn(new byte[] {2, 3});+ when(signingSessionFinalizationService.finalizeSession("s1", owner))+ .thenReturn(+ new SigningSessionFinalizationService.FinalizedDocument(+ new byte[] {2, 3}, "signed.pdf"));ResponseEntity<byte[]> response = controller.finalizeSession("s1", principal("alice"));assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);- verify(workflowSessionService).finalizeSession("s1", owner);- verify(workflowSessionService).deleteOriginalFile(session);+ assertThat(response.getBody()).containsExactly(2, 3);}@Testvoid serviceError_returns500() throws Exception {User owner = user("alice");when(userService.findByUsernameIgnoreCase("alice")).thenReturn(Optional.of(owner));- when(workflowSessionService.getSessionWithParticipantsForOwner("s1", owner))+ when(signingSessionFinalizationService.finalizeSession("s1", owner)).thenThrow(new RuntimeException("boom"));assertThat(controller.finalizeSession("s1", principal("alice")).getStatusCode())@@ -568,7 +581,7 @@ class SigningSessionControllerTest {}@Test- @DisplayName("declineSignRequest service error returns 403")+ @DisplayName("declineSignRequest preserves the service rejection status")void declineSignRequest_serviceError() {User user = user("alice");when(userService.findByUsernameIgnoreCase("alice")).thenReturn(Optional.of(user));@@ -576,8 +589,11 @@ class SigningSessionControllerTest {.when(workflowSessionService).declineSignRequest("s1", user);- assertThat(controller.declineSignRequest("s1", principal("alice")).getStatusCode())- .isEqualTo(HttpStatus.FORBIDDEN);+ org.assertj.core.api.Assertions.assertThatThrownBy(+ () -> controller.declineSignRequest("s1", principal("alice")))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.BAD_REQUEST);}// -------------------------------------------------------------------------@@ -611,7 +627,13 @@ class SigningSessionControllerTest {org.assertj.core.api.Assertions.assertThatThrownBy(() ->controller.validateCertificate(- "P12", "pw", null, null, principal("alice")))+ "P12",+ "pw",+ null,+ null,+ null,+ null,+ principal("alice"))).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);@@ -625,7 +647,8 @@ class SigningSessionControllerTest {.thenReturn(null);ResponseEntity<?> response =- controller.validateCertificate("SERVER", null, null, null, principal("alice"));+ controller.validateCertificate(+ "SERVER", null, null, null, null, null, principal("alice"));assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);}@@ -646,7 +669,7 @@ class SigningSessionControllerTest {ResponseEntity<stirling.software.proprietary.workflow.dto.CertificateValidationResponse>response =controller.validateCertificate(- "P12", "pw", p12, null, principal("alice"));+ "P12", "pw", p12, null, null, null, principal("alice"));assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);assertThat(response.getBody().valid()).isTrue();@@ -666,7 +689,7 @@ class SigningSessionControllerTest {ResponseEntity<stirling.software.proprietary.workflow.dto.CertificateValidationResponse>response =controller.validateCertificate(- "P12", "wrong", p12, null, principal("alice"));+ "P12", "wrong", p12, null, null, null, principal("alice"));assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);assertThat(response.getBody().valid()).isFalse();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.javaindex 0b1aedbc05..e84bb4f6e5 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/controller/WorkflowParticipantControllerMoreTest.java@@ -50,6 +50,10 @@ class WorkflowParticipantControllerMoreTest {@BeforeEachvoid setUp() {+ org.mockito.Mockito.lenient()+ .doCallRealMethod()+ .when(workflowSessionService)+ .ensureParticipantCanRespond(org.mockito.ArgumentMatchers.any());controller =new WorkflowParticipantController(workflowSessionService,@@ -93,7 +97,8 @@ class WorkflowParticipantControllerMoreTest {@Testvoid invalidToken_throwsForbidden() {- when(participantRepository.findByShareToken("bad")).thenReturn(Optional.empty());+ when(workflowSessionService.lockParticipantByToken("bad"))+ .thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN));assertThatThrownBy(() -> controller.getSessionByToken("bad")).isInstanceOf(ResponseStatusException.class)@@ -104,7 +109,7 @@ class WorkflowParticipantControllerMoreTest {@Testvoid pendingParticipant_marksViewedAndReturnsSession() {WorkflowParticipant p = participant(ParticipantStatus.PENDING);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);ResponseEntity<WorkflowSessionResponse> response = controller.getSessionByToken(TOKEN);@@ -116,7 +121,7 @@ class WorkflowParticipantControllerMoreTest {void expiredParticipant_throwsForbidden() {WorkflowParticipant p = participant(ParticipantStatus.PENDING);p.setExpiresAt(java.time.LocalDateTime.now().minusDays(1));- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);assertThatThrownBy(() -> controller.getSessionByToken(TOKEN)).isInstanceOf(ResponseStatusException.class)@@ -127,7 +132,7 @@ class WorkflowParticipantControllerMoreTest {@Testvoid signedParticipant_doesNotUpdateStatus() {WorkflowParticipant p = participant(ParticipantStatus.SIGNED);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);controller.getSessionByToken(TOKEN);@@ -193,7 +198,8 @@ class WorkflowParticipantControllerMoreTest {@Testvoid invalidToken_throwsForbidden() {- when(participantRepository.findByShareToken("bad")).thenReturn(Optional.empty());+ when(workflowSessionService.lockParticipantByToken("bad"))+ .thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN));assertThatThrownBy(() -> controller.submitSignature(request("bad"))).isInstanceOf(ResponseStatusException.class)@@ -202,32 +208,32 @@ class WorkflowParticipantControllerMoreTest {}@Test- void alreadyCompleted_throwsBadRequest() {+ void alreadyCompleted_throwsConflict() {WorkflowParticipant p = participant(ParticipantStatus.SIGNED);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);assertThatThrownBy(() -> controller.submitSignature(request(TOKEN))).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);}@Test- void inactiveSession_throwsBadRequest() {+ void inactiveSession_throwsConflict() {WorkflowParticipant p = participant(ParticipantStatus.PENDING);p.getWorkflowSession().setFinalized(true); // isActive() false- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);assertThatThrownBy(() -> controller.submitSignature(request(TOKEN))).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);}@Testvoid serverCert_savesParticipantSigned() {WorkflowParticipant p = participant(ParticipantStatus.PENDING);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);when(metadataEncryptionService.encrypt(org.mockito.ArgumentMatchers.any())).thenReturn("enc");when(participantRepository.save(org.mockito.ArgumentMatchers.any()))@@ -251,7 +257,8 @@ class WorkflowParticipantControllerMoreTest {@Testvoid invalidToken_throwsForbidden() {- when(participantRepository.findByShareToken("bad")).thenReturn(Optional.empty());+ when(workflowSessionService.lockParticipantByToken("bad"))+ .thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN));assertThatThrownBy(() -> controller.declineParticipation("bad", null)).isInstanceOf(ResponseStatusException.class)@@ -260,20 +267,20 @@ class WorkflowParticipantControllerMoreTest {}@Test- void alreadyCompleted_throwsBadRequest() {+ void alreadyCompleted_throwsConflict() {WorkflowParticipant p = participant(ParticipantStatus.DECLINED);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);assertThatThrownBy(() -> controller.declineParticipation(TOKEN, null)).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);}@Testvoid withReason_setsDeclinedAndNotifies() {WorkflowParticipant p = participant(ParticipantStatus.PENDING);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);when(participantRepository.save(org.mockito.ArgumentMatchers.any())).thenAnswer(i -> i.getArgument(0));@@ -288,7 +295,7 @@ class WorkflowParticipantControllerMoreTest {@Testvoid withoutReason_usesDefaultNotification() {WorkflowParticipant p = participant(ParticipantStatus.PENDING);- when(participantRepository.findByShareToken(TOKEN)).thenReturn(Optional.of(p));+ when(workflowSessionService.lockParticipantByToken(TOKEN)).thenReturn(p);when(participantRepository.save(org.mockito.ArgumentMatchers.any())).thenAnswer(i -> i.getArgument(0));diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadataTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadataTest.javaindex d0d209f9a3..ca3fc0284a 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadataTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/dto/WetSignatureMetadataTest.java@@ -9,7 +9,14 @@ import org.junit.jupiter.api.Test;class WetSignatureMetadataTest {private static WetSignatureMetadata canvas(double x, double y, double w, double h) {- return new WetSignatureMetadata("canvas", "data:image/png;base64,abc==", 0, x, y, w, h);+ return new WetSignatureMetadata(+ "canvas",+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1X8AAAAASUVORK5CYII=",+ 0,+ x,+ y,+ w,+ h);}// -------------------------------------------------------------------------@@ -25,7 +32,13 @@ class WetSignatureMetadataTest {void validate_image_withDataImagePrefix_passes() {WetSignatureMetadata sig =new WetSignatureMetadata(- "image", "data:image/jpeg;base64,xyz==", 0, 0.1, 0.1, 0.3, 0.3);+ "image",+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1X8AAAAASUVORK5CYII=",+ 0,+ 0.1,+ 0.1,+ 0.3,+ 0.3);assertThatCode(sig::validate).doesNotThrowAnyException();}@@ -40,10 +53,12 @@ class WetSignatureMetadataTest {}@Test- void validate_text_doesNotRequireDataImagePrefix() {+ void validate_text_requiresRasterizedImage() {WetSignatureMetadata sig =new WetSignatureMetadata("text", "John Doe", 0, 0.1, 0.1, 0.3, 0.2);- assertThatCode(sig::validate).doesNotThrowAnyException();+ assertThatThrownBy(sig::validate)+ .isInstanceOf(IllegalArgumentException.class)+ .hasMessageContaining("base64 image");}// -------------------------------------------------------------------------diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningFinalizationServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningFinalizationServiceMoreTest.javaindex 4d1c4b1e38..91995e4763 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningFinalizationServiceMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningFinalizationServiceMoreTest.java@@ -32,10 +32,13 @@ import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.web.server.ResponseStatusException;+import stirling.software.common.model.ApplicationProperties;import stirling.software.common.service.CustomPDFDocumentFactory;import stirling.software.common.service.PdfSigningService;import stirling.software.common.service.ServerCertificateServiceInterface;@@ -68,6 +71,98 @@ class SigningFinalizationServiceMoreTest {private SigningFinalizationService service;+ @ParameterizedTest+ @CsvSource({+ "P12,valid-test.p12,p12Keystore",+ "PFX,valid-test.p12,p12Keystore",+ "PKCS12,valid-test.p12,p12Keystore",+ "JKS,valid-test.jks,jksKeystore"+ })+ void decryptsPersistedKeystoreBeforeBindingBinaryFields(+ String certType, String fixture, String field) throws Exception {+ String fixturePassword = "JKS".equals(certType) ? "jkspass" : "testpass";+ ApplicationProperties props = new ApplicationProperties();+ props.getAutomaticallyGenerated().setKey("signing-regression-test-key");+ MetadataEncryptionService encryption = new MetadataEncryptionService(props);+ service =+ new SigningFinalizationService(+ participantRepository,+ pdfDocumentFactory,+ objectMapper,+ pdfSigningService,+ encryption,+ serverCertificateService,+ userServerCertificateService);+ var submission =+ Map.of(+ "certType",+ certType,+ "password",+ encryption.encrypt(fixturePassword),+ field,+ encryption.encryptBytes(loadCert(fixture)));+ WorkflowParticipant p = participant(1L, ParticipantStatus.SIGNED);+ p.setParticipantMetadata(+ objectMapper.readValue(+ objectMapper.writeValueAsString(+ Map.of("certificateSubmission", submission)),+ new tools.jackson.core.type.TypeReference<Map<String, Object>>() {}));+ when(participantRepository.findById(1L)).thenReturn(Optional.of(p));+ when(pdfSigningService.signWithKeystore(+ any(),+ any(),+ any(),+ anyBoolean(),+ any(),+ any(),+ any(),+ any(),+ anyBoolean()))+ .thenAnswer(+ inv -> {+ java.security.KeyStore keystore = inv.getArgument(1);+ char[] password = inv.getArgument(2);+ assertThat(new String(password)).isEqualTo(fixturePassword);+ assertThat(keystore.getKey(keystore.aliases().nextElement(), password))+ .isNotNull();+ return new byte[] {7, 8};+ });+ assertThat(service.finalizeDocument(sessionOf(p), singlePagePdf())).containsExactly(7, 8);+ }++ @Test+ void corruptEncryptedSubmissionFailsInsteadOfReturningUnsignedPdf() throws Exception {+ ApplicationProperties props = new ApplicationProperties();+ props.getAutomaticallyGenerated().setKey("signing-regression-test-key");+ MetadataEncryptionService encryption = new MetadataEncryptionService(props);+ service =+ new SigningFinalizationService(+ participantRepository,+ pdfDocumentFactory,+ objectMapper,+ pdfSigningService,+ encryption,+ serverCertificateService,+ userServerCertificateService);+ WorkflowParticipant p = participant(1L, ParticipantStatus.SIGNED);+ p.setParticipantMetadata(+ Map.of(+ "certificateSubmission",+ Map.of(+ "certType",+ "P12",+ "password",+ encryption.encrypt("testpass"),+ "p12Keystore",+ "enc:not-a-keystore")));+ when(participantRepository.findById(1L)).thenReturn(Optional.of(p));+ byte[] original = singlePagePdf();+ assertThatThrownBy(() -> service.finalizeDocument(sessionOf(p), original))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("Cannot read certificate submission");+ org.mockito.Mockito.verifyNoInteractions(pdfSigningService);+ }+@BeforeEachvoid setUp() {service =@@ -304,8 +399,8 @@ class SigningFinalizationServiceMoreTest {}@Test- @DisplayName("skips SIGNED participant with no certificate submission")- void skipsSignedParticipantWithoutSubmission() throws Exception {+ @DisplayName("rejects SIGNED participant with no certificate submission")+ void rejectsSignedParticipantWithoutSubmission() throws Exception {WorkflowParticipant p = participant(1L, ParticipantStatus.SIGNED);// metadata empty -> extractCertificateSubmission returns nullWorkflowSession session = sessionOf(p);@@ -313,9 +408,9 @@ class SigningFinalizationServiceMoreTest {when(participantRepository.findById(1L)).thenReturn(Optional.of(p));byte[] original = singlePagePdf();- byte[] result = service.finalizeDocument(session, original);-- assertThat(result).isEqualTo(original);+ assertThatThrownBy(() -> service.finalizeDocument(session, original))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("Missing certificate submission");verify(pdfSigningService, never()).signWithKeystore(any(),@@ -348,11 +443,29 @@ class SigningFinalizationServiceMoreTest {@DisplayName("finalizeDocument - wet signatures")class WetSignatures {+ void digitalSignaturePreservesWetSignatureOutput() throws Exception {+ when(pdfSigningService.signWithKeystore(+ any(),+ any(),+ any(),+ anyBoolean(),+ any(),+ any(),+ any(),+ any(),+ anyBoolean()))+ .thenAnswer(inv -> inv.getArgument(0));+ when(metadataEncryptionService.decrypt("testpass")).thenReturn("testpass");+ }+@Test@DisplayName("applies a wet signature overlay then returns the re-rendered PDF")void appliesWetSignature() throws Exception {+ digitalSignaturePreservesWetSignatureOutput();WorkflowParticipant p = participant(1L, ParticipantStatus.SIGNED);p.setParticipantMetadata(wetSignatureMetadata(pngDataUrl(), 0));+ p.getParticipantMetadata()+ .putAll(p12SubmissionMetadata(loadCert("valid-test.p12"), "testpass"));WorkflowSession session = sessionOf(p);byte[] original = singlePagePdf();@@ -363,26 +476,27 @@ class SigningFinalizationServiceMoreTest {byte[] result = service.finalizeDocument(session, original);- // wet-sig pass produced a non-empty PDF; signing was skipped (no cert submission)assertThat(result).isNotNull();assertThat(result.length).isGreaterThan(0);verify(pdfDocumentFactory, times(1)).load(any(InputStream.class));}@Test- @DisplayName("skips wet signature whose page index exceeds the document")- void skipsOutOfRangeWetSignaturePage() throws Exception {+ @DisplayName("rejects a wet signature whose page index exceeds the document")+ void rejectsOutOfRangeWetSignaturePage() throws Exception {WorkflowParticipant p = participant(1L, ParticipantStatus.SIGNED);p.setParticipantMetadata(wetSignatureMetadata(pngDataUrl(), 99));+ p.getParticipantMetadata()+ .putAll(p12SubmissionMetadata(loadCert("valid-test.p12"), "testpass"));WorkflowSession session = sessionOf(p);byte[] original = singlePagePdf();when(pdfDocumentFactory.load(any(InputStream.class))).thenReturn(loadDoc(original));when(participantRepository.findById(1L)).thenReturn(Optional.of(p));- byte[] result = service.finalizeDocument(session, original);-- assertThat(result).isNotNull();+ assertThatThrownBy(() -> service.finalizeDocument(session, original))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("page does not exist");verify(pdfDocumentFactory, times(1)).load(any(InputStream.class));}}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningPlacementTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningPlacementTest.javanew file mode 100644index 0000000000..dce2d31aa5--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningPlacementTest.java@@ -0,0 +1,72 @@+package stirling.software.proprietary.workflow.service;++import static org.assertj.core.api.Assertions.assertThat;++import java.awt.Color;+import java.awt.image.BufferedImage;+import java.io.ByteArrayOutputStream;+import java.util.Base64;++import javax.imageio.ImageIO;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.common.PDRectangle;+import org.apache.pdfbox.rendering.PDFRenderer;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.test.util.ReflectionTestUtils;++import stirling.software.proprietary.workflow.dto.WetSignatureMetadata;++class SigningPlacementTest {+ @ParameterizedTest+ @ValueSource(ints = {0, 90, 180, 270})+ void finalImageMatchesRotatedCroppedPreviewWithoutStretching(int rotation) throws Exception {+ var signature = new BufferedImage(120, 40, BufferedImage.TYPE_INT_RGB);+ var graphics = signature.createGraphics();+ graphics.setColor(Color.RED);+ graphics.fillRect(0, 0, 120, 40);+ graphics.dispose();+ var bytes = new ByteArrayOutputStream();+ ImageIO.write(signature, "png", bytes);+ var mark =+ new WetSignatureMetadata(+ "image",+ "data:image/png;base64,"+ + Base64.getEncoder().encodeToString(bytes.toByteArray()),+ 0,+ 0.1,+ 0.2,+ 0.3,+ 0.1);+ var service = new SigningFinalizationService(null, null, null, null, null, null, null);+ try (var document = new PDDocument()) {+ var page = new PDPage(new PDRectangle(600, 800));+ page.setCropBox(new PDRectangle(40, 50, 400, 600));+ page.setRotation(rotation);+ document.addPage(page);+ ReflectionTestUtils.invokeMethod(service, "applyWetSignatureToPage", document, mark);+ var rendered = new PDFRenderer(document).renderImage(0);+ int minX = rendered.getWidth(), minY = rendered.getHeight(), maxX = -1, maxY = -1;+ for (int y = 0; y < rendered.getHeight(); y++) {+ for (int x = 0; x < rendered.getWidth(); x++) {+ if ((rendered.getRGB(x, y) & 0xffffff) == 0xff0000) {+ minX = Math.min(x, minX);+ minY = Math.min(y, minY);+ maxX = Math.max(x, maxX);+ maxY = Math.max(y, maxY);+ }+ }+ }+ assertThat((minX + maxX + 1) / 2.0)+ .isCloseTo(+ rendered.getWidth() * 0.25, org.assertj.core.data.Offset.offset(1.0));+ assertThat((minY + maxY + 1) / 2.0)+ .isCloseTo(+ rendered.getHeight() * 0.25, org.assertj.core.data.Offset.offset(1.0));+ assertThat((maxX - minX + 1.0) / (maxY - minY + 1))+ .isCloseTo(3.0, org.assertj.core.data.Offset.offset(0.1));+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningSessionFinalizationDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningSessionFinalizationDbTest.javanew file mode 100644index 0000000000..279ef6df8d--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/SigningSessionFinalizationDbTest.java@@ -0,0 +1,291 @@+package stirling.software.proprietary.workflow.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.io.IOException;+import java.util.HashMap;+import java.util.Map;+import java.util.UUID;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.boot.SpringBootConfiguration;+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;+import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;+import org.springframework.boot.persistence.autoconfigure.EntityScan;+import org.springframework.context.annotation.Bean;+import org.springframework.context.annotation.Import;+import org.springframework.core.io.ByteArrayResource;+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;+import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;+import org.springframework.http.HttpStatus;+import org.springframework.test.context.bean.override.mockito.MockitoBean;+import org.springframework.transaction.PlatformTransactionManager;+import org.springframework.transaction.annotation.Propagation;+import org.springframework.transaction.annotation.Transactional;+import org.springframework.transaction.support.TransactionTemplate;+import org.springframework.web.server.ResponseStatusException;++import jakarta.persistence.EntityManager;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.LicenseServiceInterface;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.model.ShareAccessRole;+import stirling.software.proprietary.storage.model.StoredFile;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.storage.provider.StoredObject;+import stirling.software.proprietary.storage.repository.StoredFileRepository;+import stirling.software.proprietary.workflow.dto.SignDocumentRequest;+import stirling.software.proprietary.workflow.model.ParticipantStatus;+import stirling.software.proprietary.workflow.model.WorkflowParticipant;+import stirling.software.proprietary.workflow.model.WorkflowSession;+import stirling.software.proprietary.workflow.model.WorkflowType;+import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;+import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;++import tools.jackson.databind.ObjectMapper;++/**+ * Exercises commit, rollback and concurrent requests using real session rows and Spring+ * transactions.+ */+@DataJpaTest(+ showSql = false,+ properties =+ "spring.datasource.url=jdbc:h2:mem:signing-finalization;MODE=PostgreSQL;DB_CLOSE_DELAY=-1")+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)+@Transactional(propagation = Propagation.NOT_SUPPORTED)+class SigningSessionFinalizationDbTest {+ @Autowired private SigningSessionFinalizationService finalization;+ @Autowired private WorkflowSessionService workflows;+ @Autowired private WorkflowSessionRepository sessions;+ @Autowired private EntityManager entityManager;+ @Autowired private PlatformTransactionManager transactionManager;+ @MockitoBean private SigningFinalizationService signer;+ @MockitoBean private StorageProvider storage;+ @MockitoBean private UserRepository users;+ @MockitoBean private MetadataEncryptionService encryption;+ @MockitoBean private CertificateSubmissionValidator validator;+ @MockitoBean private LicenseServiceInterface license;++ @MockitoBean+ private stirling.software.common.service.CustomPDFDocumentFactory pdfDocumentFactory;++ private TransactionTemplate transactions;+ private User owner;+ private User pendingSigner;+ private String sessionId;+ private String outputKey;++ @BeforeEach+ void createSession() throws Exception {+ transactions = new TransactionTemplate(transactionManager);+ sessionId = UUID.randomUUID().toString();+ outputKey = "output-" + sessionId;+ transactions.executeWithoutResult(+ status -> {+ owner = new User();+ owner.setUsername("owner-" + sessionId);+ entityManager.persist(owner);+ pendingSigner = new User();+ pendingSigner.setUsername("pending-" + sessionId);+ entityManager.persist(pendingSigner);+ StoredFile original = new StoredFile();+ original.setOwner(owner);+ original.setStorageKey("original-" + sessionId);+ original.setOriginalFilename("agreement.pdf");+ original.setContentType("application/pdf");+ original.setSizeBytes(3L);+ entityManager.persist(original);+ WorkflowSession session = new WorkflowSession();+ session.setSessionId(sessionId);+ session.setOwner(owner);+ session.setOriginalFile(original);+ session.setWorkflowType(WorkflowType.SIGNING);+ session.setDocumentName("agreement.pdf");+ WorkflowParticipant signed = participant(owner, ParticipantStatus.SIGNED);+ signed.setParticipantMetadata(+ new HashMap<>(+ Map.of(+ "certificateSubmission",+ Map.of("certType", "P12", "password", "encrypted"))));+ session.addParticipant(signed);+ session.addParticipant(participant(pendingSigner, ParticipantStatus.PENDING));+ entityManager.persist(session);+ });+ when(storage.load("original-" + sessionId))+ .thenReturn(new ByteArrayResource(new byte[] {1}));+ when(storage.store(any(), any()))+ .thenReturn(+ StoredObject.builder()+ .storageKey(outputKey)+ .originalFilename("agreement_shared_signed.pdf")+ .contentType("application/pdf")+ .sizeBytes(2)+ .build());+ when(signer.finalizeDocument(any(), any())).thenReturn(new byte[] {2, 3});+ }++ private WorkflowParticipant participant(User user, ParticipantStatus status) {+ WorkflowParticipant participant = new WorkflowParticipant();+ participant.setUser(user);+ participant.setStatus(status);+ participant.setAccessRole(ShareAccessRole.EDITOR);+ participant.setShareToken(UUID.randomUUID().toString());+ return participant;+ }++ @Test+ void successfulFinalizationRetainsOriginalAndSignedDocumentAfterCommit() throws Exception {+ when(storage.load(outputKey)).thenReturn(new ByteArrayResource(new byte[] {2, 3}));++ assertThat(finalization.finalizeSession(sessionId, owner).bytes()).containsExactly(2, 3);++ transactions.executeWithoutResult(+ status -> {+ WorkflowSession session = sessions.findBySessionId(sessionId).orElseThrow();+ assertThat(session.isFinalized()).isTrue();+ assertThat(session.getOriginalFile().getStorageKey())+ .isEqualTo("original-" + sessionId);+ assertThat(session.getProcessedFile().getStorageKey()).isEqualTo(outputKey);+ });+ assertThat(workflows.getOriginalFile(sessionId)).containsExactly(1);+ assertThat(workflows.getProcessedFile(sessionId, owner)).containsExactly(2, 3);+ verify(storage, never()).delete("original-" + sessionId);+ }++ @Test+ void cleanupFailureRollsBackPublicationAndDeletesOutputBlob() throws Exception {+ doThrow(new IllegalStateException("cleanup failed"))+ .when(signer)+ .clearSensitiveMetadata(any());+ assertThatThrownBy(() -> finalization.finalizeSession(sessionId, owner))+ .hasMessageContaining("cleanup failed");+ transactions.executeWithoutResult(+ status -> {+ WorkflowSession session = sessions.findBySessionId(sessionId).orElseThrow();+ assertThat(session.isFinalized()).isFalse();+ assertThat(session.getProcessedFile()).isNull();+ assertThat(session.getOriginalFile().getStorageKey())+ .isEqualTo("original-" + sessionId);+ assertThat(session.getParticipants().getFirst().getParticipantMetadata())+ .containsKey("certificateSubmission");+ });+ verify(storage).delete(outputKey);+ }++ @Test+ void checkedStorageFailureLeavesSessionOpen() throws Exception {+ when(storage.store(any(), any())).thenThrow(new IOException("storage unavailable"));+ assertThatThrownBy(() -> finalization.finalizeSession(sessionId, owner))+ .isInstanceOf(IOException.class);+ assertThat(sessions.findBySessionId(sessionId).orElseThrow().isFinalized()).isFalse();+ }++ @Test+ void zeroSignaturesCannotBeFinalized() {+ transactions.executeWithoutResult(+ status ->+ sessions.findBySessionId(sessionId)+ .orElseThrow()+ .getParticipants()+ .forEach(p -> p.setStatus(ParticipantStatus.PENDING)));+ assertThatThrownBy(() -> finalization.finalizeSession(sessionId, owner))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.CONFLICT);+ }++ @Test+ void concurrentSignAndSecondFinalizationWaitThenRejectClosedSession() throws Exception {+ CountDownLatch signing = new CountDownLatch(1);+ CountDownLatch finish = new CountDownLatch(1);+ when(signer.finalizeDocument(any(), any()))+ .thenAnswer(+ inv -> {+ signing.countDown();+ if (!finish.await(5, TimeUnit.SECONDS))+ throw new IllegalStateException("test finalization timed out");+ return new byte[] {2, 3};+ });+ try (var executor = Executors.newFixedThreadPool(3)) {+ var first = executor.submit(() -> finalization.finalizeSession(sessionId, owner));+ assertThat(signing.await(5, TimeUnit.SECONDS)).isTrue();+ CountDownLatch submitted = new CountDownLatch(2);+ var lateSign =+ executor.submit(+ () -> {+ submitted.countDown();+ workflows.signDocument(+ sessionId, pendingSigner, new SignDocumentRequest());+ return null;+ });+ var second =+ executor.submit(+ () -> {+ submitted.countDown();+ return finalization.finalizeSession(sessionId, owner);+ });+ try {+ assertThat(submitted.await(5, TimeUnit.SECONDS)).isTrue();+ assertThatThrownBy(() -> lateSign.get(150, TimeUnit.MILLISECONDS))+ .isInstanceOf(TimeoutException.class);+ assertThatThrownBy(() -> second.get(150, TimeUnit.MILLISECONDS))+ .isInstanceOf(TimeoutException.class);+ } finally {+ finish.countDown();+ }+ assertThat(first.get(5, TimeUnit.SECONDS).bytes()).containsExactly(2, 3);+ assertThatThrownBy(() -> lateSign.get(5, TimeUnit.SECONDS))+ .hasCauseInstanceOf(ResponseStatusException.class);+ assertThatThrownBy(() -> second.get(5, TimeUnit.SECONDS))+ .hasCauseInstanceOf(ResponseStatusException.class);+ } finally {+ finish.countDown();+ }+ transactions.executeWithoutResult(+ status -> {+ WorkflowSession session = sessions.findBySessionId(sessionId).orElseThrow();+ assertThat(session.isFinalized()).isTrue();+ assertThat(session.getParticipants())+ .filteredOn(p -> p.getUser().equals(pendingSigner))+ .extracting(WorkflowParticipant::getStatus)+ .containsExactly(ParticipantStatus.PENDING);+ });+ }++ @SpringBootConfiguration+ @EntityScan("stirling.software.proprietary")+ @EnableJpaRepositories(basePackageClasses = WorkflowParticipantRepository.class)+ @Import({WorkflowSessionService.class, SigningSessionFinalizationService.class})+ static class TestApp {+ @Bean+ StoredFileRepository storedFiles(EntityManager entityManager) {+ return new JpaRepositoryFactory(entityManager)+ .getRepository(StoredFileRepository.class);+ }++ @Bean+ ApplicationProperties properties() {+ return new ApplicationProperties();+ }++ @Bean+ ObjectMapper objectMapper() {+ return new ObjectMapper();+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.javaindex a997a4a5d0..4c2ea45987 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceMoreTest.java@@ -94,6 +94,7 @@ class WorkflowSessionServiceMoreTest {private WorkflowParticipant participant(User user, ParticipantStatus status) {WorkflowParticipant p = new WorkflowParticipant();p.setUser(user);+ p.setAccessRole(stirling.software.proprietary.storage.model.ShareAccessRole.EDITOR);p.setStatus(status);return p;}@@ -159,6 +160,8 @@ class WorkflowSessionServiceMoreTest {User owner = user("alice", 1L);WorkflowSession s = session("s1", owner);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));assertThat(service.getSession("s1")).isSameAs(s);}@@ -222,11 +225,13 @@ class WorkflowSessionServiceMoreTest {class AddParticipants {@Test- void inactiveSession_throwsBadRequest() {+ void inactiveSession_throwsConflict() {User owner = user("alice", 1L);WorkflowSession s = session("s1", owner);s.setFinalized(true); // makes isActive() falsewhen(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));ParticipantRequest pr = new ParticipantRequest();pr.setEmail("[email protected]");@@ -234,7 +239,7 @@ class WorkflowSessionServiceMoreTest {assertThatThrownBy(() -> service.addParticipants("s1", List.of(pr), owner)).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);}@Test@@ -243,6 +248,8 @@ class WorkflowSessionServiceMoreTest {WorkflowSession s = session("s1", owner);s.setStatus(WorkflowStatus.IN_PROGRESS);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));when(workflowParticipantRepository.save(any())).thenAnswer(i -> i.getArgument(0));ParticipantRequest pr = new ParticipantRequest();@@ -262,6 +269,8 @@ class WorkflowSessionServiceMoreTest {WorkflowSession s = session("s1", owner);s.setStatus(WorkflowStatus.IN_PROGRESS);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));ParticipantRequest pr = new ParticipantRequest(); // neither userId nor email@@ -277,6 +286,8 @@ class WorkflowSessionServiceMoreTest {WorkflowSession s = session("s1", owner);s.setStatus(WorkflowStatus.IN_PROGRESS);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));when(userRepository.findById(99L)).thenReturn(Optional.empty());ParticipantRequest pr = new ParticipantRequest();@@ -302,6 +313,8 @@ class WorkflowSessionServiceMoreTest {User owner = user("alice", 1L);WorkflowSession s = session("s1", owner);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));when(workflowParticipantRepository.findById(5L)).thenReturn(Optional.empty());assertThatThrownBy(() -> service.removeParticipant("s1", 5L, owner))@@ -316,6 +329,8 @@ class WorkflowSessionServiceMoreTest {WorkflowSession s = session("s1", owner);WorkflowSession other = session("s2", owner);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));WorkflowParticipant p = participant(user("p", 9L), ParticipantStatus.PENDING);p.setWorkflowSession(other);when(workflowParticipantRepository.findById(5L)).thenReturn(Optional.of(p));@@ -333,6 +348,8 @@ class WorkflowSessionServiceMoreTest {WorkflowParticipant p = participant(user("p", 9L), ParticipantStatus.PENDING);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));when(workflowParticipantRepository.findById(5L)).thenReturn(Optional.of(p));service.removeParticipant("s1", 5L, owner);@@ -403,16 +420,18 @@ class WorkflowSessionServiceMoreTest {class FinalizeSession {@Test- void alreadyFinalized_throwsBadRequest() {+ void alreadyFinalized_throwsConflict() {User owner = user("alice", 1L);WorkflowSession s = session("s1", owner);s.setFinalized(true);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));assertThatThrownBy(() -> service.finalizeSession("s1", owner)).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);}@Test@@ -420,6 +439,8 @@ class WorkflowSessionServiceMoreTest {User owner = user("alice", 1L);WorkflowSession s = session("s1", owner);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));service.finalizeSession("s1", owner);@@ -442,6 +463,8 @@ class WorkflowSessionServiceMoreTest {User owner = user("alice", 1L);WorkflowSession s = session("s1", owner);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));assertThatThrownBy(() -> service.getProcessedFile("s1", owner)).isInstanceOf(ResponseStatusException.class)@@ -457,6 +480,8 @@ class WorkflowSessionServiceMoreTest {pf.setStorageKey("proc-key");s.setProcessedFile(pf);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));Resource resource = new ByteArrayResource(new byte[] {1, 2, 3});when(storageProvider.load("proc-key")).thenReturn(resource);@@ -468,6 +493,8 @@ class WorkflowSessionServiceMoreTest {User owner = user("alice", 1L);WorkflowSession s = session("s1", owner);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));assertThatThrownBy(() -> service.getOriginalFile("s1")).isInstanceOf(ResponseStatusException.class)@@ -483,6 +510,8 @@ class WorkflowSessionServiceMoreTest {of.setStorageKey("orig-key");s.setOriginalFile(of);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));Resource resource = new ByteArrayResource(new byte[] {7});when(storageProvider.load("orig-key")).thenReturn(resource);@@ -515,6 +544,66 @@ class WorkflowSessionServiceMoreTest {assertThat(result.get(0).getSessionId()).isEqualTo("s1");assertThat(result.get(0).getOwnerUsername()).isEqualTo("owner");assertThat(result.get(0).getMyStatus()).isEqualTo(ParticipantStatus.NOTIFIED);+ assertThat(result.get(0).isAccessExpired()).isFalse();+ assertThat(result.get(0).isClosed()).isFalse();+ }++ @Test+ void listSignRequests_reportsAccessExpiryIndependentlyOfDueDateAndStatus() {+ User user = user("alice", 1L);+ WorkflowSession s = session("s1", user("owner", 2L));+ s.setCreatedAt(LocalDateTime.now().minusDays(10));+ s.setDueDate(LocalDateTime.now().minusDays(2).toString());+ WorkflowParticipant expired = participant(user, ParticipantStatus.NOTIFIED);+ expired.setExpiresAt(LocalDateTime.now().minusDays(1));+ WorkflowParticipant available = participant(user, ParticipantStatus.PENDING);+ available.setExpiresAt(LocalDateTime.now().plusDays(1));+ WorkflowParticipant noExpiry = participant(user, ParticipantStatus.VIEWED);+ WorkflowParticipant submitted = participant(user, ParticipantStatus.SIGNED);+ submitted.setExpiresAt(LocalDateTime.now().minusDays(1));+ List<WorkflowParticipant> participants =+ List.of(expired, available, noExpiry, submitted);+ participants.forEach(p -> p.setWorkflowSession(s));+ when(workflowParticipantRepository.findByUserOrderByLastUpdatedDesc(user))+ .thenReturn(participants);++ List<SignRequestSummaryDTO> result = service.listSignRequests(user);++ assertThat(result)+ .extracting(SignRequestSummaryDTO::isAccessExpired)+ .containsExactly(true, false, false, true);+ assertThat(result)+ .extracting(SignRequestSummaryDTO::isClosed)+ .containsExactly(true, false, false, true);+ assertThat(s.isFinalized()).isFalse();+ }++ @Test+ void listSignRequests_closesNonSigningRolesAndInactiveWorkflowsButKeepsSubmissionsActive() {+ User user = user("alice", 1L);+ WorkflowSession active = session("active", user("owner", 2L));+ active.setCreatedAt(LocalDateTime.now());+ WorkflowParticipant viewer = participant(user, ParticipantStatus.PENDING);+ viewer.setAccessRole(+ stirling.software.proprietary.storage.model.ShareAccessRole.VIEWER);+ WorkflowParticipant commenter = participant(user, ParticipantStatus.VIEWED);+ commenter.setAccessRole(+ stirling.software.proprietary.storage.model.ShareAccessRole.COMMENTER);+ WorkflowParticipant submitted = participant(user, ParticipantStatus.SIGNED);+ WorkflowParticipant declined = participant(user, ParticipantStatus.DECLINED);+ List<WorkflowParticipant> participants =+ List.of(viewer, commenter, submitted, declined);+ participants.forEach(p -> p.setWorkflowSession(active));+ when(workflowParticipantRepository.findByUserOrderByLastUpdatedDesc(user))+ .thenReturn(participants);++ assertThat(service.listSignRequests(user))+ .extracting(SignRequestSummaryDTO::isClosed)+ .containsExactly(true, true, false, true);+ active.setStatus(WorkflowStatus.CANCELLED);+ assertThat(service.listSignRequests(user)).allMatch(SignRequestSummaryDTO::isClosed);+ active.setStatus(WorkflowStatus.COMPLETED);+ assertThat(service.listSignRequests(user)).allMatch(SignRequestSummaryDTO::isClosed);}@Test@@ -526,10 +615,12 @@ class WorkflowSessionServiceMoreTest {WorkflowParticipant p = participant(user, ParticipantStatus.NOTIFIED);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));SignRequestDetailDTO dto = service.getSignRequestDetail("s1", user);- assertThat(dto.getMyStatus()).isEqualTo(ParticipantStatus.NOTIFIED);+ assertThat(dto.getMyStatus()).isEqualTo(ParticipantStatus.VIEWED);assertThat(p.getStatus()).isEqualTo(ParticipantStatus.VIEWED);verify(workflowParticipantRepository).save(p);}@@ -548,6 +639,8 @@ class WorkflowSessionServiceMoreTest {WorkflowParticipant p = participant(user, ParticipantStatus.VIEWED);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));SignRequestDetailDTO dto = service.getSignRequestDetail("s1", user);@@ -562,6 +655,8 @@ class WorkflowSessionServiceMoreTest {User owner = user("owner", 2L);WorkflowSession s = session("s1", owner);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));assertThatThrownBy(() -> service.getSignRequestDetail("s1", intruder)).isInstanceOf(ResponseStatusException.class)@@ -580,6 +675,8 @@ class WorkflowSessionServiceMoreTest {WorkflowParticipant p = participant(user, ParticipantStatus.PENDING);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));when(storageProvider.load("orig-key")).thenReturn(new ByteArrayResource(new byte[] {5}));@@ -594,6 +691,8 @@ class WorkflowSessionServiceMoreTest {WorkflowParticipant p = participant(user, ParticipantStatus.PENDING);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));assertThatThrownBy(() -> service.getSignRequestDocument("s1", user)).isInstanceOf(ResponseStatusException.class)@@ -611,18 +710,20 @@ class WorkflowSessionServiceMoreTest {class DeclineSignRequest {@Test- void alreadySigned_throwsBadRequest() {+ void alreadySigned_throwsConflict() {User user = user("alice", 1L);User owner = user("owner", 2L);WorkflowSession s = session("s1", owner);WorkflowParticipant p = participant(user, ParticipantStatus.SIGNED);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));assertThatThrownBy(() -> service.declineSignRequest("s1", user)).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);verify(workflowParticipantRepository, never()).save(any());}@@ -635,6 +736,8 @@ class WorkflowSessionServiceMoreTest {WorkflowParticipant p = participant(user, ParticipantStatus.PENDING);s.addParticipant(p);when(workflowSessionRepository.findBySessionId("s1")).thenReturn(Optional.of(s));+ when(workflowSessionRepository.findBySessionIdForUpdate("s1"))+ .thenReturn(Optional.of(s));service.declineSignRequest("s1", user);@@ -642,53 +745,4 @@ class WorkflowSessionServiceMoreTest {verify(workflowParticipantRepository).save(p);}}-- // -------------------------------------------------------------------------- // deleteOriginalFile- // --------------------------------------------------------------------------- @Nested- @DisplayName("deleteOriginalFile")- class DeleteOriginalFile {-- @Test- void noOriginalFile_noOp() {- WorkflowSession s = session("s1", user("alice", 1L));-- service.deleteOriginalFile(s);-- verify(storedFileRepository, never()).delete(any());- }-- @Test- void withOriginalFile_deletesAndNullsReference() throws IOException {- WorkflowSession s = session("s1", user("alice", 1L));- StoredFile of = new StoredFile();- of.setStorageKey("orig-key");- s.setOriginalFile(of);-- service.deleteOriginalFile(s);-- assertThat(s.getOriginalFile()).isNull();- verify(storageProvider).delete("orig-key");- verify(storedFileRepository).delete(of);- verify(workflowSessionRepository).save(s);- }-- @Test- void storageError_nonFatal_keepsReference() throws IOException {- WorkflowSession s = session("s1", user("alice", 1L));- StoredFile of = new StoredFile();- of.setStorageKey("orig-key");- s.setOriginalFile(of);- org.mockito.Mockito.doThrow(new RuntimeException("boom"))- .when(storageProvider)- .delete("orig-key");-- service.deleteOriginalFile(s);-- // delete threw before nulling — reference still present, no DB delete- verify(storedFileRepository, never()).delete(any());- }- }}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.javaindex 184926574e..faac8a3780 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionServiceTest.java@@ -12,6 +12,7 @@ import java.util.List;import java.util.Map;import java.util.Optional;+import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.ArgumentCaptor;@@ -26,9 +27,11 @@ import org.springframework.web.server.ResponseStatusException;import stirling.software.common.model.ApplicationProperties;import stirling.software.common.model.ApplicationProperties.Storage;import stirling.software.common.model.ApplicationProperties.Storage.Signing;+import stirling.software.common.service.LicenseServiceInterface;import stirling.software.proprietary.security.database.repository.UserRepository;import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.storage.crypto.StorageKeyRevokedException;+import stirling.software.proprietary.storage.model.ShareAccessRole;import stirling.software.proprietary.storage.model.StoredFile;import stirling.software.proprietary.storage.provider.StorageProvider;import stirling.software.proprietary.storage.provider.StoredObject;@@ -57,8 +60,98 @@ class WorkflowSessionServiceTest {@Mock private ApplicationProperties applicationProperties;@Mock private MetadataEncryptionService metadataEncryptionService;+ @Mock private LicenseServiceInterface licenseService;+ @Mock private stirling.software.common.service.CustomPDFDocumentFactory pdfDocumentFactory;@InjectMocks private WorkflowSessionService service;+ @org.junit.jupiter.params.ParameterizedTest+ @org.junit.jupiter.params.provider.EnumSource(+ value = ShareAccessRole.class,+ names = {"VIEWER", "COMMENTER"})+ void readOnlyParticipantsCannotSignOrDecline(ShareAccessRole role) {+ User user = user("reader");+ WorkflowParticipant participant = pendingParticipant(user);+ participant.setAccessRole(role);+ sessionWithParticipant("restricted", participant);+ assertThatThrownBy(+ () -> service.signDocument("restricted", user, new SignDocumentRequest()))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("signing permission");+ assertThatThrownBy(() -> service.declineSignRequest("restricted", user))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("signing permission");+ verify(workflowParticipantRepository, never()).save(any());+ }++ @Test+ void expiredAccessRejectsSigningDecliningAndDocumentAccess() {+ User user = user("expired");+ WorkflowParticipant participant = pendingParticipant(user);+ participant.setExpiresAt(java.time.LocalDateTime.now().minusSeconds(1));+ sessionWithParticipant("expired", participant);+ assertThatThrownBy(() -> service.getSignRequestDetail("expired", user))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("access expired");+ assertThatThrownBy(() -> service.signDocument("expired", user, new SignDocumentRequest()))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("access expired");+ assertThatThrownBy(() -> service.declineSignRequest("expired", user))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("access expired");+ assertThatThrownBy(() -> service.getSignRequestDocument("expired", user))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("access expired");+ verify(workflowParticipantRepository, never()).save(any());+ }++ @Test+ void unlicensedPersonalSubmissionIsRejectedBeforeStoringSecrets() {+ when(licenseService.isRunningProOrHigher()).thenReturn(false);+ User user = user("unlicensed");+ sessionWithParticipant("unlicensed", pendingParticipant(user));+ SignDocumentRequest request = new SignDocumentRequest();+ request.setCertType("USER_CERT");+ assertThatThrownBy(() -> service.signDocument("unlicensed", user, request))+ .isInstanceOf(ResponseStatusException.class)+ .extracting(e -> ((ResponseStatusException) e).getStatusCode())+ .isEqualTo(HttpStatus.FORBIDDEN);+ verifyNoInteractions(metadataEncryptionService);+ verify(workflowParticipantRepository, never()).save(any());+ }++ @Test+ void serverCertificateSubmissionDoesNotRequireALicense() {+ lenient().when(licenseService.isRunningProOrHigher()).thenReturn(false);+ User user = user("free-server");+ WorkflowParticipant participant = pendingParticipant(user);+ sessionWithParticipant("free-server", participant);+ SignDocumentRequest request = new SignDocumentRequest();+ request.setCertType("SERVER");++ service.signDocument("free-server", user, request);++ assertThat(participant.getStatus()).isEqualTo(ParticipantStatus.SIGNED);+ verifyNoInteractions(licenseService);+ verify(workflowParticipantRepository).save(participant);+ }++ @Test+ void advisoryDueDateDoesNotPreventSigning() {+ User user = user("late");+ WorkflowParticipant participant = pendingParticipant(user);+ WorkflowSession session = sessionWithParticipant("late", participant);+ session.setDueDate("2000-01-01");+ SignDocumentRequest request = new SignDocumentRequest();+ request.setCertType("SERVER");+ service.signDocument("late", user, request);+ assertThat(participant.getStatus()).isEqualTo(ParticipantStatus.SIGNED);+ }++ @BeforeEach+ void licensedInstallation() {+ lenient().when(licenseService.isRunningProOrHigher()).thenReturn(true);+ }+// -------------------------------------------------------------------------// Helpers// -------------------------------------------------------------------------@@ -70,13 +163,20 @@ class WorkflowSessionServiceTest {List<WorkflowParticipant> participants = new ArrayList<>();participants.add(participant);session.setParticipants(participants);- when(workflowSessionRepository.findBySessionId(sessionId)).thenReturn(Optional.of(session));+ participant.setWorkflowSession(session);+ lenient()+ .when(workflowSessionRepository.findBySessionIdForUpdate(sessionId))+ .thenReturn(Optional.of(session));+ lenient()+ .when(workflowSessionRepository.findBySessionId(sessionId))+ .thenReturn(Optional.of(session));return session;}private WorkflowParticipant pendingParticipant(User user) {WorkflowParticipant p = new WorkflowParticipant();p.setUser(user);+ p.setAccessRole(ShareAccessRole.EDITOR);p.setStatus(ParticipantStatus.PENDING);return p;}@@ -169,7 +269,9 @@ class WorkflowSessionServiceTest {objectMapper,applicationProperties,realEncryption,- validator);+ validator,+ licenseService,+ pdfDocumentFactory);User user = user("dave");WorkflowParticipant participant = pendingParticipant(user);@@ -249,7 +351,7 @@ class WorkflowSessionServiceTest {// -------------------------------------------------------------------------@Test- void signDocument_throwsBadRequest_whenAlreadySigned() {+ void signDocument_throwsConflict_whenAlreadySigned() {User user = user("dave");WorkflowParticipant participant = pendingParticipant(user);participant.setStatus(ParticipantStatus.SIGNED);@@ -261,13 +363,13 @@ class WorkflowSessionServiceTest {assertThatThrownBy(() -> service.signDocument("s4", user, req)).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);verify(workflowParticipantRepository, never()).save(any());}@Test- void signDocument_throwsBadRequest_whenAlreadyDeclined() {+ void signDocument_throwsConflict_whenAlreadyDeclined() {User user = user("eve");WorkflowParticipant participant = pendingParticipant(user);participant.setStatus(ParticipantStatus.DECLINED);@@ -279,7 +381,7 @@ class WorkflowSessionServiceTest {assertThatThrownBy(() -> service.signDocument("s5", user, req)).isInstanceOf(ResponseStatusException.class).extracting(e -> ((ResponseStatusException) e).getStatusCode())- .isEqualTo(HttpStatus.BAD_REQUEST);+ .isEqualTo(HttpStatus.CONFLICT);verify(workflowParticipantRepository, never()).save(any());}@@ -361,6 +463,15 @@ class WorkflowSessionServiceTest {new MockMultipartFile("file", "doc.pdf", "application/pdf", new byte[] {1, 2});WorkflowCreationRequest request = new WorkflowCreationRequest();request.setWorkflowType(WorkflowType.SIGNING);+ request.setParticipantEmails(List.of("[email protected]"));+ when(pdfDocumentFactory.load(+ any(org.springframework.web.multipart.MultipartFile.class), eq(true)))+ .thenAnswer(+ invocation -> {+ var document = new org.apache.pdfbox.pdmodel.PDDocument();+ document.addPage(new org.apache.pdfbox.pdmodel.PDPage());+ return document;+ });request.setDocumentName("My Doc");StoredObject storedObject =@@ -396,6 +507,15 @@ class WorkflowSessionServiceTest {new MockMultipartFile("file", "original.pdf", "application/pdf", new byte[] {1});WorkflowCreationRequest request = new WorkflowCreationRequest();request.setWorkflowType(WorkflowType.SIGNING);+ request.setParticipantEmails(List.of("[email protected]"));+ when(pdfDocumentFactory.load(+ any(org.springframework.web.multipart.MultipartFile.class), eq(true)))+ .thenAnswer(+ invocation -> {+ var document = new org.apache.pdfbox.pdmodel.PDDocument();+ document.addPage(new org.apache.pdfbox.pdmodel.PDPage());+ return document;+ });request.setDocumentName("Custom Name");when(storageProvider.store(any(), any()))@@ -427,6 +547,15 @@ class WorkflowSessionServiceTest {new MockMultipartFile("file", "uploaded.pdf", "application/pdf", new byte[] {1});WorkflowCreationRequest request = new WorkflowCreationRequest();request.setWorkflowType(WorkflowType.SIGNING);+ request.setParticipantEmails(List.of("[email protected]"));+ when(pdfDocumentFactory.load(+ any(org.springframework.web.multipart.MultipartFile.class), eq(true)))+ .thenAnswer(+ invocation -> {+ var document = new org.apache.pdfbox.pdmodel.PDDocument();+ document.addPage(new org.apache.pdfbox.pdmodel.PDPage());+ return document;+ });request.setDocumentName(null);when(storageProvider.store(any(), any()))@@ -508,7 +637,8 @@ class WorkflowSessionServiceTest {WorkflowSession session = new WorkflowSession();session.setSessionId("s3");session.setOwner(owner);- when(workflowSessionRepository.findBySessionId("s3")).thenReturn(Optional.of(session));+ when(workflowSessionRepository.findBySessionIdForUpdate("s3"))+ .thenReturn(Optional.of(session));service.deleteSession("s3", owner);@@ -533,7 +663,8 @@ class WorkflowSessionServiceTest {session.setOwner(owner);session.setOriginalFile(originalFile);session.setProcessedFile(processedFile);- when(workflowSessionRepository.findBySessionId("s3b")).thenReturn(Optional.of(session));+ when(workflowSessionRepository.findBySessionIdForUpdate("s3b"))+ .thenReturn(Optional.of(session));service.deleteSession("s3b", owner);@@ -551,6 +682,30 @@ class WorkflowSessionServiceTest {inOrder.verify(storedFileRepository).delete(processedFile);}+ @Test+ void deleteSession_cancelledSession_deletesFilesAndSession() throws Exception {+ User owner = user("alice");+ owner.setId(1L);+ WorkflowSession session = new WorkflowSession();+ session.setSessionId("cancelled");+ session.setOwner(owner);+ session.setStatus(WorkflowStatus.CANCELLED);+ StoredFile original = new StoredFile();+ original.setStorageKey("cancelled-original");+ original.setWorkflowSession(session);+ session.setOriginalFile(original);+ when(workflowSessionRepository.findBySessionIdForUpdate("cancelled"))+ .thenReturn(Optional.of(session));++ service.deleteSession("cancelled", owner);++ verify(storageProvider).delete("cancelled-original");+ assertThat(original.getWorkflowSession()).isNull();+ verify(workflowSessionRepository).delete(session);+ verify(storedFileRepository).delete(original);+ verify(workflowSessionRepository, never()).save(any());+ }+@Testvoid deleteSession_finalizedSession_throwsBadRequest() {User owner = user("alice");@@ -560,14 +715,17 @@ class WorkflowSessionServiceTest {session.setSessionId("s3c");session.setOwner(owner);session.setFinalized(true);- when(workflowSessionRepository.findBySessionId("s3c")).thenReturn(Optional.of(session));+ when(workflowSessionRepository.findBySessionIdForUpdate("s3c"))+ .thenReturn(Optional.of(session));assertThatThrownBy(() -> service.deleteSession("s3c", owner)).isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("Cannot delete a finalized session").extracting(e -> ((ResponseStatusException) e).getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);verify(workflowSessionRepository, never()).delete(any());+ verifyNoInteractions(storageProvider, storedFileRepository);}@Test@@ -582,7 +740,8 @@ class WorkflowSessionServiceTest {session.setSessionId("s4");session.setOwner(owner);session.setOriginalFile(originalFile);- when(workflowSessionRepository.findBySessionId("s4")).thenReturn(Optional.of(session));+ when(workflowSessionRepository.findBySessionIdForUpdate("s4"))+ .thenReturn(Optional.of(session));doThrow(new RuntimeException("storage unavailable")).when(storageProvider).delete("key-orig");@@ -596,7 +755,7 @@ class WorkflowSessionServiceTest {}@Test- void deleteSession_notOwner_throwsForbidden() {+ void deleteSession_cancelledSessionNotOwner_throwsForbidden() {User owner = user("alice");owner.setId(1L);User other = user("bob");@@ -605,7 +764,9 @@ class WorkflowSessionServiceTest {WorkflowSession session = new WorkflowSession();session.setSessionId("s5");session.setOwner(owner);- when(workflowSessionRepository.findBySessionId("s5")).thenReturn(Optional.of(session));+ session.setStatus(WorkflowStatus.CANCELLED);+ when(workflowSessionRepository.findBySessionIdForUpdate("s5"))+ .thenReturn(Optional.of(session));assertThatThrownBy(() -> service.deleteSession("s5", other)).isInstanceOf(ResponseStatusException.class)diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionValidationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionValidationTest.javanew file mode 100644index 0000000000..1fb4f5be27--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/service/WorkflowSessionValidationTest.java@@ -0,0 +1,110 @@+package stirling.software.proprietary.workflow.service;++import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.*;+import static org.mockito.Mockito.*;++import java.util.List;+import java.util.Optional;++import org.apache.pdfbox.Loader;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.InjectMocks;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.mock.web.MockMultipartFile;+import org.springframework.web.multipart.MultipartFile;+import org.springframework.web.server.ResponseStatusException;++import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.storage.provider.StorageProvider;+import stirling.software.proprietary.workflow.dto.ParticipantRequest;+import stirling.software.proprietary.workflow.dto.WorkflowCreationRequest;+import stirling.software.proprietary.workflow.model.WorkflowParticipant;+import stirling.software.proprietary.workflow.model.WorkflowSession;+import stirling.software.proprietary.workflow.model.WorkflowType;+import stirling.software.proprietary.workflow.repository.WorkflowParticipantRepository;+import stirling.software.proprietary.workflow.repository.WorkflowSessionRepository;++@ExtendWith(MockitoExtension.class)+class WorkflowSessionValidationTest {+ @Mock private CustomPDFDocumentFactory pdfDocumentFactory;+ @Mock private StorageProvider storageProvider;+ @Mock private WorkflowSessionRepository workflowSessionRepository;+ @Mock private WorkflowParticipantRepository workflowParticipantRepository;+ @Mock private UserRepository userRepository;+ @InjectMocks private WorkflowSessionService service;++ @Test+ void rejectsEmptyParticipantsBeforeStoringAnything() {+ var request = new WorkflowCreationRequest();+ request.setWorkflowType(WorkflowType.SIGNING);+ assertThatThrownBy(() -> service.createSession(new User(), invalidPdf(), request))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("At least one participant");+ verifyNoInteractions(storageProvider, workflowSessionRepository, pdfDocumentFactory);+ }++ @Test+ void rejectsNonPdfBytesBeforeStorage() throws Exception {+ var request = new WorkflowCreationRequest();+ request.setWorkflowType(WorkflowType.SIGNING);+ request.setParticipantEmails(List.of("[email protected]"));+ when(pdfDocumentFactory.load(any(MultipartFile.class), eq(true)))+ .thenAnswer(+ invocation ->+ Loader.loadPDF(+ ((MultipartFile) invocation.getArgument(0)).getBytes()));+ assertThatThrownBy(() -> service.createSession(new User(), invalidPdf(), request))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("readable, unprotected PDF");+ verifyNoInteractions(storageProvider, workflowSessionRepository);+ }++ @Test+ void rejectsDuplicateUserAndEmailAliasesAsOneAtomicBatch() {+ var owner = new User();+ var signer = new User();+ signer.setUsername("[email protected]");+ var session = new WorkflowSession();+ session.setOwner(owner);+ when(workflowSessionRepository.findBySessionIdForUpdate("session"))+ .thenReturn(Optional.of(session));+ when(userRepository.findById(7L)).thenReturn(Optional.of(signer));+ var registered = new ParticipantRequest();+ registered.setUserId(7L);+ var email = new ParticipantRequest();+ email.setEmail(" [email protected] ");+ assertThatThrownBy(+ () -> service.addParticipants("session", List.of(registered, email), owner))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("only be added once");+ verifyNoInteractions(workflowParticipantRepository);+ }++ @Test+ void rejectsAnAlreadyInvitedParticipant() {+ var owner = new User();+ var session = new WorkflowSession();+ session.setOwner(owner);+ var existing = new WorkflowParticipant();+ existing.setEmail("[email protected]");+ session.addParticipant(existing);+ when(workflowSessionRepository.findBySessionIdForUpdate("session"))+ .thenReturn(Optional.of(session));+ var request = new ParticipantRequest();+ request.setEmail("[email protected]");+ assertThatThrownBy(() -> service.addParticipants("session", List.of(request), owner))+ .isInstanceOf(ResponseStatusException.class)+ .hasMessageContaining("only be added once");+ verifyNoInteractions(workflowParticipantRepository);+ }++ private MockMultipartFile invalidPdf() {+ return new MockMultipartFile(+ "file", "renamed.pdf", "application/pdf", "not a PDF".getBytes());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/util/WorkflowMapperShareTokenTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/util/WorkflowMapperShareTokenTest.javaindex 2d45579b09..a70960b457 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/workflow/util/WorkflowMapperShareTokenTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/workflow/util/WorkflowMapperShareTokenTest.java@@ -25,6 +25,54 @@ import stirling.software.proprietary.workflow.model.WorkflowType;*/class WorkflowMapperShareTokenTest {+ @Test+ void participantPreviewExposesOnlySubmittedMarksAndPublicProgress() {+ var session = buildSessionWithTwoParticipants();+ var alice = session.getParticipants().get(0);+ var bob = session.getParticipants().get(1);+ var mark =+ java.util.Map.of(+ "type",+ "image",+ "data",+ "data:image/png;base64,AA==",+ "page",+ 0,+ "x",+ .1,+ "y",+ .2,+ "width",+ .3,+ "height",+ .1);+ var metadata =+ java.util.Map.<String, Object>of(+ "wetSignatures", java.util.List.of(mark),+ "certificateSubmission",+ java.util.Map.of(+ "password", "private-password", "p12Data", "private-key"));+ alice.setParticipantMetadata(metadata);+ alice.setStatus(ParticipantStatus.SIGNED);+ bob.setParticipantMetadata(metadata);+ var mapper = new tools.jackson.databind.ObjectMapper();++ var previews = WorkflowMapper.toSigningParticipantPreviews(session, mapper);+ assertEquals(1, previews.get(0).wetSignatures().size());+ assertEquals(0, previews.get(1).wetSignatures().size());+ var json = mapper.valueToTree(previews);+ org.assertj.core.api.Assertions.assertThat(json.get(0).propertyNames())+ .containsExactlyInAnyOrder("id", "name", "status", "wetSignatures");+ org.assertj.core.api.Assertions.assertThat(json.toString())+ .doesNotContain(+ TOKEN_A, TOKEN_B, "private-password", "private-key", "[email protected]");++ session.setFinalized(true);+ org.assertj.core.api.Assertions.assertThat(+ WorkflowMapper.toSigningParticipantPreviews(session, mapper))+ .allMatch(p -> p.wetSignatures().isEmpty());+ }+private static final String TOKEN_A = "token-aaaa-1111";private static final String TOKEN_B = "token-bbbb-2222";diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 30ed37a2f8..f351f1fb38 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -1815,7 +1815,7 @@ label = "Enable Share Links"[admin.settings.storage.signing.enabled]description = "Allow users to create multi-participant document signing sessions. Requires server file storage to be enabled."-label = "Enable Group Signing (Alpha)"+title = "Enable Group Signing"[admin.settings.telegram]description = "Configure Telegram bot connectivity, access controls, and feedback behavior."@@ -2744,7 +2744,6 @@ reason = "Reason"serverCertMessage = "Using server certificate - no files or password required"showLogo = "Show Logo"signatureProgress = "{{signedCount}}/{{totalCount}} signatures"-signed = "Signed"tags = "authenticate,PEM,P12,official,encrypt,sign,certificate,PKCS12,JKS,server,manual,auto"title = "Certificate Signing"viewed = "Viewed"@@ -2809,7 +2808,13 @@ reasonPlaceholder = "e.g. Approval, Review..."[certSign.collab.finalize]button = "Finalize and Load Signed PDF"+confirmAction = "Confirm and finalize"+confirmDescription = "Finalizing closes this session. No more signatures can be submitted."+confirmTitle = "Finalize this signing session?"early = "Finalize with Current Signatures"+excluded = "Participants whose signatures will not be included"+included = "Signatures included"+requiresSignature = "At least one participant must sign before you can finalize."[certSign.collab.participant]certInvalid = "✗ {{error}}"@@ -2826,7 +2831,6 @@ includeSummaryPageHelp = "A summary page will be added at the end with all signa[certSign.collab.sessionDetail]addParticipants = "Add Participants"addParticipantsError = "Failed to add participants"-backToList = "Back to Sessions"deleteConfirm = "Are you sure? This cannot be undone."deleteError = "Failed to delete session"deleteSession = "Delete Session"@@ -2835,14 +2839,11 @@ finalizeError = "Failed to finalize session"loadPdfError = "Failed to load signed PDF"loadSignedPdf = "Load Signed PDF into Active Files"messageLabel = "Message"-owner = "Owner"participantRemoved = "Participant removed"participants = "Participants"participantsAdded = "Participants added successfully"-removeParticipant = "Remove"removeParticipantError = "Failed to remove participant"selectUsers = "Select users..."-sessionInfo = "Session Info"[certSign.collab.sessionList]active = "Active"@@ -2855,11 +2856,10 @@ title = "Signature Appearance"[certSign.collab.signRequest]addedToFiles = "Document added to active files"addToFiles = "Add to Active Files"-advancedSettings = "Advanced Settings"-backToList = "Back to Sign Requests"certificateChoice = "Select a certificate to sign with"changeSignature = "Change signature"clearSignature = "Clear Signature"+closed = "This session is finalized. You can view the final document, but no further signatures or declines are accepted."completeAndSign = "Complete & Sign"createNewSignature = "Create New Signature"decline = "Decline Request"@@ -2876,7 +2876,6 @@ invalidFileType = "Please select an image file"location = "Location (Optional)"locationPlaceholder = "Where are you signing from?"noCertificate = "Please select a certificate file"-noSignatures = "Please place at least one signature on the PDF"p12File = "P12/PFX Certificate File"password = "Certificate Password"penColor = "Pen Color"@@ -2894,16 +2893,15 @@ signatureText = "Signature Text"signatureTextPlaceholder = "Enter your name..."signatureTypeLabel = "Signature Type"signButton = "Sign Document"-signingTitle = "Signing"textColor = "Text Color"typeSignature = "Type your name to create a signature"-uploadCert = "Custom Certificate"-uploadCertDesc = "Use your own P12/PFX certificate"+uploadCert = "Upload a certificate"+uploadCertDesc = "Use your own PKCS12, PFX, PEM or JKS certificate."uploadSignature = "Upload your signature image"-usePersonalCert = "Personal Certificate"-usePersonalCertDesc = "Auto-generated for your account"-useServerCert = "Organization Certificate"-useServerCertDesc = "Shared organization certificate"+usePersonalCert = "Stirling Sign · Personal"+usePersonalCertDesc = "Sign with the certificate created for your account."+useServerCert = "Stirling Sign · Organization"+useServerCertDesc = "Sign with this server's shared organization certificate."useSignature = "Use signature"[certSign.collab.signRequest.certModal]@@ -2912,10 +2910,13 @@ certInvalidFallback = "Invalid certificate"certNetworkError = "Could not validate certificate"certValidating = "Validating certificate..."certValidUntil = "Certificate valid until {{date}}"-description_one = "You have placed {{count}} signature. Choose your certificate to complete signing."-description_other = "You have placed {{count}} signatures. Choose your certificate to complete signing."+description_one = "{{count}} visible mark is ready. Choose a certificate to finish signing."+description_other = "{{count}} visible marks are ready. Choose a certificate to finish signing."+description_zero = "Your certificate will sign the document without visible marks."+details = "Signing details (optional)"+format = "Certificate format"sign = "Sign Document"-title = "Configure Certificate"+title = "Choose how to sign"[certSign.collab.signRequest.mode]move = "Move Signature"@@ -2968,11 +2969,11 @@ visible = "Visible"yourSignatures = "Your Signatures ({{count}})"[certSign.collab.userSelector]-inviteUsers = "Add Users"loadError = "Failed to load users"noTeam = "No Team"noUsers = "No other users found."placeholder = "Select users..."+you = "{{name}} (You)"[certSign.device]stepTitle = "This device"@@ -5450,9 +5451,6 @@ multimedia = "Multimedia"[groupSigning.steps]back = "Back"-completed = "Completed"-current = "Current"-stepLabel = "Step {{number}}"[groupSigning.steps.configureDefaults]continue = "Continue"@@ -5460,7 +5458,6 @@ invisible = "Signatures will be invisible (metadata only)"locationLabel = "Location:"preview = "Preview"reasonLabel = "Reason:"-title = "Configure Signature Settings"visible = "Signatures will be visible on page {{page}}"[groupSigning.steps.review]@@ -5472,14 +5469,13 @@ location = "Location:"logo = "Logo:"logoHidden = "No logo"logoShown = "Stirling PDF logo shown"-participantCount_one = "{{count}} participant will sign in order"-participantCount_other = "{{count}} participants will sign in order"+participantCount_one = "{{count}} participant selected"+participantCount_other = "{{count}} participants selected"participants = "Participants"reason = "Reason:"send = "Send Signing Requests"signatureSettings = "Signature Settings"title = "Review Session Details"-titleShort = "Review & Send"visibility = "Visibility:"visible = "Visible on page {{page}}"@@ -5487,7 +5483,6 @@ visible = "Visible on page {{page}}"continue = "Continue"noFile = "Please select a single PDF file from your active files to create a signing session."selectedFile = "Selected document"-title = "Select Document"[groupSigning.steps.selectParticipants]continue = "Continue"@@ -5495,31 +5490,30 @@ count_one = "{{count}} participant selected"count_other = "{{count}} participants selected"label = "Select participants"placeholder = "Choose participants to sign..."-title = "Choose Participants"[groupSigning.tooltip]header = "About Group Signing"[groupSigning.tooltip.finalization]-bullet1 = "All signatures are applied in the participant order you specified"-bullet2 = "You can finalize with partial signatures if needed"-bullet3 = "Once finalized, the session cannot be modified"-description = "Once all participants have signed (or you choose to finalize early), you can generate the final signed PDF."+bullet1 = "The final PDF includes all accepted signatures"+bullet2 = "Review outstanding participants before finalizing with partial signatures"+bullet3 = "Finalization closes the request; outstanding participants can no longer sign"+description = "After at least one participant has signed, the owner can finalize the request and generate the signed PDF."title = "Finalization Process"[groupSigning.tooltip.roles]bullet1 = "Owner (you): Creates session, configures signature defaults, finalizes document"-bullet2 = "Participants: Create their signature, choose certificate, place on PDF"-bullet3 = "Participants cannot modify signature visibility, reason, or location settings"-description = "You control the signature appearance settings for all participants."+bullet2 = "Participants: Choose a certificate and optionally place a visible signature on the PDF"+bullet3 = "Participants can adjust their signature reason and location before submitting"+description = "The owner sets request defaults; each participant chooses their certificate and optional visible mark."title = "Participant Roles"[groupSigning.tooltip.sequential]-bullet1 = "First participant must sign before the second can access the document"-bullet2 = "Ensures proper signing order for legal compliance"-bullet3 = "You can reorder participants by dragging them in the list"-description = "Participants sign documents in the order you specify. Each signer receives a notification when it is their turn."-title = "Sequential Signing"+bullet1 = "Participants do not need to wait for another signer"+bullet2 = "Track each participant's progress in Signing Sessions"+bullet3 = "A due date is a reminder; it does not expire access"+description = "Assigned participants can review and sign independently, in any order."+title = "Signing in Any Order"[guestBanner]dismiss = "Dismiss banner"@@ -5828,7 +5822,6 @@ tags = "detect,split,photos,auto detect,detect photos,split photos,separate phottitle = "Detect & Split Scanned Photos"[home.sharedSign]-desc = "Request signatures from others and track signing sessions"title = "Shared Signing"[home.showJS]@@ -12137,28 +12130,15 @@ description = "Enter the full URL of your self-hosted Stirling PDF server"label = "Server URL"[sharedSign]-backToSessions = "Back to sessions"-createdOn = "Created {{date}}"disabledBody = "Collaborative signing isn't enabled on this server."-disabledTitle = "Not enabled"-due = "Due {{date}}"filterDeclined = "Declined"-filterMine = "Mine"filterOverdue = "Overdue"filterSigned = "Signed"-fromOwner = "From {{owner}}"-newRequest = "Request signatures"-signedCount = "{{signed}}/{{total}} signed"signInRequiredBody = "Sign in to request signatures and see requests sent to you."signInRequiredTitle = "Sign in required"-[sharedSign.empty]-active = "No pending sign requests or active sessions"-completed = "No completed sessions"-[sharedSign.tab]active = "Active"-completed = "Completed"[showJS]done = "JavaScript extracted"@@ -12508,10 +12488,68 @@ bullet3 = "Invisible signatures still provide cryptographic validation"description = "Controls whether the signature is visible on the document or embedded invisibly."title = "Signature Visibility"+[signingDetail]+allSigned = "Everyone has signed. Review the document, then finalize."+awaitingOwner = "The owner will finalize the document once they are ready."+certificateNext = "Choose your certificate in the next step."+earlyHint = "You can finalize now with the signatures received, or wait for the remaining participants."+finalDocument = "Signed document"+finalizeTitle = "Finalize document"+finalReady = "Your signed PDF is ready to open in the workbench."+inProgressPreview = "In-progress preview with submitted signatures. The owner has not finalized this document yet."+manageSession = "Manage signing session"+moveHint = "Select a signature on the document to move, resize or remove it."+notified = "Notified"+optional = "Optional"+ownerNext = "Return to your session to review everyone's signatures and finalize the document when you are ready."+placeHint = "Click on the document to place your signature."+progress = "Signature progress"+readyToSign = "Ready to sign?"+refreshPreview = "Refresh preview"+removePerson = "Remove {{name}}"+requestClosed = "This request is closed"+requestTitle = "Signature request"+signatureSubmitted = "Your signature is submitted"+signedCount = "{{signed}} / {{total}} signed"+signMyRequest = "Sign this document"+viewOnly = "You can still review the document here."+visibleSignature = "Visible signature"+visibleSignatureHelp = "About visible signatures"++[signMenu]+anyOrder = "Participants can sign in any order. The owner finalizes the document after reviewing the collected signatures."+certificateHint = "Use a certificate"+certificateTitle = "Digital signature"+closedStatus = "Closed"+completedTab = "Completed"+dueDate = "Due date (optional)"+newActivity = "New activity since you last viewed this session"+noActive = "No active sessions"+noCompleted = "No completed sessions"+noMatches = "No matching sessions"+noUnread = "You're all caught up"+optionalMarks = "Visible marks are optional. Complete & Sign also works with a certificate alone."+ownerProgress = "Your request · {{signed}} / {{total}} signed"+personalHint = "Draw, type or upload"+personalTitle = "Personal signature"+request = "Request signatures"+search = "Find a document or person"+send = "Send signing request"+sessionFilter = "Session views"+sessions = "Signing sessions"+settings = "Appearance and summary page (optional)"+signFailed = "Signing failed. Check your certificate and try again; your placed marks are preserved."+submitted = "Submitted · awaiting finalization"+title = "Sign"+triggerUnreadCount_one = "Sign · {{count}} unread session"+triggerUnreadCount_other = "Sign · {{count}} unread sessions"+unreadTab = "Unread"+[signRequest]+accessExpired = "Your access to this signing request has expired. Ask the sender for a new request."declined = "Sign request declined"+expired = "Access expired"fetchFailed = "Failed to load sign request"-signed = "Document signed successfully"[signSession]created = "Signing request sent"@@ -12548,6 +12586,52 @@ unableToAccessTool = "Unable to access tool: {{error}}"unexpectedError = "Unexpected error: {{message}}"unknownError = "Unknown error"+[signWorkspace]+changeDocument = "Change PDF"+chooseDocument = "Choose an open PDF"+chooseFromLibrary = "Choose from library"+chooseParticipants = "Choose participants"+choosePdf = "Choose a PDF"+choosePdfHeading = "Start with your document"+clearDate = "Clear date"+created = "Created"+createdByMe = "Created by me"+datesAndOptions = "Dates & options"+document = "Document"+dueDate = "Due date"+dueDateHelp = "This is a target date. Participants can still sign after it."+dueDateHelpLabel = "About due dates"+empty = "No sessions here yet."+expand = "Expand signing sessions"+inviteLoadError = "Could not load invitation options. Close this dialog and try again."+invitePerson = "Add teammate: {{name}}"+inviteTeammate = "Add a teammate"+inviteUnavailable = "Adding teammates is not available for your account or server configuration."+navigation = "Signing navigation"+needsYou = "Needs your signature"+nextMonth = "Next month"+nextStep = "Next"+noDueDate = "No due date"+noMatches = "No sessions match your search or filter."+noOpenPdfs = "Choose a PDF from your library or add one from your computer."+noPeopleMatch = "No people match your search."+noPreview = "Document preview unavailable"+owner = "Owner"+participants = "Participants"+participantsSelected = "{{count}} selected"+personalHeading = "Sign a document"+previousMonth = "Previous month"+refresh = "Refresh sessions"+requestSteps = "Signing request steps"+search = "Search documents or people"+searchParticipants = "Search people or teams"+selectOnePdf = "Choose one PDF for this signing request."+signingOrderHelp = "About signing order"+status = "Status"+unavailable = "This session is no longer available. Refresh the list to see your current sessions."+upcoming = "Upcoming"+uploadFailed = "Could not open this PDF. Please try again."+[sizes]large = "Large"medium = "Medium"diff --git a/frontend/editor/public/og-metadata.json b/frontend/editor/public/og-metadata.jsonindex 3d68a0eb63..a555772293 100644--- a/frontend/editor/public/og-metadata.json+++ b/frontend/editor/public/og-metadata.json@@ -15,11 +15,6 @@"title": "Sign PDF - Stirling PDF","description": "Adds signature to PDF by drawing, text or image"},- "sharedSign": {- "image": "/og_images/shared-sign.png",- "title": "Shared Signing - Stirling PDF",- "description": "Request signatures from others and track signing sessions"- },"addText": {"image": "/og_images/add-text.png","title": "Add Text to PDF - Stirling PDF",@@ -772,7 +767,6 @@"byPath": {"/cert-sign": "certSign","/sign": "sign",- "/shared-sign": "sharedSign","/add-text": "addText","/add-password": "addPassword","/remove-password": "removePassword",@@ -1252,10 +1246,6 @@"path": "/sanitize","label": "Sanitize PDF"},- {- "path": "/shared-sign",- "label": "Shared Signing"- },{"path": "/show-js","label": "Show JavaScript in PDF"diff --git a/frontend/editor/public/og-metadata.saas.json b/frontend/editor/public/og-metadata.saas.jsonindex 8d8ee0640e..77d0cdcf9e 100644--- a/frontend/editor/public/og-metadata.saas.json+++ b/frontend/editor/public/og-metadata.saas.json@@ -16,11 +16,6 @@"title": "Sign PDF - Stirling PDF","description": "Adds signature to PDF by drawing, text or image"},- "sharedSign": {- "image": "/og_images/shared-sign.png",- "title": "Shared Signing - Stirling PDF",- "description": "Request signatures from others and track signing sessions"- },"addText": {"image": "/og_images/add-text.png","title": "Add Text to PDF - Stirling PDF",@@ -780,7 +775,6 @@"byPath": {"/cert-sign": "certSign","/sign": "sign",- "/shared-sign": "sharedSign","/add-text": "addText","/add-password": "addPassword","/remove-password": "removePassword",@@ -1261,10 +1255,6 @@"path": "/sanitize","label": "Sanitize PDF"},- {- "path": "/shared-sign",- "label": "Shared Signing"- },{"path": "/show-js","label": "Show JavaScript in PDF"diff --git a/frontend/editor/src/core/components/FileManager.tsx b/frontend/editor/src/core/components/FileManager.tsxindex ad3899457a..a95f5b77ab 100644--- a/frontend/editor/src/core/components/FileManager.tsx+++ b/frontend/editor/src/core/components/FileManager.tsx@@ -9,7 +9,8 @@ interface FileManagerProps {/** Unmounting discards tentative selections; file ingestion remains owned by FilesModalContext. */export default function FileManager({ selectedTool }: FileManagerProps) {- const { isFilesModalOpen, closeFilesModal } = useFilesModalContext();+ const { isFilesModalOpen, closeFilesModal, supportedFormats } =+ useFilesModalContext();const [busy, setBusy] = useState(false);const [externalPickerOpen, setExternalPickerOpen] = useState(false);return (@@ -21,7 +22,7 @@ export default function FileManager({ selectedTool }: FileManagerProps) {>{isFilesModalOpen && (<LibraryFilePicker- supportedFormats={selectedTool?.supportedFormats}+ supportedFormats={supportedFormats ?? selectedTool?.supportedFormats}onBusyChange={setBusy}onExternalPickerChange={setExternalPickerOpen}/>diff --git a/frontend/editor/src/core/components/layout/Workbench.tsx b/frontend/editor/src/core/components/layout/Workbench.tsxindex b8c19952f9..8c98c7c781 100644--- a/frontend/editor/src/core/components/layout/Workbench.tsx+++ b/frontend/editor/src/core/components/layout/Workbench.tsx@@ -12,7 +12,6 @@ import {} from "@app/contexts/NavigationContext";import { isBaseWorkbench } from "@app/types/workbench";import { VIEWER_SUPPORTED_EXTENSIONS } from "@app/utils/fileUtils";-import { useSigningOverlay } from "@app/contexts/SigningOverlayContext";import { useIsPhone } from "@app/hooks/useIsMobile";import styles from "@app/components/layout/Workbench.module.css";@@ -28,6 +27,9 @@ import { NotificationBell } from "@app/components/notifications/NotificationBell// Workbench panels are loaded on demand. Viewer pulls in pdfjs-dist and the// full @embedpdf plugin set; FileEditor/PageEditor are only needed once a file// is open. Lazy-loading keeps all of that out of the initial bundle.+const SigningWorkspace = lazy(+ () => import("@app/components/shared/signing/SigningWorkspace"),+);const FileEditor = lazy(() => import("@app/components/fileEditor/FileEditor"));const PageEditor = lazy(() => import("@app/components/pageEditor/PageEditor"));const PageEditorControls = lazy(@@ -60,7 +62,6 @@ export default function Workbench() {} = useToolWorkflow();const { handleToolSelect } = useToolWorkflow();- const { overlay: signingOverlay } = useSigningOverlay();// Below this width the rail, and the bell it carries, is gone.const isPhone = useIsPhone();@@ -85,15 +86,15 @@ export default function Workbench() {const activeCustomView = customWorkbenchViews.find((v) => v.workbenchId === currentView,);- const topControlsAvailable = !activeCustomView?.hideTopControls;+ const topControlsAvailable =+ currentView !== "signing" && !activeCustomView?.hideTopControls;const hasWorkbenchContent =hasFiles ||fileIds.length > 0 ||!isBaseWorkbench(currentView) ||// The library browses stored files, so it has content of its own with none open.currentView === "myFiles" ||- // Shared signing drives the viewer from the sidebar with no file in context.- (currentView === "viewer" && !!signingOverlay?.file);+ currentView === "signing";// Reading hides the bar; the rail's Reader entry is the way back. A takeover hides// the switcher and search too: both navigate away from a flow that must finish.const showWorkbenchBar =@@ -149,29 +150,14 @@ export default function Workbench() {}}+ if (currentView === "signing") return <SigningWorkspace />;+// The file-library workbench is available regardless of whether files are// currently loaded into the workbench - it lives on top of the IDB store.if (currentView === "myFiles") {return <FileManagerView />;}- // Shared Signing drives the main viewer from the sidebar (document + overlays- // via context), ahead of the empty-state landing page.- if (currentView === "viewer" && signingOverlay?.file) {- return (- <Viewer- previewFile={signingOverlay.file}- signaturePreviews={signingOverlay.signaturePreviews}- signaturePreviewsReadOnly={signingOverlay.signaturePreviewsReadOnly}- signaturePlacementMode={signingOverlay.signaturePlacementMode}- signaturePlacementData={signingOverlay.signaturePlacementData}- signaturePlacementType={signingOverlay.signaturePlacementType}- onSignaturePreviewsChange={signingOverlay.onSignaturePreviewsChange}- signatureOverlayApiRef={signingOverlay.signatureOverlayApiRef}- />- );- }-if (activeFiles.length === 0) {// Files are open but their bytes are still loading (a cold PDF engine can// take seconds). Showing the drop zone here reads as "the click did nothing".@@ -263,7 +249,7 @@ export default function Workbench() {<BoxclassName="flex-1 h-full min-w-0 relative flex flex-col"data-tour="workbench"- style={{ backgroundColor: "var(--c-bg)", minWidth: 0 }}+ style={{ backgroundColor: "var(--c-bg)", minWidth: 0, minHeight: 0 }}>{/* Phone only: above that the rail carries the bell, and here no bar does. */}{isPhone && !showWorkbenchBar && topControlsAvailable && (@@ -306,7 +292,7 @@ export default function Workbench() {<DismissAllErrorsButton />{/* Floating AI chat button + panel */}- {currentView !== "myFiles" && <ChatFAB />}+ {currentView !== "myFiles" && currentView !== "signing" && <ChatFAB />}{/* Main content area */}<Boxdiff --git a/frontend/editor/src/core/components/shared/InviteTeammateButton.tsx b/frontend/editor/src/core/components/shared/InviteTeammateButton.tsxnew file mode 100644index 0000000000..9855b07f1e--- /dev/null+++ b/frontend/editor/src/core/components/shared/InviteTeammateButton.tsx@@ -0,0 +1,11 @@+export interface InviteTeammateButtonProps {+ search: string;+ disabled?: boolean;+ /** Refresh the participant directory after the invite flow succeeds. */+ onInvited: () => void;+}++/** Builds with account management supply the invitation flow. */+export function InviteTeammateButton(_props: InviteTeammateButtonProps) {+ return null;+}diff --git a/frontend/editor/src/core/components/shared/Tooltip.tsx b/frontend/editor/src/core/components/shared/Tooltip.tsxindex b4d320ffbb..17e43b7534 100644--- a/frontend/editor/src/core/components/shared/Tooltip.tsx+++ b/frontend/editor/src/core/components/shared/Tooltip.tsx@@ -378,9 +378,8 @@ export const Tooltip: React.FC<TooltipProps> = ({{ref: (node: HTMLElement | null) => {triggerRef.current = node || null;- const originalRef = (- children as React.ReactElement & { ref?: React.Ref<HTMLElement> }- ).ref;+ const originalRef = (children.props as { ref?: React.Ref<HTMLElement> })+ .ref;if (typeof originalRef === "function") originalRef(node);else if (originalRef && typeof originalRef === "object")originalRef.current = node;diff --git a/frontend/editor/src/core/components/shared/UserSelector.module.css b/frontend/editor/src/core/components/shared/UserSelector.module.cssnew file mode 100644index 0000000000..6524c312de--- /dev/null+++ b/frontend/editor/src/core/components/shared/UserSelector.module.css@@ -0,0 +1,61 @@+.groups {+ display: grid;+ gap: 16px;+ max-height: 320px;+ overflow-y: auto;+ padding: 3px;+}+.grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr));+ gap: 12px;+}+.card {+ display: flex;+ align-items: center;+ gap: 12px;+ min-width: 0;+ padding: 16px;+ border: 1px solid var(--c-border);+ border-radius: 12px;+ cursor: pointer;+}+.card:hover {+ background: var(--c-hover);+}+.card[data-selected="true"] {+ border-color: var(--c-primary);+ background: var(--c-primary-subtle);+}+.card:focus-within {+ outline: 2px solid var(--c-primary);+ outline-offset: 2px;+}+.card:has(input:disabled) {+ opacity: 0.6;+ cursor: default;+}+.avatar {+ display: grid;+ place-items: center;+ flex-shrink: 0;+ width: 44px;+ height: 44px;+ border-radius: 50%;+ background: var(--c-primary-subtle);+ color: var(--c-accent-fg);+ font-size: 14px;+ font-weight: 600;+}+.name {+ flex: 1;+ min-width: 0;+ overflow-wrap: anywhere;+ font-size: 14px;+}+.card input {+ flex-shrink: 0;+ width: 18px;+ height: 18px;+ accent-color: var(--c-primary);+}diff --git a/frontend/editor/src/core/components/shared/UserSelector.tsx b/frontend/editor/src/core/components/shared/UserSelector.tsxindex 5c25728e4a..89b1e2a432 100644--- a/frontend/editor/src/core/components/shared/UserSelector.tsx+++ b/frontend/editor/src/core/components/shared/UserSelector.tsx@@ -1,9 +1,10 @@import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { useQuery } from "@tanstack/react-query";-import { MultiSelect, Loader, Text, Stack } from "@mantine/core";-import { Button } from "@app/ui/Button";-import { useNavigate } from "react-router-dom";+import { MultiSelect, Loader, Text, Stack, TextInput } from "@mantine/core";+import { Icon } from "@app/ui/Icon";+import { InviteTeammateButton } from "@app/components/shared/InviteTeammateButton";+import styles from "@app/components/shared/UserSelector.module.css";import { alert } from "@app/components/toast";import { fetchUsers } from "@app/api/users";import { useAuth } from "@app/auth/UseSession";@@ -14,8 +15,10 @@ interface UserSelectorProps {value: number[];onChange: (userIds: number[]) => void;placeholder?: string;+ label?: string;size?: "xs" | "sm" | "md" | "lg" | "xl";disabled?: boolean;+ presentation?: "dropdown" | "cards";}type SelectItem = { value: string; label: string };@@ -25,18 +28,21 @@ const UserSelector = ({value,onChange,placeholder,+ label,size = "sm",disabled = false,+ presentation = "dropdown",}: UserSelectorProps) => {const { t } = useTranslation();const { user } = useAuth();- const navigate = useNavigate();const [stringValue, setStringValue] = useState<string[]>([]);+ const [search, setSearch] = useState("");const {data: users,isPending: loading,error,+ refetch,} = useQuery({ queryKey: qk.users(), queryFn: fetchUsers });useEffect(() => {@@ -54,7 +60,6 @@ const UserSelector = ({(users ?? []).filter((u) => u && u.userId && u.username)- .filter((u) => u.userId !== currentUserId).filter((u) => u.teamName?.toLowerCase() !== "internal").forEach((u) => {const teamName =@@ -68,7 +73,15 @@ const UserSelector = ({displayName !== username? `${displayName} (@${username})`: displayName;- usersByTeam[teamName].push({ value: String(u.userId), label });+ usersByTeam[teamName].push({+ value: String(u.userId),+ label:+ u.userId === currentUserId+ ? t("certSign.collab.userSelector.you", "{{name}} (You)", {+ name: label,+ })+ : label,+ });});return Object.entries(usersByTeam).map(([teamName, items]) => ({@@ -77,7 +90,6 @@ const UserSelector = ({}));}, [users, user, t]);- // Process stringValue when value prop changesuseEffect(() => {const safeValue = Array.isArray(value) ? value : [];const result = safeValue@@ -90,26 +102,113 @@ const UserSelector = ({return <Loader size="sm" />;}- // No users available — prompt to invite- if (!selectData || selectData.length === 0) {+ const inviteButton = (+ <InviteTeammateButton+ search={search}+ disabled={disabled}+ onInvited={() => {+ setSearch("");+ void refetch();+ }}+ />+ );++ if (selectData.length === 0 && presentation !== "cards") {return (<Stack gap="xs" align="flex-start"><Text size="sm" c="dimmed">{t("certSign.collab.userSelector.noUsers", "No other users found.")}</Text>- <Button- size="sm"- variant="secondary"- onClick={() => navigate("/settings/people")}- >- {t("certSign.collab.userSelector.inviteUsers", "Add Users")}- </Button>+ {inviteButton}+ </Stack>+ );+ }++ if (presentation === "cards") {+ const matchingGroups = selectData+ .map((group) => ({+ ...group,+ items: group.items.filter((item) =>+ `${item.label} ${group.group}`+ .toLocaleLowerCase()+ .includes(search.trim().toLocaleLowerCase()),+ ),+ }))+ .filter((group) => group.items.length > 0);+ return (+ <Stack gap="md" role="group" aria-label={label}>+ <TextInput+ aria-label={t(+ "signWorkspace.searchParticipants",+ "Search people or teams",+ )}+ placeholder={t(+ "signWorkspace.searchParticipants",+ "Search people or teams",+ )}+ leftSection={<Icon name="search" size={18} />}+ value={search}+ onChange={(event) => setSearch(event.currentTarget.value)}+ disabled={disabled}+ />+ <div className={styles.groups}>+ {matchingGroups.map((group) => (+ <div key={group.group}>+ {group.group.toLowerCase() !== "default" && (+ <Text size="xs" c="dimmed" mb="xs">+ {group.group}+ </Text>+ )}+ <div className={styles.grid}>+ {group.items.map((item) => {+ const id = Number(item.value);+ const selected = value.includes(id);+ return (+ <label+ key={id}+ className={styles.card}+ data-selected={selected}+ >+ <span className={styles.avatar} aria-hidden="true">+ {item.label.slice(0, 2).toLocaleUpperCase()}+ </span>+ <span className={styles.name}>{item.label}</span>+ <input+ type="checkbox"+ checked={selected}+ disabled={disabled}+ onChange={() =>+ onChange(+ selected+ ? value.filter((userId) => userId !== id)+ : [...value, id],+ )+ }+ />+ </label>+ );+ })}+ </div>+ </div>+ ))}+ </div>+ {matchingGroups.length === 0 && (+ <Text size="sm" c="dimmed">+ {t("signWorkspace.noPeopleMatch", "No people match your search.")}+ </Text>+ )}+ {inviteButton}</Stack>);}return (<MultiSelect+ label={label}+ aria-label={+ label ??+ t("certSign.collab.userSelector.placeholder", "Select users...")+ }data={selectData}value={stringValue}onChange={(selectedIds) => {diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsxindex ca2a479945..8d570af72b 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.state.test.tsx@@ -11,6 +11,7 @@ import {import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";import { fetchSigningSessions, type SigningSessions } from "@app/api/signing";import { alert } from "@app/components/toast";+import { markSigningItemSeen } from "@app/services/signingSeenStore";import { expectConsole } from "@app/tests/failOnConsole";const auth = vi.hoisted<Pick<ReturnType<typeof useAuth>, "user" | "loading">>(@@ -59,6 +60,7 @@ function RailState() {<><output data-testid="access">{String(host?.portalAccess)}</output><output data-testid="badge">{host?.signingBadge}</output>+ <output data-testid="items">{JSON.stringify(host?.signingItems)}</output></>);}@@ -121,6 +123,49 @@ describe("quick-nav account data during view switches", () => {mockFetch.mockResolvedValue(UNREAD);});+ it("keeps the unread count in sync as owners view updates and ready sessions", async () => {+ const partial = UNREAD.mySessions[0];+ mockFetch.mockResolvedValue({+ signRequests: [+ {+ sessionId: "request",+ documentName: "Request.pdf",+ ownerUsername: "Owner",+ createdAt: "2026-09-24",+ dueDate: "",+ myStatus: "PENDING",+ },+ ],+ mySessions: [+ partial,+ { ...partial, sessionId: "ready", signedCount: 2 },+ { ...partial, sessionId: "closed", finalized: true },+ ],+ });+ setup();+ await waitFor(() => expectRail(true, 3));+ const unreadCount = () =>+ JSON.parse(screen.getByTestId("items").textContent ?? "[]").filter(+ (item: { unread: boolean }) => item.unread,+ ).length;+ expect(unreadCount()).toBe(3);+ act(() => markSigningItemSeen("ada", { ...partial, kind: "session" }));+ await waitFor(() => expectRail(true, 2));+ expect(unreadCount()).toBe(2);+ act(() =>+ markSigningItemSeen("ada", {+ ...partial,+ kind: "session",+ sessionId: "ready",+ signedCount: 2,+ }),+ );+ await waitFor(() => expectRail(true, 1));+ expect(unreadCount()).toBe(1);+ expect(+ JSON.parse(screen.getByTestId("items").textContent ?? "[]"),+ ).toHaveLength(4);+ });it("retains access and the count until each incoming lookup settles", async () => {const switchView = setup();await waitFor(() => expectRail(true, 1));diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.css b/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.cssindex f49552d667..b106d1e863 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.css+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRail.css@@ -17,6 +17,10 @@width: 100%;}+.quick-nav-rail-group > .sui-dd {+ width: 100%;+}+/* The glyph stays at the sidebar's scale; the button fills the rail for hit area. */.quick-nav-rail-item {position: relative;diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.test.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.test.tsxindex 328f2d8f4e..e2d4541541 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.test.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { render } from "@testing-library/react";+import { render, screen, within } from "@testing-library/react";import {QuickNavRailBase,type QuickNavEntry,@@ -55,6 +55,31 @@ describe("QuickNavRailBase — groups", () => {});describe("QuickNavRailBase — entry state", () => {+ it("shows the exact signing count while preserving capped badges for other entries", () => {+ render(+ <QuickNavRailBase+ groups={[+ [+ entry("sign", { badge: 167, badgeMax: null }),+ entry("notifications", { badge: 167 }),+ entry("empty", { badge: 0, badgeMax: null }),+ ],+ ]}+ />,+ );+ expect(+ within(screen.getByRole("button", { name: "sign" })).getByText("167"),+ ).toBeInTheDocument();+ expect(+ within(screen.getByRole("button", { name: "notifications" })).getByText(+ "9+",+ ),+ ).toBeInTheDocument();+ expect(+ within(screen.getByRole("button", { name: "empty" })).queryByText("0"),+ ).not.toBeInTheDocument();+ });+it("reports on/off for a toggle and nothing for the rest", () => {// Nothing here is a view you occupy, so only a real toggle has state.const { container } = render(diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsxindex 8d06a377b2..31b2ff672b 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailBase.tsx@@ -1,4 +1,4 @@-import type { ReactNode } from "react";+import { Fragment, type ReactNode, type ReactElement, type Ref } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@app/components/shared/Tooltip";import "@app/components/shared/quickNav/QuickNavRail.css";@@ -17,6 +17,8 @@ export interface QuickNavEntry {disabled?: boolean;reason?: string;badge?: number;+ /** Counts above this use a plus suffix; null shows the full count. Defaults to nine. */+ badgeMax?: number | null;/** Popup semantics for an entry whose panel is rendered in another tree. */expanded?: boolean;controls?: string;@@ -27,6 +29,8 @@ export interface QuickNavEntry {/** Stable guided-tour anchor when it differs from the test hook. */tourId?: string;onClick: () => void;+ /** Allows an entry to anchor a popup while retaining the shared rail control. */+ wrap?: (button: ReactElement<{ onClick: () => void }>) => ReactNode;}export interface QuickNavRailBaseProps {@@ -43,6 +47,7 @@ export function RailButton({disabled,reason,badge,+ badgeMax = 9,badgeTone = "danger",current,expanded,@@ -50,7 +55,14 @@ export function RailButton({testId,tourId,onClick,-}: Omit<QuickNavEntry, "id">) {+ ref,+ "aria-haspopup": popupRole,+ "aria-controls": popupControls,+}: Omit<QuickNavEntry, "id"> & {+ ref?: Ref<HTMLButtonElement>;+ "aria-haspopup"?: "menu" | "dialog";+ "aria-controls"?: string;+}) {return (<Tooltipcontent={disabled && reason ? `${label} — ${reason}` : label}@@ -59,14 +71,19 @@ export function RailButton({containerStyle={{ pointerEvents: "none" }}><button+ ref={ref}type="button"className="quick-nav-rail-item"aria-pressed={pressed}aria-current={current ? "true" : undefined}aria-label={label}- aria-haspopup={expanded === undefined ? undefined : "dialog"}+ aria-haspopup={+ popupRole ?? (expanded === undefined ? undefined : "dialog")+ }aria-expanded={expanded}- aria-controls={expanded === undefined ? undefined : controls}+ aria-controls={+ popupControls ?? (expanded === undefined ? undefined : controls)+ }// aria-disabled, not `disabled`: stays focusable, so its tooltip is reachable.aria-disabled={disabled || undefined}data-testid={testId}@@ -80,7 +97,7 @@ export function RailButton({data-tone={badgeTone}aria-hidden="true">- {badge > 9 ? "9+" : badge}+ {badgeMax !== null && badge > badgeMax ? `${badgeMax}+` : badge}</span>)}</button>@@ -100,7 +117,13 @@ export function QuickNavRailBase({ groups, footer }: QuickNavRailBaseProps) {<div className="quick-nav-rail-group" key={group[0].id}>{index > 0 && <hr className="quick-nav-rail-divider" />}{group.map((entry) => (- <RailButton key={entry.id} {...entry} />+ <Fragment key={entry.id}>+ {entry.wrap ? (+ entry.wrap(<RailButton {...entry} />)+ ) : (+ <RailButton {...entry} />+ )}+ </Fragment>))}</div>))}diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsxindex a243823b70..085af04ccd 100644--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx@@ -1,4 +1,7 @@import { useTranslation } from "react-i18next";+import { useState } from "react";+import { SignMenu } from "@app/components/shared/signing/SignMenu";+import { requestSigningIntent } from "@app/utils/pendingSigningIntent";import { useLocation, useNavigate } from "react-router-dom";import { QuickNavRailContainer } from "@app/components/shared/quickNav/QuickNavRailContainer";import type { QuickNavEntry } from "@app/components/shared/quickNav/QuickNavRailBase";@@ -32,6 +35,7 @@ export function QuickNavRailHost() {const navigate = useNavigate();const { pathname } = useLocation();const host = useQuickNavHost();+ const [signMenuOpen, setSignMenuOpen] = useState(false);// Processing folders run on the non-core API server. True on web (served by that backend);// on desktop it tracks the signed-in connection, so the entry falls inert until the user// signs in to Stirling Cloud or a self-hosted server.@@ -111,7 +115,11 @@ export function QuickNavRailHost() {icon: <Icon name="pencil" size={SIZE} filled={inEditor} />,// The library and reading are places of their own, not the editor with a// different centre.- current: inEditor && !host?.fileLibrary && !host?.readerMode,+ current:+ inEditor &&+ !host?.fileLibrary &&+ !host?.readerMode &&+ path !== "/shared-sign",onClick: () => {if (inEditor) {returnHome();@@ -222,14 +230,41 @@ export function QuickNavRailHost() {onClick: () => openTool("automate", "/automate"),},{- id: "sharedSign",- label: t("home.sharedSign.title", "Shared Signing"),+ id: "sign",+ label: host?.signingBadge+ ? t("signMenu.triggerUnreadCount", "Sign · {{count}} unread sessions", {+ count: host.signingBadge,+ })+ : t("signMenu.title", "Sign"),icon: <Icon name="pen-tool" size={SIZE} />,badge: host?.signingBadge,+ badgeMax: null,badgeTone: "warning",- ...openingTool("sharedSign"),- ...unusable("sharedSign"),- onClick: () => openTool("sharedSign", "/shared-sign"),+ current:+ host?.activeTool === "sign" ||+ host?.activeTool === "certSign" ||+ path === "/shared-sign",+ expanded: signMenuOpen,+ onClick: () => setSignMenuOpen((open) => !open),+ wrap: (button) => (+ <SignMenu+ opened={signMenuOpen}+ onClose={() => setSignMenuOpen(false)}+ reasons={host?.toolReasons ?? {}}+ items={host?.signingItems ?? []}+ onOpenSigning={(intent) =>+ guarded(() => {+ requestSigningIntent(intent);+ navigate("/shared-sign");+ })+ }+ onSelect={(tool) =>+ openTool(tool, tool === "certSign" ? "/cert-sign" : "/sign")+ }+ >+ {button}+ </SignMenu>+ ),},];diff --git a/frontend/editor/src/core/components/shared/quickNav/useQuickNavToolReasons.ts b/frontend/editor/src/core/components/shared/quickNav/useQuickNavToolReasons.tsindex 989c2eea16..460b2000ff 100644--- a/frontend/editor/src/core/components/shared/quickNav/useQuickNavToolReasons.ts+++ b/frontend/editor/src/core/components/shared/quickNav/useQuickNavToolReasons.ts@@ -5,11 +5,16 @@ import { useAppConfig } from "@app/contexts/AppConfigContext";import { useGroupSigningEnabled } from "@app/hooks/useGroupSigningEnabled";import { useAuth } from "@app/auth/UseSession";import { getDisabledLabel } from "@app/components/tools/fullscreen/shared";-import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";+import type {+ QuickNavToolReasons,+ QuickNavEntryId,+} from "@app/contexts/QuickNavHostContext";import type { ToolId } from "@app/types/toolId";const ENTRY_ENDPOINTS = {automate: ["automate"],+ sign: ["sign"],+ certSign: ["cert-sign"],} satisfies Partial<Record<ToolId, string[]>>;// Object.keys widens to string, which a tool-id-keyed record can't be indexed by.@@ -21,7 +26,7 @@ const ENDPOINT_ENTRIES = Object.keys(type EndpointCause = "missingDependency" | "disabledByAdmin";// Guest-only; left out of CAUSES so it is never read back for whoever signs in next.type Cause = EndpointCause | "groupSigningOff" | "signInRequired";-type Causes = Partial<Record<ToolId, Cause>>;+type Causes = Partial<Record<QuickNavEntryId, Cause>>;const CAUSES: Cause[] = ["missingDependency","disabledByAdmin",@@ -41,7 +46,7 @@ function readRemembered(): Causes | null {}const known = Object.entries(parsed as Record<string, unknown>).filter(([, cause]) => CAUSES.includes(cause as Cause),- ) as [ToolId, Cause][];+ ) as [QuickNavEntryId, Cause][];return Object.fromEntries(known);} catch {return null;@@ -117,7 +122,7 @@ export function useQuickNavToolReasons(): QuickNavToolReasons | null {return useMemo(() => {if (!causes) return null;const reasons: QuickNavToolReasons = {};- for (const entry of Object.keys(causes) as ToolId[]) {+ for (const entry of Object.keys(causes) as QuickNavEntryId[]) {const cause = causes[entry];if (cause === "signInRequired") {reasons[entry] = t(diff --git a/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts b/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.tsindex 27a3701bb6..ff7ed29c7e 100644--- a/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts+++ b/frontend/editor/src/core/components/shared/quickNav/useSyncQuickNavAccount.ts@@ -15,7 +15,7 @@ export function useSyncQuickNavAccount(): void {loading: identityLoading,} = useAccountIdentity();const { granted, settled: accessSettled } = usePortalAccessState();- const { count, settled: signingSettled } = useSigningBadgeState();+ const { count, settled: signingSettled, items } = useSigningBadgeState();const accountId = user?.id ?? null;useEffect(() => {@@ -27,6 +27,7 @@ export function useSyncQuickNavAccount(): void {? undefined: { displayName, profilePictureUrl },signingBadge: signingSettled ? count : undefined,+ signingItems: signingSettled ? items : undefined,portalAccess: accessSettled ? granted : undefined,});}, [@@ -38,6 +39,7 @@ export function useSyncQuickNavAccount(): void {displayName,profilePictureUrl,signingSettled,+ items,count,accessSettled,granted,diff --git a/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.stories.tsx b/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.stories.tsxindex 9de692e597..b29841f43b 100644--- a/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.stories.tsx+++ b/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.stories.tsx@@ -18,6 +18,7 @@ function CreateSessionFlowDemo({return (<CreateSessionFlow+ documentPicker={<div>{initialFiles[0]?.name ?? "Choose a PDF"}</div>}selectedFiles={initialFiles}selectedUserIds={selectedUserIds}onSelectedUserIdsChange={setSelectedUserIds}@@ -34,6 +35,7 @@ const meta = {component: CreateSessionFlow,parameters: { layout: "padded" },args: {+ documentPicker: <div>contract.pdf</div>,selectedFiles: [mockFile],selectedUserIds: [],onSelectedUserIdsChange: () => {},diff --git a/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.test.tsx b/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.test.tsxnew file mode 100644index 0000000000..5c239da103--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.test.tsx@@ -0,0 +1,401 @@+import { useState } from "react";+import { fireEvent, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { MantineProvider } from "@mantine/core";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter } from "react-router-dom";+import { beforeEach, expect, it, vi } from "vitest";+import { CreateSessionFlow } from "@app/components/shared/signing/CreateSessionFlow";+import UserSelector from "@app/components/shared/UserSelector";+import { qk } from "@app/query/keys";++const viewport = vi.hoisted(() => ({ mobile: false }));+vi.mock("@app/hooks/useIsMobile", () => ({+ useIsMobile: () => viewport.mobile,+}));+beforeEach(() => {+ viewport.mobile = false;+});++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ i18n: { language: "en-US" },+ t: (key: string, fallback?: string, values?: Record<string, unknown>) =>+ (fallback ?? key).replace(/{{(\w+)}}/g, (_, name) =>+ String(values?.[name] ?? name),+ ),+ }),+}));+vi.mock("@app/auth/UseSession", () => ({+ useAuth: () => ({ user: { id: "1" } }),+}));+vi.mock("@app/api/users", () => ({ fetchUsers: vi.fn() }));+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));++const users = [+ {+ userId: 1,+ username: "owner",+ displayName: "Owner",+ teamName: "Sales",+ enabled: true,+ },+ {+ userId: 2,+ username: "bob",+ displayName: "Bob",+ teamName: "Sales",+ enabled: true,+ },+ {+ userId: 3,+ username: "alice",+ displayName: "Alice",+ teamName: "Legal",+ enabled: true,+ },+ {+ userId: 4,+ username: "internal",+ displayName: "Internal",+ teamName: "Internal",+ enabled: true,+ },+];++function Harness({+ onSubmit,+ creating = false,+ initialIds = [],+ initialFileSelected = true,+}: {+ onSubmit: ReturnType<typeof vi.fn>;+ creating?: boolean;+ initialIds?: number[];+ initialFileSelected?: boolean;+}) {+ const [ids, setIds] = useState(initialIds);+ const [date, setDate] = useState("2026-10-01");+ const [hasFile, setHasFile] = useState(initialFileSelected);+ return (+ <>+ <output aria-label="Date sent to API">{date}</output>+ <output aria-label="Selected participant IDs">{ids.join(",")}</output>+ <CreateSessionFlow+ documentPicker={+ <button disabled={creating} onClick={() => setHasFile(!hasFile)}>+ {hasFile ? "Change PDF" : "Choose PDF"}+ </button>+ }+ selectedFiles={hasFile ? [{ name: "Document.pdf", size: 100 }] : []}+ selectedUserIds={ids}+ onSelectedUserIdsChange={setIds}+ dueDate={date}+ onDueDateChange={setDate}+ creating={creating}+ onSubmit={onSubmit}+ />+ </>+ );+}++function show({+ creating = false,+ initialIds = [],+ mobile = false,+ initialFileSelected = true,+ availableUsers = users,+}: {+ creating?: boolean;+ initialIds?: number[];+ mobile?: boolean;+ initialFileSelected?: boolean;+ availableUsers?: typeof users;+} = {}) {+ viewport.mobile = mobile;+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ });+ client.setQueryData(qk.users(), availableUsers);+ const onSubmit = vi.fn();+ const content = () => (+ <QueryClientProvider client={client}>+ <MemoryRouter>+ <MantineProvider env="test">+ <Harness+ onSubmit={onSubmit}+ creating={creating}+ initialIds={initialIds}+ initialFileSelected={initialFileSelected}+ />+ </MantineProvider>+ </MemoryRouter>+ </QueryClientProvider>+ );+ const view = render(content());+ return {+ onSubmit,+ user: userEvent.setup(),+ resize: (mobile: boolean) => {+ viewport.mobile = mobile;+ view.rerender(content());+ },+ };+}++it("guides mobile creation through three pages and retains the draft when going back", async () => {+ const { user, onSubmit } = show({ mobile: true, initialFileSelected: false });+ expect(screen.getByRole("button", { name: "Next" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Participants" })).toBeDisabled();+ expect(+ screen.queryByRole("button", { name: "Send signing request" }),+ ).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Choose PDF" }));+ await user.click(screen.getByRole("button", { name: "Next" }));+ expect(screen.getByRole("button", { name: "Participants" })).toHaveAttribute(+ "aria-current",+ "step",+ );+ expect(screen.getByRole("button", { name: "Next" })).toBeDisabled();+ expect(+ screen.queryByRole("button", { name: "Change PDF" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Clear date" }),+ ).not.toBeInTheDocument();+ await user.click(screen.getByRole("checkbox", { name: /Bob/ }));+ await user.click(screen.getByRole("button", { name: "Next" }));+ expect(+ screen.getByRole("button", { name: "Dates & options" }),+ ).toHaveAttribute("aria-current", "step");+ await user.click(+ screen.getByRole("button", { name: "Sunday, October 25, 2026" }),+ );+ await user.click(+ screen.getByRole("button", {+ name: "Appearance and summary page (optional)",+ }),+ );+ await user.click(+ await screen.findByRole("switch", {+ name: "Include Signature Summary Page",+ }),+ );+ await user.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByRole("checkbox", { name: /Bob/ })).toBeChecked();+ await user.click(screen.getByRole("button", { name: "Back" }));+ await user.click(screen.getByRole("button", { name: "Change PDF" }));+ expect(screen.getByRole("button", { name: "Next" })).toBeDisabled();+ await user.click(screen.getByRole("button", { name: "Choose PDF" }));+ await user.click(screen.getByRole("button", { name: "Next" }));+ expect(screen.getByRole("checkbox", { name: /Bob/ })).toBeChecked();+ await user.click(screen.getByRole("button", { name: "Next" }));+ expect(screen.getByLabelText("Date sent to API")).toHaveTextContent(+ "2026-10-25",+ );+ expect(+ screen.getByRole("switch", { name: "Include Signature Summary Page" }),+ ).toBeChecked();+ expect(onSubmit).not.toHaveBeenCalled();+ await user.click(+ screen.getByRole("button", { name: "Send signing request" }),+ );+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ includeSummaryPage: true }),+ );+}, 15000);++it("preserves the mobile page and signature settings across desktop resizing", async () => {+ const { user, resize } = show({ mobile: true, initialIds: [2] });+ await user.click(screen.getByRole("button", { name: "Dates & options" }));+ await user.click(+ screen.getByRole("button", {+ name: "Appearance and summary page (optional)",+ }),+ );+ await user.click(+ await screen.findByRole("switch", {+ name: "Include Signature Summary Page",+ }),+ );+ resize(false);+ expect(screen.getByRole("button", { name: "Change PDF" })).toBeVisible();+ expect(screen.getByRole("checkbox", { name: /Bob/ })).toBeChecked();+ expect(+ screen.getByRole("switch", { name: "Include Signature Summary Page" }),+ ).toBeChecked();+ resize(true);+ expect(+ screen.getByRole("button", { name: "Dates & options" }),+ ).toHaveAttribute("aria-current", "step");+ expect(+ screen.getByRole("switch", { name: "Include Signature Summary Page" }),+ ).toBeChecked();+ expect(+ screen.queryByRole("button", { name: "Change PDF" }),+ ).not.toBeInTheDocument();+});++it("locks mobile navigation during submission", () => {+ show({ mobile: true, creating: true, initialIds: [2] });+ for (const label of ["Document", "Participants", "Dates & options", "Next"]) {+ expect(screen.getByRole("button", { name: label })).toBeDisabled();+ }+});++it("selects participants inline, retaining checked people while searching", async () => {+ const { user } = show();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.getAllByRole("checkbox")).toHaveLength(3);+ expect(+ screen.queryByRole("checkbox", { name: /Internal/ }),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Send signing request" }),+ ).toBeDisabled();+ await user.click(screen.getByRole("checkbox", { name: /Bob/ }));+ expect(+ screen.getByRole("button", { name: "Send signing request" }),+ ).toBeEnabled();+ const search = screen.getByRole("textbox", {+ name: "Search people or teams",+ });+ await user.type(search, "legal");+ expect(screen.getAllByRole("checkbox")).toHaveLength(1);+ await user.click(screen.getByRole("checkbox", { name: /Alice/ }));+ expect(screen.getByText("2 selected")).toHaveAttribute("role", "status");+ await user.clear(search);+ expect(screen.getByRole("checkbox", { name: /Bob/ })).toBeChecked();+ expect(screen.getByRole("checkbox", { name: /Alice/ })).toBeChecked();+ await user.click(screen.getByRole("checkbox", { name: /Bob/ }));+ await user.click(screen.getByRole("checkbox", { name: /Alice/ }));+ expect(+ screen.getByRole("button", { name: "Send signing request" }),+ ).toBeDisabled();+});+it.each([{ availableUsers: users }, { availableUsers: [users[0]] }])(+ "allows the owner as the only signer, including a directory scoped to their own account",+ async ({ availableUsers }) => {+ const { user, onSubmit } = show({ availableUsers });+ const self = screen.getByRole("checkbox", { name: "Owner (@owner) (You)" });+ await user.click(self);+ expect(screen.getByLabelText("Selected participant IDs")).toHaveTextContent(+ "1",+ );+ await user.click(+ screen.getByRole("button", { name: "Send signing request" }),+ );+ expect(onSubmit).toHaveBeenCalledOnce();+ await user.click(self);+ expect(+ screen.getByRole("button", { name: "Send signing request" }),+ ).toBeDisabled();+ },+);++it("keeps the owner selected while adding other participants", async () => {+ const { user } = show();+ await user.click(+ screen.getByRole("checkbox", { name: "Owner (@owner) (You)" }),+ );+ await user.click(screen.getByRole("checkbox", { name: /Bob/ }));+ expect(screen.getByLabelText("Selected participant IDs")).toHaveTextContent(+ "1,2",+ );+});+it("round-trips calendar dates without timezone conversion and allows clearing the deadline", async () => {+ const { user } = show();+ await user.click(+ screen.getByRole("button", { name: "Sunday, October 25, 2026" }),+ );+ expect(screen.getByLabelText("Date sent to API")).toHaveTextContent(+ "2026-10-25",+ );+ await user.click(screen.getByRole("button", { name: "Clear date" }));+ expect(screen.getByLabelText("Date sent to API")).toBeEmptyDOMElement();+ expect(screen.getByText("No due date")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Next month" }));+ expect(screen.getByText("November 2026")).toBeInTheDocument();+});++it("moves signing guidance into focusable tooltips while preserving submitted signature settings", async () => {+ const { user, onSubmit } = show({ initialIds: [2] });+ expect(+ screen.queryByText(/^Participants can sign in any order/),+ ).not.toBeInTheDocument();+ fireEvent.focus(screen.getByRole("button", { name: "About signing order" }));+ expect(screen.getByRole("tooltip")).toHaveTextContent(+ "Participants can sign in any order",+ );+ fireEvent.blur(screen.getByRole("button", { name: "About signing order" }));+ await user.click(+ screen.getByRole("button", {+ name: "Appearance and summary page (optional)",+ }),+ );+ expect(screen.queryByText(/^A summary page will/)).not.toBeInTheDocument();+ fireEvent.focus(+ await screen.findByRole("button", {+ name: "Include Signature Summary Page",+ }),+ );+ expect(screen.getByRole("tooltip")).toHaveTextContent(+ "wet signatures are unaffected",+ );+ fireEvent.blur(+ screen.getByRole("button", { name: "Include Signature Summary Page" }),+ );+ await user.click(+ screen.getByRole("switch", { name: "Include Signature Summary Page" }),+ );+ await user.click(+ screen.getByRole("button", { name: "Send signing request" }),+ );+ expect(onSubmit).toHaveBeenCalledWith(+ expect.objectContaining({ includeSummaryPage: true, showSignature: false }),+ );+});++it("locks participants, dates and sending while creation is in progress", () => {+ show({ creating: true, initialIds: [2] });+ expect(+ screen.getByRole("textbox", { name: "Search people or teams" }),+ ).toBeDisabled();+ expect(screen.getByRole("checkbox", { name: /Bob/ })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Clear date" })).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Sunday, October 25, 2026" }),+ ).toBeDisabled();+ expect(screen.getByRole("button", { name: "Next month" })).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Send signing request" }),+ ).toBeDisabled();+});++it("preserves the existing dropdown selector for other callers", async () => {+ const client = new QueryClient({+ defaultOptions: { queries: { staleTime: Infinity } },+ });+ client.setQueryData(qk.users(), users);+ const onChange = vi.fn();+ render(+ <QueryClientProvider client={client}>+ <MemoryRouter>+ <MantineProvider env="test">+ <UserSelector label="Recipients" value={[2]} onChange={onChange} />+ </MantineProvider>+ </MemoryRouter>+ </QueryClientProvider>,+ );+ const user = userEvent.setup();+ await user.click(screen.getByRole("textbox", { name: "Recipients" }));+ expect(+ screen.queryByRole("option", { name: /Internal/ }),+ ).not.toBeInTheDocument();+ await user.click(screen.getByRole("option", { name: /Alice/ }));+ expect(onChange).toHaveBeenCalledWith([2, 3]);+ await user.click(+ screen.getByRole("option", { name: "Owner (@owner) (You)" }),+ );+ expect(onChange).toHaveBeenLastCalledWith([2, 1]);+});diff --git a/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.tsx b/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.tsxindex 720ae76394..544231ce17 100644--- a/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.tsx+++ b/frontend/editor/src/core/components/shared/signing/CreateSessionFlow.tsx@@ -1,17 +1,21 @@-import { useState } from "react";-import { Stack, Text, Group, Badge } from "@mantine/core";+import { useEffect, useRef, useState, type ReactNode } from "react";+import { Collapse } from "@mantine/core";+import { DatePicker } from "@mantine/dates";import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { ActionIcon } from "@app/ui/ActionIcon";import { Icon } from "@app/ui/Icon";-import { SelectDocumentStep } from "@app/components/shared/signing/steps/SelectDocumentStep";-import { SelectParticipantsStep } from "@app/components/shared/signing/steps/SelectParticipantsStep";-import { ConfigureSignatureDefaultsStep } from "@app/components/shared/signing/steps/ConfigureSignatureDefaultsStep";-import { ReviewSessionStep } from "@app/components/shared/signing/steps/ReviewSessionStep";-import { useGroupSigningTips } from "@app/components/tooltips/useGroupSigningTips";-import { useSignatureSettingsTips } from "@app/components/tooltips/useSignatureSettingsTips";-import type { SignatureSettings } from "@app/components/tools/certSign/SignatureSettingsInput";+import { Tooltip } from "@app/ui/Tooltip";+import { SigningParticipantPicker } from "@app/components/shared/signing/SigningParticipantPicker";+import { useIsMobile } from "@app/hooks/useIsMobile";+import SignatureSettingsInput, {+ type SignatureSettings,+} from "@app/components/tools/certSign/SignatureSettingsInput";import type { FileState } from "@app/types/file";+import "@app/components/shared/signing/signing.css";interface CreateSessionFlowProps {+ documentPicker: ReactNode;selectedFiles: FileState[];selectedUserIds: number[];onSelectedUserIdsChange: (userIds: number[]) => void;@@ -21,89 +25,8 @@ interface CreateSessionFlowProps {onSubmit: (signatureSettings: SignatureSettings) => void;}-interface StepWrapperProps {- number: number;- title: string;- isActive: boolean;- isCompleted: boolean;- children: React.ReactNode;-}--const StepWrapper: React.FC<StepWrapperProps> = ({- number,- title,- isActive,- isCompleted,- children,-}) => {- const { t } = useTranslation();-- return (- <div- style={{- padding: "16px",- border: isActive- ? "2px solid var(--mantine-color-blue-6)"- : "1px solid var(--mantine-color-default-border)",- borderRadius: "var(--mantine-radius-default)",- backgroundColor: isActive- ? "var(--mantine-color-blue-light)"- : isCompleted- ? "var(--mantine-color-gray-light)"- : "transparent",- // Pending steps recede via a muted text colour rather than opacity,- // which would drag their labels below the contrast floor.- color:- !isActive && !isCompleted ? "var(--c-text-muted)" : "var(--c-text)",- }}- >- <Group gap="sm" mb={isActive ? "md" : 0}>- <div- style={{- width: "32px",- height: "32px",- borderRadius: "50%",- display: "flex",- alignItems: "center",- justifyContent: "center",- backgroundColor: isCompleted- ? "var(--mantine-color-green-6)"- : isActive- ? "var(--mantine-color-blue-6)"- : "var(--mantine-color-gray-4)",- color: "white",- fontWeight: 600,- fontSize: "14px",- }}- >- {isCompleted ? <Icon name="check" size={18} /> : number}- </div>- <div style={{ flex: 1 }}>- <Text size="sm" fw={600}>- {t("groupSigning.steps.stepLabel", "Step {{number}}", { number })}- </Text>- <Text size="sm" c="dimmed">- {title}- </Text>- </div>- {isActive && (- <Badge color="blue" variant="light">- {t("groupSigning.steps.current", "Current")}- </Badge>- )}- {isCompleted && (- <Badge color="green" variant="light">- {t("groupSigning.steps.completed", "Completed")}- </Badge>- )}- </Group>-- {isActive && children}- </div>- );-};--export const CreateSessionFlow: React.FC<CreateSessionFlowProps> = ({+export function CreateSessionFlow({+ documentPicker,selectedFiles,selectedUserIds,onSelectedUserIdsChange,@@ -111,137 +34,223 @@ export const CreateSessionFlow: React.FC<CreateSessionFlowProps> = ({onDueDateChange,creating,onSubmit,-}) => {- const { t } = useTranslation();- const [currentStep, setCurrentStep] = useState(1);-- // Signature settings state- const [signatureSettings, setSignatureSettings] = useState<SignatureSettings>(- {- showSignature: false,- pageNumber: 1,- reason: "",- location: "",- showLogo: false,- includeSummaryPage: false,- },- );-- const groupSigningTips = useGroupSigningTips();- const signatureSettingsTips = useSignatureSettingsTips();-- const hasValidFile = selectedFiles.length === 1;- const selectedFile = hasValidFile ? selectedFiles[0] : null;-- const steps = [- {- number: 1,- title: t("groupSigning.steps.selectDocument.title", "Select Document"),- tooltip: groupSigningTips,- },- {- number: 2,- title: t(- "groupSigning.steps.selectParticipants.title",- "Choose Participants",- ),- tooltip: null,- },- {- number: 3,- title: t(- "groupSigning.steps.configureDefaults.title",- "Configure Signature Settings",- ),- tooltip: signatureSettingsTips,- },- {- number: 4,- title: t("groupSigning.steps.review.titleShort", "Review & Send"),- tooltip: null,- },+}: CreateSessionFlowProps) {+ const { t, i18n } = useTranslation();+ const isMobile = useIsMobile();+ const [step, setStep] = useState(0);+ const stepsRef = useRef<HTMLElement>(null);+ const [showSettings, setShowSettings] = useState(false);+ const [settings, setSettings] = useState<SignatureSettings>({+ showSignature: false,+ pageNumber: 1,+ reason: "",+ location: "",+ showLogo: false,+ includeSummaryPage: false,+ });+ const file = selectedFiles.length === 1 ? selectedFiles[0] : null;+ const activeStep = !file+ ? 0+ : selectedUserIds.length === 0 && step === 2+ ? 1+ : step;+ const stepLabels = [+ t("signWorkspace.document", "Document"),+ t("signWorkspace.participants", "Participants"),+ t("signWorkspace.datesAndOptions", "Dates & options"),];-+ useEffect(() => {+ setStep(activeStep);+ if (isMobile) stepsRef.current?.focus();+ }, [activeStep, isMobile]);+ const sendButton = (+ <Button+ size="md"+ fullWidth+ disabled={!file || selectedUserIds.length === 0 || creating}+ loading={creating}+ onClick={() => onSubmit(settings)}+ >+ {t("signMenu.send", "Send signing request")}+ </Button>+ );return (- <div className="quick-access-popout__panel">- <Stack gap="md">- {/* Step 1: Select Document */}- <StepWrapper- number={1}- title={steps[0].title}- isActive={currentStep === 1}- isCompleted={currentStep > 1}- >- {hasValidFile ? (- <SelectDocumentStep- selectedFiles={selectedFiles}- onNext={() => setCurrentStep(2)}- />- ) : (- <div style={{ padding: "12px 0" }}>- <Text size="sm" c="dimmed" ta="center">- {t(- "groupSigning.steps.selectDocument.noFile",- "Please select a single PDF file from your active files to create a signing session.",- )}- </Text>- </div>- )}- </StepWrapper>-- {/* Step 2: Select Participants */}- <StepWrapper- number={2}- title={steps[1].title}- isActive={currentStep === 2}- isCompleted={currentStep > 2}- >- <SelectParticipantsStep- selectedUserIds={selectedUserIds}- onSelectedUserIdsChange={onSelectedUserIdsChange}- onBack={() => setCurrentStep(1)}- onNext={() => setCurrentStep(3)}- disabled={creating}- />- </StepWrapper>-- {/* Step 3: Configure Signature Defaults */}- <StepWrapper- number={3}- title={steps[2].title}- isActive={currentStep === 3}- isCompleted={currentStep > 3}+ <div+ className="signing-workspace__create"+ data-mobile={isMobile || undefined}+ >+ {isMobile && (+ <nav+ className="signing-request__steps"+ aria-label={t("signWorkspace.requestSteps", "Signing request steps")}+ ref={stepsRef}+ tabIndex={-1}>- <ConfigureSignatureDefaultsStep- settings={signatureSettings}- onSettingsChange={setSignatureSettings}- onBack={() => setCurrentStep(2)}- onNext={() => setCurrentStep(4)}+ <ol>+ {stepLabels.map((label, index) => (+ <li key={label}>+ <button+ type="button"+ aria-current={activeStep === index ? "step" : undefined}+ disabled={+ creating ||+ (index > 0 && !file) ||+ (index > 1 && selectedUserIds.length === 0)+ }+ onClick={() => setStep(index)}+ >+ <span aria-hidden="true">{index + 1}</span>+ {label}+ </button>+ </li>+ ))}+ </ol>+ </nav>+ )}+ <div+ className="signing-request__document"+ hidden={isMobile && activeStep !== 0}+ >+ {documentPicker}+ </div>+ <div className="signing-request" hidden={isMobile && activeStep === 0}>+ <div hidden={isMobile && activeStep !== 1}>+ <SigningParticipantPicker+ value={selectedUserIds}+ onChange={onSelectedUserIdsChange}disabled={creating}/>- </StepWrapper>-- {/* Step 4: Review & Send */}- <StepWrapper- number={4}- title={steps[3].title}- isActive={currentStep === 4}- isCompleted={false}+ </div>+ <div+ className="signing-request__options"+ hidden={isMobile && activeStep !== 2}>- {selectedFile && (- <ReviewSessionStep- selectedFile={selectedFile}- participantCount={selectedUserIds.length}- signatureSettings={signatureSettings}- dueDate={dueDate}- onDueDateChange={onDueDateChange}- onBack={() => setCurrentStep(3)}- onSubmit={() => onSubmit(signatureSettings)}+ <fieldset className="signing-request__calendar" disabled={creating}>+ <legend>+ {t("signMenu.dueDate", "Due date (optional)")}+ <Tooltip+ content={t(+ "signWorkspace.dueDateHelp",+ "This is a target date. Participants can still sign after it.",+ )}+ >+ <ActionIcon+ variant="quiet"+ aria-label={t(+ "signWorkspace.dueDateHelpLabel",+ "About due dates",+ )}+ >+ <Icon name="info" size={16} />+ </ActionIcon>+ </Tooltip>+ </legend>+ <div className="signing-request__date-value">+ <span aria-live="polite">+ {dueDate+ ? new Intl.DateTimeFormat(i18n.language, {+ dateStyle: "long",+ }).format(new Date(`${dueDate}T12:00:00`))+ : t("signWorkspace.noDueDate", "No due date")}+ </span>+ {dueDate && (+ <Button+ variant="tertiary"+ disabled={creating}+ onClick={() => onDueDateChange("")}+ >+ {t("signWorkspace.clearDate", "Clear date")}+ </Button>+ )}+ </div>+ <DatePicker+ value={dueDate || null}+ onChange={(date) => {+ if (!creating) onDueDateChange(date ?? "");+ }}+ allowDeselect+ highlightToday+ size="md"+ maxLevel="month"+ nextLabel={t("signWorkspace.nextMonth", "Next month")}+ previousLabel={t("signWorkspace.previousMonth", "Previous month")}+ monthLabelFormat={(date) =>+ new Intl.DateTimeFormat(i18n.language, {+ month: "long",+ year: "numeric",+ }).format(new Date(`${date}T12:00:00`))+ }+ weekdayFormat={(date) =>+ new Intl.DateTimeFormat(i18n.language, {+ weekday: "short",+ }).format(new Date(`${date}T12:00:00`))+ }+ getDayAriaLabel={(date) =>+ new Intl.DateTimeFormat(i18n.language, {+ dateStyle: "full",+ }).format(new Date(`${date}T12:00:00`))+ }+ classNames={{+ month: "signing-request__month",+ day: "signing-request__day",+ calendarHeader: "signing-request__month-header",+ }}+ />+ </fieldset>+ <Button+ variant="tertiary"+ onClick={() => setShowSettings((shown) => !shown)}+ aria-expanded={showSettings}+ justify="between"+ rightSection={+ <Icon+ name={showSettings ? "chevron-up" : "chevron-down"}+ size={18}+ />+ }+ >+ {t("signMenu.settings", "Appearance and summary page (optional)")}+ </Button>+ <Collapse in={showSettings}>+ <SignatureSettingsInput+ value={settings}+ onChange={setSettings}disabled={creating}/>+ </Collapse>+ </div>+ {!isMobile && sendButton}+ </div>+ {isMobile && (+ <div className="signing-request__step-actions">+ {activeStep > 0 && (+ <Button+ size="md"+ variant="secondary"+ disabled={creating}+ onClick={() => setStep(activeStep - 1)}+ >+ {t("back", "Back")}+ </Button>+ )}+ {activeStep === 2 ? (+ sendButton+ ) : (+ <Button+ size="md"+ fullWidth+ disabled={+ creating ||+ (activeStep === 0 ? !file : selectedUserIds.length === 0)+ }+ onClick={() => setStep(activeStep + 1)}+ rightSection={<Icon name="arrow-right" size={18} />}+ >+ {t("signWorkspace.nextStep", "Next")}+ </Button>)}- </StepWrapper>- </Stack>+ </div>+ )}</div>);-};+}diff --git a/frontend/editor/src/core/components/shared/signing/SharedSigningLauncher.tsx b/frontend/editor/src/core/components/shared/signing/SharedSigningLauncher.tsxindex da288249d6..d22f05378d 100644--- a/frontend/editor/src/core/components/shared/signing/SharedSigningLauncher.tsx+++ b/frontend/editor/src/core/components/shared/signing/SharedSigningLauncher.tsx@@ -4,24 +4,27 @@ import { useTranslation } from "react-i18next";import { Icon } from "@app/ui/Icon";import { useGroupSigningEnabled } from "@app/hooks/useGroupSigningEnabled";import { useSigningSessions } from "@app/hooks/signing/useSigningSessions";-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";+import { useOpenSigning } from "@app/hooks/signing/useOpenSigning";/*** Content for the optional "Request signatures" step in the Sign tool: a short- * explanation plus a link to the standalone Shared Signing tool. Renders+ * explanation plus a link to the signing workspace. Renders* nothing unless group signing is enabled on the server.*/export default function SharedSigningLauncher() {const { t } = useTranslation();const groupSigningEnabled = useGroupSigningEnabled();- const { handleToolSelect } = useToolWorkflow();+ const openSigning = useOpenSigning();// Surfaces the count of sign requests awaiting this user's action.const { signRequests } = useSigningSessions({enabled: groupSigningEnabled,});const pendingCount = signRequests.filter(- (req) => req.myStatus !== "SIGNED" && req.myStatus !== "DECLINED",+ (req) =>+ !req.finalized &&+ req.myStatus !== "SIGNED" &&+ req.myStatus !== "DECLINED",).length;if (!groupSigningEnabled) return null;@@ -45,7 +48,7 @@ export default function SharedSigningLauncher() {</Badge>) : undefined}- onClick={() => handleToolSelect("sharedSign")}+ onClick={() => openSigning("create")}>{t("sign.sharedSigningOpen", "Open shared signing")}</Button>diff --git a/frontend/editor/src/core/components/shared/signing/SignMenu.test.tsx b/frontend/editor/src/core/components/shared/signing/SignMenu.test.tsxnew file mode 100644index 0000000000..3d9c80357e--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SignMenu.test.tsx@@ -0,0 +1,340 @@+import { fireEvent, render, screen, within } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import { SignMenu } from "@app/components/shared/signing/SignMenu";+import {+ collectSigningItems,+ type SigningMenuItem,+} from "@app/utils/signingItems";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));++const incoming: SigningMenuItem = {+ kind: "request",+ sessionId: "incoming",+ documentName: "Contract.pdf",+ ownerUsername: "Alice",+ createdAt: "2026-09-24",+ dueDate: "",+ myStatus: "PENDING",+ unread: true,+};+const owned: SigningMenuItem = {+ kind: "session",+ sessionId: "owned",+ documentName: "Owned.pdf",+ createdAt: "2026-09-24",+ participantCount: 2,+ signedCount: 1,+ finalized: false,+ unread: true,+};+function setup(items: SigningMenuItem[] = [], sharedSign?: string) {+ const onSelect = vi.fn();+ const onOpenSigning = vi.fn();+ const onClose = vi.fn();+ const menu = (rows: SigningMenuItem[]) => (+ <SignMenu+ opened+ onClose={onClose}+ onSelect={onSelect}+ onOpenSigning={onOpenSigning}+ reasons={{ sharedSign }}+ items={rows}+ >+ <button>Sign</button>+ </SignMenu>+ );+ const view = render(menu(items));+ return {+ ...view,+ onSelect,+ onOpenSigning,+ onClose,+ updateItems: (rows: SigningMenuItem[]) => view.rerender(menu(rows)),+ };+}++it("shows one owner session in the popover as its action changes from signing to finalization", () => {+ const request = { ...incoming, sessionId: owned.sessionId };+ const rows = collectSigningItems([request], [owned]).map((item) => ({+ ...item,+ unread: true,+ }));+ const { onOpenSigning, updateItems } = setup(rows);+ const active = within(screen.getByRole("region", { name: "Active" }));+ expect(active.getAllByRole("button")).toHaveLength(1);+ fireEvent.click(+ active.getByRole("button", { name: /Owned.pdf.*Needs your signature/ }),+ );+ expect(onOpenSigning).toHaveBeenCalledWith({+ kind: "session",+ sessionId: "owned",+ });+ expect(+ screen.getByRole("button", { name: /^Unread\s*1$/ }),+ ).toBeInTheDocument();+ updateItems(+ collectSigningItems(+ [{ ...request, myStatus: "SIGNED" }],+ [{ ...owned, signedCount: 2 }],+ ).map((item) => ({ ...item, unread: false })),+ );+ expect(active.getAllByRole("button")).toHaveLength(1);+ expect(+ active.getByRole("button", { name: /Owned.pdf.*Ready to finalize/ }),+ ).toBeInTheDocument();+});++it("filters unread invitations and ready owner sessions, updating the count when read", () => {+ const items: SigningMenuItem[] = [+ incoming,+ { ...owned, signedCount: 2 },+ { ...incoming, sessionId: "read", documentName: "Read.pdf", unread: false },+ {+ ...owned,+ sessionId: "closed",+ documentName: "Closed.pdf",+ finalized: true,+ },+ ];+ const { updateItems, onOpenSigning } = setup(items);+ fireEvent.click(screen.getByRole("button", { name: /^Unread\s*2$/ }));+ const list = within(screen.getByRole("region", { name: "Unread" }));+ expect(list.getAllByRole("button")).toHaveLength(2);+ expect(+ list.getByRole("button", { name: /Owned.pdf.*Ready to finalize/ }),+ ).toBeInTheDocument();+ expect(+ list.queryByRole("button", { name: /Read.pdf|Closed.pdf/ }),+ ).not.toBeInTheDocument();+ fireEvent.change(screen.getByRole("searchbox"), {+ target: { value: "Owned" },+ });+ expect(list.getAllByRole("button")).toHaveLength(1);+ expect(screen.getByRole("button", { name: /^Unread\s*2$/ })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ expect(onOpenSigning).not.toHaveBeenCalled();+ fireEvent.change(screen.getByRole("searchbox"), { target: { value: "" } });+ updateItems(items.map((item) => ({ ...item, unread: false })));+ expect(screen.getByRole("button", { name: /^Unread\s*0$/ })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ expect(screen.getByText("You're all caught up")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Active" }));+ expect(+ screen.getByRole("button", { name: /Owned.pdf.*Ready to finalize/ }),+ ).toBeInTheDocument();+});++it("keeps personal signing accessible when shared signing is disabled", () => {+ const { onSelect } = setup([], "Disabled on this server");+ expect(screen.getByRole("dialog", { name: "Sign" })).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Request signatures" }),+ ).toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: /Personal signature/ }));+ expect(onSelect).toHaveBeenCalledWith("sign");+});++it("keeps expired and server-closed requests out of Active and the unread count", () => {+ setup([+ { ...incoming, closed: true, documentName: "Viewer.pdf" },+ {+ ...incoming,+ sessionId: "expired",+ accessExpired: true,+ documentName: "Expired.pdf",+ },+ ]);+ expect(+ screen.getByRole("button", { name: /^Unread\s*0$/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Viewer.pdf|Expired.pdf/ }),+ ).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Completed" }));+ expect(+ screen.getByRole("button", { name: /Viewer.pdf.*Closed/ }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /Expired.pdf.*Access expired/ }),+ ).toBeInTheDocument();+});++it("opens request creation, expanded sessions and certificate signing directly", () => {+ const { onSelect, onOpenSigning, onClose } = setup();+ fireEvent.click(screen.getByRole("button", { name: "Request signatures" }));+ expect(onOpenSigning).toHaveBeenLastCalledWith("create");+ fireEvent.click(+ screen.getByRole("button", { name: "Expand signing sessions" }),+ );+ expect(onOpenSigning).toHaveBeenLastCalledWith("list");+ fireEvent.click(screen.getByRole("button", { name: /Digital signature/ }));+ expect(onSelect).toHaveBeenCalledWith("certSign");+ expect(onClose).toHaveBeenCalledTimes(3);+});++it("shows requests and owned sessions together, with unread dots independent of readiness", () => {+ setup([+ incoming,+ owned,+ {+ ...owned,+ sessionId: "ready",+ documentName: "Ready.pdf",+ signedCount: 2,+ unread: false,+ },+ {+ ...owned,+ sessionId: "waiting",+ documentName: "Waiting.pdf",+ signedCount: 0,+ unread: false,+ },+ ]);+ expect(+ screen.queryByRole("button", { name: /Needs action/ }),+ ).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Active" })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ const list = within(screen.getByRole("region", { name: "Active" }));+ expect(list.getAllByRole("button")).toHaveLength(4);+ expect(list.getAllByRole("img", { name: /New activity/ })).toHaveLength(2);+ const ready = list.getByRole("button", {+ name: /Ready.pdf.*Ready to finalize/,+ });+ expect(ready).toBeInTheDocument();+ expect(+ within(ready).queryByRole("img", { name: /New activity/ }),+ ).not.toBeInTheDocument();+ expect(list.getByRole("button", { name: /Waiting.pdf/ })).toBeInTheDocument();+});+it("opens the selected role by identity and closes the popover", () => {+ const { onOpenSigning, onSelect, onClose } = setup([incoming]);+ fireEvent.click(+ screen.getByRole("button", { name: /Contract.pdf.*Needs your signature/ }),+ );+ expect(onOpenSigning).toHaveBeenCalledWith({+ kind: "request",+ sessionId: "incoming",+ });+ expect(onSelect).not.toHaveBeenCalled();+ expect(onClose).toHaveBeenCalledTimes(1);+});++it("includes a newly finalized document in Unread and Completed, but never Active", () => {+ const completed: SigningMenuItem = {+ ...incoming,+ finalized: true,+ closed: true,+ myStatus: "SIGNED",+ };+ const { updateItems } = setup([completed]);+ expect(+ screen.queryByRole("button", { name: /Contract.pdf.*Finalized/ }),+ ).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /^Unread\s*1$/ }));+ expect(+ screen.getByRole("button", { name: /Contract.pdf.*Finalized/ }),+ ).toBeInTheDocument();+ updateItems([{ ...completed, unread: false }]);+ expect(+ screen.queryByRole("button", { name: /Contract.pdf.*Finalized/ }),+ ).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Completed" }));+ expect(+ screen.getByRole("button", { name: /Contract.pdf.*Finalized/ }),+ ).toBeInTheDocument();+});++it("shows every active item and searches without marking hidden items as read", () => {+ const requests = Array.from({ length: 9 }, (_, index) => ({+ ...incoming,+ sessionId: `request-${index}`,+ documentName: `Document ${index}.pdf`,+ }));+ setup([...requests, { ...owned, unread: false }]);+ fireEvent.click(screen.getByRole("button", { name: "Active" }));+ expect(+ within(screen.getByRole("region", { name: "Active" })).getAllByRole(+ "button",+ ),+ ).toHaveLength(10);+ fireEvent.change(screen.getByRole("searchbox"), {+ target: { value: "Document 8" },+ });+ expect(+ screen.getByRole("button", { name: /Document 8.pdf/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Document 0.pdf/ }),+ ).not.toBeInTheDocument();+ expect(screen.getByRole("img", { name: /New activity/ })).toBeInTheDocument();+ fireEvent.change(screen.getByRole("searchbox"), {+ target: { value: "alice" },+ });+ expect(+ within(screen.getByRole("region", { name: "Active" })).getAllByRole(+ "button",+ ),+ ).toHaveLength(9);+});++it("keeps submitted requests active and places finalized or declined requests in Completed", () => {+ setup([+ {+ ...incoming,+ documentName: "Submitted.pdf",+ myStatus: "SIGNED",+ unread: false,+ },+ { ...owned, finalized: true, unread: false },+ {+ ...incoming,+ sessionId: "declined",+ documentName: "Declined.pdf",+ myStatus: "DECLINED",+ unread: false,+ },+ ]);+ fireEvent.click(screen.getByRole("button", { name: "Active" }));+ expect(+ screen.getByRole("button", { name: /Submitted.pdf.*Submitted/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Declined.pdf/ }),+ ).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Completed" }));+ expect(+ screen.getByRole("button", { name: /Owned.pdf.*Finalized/ }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /Declined.pdf.*Declined/ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Submitted.pdf/ }),+ ).not.toBeInTheDocument();+});++it("allows editing search with Home/End and restores the trigger on Escape", () => {+ const { onClose } = setup([incoming]);+ const search = screen.getByRole("searchbox");+ search.focus();+ fireEvent.keyDown(search, { key: "Home" });+ expect(search).toHaveFocus();+ fireEvent.keyDown(search, { key: "End" });+ expect(search).toHaveFocus();+ fireEvent.keyDown(search, { key: "Escape" });+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(screen.getByRole("button", { name: "Sign" })).toHaveFocus();+});diff --git a/frontend/editor/src/core/components/shared/signing/SignMenu.tsx b/frontend/editor/src/core/components/shared/signing/SignMenu.tsxnew file mode 100644index 0000000000..f69236cff4--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SignMenu.tsx@@ -0,0 +1,69 @@+import { useTranslation } from "react-i18next";+import { Dropdown, type DropdownTriggerProps } from "@app/ui/Dropdown";+import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";+import type { ToolId } from "@app/types/toolId";+import type { SigningIntent } from "@app/utils/pendingSigningIntent";+import type { SigningMenuItem } from "@app/utils/signingItems";+import { SignMenuPersonalSection } from "@app/components/shared/signing/SignMenuPersonalSection";+import { SignMenuSessionsSection } from "@app/components/shared/signing/SignMenuSessionsSection";+import { useSignMenuSessions } from "@app/components/shared/signing/useSignMenuSessions";+import "@app/components/shared/signing/signing.css";++interface SignMenuProps {+ children: DropdownTriggerProps["children"];+ opened: boolean;+ onClose: () => void;+ onSelect: (tool: ToolId) => void;+ onOpenSigning: (intent: SigningIntent) => void;+ reasons: QuickNavToolReasons;+ items: SigningMenuItem[];+}++/** The global rail cannot depend on either app's file, authentication or Mantine providers. */+export function SignMenu({+ children,+ opened,+ onClose,+ onSelect,+ onOpenSigning,+ reasons,+ items,+}: SignMenuProps) {+ const { t } = useTranslation();+ const sessions = useSignMenuSessions(items, opened);+ const openSigning = (intent: SigningIntent) => {+ onClose();+ onOpenSigning(intent);+ };+ const selectTool = (tool: ToolId) => {+ onClose();+ onSelect(tool);+ };++ return (+ <Dropdown.Root+ open={opened}+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ align="start"+ >+ <Dropdown.Trigger popupRole="dialog">{children}</Dropdown.Trigger>+ <Dropdown.Menu+ className={`sign-menu${reasons.sharedSign ? " sign-menu--unavailable" : ""}`}+ width="min(400px, calc(100vw - 24px))"+ autoFocus+ role="dialog"+ ariaLabel={t("signMenu.title", "Sign")}+ placement="side"+ >+ <SignMenuPersonalSection reasons={reasons} onSelectTool={selectTool} />+ <SignMenuSessionsSection+ sessions={sessions}+ unavailableReason={reasons.sharedSign}+ onOpenSigning={openSigning}+ />+ </Dropdown.Menu>+ </Dropdown.Root>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SignMenuPersonalSection.tsx b/frontend/editor/src/core/components/shared/signing/SignMenuPersonalSection.tsxnew file mode 100644index 0000000000..34a32c7e91--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SignMenuPersonalSection.tsx@@ -0,0 +1,76 @@+import { useTranslation } from "react-i18next";+import { Icon, type IconName } from "@app/ui/Icon";+import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";+import type { ToolId } from "@app/types/toolId";++interface SignToolButtonProps {+ icon: IconName;+ title: string;+ hint: string;+ unavailableReason?: string;+ onClick: () => void;+}++function SignToolButton({+ icon,+ title,+ hint,+ unavailableReason,+ onClick,+}: SignToolButtonProps) {+ return (+ <button+ type="button"+ className="sign-menu__tool"+ disabled={Boolean(unavailableReason)}+ onClick={onClick}+ title={unavailableReason}+ >+ <Icon name={icon} size={20} />+ <strong>{title}</strong>+ <span>{hint}</span>+ </button>+ );+}++interface SignMenuPersonalSectionProps {+ reasons: QuickNavToolReasons;+ onSelectTool: (tool: ToolId) => void;+}++export function SignMenuPersonalSection({+ reasons,+ onSelectTool,+}: SignMenuPersonalSectionProps) {+ const { t } = useTranslation();+ const unavailable = [+ ...new Set([reasons.sign, reasons.certSign].filter(Boolean)),+ ];+ return (+ <section+ className="sign-menu__personal"+ aria-label={t("signWorkspace.personalHeading", "Sign a document")}+ >+ <h2>{t("signWorkspace.personalHeading", "Sign a document")}</h2>+ <div className="sign-menu__tools">+ <SignToolButton+ icon="pen-tool"+ title={t("signMenu.personalTitle", "Personal signature")}+ hint={t("signMenu.personalHint", "Draw, type or upload")}+ unavailableReason={reasons.sign}+ onClick={() => onSelectTool("sign")}+ />+ <SignToolButton+ icon="shield-check"+ title={t("signMenu.certificateTitle", "Digital signature")}+ hint={t("signMenu.certificateHint", "Use a certificate")}+ unavailableReason={reasons.certSign}+ onClick={() => onSelectTool("certSign")}+ />+ </div>+ {unavailable.length > 0 && (+ <p className="sign-menu__hint">{unavailable.join(" · ")}</p>+ )}+ </section>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SignMenuSessionsSection.tsx b/frontend/editor/src/core/components/shared/signing/SignMenuSessionsSection.tsxnew file mode 100644index 0000000000..16a20b5016--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SignMenuSessionsSection.tsx@@ -0,0 +1,169 @@+import { useTranslation } from "react-i18next";+import { Icon } from "@app/ui/Icon";+import { Tabs } from "@app/ui/Tabs";+import { Tooltip } from "@app/ui/Tooltip";+import type { SigningIntent } from "@app/utils/pendingSigningIntent";+import type { SigningMenuItem } from "@app/utils/signingItems";+import { SigningSessionRow } from "@app/components/shared/signing/SigningSessionRow";+import type {+ SessionTab,+ SignMenuSessions,+} from "@app/components/shared/signing/useSignMenuSessions";++interface SessionsHeaderProps {+ disabled: boolean;+ onOpenSigning: (intent: SigningIntent) => void;+}++function SessionsHeader({ disabled, onOpenSigning }: SessionsHeaderProps) {+ const { t } = useTranslation();+ return (+ <div className="sign-menu__session-header">+ <div className="sign-menu__heading">+ <h2>{t("signMenu.sessions", "Signing sessions")}</h2>+ <Tooltip content={t("signWorkspace.expand", "Expand signing sessions")}>+ <button+ type="button"+ className="sign-menu__icon-button"+ aria-label={t("signWorkspace.expand", "Expand signing sessions")}+ disabled={disabled}+ onClick={() => onOpenSigning("list")}+ >+ <Icon name="maximize-2" size={18} />+ </button>+ </Tooltip>+ </div>+ <button+ type="button"+ className="sign-menu__request"+ disabled={disabled}+ onClick={() => onOpenSigning("create")}+ >+ <Icon name="plus" size={18} />+ {t("signMenu.request", "Request signatures")}+ </button>+ </div>+ );+}++function SessionFilters({ sessions }: { sessions: SignMenuSessions }) {+ const { t } = useTranslation();+ const searchLabel = t("signMenu.search", "Find a document or person");+ return (+ <div className="sign-menu__filters">+ <Tabs+ items={sessions.tabs}+ activeKey={sessions.tab}+ onChange={sessions.setTab}+ variant="underline"+ ariaLabel={t("signMenu.sessionFilter", "Session views")}+ className="sign-menu__tabs"+ />+ <div className="sign-menu__search">+ <Icon name="search" size={16} />+ <input+ type="search"+ value={sessions.query}+ onChange={(event) => sessions.setQuery(event.currentTarget.value)}+ placeholder={searchLabel}+ aria-label={searchLabel}+ />+ </div>+ </div>+ );+}++function EmptySessions({ query, tab }: { query: string; tab: SessionTab }) {+ const { t } = useTranslation();+ const emptyByTab: Record<SessionTab, string> = {+ active: t("signMenu.noActive", "No active sessions"),+ unread: t("signMenu.noUnread", "You're all caught up"),+ closed: t("signMenu.noCompleted", "No completed sessions"),+ };+ return (+ <div className="sign-menu__empty" role="status">+ <Icon name="search" size={24} />+ <strong>+ {query+ ? t("signMenu.noMatches", "No matching sessions")+ : emptyByTab[tab]}+ </strong>+ </div>+ );+}++interface SessionResultsProps {+ sessions: SignMenuSessions;+ onOpenSigning: (intent: SigningIntent) => void;+}++function SessionResults({ sessions, onOpenSigning }: SessionResultsProps) {+ const { tab, tabs, rows, query } = sessions;+ return (+ <div+ key={tab}+ className="sign-menu__results"+ tabIndex={0}+ role="region"+ aria-label={tabs.find((item) => item.key === tab)?.label}+ >+ {rows.length > 0 ? (+ <SessionList rows={rows} onOpenSigning={onOpenSigning} />+ ) : (+ <EmptySessions query={query} tab={tab} />+ )}+ </div>+ );+}++interface SessionListProps {+ rows: SigningMenuItem[];+ onOpenSigning: (intent: SigningIntent) => void;+}++function SessionList({ rows, onOpenSigning }: SessionListProps) {+ return (+ <ul className="sign-menu__list">+ {rows.map((item) => (+ <SigningSessionRow+ key={`${item.kind}-${item.sessionId}`}+ item={item}+ onOpenSigning={onOpenSigning}+ />+ ))}+ </ul>+ );+}++interface SignMenuSessionsSectionProps {+ sessions: SignMenuSessions;+ unavailableReason?: string;+ onOpenSigning: (intent: SigningIntent) => void;+}++export function SignMenuSessionsSection({+ sessions,+ unavailableReason,+ onOpenSigning,+}: SignMenuSessionsSectionProps) {+ const { t } = useTranslation();+ return (+ <section+ className="sign-menu__sessions"+ aria-label={t("signMenu.sessions", "Signing sessions")}+ >+ <SessionsHeader+ disabled={Boolean(unavailableReason)}+ onOpenSigning={onOpenSigning}+ />+ {unavailableReason ? (+ <p className="sign-menu__hint">{unavailableReason}</p>+ ) : (+ <>+ <SessionFilters sessions={sessions} />+ <SessionResults sessions={sessions} onOpenSigning={onOpenSigning} />+ </>+ )}+ </section>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SigningActivityDot.tsx b/frontend/editor/src/core/components/shared/signing/SigningActivityDot.tsxnew file mode 100644index 0000000000..8d05a6af71--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningActivityDot.tsx@@ -0,0 +1,19 @@+import { useTranslation } from "react-i18next";+import "@app/components/shared/signing/signing.css";++/** Unread activity indicator with the same accessible description in every signing entry point. */+export function SigningActivityDot({ className = "" }: { className?: string }) {+ const { t } = useTranslation();+ const label = t(+ "signMenu.newActivity",+ "New activity since you last viewed this session",+ );+ return (+ <span+ className={`signing-activity-dot ${className}`}+ role="img"+ aria-label={label}+ title={label}+ />+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SigningDocumentPicker.test.tsx b/frontend/editor/src/core/components/shared/signing/SigningDocumentPicker.test.tsxnew file mode 100644index 0000000000..17e9743e7f--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningDocumentPicker.test.tsx@@ -0,0 +1,174 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { useState } from "react";+import { MantineProvider } from "@mantine/core";+import { beforeEach, beforeAll, afterAll, expect, it, vi } from "vitest";+import { SigningDocumentPicker } from "@app/components/shared/signing/SigningDocumentPicker";+import {+ createNewStirlingFileStub,+ createStirlingFile,+} from "@app/types/fileContext";++const state = vi.hoisted(() => ({+ open: vi.fn(),+ add: vi.fn(),+ files: vi.fn(),+ stubs: vi.fn(),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));+vi.mock("@app/contexts/FileContext", () => ({+ useAllFiles: () => ({ fileStubs: state.stubs() }),+}));+vi.mock("@app/contexts/file/fileHooks", () => ({+ useFileSelectors: () => ({ getFiles: state.files }),+}));+vi.mock("@app/contexts/FilesModalContext", () => ({+ useFilesModalContext: () => ({ openFilesModal: state.open }),+}));+vi.mock("@app/hooks/useFileHandler", () => ({+ useFileHandler: () => ({ addFiles: state.add }),+}));+vi.mock("@app/hooks/useFileThumbnail", () => ({+ useFileThumbnail: () => ({+ thumbnail: null,+ isEncrypted: false,+ isGenerating: false,+ }),+}));+vi.mock("@app/components/shared/filePreview/DocumentThumbnail", () => ({+ default: () => null,+}));++const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;+beforeAll(() => {+ HTMLElement.prototype.scrollIntoView = vi.fn();+});+afterAll(() => {+ HTMLElement.prototype.scrollIntoView = originalScrollIntoView;+});++beforeEach(() => {+ vi.clearAllMocks();+ state.stubs.mockReturnValue([]);+ state.files.mockReturnValue([]);+});++function show(value: string | null = null) {+ const onChange = vi.fn();+ const onLoadingChange = vi.fn();+ function Picker() {+ const [selected, setSelected] = useState(value);+ return (+ <SigningDocumentPicker+ value={selected}+ onChange={(id) => {+ setSelected(id);+ onChange(id);+ }}+ disabled={false}+ loading={false}+ onLoadingChange={onLoadingChange}+ />+ );+ }+ render(+ <MantineProvider env="test">+ <Picker />+ </MantineProvider>,+ );+ return { onChange, onLoadingChange };+}++it("shows only PDFs and selects an open document without importing it", () => {+ const first = createNewStirlingFileStub(new File(["one"], "First.pdf"));+ const second = createNewStirlingFileStub(new File(["two"], "Second.pdf"));+ state.stubs.mockReturnValue([+ first,+ second,+ createNewStirlingFileStub(new File([], "Notes.txt")),+ ]);+ const { onChange } = show();+ expect(screen.getAllByRole("radio")).toHaveLength(2);+ fireEvent.click(screen.getByRole("radio", { name: "Second.pdf" }));+ expect(onChange).toHaveBeenCalledWith(second.id);+ expect(screen.queryByRole("radio")).not.toBeInTheDocument();+ expect(screen.getByRole("figure")).toHaveAccessibleName("Second.pdf");+ expect(screen.getByRole("heading", { name: "Second.pdf" })).toBeVisible();+ expect(+ screen.queryByRole("heading", { name: "Document" }),+ ).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Change PDF" }));+ expect(onChange).toHaveBeenLastCalledWith(null);+ expect(screen.getAllByRole("radio")).toHaveLength(2);+ fireEvent.click(screen.getByRole("radio", { name: "First.pdf" }));+ expect(screen.getByRole("figure")).toHaveAccessibleName("First.pdf");+ expect(state.add).not.toHaveBeenCalled();+});++it("can deselect even when only one PDF is open", () => {+ const file = createNewStirlingFileStub(new File(["one"], "Only.pdf"));+ state.stubs.mockReturnValue([file]);+ const { onChange } = show(file.id);+ expect(screen.getByRole("figure")).toHaveAccessibleName("Only.pdf");+ fireEvent.click(screen.getByRole("button", { name: "Change PDF" }));+ expect(onChange).toHaveBeenCalledWith(null);+ expect(screen.getByRole("radio", { name: "Only.pdf" })).not.toBeChecked();+ expect(+ screen.getByRole("button", { name: "Choose from library" }),+ ).toBeEnabled();+});++it("uses the single-PDF library picker and reuses an already-open file", async () => {+ const file = createStirlingFile(new File(["same"], "Open.pdf"));+ state.files.mockReturnValue([file]);+ const { onChange } = show();+ fireEvent.click(screen.getByRole("button", { name: "Choose a PDF" }));+ const options = state.open.mock.calls[0][0];+ expect(options).toMatchObject({+ supportedFormats: ["pdf"],+ maxSelectable: 1,+ });+ await act(() => options.customHandler([file]));+ expect(onChange).toHaveBeenCalledWith(file.fileId);+ expect(state.add).not.toHaveBeenCalled();+});++it("selects the imported PDF and releases loading state when ingestion fails", async () => {+ const source = new File(["new"], "New.pdf");+ const added = createStirlingFile(source);+ state.add+ .mockResolvedValueOnce([added])+ .mockRejectedValueOnce(new Error("Storage unavailable"));+ const { onChange, onLoadingChange } = show();+ fireEvent.click(screen.getByRole("button", { name: "Choose a PDF" }));+ const options = state.open.mock.calls[0][0];+ await act(() => options.customHandler([source]));+ expect(state.add).toHaveBeenCalledWith([source], { selectFiles: false });+ expect(onChange).toHaveBeenCalledExactlyOnceWith(added.fileId);+ await act(async () => {+ await expect(options.customHandler([source])).rejects.toThrow(+ "Storage unavailable",+ );+ });+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(onLoadingChange).toHaveBeenLastCalledWith(false);+});++it("rejects a multi-document bundle before changing the selected PDF", async () => {+ const { onChange } = show();+ fireEvent.click(screen.getByRole("button", { name: "Choose a PDF" }));+ const options = state.open.mock.calls[0][0];+ await act(async () => {+ await expect(+ options.customHandler([new File([], "One.pdf"), new File([], "Two.pdf")]),+ ).rejects.toThrow("Choose one PDF");+ await expect(+ options.customHandler([new File([], "Notes.txt")]),+ ).rejects.toThrow("Choose one PDF");+ });+ expect(onChange).not.toHaveBeenCalled();+ expect(state.add).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/core/components/shared/signing/SigningDocumentPicker.tsx b/frontend/editor/src/core/components/shared/signing/SigningDocumentPicker.tsxnew file mode 100644index 0000000000..a7bd742847--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningDocumentPicker.tsx@@ -0,0 +1,239 @@+import { useId, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { Icon } from "@app/ui/Icon";+import { useAllFiles } from "@app/contexts/FileContext";+import { useFileSelectors } from "@app/contexts/file/fileHooks";+import { useFilesModalContext } from "@app/contexts/FilesModalContext";+import { useFileHandler } from "@app/hooks/useFileHandler";+import { useFileThumbnail } from "@app/hooks/useFileThumbnail";+import DocumentThumbnail from "@app/components/shared/filePreview/DocumentThumbnail";+import { PrivateContent } from "@app/components/shared/PrivateContent";+import { createQuickKey, type StirlingFileStub } from "@app/types/fileContext";+import thumbnailStyles from "@app/components/fileEditor/FileEditorThumbnail.module.css";++/** Picks one PDF without navigating away; library imports use the normal FileContext ingestion path. */+export function SigningDocumentPicker({+ value,+ onChange,+ disabled,+ loading,+ onLoadingChange,+}: {+ value: string | null;+ onChange: (fileId: string | null) => void;+ disabled: boolean;+ loading: boolean;+ onLoadingChange: (loading: boolean) => void;+}) {+ const { t } = useTranslation();+ const headingId = useId();+ const { fileStubs } = useAllFiles();+ const selectors = useFileSelectors();+ const { openFilesModal } = useFilesModalContext();+ const { addFiles } = useFileHandler();+ const pdfs = fileStubs.filter((file) =>+ file.name.toLowerCase().endsWith(".pdf"),+ );+ const selectedFile = pdfs.find((file) => file.id === value);++ const openLibrary = () => {+ openFilesModal({+ maxSelectable: 1,+ supportedFormats: ["pdf"],+ customHandler: async (files) => {+ if (+ files.length !== 1 ||+ !files[0].name.toLowerCase().endsWith(".pdf")+ ) {+ throw new Error(+ t(+ "signWorkspace.selectOnePdf",+ "Choose one PDF for this signing request.",+ ),+ );+ }+ onLoadingChange(true);+ try {+ const existing = selectors+ .getFiles()+ .find((file) => createQuickKey(file) === createQuickKey(files[0]));+ const selected =+ existing ?? (await addFiles(files, { selectFiles: false }))[0];+ if (!selected)+ throw new Error(+ t(+ "signWorkspace.uploadFailed",+ "Could not open this PDF. Please try again.",+ ),+ );+ onChange(selected.fileId);+ } finally {+ onLoadingChange(false);+ }+ },+ });+ };++ return (+ <div className="signing-workspace__document-picker">+ <div className="signing-document-picker__heading">+ <h2 id={headingId} title={selectedFile?.name}>+ {selectedFile ? (+ <PrivateContent>{selectedFile.name}</PrivateContent>+ ) : (+ t("signWorkspace.document", "Document")+ )}+ </h2>+ {selectedFile ? (+ <Button+ variant="secondary"+ disabled={disabled || loading}+ onClick={() => onChange(null)}+ leftSection={<Icon name="arrow-left" size={18} />}+ >+ {t("signWorkspace.changeDocument", "Change PDF")}+ </Button>+ ) : pdfs.length > 0 ? (+ <Button+ variant="secondary"+ loading={loading}+ disabled={disabled}+ leftSection={<Icon name="folder-open" size={18} />}+ onClick={openLibrary}+ >+ {t("signWorkspace.chooseFromLibrary", "Choose from library")}+ </Button>+ ) : null}+ </div>+ {selectedFile ? (+ <figure+ className="signing-document-picker__selected"+ aria-labelledby={headingId}+ >+ <SigningDocumentPreview+ key={selectedFile.id}+ file={selectedFile}+ floating+ />+ </figure>+ ) : pdfs.length > 0 ? (+ <fieldset+ disabled={disabled || loading}+ className="signing-document-picker__files"+ >+ <legend>+ {t("signWorkspace.chooseDocument", "Choose an open PDF")}+ </legend>+ <div className="signing-document-picker__grid">+ {pdfs.map((file) => (+ <SigningDocumentCard+ key={file.id}+ file={file}+ onSelect={() => onChange(file.id)}+ />+ ))}+ </div>+ </fieldset>+ ) : (+ <div className="signing-document-picker__empty">+ <div className="signing-document-picker__empty-content">+ <div+ className="signing-document-picker__empty-icon"+ aria-hidden="true"+ >+ <Icon name="file-text" size={40} />+ </div>+ <h3>+ {t("signWorkspace.choosePdfHeading", "Start with your document")}+ </h3>+ <p>+ {t(+ "signWorkspace.noOpenPdfs",+ "Choose a PDF from your library or add one from your computer.",+ )}+ </p>+ <Button+ size="lg"+ loading={loading}+ disabled={disabled}+ leftSection={<Icon name="folder-open" size={20} />}+ onClick={openLibrary}+ >+ {t("signWorkspace.choosePdf", "Choose a PDF")}+ </Button>+ </div>+ </div>+ )}+ </div>+ );+}++function SigningDocumentCard({+ file,+ onSelect,+}: {+ file: StirlingFileStub;+ onSelect: () => void;+}) {+ return (+ <label className="signing-document-card">+ <input+ type="radio"+ name="signing-document"+ aria-label={file.name}+ checked={false}+ onChange={onSelect}+ />+ <SigningDocumentPreview file={file} />+ <span className="signing-document-card__name" title={file.name}>+ {file.name}+ </span>+ </label>+ );+}++function SigningDocumentPreview({+ file,+ floating = false,+}: {+ file: StirlingFileStub;+ floating?: boolean;+}) {+ const { thumbnail, isEncrypted, isGenerating } = useFileThumbnail(file);+ const [pageRatio, setPageRatio] = useState(210 / 297);+ return (+ <div+ className={+ floating+ ? "signing-document-preview"+ : `${thumbnailStyles.thumbContainer} signing-document-card__preview`+ }+ >+ {floating && thumbnail && !isEncrypted ? (+ <PrivateContent>+ <img+ src={thumbnail}+ alt={`Preview of ${file.name}`}+ draggable={false}+ className="signing-document-preview__page"+ style={{ width: `min(100cqw, calc(100cqh * ${pageRatio}))` }}+ onLoad={(event) => {+ const image = event.currentTarget;+ if (image.naturalHeight > 0)+ setPageRatio(image.naturalWidth / image.naturalHeight);+ }}+ />+ </PrivateContent>+ ) : (+ <DocumentThumbnail+ file={file}+ thumbnail={thumbnail}+ isEncrypted={isEncrypted}+ isLoading={isGenerating}+ imgClassName={thumbnailStyles.thumbImage}+ />+ )}+ </div>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SigningParticipantPicker.tsx b/frontend/editor/src/core/components/shared/signing/SigningParticipantPicker.tsxnew file mode 100644index 0000000000..751977314e--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningParticipantPicker.tsx@@ -0,0 +1,56 @@+import { Group } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Icon } from "@app/ui/Icon";+import { Tooltip } from "@app/ui/Tooltip";+import UserSelector from "@app/components/shared/UserSelector";++/** Updates the request's participants directly; sending the request is the commit point. */+export function SigningParticipantPicker({+ value,+ onChange,+ disabled,+}: {+ value: number[];+ onChange: (ids: number[]) => void;+ disabled: boolean;+}) {+ const { t } = useTranslation();+ return (+ <section className="signing-request__participants">+ <div className="signing-request__heading">+ <Group gap="xs">+ <h2>{t("signWorkspace.participants", "Participants")}</h2>+ <Tooltip+ content={t(+ "signMenu.anyOrder",+ "Participants can sign in any order. The owner finalizes the document after reviewing the collected signatures.",+ )}+ >+ <ActionIcon+ variant="quiet"+ aria-label={t(+ "signWorkspace.signingOrderHelp",+ "About signing order",+ )}+ >+ <Icon name="info" size={16} />+ </ActionIcon>+ </Tooltip>+ </Group>+ <span className="signing-request__selection-count" role="status">+ {t("signWorkspace.participantsSelected", "{{count}} selected", {+ count: value.length,+ })}+ </span>+ </div>+ <UserSelector+ presentation="cards"+ label={t("signWorkspace.chooseParticipants", "Choose participants")}+ value={value}+ onChange={onChange}+ disabled={disabled}+ />+ </section>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SigningSessionHeader.tsx b/frontend/editor/src/core/components/shared/signing/SigningSessionHeader.tsxnew file mode 100644index 0000000000..aa4be509d4--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningSessionHeader.tsx@@ -0,0 +1,69 @@+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Avatar } from "@app/ui/Avatar";+import { Icon } from "@app/ui/Icon";+import "@app/components/shared/signing/signingDetail.css";++interface SigningSessionHeaderProps {+ documentName: string;+ owner: string;+ createdAt: string;+ dueDate: string;+ message: string;+ status: ReactNode;+ actions?: ReactNode;+}++/** Shared document and sender information for owner and participant session views. */+export function SigningSessionHeader({+ documentName,+ owner,+ createdAt,+ dueDate,+ message,+ status,+ actions,+}: SigningSessionHeaderProps) {+ const { t } = useTranslation();+ return (+ <header className="signing-detail__header">+ <div className="signing-detail__header-row">+ {status}+ {actions}+ </div>+ <h2>{documentName}</h2>+ <div className="signing-detail__sender">+ {owner && <Avatar name={owner} size="sm" tone="neutral" />}+ <div>+ <span>+ {owner+ ? `${t("certSign.collab.signRequest.from", "From")}: ${owner}`+ : t("signWorkspace.createdByMe", "Created by me")}+ </span>+ <time dateTime={createdAt}>+ {new Date(createdAt).toLocaleDateString()}+ </time>+ </div>+ </div>+ {dueDate && (+ <div className="signing-detail__due">+ <Icon name="calendar" size={16} />+ <span>+ {t("certSign.collab.sessionDetail.dueDate", "Due Date")}:{" "}+ <time dateTime={dueDate}>+ {new Date(+ `${dueDate.slice(0, 10)}T00:00:00`,+ ).toLocaleDateString()}+ </time>+ </span>+ </div>+ )}+ {message && (+ <div className="signing-detail__message">+ <h3>{t("certSign.collab.sessionDetail.messageLabel", "Message")}</h3>+ <p>{message}</p>+ </div>+ )}+ </header>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SigningSessionRow.tsx b/frontend/editor/src/core/components/shared/signing/SigningSessionRow.tsxnew file mode 100644index 0000000000..801569dda9--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningSessionRow.tsx@@ -0,0 +1,67 @@+import { useTranslation } from "react-i18next";+import { Icon, type IconName } from "@app/ui/Icon";+import type { SigningIntent } from "@app/utils/pendingSigningIntent";+import { needsSignature, type SigningMenuItem } from "@app/utils/signingItems";+import { signingStatus } from "@app/utils/signingStatus";+import { SigningActivityDot } from "@app/components/shared/signing/SigningActivityDot";++interface SigningSessionRowProps {+ item: SigningMenuItem;+ onOpenSigning: (intent: SigningIntent) => void;+}++function rowIcon(item: SigningMenuItem): IconName {+ if (needsSignature(item)) return "pen-tool";+ return item.kind === "session" ? "users" : "file-text";+}++export function SigningSessionRow({+ item,+ onOpenSigning,+}: SigningSessionRowProps) {+ const { t } = useTranslation();+ const state = needsSignature(item)+ ? t("signWorkspace.needsYou", "Needs your signature")+ : signingStatus(item, t).label;+ return (+ <li>+ <button+ type="button"+ className="sign-menu__session"+ data-unread={item.unread}+ onClick={() =>+ onOpenSigning({+ kind: item.kind,+ sessionId: item.sessionId,+ })+ }+ >+ <span className="sign-menu__session-icon">+ <Icon name={rowIcon(item)} size={19} />+ </span>+ <span className="sign-menu__session-copy">+ <span className="sign-menu__document-heading">+ <span className="sign-menu__document" title={item.documentName}>+ {item.documentName}+ </span>+ {item.unread && <SigningActivityDot />}+ </span>+ <span className="sign-menu__state">{state}</span>+ <span className="sign-menu__meta">+ {item.kind === "request"+ ? `${t("certSign.collab.signRequest.from", "From")}: ${item.ownerUsername}`+ : t(+ "signMenu.ownerProgress",+ "Your request · {{signed}} / {{total}} signed",+ {+ signed: item.signedCount,+ total: item.participantCount,+ },+ )}+ </span>+ </span>+ <Icon name="chevron-right" size={16} />+ </button>+ </li>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SigningSessionsTable.test.tsx b/frontend/editor/src/core/components/shared/signing/SigningSessionsTable.test.tsxnew file mode 100644index 0000000000..d0f70dec1d--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningSessionsTable.test.tsx@@ -0,0 +1,394 @@+import { MantineProvider } from "@mantine/core";+import { fireEvent, render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { expect, it, vi } from "vitest";+import { SigningSessionsTable } from "@app/components/shared/signing/SigningSessionsTable";+import { collectSigningItems, type SigningItem } from "@app/utils/signingItems";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string, values?: Record<string, unknown>) =>+ (fallback ?? key).replace(/{{(\w+)}}/g, (_, name) =>+ String(values?.[name] ?? name),+ ),+ }),+}));++const items: SigningItem[] = [+ {+ kind: "session",+ sessionId: "shared",+ documentName: "Budget.pdf",+ createdAt: "2026-01-31T10:00:00Z",+ participantCount: 2,+ signedCount: 1,+ finalized: false,+ },+ {+ kind: "request",+ sessionId: "another-budget",+ documentName: "Budget.pdf",+ ownerUsername: "alice",+ createdAt: "2026-01-31T10:00:00Z",+ dueDate: "2020-05-01",+ myStatus: "SIGNED",+ },+ {+ kind: "request",+ sessionId: "review",+ documentName: "Agreement.pdf",+ ownerUsername: "bob",+ createdAt: "2026-02-01T10:00:00Z",+ dueDate: "2020-04-30",+ myStatus: "VIEWED",+ },+ {+ kind: "request",+ sessionId: "future",+ documentName: "Plan.pdf",+ ownerUsername: "bob",+ createdAt: "2026-01-30T10:00:00Z",+ dueDate: "2099-12-01",+ myStatus: "PENDING",+ },+ {+ kind: "session",+ sessionId: "ready",+ documentName: "Ready.pdf",+ createdAt: "2026-01-29T10:00:00Z",+ participantCount: 2,+ signedCount: 2,+ finalized: false,+ },+ {+ kind: "request",+ sessionId: "done",+ documentName: "Completed.pdf",+ ownerUsername: "alice",+ createdAt: "2026-02-02T10:00:00Z",+ dueDate: "2020-04-30",+ myStatus: "SIGNED",+ finalized: true,+ },+ {+ kind: "request",+ sessionId: "declined",+ documentName: "Declined.pdf",+ ownerUsername: "alice",+ createdAt: "2026-01-28T10:00:00Z",+ dueDate: "",+ myStatus: "DECLINED",+ },+];++function show(+ loading = false,+ rows: (SigningItem & { unread?: boolean })[] = items,+) {+ const onOpen = vi.fn();+ const onRefresh = vi.fn();+ const onCreate = vi.fn();+ const table = (rows: (SigningItem & { unread?: boolean })[]) => (+ <MantineProvider>+ <SigningSessionsTable+ items={rows}+ loading={loading}+ onOpen={onOpen}+ onRefresh={onRefresh}+ onCreate={onCreate}+ />+ </MantineProvider>+ );+ const view = render(table(rows));+ return {+ user: userEvent.setup(),+ onOpen,+ onRefresh,+ onCreate,+ updateItems: (rows: (SigningItem & { unread?: boolean })[]) =>+ view.rerender(table(rows)),+ };+}++it("filters unread sessions and completed documents while keeping read sessions in Active", async () => {+ const rows = items.map((item) => ({+ ...item,+ unread: ["ready", "future", "done"].includes(item.sessionId),+ }));+ const { user, updateItems } = show(false, rows);+ await user.click(screen.getByRole("radio", { name: "Unread" }));+ expect(documents()).toEqual(["Completed.pdf", "Plan.pdf", "Ready.pdf"]);+ await pick(user, "Due date", "Upcoming");+ expect(documents()).toEqual(["Plan.pdf"]);+ await user.click(screen.getByRole("button", { name: "Clear filters" }));+ updateItems(rows.map((item) => ({ ...item, unread: false })));+ expect(screen.getByText("You're all caught up")).toBeInTheDocument();+ await user.click(screen.getByRole("radio", { name: "Active" }));+ expect(documents()).toContain("Ready.pdf");+ expect(documents()).toContain("Plan.pdf");+});++it("moves expired access from Active and Unread into Completed when refreshed", async () => {+ const request = items[3];+ if (request.kind !== "request") throw new Error("Expected a request fixture");+ const { user, updateItems } = show(false, [{ ...request, unread: true }]);+ expect(documents()).toEqual(["Plan.pdf"]);+ updateItems([{ ...request, accessExpired: true, unread: false }]);+ expect(documents()).toEqual([]);+ await user.click(screen.getByRole("radio", { name: "Unread" }));+ expect(documents()).toEqual([]);+ await user.click(screen.getByRole("radio", { name: "Completed" }));+ expect(documents()).toEqual(["Plan.pdf"]);+ expect(screen.getByText("Access expired")).toBeInTheDocument();+ await pick(user, "Status", "Access expired");+ expect(documents()).toEqual(["Plan.pdf"]);+});++it("shows completion progress for owners without implying aggregate progress for participants", () => {+ show(false, [+ ...items,+ {+ kind: "session",+ sessionId: "empty",+ documentName: "Empty.pdf",+ createdAt: "2026-01-01",+ participantCount: 0,+ signedCount: 0,+ finalized: false,+ },+ ]);+ const partial = screen.getByRole("button", {+ name: /Budget.pdf Created by me/,+ });+ expect(+ within(partial).getByRole("progressbar", { name: "1 / 2 signed" }),+ ).toHaveAttribute("aria-valuenow", "50");+ expect(within(partial).getByText("Awaiting signatures")).toBeInTheDocument();+ const ready = screen.getByRole("button", {+ name: /Ready.pdf.*Ready to finalize/,+ });+ expect(+ within(ready).getByRole("progressbar", { name: "2 / 2 signed" }),+ ).toHaveAttribute("aria-valuenow", "100");+ expect(+ within(+ screen.getByRole("button", { name: /Budget.pdf alice/ }),+ ).queryByRole("progressbar"),+ ).not.toBeInTheDocument();+ expect(+ within(screen.getByRole("button", { name: /Empty.pdf/ })).queryByRole(+ "progressbar",+ ),+ ).not.toBeInTheDocument();+});++function documents() {+ return within(screen.getByRole("table"))+ .queryAllByRole("button")+ .filter((element) => element.tagName === "TR")+ .map((row) => within(row).getAllByRole("cell")[0].textContent);+}++async function pick(+ user: ReturnType<typeof userEvent.setup>,+ facet: string,+ option: string,+) {+ await user.click(+ screen.getByRole("button", { name: facet, expanded: false }),+ );+ await user.click(+ screen.getByRole("menuitemcheckbox", { name: new RegExp(option) }),+ );+ await user.keyboard("{Escape}");+}++it("sorts document names and actual timestamps, keeping undated sessions last", async () => {+ const { user } = show();+ expect(documents()[0]).toBe("Agreement.pdf");+ await user.click(+ within(screen.getByRole("columnheader", { name: "Document" })).getByRole(+ "button",+ ),+ );+ expect(documents()).toEqual([+ "Agreement.pdf",+ "Budget.pdf",+ "Budget.pdf",+ "Plan.pdf",+ "Ready.pdf",+ ]);+ const due = within(+ screen.getByRole("columnheader", { name: "Due date" }),+ ).getByRole("button");+ await user.click(due);+ if (+ screen+ .getByRole("columnheader", { name: "Due date" })+ .getAttribute("aria-sort") !== "ascending"+ )+ await user.click(due);+ expect(documents()).toEqual([+ "Agreement.pdf",+ "Budget.pdf",+ "Plan.pdf",+ "Budget.pdf",+ "Ready.pdf",+ ]);+ await user.click(due);+ if (+ screen+ .getByRole("columnheader", { name: "Due date" })+ .getAttribute("aria-sort") === "none"+ )+ await user.click(due);+ expect(documents().slice(0, 3)).toEqual([+ "Plan.pdf",+ "Budget.pdf",+ "Agreement.pdf",+ ]);+});++it("combines owner, status and due-date facets with search, and clears filters", async () => {+ const { user } = show();+ await pick(user, "Owner", "bob");+ await pick(user, "Status", "Needs your signature");+ await pick(user, "Due date", "Overdue");+ expect(documents()).toEqual(["Agreement.pdf"]);+ await user.type(+ screen.getByRole("textbox", { name: "Search documents or people" }),+ "missing",+ );+ expect(+ screen.getByText("No sessions match your search or filter."),+ ).toBeInTheDocument();+ await user.clear(+ screen.getByRole("textbox", { name: "Search documents or people" }),+ );+ await user.click(screen.getByRole("button", { name: "Clear filters" }));+ expect(documents()).toHaveLength(5);+});++it("keeps different workflows with the same filename distinct and opens them with mouse or keyboard", async () => {+ const { user, onOpen } = show();+ await user.click(+ screen.getByRole("button", { name: /Budget.pdf Created by me/ }),+ );+ expect(onOpen).toHaveBeenLastCalledWith(items[0]);+ fireEvent.keyDown(screen.getByRole("button", { name: /Budget.pdf alice/ }), {+ key: "Enter",+ });+ expect(onOpen).toHaveBeenLastCalledWith(items[1]);+});++it("shows one owned row with personal action and progress through signing and finalization", async () => {+ const owned = items[0];+ const request = items[1];+ if (owned.kind !== "session" || request.kind !== "request")+ throw new Error("Invalid fixture");+ const ownRequest = {+ ...request,+ sessionId: owned.sessionId,+ myStatus: "PENDING" as const,+ };+ const pending = collectSigningItems([ownRequest], [owned]);+ const { user, onOpen, updateItems } = show(false, pending);+ expect(documents()).toEqual(["Budget.pdf"]);+ const row = screen.getByRole("button", {+ name: /Budget.pdf Created by me Needs your signature/,+ });+ expect(+ within(row).getByRole("progressbar", { name: "1 / 2 signed" }),+ ).toBeInTheDocument();+ await user.click(row);+ expect(onOpen).toHaveBeenLastCalledWith(pending[0]);+ await pick(user, "Status", "Needs your signature");+ expect(documents()).toEqual(["Budget.pdf"]);+ await user.click(screen.getByRole("button", { name: "Clear filters" }));+ const ready = { ...owned, signedCount: 2 };+ updateItems(+ collectSigningItems([{ ...ownRequest, myStatus: "SIGNED" }], [ready]),+ );+ expect(documents()).toEqual(["Budget.pdf"]);+ expect(+ screen.getByRole("button", { name: /Budget.pdf.*Ready to finalize/ }),+ ).toBeInTheDocument();+ updateItems(+ collectSigningItems(+ [{ ...ownRequest, myStatus: "SIGNED", finalized: true }],+ [{ ...ready, finalized: true }],+ ),+ );+ expect(documents()).toEqual([]);+ await user.click(screen.getByRole("radio", { name: "Completed" }));+ expect(documents()).toEqual(["Budget.pdf"]);+});++it("keeps submitted and ready sessions active, moving finalized and declined entries to Completed", async () => {+ const { user } = show();+ expect(documents()).toContain("Ready.pdf");+ expect(documents()).not.toContain("Declined.pdf");+ await pick(user, "Status", "Signed");+ expect(documents()).toEqual(["Budget.pdf"]);+ await user.click(screen.getByRole("radio", { name: "Completed" }));+ expect(documents()).toEqual(["Completed.pdf", "Declined.pdf"]);+ expect(+ screen.queryByRole("button", { name: "Due date", expanded: false }),+ ).not.toBeInTheDocument();+ await pick(user, "Status", "Declined");+ expect(documents()).toEqual(["Declined.pdf"]);+});+it("retains sorting after zero search results and refreshes without clearing the search", async () => {+ const { user, onRefresh } = show();+ await user.click(+ within(screen.getByRole("columnheader", { name: "Document" })).getByRole(+ "button",+ ),+ );+ const search = screen.getByRole("textbox", {+ name: "Search documents or people",+ });+ await user.type(search, "nonexistent");+ await user.clear(search);+ expect(documents()[0]).toBe("Agreement.pdf");+ expect(+ screen.getByRole("columnheader", { name: "Document" }),+ ).toHaveAttribute("aria-sort", "ascending");+ await user.type(search, "ALICE");+ await user.click(screen.getByRole("button", { name: "Refresh sessions" }));+ expect(onRefresh).toHaveBeenCalledOnce();+ expect(documents()).toEqual(["Budget.pdf"]);+});++it("distinguishes initial loading from an empty list", () => {+ show(true, []);+ expect(screen.queryByText("No sessions here yet.")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Refresh sessions" }),+ ).toBeDisabled();+});++it("shows an unread final document without putting it back in Active", async () => {+ const completed = { ...items[5], unread: true };+ const { user, updateItems } = show(false, [completed]);+ expect(documents()).toEqual([]);+ await user.click(screen.getByRole("radio", { name: "Unread" }));+ expect(documents()).toEqual(["Completed.pdf"]);+ updateItems([{ ...completed, unread: false }]);+ expect(documents()).toEqual([]);+ await user.click(screen.getByRole("radio", { name: "Completed" }));+ expect(documents()).toEqual(["Completed.pdf"]);+});++it("exposes unread activity beside the document without changing the ready-to-finalize status", () => {+ show(+ false,+ items.map((item) => ({ ...item, unread: item.sessionId === "ready" })),+ );+ const ready = screen.getByRole("button", {+ name: /Ready.pdf.*New activity.*Ready to finalize/,+ });+ expect(+ within(ready).getByRole("img", { name: /New activity/ }),+ ).toBeInTheDocument();+});diff --git a/frontend/editor/src/core/components/shared/signing/SigningSessionsTable.tsx b/frontend/editor/src/core/components/shared/signing/SigningSessionsTable.tsxnew file mode 100644index 0000000000..1e78ba53f9--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningSessionsTable.tsx@@ -0,0 +1,285 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { DataTable, column } from "@app/ui/DataTable";+import {+ DataTableFilterBar,+ useDataTableFilters,+} from "@app/ui/DataTableFilterBar";+import { Icon } from "@app/ui/Icon";+import { Input } from "@app/ui/Input";+import { SegmentedControl } from "@app/ui/SegmentedControl";+import type { StatusTone } from "@app/ui/StatusBadge";+import {+ isSigningItemClosed,+ canReceiveSigningActivity,+ needsSignature,+ type SigningItem,+} from "@app/utils/signingItems";+import { signingStatus } from "@app/utils/signingStatus";++type SessionRow = SigningItem & { unread?: boolean };++interface SigningSessionsTableProps {+ items: SessionRow[];+ loading: boolean;+ onOpen: (item: SigningItem) => void;+ onRefresh: () => void;+ onCreate: () => void;+}++function statusKey(item: SigningItem): string {+ if (item.kind === "request" && item.accessExpired) return "expired";+ if (item.finalized) return "finalized";+ if (needsSignature(item)) return "needsYou";+ if (item.kind === "request") {+ if (item.myStatus === "DECLINED") return "declined";+ if (item.closed) return "closed";+ if (item.myStatus === "SIGNED") return "signed";+ }+ if (isSigningItemClosed(item)) return "closed";+ if (+ item.kind === "session" &&+ item.participantCount > 0 &&+ item.signedCount === item.participantCount+ )+ return "ready";+ return "awaiting";+}++const statusTones: Record<string, StatusTone> = {+ green: "success",+ blue: "info",+ red: "danger",+ yellow: "warning",+ orange: "warning",+};++/** Keep mounted while opening a session so search, facets and column sorting survive return navigation. */+export function SigningSessionsTable({+ items,+ loading,+ onOpen,+ onRefresh,+ onCreate,+}: SigningSessionsTableProps) {+ const { t } = useTranslation();+ const [tab, setTab] = useState("active");+ const statusLabels: Record<string, string> = {+ expired: t("signRequest.expired", "Access expired"),+ closed: t("signMenu.closedStatus", "Closed"),+ needsYou: t("signWorkspace.needsYou", "Needs your signature"),+ signed: t("sharedSign.filterSigned", "Signed"),+ declined: t("sharedSign.filterDeclined", "Declined"),+ finalized: t("certSign.finalized", "Finalized"),+ ready: t("certSign.readyToFinalize", "Ready to finalize"),+ awaiting: t("certSign.awaitingSignatures", "Awaiting signatures"),+ };+ const dueLabels: Record<string, string> = {+ overdue: t("sharedSign.filterOverdue", "Overdue"),+ upcoming: t("signWorkspace.upcoming", "Upcoming"),+ none: t("signWorkspace.noDueDate", "No due date"),+ };+ const owner = (item: SigningItem) =>+ item.kind === "session"+ ? t("signWorkspace.createdByMe", "Created by me")+ : item.ownerUsername;+ const rows = items.filter((item) =>+ tab === "unread"+ ? item.unread && canReceiveSigningActivity(item)+ : isSigningItemClosed(item) === (tab === "closed"),+ );+ const filters = useDataTableFilters({+ rows,+ searchText: (item) => `${item.documentName} ${owner(item)}`,+ searchPlaceholder: t("signWorkspace.search", "Search documents or people"),+ facets: [+ {+ key: "owner",+ label: t("signWorkspace.owner", "Owner"),+ getValue: (item) =>+ item.kind === "session" ? "mine" : `user:${item.ownerUsername}`,+ formatValue: (value) =>+ value === "mine"+ ? t("signWorkspace.createdByMe", "Created by me")+ : value.slice(5),+ },+ {+ key: "status",+ label: t("signWorkspace.status", "Status"),+ getValue: statusKey,+ formatValue: (value) => statusLabels[value],+ },+ ...(tab !== "closed"+ ? [+ {+ key: "due",+ label: t("signWorkspace.dueDate", "Due date"),+ getValue: (item: SigningItem) =>+ !item.dueDate+ ? "none"+ : Date.parse(item.dueDate) < Date.now()+ ? "overdue"+ : "upcoming",+ formatValue: (value: string) => dueLabels[value],+ },+ ]+ : []),+ ],+ });+ const columns = [+ column.entity<SessionRow>({+ key: "document",+ header: t("signWorkspace.document", "Document"),+ sortable: true,+ primary: (item) => item.documentName,+ icon: () => <Icon name="file-text" size={18} />,+ unreadLabel: (item) =>+ item.unread+ ? t(+ "signMenu.newActivity",+ "New activity since you last viewed this session",+ )+ : undefined,+ }),+ column.text<SigningItem>({+ key: "owner",+ header: t("signWorkspace.owner", "Owner"),+ sortable: true,+ get: owner,+ }),+ column.badge<SigningItem>({+ key: "status",+ header: t("signWorkspace.status", "Status"),+ sortable: true,+ sortBy: (item) => statusLabels[statusKey(item)],+ get: (item) => {+ const status = signingStatus(item, t);+ if (item.kind === "session") {+ return {+ tone: statusTones[status.color] ?? "neutral",+ label: statusLabels[statusKey(item)],+ progress:+ item.participantCount > 0+ ? {+ value: item.signedCount / item.participantCount,+ label: t(+ "signingDetail.signedCount",+ "{{signed}} / {{total}} signed",+ {+ signed: item.signedCount,+ total: item.participantCount,+ },+ ),+ }+ : undefined,+ };+ }+ return needsSignature(item)+ ? { tone: "warning", label: statusLabels.needsYou }+ : {+ tone: statusTones[status.color] ?? "neutral",+ label: status.label,+ };+ },+ }),+ column.number<SigningItem>({+ key: "created",+ header: t("signWorkspace.created", "Created"),+ sortable: true,+ get: (item) => Date.parse(item.createdAt),+ format: (value) => new Date(value).toLocaleDateString(),+ }),+ column.number<SigningItem>({+ key: "due",+ header: t("signWorkspace.dueDate", "Due date"),+ sortable: true,+ get: (item) => (item.dueDate ? Date.parse(item.dueDate) : undefined),+ format: (value) => new Date(value).toLocaleDateString(),+ placeholder: t("signWorkspace.noDueDate", "No due date"),+ }),+ ];++ return (+ <div className="signing-workspace__content">+ <div className="signing-workspace__list-heading">+ <Input+ className="signing-workspace__search"+ inputSize="sm"+ leadingIcon={<Icon name="search" size={16} />}+ value={filters.filterBar.search?.value ?? ""}+ onChange={(event) =>+ filters.filterBar.search?.onChange(event.target.value)+ }+ placeholder={t("signWorkspace.search", "Search documents or people")}+ aria-label={t("signWorkspace.search", "Search documents or people")}+ />+ <div className="signing-workspace__list-action">+ <Button+ leftSection={<Icon name="plus" size={18} />}+ onClick={onCreate}+ >+ {t("signMenu.request", "Request signatures")}+ </Button>+ </div>+ </div>+ <DataTable+ variant="comfortable"+ toolbar={+ <div className="signing-workspace__table-controls">+ <SegmentedControl+ ariaLabel={t("signMenu.sessionFilter", "Session views")}+ value={tab}+ onChange={(value) => {+ setTab(value);+ filters.filterBar.onClearAll();+ }}+ options={[+ {+ value: "active",+ label: t("sharedSign.tab.active", "Active"),+ },+ { value: "unread", label: t("signMenu.unreadTab", "Unread") },+ {+ value: "closed",+ label: t("signMenu.completedTab", "Completed"),+ },+ ]}+ />+ <DataTableFilterBar+ {...filters.filterBar}+ search={undefined}+ trailing={+ <Button+ variant="quiet"+ aria-label={t("signWorkspace.refresh", "Refresh sessions")}+ title={t("signWorkspace.refresh", "Refresh sessions")}+ onClick={onRefresh}+ disabled={loading}+ leftSection={<Icon name="refresh-cw" size={18} />}+ />+ }+ />+ </div>+ }+ columns={columns}+ rows={filters.rows}+ rowKey={(item) => `${item.kind}:${item.sessionId}`}+ onRowClick={onOpen}+ rowAffordance="chevron"+ defaultSort={{ key: "created", direction: "desc" }}+ loading={loading && items.length === 0}+ empty={+ rows.length === 0+ ? tab === "unread"+ ? t("signMenu.noUnread", "You're all caught up")+ : t("signWorkspace.empty", "No sessions here yet.")+ : t(+ "signWorkspace.noMatches",+ "No sessions match your search or filter.",+ )+ }+ />+ </div>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/SigningWorkspace.tsx b/frontend/editor/src/core/components/shared/signing/SigningWorkspace.tsxnew file mode 100644index 0000000000..753a873b54--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/SigningWorkspace.tsx@@ -0,0 +1,292 @@+import { useNavigate } from "react-router-dom";+import { EDITOR_BASENAME } from "@app/routes/editorBasename";+import { lazy, Suspense, useEffect, useMemo, useState } from "react";+import { Alert, Center, Loader } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui/Button";+import { Icon } from "@app/ui/Icon";+import { SigningSessionsTable } from "@app/components/shared/signing/SigningSessionsTable";+import { useGroupSigningEnabled } from "@app/hooks/useGroupSigningEnabled";+import { useAuth } from "@app/auth/UseSession";+import { useSigningSessionController } from "@app/hooks/signing/useSigningSessionController";+import { useAllFiles } from "@app/contexts/FileContext";+import { useViewer } from "@app/contexts/ViewerContext";+import { useNavigationGuard } from "@app/contexts/NavigationContext";+import { SigningDocumentPicker } from "@app/components/shared/signing/SigningDocumentPicker";+import { useSigningOverlay } from "@app/contexts/SigningOverlayContext";+import { CreateSessionFlow } from "@app/components/shared/signing/CreateSessionFlow";+import { SessionDetailPanel } from "@app/components/tools/certSign/panels/SessionDetailPanel";+import SignRequestPanel from "@app/components/tools/certSign/panels/SignRequestPanel";+import {+ collectSigningItems,+ getSigningItemToOpen,+ type SigningItem,+} from "@app/utils/signingItems";+import { useSigningActivity } from "@app/hooks/signing/useSigningActivity";+import {+ requestSigningIntent,+ usePendingSigningIntent,+} from "@app/utils/pendingSigningIntent";+import "@app/components/shared/signing/signing.css";++const Viewer = lazy(() => import("@app/components/viewer/Viewer"));++/** Guests are told to sign in rather than that the server has signing off. */+function SigningUnavailableNotice() {+ const { t } = useTranslation();+ const { isAnonymous } = useAuth();+ if (isAnonymous) {+ return (+ <Alert+ color="yellow"+ title={t("sharedSign.signInRequiredTitle", "Sign in required")}+ >+ {t(+ "sharedSign.signInRequiredBody",+ "Sign in to request signatures and see requests sent to you.",+ )}+ </Alert>+ );+ }+ return (+ <Alert>+ {t(+ "sharedSign.disabledBody",+ "Collaborative signing isn't enabled on this server.",+ )}+ </Alert>+ );+}++/** Owns session navigation and gives the document and signing controls their own workspace. */+export default function SigningWorkspace() {+ const { t } = useTranslation();+ const enabled = useGroupSigningEnabled();+ const navigate = useNavigate();+ const { requestNavigation } = useNavigationGuard();+ const controller = useSigningSessionController(enabled, () =>+ navigate(EDITOR_BASENAME),+ );+ const { overlay } = useSigningOverlay();+ const { files } = useAllFiles();+ const { activeFileIndex } = useViewer();+ const pdfs = files.filter((file) => file.name.toLowerCase().endsWith(".pdf"));+ const [documentId, setDocumentId] = useState<string | null>(+ pdfs.find((file) => file.fileId === files[activeFileIndex]?.fileId)+ ?.fileId ?? (pdfs.length === 1 ? pdfs[0].fileId : null),+ );+ const document = pdfs.find((file) => file.fileId === documentId);+ const [uploading, setUploading] = useState(false);+ const [showCreate, setShowCreate] = useState(false);+ const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);+ const [dueDate, setDueDate] = useState("");+ const [listRevision, setListRevision] = useState(0);+ const [opening, setOpening] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const pendingIntent = usePendingSigningIntent();+ const sessions = useMemo(+ () => collectSigningItems(controller.signRequests, controller.mySessions),+ [controller.signRequests, controller.mySessions],+ );+ const items = useSigningActivity(sessions);++ const openItem = async (item: SigningItem) => {+ setOpening(true);+ setShowCreate(false);+ try {+ const target = getSigningItemToOpen(item);+ if (target.kind === "request") await controller.openSignRequest(target);+ else await controller.openSession(target);+ } finally {+ setOpening(false);+ }+ };++ useEffect(() => {+ if (!pendingIntent || !enabled || controller.loading || opening) return;+ requestSigningIntent(null);+ controller.backToList();+ setError(null);+ setShowCreate(pendingIntent === "create");+ if (typeof pendingIntent === "object") {+ const item = items.find(+ (entry) => entry.sessionId === pendingIntent.sessionId,+ );+ if (item) void openItem(item);+ else+ setError(+ t(+ "signWorkspace.unavailable",+ "This session is no longer available. Refresh the list to see your current sessions.",+ ),+ );+ }+ }, [+ pendingIntent,+ opening,+ enabled,+ controller.loading,+ items,+ controller.backToList,+ ]);++ const detail = controller.view !== "list" && !showCreate;+ const currentLocation = showCreate+ ? t("signMenu.request", "Request signatures")+ : detail+ ? (controller.detailData?.session.documentName ??+ controller.requestData?.signRequest.documentName)+ : null;++ return (+ <section+ className="signing-workspace"+ aria-label={t("signMenu.sessions", "Signing sessions")}+ >+ {currentLocation && (+ <header className="signing-workspace__header">+ <nav+ className="signing-workspace__navigation"+ aria-label={t("signWorkspace.navigation", "Signing navigation")}+ >+ <h1 className="signing-workspace__path">+ <Button+ variant="tertiary"+ shape="pill"+ size="sm"+ disabled={controller.creating || uploading || opening}+ onClick={() =>+ requestNavigation(() => {+ controller.backToList();+ setShowCreate(false);+ setError(null);+ })+ }+ >+ {t("signMenu.sessions", "Signing sessions")}+ </Button>+ <Icon name="chevron-right" size={16} aria-hidden="true" />+ <span+ className="signing-workspace__current"+ aria-current="page"+ title={currentLocation}+ >+ {currentLocation}+ </span>+ </h1>+ </nav>+ </header>+ )}+ {!enabled ? (+ <div className="signing-workspace__body">+ <SigningUnavailableNotice />+ </div>+ ) : opening ? (+ <Center h="100%">+ <Loader />+ </Center>+ ) : detail ? (+ <div className="signing-workspace__detail">+ <div className="signing-workspace__preview">+ {overlay?.file ? (+ <Suspense+ fallback={+ <Center h="100%">+ <Loader />+ </Center>+ }+ >+ <Viewer+ previewFile={overlay.file}+ signaturePreviews={overlay.signaturePreviews}+ signaturePreviewsReadOnly={overlay.signaturePreviewsReadOnly}+ readOnlySignaturePreviews={overlay.readOnlySignaturePreviews}+ signaturePlacementMode={overlay.signaturePlacementMode}+ signaturePlacementData={overlay.signaturePlacementData}+ signaturePlacementType={overlay.signaturePlacementType}+ onSignaturePreviewsChange={overlay.onSignaturePreviewsChange}+ signatureOverlayApiRef={overlay.signatureOverlayApiRef}+ />+ </Suspense>+ ) : (+ <div className="signing-workspace__empty">+ {t("signWorkspace.noPreview", "Document preview unavailable")}+ </div>+ )}+ </div>+ <div className="signing-workspace__panel">+ {controller.view === "detail" && controller.detailData && (+ <SessionDetailPanel data={controller.detailData} />+ )}+ {controller.view === "request" && controller.requestData && (+ <SignRequestPanel data={controller.requestData} />+ )}+ </div>+ </div>+ ) : (+ <div className="signing-workspace__body" hidden={!showCreate}>+ {error && (+ <Alert mb="md" color="red">+ {error}+ </Alert>+ )}+ {showCreate && (+ <CreateSessionFlow+ documentPicker={+ <SigningDocumentPicker+ value={document?.fileId ?? null}+ onChange={setDocumentId}+ disabled={controller.creating}+ loading={uploading}+ onLoadingChange={setUploading}+ />+ }+ selectedFiles={document ? [document] : []}+ selectedUserIds={selectedUserIds}+ onSelectedUserIdsChange={setSelectedUserIds}+ dueDate={dueDate}+ onDueDateChange={setDueDate}+ creating={controller.creating || uploading}+ onSubmit={(settings) => {+ if (!document) return;+ void controller+ .createSession(settings, selectedUserIds, dueDate, document)+ .then((ok) => {+ if (!ok) return;+ setShowCreate(false);+ setSelectedUserIds([]);+ setDueDate("");+ setListRevision((revision) => revision + 1);+ });+ }}+ />+ )}+ </div>+ )}+ {enabled && (+ <div+ className="signing-workspace__body"+ hidden={opening || detail || showCreate}+ >+ {error && (+ <Alert mb="md" color="red">+ {error}+ </Alert>+ )}+ <SigningSessionsTable+ key={listRevision}+ items={items}+ loading={controller.loading}+ onCreate={() => setShowCreate(true)}+ onOpen={(item) => {+ void openItem(item);+ }}+ onRefresh={() => {+ void controller.refetch();+ }}+ />+ </div>+ )}+ </section>+ );+}diff --git a/frontend/editor/src/core/components/shared/signing/signing.css b/frontend/editor/src/core/components/shared/signing/signing.cssnew file mode 100644index 0000000000..8e04afdb08--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/signing.css@@ -0,0 +1,831 @@+.sign-menu.sui-dd__menu {+ width: min(400px, calc(100vw - 24px));+ height: min(660px, calc(100dvh - 24px));+ padding: 0;+ gap: 0;+ overflow: hidden;+ border-radius: 14px;+}+.sign-menu.sign-menu--unavailable {+ height: auto;+}+.sign-menu h2 {+ margin: 0;+ font-size: 14px;+ font-weight: 600;+ color: var(--c-text);+}+.sign-menu__personal {+ flex-shrink: 0;+ padding: 18px;+ background: var(--c-bg-raised);+ border-bottom: 1px solid var(--c-border);+}+.sign-menu__tools {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 10px;+ margin-top: 12px;+}+.sign-menu__tool {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 6px;+ min-width: 0;+ padding: 12px;+ border: 1px solid var(--c-border);+ border-radius: 10px;+ background: var(--c-surface);+ color: var(--c-text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.sign-menu__tool svg {+ margin-bottom: 4px;+ color: var(--c-text-muted);+}+.sign-menu__tool strong {+ font-size: 13px;+ font-weight: 500;+}+.sign-menu__tool span {+ font-size: 11px;+ line-height: 1.4;+ color: var(--c-text-muted);+}+.sign-menu button:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}+.sign-menu button:focus-visible,+.sign-menu__results:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: -2px;+}+.sign-menu__sessions {+ display: flex;+ flex-direction: column;+ flex: 1;+ min-height: 0;+}+.sign-menu__session-header {+ flex-shrink: 0;+ padding: 12px 18px 0;+}+.sign-menu__heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ margin-bottom: 10px;+}+.sign-menu__icon-button {+ display: grid;+ place-items: center;+ width: 32px;+ height: 32px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--c-text-muted);+ cursor: pointer;+}+.sign-menu__request {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ width: 100%;+ min-height: 36px;+ padding: 8px 12px;+ border: 1px solid var(--c-border-strong);+ border-radius: 8px;+ background: var(--c-surface);+ color: var(--c-text);+ font: inherit;+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+}+.sign-menu__tool:hover:not(:disabled),+.sign-menu__request:hover:not(:disabled),+.sign-menu__icon-button:hover:not(:disabled) {+ background: var(--c-hover);+}+.sign-menu__filters {+ flex-shrink: 0;+ padding: 12px 18px 8px;+}+.sign-menu__tabs {+ gap: 8px;+ flex-wrap: nowrap;+}+.sign-menu__tabs .sui-tabs__tab {+ padding: 8px 6px;+ font-size: 12px;+ white-space: nowrap;+}+.sign-menu__hint {+ margin: 10px 0 0;+ color: var(--c-text-muted);+ font-size: 11px;+ line-height: 1.5;+}+.sign-menu__sessions > .sign-menu__hint {+ padding: 0 18px 18px;+}+.sign-menu__search {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 12px;+ padding: 7px 10px;+ border: 1px solid var(--c-border);+ border-radius: 7px;+ color: var(--c-text-muted);+ background: var(--c-input-bg);+}+.sign-menu__search:focus-within {+ outline: 2px solid var(--c-primary);+ outline-offset: 1px;+}+.sign-menu__search input {+ min-width: 0;+ width: 100%;+ padding: 0;+ border: 0;+ outline: none;+ background: transparent;+ color: var(--c-text);+ font: inherit;+ font-size: 12px;+}+.sign-menu__search input::placeholder {+ color: var(--c-text-muted);+}+.sign-menu__results {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ overscroll-behavior: contain;+ padding: 0 8px 10px;+ scrollbar-gutter: stable;+}+.sign-menu__list {+ list-style: none;+ padding: 0;+ margin: 0;+}+.sign-menu__session {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 12px 10px;+ border: 0;+ border-radius: 8px;+ background: transparent;+ color: var(--c-text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.sign-menu__session:hover {+ background: var(--c-hover);+}+.sign-menu__session > svg {+ flex-shrink: 0;+ color: var(--c-text-subtle);+}+.sign-menu__session-icon {+ display: grid;+ place-items: center;+ width: 34px;+ height: 34px;+ flex-shrink: 0;+ border-radius: 9px;+ background: var(--c-surface-sunken);+ color: var(--c-text-muted);+}+.sign-menu__session[data-unread="true"] .sign-menu__session-icon {+ color: var(--c-accent-fg);+ background: var(--c-primary-subtle);+}+.sign-menu__session-copy {+ display: flex;+ flex-direction: column;+ gap: 4px;+ flex: 1;+ min-width: 0;+}+.sign-menu__document {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 13px;+ font-weight: 500;+}+.sign-menu__document-heading {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}+.signing-activity-dot {+ display: inline-block;+ width: 7px;+ height: 7px;+ flex-shrink: 0;+ border-radius: 50%;+ background: var(--c-accent-fg);+}+.sign-menu__state {+ font-size: 12px;+ color: var(--c-text-muted);+}+.sign-menu__session[data-unread="true"] .sign-menu__state {+ color: var(--c-accent-fg);+}+.sign-menu__meta {+ font-size: 11px;+ color: var(--c-text-muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.sign-menu__empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 10px;+ padding: 26px 20px;+ text-align: center;+ color: var(--c-text-muted);+ font-size: 12px;+ line-height: 1.5;+}+.sign-menu__empty strong {+ color: var(--c-text);+ font-size: 13px;+ font-weight: 500;+}+.sign-menu__trigger-badge {+ position: absolute;+ top: 2px;+ right: 8px;+ min-width: 16px;+ border-radius: 10px;+ padding: 1px 4px;+ font-size: 10px;+ line-height: 14px;+ font-weight: 600;+ background: var(--c-warning-solid);+ color: var(--c-text-on-primary);+}+.signing-workspace {+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ color: var(--c-text);+}+.signing-workspace__header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ flex-wrap: wrap;+ flex-shrink: 0;+ gap: 12px;+ padding: 8px 20px;+ border-bottom: 1px solid var(--c-border);+ background: var(--c-surface);+}+.signing-workspace__navigation {+ min-width: 0;+ flex: 1;+}+.signing-workspace__path {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ margin: 0;+ font-size: 14px;+ font-weight: 500;+}+.signing-workspace__path > button,+.signing-workspace__path > svg {+ flex-shrink: 0;+}+.signing-workspace__path > svg {+ color: var(--c-text-muted);+}+.signing-workspace__current {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.signing-workspace__body {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 24px 32px;+}+.signing-workspace__body[hidden] {+ display: none;+}+.signing-workspace__content {+ min-width: 0;+ max-width: 72rem;+ margin-inline: auto;+}+.signing-workspace__list-heading {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 24rem) minmax(0, 1fr);+ align-items: center;+ gap: 1.5rem;+ margin-bottom: 1.5rem;+}+.signing-workspace__search {+ grid-column: 2;+ width: 100%;+ min-width: 0;+ background: transparent;+}+.signing-workspace__list-action {+ grid-column: 3;+ justify-self: end;+}+.signing-workspace__table-controls {+ display: flex;+ align-items: flex-start;+ flex-wrap: wrap;+ gap: 1rem 1.5rem;+ width: 100%;+}+.signing-workspace__table-controls > .sui-dtfb {+ flex: 1 1 20rem;+}+.signing-workspace__table-controls .sui-dtfb__row {+ justify-content: flex-end;+}+.signing-workspace__table-controls .sui-dtfb__trailing {+ margin-inline-start: 0;+}+.signing-workspace__table-controls .sui-dtfb__active {+ justify-content: flex-end;+}+.signing-workspace__empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 12px;+ padding: 72px 24px;+ text-align: center;+ color: var(--c-text-muted);+}+.signing-workspace__detail {+ display: grid;+ grid-template-columns: minmax(0, 1fr) clamp(380px, 34%, 480px);+ flex: 1;+ min-height: 0;+}+.signing-workspace__preview {+ min-width: 0;+ min-height: 0;+ overflow: hidden;+ position: relative;+}+.signing-workspace__panel {+ min-width: 0;+ min-height: 0;+ overflow-y: auto;+ border-left: 1px solid var(--c-border);+ background: var(--c-surface);+}+.signing-workspace__create {+ display: grid;+ grid-template-columns: minmax(0, 1fr);+ max-width: 800px;+ margin: 0 auto;+ padding: 28px;+ border: 1px solid var(--c-border);+ border-radius: 12px;+ background: var(--c-surface);+}+.signing-workspace__create > * {+ min-width: 0;+}+.signing-workspace__create [hidden] {+ display: none;+}+.signing-request__document {+ display: flex;+ flex-direction: column;+}+.signing-workspace__document-picker {+ display: flex;+ flex-direction: column;+ flex: 1;+ padding-bottom: 24px;+ margin-bottom: 24px;+ border-bottom: 1px solid var(--c-border);+}+.signing-document-picker__heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 12px;+ margin-bottom: 16px;+}+.signing-document-picker__heading h2 {+ flex: 1;+ min-width: 0;+ overflow-wrap: anywhere;+ margin: 0;+ font-size: 16px;+ font-weight: 600;+}+.signing-document-picker__files {+ margin: 0;+ padding: 0;+ border: 0;+ min-width: 0;+}+.signing-document-picker__files legend {+ margin: 0 0 12px;+ padding: 0;+ font-size: 12px;+ color: var(--c-text-muted);+}+.signing-document-picker__empty {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-height: 320px;+ padding: clamp(24px, 4vw, 56px);+ border: 1px dashed var(--c-border-strong);+ border-radius: 16px;+ background: var(--c-bg);+ text-align: center;+}+.signing-document-picker__empty-content {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 20px;+ min-height: clamp(260px, calc(100dvh - 280px), 600px);+}+.signing-document-picker__empty-icon {+ display: grid;+ place-items: center;+ width: 88px;+ height: 104px;+ border: 1px solid var(--c-border);+ border-radius: 12px;+ background: var(--c-surface);+ color: var(--c-accent-fg);+ box-shadow: var(--shadow-sm);+}+.signing-document-picker__empty h3 {+ margin: 0;+ font-size: 20px;+ font-weight: 600;+}+.signing-document-picker__empty p {+ max-width: 32ch;+ margin: -8px 0 4px;+ color: var(--c-text-muted);+ font-size: 14px;+ line-height: 1.6;+}+.signing-document-picker__grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr));+ gap: 16px;+ max-height: 520px;+ align-items: start;+ overflow-y: auto;+ padding: 3px;+}+.signing-document-card {+ position: relative;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 10px;+ min-width: 0;+ padding: 10px;+ border: 2px solid transparent;+ border-radius: 12px;+ cursor: pointer;+}+.signing-document-card:hover {+ background: var(--c-hover);+}+.signing-document-card:focus-within {+ outline: 2px solid var(--c-primary);+ outline-offset: 1px;+}+.signing-document-card:has(input:disabled) {+ opacity: 0.6;+ cursor: default;+}+.signing-document-card input {+ position: absolute;+ top: 16px;+ right: 16px;+ width: 18px;+ height: 18px;+ margin: 0;+ z-index: 2;+ accent-color: var(--c-primary);+}+.signing-document-card__preview {+ height: auto;+ aspect-ratio: 210 / 297;+ max-width: 280px;+ pointer-events: none;+}+.signing-document-picker__selected {+ display: flex;+ flex-direction: column;+ align-items: center;+ margin: 0;+ padding: 12px;+}+.signing-document-preview {+ display: flex;+ align-items: center;+ justify-content: center;+ container-type: size;+ width: 100%;+ aspect-ratio: 210 / 297;+ max-width: 320px;+}+.signing-document-preview__page {+ display: block;+ height: auto;+ max-width: 100%;+ max-height: 100%;+ border-radius: 12px;+ box-shadow: var(--shadow-md);+}+.signing-document-card__name {+ display: -webkit-box;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ overflow-wrap: anywhere;+ width: 100%;+ font-size: 12px;+ font-weight: 500;+ line-height: 18px;+ text-align: center;+}+.signing-request,+.signing-request__options {+ display: flex;+ flex-direction: column;+ gap: 24px;+}+.signing-workspace__create[data-mobile] {+ display: flex;+ flex-direction: column;+ min-height: 100%;+ gap: 24px;+ padding: 0;+ border: 0;+ background: transparent;+}+.signing-workspace__create[data-mobile] .signing-workspace__document-picker {+ margin: 0;+ padding: 0;+ border: 0;+}+.signing-request__steps ol {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 8px;+ margin: 0;+ padding: 0;+ list-style: none;+}+.signing-request__steps button {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ width: 100%;+ padding: 8px 4px;+ border: 0;+ border-radius: 8px;+ background: transparent;+ color: var(--c-text-muted);+ font: inherit;+ font-size: 12px;+ cursor: pointer;+}+.signing-request__steps button > span {+ display: grid;+ place-items: center;+ width: 28px;+ height: 28px;+ border: 1px solid var(--c-border);+ border-radius: 50%;+}+.signing-request__steps [aria-current="step"] {+ color: var(--c-accent-fg);+ font-weight: 600;+}+.signing-request__steps [aria-current="step"] > span {+ border-color: var(--c-primary);+ background: var(--c-primary-subtle);+}+.signing-request__steps button:disabled {+ opacity: 0.5;+ cursor: default;+}+.signing-request__steps button:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: 2px;+}+.signing-request__step-actions {+ display: flex;+ gap: 12px;+ margin-top: auto;+}+.signing-request__step-actions > :first-child:not(:last-child) {+ flex-shrink: 0;+}+.signing-request__heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 12px;+ margin-bottom: 16px;+}+.signing-request__heading h2 {+ margin: 0;+ font-size: 16px;+ font-weight: 600;+}+.signing-request__selection-count {+ color: var(--c-text-muted);+ font-size: 13px;+}+.signing-request__calendar {+ min-width: 0;+ padding: 16px 20px;+ margin: 0;+ border: 1px solid var(--c-border);+ border-radius: 12px;+}+.signing-request__calendar legend {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 0 6px;+ font-size: 14px;+ font-weight: 600;+}+.signing-request__date-value {+ display: flex;+ align-items: center;+ justify-content: space-between;+ min-height: 32px;+ margin-bottom: 8px;+ color: var(--c-text-muted);+ font-size: 13px;+}+.signing-request__month,+.signing-request__month-header {+ width: 100%;+ max-width: none;+}+.signing-request__month {+ table-layout: fixed;+}+.signing-request__day {+ width: 100%;+}+@media (min-width: 1100px) {+ .signing-workspace__create {+ grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr);+ gap: 28px;+ max-width: 1600px;+ }+ .signing-workspace__document-picker {+ display: flex;+ flex-direction: column;+ margin-bottom: 0;+ padding: 0 28px 0 0;+ border-bottom: 0;+ border-right: 1px solid var(--c-border);+ }+ .signing-document-picker__selected {+ flex: 1;+ min-height: 0;+ }+ .signing-document-preview {+ flex: 1;+ min-height: 0;+ max-width: none;+ aspect-ratio: auto;+ contain: size;+ }+ .signing-document-picker__grid {+ max-height: clamp(420px, calc(100dvh - 260px), 900px);+ }+}+@media (max-width: 960px) {+ .signing-workspace__list-heading {+ grid-template-columns: minmax(0, 1fr) auto;+ gap: 1rem;+ }+ .signing-workspace__search {+ grid-column: 1;+ }+ .signing-workspace__list-action {+ grid-column: 2;+ }+}+@media (max-width: 800px) {+ .signing-workspace__table-controls .sui-dtfb__row,+ .signing-workspace__table-controls .sui-dtfb__active {+ justify-content: flex-start;+ }+ .signing-workspace__header {+ padding: 8px 12px;+ }+ .signing-workspace__body {+ padding: 16px;+ }+ .signing-workspace__detail {+ display: flex;+ flex-direction: column;+ overflow-y: auto;+ }+ .signing-workspace__preview {+ flex: 0 0 55vh;+ }+ .signing-workspace__panel {+ overflow: visible;+ border-left: 0;+ border-top: 1px solid var(--c-border);+ }+ .signing-workspace__create {+ padding: 16px;+ }+ .signing-request__calendar {+ padding: 12px 8px;+ }+}++@media (max-width: 560px) {+ .signing-workspace__list-heading {+ grid-template-columns: minmax(0, 1fr);+ }+ .signing-workspace__search {+ grid-row: 2;+ }+ .signing-workspace__list-action {+ grid-column: 1;+ }+}++@media (max-height: 560px) {+ .sign-menu__personal {+ padding: 12px;+ }+ .sign-menu__tool {+ flex-direction: row;+ align-items: center;+ padding: 8px;+ }+ .sign-menu__tool svg {+ margin: 0;+ flex-shrink: 0;+ }+ .sign-menu__tool span,+ .sign-menu__filters > .sign-menu__hint {+ display: none;+ }+ .sign-menu__session-header {+ padding: 8px 12px 0;+ }+ .sign-menu__heading {+ margin-bottom: 6px;+ }+ .sign-menu__filters {+ padding: 8px 12px;+ }+}diff --git a/frontend/editor/src/core/components/shared/signing/signingDetail.css b/frontend/editor/src/core/components/shared/signing/signingDetail.cssnew file mode 100644index 0000000000..012aca7650--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/signingDetail.css@@ -0,0 +1,221 @@+.signing-detail {+ display: flex;+ flex-direction: column;+ min-height: 100%;+ min-width: 0;+ color: var(--c-text);+}+.signing-detail__body {+ display: flex;+ flex-direction: column;+ gap: 28px;+ padding: 24px;+}+.signing-detail h2,+.signing-detail h3,+.signing-detail p {+ margin: 0;+}+.signing-detail h2 {+ font-size: 20px;+ line-height: 1.4;+ font-weight: 600;+ overflow-wrap: anywhere;+}+.signing-detail h3 {+ font-size: 15px;+ font-weight: 600;+}+.signing-detail__header {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 16px;+}+.signing-detail__header-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ width: 100%;+}+.signing-detail__sender {+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 13px;+ overflow-wrap: anywhere;+}+.signing-detail__sender time {+ display: block;+ margin-top: 3px;+ color: var(--c-text-muted);+ font-size: 12px;+}+.signing-detail__due {+ display: flex;+ align-items: center;+ gap: 8px;+ color: var(--c-text-muted);+ font-size: 13px;+}+.signing-detail__message {+ width: 100%;+ padding: 12px 16px;+ border-left: 2px solid var(--c-border-strong);+ background: var(--c-surface-sunken);+ border-radius: 0 8px 8px 0;+}+.signing-detail__message p {+ margin-top: 6px;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ font-size: 13px;+ line-height: 1.5;+ color: var(--c-text-muted);+}+.signing-detail__heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 8px;+}+.signing-detail__section {+ display: flex;+ flex-direction: column;+ gap: 16px;+}+.signing-detail__summary {+ display: flex;+ flex-direction: column;+ gap: 14px;+ padding: 18px;+ border: 1px solid var(--c-border);+ border-radius: 12px;+ background: var(--c-surface-raised);+}+.signing-detail__summary p,+.signing-detail__hint {+ font-size: 13px;+ line-height: 1.5;+ color: var(--c-text-muted);+}+.signing-detail__footer {+ display: flex;+ flex-direction: column;+ gap: 16px;+ margin-top: auto;+ padding: 20px 24px;+ border-top: 1px solid var(--c-border);+ background: var(--c-surface);+}+.signing-detail__footer .sui-btn {+ white-space: normal;+ height: auto;+ min-height: 36px;+}+.signing-detail__secondary {+ display: flex;+ flex-wrap: wrap;+ justify-content: space-between;+ gap: 8px;+}+.signing-participants {+ display: flex;+ flex-direction: column;+ gap: 10px;+ list-style: none;+ margin: 0;+ padding: 0;+}+.signing-participant {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 14px;+ border: 1px solid var(--c-border);+ border-radius: 10px;+}+.signing-participant__identity {+ flex: 1;+ min-width: 0;+ font-size: 14px;+}+.signing-participant__identity strong {+ display: block;+ font-weight: 500;+ overflow-wrap: anywhere;+}+.signing-participant__email {+ display: block;+ margin: 3px 0 5px;+ font-size: 12px;+ color: var(--c-text-muted);+ overflow-wrap: anywhere;+}+.signing-participant__color {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex-shrink: 0;+}+.signing-controls__picker.sui-btn {+ min-height: 72px;+ height: auto;+ border-radius: 10px;+}+.signing-controls__preview {+ display: flex;+ align-items: center;+ justify-content: flex-start;+ height: 64px;+ min-width: 0;+ flex: 1;+ padding: 6px 12px;+ background: var(--c-document-bg);+ border-radius: 6px;+ overflow: hidden;+}+.signing-controls__preview img {+ display: block;+ width: 100%;+ height: 100%;+ object-fit: contain;+ object-position: left center;+}+.signing-finalize__group {+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding: 16px;+ border: 1px solid var(--c-border);+ border-radius: 10px;+}+.signing-finalize__list {+ display: flex;+ flex-direction: column;+ gap: 10px;+ list-style: none;+ margin: 0;+ padding: 0;+}+.signing-finalize__list li {+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 14px;+ overflow-wrap: anywhere;+}+.signing-finalize__list svg {+ flex-shrink: 0;+}+@media (max-width: 800px) {+ .signing-detail__body {+ padding: 20px;+ gap: 24px;+ }+ .signing-detail__footer {+ padding: 20px;+ }+}diff --git a/frontend/editor/src/core/components/shared/signing/steps/ReviewSessionStep.tsx b/frontend/editor/src/core/components/shared/signing/steps/ReviewSessionStep.tsxindex 29a6a7c98a..f3ccd34f18 100644--- a/frontend/editor/src/core/components/shared/signing/steps/ReviewSessionStep.tsx+++ b/frontend/editor/src/core/components/shared/signing/steps/ReviewSessionStep.tsx@@ -79,7 +79,7 @@ export const ReviewSessionStep: React.FC<ReviewSessionStepProps> = ({<Text size="sm">{t("groupSigning.steps.review.participantCount", {count: participantCount,- defaultValue: "{{count}} participant(s) will sign in order",+ defaultValue: "{{count}} participant(s) can sign in any order",})}</Text></div>diff --git a/frontend/editor/src/core/components/shared/signing/useSignMenuSessions.ts b/frontend/editor/src/core/components/shared/signing/useSignMenuSessions.tsnew file mode 100644index 0000000000..cb5fdebeb5--- /dev/null+++ b/frontend/editor/src/core/components/shared/signing/useSignMenuSessions.ts@@ -0,0 +1,55 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ isSigningItemClosed,+ canReceiveSigningActivity,+ type SigningMenuItem,+} from "@app/utils/signingItems";++export type SessionTab = "active" | "unread" | "closed";++function hasUnreadActivity(item: SigningMenuItem): boolean {+ return item.unread && canReceiveSigningActivity(item);+}++function isInTab(item: SigningMenuItem, tab: SessionTab): boolean {+ if (tab === "unread") return hasUnreadActivity(item);+ return isSigningItemClosed(item) === (tab === "closed");+}++/** Tab and search state for the Sign popover, reset each time it opens. */+export function useSignMenuSessions(items: SigningMenuItem[], opened: boolean) {+ const { t } = useTranslation();+ const [tab, setTab] = useState<SessionTab>("active");+ const [query, setQuery] = useState("");+ useEffect(() => {+ if (opened) {+ setTab("active");+ setQuery("");+ }+ }, [opened]);++ const tabs = [+ {+ key: "active" as const,+ label: t("certSign.collab.sessionList.active", "Active"),+ },+ {+ key: "unread" as const,+ label: t("signMenu.unreadTab", "Unread"),+ count: items.filter(hasUnreadActivity).length,+ },+ { key: "closed" as const, label: t("signMenu.completedTab", "Completed") },+ ];+ const needle = query.trim().toLocaleLowerCase();+ const rows = items.filter((item) => {+ const searchable = `${item.documentName} ${item.kind === "request" ? item.ownerUsername : t("signWorkspace.createdByMe", "Created by me")}`;+ return (+ isInTab(item, tab) && searchable.toLocaleLowerCase().includes(needle)+ );+ });++ return { tab, setTab, query, setQuery, tabs, rows };+}++export type SignMenuSessions = ReturnType<typeof useSignMenuSessions>;diff --git a/frontend/editor/src/core/components/shared/wetSignature/DrawSignatureCanvas.test.tsx b/frontend/editor/src/core/components/shared/wetSignature/DrawSignatureCanvas.test.tsxnew file mode 100644index 0000000000..2ac3d522ce--- /dev/null+++ b/frontend/editor/src/core/components/shared/wetSignature/DrawSignatureCanvas.test.tsx@@ -0,0 +1,46 @@+import { fireEvent, render } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { afterEach, expect, it, vi } from "vitest";+import { DrawSignatureCanvas } from "@app/components/shared/wetSignature/DrawSignatureCanvas";++afterEach(() => vi.restoreAllMocks());++it("maps the full displayed drawing area to the saved canvas at narrow widths", () => {+ const ctx = {+ clearRect: vi.fn(),+ beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ stroke: vi.fn(),+ };+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(+ ctx as unknown as CanvasRenderingContext2D,+ );+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(+ "data:image/png;base64,AA==",+ );+ const onChange = vi.fn();+ const { container } = render(+ <MantineProvider>+ <DrawSignatureCanvas signature={null} onChange={onChange} />+ </MantineProvider>,+ );+ const canvas = container.querySelector("canvas")!;+ vi.spyOn(canvas, "getBoundingClientRect").mockReturnValue({+ x: 10,+ y: 20,+ left: 10,+ top: 20,+ right: 210,+ bottom: 95,+ width: 200,+ height: 75,+ toJSON: () => ({}),+ });+ fireEvent.mouseDown(canvas, { clientX: 20, clientY: 30 });+ fireEvent.mouseMove(canvas, { clientX: 200, clientY: 85 });+ fireEvent.mouseUp(canvas);+ expect(ctx.moveTo).toHaveBeenCalledWith(20, 20);+ expect(ctx.lineTo).toHaveBeenCalledWith(380, 130);+ expect(onChange).toHaveBeenCalledWith("data:image/png;base64,AA==");+});diff --git a/frontend/editor/src/core/components/shared/wetSignature/DrawSignatureCanvas.tsx b/frontend/editor/src/core/components/shared/wetSignature/DrawSignatureCanvas.tsxindex e8fb8a750c..26b1f90ed8 100644--- a/frontend/editor/src/core/components/shared/wetSignature/DrawSignatureCanvas.tsx+++ b/frontend/editor/src/core/components/shared/wetSignature/DrawSignatureCanvas.tsx@@ -45,8 +45,8 @@ export const DrawSignatureCanvas: React.FC<DrawSignatureCanvasProps> = ({const canvas = canvasRef.current;if (!canvas) return;const rect = canvas.getBoundingClientRect();- const x = e.clientX - rect.left;- const y = e.clientY - rect.top;+ const x = ((e.clientX - rect.left) * canvas.width) / rect.width;+ const y = ((e.clientY - rect.top) * canvas.height) / rect.height;const ctx = canvas.getContext("2d");if (!ctx) return;@@ -59,8 +59,8 @@ export const DrawSignatureCanvas: React.FC<DrawSignatureCanvasProps> = ({const canvas = canvasRef.current;if (!canvas) return;const rect = canvas.getBoundingClientRect();- const x = e.clientX - rect.left;- const y = e.clientY - rect.top;+ const x = ((e.clientX - rect.left) * canvas.width) / rect.width;+ const y = ((e.clientY - rect.top) * canvas.height) / rect.height;const ctx = canvas.getContext("2d");if (!ctx) return;diff --git a/frontend/editor/src/core/components/shared/wetSignature/TypeSignatureText.tsx b/frontend/editor/src/core/components/shared/wetSignature/TypeSignatureText.tsxindex c76e2261d6..94a9f11eb4 100644--- a/frontend/editor/src/core/components/shared/wetSignature/TypeSignatureText.tsx+++ b/frontend/editor/src/core/components/shared/wetSignature/TypeSignatureText.tsx@@ -55,16 +55,23 @@ export const TypeSignatureText: React.FC<TypeSignatureTextProps> = ({ctx.font = `${fontSize}px ${fontFamily}`;const metrics = ctx.measureText(text);const textWidth = metrics.width;- const _textHeight = fontSize * 1.2; // Approximate height// Center text on canvasctx.fillStyle = color;ctx.textBaseline = "middle";ctx.fillText(text, (canvas.width - textWidth) / 2, canvas.height / 2);- // Convert to base64- const dataUrl = canvas.toDataURL("image/png");- onSignatureChange(dataUrl);+ // Export the ink bounds: the fixed preview canvas shrinks short names when placed on a PDF.+ const exportCanvas = document.createElement("canvas");+ exportCanvas.width = Math.max(1, Math.ceil(textWidth + fontSize));+ exportCanvas.height = Math.max(1, Math.ceil(fontSize * 2));+ const exportContext = exportCanvas.getContext("2d");+ if (!exportContext) return;+ exportContext.font = `${fontSize}px ${fontFamily}`;+ exportContext.fillStyle = color;+ exportContext.textBaseline = "middle";+ exportContext.fillText(text, fontSize / 2, exportCanvas.height / 2);+ onSignatureChange(exportCanvas.toDataURL("image/png"));}, [text, fontFamily, fontSize, color, onSignatureChange]);const fontOptions = [diff --git a/frontend/editor/src/core/components/tools/ToolPicker.tsx b/frontend/editor/src/core/components/tools/ToolPicker.tsxindex 85c9b2961f..c6561ee7ea 100644--- a/frontend/editor/src/core/components/tools/ToolPicker.tsx+++ b/frontend/editor/src/core/components/tools/ToolPicker.tsx@@ -11,7 +11,6 @@ import NoToolsFound from "@app/components/tools/shared/NoToolsFound";import { renderToolButtons } from "@app/components/tools/shared/renderToolButtons";import ToolButton from "@app/components/tools/toolPicker/ToolButton";import { useToolWorkflowData } from "@app/contexts/ToolWorkflowContext";-import { useSigningBadgeCount } from "@app/hooks/signing/useSigningBadgeCount";import { useIsScrolled } from "@app/hooks/useIsScrolled";import { ToolId } from "@app/types/toolId";import { getSubcategoryLabel } from "@app/data/toolsTaxonomy";@@ -84,29 +83,13 @@ const ToolPicker = ({[visibleSections],);- // Signing items needing the user's attention: requests awaiting their- // signature, plus their own sessions newly signed since last opened- // (0 when group signing is disabled).- const signingBadgeCount = useSigningBadgeCount();-const recommendedItems = useMemo(() => {const items: Array<{ id: string; tool: ToolRegistryEntry }> = [];quickSection?.subcategories.forEach((sc: SubcategoryGroup) =>sc.tools.forEach((toolEntry) => items.push(toolEntry)),);- // While signing needs the user's attention, surface Shared Signing at the- // top of Recommended so it's easy to find without hunting in the Signing group.- if (signingBadgeCount > 0) {- const sharedSignTool = toolRegistry["sharedSign" as ToolId];- if (sharedSignTool) {- return [- { id: "sharedSign", tool: sharedSignTool },- ...items.filter(({ id }) => id !== "sharedSign"),- ];- }- }return items;- }, [quickSection, signingBadgeCount, toolRegistry]);+ }, [quickSection]);const allSection = useMemo(() => visibleSections.find((s) => s.key === "all"),@@ -186,9 +169,6 @@ const ToolPicker = ({onSelect={onSelect}hasStarsshowDescription- badgeCount={- id === "sharedSign" ? signingBadgeCount : undefined- }/>))}</div>@@ -243,9 +223,6 @@ const ToolPicker = ({isSelected={selectedToolKey === id}onSelect={onSelect}hasStars- badgeCount={- id === "sharedSign" ? signingBadgeCount : undefined- }/>))}</div>diff --git a/frontend/editor/src/core/components/tools/certSign/CertificateSelector.css b/frontend/editor/src/core/components/tools/certSign/CertificateSelector.cssnew file mode 100644index 0000000000..51af92f55c--- /dev/null+++ b/frontend/editor/src/core/components/tools/certSign/CertificateSelector.css@@ -0,0 +1,117 @@+.certificate-choices {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.certificate-choice {+ align-items: center;+ padding: 1rem;+ border: 1px solid var(--c-border);+ border-radius: var(--radius-lg);+ background: var(--c-surface);+ transition:+ border-color var(--motion-fast),+ background var(--motion-fast);+}++.certificate-choice:not(.sui-radio--disabled):hover {+ background: var(--c-hover);+ border-color: var(--c-border-strong);+}++.certificate-choice:has(input:checked) {+ border-color: var(--c-primary);+ background: var(--c-primary-subtle);+}++.certificate-choice:has(input:focus-visible) {+ outline: 2px solid var(--c-primary);+ outline-offset: 3px;+}++.certificate-choice .sui-radio__dot {+ order: 1;+ margin: 0 0 0 0.5rem;+}++.certificate-choice .sui-radio__text {+ flex: 1;+ min-width: 0;+}++.certificate-choice__content {+ display: flex;+ gap: 0.875rem;+ align-items: center;+}++.certificate-choice__icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+ width: 2.5rem;+ height: 2.5rem;+ border-radius: var(--radius-md);+ color: var(--c-text-subtle);+ background: var(--c-surface-sunken);+}++.certificate-choice:has(input:checked) .certificate-choice__icon {+ color: var(--c-accent-fg);+ background: var(--c-surface);+}++.certificate-choice__copy {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.certificate-choice__title {+ font-size: 0.875rem;+ font-weight: 600;+ line-height: 1.4;+}++.certificate-choice__description {+ font-size: 0.8125rem;+ font-weight: 400;+ line-height: 1.45;+ color: var(--c-text-subtle);+}++.certificate-upload {+ padding: 1rem;+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-lg);+ background: var(--c-surface-sunken);+}++.certificate-config__details {+ border-top: 1px solid var(--c-border-subtle);+ padding-top: 0.5rem;+}++.certificate-config__details-toggle {+ width: 100%;+}++.certificate-config__fields {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 12rem), 1fr));+ gap: 0.875rem;+ padding-top: 0.75rem;+}++.certificate-config__footer {+ width: 100%;+}++.certificate-config__validation {+ padding: 0.75rem 1rem;+ border-radius: var(--radius-md);+ background: var(--c-surface-sunken);+}diff --git a/frontend/editor/src/core/components/tools/certSign/CertificateSelector.test.tsx b/frontend/editor/src/core/components/tools/certSign/CertificateSelector.test.tsxnew file mode 100644index 0000000000..20af07bbb1--- /dev/null+++ b/frontend/editor/src/core/components/tools/certSign/CertificateSelector.test.tsx@@ -0,0 +1,101 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { beforeEach, expect, it, vi } from "vitest";+import {+ CertificateSelector,+ type CertificateType,+} from "@app/components/tools/certSign/CertificateSelector";++const { config } = vi.hoisted(() => ({+ config: { runningProOrHigher: false, serverCertificateEnabled: true },+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config }),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));+vi.mock("@app/components/shared/FileUploadButton", () => ({+ default: () => <button>Upload certificate file</button>,+}));++beforeEach(() => {+ config.runningProOrHigher = false;+ config.serverCertificateEnabled = true;+});++function setup(certType: CertificateType = "SERVER") {+ const onCertTypeChange = vi.fn();+ render(+ <MantineProvider>+ <CertificateSelector+ certType={certType}+ onCertTypeChange={onCertTypeChange}+ uploadFormat="PKCS12"+ onUploadFormatChange={vi.fn()}+ p12File={null}+ onP12FileChange={vi.fn()}+ privateKeyFile={null}+ onPrivateKeyFileChange={vi.fn()}+ certFile={null}+ onCertFileChange={vi.fn()}+ jksFile={null}+ onJksFileChange={vi.fn()}+ password=""+ onPasswordChange={vi.fn()}+ />+ </MantineProvider>,+ );+ return onCertTypeChange;+}++it("offers organization signing without a paid license", () => {+ const onChange = setup("UPLOAD");+ fireEvent.click(+ screen.getByRole("radio", { name: /Stirling Sign · Organization/ }),+ );+ expect(onChange).toHaveBeenCalledWith("SERVER");+ expect(+ screen.queryByRole("radio", { name: /Stirling Sign · Personal/ }),+ ).not.toBeInTheDocument();+});++it("selects the available organization certificate when personal signing is unavailable", () => {+ const onChange = setup("USER_CERT");+ expect(onChange).toHaveBeenCalledWith("SERVER");+});++it("preserves a server certificate selection on the free tier", () => {+ const onChange = setup();+ expect(+ screen.getByRole("radio", { name: /Stirling Sign · Organization/ }),+ ).toBeChecked();+ expect(onChange).not.toHaveBeenCalled();+});++it("falls back to upload when the administrator disables organization signing", () => {+ config.serverCertificateEnabled = false;+ const onChange = setup();+ expect(+ screen.queryByRole("radio", { name: /Stirling Sign · Organization/ }),+ ).not.toBeInTheDocument();+ expect(onChange).toHaveBeenCalledWith("UPLOAD");+});++it("keeps personal signing available on paid servers with organization signing disabled", () => {+ config.runningProOrHigher = true;+ config.serverCertificateEnabled = false;+ const onChange = setup("USER_CERT");+ expect(+ screen.getByRole("radio", { name: /Stirling Sign · Personal/ }),+ ).toBeChecked();+ expect(+ screen.queryByRole("radio", { name: /Stirling Sign · Organization/ }),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole("radio", { name: "Upload a certificate" }),+ ).toBeInTheDocument();+ expect(onChange).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/core/components/tools/certSign/CertificateSelector.tsx b/frontend/editor/src/core/components/tools/certSign/CertificateSelector.tsxindex 0cccbe4a40..21b573f062 100644--- a/frontend/editor/src/core/components/tools/certSign/CertificateSelector.tsx+++ b/frontend/editor/src/core/components/tools/certSign/CertificateSelector.tsx@@ -1,13 +1,71 @@-import { Stack, Radio, Divider, TextInput, Text, Group } from "@mantine/core";-import { Button } from "@app/ui/Button";+import { Stack, Text } from "@mantine/core";+import { Radio } from "@app/ui/Radio";+import { Icon, type IconName } from "@app/ui/Icon";+import { FormField } from "@app/ui/FormField";+import { Input } from "@app/ui/Input";+import { SegmentedControl } from "@app/ui/SegmentedControl";import { useTranslation } from "react-i18next";-import { useEffect } from "react";+import { useEffect, useId } from "react";import { useAppConfig } from "@app/contexts/AppConfigContext";import FileUploadButton from "@app/components/shared/FileUploadButton";+import "@app/components/tools/certSign/CertificateSelector.css";export type CertificateType = "USER_CERT" | "SERVER" | "UPLOAD";export type UploadFormat = "PKCS12" | "PFX" | "PEM" | "JKS";+function CertificateChoice({+ name,+ value,+ selected,+ onSelect,+ disabled,+ icon,+ title,+ description,+}: {+ name: string;+ value: CertificateType;+ selected: CertificateType;+ onSelect: (value: CertificateType) => void;+ disabled: boolean;+ icon: IconName;+ title: string;+ description: string;+}) {+ const titleId = useId();+ const descriptionId = useId();+ return (+ <Radio+ className="certificate-choice"+ name={name}+ value={value}+ checked={selected === value}+ onChange={() => onSelect(value)}+ disabled={disabled}+ aria-labelledby={titleId}+ aria-describedby={descriptionId}+ label={+ <span className="certificate-choice__content">+ <span className="certificate-choice__icon" aria-hidden>+ <Icon name={icon} size={22} />+ </span>+ <span className="certificate-choice__copy">+ <span id={titleId} className="certificate-choice__title">+ {title}+ </span>+ <span+ id={descriptionId}+ className="certificate-choice__description"+ >+ {description}+ </span>+ </span>+ </span>+ }+ />+ );+}+interface CertificateSelectorProps {certType: CertificateType;onCertTypeChange: (certType: CertificateType) => void;@@ -44,15 +102,26 @@ export const CertificateSelector: React.FC<CertificateSelectorProps> = ({disabled = false,}) => {const { t } = useTranslation();+ const choiceName = useId();const { config } = useAppConfig();- const isServerPlan = config?.runningProOrHigher ?? false;+ const personalCertificateAvailable = config?.runningProOrHigher ?? false;+ const serverCertificateAvailable = config?.serverCertificateEnabled ?? false;+ const managedCertificateAvailable =+ personalCertificateAvailable || serverCertificateAvailable;- // If managed cert types are not available, reset to UPLOADuseEffect(() => {- if (!isServerPlan && (certType === "USER_CERT" || certType === "SERVER")) {- onCertTypeChange("UPLOAD");+ if (+ (certType === "USER_CERT" && !personalCertificateAvailable) ||+ (certType === "SERVER" && !serverCertificateAvailable)+ ) {+ onCertTypeChange(serverCertificateAvailable ? "SERVER" : "UPLOAD");}- }, [isServerPlan, certType, onCertTypeChange]);+ }, [+ personalCertificateAvailable,+ serverCertificateAvailable,+ certType,+ onCertTypeChange,+ ]);const handleFormatChange = (fmt: UploadFormat) => {onUploadFormatChange(fmt);@@ -70,98 +139,93 @@ export const CertificateSelector: React.FC<CertificateSelectorProps> = ({return (<Stack gap="md">- {/* Managed certificate options — Team plan only */}- {isServerPlan && (- <Radio.Group- value={certType}- onChange={(val) => onCertTypeChange(val as CertificateType)}+ {managedCertificateAvailable && (+ <div+ className="certificate-choices"+ role="radiogroup"+ aria-label={t(+ "certSign.collab.signRequest.certificateChoice",+ "Select a certificate to sign with",+ )}>- <Stack gap="sm">- <Radio+ {personalCertificateAvailable && (+ <CertificateChoice+ name={choiceName}value="USER_CERT"+ selected={certType}+ onSelect={onCertTypeChange}disabled={disabled}- label={- <Stack gap={1}>- <Text size="sm" fw={500}>- {t(- "certSign.collab.signRequest.usePersonalCert",- "Personal Certificate",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "certSign.collab.signRequest.usePersonalCertDesc",- "Auto-generated for your account",- )}- </Text>- </Stack>- }+ icon="user"+ title={t(+ "certSign.collab.signRequest.usePersonalCert",+ "Stirling Sign · Personal",+ )}+ description={t(+ "certSign.collab.signRequest.usePersonalCertDesc",+ "Sign with the certificate created for your account.",+ )}/>- <Radio+ )}+ {serverCertificateAvailable && (+ <CertificateChoice+ name={choiceName}value="SERVER"+ selected={certType}+ onSelect={onCertTypeChange}disabled={disabled}- label={- <Stack gap={1}>- <Text size="sm" fw={500}>- {t(- "certSign.collab.signRequest.useServerCert",- "Organization Certificate",- )}- </Text>- <Text size="xs" c="dimmed">- {t(- "certSign.collab.signRequest.useServerCertDesc",- "Shared organization certificate",- )}- </Text>- </Stack>- }- />- <Radio- value="UPLOAD"- disabled={disabled}- label={- <Text size="sm" fw={500}>- {t(- "certSign.collab.signRequest.uploadCert",- "Custom Certificate",- )}- </Text>- }- />- </Stack>- </Radio.Group>- )}-- {/* Upload section */}- {certType === "UPLOAD" && (- <Stack gap="sm">- {isServerPlan && (- <Divider- label={t(- "certSign.collab.signRequest.uploadCert",- "Custom Certificate",+ icon="building-2"+ title={t(+ "certSign.collab.signRequest.useServerCert",+ "Stirling Sign · Organization",+ )}+ description={t(+ "certSign.collab.signRequest.useServerCertDesc",+ "Sign with this server's shared organization certificate.",)}- labelPosition="left"/>)}+ <CertificateChoice+ name={choiceName}+ value="UPLOAD"+ selected={certType}+ onSelect={onCertTypeChange}+ disabled={disabled}+ icon="upload"+ title={t(+ "certSign.collab.signRequest.uploadCert",+ "Upload a certificate",+ )}+ description={t(+ "certSign.collab.signRequest.uploadCertDesc",+ "Use your own PKCS12, PFX, PEM or JKS certificate.",+ )}+ />+ </div>+ )}- {/* Format picker */}- <Group gap="xs">- {(["PKCS12", "PFX", "PEM", "JKS"] as UploadFormat[]).map((fmt) => (- <Button- key={fmt}- size="sm"- variant={uploadFormat === fmt ? "primary" : "secondary"}- onClick={() => handleFormatChange(fmt)}- disabled={disabled}- >- {fmt}- </Button>- ))}- </Group>+ {certType === "UPLOAD" && (+ <Stack gap="md" className="certificate-upload">+ <Text size="sm" fw={600} c="var(--c-text)">+ {t(+ "certSign.collab.signRequest.certModal.format",+ "Certificate format",+ )}+ </Text>+ <SegmentedControl<UploadFormat>+ options={(["PKCS12", "PFX", "PEM", "JKS"] as UploadFormat[]).map(+ (format) => ({ value: format, label: format }),+ )}+ value={uploadFormat}+ onChange={handleFormatChange}+ disabled={disabled}+ ariaLabel={t(+ "certSign.collab.signRequest.certModal.format",+ "Certificate format",+ )}+ fullWidth+ variant="secondary"+ />- {/* PKCS12 / PFX */}{(uploadFormat === "PKCS12" || uploadFormat === "PFX") && (<FileUploadButtonfile={p12File ?? undefined}@@ -218,7 +282,6 @@ export const CertificateSelector: React.FC<CertificateSelectorProps> = ({</Stack>)}- {/* JKS */}{uploadFormat === "JKS" && (<FileUploadButtonfile={jksFile ?? undefined}@@ -229,23 +292,24 @@ export const CertificateSelector: React.FC<CertificateSelectorProps> = ({/>)}- {/* Password */}{showPassword && (- <TextInput+ <FormFieldlabel={t("certSign.collab.signRequest.password","Certificate Password",)}- type="password"- placeholder={t(- "certSign.passwordOptional",- "Leave empty if no password",- )}- value={password}- onChange={(e) => onPasswordChange(e.target.value)}- disabled={disabled}- size="sm"- />+ >+ <Input+ type="password"+ placeholder={t(+ "certSign.passwordOptional",+ "Leave empty if no password",+ )}+ value={password}+ onChange={(e) => onPasswordChange(e.target.value)}+ disabled={disabled}+ />+ </FormField>)}</Stack>)}diff --git a/frontend/editor/src/core/components/tools/certSign/SignatureSettingsInput.tsx b/frontend/editor/src/core/components/tools/certSign/SignatureSettingsInput.tsxindex a89d66e447..d230084ae3 100644--- a/frontend/editor/src/core/components/tools/certSign/SignatureSettingsInput.tsx+++ b/frontend/editor/src/core/components/tools/certSign/SignatureSettingsInput.tsx@@ -1,5 +1,15 @@-import { Stack, Text, TextInput, NumberInput, Switch } from "@mantine/core";+import {+ Stack,+ Text,+ TextInput,+ NumberInput,+ Switch,+ Group,+} from "@mantine/core";import { Button } from "@app/ui/Button";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Icon } from "@app/ui/Icon";+import { Tooltip } from "@app/ui/Tooltip";import { useTranslation } from "react-i18next";export interface SignatureSettings {@@ -33,17 +43,28 @@ const SignatureSettingsInput = ({return (<Stack gap="sm">- <Text size="sm" fw={600}>- {t("certSign.collab.signatureSettings.title", "Signature Appearance")}- </Text>- <Text size="xs" c="dimmed">- {t(- "certSign.collab.signatureSettings.description",- "Configure how signatures will appear for all participants",- )}- </Text>+ <Group gap="xs">+ <Text size="sm" fw={600}>+ {t("certSign.collab.signatureSettings.title", "Signature Appearance")}+ </Text>+ <Tooltip+ content={t(+ "certSign.collab.signatureSettings.description",+ "Configure how signatures will appear for all participants",+ )}+ >+ <ActionIcon+ variant="quiet"+ aria-label={t(+ "certSign.collab.signatureSettings.title",+ "Signature Appearance",+ )}+ >+ <Icon name="info" size={16} />+ </ActionIcon>+ </Tooltip>+ </Group>- {/* Signature Visibility */}<div style={{ display: "flex", gap: "4px" }}><Buttonaccent={!value.showSignature ? "default" : "neutral"}@@ -83,7 +104,6 @@ const SignatureSettingsInput = ({</Button></div>- {/* Visible Signature Options */}{value.showSignature && (<Stack gap="sm"><TextInput@@ -126,23 +146,36 @@ const SignatureSettingsInput = ({</Stack>)}- {/* Summary Page Toggle */}- <Switch- label={t(- "certSign.collab.sessionCreation.includeSummaryPage",- "Include Signature Summary Page",- )}- description={t(- "certSign.collab.sessionCreation.includeSummaryPageHelp",- "A summary page will be added at the end with all signature metadata. The digital certificate signature boxes on individual pages will be suppressed (wet signatures are unaffected).",- )}- checked={value.includeSummaryPage || false}- onChange={(event) =>- handleChange("includeSummaryPage", event.currentTarget.checked)- }- disabled={disabled}- size="sm"- />+ <Group gap="xs" wrap="nowrap" align="center">+ <Switch+ label={t(+ "certSign.collab.sessionCreation.includeSummaryPage",+ "Include Signature Summary Page",+ )}+ checked={value.includeSummaryPage || false}+ onChange={(event) =>+ handleChange("includeSummaryPage", event.currentTarget.checked)+ }+ disabled={disabled}+ size="sm"+ />+ <Tooltip+ content={t(+ "certSign.collab.sessionCreation.includeSummaryPageHelp",+ "A summary page will be added at the end with all signature metadata. The digital certificate signature boxes on individual pages will be suppressed (wet signatures are unaffected).",+ )}+ >+ <ActionIcon+ variant="quiet"+ aria-label={t(+ "certSign.collab.sessionCreation.includeSummaryPage",+ "Include Signature Summary Page",+ )}+ >+ <Icon name="info" size={16} />+ </ActionIcon>+ </Tooltip>+ </Group></Stack>);};diff --git a/frontend/editor/src/core/components/tools/certSign/WetSignatureInput.tsx b/frontend/editor/src/core/components/tools/certSign/WetSignatureInput.tsxindex af1913baa7..5ec5415611 100644--- a/frontend/editor/src/core/components/tools/certSign/WetSignatureInput.tsx+++ b/frontend/editor/src/core/components/tools/certSign/WetSignatureInput.tsx@@ -269,11 +269,11 @@ const WetSignatureInput = ({value="USER_CERT"label={t("certSign.collab.signRequest.usePersonalCert",- "Use My Personal Certificate",+ "Stirling Sign · Personal",)}description={t("certSign.collab.signRequest.usePersonalCertDesc",- "Auto-generated for your account",+ "Sign with the certificate created for your account.",)}disabled={disabled}/>@@ -281,11 +281,11 @@ const WetSignatureInput = ({value="SERVER"label={t("certSign.collab.signRequest.useServerCert",- "Use Organization Certificate",+ "Stirling Sign · Organization",)}description={t("certSign.collab.signRequest.useServerCertDesc",- "Shared organization certificate",+ "Sign with this server's shared organization certificate.",)}disabled={disabled}/>@@ -293,11 +293,11 @@ const WetSignatureInput = ({value="UPLOAD"label={t("certSign.collab.signRequest.uploadCert",- "Upload Custom Certificate",+ "Upload a certificate",)}description={t("certSign.collab.signRequest.uploadCertDesc",- "Use your own PKCS12 certificate",+ "Use your own PKCS12, PFX, PEM or JKS certificate.",)}disabled={disabled}/>diff --git a/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.stories.tsx b/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.stories.tsxindex 2962196a74..c3bf748752 100644--- a/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.stories.tsx+++ b/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.stories.tsx@@ -1,10 +1,26 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { CertificateConfigModal } from "@app/components/tools/certSign/modals/CertificateConfigModal";+import { AppConfigProvider } from "@app/contexts/AppConfigContext";const meta = {title: "Tools/CertSign/Modals/CertificateConfigModal",component: CertificateConfigModal,parameters: { layout: "fullscreen" },+ decorators: [+ (Story, context) => (+ <AppConfigProvider+ autoFetch={false}+ bootstrapMode="non-blocking"+ initialConfig={{+ runningProOrHigher: context.parameters.personalCertificate ?? true,+ serverCertificateEnabled:+ context.parameters.serverCertificate ?? true,+ }}+ >+ <Story />+ </AppConfigProvider>+ ),+ ],args: {opened: true,onClose: () => {},@@ -21,6 +37,15 @@ export const MultipleSignatures: Story = {args: { signatureCount: 3 },};+export const OrganizationOnly: Story = {+ parameters: { personalCertificate: false },+};++export const UploadOnly: Story = {+ parameters: { personalCertificate: false, serverCertificate: false },+ args: { signatureCount: 0 },+};+export const Disabled: Story = {args: { disabled: true },};diff --git a/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.test.tsx b/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.test.tsxnew file mode 100644index 0000000000..83b02bae2a--- /dev/null+++ b/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.test.tsx@@ -0,0 +1,167 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { CertificateConfigModal } from "@app/components/tools/certSign/modals/CertificateConfigModal";++const { post, t } = vi.hoisted(() => ({+ post: vi.fn(),+ t: (key: string, fallback?: string) => fallback ?? key,+}));+vi.mock("@app/services/apiClient", () => ({ default: { post } }));+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t }) }));+vi.mock("@app/components/tools/certSign/CertificateSelector", () => ({+ CertificateSelector: (props: {+ onCertTypeChange: (value: string) => void;+ onP12FileChange: (file: File) => void;+ onPasswordChange: (value: string) => void;+ onUploadFormatChange: (value: string) => void;+ onPrivateKeyFileChange: (file: File) => void;+ onCertFileChange: (file: File) => void;+ }) => (+ <>+ <button+ onClick={() => {+ props.onCertTypeChange("UPLOAD");+ props.onP12FileChange(new File(["certificate"], "test.p12"));+ }}+ >+ Upload test certificate+ </button>+ <button+ onClick={() => {+ props.onCertTypeChange("UPLOAD");+ props.onUploadFormatChange("PEM");+ props.onPrivateKeyFileChange(new File(["key"], "key.pem"));+ props.onCertFileChange(new File(["cert"], "cert.pem"));+ }}+ >+ Use PEM+ </button>+ <input+ aria-label="Password"+ onChange={(event) => props.onPasswordChange(event.target.value)}+ />+ </>+ ),+}));++beforeEach(() => {+ vi.useFakeTimers();+ post.mockReset();+});+afterEach(() => {+ vi.useRealTimers();+});+const tick = () =>+ act(async () => {+ await vi.advanceTimersByTimeAsync(650);+ });+function setup() {+ const onSign = vi.fn().mockResolvedValue(undefined);+ render(+ <MantineProvider>+ <CertificateConfigModal+ opened+ onClose={vi.fn()}+ onSign={onSign}+ signatureCount={0}+ />+ </MantineProvider>,+ );+ return onSign;+}++it("blocks invalid certificates, then permits certificate-only signing after correction", async () => {+ const onSign = setup();+ post.mockResolvedValueOnce({+ data: { valid: false, error: "Incorrect password" },+ });+ fireEvent.click(screen.getByText("Upload test certificate"));+ expect(screen.getByRole("button", { name: "Sign Document" })).toBeDisabled();+ await tick();+ expect(screen.getByRole("button", { name: "Sign Document" })).toBeDisabled();+ post.mockResolvedValueOnce({+ data: { valid: true, subjectName: "Alice", notAfter: null },+ });+ fireEvent.change(screen.getByLabelText("Password"), {+ target: { value: "correct" },+ });+ await tick();+ expect(screen.getByRole("button", { name: "Sign Document" })).toBeEnabled();+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Sign Document" }));+ });+ expect(onSign).toHaveBeenCalledWith(+ expect.objectContaining({ password: "correct" }),+ "",+ "",+ );+});++it("ignores an older valid response after the password has changed", async () => {+ setup();+ let resolveOld: (value: unknown) => void = () => {};+ post.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveOld = resolve;+ }),+ );+ fireEvent.click(screen.getByText("Upload test certificate"));+ await tick();+ fireEvent.change(screen.getByLabelText("Password"), {+ target: { value: "wrong" },+ });+ post.mockResolvedValueOnce({+ data: { valid: false, error: "Incorrect password" },+ });+ await tick();+ await act(async () => {+ resolveOld({ data: { valid: true, subjectName: "Alice" } });+ });+ expect(screen.getByRole("button", { name: "Sign Document" })).toBeDisabled();+});++it("prevalidates both PEM files before enabling submission", async () => {+ setup();+ post.mockResolvedValueOnce({ data: { valid: true } });+ fireEvent.click(screen.getByText("Use PEM"));+ await tick();+ const payload = post.mock.calls[0][1] as FormData;+ expect(payload.get("certType")).toBe("PEM");+ expect(payload.get("privateKeyFile")).toBeInstanceOf(File);+ expect(payload.get("certFile")).toBeInstanceOf(File);+ expect(screen.getByRole("button", { name: "Sign Document" })).toBeEnabled();+});++it("keeps the certificate dialog open while a signature submission is in flight", async () => {+ const onClose = vi.fn();+ let finishSigning: () => void = () => {};+ const onSign = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ finishSigning = resolve;+ }),+ );+ render(+ <MantineProvider>+ <CertificateConfigModal+ opened+ onClose={onClose}+ onSign={onSign}+ signatureCount={0}+ />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Sign Document" }));+ expect(onSign).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ fireEvent.keyDown(document, { key: "Escape" });+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();+ expect(onClose).not.toHaveBeenCalled();+ await act(async () => {+ finishSigning();+ });+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(onClose).toHaveBeenCalledTimes(1);+});diff --git a/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.tsx b/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.tsxindex bc8fa55b95..4c56aee988 100644--- a/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.tsx+++ b/frontend/editor/src/core/components/tools/certSign/modals/CertificateConfigModal.tsx@@ -1,21 +1,17 @@-import {- Modal,- Stack,- Group,- Text,- Collapse,- TextInput,- Loader,-} from "@mantine/core";+import { Stack, Group, Text, Collapse, Loader } from "@mantine/core";import { Button } from "@app/ui/Button";+import { Modal } from "@app/ui/Modal";+import { FormField } from "@app/ui/FormField";+import { Input } from "@app/ui/Input";import { useTranslation } from "react-i18next";-import { useState, useEffect, useRef } from "react";+import { useState, useEffect, useMemo } from "react";import { Icon } from "@app/ui/Icon";import {CertificateSelector,CertificateType,UploadFormat,} from "@app/components/tools/certSign/CertificateSelector";+import { isAxiosError } from "axios";import apiClient from "@app/services/apiClient";export interface CertificateSubmitData {@@ -73,47 +69,65 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({const [certValidation, setCertValidation] = useState<CertValidationState>({status: "idle",});- const validationTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const [submitError, setSubmitError] = useState<string | null>(null);+ const [validatedPayload, setValidatedPayload] = useState<FormData | null>(+ null,+ );+ const validationPayload = useMemo(() => {+ if (certType !== "UPLOAD") return null;+ const form = new FormData();+ form.append("password", password);+ if (participantToken) form.append("participantToken", participantToken);+ if (uploadFormat === "PEM") {+ if (!privateKeyFile || !certFile) return null;+ form.append("certType", "PEM");+ form.append("privateKeyFile", privateKeyFile);+ form.append("certFile", certFile);+ } else {+ const file = uploadFormat === "JKS" ? jksFile : p12File;+ if (!file) return null;+ form.append("certType", uploadFormat === "JKS" ? "JKS" : "P12");+ form.append(uploadFormat === "JKS" ? "jksFile" : "p12File", file);+ }+ return form;+ }, [+ certType,+ uploadFormat,+ p12File,+ jksFile,+ privateKeyFile,+ certFile,+ password,+ participantToken,+ ]);- // Debounced certificate pre-validation: fires 600ms after cert file or password changesuseEffect(() => {- // Only validate uploaded keystores (not SERVER/USER_CERT, not PEM which uses separate files)- const keystoreFile = uploadFormat === "JKS" ? jksFile : p12File;- if (certType !== "UPLOAD" || !keystoreFile || uploadFormat === "PEM") {+ setSubmitError(null);+ setValidatedPayload(null);+ if (!opened || !validationPayload) {setCertValidation({ status: "idle" });return;}-- if (validationTimerRef.current) clearTimeout(validationTimerRef.current);+ let active = true;+ const abort = new AbortController();setCertValidation({ status: "validating" });-- validationTimerRef.current = setTimeout(async () => {+ const timer = setTimeout(async () => {try {- const formData = new FormData();- formData.append("certType", uploadFormat === "JKS" ? "JKS" : "P12");- formData.append("password", password);- if (uploadFormat === "JKS") {- formData.append("jksFile", keystoreFile);- } else {- formData.append("p12File", keystoreFile);- }-const endpoint = participantToken? "/api/v1/workflow/participant/validate-certificate": "/api/v1/security/cert-sign/validate-certificate";-- if (participantToken) {- formData.append("participantToken", participantToken);- }-const response = await apiClient.post<{valid: boolean;subjectName: string | null;notAfter: string | null;error: string | null;- }>(endpoint, formData);-+ }>(endpoint, validationPayload, {+ signal: abort.signal,+ suppressErrorToast: true,+ });+ if (!active) return;if (response.data.valid) {+ setValidatedPayload(validationPayload);setCertValidation({status: "valid",subjectName: response.data.subjectName,@@ -131,45 +145,37 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({});}} catch {- setCertValidation({- status: "error",- message: t(- "certSign.collab.signRequest.certModal.certNetworkError",- "Could not validate certificate",- ),- });+ if (active)+ setCertValidation({+ status: "error",+ message: t(+ "certSign.collab.signRequest.certModal.certNetworkError",+ "Could not validate certificate",+ ),+ });}}, 600);-return () => {- if (validationTimerRef.current) clearTimeout(validationTimerRef.current);+ active = false;+ clearTimeout(timer);+ abort.abort();};- }, [certType, uploadFormat, p12File, jksFile, password, participantToken]);+ }, [opened, validationPayload, participantToken, t]);- // Advanced settingsconst [showAdvanced, setShowAdvanced] = useState(false);const [reason, setReason] = useState(defaultReason);const [location, setLocation] = useState(defaultLocation);- const isUploadValid = () => {- if (certType !== "UPLOAD") return true;- switch (uploadFormat) {- case "PKCS12":- case "PFX":- return p12File !== null;- case "PEM":- return privateKeyFile !== null && certFile !== null;- case "JKS":- return jksFile !== null;- }- };-const isValid =- certType === "USER_CERT" || certType === "SERVER" || isUploadValid();+ certType !== "UPLOAD" ||+ (validationPayload !== null &&+ validatedPayload === validationPayload &&+ certValidation.status === "valid");const handleSign = async () => {if (!isValid) return;+ setSubmitError(null);setSigning(true);try {await onSign(@@ -186,7 +192,21 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({location,);} catch (error) {- console.error("Failed to sign document:", error);+ const data: unknown = isAxiosError(error) ? error.response?.data : null;+ const detail =+ data && typeof data === "object" && "detail" in data+ ? data.detail+ : null;+ setSubmitError(+ typeof detail === "string"+ ? detail+ : typeof data === "string"+ ? data+ : t(+ "signMenu.signFailed",+ "Signing failed. Check your certificate and try again; your placed marks are preserved.",+ ),+ );} finally {setSigning(false);}@@ -194,23 +214,59 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({return (<Modal- opened={opened}- onClose={onClose}+ open={opened}+ onClose={() => {+ if (!signing && !disabled) onClose();+ }}title={t("certSign.collab.signRequest.certModal.title",- "Configure Certificate",+ "Choose how to sign",)}- centered- size="lg"+ subtitle={t(+ "certSign.collab.signRequest.certModal.description",+ "Choose a certificate to complete your signature.",+ {+ count: signatureCount,+ },+ )}+ width="md"+ disableBackdropClose={signing || disabled}+ disableEscapeClose={signing || disabled}+ footer={+ <Group+ justify="space-between"+ wrap="wrap"+ className="certificate-config__footer"+ >+ <Button+ variant="secondary"+ onClick={onClose}+ disabled={signing || disabled}+ >+ {t("cancel", "Cancel")}+ </Button>+ <Button+ onClick={handleSign}+ disabled={+ !isValid ||+ disabled ||+ signing ||+ certValidation.status === "validating"+ }+ loading={signing}+ leftSection={<Icon name="shield-check" size={18} />}+ >+ {t("certSign.collab.signRequest.certModal.sign", "Sign Document")}+ </Button>+ </Group>+ }><Stack gap="md">- <Text size="sm" c="dimmed">- {t(- "certSign.collab.signRequest.certModal.description",- "You have placed {{count}} signature(s). Choose your certificate to complete signing.",- { count: signatureCount },- )}- </Text>+ {submitError && (+ <Text role="alert" size="sm" c="var(--c-danger)">+ {submitError}+ </Text>+ )}<CertificateSelectorcertType={certType}@@ -230,9 +286,12 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({disabled={disabled || signing}/>- {/* Certificate validation status */}{certValidation.status === "validating" && (- <Group gap="xs">+ <Group+ gap="xs"+ role="status"+ className="certificate-config__validation"+ ><Loader size="xs" /><Text size="sm" c="dimmed">{t(@@ -243,13 +302,17 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({</Group>)}{certValidation.status === "valid" && (- <Group gap="xs">+ <Group+ gap="xs"+ role="status"+ className="certificate-config__validation"+ ><Iconname="circle-check"size={20}- style={{ color: "var(--mantine-color-green-6)" }}+ style={{ color: "var(--c-success)" }}/>- <Text size="sm" c="var(--color-green-dark)">+ <Text size="sm" c="var(--c-success)">{t("certSign.collab.signRequest.certModal.certValidUntil","Certificate valid until {{date}}",@@ -266,13 +329,17 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({</Group>)}{certValidation.status === "error" && (- <Group gap="xs">+ <Group+ gap="xs"+ role="alert"+ className="certificate-config__validation"+ ><Iconname="circle-alert"size={20}- style={{ color: "var(--mantine-color-red-6)" }}+ style={{ color: "var(--c-danger)" }}/>- <Text size="sm" c="var(--color-red-dark)">+ <Text size="sm" c="var(--c-danger)">{t("certSign.collab.signRequest.certModal.certInvalid","Certificate invalid: {{error}}",@@ -284,70 +351,66 @@ export const CertificateConfigModal: React.FC<CertificateConfigModalProps> = ({</Group>)}- {/* Advanced Settings - Optional */}- <div>+ <div className="certificate-config__details"><Buttonvariant="tertiary"size="sm"+ accent="neutral"+ className="certificate-config__details-toggle"+ justify="between"onClick={() => setShowAdvanced(!showAdvanced)}disabled={disabled || signing}- style={{ marginBottom: "8px" }}+ aria-expanded={showAdvanced}+ rightSection={+ <Icon+ name={showAdvanced ? "chevron-up" : "chevron-down"}+ size={16}+ />+ }>{t(- "certSign.collab.signRequest.advancedSettings",- "Advanced Settings",+ "certSign.collab.signRequest.certModal.details",+ "Signing details (optional)",)}</Button><Collapse in={showAdvanced}>- <Stack gap="sm">- <TextInput+ <div className="certificate-config__fields">+ <FormFieldlabel={t("certSign.collab.signRequest.reason","Reason (Optional)",)}- placeholder={t(- "certSign.collab.signRequest.reasonPlaceholder",- "Why are you signing?",- )}- value={reason}- onChange={(e) => setReason(e.currentTarget.value)}- disabled={disabled || signing}- />- <TextInput+ >+ <Input+ placeholder={t(+ "certSign.collab.signRequest.reasonPlaceholder",+ "Why are you signing?",+ )}+ value={reason}+ onChange={(e) => setReason(e.currentTarget.value)}+ disabled={disabled || signing}+ />+ </FormField>+ <FormFieldlabel={t("certSign.collab.signRequest.location","Location (Optional)",)}- placeholder={t(- "certSign.collab.signRequest.locationPlaceholder",- "Where are you signing from?",- )}- value={location}- onChange={(e) => setLocation(e.currentTarget.value)}- disabled={disabled || signing}- />- </Stack>+ >+ <Input+ placeholder={t(+ "certSign.collab.signRequest.locationPlaceholder",+ "Where are you signing from?",+ )}+ value={location}+ onChange={(e) => setLocation(e.currentTarget.value)}+ disabled={disabled || signing}+ />+ </FormField>+ </div></Collapse></div>-- <Group justify="space-between" wrap="wrap" mt="md">- <Button variant="secondary" onClick={onClose} disabled={signing}>- {t("cancel", "Cancel")}- </Button>- <Button- onClick={handleSign}- disabled={- !isValid ||- disabled ||- signing ||- certValidation.status === "validating"- }- loading={signing}- >- {t("certSign.collab.signRequest.certModal.sign", "Sign Document")}- </Button>- </Group></Stack></Modal>);diff --git a/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsx b/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsxindex 41cd2d0820..830bd6f7ca 100644--- a/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsx+++ b/frontend/editor/src/core/components/tools/certSign/panels/ParticipantListPanel.tsx@@ -1,109 +1,89 @@-import { Stack, Text, List, Group, Badge } from "@mantine/core";-import { ActionIcon } from "@app/ui/ActionIcon";import { useTranslation } from "react-i18next";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Avatar } from "@app/ui/Avatar";import { Icon } from "@app/ui/Icon";-import type { ParticipantInfo } from "@app/types/signingSession";+import { StatusBadge } from "@app/ui/StatusBadge";+import type {+ ParticipantInfo,+ SigningParticipantPreview,+} from "@app/types/signingSession";import { getFileColor } from "@app/components/pageEditor/fileColors";+import "@app/components/shared/signing/signingDetail.css";interface ParticipantListPanelProps {- participants: ParticipantInfo[];+ participants: (SigningParticipantPreview & { email?: string })[];finalized: boolean;- onRemove: (participantId: number) => void;+ onRemove?: (participantId: number) => void;+ disabled?: boolean;}export const ParticipantListPanel: React.FC<ParticipantListPanelProps> = ({participants,finalized,onRemove,+ disabled = false,}) => {const { t } = useTranslation();-- const getIcon = (status: string) => {- if (status === "SIGNED")- return (- <Icon name="circle-check" size={"1rem"} style={{ color: "green" }} />- );- if (status === "DECLINED")- return <Icon name="circle-x" size={"1rem"} style={{ color: "red" }} />;- return <Icon name="clock" size={"1rem"} style={{ color: "orange" }} />;- };-- const getColor = (status: string) => {- if (status === "SIGNED") return "green";- if (status === "DECLINED") return "red";- return "orange";+ const statusLabels: Record<ParticipantInfo["status"], string> = {+ SIGNED: t("sharedSign.filterSigned", "Signed"),+ DECLINED: t("certSign.declined", "Declined"),+ VIEWED: t("certSign.viewed", "Viewed"),+ NOTIFIED: t("signingDetail.notified", "Notified"),+ PENDING: t("certSign.pending", "Pending"),};-return (- <Stack gap="md">- <Text size="md" fw={600}>- {t("certSign.collab.sessionDetail.participants", "Participants")}- </Text>-- <List spacing={8} size="sm">- {participants.map((participant, participantIndex) => {- const isSigned = participant.status === "SIGNED";- const isDeclined = participant.status === "DECLINED";- const annotationColor = getFileColor(participantIndex);-- return (- <List.Item key={participant.id} icon={getIcon(participant.status)}>- <Group justify="space-between" wrap="nowrap" gap={4}>- <Stack gap={2} style={{ flex: 1, minWidth: 0 }}>- <Group gap={6} wrap="nowrap">- <div- style={{- width: 10,- height: 10,- borderRadius: "50%",- backgroundColor: annotationColor,- flexShrink: 0,- }}- />- <Text size="xs" truncate>- {participant.name}- </Text>- </Group>- {participant.email &&- participant.email !== participant.name && (- <Text size="xs" c="dimmed" truncate>- @{participant.email}- </Text>- )}- <Badge- size="xs"- color={getColor(participant.status)}- variant="light"- >- {t(- `certSign.collab.status.${participant.status.toLowerCase()}`,- participant.status,- )}- </Badge>- </Stack>- {!finalized && !isSigned && !isDeclined && (- <ActionIcon- size="sm"- variant="tertiary"- accent="danger"- onClick={() => onRemove(participant.id)}- title={t(- "certSign.collab.sessionDetail.removeParticipant",- "Remove",- )}- aria-label={t(- "certSign.collab.sessionDetail.removeParticipant",- "Remove",- )}- >- <Icon name="trash" size={"1rem"} />- </ActionIcon>- )}- </Group>- </List.Item>- );- })}- </List>- </Stack>+ <ul+ className="signing-participants"+ aria-label={t(+ "certSign.collab.sessionDetail.participants",+ "Participants",+ )}+ >+ {participants.map((participant, participantIndex) => {+ const isSigned = participant.status === "SIGNED";+ const isDeclined = participant.status === "DECLINED";+ const name = participant.name || participant.email || "";+ return (+ <li className="signing-participant" key={participant.id}>+ <Avatar name={name} size="sm" tone="neutral" />+ <div className="signing-participant__identity">+ <strong>{name}</strong>+ {participant.email && participant.email !== name && (+ <span className="signing-participant__email">+ {participant.email}+ </span>+ )}+ <StatusBadge+ tone={isSigned ? "success" : isDeclined ? "danger" : "neutral"}+ size="sm"+ >+ {statusLabels[participant.status]}+ </StatusBadge>+ </div>+ {participant.wetSignatures?.length ? (+ <span+ className="signing-participant__color"+ style={{ backgroundColor: getFileColor(participantIndex) }}+ aria-hidden="true"+ />+ ) : null}+ {onRemove && !finalized && !isSigned && !isDeclined && (+ <ActionIcon+ size="sm"+ variant="tertiary"+ accent="danger"+ disabled={disabled}+ onClick={() => onRemove(participant.id)}+ aria-label={t("signingDetail.removePerson", "Remove {{name}}", {+ name,+ })}+ >+ <Icon name="x" size={16} />+ </ActionIcon>+ )}+ </li>+ );+ })}+ </ul>);};diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.stories.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.stories.tsxindex 95575dab64..558275749b 100644--- a/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.stories.tsx+++ b/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.stories.tsx@@ -43,7 +43,6 @@ type Story = StoryObj<typeof meta>;export const Default: Story = {args: {session: baseSession,- onAddParticipants: () => {},onFinalize: () => {},onLoadSignedPdf: () => {},finalizing: false,diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.test.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.test.tsxnew file mode 100644index 0000000000..a2db9aad87--- /dev/null+++ b/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.test.tsx@@ -0,0 +1,111 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen, fireEvent, within } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { SessionActionsPanel } from "@app/components/tools/certSign/panels/SessionActionsPanel";+import type { ParticipantInfo, SessionDetail } from "@app/types/signingSession";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));++function participant(+ id: number,+ name: string,+ status: ParticipantInfo["status"],+): ParticipantInfo {+ return {+ id,+ userId: id,+ name,+ email: `${name}@example.test`,+ status,+ lastUpdated: "2026-09-24",+ };+}++function renderSession(participants: ParticipantInfo[], finalized = false) {+ const onFinalize = vi.fn();+ const session: SessionDetail = {+ sessionId: "session",+ documentName: "agreement.pdf",+ ownerEmail: "[email protected]",+ message: "",+ dueDate: "",+ createdAt: "2026-09-24",+ updatedAt: "2026-09-24",+ finalized,+ participants,+ };+ render(+ <MantineProvider>+ <SessionActionsPanel+ session={session}+ onFinalize={onFinalize}+ onLoadSignedPdf={vi.fn()}+ finalizing={false}+ loadingPdf={false}+ />+ </MantineProvider>,+ );+ return onFinalize;+}++describe("signing finalization confirmation", () => {+ it.each([+ { participants: [] },+ { participants: [participant(1, "Alice", "PENDING")] },+ ])(+ "blocks finalization without accepted signatures (%j)",+ ({ participants }) => {+ const onFinalize = renderSession(participants);+ expect(+ screen.getByRole("button", {+ name: "Finalize with Current Signatures",+ }),+ ).toBeDisabled();+ expect(onFinalize).not.toHaveBeenCalled();+ },+ );++ it("lists included and excluded participants before the owner commits", () => {+ const onFinalize = renderSession([+ participant(1, "Alice", "SIGNED"),+ participant(2, "Bob", "PENDING"),+ participant(3, "Carol", "DECLINED"),+ ]);+ fireEvent.click(+ screen.getByRole("button", { name: "Finalize with Current Signatures" }),+ );+ const dialog = within(screen.getByRole("dialog"));+ expect(dialog.getByText("Alice")).toBeInTheDocument();+ expect(dialog.getByText("Bob — Pending")).toBeInTheDocument();+ expect(dialog.getByText("Carol — Declined")).toBeInTheDocument();+ expect(onFinalize).not.toHaveBeenCalled();+ fireEvent.click(+ dialog.getByRole("button", { name: "Confirm and finalize" }),+ );+ expect(onFinalize).toHaveBeenCalledTimes(1);+ });++ it("allows cancelling without finalizing", () => {+ const onFinalize = renderSession([participant(1, "Alice", "SIGNED")]);+ fireEvent.click(+ screen.getByRole("button", { name: "Finalize and Load Signed PDF" }),+ );+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(onFinalize).not.toHaveBeenCalled();+ });++ it("offers the final PDF after the session closes", () => {+ renderSession([participant(1, "Alice", "SIGNED")], true);+ expect(+ screen.getByRole("button", { name: "Load Signed PDF into Active Files" }),+ ).toBeEnabled();+ expect(+ screen.queryByRole("button", { name: /Finalize/ }),+ ).not.toBeInTheDocument();+ });+});diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.tsxindex a3190ede1e..fdc889530a 100644--- a/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.tsx+++ b/frontend/editor/src/core/components/tools/certSign/panels/SessionActionsPanel.tsx@@ -1,80 +1,83 @@-import { Stack, Text, Divider, Paper } from "@mantine/core";+import { useState } from "react";+import { Stack, Text, Group } from "@mantine/core";import { Button } from "@app/ui/Button";+import { Modal } from "@app/ui/Modal";+import { StatusBadge } from "@app/ui/StatusBadge";import { useTranslation } from "react-i18next";import { Icon } from "@app/ui/Icon";import type { SessionDetail } from "@app/types/signingSession";+import "@app/components/shared/signing/signingDetail.css";interface SessionActionsPanelProps {session: SessionDetail;- onAddParticipants: () => void;onFinalize: () => void;onLoadSignedPdf: () => void;finalizing: boolean;loadingPdf: boolean;+ disabled?: boolean;}export const SessionActionsPanel: React.FC<SessionActionsPanelProps> = ({session,- onAddParticipants,onFinalize,onLoadSignedPdf,finalizing,loadingPdf,+ disabled = false,}) => {const { t } = useTranslation();-- const allSigned = session.participants.every((p) => p.status === "SIGNED");+ const [confirming, setConfirming] = useState(false);+ const included = session.participants.filter((p) => p.status === "SIGNED");+ const excluded = session.participants.filter((p) => p.status !== "SIGNED");+ const allSigned = included.length > 0 && excluded.length === 0;return (- <Stack gap="md">- {/* Session Info - only shown when there is something to display */}- {(session.dueDate || session.message) && (- <Stack gap="xs">- <Text size="sm" fw={600}>- {t("certSign.collab.sessionDetail.sessionInfo", "Session Info")}- </Text>- {session.dueDate && (- <Paper p="xs" withBorder>- <Text size="xs" fw={600} c="dimmed">- {t("certSign.collab.sessionDetail.dueDate", "Due Date")}- </Text>- <Text size="xs">{session.dueDate}</Text>- </Paper>- )}- {session.message && (- <Paper p="xs" withBorder>- <Text size="xs" fw={600} c="dimmed">- {t("certSign.collab.sessionDetail.messageLabel", "Message")}- </Text>- <Text size="xs">{session.message}</Text>- </Paper>+ <div className="signing-detail__section">+ <h3>+ {session.finalized+ ? t("signingDetail.finalDocument", "Signed document")+ : t("signingDetail.finalizeTitle", "Finalize document")}+ </h3>+ <p className="signing-detail__hint">+ {session.finalized+ ? t(+ "signingDetail.finalReady",+ "Your signed PDF is ready to open in the workbench.",+ )+ : included.length === 0+ ? t(+ "certSign.collab.finalize.requiresSignature",+ "At least one participant must sign before you can finalize.",+ )+ : allSigned+ ? t(+ "signingDetail.allSigned",+ "Everyone has signed. Review the document, then finalize.",+ )+ : t(+ "signingDetail.earlyHint",+ "You can finalize now with the signatures received, or wait for the remaining participants.",+ )}+ </p>+ {session.finalized ? (+ <Button+ leftSection={<Icon name="folder-open" size={18} />}+ fullWidth+ onClick={onLoadSignedPdf}+ loading={loadingPdf}+ >+ {t(+ "certSign.collab.sessionDetail.loadSignedPdf",+ "Load Signed PDF into Active Files",)}- </Stack>- )}-- {/* Primary Actions */}- {!session.finalized && (+ </Button>+ ) : (<>- <Divider />- <Button- variant="secondary"- leftSection={<Icon name="plus" />}- onClick={onAddParticipants}- fullWidth- >- {t(- "certSign.collab.sessionDetail.addParticipants",- "Add Participants",- )}- </Button>-- <Divider />-<Button- leftSection={<Icon name="circle-check" />}- accent={allSigned ? "success" : "warning"}+ leftSection={<Icon name="circle-check" size={18} />}fullWidth- onClick={onFinalize}+ onClick={() => setConfirming(true)}+ disabled={included.length === 0 || disabled}loading={finalizing}>{allSigned@@ -87,24 +90,96 @@ export const SessionActionsPanel: React.FC<SessionActionsPanelProps> = ({"Finalize with Current Signatures",)}</Button>- </>- )}-- {session.finalized && (- <>- <Button- leftSection={<Icon name="circle-check" />}- fullWidth- onClick={onLoadSignedPdf}- loading={loadingPdf}- >- {t(- "certSign.collab.sessionDetail.loadSignedPdf",- "Load Signed PDF into Active Files",+ <Modal+ open={confirming}+ onClose={() => setConfirming(false)}+ title={t(+ "certSign.collab.finalize.confirmTitle",+ "Finalize this signing session?",)}- </Button>+ subtitle={session.documentName}+ footer={+ <Group justify="flex-end">+ <Button+ variant="secondary"+ onClick={() => setConfirming(false)}+ >+ {t("cancel", "Cancel")}+ </Button>+ <Button+ disabled={included.length === 0 || disabled || finalizing}+ onClick={() => {+ setConfirming(false);+ onFinalize();+ }}+ >+ {t(+ "certSign.collab.finalize.confirmAction",+ "Confirm and finalize",+ )}+ </Button>+ </Group>+ }+ >+ <Stack gap="lg">+ <Text size="sm">+ {t(+ "certSign.collab.finalize.confirmDescription",+ "Finalizing closes this session. No more signatures can be submitted.",+ )}+ </Text>+ <section className="signing-finalize__group">+ <StatusBadge tone="success">+ {t(+ "certSign.collab.finalize.included",+ "Signatures included",+ )}{" "}+ · {included.length}+ </StatusBadge>+ <ul className="signing-finalize__list">+ {included.map((p) => (+ <li key={p.id}>+ <Icon+ name="circle-check"+ size={16}+ style={{ color: "var(--c-success)" }}+ />+ <span>{p.name || p.email}</span>+ </li>+ ))}+ </ul>+ </section>+ {excluded.length > 0 && (+ <section className="signing-finalize__group">+ <Text size="sm" fw={600}>+ {t(+ "certSign.collab.finalize.excluded",+ "Participants whose signatures will not be included",+ )}+ </Text>+ <ul className="signing-finalize__list">+ {excluded.map((p) => (+ <li key={p.id}>+ <Icon+ name={p.status === "DECLINED" ? "circle-x" : "clock"}+ size={16}+ style={{ color: "var(--c-text-muted)" }}+ />+ <span>+ {p.name || p.email} —{" "}+ {p.status === "DECLINED"+ ? t("certSign.declined", "Declined")+ : t("certSign.pending", "Pending")}+ </span>+ </li>+ ))}+ </ul>+ </section>+ )}+ </Stack>+ </Modal></>)}- </Stack>+ </div>);};diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SessionDetailPanel.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SessionDetailPanel.tsxindex 755f2d7a02..89079f7bce 100644--- a/frontend/editor/src/core/components/tools/certSign/panels/SessionDetailPanel.tsx+++ b/frontend/editor/src/core/components/tools/certSign/panels/SessionDetailPanel.tsx@@ -1,7 +1,12 @@import { useState, useEffect } from "react";import { useTranslation } from "react-i18next";-import { Stack, Text, Group, Badge, Divider, Modal } from "@mantine/core";+import { Stack, Text, Group, Modal } from "@mantine/core";import { Button } from "@app/ui/Button";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Tooltip } from "@app/ui/Tooltip";+import { StatusBadge } from "@app/ui/StatusBadge";+import { ProgressBar } from "@app/ui/ProgressBar";+import { SigningSessionHeader } from "@app/components/shared/signing/SigningSessionHeader";import { alert } from "@app/components/toast";import { Icon } from "@app/ui/Icon";import { ParticipantListPanel } from "@app/components/tools/certSign/panels/ParticipantListPanel";@@ -23,7 +28,6 @@ export const SessionDetailPanel = ({ data }: SessionDetailPanelProps) => {onAddParticipants,onRemoveParticipant,onDelete,- onBack,onRefresh,} = data;@@ -33,6 +37,10 @@ export const SessionDetailPanel = ({ data }: SessionDetailPanelProps) => {const [finalizing, setFinalizing] = useState(false);const [deleting, setDeleting] = useState(false);const [loadingPdf, setLoadingPdf] = useState(false);+ const signedCount = session.participants.filter(+ (p) => p.status === "SIGNED",+ ).length;+ const busy = finalizing || deleting || loadingPdf;// Auto-refresh every 30 seconds while the session is active.useEffect(() => {@@ -148,86 +156,120 @@ export const SessionDetailPanel = ({ data }: SessionDetailPanelProps) => {};return (- <Stack gap="md" p="md" h="100%" style={{ minHeight: 0 }}>- <Button- leftSection={<Icon name="arrow-left" size={20} />}- variant="tertiary"- size="sm"- onClick={onBack}- justify="start"- style={{ alignSelf: "flex-start" }}- >- {t("certSign.collab.sessionDetail.backToList", "Back to Sessions")}- </Button>-- <Stack gap={4}>- <Group gap="sm" wrap="nowrap">- <Text size="sm" fw={600} truncate style={{ flex: 1, minWidth: 0 }}>- {session.documentName}- </Text>- <Badge- size="sm"- color={session.finalized ? "green" : "blue"}- variant="light"- >- {session.finalized- ? t("certSign.collab.sessionList.finalized", "Finalized")- : t("certSign.collab.sessionList.active", "Active")}- </Badge>- </Group>- {(session.ownerEmail || session.createdAt) && (- <Text size="xs" c="dimmed">- {session.ownerEmail &&- `${t("certSign.collab.sessionDetail.owner", "Owner")}: ${session.ownerEmail}`}- {session.ownerEmail && session.createdAt && " • "}- {session.createdAt &&- new Date(session.createdAt).toLocaleDateString()}- </Text>- )}- </Stack>-- <Divider />-- {/* Participants — scrollable, bounded so actions stay visible */}- <div style={{ flex: 1, minHeight: 0, overflowY: "auto" }}>- <ParticipantListPanel- participants={session.participants}- finalized={session.finalized}- onRemove={handleRemoveParticipant}+ <div className="signing-detail">+ <div className="signing-detail__body">+ <SigningSessionHeader+ documentName={session.documentName}+ owner={session.ownerEmail}+ createdAt={session.createdAt}+ dueDate={session.dueDate}+ message={session.message}+ status={+ <StatusBadge tone={session.finalized ? "success" : "info"}>+ {session.finalized+ ? t("certSign.collab.sessionList.finalized", "Finalized")+ : t("certSign.collab.sessionList.active", "Active")}+ </StatusBadge>+ }+ actions={+ !session.finalized && (+ <Tooltip+ content={t(+ "certSign.collab.sessionDetail.deleteSession",+ "Delete Session",+ )}+ >+ <ActionIcon+ variant="tertiary"+ accent="neutral"+ aria-label={t(+ "certSign.collab.sessionDetail.deleteSession",+ "Delete Session",+ )}+ disabled={busy}+ onClick={() => setDeleteModalOpen(true)}+ >+ <Icon name="trash" size={18} />+ </ActionIcon>+ </Tooltip>+ )+ }/>+ <div className="signing-detail__summary">+ <div className="signing-detail__heading">+ <h3>{t("signingDetail.progress", "Signature progress")}</h3>+ <StatusBadge+ tone={+ signedCount === session.participants.length && signedCount > 0+ ? "success"+ : "neutral"+ }+ showDot={false}+ >+ {t("signingDetail.signedCount", "{{signed}} / {{total}} signed", {+ signed: signedCount,+ total: session.participants.length,+ })}+ </StatusBadge>+ </div>+ <ProgressBar+ value={+ session.participants.length+ ? signedCount / session.participants.length+ : 0+ }+ label={t("signingDetail.progress", "Signature progress")}+ />+ </div>+ <section className="signing-detail__section">+ <div className="signing-detail__heading">+ <h3>+ {t("certSign.collab.sessionDetail.participants", "Participants")}+ </h3>+ {!session.finalized && (+ <Button+ size="sm"+ variant="tertiary"+ leftSection={<Icon name="plus" size={16} />}+ disabled={busy}+ onClick={() => setAddParticipantsModalOpen(true)}+ >+ {t(+ "certSign.collab.sessionDetail.addParticipants",+ "Add Participants",+ )}+ </Button>+ )}+ </div>+ <ParticipantListPanel+ participants={session.participants}+ finalized={session.finalized}+ onRemove={handleRemoveParticipant}+ disabled={busy}+ />+ </section></div>-- <Divider />-- <SessionActionsPanel- session={session}- onAddParticipants={() => setAddParticipantsModalOpen(true)}- onFinalize={handleFinalize}- onLoadSignedPdf={handleLoadSignedPdf}- finalizing={finalizing}- loadingPdf={loadingPdf}- />-- {!session.finalized && (- <Button- leftSection={<Icon name="trash" size={20} />}- accent="danger"- variant="tertiary"- fullWidth- onClick={() => setDeleteModalOpen(true)}- >- {t("certSign.collab.sessionDetail.deleteSession", "Delete Session")}- </Button>- )}-- {/* Add Participants Modal */}+ <footer className="signing-detail__footer">+ {data.onOpenMyRequest && !session.finalized && (+ <Button onClick={data.onOpenMyRequest} disabled={busy} fullWidth>+ {t("signingDetail.signMyRequest", "Sign this document")}+ </Button>+ )}+ <SessionActionsPanel+ session={session}+ onFinalize={handleFinalize}+ onLoadSignedPdf={handleLoadSignedPdf}+ finalizing={finalizing}+ loadingPdf={loadingPdf}+ disabled={busy}+ />+ </footer><AddParticipantsFlowopened={addParticipantsModalOpen}onClose={() => setAddParticipantsModalOpen(false)}onSubmit={handleAddParticipants}/>- {/* Delete Confirmation Modal */}<Modalopened={deleteModalOpen}onClose={() => setDeleteModalOpen(false)}@@ -256,7 +298,7 @@ export const SessionDetailPanel = ({ data }: SessionDetailPanelProps) => {</Group></Stack></Modal>- </Stack>+ </div>);};diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.stories.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.stories.tsxindex 2a1792b5c3..1a41244945 100644--- a/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.stories.tsx+++ b/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.stories.tsx@@ -25,8 +25,6 @@ export const Default: Story = {placementMode: false,onPlacementModeChange: () => {},onSignatureSelected: () => {},- onComplete: () => {},- canComplete: true,signatureConfig: textSignatureConfig,hasSelectedAnnotation: true,onDeleteSelected: () => {},@@ -37,7 +35,6 @@ export const PlacingNoSelection: Story = {args: {...Default.args,placementMode: true,- canComplete: false,hasSelectedAnnotation: false,},};diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.test.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.test.tsxnew file mode 100644index 0000000000..d0d5d8a207--- /dev/null+++ b/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.test.tsx@@ -0,0 +1,67 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { expect, it, vi } from "vitest";+import SignControlsPanel from "@app/components/tools/certSign/panels/SignControlsPanel";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));++vi.mock("@app/hooks/tools/sign/useSavedSignatures", () => ({+ useSavedSignatures: () => ({+ savedSignatures: [],+ addSignature: vi.fn(),+ removeSignature: vi.fn(),+ isAtCapacity: false,+ byTypeCounts: {},+ }),+}));++it("exposes undo and redo controls and keyboard shortcuts without intercepting form editing", () => {+ const onUndo = vi.fn();+ const onRedo = vi.fn();+ const content = (canUndo: boolean, canRedo: boolean) => (+ <MantineProvider>+ <SignControlsPanel+ signatureConfig={{+ signatureType: "canvas",+ signatureData: "data:image/png;base64,AA==",+ }}+ placementMode={false}+ onPlacementModeChange={vi.fn()}+ onSignatureSelected={vi.fn()}+ canUndo={canUndo}+ canRedo={canRedo}+ onUndo={onUndo}+ onRedo={onRedo}+ />+ <input aria-label="Name" />+ <div role="dialog">+ <button>Dialog action</button>+ </div>+ </MantineProvider>+ );+ const { rerender } = render(content(true, false));+ fireEvent.click(screen.getByRole("button", { name: "Undo" }));+ expect(onUndo).toHaveBeenCalledOnce();+ expect(screen.getByRole("button", { name: "Redo" })).toBeDisabled();+ rerender(content(false, true));+ expect(screen.getByRole("button", { name: "Undo" })).toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: "Redo" }));+ fireEvent.keyDown(document.body, { key: "z", ctrlKey: true });+ fireEvent.keyDown(document.body, { key: "Z", metaKey: true, shiftKey: true });+ fireEvent.keyDown(document.body, { key: "y", ctrlKey: true });+ expect(onUndo).toHaveBeenCalledTimes(2);+ expect(onRedo).toHaveBeenCalledTimes(3);+ fireEvent.keyDown(screen.getByRole("textbox", { name: "Name" }), {+ key: "z",+ ctrlKey: true,+ });+ fireEvent.keyDown(screen.getByRole("button", { name: "Dialog action" }), {+ key: "z",+ ctrlKey: true,+ });+ expect(onUndo).toHaveBeenCalledTimes(2);+});diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.tsxindex 390464b539..067896e540 100644--- a/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.tsx+++ b/frontend/editor/src/core/components/tools/certSign/panels/SignControlsPanel.tsx@@ -1,8 +1,11 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { Box, Group, Menu, Modal, Stack, Text } from "@mantine/core";+import { Group, Menu, Modal, Text } from "@mantine/core";import { ActionIcon } from "@app/ui/ActionIcon";import { Button } from "@app/ui/Button";import { SegmentedControl } from "@app/ui/SegmentedControl";+import { Tooltip } from "@app/ui/Tooltip";+import { StatusBadge } from "@app/ui/StatusBadge";+import "@app/components/shared/signing/signingDetail.css";import { useTranslation } from "react-i18next";import { Icon } from "@app/ui/Icon";import {@@ -20,11 +23,13 @@ interface SignControlsPanelProps {placementMode: boolean;onPlacementModeChange: (active: boolean) => void;onSignatureSelected: (config: SignParameters) => void;- onComplete: () => void;- canComplete: boolean;signatureConfig: SignParameters | null;hasSelectedAnnotation?: boolean;onDeleteSelected?: () => void;+ canUndo?: boolean;+ canRedo?: boolean;+ onUndo?: () => void;+ onRedo?: () => void;}// wetSignature creation type ↔ stored/placement signature type.@@ -34,16 +39,18 @@ const STORED_TYPE: Record<SignatureType, SavedSignature["type"]> = {type: "text",};-/** Vertical sidebar signing controls: pick/create a signature, toggle place/move, delete, and complete & sign (placement happens on the main Viewer). */+/** Places optional visible marks in the shared viewer; certificate submission belongs to the request panel. */export default function SignControlsPanel({placementMode,onPlacementModeChange,onSignatureSelected,- onComplete,- canComplete,signatureConfig,hasSelectedAnnotation = false,onDeleteSelected,+ canUndo = false,+ canRedo = false,+ onUndo,+ onRedo,}: SignControlsPanelProps) {const { t } = useTranslation();const {@@ -71,21 +78,9 @@ export default function SignControlsPanel({(sig: SavedSignature) => {if (sig.type === "text") {return (- <Box- style={{- width: 72,- height: 28,- backgroundColor: "#ffffff",- borderRadius: 8,- display: "flex",- alignItems: "center",- justifyContent: "center",- padding: "0 8px",- overflow: "hidden",- }}- >+ <span className="signing-controls__preview"><Text- size="sm"+ size="lg"style={{fontFamily: sig.fontFamily,color: sig.textColor,@@ -97,38 +92,20 @@ export default function SignControlsPanel({>{sig.signerName}</Text>- </Box>+ </span>);}return (- <Box- style={{- width: 72,- height: 28,- backgroundColor: "#ffffff",- borderRadius: 8,- display: "flex",- alignItems: "center",- justifyContent: "center",- padding: "2px 6px",- }}- >- <Box- component="img"+ <span className="signing-controls__preview">+ <imgsrc={sig.dataUrl}alt={sig.label ||t("certSign.collab.signRequest.saved.defaultLabel", "Signature")}- style={{- maxWidth: "100%",- maxHeight: "100%",- objectFit: "contain",- display: "block",- }}/>- </Box>+ </span>);},[t],@@ -271,7 +248,6 @@ export default function SignControlsPanel({textColor,]);- // Keyboard: Esc pauses placement, Backspace deletes the selected placement.useEffect(() => {if (!signatureConfig || createOpen) return;@@ -282,7 +258,18 @@ export default function SignControlsPanel({target?.tagName === "TEXTAREA" ||target?.tagName === "CANVAS" ||(target as { isContentEditable?: boolean })?.isContentEditable;- if (isTypingTarget) return;+ if (isTypingTarget || target?.closest('[role="dialog"]')) return;++ if ((event.ctrlKey || event.metaKey) && !event.altKey) {+ const key = event.key.toLowerCase();+ if (key === "z" || key === "y") {+ event.preventDefault();+ event.stopPropagation();+ if (key === "y" || event.shiftKey) onRedo?.();+ else onUndo?.();+ return;+ }+ }if (event.key === "Escape") {onPlacementModeChange(false);@@ -294,16 +281,23 @@ export default function SignControlsPanel({}};- window.addEventListener("keydown", onKeyDown);- return () => window.removeEventListener("keydown", onKeyDown);- }, [onPlacementModeChange, onDeleteSelected, signatureConfig, createOpen]);+ window.addEventListener("keydown", onKeyDown, true);+ return () => window.removeEventListener("keydown", onKeyDown, true);+ }, [+ onPlacementModeChange,+ onDeleteSelected,+ onUndo,+ onRedo,+ signatureConfig,+ createOpen,+ ]);if (!signatureConfig) return null;const previewNode =signatureConfig.signatureType === "text" ? (<Text- size="sm"+ size="lg"style={{fontFamily: signatureConfig.fontFamily ?? "Helvetica",color: signatureConfig.textColor ?? "#000000",@@ -323,12 +317,6 @@ export default function SignControlsPanel({"certSign.collab.signRequest.preview.imageAlt","Selected signature",)}- style={{- maxHeight: 32,- maxWidth: "100%",- objectFit: "contain",- display: "block",- }}/>) : (// Sits on the white signature sheet in both schemes, so it takes a fixed@@ -342,147 +330,193 @@ export default function SignControlsPanel({);return (- <Stack gap="sm">- <Text size="sm" fw={700}>- {t("certSign.collab.signRequest.signingTitle", "Signing")}- </Text>-- {/* Current signature + change menu */}- <Menu withinPortal position="bottom" shadow="md" width="target">- <Menu.Target>- <Button- variant="secondary"- fullWidth- justify="between"- rightSection={<Icon name="chevron-down" size={"1.1rem"} />}- aria-label={t(- "certSign.collab.signRequest.changeSignature",- "Change signature",+ <section className="signing-detail__section">+ <div className="signing-detail__heading">+ <h3>{t("signingDetail.visibleSignature", "Visible signature")}</h3>+ <Group gap={4}>+ <StatusBadge tone="neutral" showDot={false} size="sm">+ {t("signingDetail.optional", "Optional")}+ </StatusBadge>+ <Tooltip+ content={t(+ "signMenu.optionalMarks",+ "Visible marks are optional. Complete & Sign also works with a certificate alone.",)}>- <Box- style={{- display: "flex",- alignItems: "center",- gap: 8,- minWidth: 0,- backgroundColor: "#ffffff",- borderRadius: 8,- padding: "2px 8px",- minHeight: 28,- }}+ <ActionIcon+ variant="tertiary"+ size="sm"+ aria-label={t(+ "signingDetail.visibleSignatureHelp",+ "About visible signatures",+ )}>- {previewNode}- </Box>- </Button>- </Menu.Target>- <Menu.Dropdown>- {sortedSavedSignatures.length ? (- sortedSavedSignatures.map((sig) => (- <Menu.Item key={sig.id} onClick={() => applySavedSignature(sig)}>- <Group gap="sm" wrap="nowrap" justify="space-between">- {renderSavedSignaturePreview(sig)}- <ActionIcon- as="div"- size="sm"- accent="danger"- variant="tertiary"- onClick={(e) => {- e.stopPropagation();- removeSignature(sig.id);- }}- aria-label={t(- "certSign.collab.signRequest.saved.delete",- "Delete signature",- )}- >- <Icon name="x" size={"0.9rem"} />- </ActionIcon>- </Group>+ <Icon name="info" size={16} />+ </ActionIcon>+ </Tooltip>+ </Group>+ </div>+ {!sortedSavedSignatures.length && !signatureConfig.signatureData ? (+ <Button+ variant="secondary"+ className="signing-controls__picker"+ leftSection={<Icon name="pen-tool" size={20} />}+ onClick={openCreateModal}+ fullWidth+ >+ {t("certSign.collab.signRequest.preview.create", "Add signature")}+ </Button>+ ) : (+ <Menu withinPortal position="bottom" shadow="md" width="target">+ <Menu.Target>+ <Button+ variant="secondary"+ className="signing-controls__picker"+ fullWidth+ justify="between"+ rightSection={<Icon name="chevron-down" size={"1.1rem"} />}+ aria-label={t(+ "certSign.collab.signRequest.changeSignature",+ "Change signature",+ )}+ >+ <span className="signing-controls__preview">{previewNode}</span>+ </Button>+ </Menu.Target>+ <Menu.Dropdown>+ {sortedSavedSignatures.length ? (+ sortedSavedSignatures.map((sig) => (+ <Menu.Item+ key={sig.id}+ onClick={() => applySavedSignature(sig)}+ >+ <Group gap="sm" wrap="nowrap" justify="space-between">+ {renderSavedSignaturePreview(sig)}+ <ActionIcon+ as="div"+ size="sm"+ accent="danger"+ variant="tertiary"+ onClick={(e) => {+ e.stopPropagation();+ removeSignature(sig.id);+ }}+ aria-label={t(+ "certSign.collab.signRequest.saved.delete",+ "Delete signature",+ )}+ >+ <Icon name="x" size={"0.9rem"} />+ </ActionIcon>+ </Group>+ </Menu.Item>+ ))+ ) : (+ <Menu.Item disabled>+ {t(+ "certSign.collab.signRequest.saved.none",+ "No saved signatures",+ )}</Menu.Item>- ))- ) : (- <Menu.Item disabled>+ )}+ <Menu.Divider />+ <Menu.Item+ leftSection={<Icon name="plus" size={"1rem"} />}+ onClick={openCreateModal}+ disabled={isAtCapacity}+ >{t(- "certSign.collab.signRequest.saved.none",- "No saved signatures",+ "certSign.collab.signRequest.createNewSignature",+ "Create New Signature",)}</Menu.Item>- )}- <Menu.Divider />- <Menu.Item- leftSection={<Icon name="plus" size={"1rem"} />}- onClick={openCreateModal}- disabled={isAtCapacity}- >- {t(- "certSign.collab.signRequest.createNewSignature",- "Create New Signature",+ </Menu.Dropdown>+ </Menu>+ )}+ {signatureConfig.signatureData && (+ <>+ <Group gap="xs" grow>+ <Button+ variant="secondary"+ size="sm"+ disabled={!canUndo}+ onClick={onUndo}+ leftSection={<Icon name="undo-2" size={16} />}+ >+ {t("pageEditor.toolbar.undo", "Undo")}+ </Button>+ <Button+ variant="secondary"+ size="sm"+ disabled={!canRedo}+ onClick={onRedo}+ leftSection={<Icon name="redo-2" size={16} />}+ >+ {t("pageEditor.toolbar.redo", "Redo")}+ </Button>+ </Group>+ <SegmentedControl+ fullWidth+ value={placementMode ? "place" : "move"}+ onChange={(value) => onPlacementModeChange(value === "place")}+ options={[+ {+ value: "place",+ label: (+ <Group gap={6} wrap="nowrap" justify="center">+ <Icon name="pen-tool" size={"1.1rem"} />+ <span>+ {t("certSign.collab.signRequest.mode.place", "Place")}+ </span>+ </Group>+ ),+ },+ {+ value: "move",+ label: (+ <Group gap={6} wrap="nowrap" justify="center">+ <Icon name="move" size={"1.1rem"} />+ <span>+ {t("certSign.collab.signRequest.mode.move", "Move")}+ </span>+ </Group>+ ),+ },+ ]}+ size="sm"+ ariaLabel={t(+ "certSign.collab.signRequest.mode.title",+ "Sign or move mode",)}- </Menu.Item>- </Menu.Dropdown>- </Menu>-- {/* Place vs. move */}- <SegmentedControl- fullWidth- value={placementMode ? "place" : "move"}- onChange={(value) => onPlacementModeChange(value === "place")}- options={[- {- value: "place",- label: (- <Group gap={6} wrap="nowrap" justify="center">- <Icon name="pen-tool" size={"1.1rem"} />- <span>- {t("certSign.collab.signRequest.mode.place", "Place")}- </span>- </Group>- ),- },- {- value: "move",- label: (- <Group gap={6} wrap="nowrap" justify="center">- <Icon name="move" size={"1.1rem"} />- <span>- {t("certSign.collab.signRequest.mode.move", "Move")}- </span>- </Group>- ),- },- ]}- size="xs"- ariaLabel={t(- "certSign.collab.signRequest.mode.title",- "Sign or move mode",- )}- />-- <Button- variant="tertiary"- accent="danger"- leftSection={<Icon name="trash" size={"1.1rem"} />}- onClick={onDeleteSelected}- disabled={!hasSelectedAnnotation}- fullWidth- >- {t(- "certSign.collab.signRequest.deleteSelected",- "Delete selected signature",- )}- </Button>-- <Button- leftSection={<Icon name="check" size={"1.1rem"} />}- onClick={onComplete}- disabled={!canComplete}- fullWidth- >- {t("certSign.collab.signRequest.completeAndSign", "Complete & Sign")}- </Button>-- {/* Create signature — reuses the shared wet-signature creation flow */}+ />+ {hasSelectedAnnotation && (+ <Button+ variant="tertiary"+ accent="danger"+ leftSection={<Icon name="trash" size={"1.1rem"} />}+ onClick={onDeleteSelected}+ disabled={!hasSelectedAnnotation}+ fullWidth+ >+ {t(+ "certSign.collab.signRequest.deleteSelected",+ "Delete selected signature",+ )}+ </Button>+ )}+ <p className="signing-detail__hint">+ {placementMode+ ? t(+ "signingDetail.placeHint",+ "Click on the document to place your signature.",+ )+ : t(+ "signingDetail.moveHint",+ "Select a signature on the document to move, resize or remove it.",+ )}+ </p>+ </>+ )}<Modalopened={createOpen}onClose={() => setCreateOpen(false)}@@ -513,6 +547,6 @@ export default function SignControlsPanel({)}/></Modal>- </Stack>+ </section>);}diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SignRequestPanel.test.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SignRequestPanel.test.tsxnew file mode 100644index 0000000000..5b1fc01c2e--- /dev/null+++ b/frontend/editor/src/core/components/tools/certSign/panels/SignRequestPanel.test.tsx@@ -0,0 +1,222 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { beforeEach, expect, it, vi } from "vitest";+import SignRequestPanel from "@app/components/tools/certSign/panels/SignRequestPanel";+import type { SigningRequestData } from "@app/hooks/signing/useSigningSessionController";++const { setOverlay, addFiles, t } = vi.hoisted(() => ({+ setOverlay: vi.fn(),+ addFiles: vi.fn(),+ t: (key: string, fallback?: string) => fallback ?? key,+}));+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t }) }));+vi.mock("@app/contexts/SigningOverlayContext", () => ({+ useSigningOverlay: () => ({ setOverlay }),+}));+vi.mock("@app/contexts/file/fileHooks", () => ({+ useFileActions: () => ({ actions: { addFiles } }),+}));+vi.mock("@app/components/tools/certSign/panels/SignControlsPanel", () => ({+ default: () => <div>Visible mark editor</div>,+}));+vi.mock("@app/components/tools/certSign/modals/CertificateConfigModal", () => ({+ CertificateConfigModal: ({+ opened,+ signatureCount,+ onClose,+ }: {+ opened: boolean;+ signatureCount: number;+ onClose: () => void;+ }) =>+ opened ? (+ <div role="dialog" aria-label="Certificate">+ <span>{signatureCount} visible marks</span>+ <button onClick={onClose}>Cancel certificate</button>+ </div>+ ) : null,+}));++beforeEach(() => vi.clearAllMocks());++function setup(+ status: SigningRequestData["signRequest"]["myStatus"] = "PENDING",+ finalized = false,+) {+ const data: SigningRequestData = {+ signRequest: {+ sessionId: "demo",+ documentName: "agreement.pdf",+ ownerUsername: "Alice",+ message: "Please check the second page.",+ dueDate: "2026-10-12",+ createdAt: "2026-10-01T10:00:00Z",+ myStatus: status,+ finalized,+ },+ pdfFile: new File(["pdf"], "agreement.pdf"),+ canSign: !finalized && status !== "SIGNED" && status !== "DECLINED",+ onSign: vi.fn(),+ onDecline: vi.fn(),+ onRefresh: vi.fn().mockResolvedValue(undefined),+ onBack: vi.fn(),+ };+ const result = render(+ <MantineProvider>+ <SignRequestPanel data={data} />+ </MantineProvider>,+ );+ return { ...result, data };+}++it("shows the owner's message and a local-calendar due date", () => {+ const { container } = setup();+ expect(+ screen.getByRole("heading", { name: "agreement.pdf" }),+ ).toBeInTheDocument();+ expect(screen.getByText("Please check the second page.")).toBeInTheDocument();+ expect(+ container.querySelector('time[datetime="2026-10-12"]'),+ ).toHaveTextContent(new Date(2026, 9, 12).toLocaleDateString());+});++it("directs an owner back to their session after submitting their own signature", () => {+ const { data, rerender } = setup("SIGNED");+ expect(+ screen.queryByRole("button", { name: "Manage signing session" }),+ ).not.toBeInTheDocument();+ data.onManageSession = vi.fn();+ rerender(+ <MantineProvider>+ <SignRequestPanel data={data} />+ </MantineProvider>,+ );+ expect(screen.getByRole("status")).toHaveTextContent(+ "Return to your session",+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Manage signing session" }),+ );+ expect(data.onManageSession).toHaveBeenCalledOnce();+});++it("releases its own viewer on unmount without clearing a replacement owner preview", () => {+ const { unmount, data } = setup();+ const participantOverlay = setOverlay.mock.calls.at(-1)![0];+ const ownerOverlay = { file: data.pdfFile, signaturePreviewsReadOnly: true };+ unmount();+ const releaseOverlay = setOverlay.mock.calls.at(-1)![0];+ expect(releaseOverlay(participantOverlay)).toBeNull();+ expect(releaseOverlay(ownerOverlay)).toBe(ownerOverlay);+});++it("opens certificate-only signing without submitting and preserves the editor on cancel", () => {+ const { data } = setup();+ fireEvent.click(screen.getByRole("button", { name: "Complete & Sign" }));+ expect(screen.getByRole("dialog", { name: "Certificate" })).toHaveTextContent(+ "0 visible marks",+ );+ expect(data.onSign).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Cancel certificate" }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.getByText("Visible mark editor")).toBeInTheDocument();+});++it.each([+ ["SIGNED", false, "Your signature is submitted"],+ ["DECLINED", false, "This request is closed"],+ ["PENDING", true, "Signed document"],+] as const)(+ "keeps %s requests read-only when finalized=%s",+ (status, finalized, heading) => {+ setup(status, finalized);+ expect(screen.getByRole("status")).toHaveTextContent(heading);+ expect(+ screen.queryByRole("button", { name: "Complete & Sign" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Decline Request" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("Visible mark editor")).not.toBeInTheDocument();+ expect(setOverlay).toHaveBeenLastCalledWith(+ expect.objectContaining({ signaturePlacementMode: false }),+ );+ },+);++it("renders submitted marks separately from the participant's editable draft and supports refresh", async () => {+ const { data, rerender } = setup("SIGNED");+ data.signRequest = {+ ...data.signRequest,+ participants: [+ {+ id: 2,+ name: "Bob",+ status: "SIGNED",+ wetSignatures: [+ {+ type: "image",+ data: "data:image/png;base64,AA==",+ page: 0,+ x: 0.1,+ y: 0.2,+ width: 0.3,+ height: 0.1,+ },+ ],+ },+ ],+ };+ rerender(+ <MantineProvider>+ <SignRequestPanel data={data} />+ </MantineProvider>,+ );+ const overlay = setOverlay.mock.calls.at(-1)![0];+ expect(overlay.readOnlySignaturePreviews).toHaveLength(1);+ expect(overlay.signaturePreviews).toBeUndefined();+ expect(screen.getByRole("list", { name: "Participants" })).toHaveTextContent(+ "Bob",+ );+ expect(+ screen.queryByRole("button", { name: /Remove Bob/ }),+ ).not.toBeInTheDocument();+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Refresh preview" }));+ });+ expect(data.onRefresh).toHaveBeenCalledOnce();+ data.signRequest = { ...data.signRequest, finalized: true };+ rerender(+ <MantineProvider>+ <SignRequestPanel data={data} />+ </MantineProvider>,+ );+ expect(setOverlay.mock.calls.at(-1)![0].readOnlySignaturePreviews).toEqual(+ [],+ );+ expect(+ screen.queryByRole("button", { name: "Refresh preview" }),+ ).not.toBeInTheDocument();+});++it("clears an unfinished draft when the owner finalizes or closes access", () => {+ const { data, rerender } = setup();+ const clearPreviews = vi.fn();+ const overlay = setOverlay.mock.calls.at(-1)![0];+ overlay.signatureOverlayApiRef.current = { clearPreviews };+ data.canSign = false;+ data.signRequest = { ...data.signRequest, finalized: true };+ rerender(+ <MantineProvider>+ <SignRequestPanel data={data} />+ </MantineProvider>,+ );+ expect(clearPreviews).toHaveBeenCalledOnce();+ expect(setOverlay.mock.calls.at(-1)![0]).toEqual(+ expect.objectContaining({+ signaturePreviewsReadOnly: true,+ signaturePlacementMode: false,+ readOnlySignaturePreviews: [],+ }),+ );+});diff --git a/frontend/editor/src/core/components/tools/certSign/panels/SignRequestPanel.tsx b/frontend/editor/src/core/components/tools/certSign/panels/SignRequestPanel.tsxindex 00589ee0ef..eb056dcec5 100644--- a/frontend/editor/src/core/components/tools/certSign/panels/SignRequestPanel.tsx+++ b/frontend/editor/src/core/components/tools/certSign/panels/SignRequestPanel.tsx@@ -1,8 +1,9 @@-import { useState, useRef, useEffect, useCallback } from "react";+import { useState, useRef, useEffect, useCallback, useMemo } from "react";import { useTranslation } from "react-i18next";-import { Stack, Text, Divider } from "@mantine/core";import { Button } from "@app/ui/Button";import { Icon } from "@app/ui/Icon";+import { StatusBadge } from "@app/ui/StatusBadge";+import { SigningSessionHeader } from "@app/components/shared/signing/SigningSessionHeader";import { alert } from "@app/components/toast";import type {SignatureOverlayAPI,@@ -15,15 +16,25 @@ import SignControlsPanel from "@app/components/tools/certSign/panels/SignControlimport { CertificateConfigModal } from "@app/components/tools/certSign/modals/CertificateConfigModal";import type { CertificateSubmitData } from "@app/components/tools/certSign/modals/CertificateConfigModal";import type { SigningRequestData } from "@app/hooks/signing/useSigningSessionController";+import { getSubmittedSignaturePreviews } from "@app/utils/signingPreviews";+import { ParticipantListPanel } from "@app/components/tools/certSign/panels/ParticipantListPanel";interface SignRequestPanelProps {data: SigningRequestData;}-/** Sidebar controls for a sign request: drives viewer placement via the overlay context and reads placed signatures via the overlay API ref. */+/** Controls for a sign request: drives viewer placement via the overlay context and reads placed signatures via the overlay API ref. */const SignRequestPanel = ({ data }: SignRequestPanelProps) => {const { t } = useTranslation();- const { signRequest, pdfFile, onSign, onDecline, onBack, canSign } = data;+ const {+ signRequest,+ pdfFile,+ onSign,+ onDecline,+ onRefresh,+ onBack,+ canSign,+ } = data;const { actions: fileActions } = useFileActions();const { setOverlay } = useSigningOverlay();@@ -42,14 +53,42 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {: null,);const [previewCount, setPreviewCount] = useState(0);- const [placementMode, setPlacementMode] = useState(true);+ const [placementMode, setPlacementMode] = useState(false);const [hasSelectedAnnotation, setHasSelectedAnnotation] = useState(false);+ const [canUndo, setCanUndo] = useState(false);+ const [canRedo, setCanRedo] = useState(false);const [certificateModalOpen, setCertificateModalOpen] = useState(false);const [signing, setSigning] = useState(false);const [declining, setDeclining] = useState(false);+ const [refreshing, setRefreshing] = useState(false);+ const submittedPreviews = useMemo(+ () => getSubmittedSignaturePreviews(signRequest),+ [signRequest],+ );++ useEffect(() => {+ if (signRequest.finalized || signing || declining) return;+ const timer = setInterval(() => {+ void onRefresh();+ }, 30000);+ return () => clearInterval(timer);+ }, [signRequest.finalized, signing, declining, onRefresh]);++ const refreshPreview = async () => {+ setRefreshing(true);+ try {+ await onRefresh();+ } finally {+ setRefreshing(false);+ }+ };const signControlsVisible = canSign && signatureConfig !== null;+ useEffect(() => {+ if (!canSign) overlayApiRef.current?.clearPreviews();+ }, [canSign]);+const handlePreviewsChange = useCallback((previews: SignaturePreview[]) => {setPreviewCount(previews.length);}, []);@@ -61,6 +100,8 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {useEffect(() => {setOverlay({file: pdfFile,+ readOnlySignaturePreviews: submittedPreviews,+ signaturePreviewsReadOnly: !canSign,signaturePlacementMode: signControlsVisible ? placementMode : false,signaturePlacementData: signControlsVisible ? placementData : undefined,signaturePlacementType: signControlsVisible ? placementType : undefined,@@ -69,6 +110,8 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {});}, [pdfFile,+ submittedPreviews,+ canSign,signControlsVisible,placementMode,placementData,@@ -77,36 +120,33 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {setOverlay,]);- // Clear the shared viewer overlay when leaving the sign request.+ // Owner navigation may install its preview before this panel unmounts.useEffect(() => {- return () => setOverlay(null);+ return () =>+ setOverlay((current) =>+ current?.signatureOverlayApiRef === overlayApiRef ? null : current,+ );}, [setOverlay]);- // Poll for a selected placement (drives the delete control).+ // The viewer owns placement state; the panel reads its current selection and history.useEffect(() => {if (!signControlsVisible) {setHasSelectedAnnotation(false);+ setCanUndo(false);+ setCanRedo(false);return;}- const check = () =>+ const check = () => {setHasSelectedAnnotation(Boolean(overlayApiRef.current?.hasSelected?.()));+ setCanUndo(Boolean(overlayApiRef.current?.canUndo()));+ setCanRedo(Boolean(overlayApiRef.current?.canRedo()));+ };check();const id = setInterval(check, 350);return () => clearInterval(id);}, [signControlsVisible]);const handleOpenCertificateModal = () => {- if (previewCount === 0) {- alert({- alertType: "error",- title: t("common.error"),- body: t(- "certSign.collab.signRequest.noSignatures",- "Please place at least one signature on the PDF",- ),- });- return;- }setCertificateModalOpen(true);};@@ -230,9 +270,8 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {}await onSign(formData);+ overlayApiRef.current?.clearPreviews();setCertificateModalOpen(false);- } catch (error) {- console.error("Failed to sign document:", error);} finally {setSigning(false);}@@ -261,6 +300,7 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {durationMs: 2500,});onBack();+ data.onOpenFiles?.();};const handleDeleteSelected = () => {@@ -268,75 +308,173 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {};return (- <Stack gap="md" p="md">- <Button- leftSection={<Icon name="arrow-left" size={20} />}- variant="tertiary"- size="sm"- onClick={onBack}- justify="start"- style={{ alignSelf: "flex-start" }}- >- {t("certSign.collab.signRequest.backToList", "Back to Sign Requests")}- </Button>-- <Stack gap={2}>- <Text size="sm" fw={600} truncate>- {signRequest.documentName}- </Text>- <Text size="xs" c="dimmed">- {t("certSign.collab.signRequest.from", "From")}:{" "}- {signRequest.ownerUsername} •{" "}- {new Date(signRequest.createdAt).toLocaleDateString()}- </Text>- </Stack>-- <Divider />-- {canSign && signControlsVisible && (- <>+ <div className="signing-detail">+ <div className="signing-detail__body">+ <SigningSessionHeader+ documentName={signRequest.documentName}+ owner={signRequest.ownerUsername}+ createdAt={signRequest.createdAt}+ dueDate={signRequest.dueDate}+ message={signRequest.message}+ status={+ <StatusBadge+ tone={+ signRequest.finalized || signRequest.myStatus === "SIGNED"+ ? "success"+ : signRequest.myStatus === "DECLINED"+ ? "neutral"+ : "info"+ }+ >+ {signRequest.finalized+ ? t("certSign.collab.sessionList.finalized", "Finalized")+ : signRequest.myStatus === "SIGNED"+ ? t("signMenu.submitted", "Submitted · awaiting finalization")+ : signRequest.myStatus === "DECLINED"+ ? t("certSign.declined", "Declined")+ : t("signingDetail.requestTitle", "Signature request")}+ </StatusBadge>+ }+ />+ {!signRequest.finalized && (+ <p className="signing-detail__hint">+ {t(+ "signingDetail.inProgressPreview",+ "In-progress preview with submitted signatures. The owner has not finalized this document yet.",+ )}+ </p>+ )}+ {!canSign && (+ <div className="signing-detail__summary" role="status">+ <Icon+ name={+ signRequest.finalized || signRequest.myStatus === "SIGNED"+ ? "circle-check"+ : "info"+ }+ size={24}+ />+ <h3>+ {signRequest.finalized+ ? t("signingDetail.finalDocument", "Signed document")+ : signRequest.myStatus === "SIGNED"+ ? t(+ "signingDetail.signatureSubmitted",+ "Your signature is submitted",+ )+ : t("signingDetail.requestClosed", "This request is closed")}+ </h3>+ <p>+ {signRequest.finalized+ ? t(+ "certSign.collab.signRequest.closed",+ "This session is finalized. You can view the final document, but no further signatures or declines are accepted.",+ )+ : signRequest.myStatus === "SIGNED"+ ? data.onManageSession+ ? t(+ "signingDetail.ownerNext",+ "Return to your session to review everyone's signatures and finalize the document when you are ready.",+ )+ : t(+ "signingDetail.awaitingOwner",+ "The owner will finalize the document once they are ready.",+ )+ : t(+ "signingDetail.viewOnly",+ "You can still review the document here.",+ )}+ </p>+ </div>+ )}+ {signRequest.participants && (+ <ParticipantListPanel+ participants={signRequest.participants}+ finalized={Boolean(signRequest.finalized)}+ />+ )}+ {signControlsVisible && (<SignControlsPanelplacementMode={placementMode}onPlacementModeChange={setPlacementMode}onSignatureSelected={setSignatureConfig}- onComplete={handleOpenCertificateModal}- canComplete={previewCount > 0}signatureConfig={signatureConfig}hasSelectedAnnotation={hasSelectedAnnotation}onDeleteSelected={handleDeleteSelected}+ canUndo={canUndo}+ canRedo={canRedo}+ onUndo={() => overlayApiRef.current?.undo()}+ onRedo={() => overlayApiRef.current?.redo()}/>- <Divider />- </>- )}-- <Button- variant="tertiary"- leftSection={<Icon name="folder-open" size={20} />}- onClick={handleAddToActiveFiles}- fullWidth- style={{- backgroundColor: "var(--c-surface-raised)",- color: "var(--c-accent-text)",- border: "1px solid var(--c-border)",- }}- >- {t("certSign.collab.signRequest.addToFiles", "Add to Active Files")}- </Button>-- {signRequest.myStatus !== "SIGNED" &&- signRequest.myStatus !== "DECLINED" && (+ )}+ </div>+ <footer className="signing-detail__footer">+ {data.onManageSession && (<Button- variant="tertiary"- accent="danger"- leftSection={<Icon name="circle-x" size={20} />}- onClick={handleDecline}- loading={declining}- fullWidth+ variant="secondary"+ onClick={data.onManageSession}+ disabled={signing || declining}>- {t("certSign.collab.signRequest.decline", "Decline Request")}+ {t("signingDetail.manageSession", "Manage signing session")}</Button>)}-+ {!signRequest.finalized && (+ <Button+ variant="secondary"+ onClick={refreshPreview}+ loading={refreshing}+ disabled={signing || declining}+ >+ {t("signingDetail.refreshPreview", "Refresh preview")}+ </Button>+ )}+ {canSign && (+ <>+ <h3>{t("signingDetail.readyToSign", "Ready to sign?")}</h3>+ <p className="signing-detail__hint">+ {t(+ "signingDetail.certificateNext",+ "Choose your certificate in the next step.",+ )}+ </p>+ <Button+ leftSection={<Icon name="check" size={18} />}+ onClick={handleOpenCertificateModal}+ disabled={declining || signing}+ fullWidth+ >+ {t(+ "certSign.collab.signRequest.completeAndSign",+ "Complete & Sign",+ )}+ </Button>+ </>+ )}+ <div className="signing-detail__secondary">+ <Button+ variant="tertiary"+ leftSection={<Icon name="folder-open" size={16} />}+ onClick={handleAddToActiveFiles}+ size="sm"+ disabled={declining || signing}+ >+ {t("certSign.collab.signRequest.addToFiles", "Add to Active Files")}+ </Button>+ {canSign && (+ <Button+ variant="tertiary"+ accent="danger"+ leftSection={<Icon name="circle-x" size={16} />}+ onClick={handleDecline}+ loading={declining}+ size="sm"+ disabled={signing}+ >+ {t("certSign.collab.signRequest.decline", "Decline Request")}+ </Button>+ )}+ </div>+ </footer>{canSign && (<CertificateConfigModalopened={certificateModalOpen}@@ -348,7 +486,7 @@ const SignRequestPanel = ({ data }: SignRequestPanelProps) => {defaultLocation={signRequest.location || ""}/>)}- </Stack>+ </div>);};diff --git a/frontend/editor/src/core/components/tools/certSign/steps/ReviewSignatureStep.tsx b/frontend/editor/src/core/components/tools/certSign/steps/ReviewSignatureStep.tsxindex 131c5d91d2..6f4256c44d 100644--- a/frontend/editor/src/core/components/tools/certSign/steps/ReviewSignatureStep.tsx+++ b/frontend/editor/src/core/components/tools/certSign/steps/ReviewSignatureStep.tsx@@ -38,15 +38,15 @@ export const ReviewSignatureStep: React.FC<ReviewSignatureStepProps> = ({case "USER_CERT":return t("certSign.collab.signRequest.usePersonalCert",- "Personal Certificate",+ "Stirling Sign · Personal",);case "SERVER":return t("certSign.collab.signRequest.useServerCert",- "Organization Certificate",+ "Stirling Sign · Organization",);case "UPLOAD":- return `${uploadFormat} — ${p12File?.name || t("certSign.collab.signRequest.uploadCert", "Custom Certificate")}`;+ return `${uploadFormat} — ${p12File?.name || t("certSign.collab.signRequest.uploadCert", "Upload a certificate")}`;default:return "";}diff --git a/frontend/editor/src/core/components/tooltips/useGroupSigningTips.ts b/frontend/editor/src/core/components/tooltips/useGroupSigningTips.tsindex 34b55a7a57..15011548cf 100644--- a/frontend/editor/src/core/components/tooltips/useGroupSigningTips.ts+++ b/frontend/editor/src/core/components/tooltips/useGroupSigningTips.ts@@ -10,23 +10,26 @@ export const useGroupSigningTips = (): TooltipContent => {},tips: [{- title: t("groupSigning.tooltip.sequential.title", "Sequential Signing"),+ title: t(+ "groupSigning.tooltip.sequential.title",+ "Signing in Any Order",+ ),description: t("groupSigning.tooltip.sequential.description",- "Participants sign documents in the order you specify. Each signer receives a notification when it is their turn.",+ "Assigned participants can review and sign independently, in any order.",),bullets: [t("groupSigning.tooltip.sequential.bullet1",- "First participant must sign before the second can access the document",+ "Participants do not need to wait for another signer",),t("groupSigning.tooltip.sequential.bullet2",- "Ensures proper signing order for legal compliance",+ "Track each participant's progress in Signing Sessions",),t("groupSigning.tooltip.sequential.bullet3",- "You can reorder participants by dragging them in the list",+ "A due date is a reminder; it does not expire access",),],},@@ -34,7 +37,7 @@ export const useGroupSigningTips = (): TooltipContent => {title: t("groupSigning.tooltip.roles.title", "Participant Roles"),description: t("groupSigning.tooltip.roles.description",- "You control the signature appearance settings for all participants.",+ "The owner sets request defaults; each participant chooses their certificate and optional visible mark.",),bullets: [t(@@ -43,11 +46,11 @@ export const useGroupSigningTips = (): TooltipContent => {),t("groupSigning.tooltip.roles.bullet2",- "Participants: Create their signature, choose certificate, place on PDF",+ "Participants: Choose a certificate and optionally place a visible signature on the PDF",),t("groupSigning.tooltip.roles.bullet3",- "Participants cannot modify signature visibility, reason, or location settings",+ "Participants can adjust their signature reason and location before submitting",),],},@@ -58,20 +61,20 @@ export const useGroupSigningTips = (): TooltipContent => {),description: t("groupSigning.tooltip.finalization.description",- "Once all participants have signed (or you choose to finalize early), you can generate the final signed PDF.",+ "After at least one participant has signed, the owner can finalize the request and generate the signed PDF.",),bullets: [t("groupSigning.tooltip.finalization.bullet1",- "All signatures are applied in the participant order you specified",+ "The final PDF includes all accepted signatures",),t("groupSigning.tooltip.finalization.bullet2",- "You can finalize with partial signatures if needed",+ "Review outstanding participants before finalizing with partial signatures",),t("groupSigning.tooltip.finalization.bullet3",- "Once finalized, the session cannot be modified",+ "Finalization closes the request; outstanding participants can no longer sign",),],},diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsxindex 79bc57b7f7..4b0ed257a1 100644--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx@@ -73,6 +73,8 @@ export interface EmbedPdfViewerProps {previewFile?: File | null;// ── Signature overlay pass-through (opt-in; all default off) ──────────────signaturePreviews?: SignaturePreview[];+ /** Submitted marks rendered separately from editable previews and excluded from submission. */+ readOnlySignaturePreviews?: SignaturePreview[];signaturePreviewsReadOnly?: boolean;signaturePlacementMode?: boolean;signaturePlacementData?: string;@@ -114,6 +116,7 @@ const EmbedPdfViewerContent = ({onClose,previewFile,signaturePreviews,+ readOnlySignaturePreviews,signaturePreviewsReadOnly,signaturePlacementMode,signaturePlacementData,@@ -1865,6 +1868,7 @@ const EmbedPdfViewerContent = ({// Future: Handle signature completion}}signaturePreviews={signaturePreviews}+ readOnlySignaturePreviews={readOnlySignaturePreviews}signaturePreviewsReadOnly={signaturePreviewsReadOnly}signaturePlacementMode={signaturePlacementMode}signaturePlacementData={signaturePlacementData}diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsxindex abd296799a..1094eb2e10 100644--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx@@ -13,6 +13,7 @@ import { EmbedPDF, useDocumentState } from "@embedpdf/core/react";import { usePdfiumEngine } from "@embedpdf/engines/react";import { PrivateContent } from "@app/components/shared/PrivateContent";import { useAppConfig } from "@app/contexts/AppConfigContext";+import { useSignaturePreviewHistory } from "@app/hooks/signing/useSignaturePreviewHistory";// Import the essential pluginsimport {@@ -150,6 +151,8 @@ interface LocalEmbedPDFProps {// ── Signature overlay (opt-in; all default off) ──────────────────────────/** Read-only / interactive signature preview overlays to render per page. */signaturePreviews?: SignaturePreview[];+ /** Submitted marks rendered separately from editable previews and excluded from submission. */+ readOnlySignaturePreviews?: SignaturePreview[];/** If true, previews are display-only (cannot be moved, resized, or deleted). */signaturePreviewsReadOnly?: boolean;/** When true (and not read-only), clicking a page places a new preview. */@@ -275,6 +278,7 @@ interface PageLayerOptions {onAnnotationMenuAnchor: (anchor: AnnotationMenuAnchor | null) => void;/** Null while the signature preview overlay is not mounted. */signatureOverlay: SignatureOverlayOptions | null;+ readOnlySignaturePreviews?: SignaturePreview[];}/** Everything a page needs besides the geometry the Scroller supplies. */@@ -459,6 +463,7 @@ function PageLayers({showBakedAnnotations,onAnnotationMenuAnchor,signatureOverlay,+ readOnlySignaturePreviews,}: PageGeometry & PageLayerOptions) {return (<>@@ -499,6 +504,17 @@ function PageLayers({/>{/* LinkLayer: uses EmbedPDF annotation state for link rendering */}<LinkLayer documentId={documentId} pageIndex={pageIndex} />+ {readOnlySignaturePreviews && (+ <SignaturePreviewLayer+ pageIndex={pageIndex}+ pageWidth={width}+ pageHeight={height}+ previews={readOnlySignaturePreviews}+ readOnly+ placementMode={false}+ onChange={() => {}}+ />+ )}{/* Signature preview overlay (opt-in; off by default) */}{signatureOverlay && (<SignaturePreviewLayer@@ -681,6 +697,7 @@ export function LocalEmbedPDF({isSignMode = false,pdfRenderMode = "normal",signaturePreviews,+ readOnlySignaturePreviews,signaturePreviewsReadOnly = false,signaturePlacementMode = false,signaturePlacementData,@@ -703,9 +720,15 @@ export function LocalEmbedPDF({>([]);const [commentAuthorName, setCommentAuthorName] = useState<string>("Guest");- const [localSignaturePreviews, setLocalSignaturePreviews] = useState<- SignaturePreview[]- >(signaturePreviews ?? []);+ const {+ previews: localSignaturePreviews,+ change: handleSignaturePreviewsChange,+ reset: resetSignaturePreviews,+ undo: undoSignaturePreview,+ redo: redoSignaturePreview,+ canUndo: canUndoSignaturePreview,+ canRedo: canRedoSignaturePreview,+ } = useSignaturePreviewHistory(signaturePreviews);// Mount the overlay for controlled previews, placement mode, or once any// signature is placed — so leaving placement mode doesn't hide placements.@@ -720,26 +743,21 @@ export function LocalEmbedPDF({// Keep internal state in sync when the caller supplies controlled previews.useEffect(() => {if (signaturePreviews !== undefined) {- setLocalSignaturePreviews(signaturePreviews);+ resetSignaturePreviews(signaturePreviews);}- }, [signaturePreviews]);+ }, [signaturePreviews, resetSignaturePreviews]);- const handleSignaturePreviewsChange = useCallback(- (next: SignaturePreview[]) => {- setLocalSignaturePreviews(next);- onSignaturePreviewsChange?.(next);- },- [onSignaturePreviewsChange],- );+ useEffect(() => {+ onSignaturePreviewsChange?.(localSignaturePreviews);+ }, [localSignaturePreviews, onSignaturePreviewsChange]);useImperativeHandle(signatureOverlayApiRef,() => ({getSignaturePreviews: () => localSignaturePreviews,clearPreviews: () => {- setLocalSignaturePreviews([]);+ resetSignaturePreviews([]);setSelectedSignatureId(null);- onSignaturePreviewsChange?.([]);},deleteSelected: () => {if (!selectedSignatureId) return;@@ -747,12 +765,32 @@ export function LocalEmbedPDF({(p) => p.id !== selectedSignatureId,);setSelectedSignatureId(null);- setLocalSignaturePreviews(next);- onSignaturePreviewsChange?.(next);+ handleSignaturePreviewsChange(next);+ },+ hasSelected: () =>+ localSignaturePreviews.some(+ (preview) => preview.id === selectedSignatureId,+ ),+ undo: () => {+ if (!signaturePreviewsReadOnly) undoSignaturePreview();+ },+ redo: () => {+ if (!signaturePreviewsReadOnly) redoSignaturePreview();},- hasSelected: () => selectedSignatureId !== null,+ canUndo: () => !signaturePreviewsReadOnly && canUndoSignaturePreview,+ canRedo: () => !signaturePreviewsReadOnly && canRedoSignaturePreview,}),- [localSignaturePreviews, selectedSignatureId, onSignaturePreviewsChange],+ [+ localSignaturePreviews,+ selectedSignatureId,+ resetSignaturePreviews,+ handleSignaturePreviewsChange,+ undoSignaturePreview,+ redoSignaturePreview,+ canUndoSignaturePreview,+ canRedoSignaturePreview,+ signaturePreviewsReadOnly,+ ],);useEffect(() => {@@ -1247,6 +1285,7 @@ export function LocalEmbedPDF({enableRedaction,showBakedAnnotations,onAnnotationMenuAnchor: handleAnnotationMenuAnchor,+ readOnlySignaturePreviews,signatureOverlay: signatureOverlayEnabled? {previews: localSignaturePreviews,diff --git a/frontend/editor/src/core/components/viewer/SignaturePreviewLayer.test.tsx b/frontend/editor/src/core/components/viewer/SignaturePreviewLayer.test.tsxnew file mode 100644index 0000000000..4ba2122e57--- /dev/null+++ b/frontend/editor/src/core/components/viewer/SignaturePreviewLayer.test.tsx@@ -0,0 +1,120 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { expect, it, vi } from "vitest";+import { SignaturePreviewLayer } from "@app/components/viewer/SignaturePreviewLayer";+import type { SignaturePreview } from "@app/components/viewer/viewerTypes";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));++vi.mock("@embedpdf/plugin-interaction-manager/react", () => ({+ useInteractionManagerCapability: () => ({+ provides: { pause: vi.fn(), resume: vi.fn() },+ }),+}));++const signature: SignaturePreview = {+ id: "draft",+ pageIndex: 0,+ x: 0.1,+ y: 0.2,+ width: 0.3,+ height: 0.1,+ signatureData: "data:image/png;base64,AA==",+ signatureType: "canvas",+};++it.each([+ [true, undefined, false, "default", "none"],+ [false, signature.signatureData, false, "default", "none"],+ [true, signature.signatureData, true, "default", "none"],+ [true, signature.signatureData, false, "crosshair", "auto"],+] as const)(+ "captures placement only with a selected signature and Place mode (%s, %s, %s)",+ (placementMode, placementData, readOnly, cursor, pointerEvents) => {+ const onChange = vi.fn();+ const { container } = render(+ <MantineProvider>+ <SignaturePreviewLayer+ pageIndex={0}+ pageWidth={600}+ pageHeight={800}+ previews={[]}+ onChange={onChange}+ placementMode={placementMode}+ placementData={placementData}+ readOnly={readOnly}+ />+ </MantineProvider>,+ );+ const layer = container.querySelector("div")!;+ expect(layer).toHaveStyle({ cursor, "pointer-events": pointerEvents });+ fireEvent.click(layer, { clientX: 200, clientY: 300 });+ expect(onChange).toHaveBeenCalledTimes(cursor === "crosshair" ? 1 : 0);+ },+);++it.each(["move", "resize"])(+ "commits %s once on release after transient pointer updates",+ (gesture) => {+ const onChange = vi.fn();+ const { container } = render(+ <MantineProvider>+ <SignaturePreviewLayer+ pageIndex={0}+ pageWidth={600}+ pageHeight={800}+ previews={[signature]}+ onChange={onChange}+ placementMode={false}+ readOnly={false}+ />+ </MantineProvider>,+ );+ const target =+ gesture === "move"+ ? screen.getByRole("img", { name: "Signature preview" }).parentElement!+ : container.querySelector<HTMLElement>('[data-resize-handle="true"]')!;+ target.setPointerCapture = vi.fn();+ target.releasePointerCapture = vi.fn();+ fireEvent(+ target,+ new MouseEvent("pointerdown", {+ bubbles: true,+ clientX: 200,+ clientY: 300,+ }),+ );+ fireEvent(+ target,+ new MouseEvent("pointermove", {+ bubbles: true,+ clientX: 210,+ clientY: 310,+ }),+ );+ fireEvent(+ target,+ new MouseEvent("pointermove", {+ bubbles: true,+ clientX: 220,+ clientY: 320,+ }),+ );+ expect(onChange.mock.calls.map((call) => call[1])).toEqual([true, true]);+ const updated = onChange.mock.calls.at(-1)![0];+ fireEvent(+ target,+ new MouseEvent("pointerup", {+ bubbles: true,+ clientX: 220,+ clientY: 320,+ }),+ );+ expect(onChange).toHaveBeenLastCalledWith(updated);+ expect(updated[0]).not.toEqual(signature);+ },+);diff --git a/frontend/editor/src/core/components/viewer/SignaturePreviewLayer.tsx b/frontend/editor/src/core/components/viewer/SignaturePreviewLayer.tsxindex 104af05e37..b77a37733f 100644--- a/frontend/editor/src/core/components/viewer/SignaturePreviewLayer.tsx+++ b/frontend/editor/src/core/components/viewer/SignaturePreviewLayer.tsx@@ -33,8 +33,8 @@ export interface SignaturePreviewLayerProps {placementData?: string;/** Signature type assigned to newly placed previews. */placementType?: "canvas" | "image" | "text";- /** Emits the full updated preview array (across all pages) whenever it changes. */- onChange: (previews: SignaturePreview[]) => void;+ /** Transient drag updates must be followed by a committed update on release. */+ onChange: (previews: SignaturePreview[], transient?: boolean) => void;/** Currently selected preview id (managed by the parent layer). */selectedId?: string | null;/** Notifies the parent when a preview is selected (used for deleteSelected/hasSelected). */@@ -68,6 +68,7 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({const pauseInteraction = () => interactionManager?.pause();const resumeInteraction = () => interactionManager?.resume();+ const canPlace = !readOnly && placementMode && Boolean(placementData);const pagePreviews = previews.filter((preview) => preview.pageIndex === pageIndex,@@ -106,13 +107,13 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({style={{position: "absolute",inset: 0,- cursor: !readOnly && placementMode ? "crosshair" : "default",+ cursor: canPlace ? "crosshair" : "default",// Let clicks fall through to the page except in placement mode, where we// need to capture click-to-place. Individual previews opt back in below.- pointerEvents: !readOnly && placementMode ? "auto" : "none",+ pointerEvents: canPlace ? "auto" : "none",}}onMouseMove={- !readOnly && placementMode && placementData+ canPlace? (e) => {const rect = e.currentTarget.getBoundingClientRect();setCursorPos({@@ -123,7 +124,7 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({: undefined}onMouseLeave={() => setCursorPos(null)}- onClick={!readOnly && placementMode ? handlePlaceClick : undefined}+ onClick={canPlace ? handlePlaceClick : undefined}>{pagePreviews.map((preview) => {if (!preview.signatureData) return null;@@ -209,6 +210,7 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({const startY = e.clientY;const startLeft = preview.x;const startTop = preview.y;+ let latest = previews;const handlePointerMove = (moveEvent: PointerEvent) => {isDraggingRef.current = true;@@ -216,17 +218,16 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({(moveEvent.clientX - startX) / pageWidth;const deltaY =(moveEvent.clientY - startY) / pageHeight;- onChange(- previews.map((p) =>- p.id === preview.id- ? {- ...p,- x: startLeft + deltaX,- y: startTop + deltaY,- }- : p,- ),+ latest = previews.map((p) =>+ p.id === preview.id+ ? {+ ...p,+ x: startLeft + deltaX,+ y: startTop + deltaY,+ }+ : p,);+ onChange(latest, true);};const handlePointerUp = (upEvent: PointerEvent) => {@@ -235,7 +236,16 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({handlePointerMove,);el.removeEventListener("pointerup", handlePointerUp);+ el.removeEventListener(+ "pointercancel",+ handlePointerUp,+ );el.releasePointerCapture(upEvent.pointerId);+ onChange(+ upEvent.type === "pointercancel"+ ? previews+ : latest,+ );resumeInteraction();window.getSelection()?.removeAllRanges();setTimeout(() => {@@ -245,6 +255,7 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({el.addEventListener("pointermove", handlePointerMove);el.addEventListener("pointerup", handlePointerUp);+ el.addEventListener("pointercancel", handlePointerUp);}}>@@ -300,6 +311,7 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({const startHeight = preview.height;const startLeft = preview.x;const startTop = preview.y;+ let latest = previews;const handlePointerMove = (moveEvent: PointerEvent) => {isDraggingRef.current = true;@@ -338,19 +350,18 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({newX = Math.max(0, Math.min(newX, 1 - newWidth));newY = Math.max(0, Math.min(newY, 1 - newHeight));- onChange(- previews.map((p) =>- p.id === preview.id- ? {- ...p,- x: newX,- y: newY,- width: newWidth,- height: newHeight,- }- : p,- ),+ latest = previews.map((p) =>+ p.id === preview.id+ ? {+ ...p,+ x: newX,+ y: newY,+ width: newWidth,+ height: newHeight,+ }+ : p,);+ onChange(latest, true);};const handlePointerUp = (upEvent: PointerEvent) => {@@ -359,7 +370,16 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({handlePointerMove,);el.removeEventListener("pointerup", handlePointerUp);+ el.removeEventListener(+ "pointercancel",+ handlePointerUp,+ );el.releasePointerCapture(upEvent.pointerId);+ onChange(+ upEvent.type === "pointercancel"+ ? previews+ : latest,+ );resumeInteraction();window.getSelection()?.removeAllRanges();setTimeout(() => {@@ -369,6 +389,7 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({el.addEventListener("pointermove", handlePointerMove);el.addEventListener("pointerup", handlePointerUp);+ el.addEventListener("pointercancel", handlePointerUp);}}/>))}@@ -379,7 +400,7 @@ export const SignaturePreviewLayer = memo(function SignaturePreviewLayer({})}{/* Hover preview: ghost signature following cursor in placement mode */}- {!readOnly && placementMode && placementData && cursorPos && (+ {canPlace && cursorPos && (<imgsrc={placementData}alt=""diff --git a/frontend/editor/src/core/components/viewer/Viewer.tsx b/frontend/editor/src/core/components/viewer/Viewer.tsxindex d1c429f4f8..eb816e58ff 100644--- a/frontend/editor/src/core/components/viewer/Viewer.tsx+++ b/frontend/editor/src/core/components/viewer/Viewer.tsx@@ -19,6 +19,7 @@ export type { ViewerProps };type SignatureOverlayPassThrough = Pick<EmbedPdfViewerProps,| "signaturePreviews"+ | "readOnlySignaturePreviews"| "signaturePreviewsReadOnly"| "signaturePlacementMode"| "signaturePlacementData"diff --git a/frontend/editor/src/core/components/viewer/viewerTypes.ts b/frontend/editor/src/core/components/viewer/viewerTypes.tsindex b3c1d09b33..f7ae383fb3 100644--- a/frontend/editor/src/core/components/viewer/viewerTypes.ts+++ b/frontend/editor/src/core/components/viewer/viewerTypes.ts@@ -23,6 +23,10 @@ export interface SignatureOverlayAPI {clearPreviews: () => void;deleteSelected: () => void;hasSelected: () => boolean;+ undo: () => void;+ redo: () => void;+ canUndo: () => boolean;+ canRedo: () => boolean;}export interface ClearDocumentAnnotationsResult {diff --git a/frontend/editor/src/core/contexts/FilesModalContext.test.tsx b/frontend/editor/src/core/contexts/FilesModalContext.test.tsxindex e6a7d7108d..0f537aff98 100644--- a/frontend/editor/src/core/contexts/FilesModalContext.test.tsx+++ b/frontend/editor/src/core/contexts/FilesModalContext.test.tsx@@ -59,6 +59,24 @@ vi.mock("@app/services/apiClient", () => ({ default: { get: state.apiGet } }));beforeEach(() => vi.clearAllMocks());describe("file picker caller contract", () => {+ it("clears a caller's format and count restrictions when the next picker opens", () => {+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() =>+ result.current.openFilesModal({+ supportedFormats: ["pdf"],+ maxSelectable: 1,+ }),+ );+ expect(result.current.supportedFormats).toEqual(["pdf"]);+ expect(result.current.maxSelectable).toBe(1);+ act(() => result.current.closeFilesModal());+ act(() => result.current.openFilesModal());+ expect(result.current.supportedFormats).toBeUndefined();+ expect(result.current.maxSelectable).toBeNull();+ });+it("inserts readable files when a share is revoked and another local blob is missing", async () => {allowConsole.error(/Could not load selected file/);const first = new File(["first"], "First.pdf");diff --git a/frontend/editor/src/core/contexts/FilesModalContext.tsx b/frontend/editor/src/core/contexts/FilesModalContext.tsxindex 1660f5c3d8..1790ad9b5c 100644--- a/frontend/editor/src/core/contexts/FilesModalContext.tsx+++ b/frontend/editor/src/core/contexts/FilesModalContext.tsx@@ -35,6 +35,7 @@ interface FilesModalOptions {insertAfterPage?: number;customHandler?: CustomFileHandler;maxSelectable?: number | null;+ supportedFormats?: string[];}interface FilesModalContextType {@@ -42,6 +43,8 @@ interface FilesModalContextType {openFilesModal: (options?: FilesModalOptions) => void;closeFilesModal: () => void;maxSelectable: number | null;+ /** A caller's format restriction takes precedence over the currently selected tool. */+ supportedFormats?: string[];/** Closes the picker before ingestion; rejects on import failure. */onFileUpload: (files: File[]) => Promise<void>;/** Imports readable selections before rejecting with unavailable filenames; leaves modal state unchanged. */@@ -75,6 +78,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({const [insertAfterPage, setInsertAfterPage] = useState<number | undefined>();const [customHandler, setCustomHandler] = useState<CustomFileHandler>();const [maxSelectable, setMaxSelectable] = useState<number | null>(null);+ const [supportedFormats, setSupportedFormats] = useState<string[]>();const importBundleToWorkbench = useCallback(async (@@ -215,6 +219,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({setInsertAfterPage(options?.insertAfterPage);setCustomHandler(() => options?.customHandler);setMaxSelectable(options?.maxSelectable ?? null);+ setSupportedFormats(options?.supportedFormats);setIsFilesModalOpen(true);}, []);@@ -364,6 +369,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({onModalClose,setOnModalClose: setModalCloseCallback,maxSelectable,+ supportedFormats,}),[isFilesModalOpen,@@ -375,6 +381,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({onModalClose,setModalCloseCallback,maxSelectable,+ supportedFormats,],);diff --git a/frontend/editor/src/core/contexts/NavigationContext.tsx b/frontend/editor/src/core/contexts/NavigationContext.tsxindex d1ebe3391e..54c72456bf 100644--- a/frontend/editor/src/core/contexts/NavigationContext.tsx+++ b/frontend/editor/src/core/contexts/NavigationContext.tsx@@ -179,8 +179,8 @@ export const NavigationProvider: React.FC<{(state.workbench === "pageEditor" &&workbench !== "pageEditor" &&hasUnsavedChanges) ||- (state.workbench === "viewer" &&- workbench !== "viewer" &&+ ((state.workbench === "viewer" || state.workbench === "signing") &&+ workbench !== state.workbench &&hasUnsavedChanges) ||(state.workbench.startsWith("custom:") &&workbench !== state.workbench &&@@ -249,8 +249,8 @@ export const NavigationProvider: React.FC<{(state.workbench === "pageEditor" &&workbench !== "pageEditor" &&hasUnsavedChanges) ||- (state.workbench === "viewer" &&- workbench !== "viewer" &&+ ((state.workbench === "viewer" || state.workbench === "signing") &&+ workbench !== state.workbench &&hasUnsavedChanges) ||(state.workbench.startsWith("custom:") &&workbench !== state.workbench &&diff --git a/frontend/editor/src/core/contexts/NavigationContext.unsavedWork.test.tsx b/frontend/editor/src/core/contexts/NavigationContext.unsavedWork.test.tsxindex 9e5f78b0bf..65b43a0501 100644--- a/frontend/editor/src/core/contexts/NavigationContext.unsavedWork.test.tsx+++ b/frontend/editor/src/core/contexts/NavigationContext.unsavedWork.test.tsx@@ -70,4 +70,16 @@ describe("the dirty state the disk reconciliation reads", () => {view.unmount();expect(hasUnsavedWork()).toBe(false);});++ it("guards leaving the signing workspace and keeps it open when cancelled", () => {+ renderEditor();+ act(() => editor.setWorkbench("signing"));+ act(() => editor.setHasUnsavedChanges(true));+ act(() => editor.setWorkbench("myFiles"));+ expect(editor.workbench).toBe("signing");+ expect(editor.pendingNavigation).toEqual(expect.any(Function));+ act(() => editor.cancelNavigation());+ expect(editor.workbench).toBe("signing");+ expect(editor.pendingNavigation).toBeNull();+ });});diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.tsxindex 5dbab6f6e2..a9a4cd6f80 100644--- a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx@@ -17,7 +17,8 @@ import {type ReactNode,} from "react";-export type QuickNavToolReasons = Partial<Record<ToolId, string>>;+export type QuickNavEntryId = ToolId | "sharedSign";+export type QuickNavToolReasons = Partial<Record<QuickNavEntryId, string>>;export type { QuickNavIdentity } from "@app/contexts/quickNavAccount";@@ -84,7 +85,9 @@ function sameReasons(): boolean {const nextKeys = Object.keys(next);if (nextKeys.length !== Object.keys(prev).length) return false;- return nextKeys.every((key) => next[key as ToolId] === prev[key as ToolId]);+ return nextKeys.every(+ (key) => next[key as QuickNavEntryId] === prev[key as QuickNavEntryId],+ );}const QuickNavHostContext = createContext<QuickNavHostValue | null>(null);diff --git a/frontend/editor/src/core/contexts/SigningOverlayContext.tsx b/frontend/editor/src/core/contexts/SigningOverlayContext.tsxindex f24ceeb6fc..3d2cb12ac6 100644--- a/frontend/editor/src/core/contexts/SigningOverlayContext.tsx+++ b/frontend/editor/src/core/contexts/SigningOverlayContext.tsx@@ -4,10 +4,12 @@ import type {SignatureOverlayAPI,} from "@app/components/viewer/viewerTypes";-/** Signing document + signature-overlay props the Shared Signing sidebar tool feeds to the main Workbench Viewer. */+/** Document and signature placement state shared by the signing workspace viewer and its controls. */export interface SigningOverlay {file: File | null;signaturePreviews?: SignaturePreview[];+ /** Submitted marks rendered separately from editable previews and excluded from submission. */+ readOnlySignaturePreviews?: SignaturePreview[];signaturePreviewsReadOnly?: boolean;signaturePlacementMode?: boolean;signaturePlacementData?: string;diff --git a/frontend/editor/src/core/contexts/ViewerContext.tsx b/frontend/editor/src/core/contexts/ViewerContext.tsxindex b4c16f4aca..86c42743be 100644--- a/frontend/editor/src/core/contexts/ViewerContext.tsx+++ b/frontend/editor/src/core/contexts/ViewerContext.tsx@@ -1,6 +1,4 @@import React, {- createContext,- useContext,useState,useMemo,useEffect,@@ -26,17 +24,7 @@ import {} from "@app/services/preferencesService";import {createViewerActions,- ScrollActions,- ZoomActions,- PanActions,- SelectionActions,- SpreadActions,- RotationActions,- SearchActions,- ExportActions,- BookmarkActions,- AttachmentActions,- PrintActions,+ type PrintActions,} from "@app/contexts/viewer/viewerActions";import {BridgeRef,@@ -54,13 +42,19 @@ import {RotationState,SearchState,ExportState,- ThumbnailAPIWrapper,BookmarkState,AttachmentState,DocumentPermissionsState,PdfPermissionFlag,} from "@app/contexts/viewer/viewerBridges";import { SpreadMode } from "@embedpdf/plugin-spread/react";+import {+ ViewerContext,+ type ViewerContextType,+} from "@app/contexts/viewer/viewerContext";++export { ViewerContext, useViewer } from "@app/contexts/viewer/viewerContext";+export type { ViewerContextType } from "@app/contexts/viewer/viewerContext";function useImmediateNotifier<Args extends unknown[]>() {const callbacksRef = useRef(new Set<(...args: Args) => void>());@@ -85,152 +79,6 @@ function useImmediateNotifier<Args extends unknown[]>() {return { register, trigger };}-/**- * ViewerContext provides a unified interface to EmbedPDF functionality.- *- * Architecture:- * - Bridges store their own state locally and register with this context- * - Context provides read-only access to bridge state via getter functions- * - Actions call EmbedPDF APIs directly through bridge references- * - No circular dependencies - bridges don't call back into this context- */-export interface ViewerContextType {- // UI state managed by this context- isThumbnailSidebarVisible: boolean;- toggleThumbnailSidebar: () => void;- isBookmarkSidebarVisible: boolean;- toggleBookmarkSidebar: () => void;- isAttachmentSidebarVisible: boolean;- toggleAttachmentSidebar: () => void;- isLayerSidebarVisible: boolean;- toggleLayerSidebar: () => void;- hasLayers: boolean;- setHasLayers: (value: boolean) => void;- isCommentsSidebarVisible: boolean;- setCommentsSidebarVisible: (visible: boolean) => void;- toggleCommentsSidebar: () => void;-- /** Request focus or highlight of a comment card in the sidebar (opens sidebar, then scrolls + flashes or focuses input). */- highlightCommentRequest: {- documentId: string;- pageIndex: number;- annotationId: string;- action: "focus" | "highlight";- } | null;- requestCommentFocus: (- documentId: string,- pageIndex: number,- annotationId: string,- hasContent: boolean,- ) => void;- clearHighlightCommentRequest: () => void;-- // Search interface visibility- isSearchInterfaceVisible: boolean;- searchInterfaceActions: {- open: () => void;- close: () => void;- toggle: () => void;- };-- // Annotation visibility toggle- isAnnotationsVisible: boolean;- toggleAnnotationsVisibility: () => void;-- // Annotation/drawing mode for viewer- isAnnotationMode: boolean;- setAnnotationMode: (enabled: boolean) => void;-- // Active file tracking — ID is the stable source of truth; index is derived from it- activeFileId: string | null;- setActiveFileId: (id: string | null) => void;- activeFileIndex: number;- setActiveFileIndex: (index: number) => void;-- // State getters - read current state from bridges- getScrollState: () => ScrollState;- getZoomState: () => ZoomState;- getPanState: () => PanState;- getSelectionState: () => SelectionState;- getSpreadState: () => SpreadState;- getRotationState: () => RotationState;- getSearchState: () => SearchState;- getThumbnailAPI: () => ThumbnailAPIWrapper | null;- getExportState: () => ExportState;- getBookmarkState: () => BookmarkState;- hasBookmarkSupport: () => boolean;- getAttachmentState: () => AttachmentState;- hasAttachmentSupport: () => boolean;- getDocumentPermissions: () => DocumentPermissionsState;- hasPermission: (flag: PdfPermissionFlag) => boolean;-- // Immediate update callbacks- registerImmediateZoomUpdate: (- callback: (percent: number) => void,- ) => () => void;- registerImmediateScrollUpdate: (- callback: (currentPage: number, totalPages: number) => void,- ) => () => void;- registerImmediateSpreadUpdate: (- callback: (mode: SpreadMode, isDualPage: boolean) => void,- ) => () => void;- registerImmediatePanUpdate: (- callback: (isPanning: boolean) => void,- ) => () => void;- registerImmediateRotationUpdate: (- callback: (rotation: number) => void,- ) => () => void;-- // True while a carried zoom lands after a swap; zoom percent updates in that- // window are intermediate and must not reach the toolbar.- zoomRestorePendingRef: React.MutableRefObject<boolean>;- /** Bumped when the carried zoom settles so bridges can re-publish the state. */- zoomRestoreSettledTick: number;- notifyZoomRestoreSettled: () => void;-- // Internal - for bridges to trigger immediate updates- triggerImmediateScrollUpdate: (- currentPage: number,- totalPages: number,- ) => void;- triggerImmediateZoomUpdate: (zoomPercent: number) => void;- triggerImmediateSpreadUpdate: (- mode: SpreadMode,- isDualPage?: boolean,- ) => void;- triggerImmediatePanUpdate: (isPanning: boolean) => void;- triggerImmediateRotationUpdate: (rotation: number) => void;-- // Action handlers - call EmbedPDF APIs directly- scrollActions: ScrollActions;- zoomActions: ZoomActions;- panActions: PanActions;- selectionActions: SelectionActions;- spreadActions: SpreadActions;- rotationActions: RotationActions;- searchActions: SearchActions;- exportActions: ExportActions;- bookmarkActions: BookmarkActions;- attachmentActions: AttachmentActions;- printActions: PrintActions;-- // Bridge registration - internal use by bridges- registerBridge: <K extends BridgeKey>(- type: K,- ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]> | null,- ) => void;-- // Save changes function - registered by EmbedPdfViewer- applyChanges: (() => Promise<void>) | null;- setApplyChanges: (fn: (() => Promise<void>) | null) => void;-- // PDF page color rendering mode (viewer-only, never modifies the PDF)- pdfRenderMode: PdfRenderMode;- cyclePdfRenderMode: () => void;-}--export const ViewerContext = createContext<ViewerContextType | null>(null);-interface ViewerProviderProps {children: ReactNode;}@@ -779,11 +627,3 @@ export const ViewerProvider: React.FC<ViewerProviderProps> = ({ children }) => {<ViewerContext.Provider value={value}>{children}</ViewerContext.Provider>);};--export const useViewer = (): ViewerContextType => {- const context = useContext(ViewerContext);- if (!context) {- throw new Error("useViewer must be used within a ViewerProvider");- }- return context;-};diff --git a/frontend/editor/src/core/contexts/quickNavAccount.ts b/frontend/editor/src/core/contexts/quickNavAccount.tsindex ed115613e0..80b043672e 100644--- a/frontend/editor/src/core/contexts/quickNavAccount.ts+++ b/frontend/editor/src/core/contexts/quickNavAccount.ts@@ -1,3 +1,5 @@+import type { SigningMenuItem } from "@app/utils/signingItems";+export interface QuickNavIdentity {displayName: string;profilePictureUrl: string | null;@@ -9,6 +11,7 @@ export interface QuickNavAccount {isAnonymous: boolean;identity: QuickNavIdentity | null;signingBadge: number;+ signingItems: SigningMenuItem[];portalAccess: boolean;}@@ -20,6 +23,7 @@ export const EMPTY_QUICK_NAV_ACCOUNT: QuickNavAccount = {isAnonymous: false,identity: null,signingBadge: 0,+ signingItems: [],portalAccess: false,};@@ -38,6 +42,7 @@ export function updateQuickNavAccount(identity:update.identity === undefined ? current.identity : update.identity,signingBadge: update.signingBadge ?? current.signingBadge,+ signingItems: update.signingItems ?? current.signingItems,portalAccess: update.portalAccess ?? current.portalAccess,};@@ -45,6 +50,7 @@ export function updateQuickNavAccount(next.accountId === previous.accountId &&next.isAnonymous === previous.isAnonymous &&next.signingBadge === previous.signingBadge &&+ next.signingItems === previous.signingItems &&next.portalAccess === previous.portalAccess &&next.identity?.displayName === previous.identity?.displayName &&next.identity?.profilePictureUrl === previous.identity?.profilePictureUrl;diff --git a/frontend/editor/src/core/contexts/viewer/viewerContext.ts b/frontend/editor/src/core/contexts/viewer/viewerContext.tsnew file mode 100644index 0000000000..95d5b6e796--- /dev/null+++ b/frontend/editor/src/core/contexts/viewer/viewerContext.ts@@ -0,0 +1,182 @@+import { createContext, useContext, type MutableRefObject } from "react";+import type { PdfRenderMode } from "@app/services/preferencesService";+import type {+ ScrollActions,+ ZoomActions,+ PanActions,+ SelectionActions,+ SpreadActions,+ RotationActions,+ SearchActions,+ ExportActions,+ BookmarkActions,+ AttachmentActions,+ PrintActions,+} from "@app/contexts/viewer/viewerActions";+import type {+ BridgeRef,+ BridgeApiMap,+ BridgeStateMap,+ BridgeKey,+ ScrollState,+ ZoomState,+ PanState,+ SelectionState,+ SpreadState,+ RotationState,+ SearchState,+ ExportState,+ ThumbnailAPIWrapper,+ BookmarkState,+ AttachmentState,+ DocumentPermissionsState,+ PdfPermissionFlag,+} from "@app/contexts/viewer/viewerBridges";+import type { SpreadMode } from "@embedpdf/plugin-spread/react";++/**+ * ViewerContext provides a unified interface to EmbedPDF functionality.+ *+ * Architecture:+ * - Bridges store their own state locally and register with this context+ * - Context provides read-only access to bridge state via getter functions+ * - Actions call EmbedPDF APIs directly through bridge references+ * - No circular dependencies - bridges don't call back into this context+ */+export interface ViewerContextType {+ isThumbnailSidebarVisible: boolean;+ toggleThumbnailSidebar: () => void;+ isBookmarkSidebarVisible: boolean;+ toggleBookmarkSidebar: () => void;+ isAttachmentSidebarVisible: boolean;+ toggleAttachmentSidebar: () => void;+ isLayerSidebarVisible: boolean;+ toggleLayerSidebar: () => void;+ hasLayers: boolean;+ setHasLayers: (value: boolean) => void;+ isCommentsSidebarVisible: boolean;+ setCommentsSidebarVisible: (visible: boolean) => void;+ toggleCommentsSidebar: () => void;++ /** Request focus or highlight of a comment card in the sidebar (opens sidebar, then scrolls + flashes or focuses input). */+ highlightCommentRequest: {+ documentId: string;+ pageIndex: number;+ annotationId: string;+ action: "focus" | "highlight";+ } | null;+ requestCommentFocus: (+ documentId: string,+ pageIndex: number,+ annotationId: string,+ hasContent: boolean,+ ) => void;+ clearHighlightCommentRequest: () => void;++ isSearchInterfaceVisible: boolean;+ searchInterfaceActions: {+ open: () => void;+ close: () => void;+ toggle: () => void;+ };++ isAnnotationsVisible: boolean;+ toggleAnnotationsVisibility: () => void;++ isAnnotationMode: boolean;+ setAnnotationMode: (enabled: boolean) => void;++ // Active file tracking — ID is the stable source of truth; index is derived from it+ activeFileId: string | null;+ setActiveFileId: (id: string | null) => void;+ activeFileIndex: number;+ setActiveFileIndex: (index: number) => void;++ getScrollState: () => ScrollState;+ getZoomState: () => ZoomState;+ getPanState: () => PanState;+ getSelectionState: () => SelectionState;+ getSpreadState: () => SpreadState;+ getRotationState: () => RotationState;+ getSearchState: () => SearchState;+ getThumbnailAPI: () => ThumbnailAPIWrapper | null;+ getExportState: () => ExportState;+ getBookmarkState: () => BookmarkState;+ hasBookmarkSupport: () => boolean;+ getAttachmentState: () => AttachmentState;+ hasAttachmentSupport: () => boolean;+ getDocumentPermissions: () => DocumentPermissionsState;+ hasPermission: (flag: PdfPermissionFlag) => boolean;++ registerImmediateZoomUpdate: (+ callback: (percent: number) => void,+ ) => () => void;+ registerImmediateScrollUpdate: (+ callback: (currentPage: number, totalPages: number) => void,+ ) => () => void;+ registerImmediateSpreadUpdate: (+ callback: (mode: SpreadMode, isDualPage: boolean) => void,+ ) => () => void;+ registerImmediatePanUpdate: (+ callback: (isPanning: boolean) => void,+ ) => () => void;+ registerImmediateRotationUpdate: (+ callback: (rotation: number) => void,+ ) => () => void;++ // True while a carried zoom lands after a swap; zoom percent updates in that+ // window are intermediate and must not reach the toolbar.+ zoomRestorePendingRef: MutableRefObject<boolean>;+ /** Bumped when the carried zoom settles so bridges can re-publish the state. */+ zoomRestoreSettledTick: number;+ notifyZoomRestoreSettled: () => void;++ triggerImmediateScrollUpdate: (+ currentPage: number,+ totalPages: number,+ ) => void;+ triggerImmediateZoomUpdate: (zoomPercent: number) => void;+ triggerImmediateSpreadUpdate: (+ mode: SpreadMode,+ isDualPage?: boolean,+ ) => void;+ triggerImmediatePanUpdate: (isPanning: boolean) => void;+ triggerImmediateRotationUpdate: (rotation: number) => void;++ scrollActions: ScrollActions;+ zoomActions: ZoomActions;+ panActions: PanActions;+ selectionActions: SelectionActions;+ spreadActions: SpreadActions;+ rotationActions: RotationActions;+ searchActions: SearchActions;+ exportActions: ExportActions;+ bookmarkActions: BookmarkActions;+ attachmentActions: AttachmentActions;+ printActions: PrintActions;++ registerBridge: <K extends BridgeKey>(+ type: K,+ ref: BridgeRef<BridgeStateMap[K], BridgeApiMap[K]> | null,+ ) => void;++ // Save changes function - registered by EmbedPdfViewer+ applyChanges: (() => Promise<void>) | null;+ setApplyChanges: (fn: (() => Promise<void>) | null) => void;++ // PDF page color rendering mode (viewer-only, never modifies the PDF)+ pdfRenderMode: PdfRenderMode;+ cyclePdfRenderMode: () => void;+}++// Shared outside the provider module so Fast Refresh cannot split mounted providers from their consumers.+export const ViewerContext = createContext<ViewerContextType | null>(null);++/** Requires an ancestor ViewerProvider; missing providers are programming errors. */+export const useViewer = (): ViewerContextType => {+ const context = useContext(ViewerContext);+ if (!context) {+ throw new Error("useViewer must be used within a ViewerProvider");+ }+ return context;+};diff --git a/frontend/editor/src/core/data/ogImageMap.json b/frontend/editor/src/core/data/ogImageMap.jsonindex 11868c2fcb..617c66360d 100644--- a/frontend/editor/src/core/data/ogImageMap.json+++ b/frontend/editor/src/core/data/ogImageMap.json@@ -1,7 +1,6 @@{"certSign": "certSign","sign": "sign",- "sharedSign": "shared-sign","addText": "add-text","addPassword": "add-password","removePassword": "remove-password",diff --git a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsxindex 3aa46c048c..9998b6355b 100644--- a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx+++ b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx@@ -194,20 +194,6 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {synonyms: getSynonyms(t, "sign"),supportsAutomate: false, //TODO make support Sign},- sharedSign: {- icon: <Icon name="users-plus" size={"1.5rem"} />,- name: t("home.sharedSign.title", "Shared Signing"),- component: lazy(() => import("@app/tools/SharedSign")),- description: t(- "home.sharedSign.desc",- "Request signatures from others and track signing sessions",- ),- categoryId: ToolCategoryId.STANDARD_TOOLS,- subcategoryId: SubcategoryId.SIGNING,- automationSettings: null,- supportsAutomate: false,- synonyms: getSynonyms(t, "sharedSign"),- },addText: {icon: <Icon name="type" size="1.5rem" />,name: t("home.addText.title", "Add Text"),diff --git a/frontend/editor/src/core/hooks/signing/useOpenSigning.ts b/frontend/editor/src/core/hooks/signing/useOpenSigning.tsnew file mode 100644index 0000000000..c1f1def03b--- /dev/null+++ b/frontend/editor/src/core/hooks/signing/useOpenSigning.ts@@ -0,0 +1,17 @@+import { useNavigate } from "react-router-dom";+import { useNavigationActions } from "@app/contexts/NavigationContext";+import {+ requestSigningIntent,+ type SigningIntent,+} from "@app/utils/pendingSigningIntent";++/** Queue the intent only after any unsaved-work prompt has been accepted. */+export function useOpenSigning() {+ const navigate = useNavigate();+ const { actions } = useNavigationActions();+ return (intent: SigningIntent) =>+ actions.requestNavigation(() => {+ requestSigningIntent(intent);+ navigate("/shared-sign");+ });+}diff --git a/frontend/editor/src/core/hooks/signing/useSignaturePreviewHistory.test.ts b/frontend/editor/src/core/hooks/signing/useSignaturePreviewHistory.test.tsnew file mode 100644index 0000000000..c7512ca50c--- /dev/null+++ b/frontend/editor/src/core/hooks/signing/useSignaturePreviewHistory.test.ts@@ -0,0 +1,68 @@+import { act, renderHook } from "@testing-library/react";+import { expect, it } from "vitest";+import { useSignaturePreviewHistory } from "@app/hooks/signing/useSignaturePreviewHistory";+import type { SignaturePreview } from "@app/components/viewer/viewerTypes";++const signature: SignaturePreview = {+ id: "draft",+ pageIndex: 0,+ x: 0.1,+ y: 0.2,+ width: 0.3,+ height: 0.1,+ signatureData: "data:image/png;base64,AA==",+ signatureType: "canvas",+};++it("undoes and redoes adding and deleting a signature, discarding redo after a new edit", () => {+ const { result } = renderHook(() => useSignaturePreviewHistory());+ act(() => result.current.change([signature]));+ act(() => result.current.change([]));+ act(() => result.current.undo());+ expect(result.current.previews).toEqual([signature]);+ act(() => result.current.undo());+ expect(result.current.previews).toEqual([]);+ expect(result.current.canUndo).toBe(false);+ act(() => result.current.redo());+ expect(result.current.previews).toEqual([signature]);+ act(() => result.current.change([{ ...signature, pageIndex: 1 }]));+ expect(result.current.canRedo).toBe(false);+});++it("undoes a whole drag or resize in one step, retaining edits on other pages", () => {+ const initial = [signature, { ...signature, id: "page-two", pageIndex: 1 }];+ const { result } = renderHook(() => useSignaturePreviewHistory(initial));+ for (let step = 1; step <= 12; step++) {+ act(() =>+ result.current.change(+ [+ { ...signature, x: 0.1 + step / 100, width: 0.3 + step / 100 },+ initial[1],+ ],+ true,+ ),+ );+ }+ const moved = result.current.previews;+ expect(result.current.canUndo).toBe(false);+ act(() => result.current.change(moved));+ act(() => result.current.undo());+ expect(result.current.previews).toEqual(initial);+ expect(result.current.canUndo).toBe(false);+ act(() => result.current.redo());+ expect(result.current.previews).toEqual(moved);+});++it("resets history after submission and does not record a cancelled gesture", () => {+ const initial = [signature];+ const { result } = renderHook(() => useSignaturePreviewHistory(initial));+ act(() => result.current.change([{ ...signature, x: 0.5 }], true));+ act(() => result.current.change(initial));+ expect(result.current.previews).toEqual(initial);+ expect(result.current.canUndo).toBe(false);+ act(() => result.current.change([]));+ act(() => result.current.reset([]));+ act(() => result.current.undo());+ expect(result.current.previews).toEqual([]);+ expect(result.current.canUndo || result.current.canRedo).toBe(false);+});diff --git a/frontend/editor/src/core/hooks/signing/useSignaturePreviewHistory.ts b/frontend/editor/src/core/hooks/signing/useSignaturePreviewHistory.tsnew file mode 100644index 0000000000..47edd91db3--- /dev/null+++ b/frontend/editor/src/core/hooks/signing/useSignaturePreviewHistory.ts@@ -0,0 +1,80 @@+import { useCallback, useReducer } from "react";+import type { SignaturePreview } from "@app/components/viewer/viewerTypes";++interface PreviewHistory {+ past: SignaturePreview[][];+ present: SignaturePreview[];+ committed: SignaturePreview[];+ future: SignaturePreview[][];+}++type Action =+ | { type: "change"; previews: SignaturePreview[]; transient: boolean }+ | { type: "reset"; previews: SignaturePreview[] }+ | { type: "undo" | "redo" };++function initialState(previews: SignaturePreview[]): PreviewHistory {+ return { past: [], present: previews, committed: previews, future: [] };+}++function reduceHistory(state: PreviewHistory, action: Action): PreviewHistory {+ switch (action.type) {+ case "reset":+ return initialState(action.previews);+ case "change":+ if (action.transient) return { ...state, present: action.previews };+ if (action.previews === state.committed)+ return { ...state, present: action.previews };+ return {+ past: [...state.past, state.committed].slice(-100),+ present: action.previews,+ committed: action.previews,+ future: [],+ };+ case "undo": {+ const previous = state.past.at(-1);+ if (!previous) return state;+ return {+ past: state.past.slice(0, -1),+ present: previous,+ committed: previous,+ future: [state.committed, ...state.future],+ };+ }+ case "redo": {+ const next = state.future[0];+ if (!next) return state;+ return {+ past: [...state.past, state.committed],+ present: next,+ committed: next,+ future: state.future.slice(1),+ };+ }+ }+}++/** Keeps up to 100 edits; transient drag updates form one undo step when committed. Reset discards document history. */+export function useSignaturePreviewHistory(initial: SignaturePreview[] = []) {+ const [state, dispatch] = useReducer(reduceHistory, initial, initialState);+ const change = useCallback(+ (previews: SignaturePreview[], transient = false) => {+ dispatch({ type: "change", previews, transient });+ },+ [],+ );+ const reset = useCallback((previews: SignaturePreview[]) => {+ dispatch({ type: "reset", previews });+ }, []);+ const undo = useCallback(() => dispatch({ type: "undo" }), []);+ const redo = useCallback(() => dispatch({ type: "redo" }), []);+ return {+ previews: state.present,+ change,+ reset,+ undo,+ redo,+ canUndo: state.past.length > 0,+ canRedo: state.future.length > 0,+ };+}diff --git a/frontend/editor/src/core/hooks/signing/useSigningActivity.ts b/frontend/editor/src/core/hooks/signing/useSigningActivity.tsnew file mode 100644index 0000000000..5283b555b7--- /dev/null+++ b/frontend/editor/src/core/hooks/signing/useSigningActivity.ts@@ -0,0 +1,27 @@+import { useMemo, useSyncExternalStore } from "react";+import { useAuth } from "@app/auth/UseSession";+import {+ getSigningSeenVersion,+ hasUnseenSigningActivity,+ subscribeSigningSeen,+} from "@app/services/signingSeenStore";+import type { SigningItem, SigningMenuItem } from "@app/utils/signingItems";++/** Shares account-scoped unread indicators between the popover and expanded session table. */+export function useSigningActivity(items: SigningItem[]): SigningMenuItem[] {+ const { user } = useAuth();+ const accountId = user?.id ?? null;+ const version = useSyncExternalStore(+ subscribeSigningSeen,+ getSigningSeenVersion,+ getSigningSeenVersion,+ );+ return useMemo(+ () =>+ items.map((item) => ({+ ...item,+ unread: hasUnseenSigningActivity(accountId, item),+ })),+ [items, accountId, version],+ );+}diff --git a/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.ts b/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.tsindex 86424e5ca8..c719ca9552 100644--- a/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.ts+++ b/frontend/editor/src/core/hooks/signing/useSigningBadgeCount.ts@@ -1,21 +1,24 @@-import { useSyncExternalStore } from "react";+import { useMemo } from "react";+import {+ collectSigningItems,+ type SigningMenuItem,+} from "@app/utils/signingItems";import { useAuth } from "@app/auth/UseSession";import { useGroupSigningState } from "@app/hooks/useGroupSigningEnabled";import { useSigningSessions } from "@app/hooks/signing/useSigningSessions";-import {- getLastSeenSignedCount,- getSigningSeenVersion,- subscribeSigningSeen,-} from "@app/services/signingSeenStore";+import { useSigningActivity } from "@app/hooks/signing/useSigningActivity";/**- * Count that drives the Shared Signing badge: sign requests awaiting the user's- * signature, plus the user's own sessions that gained new signatures since they- * last opened them. 0 when group signing is disabled. Polls in the background+ * Counts unread invitations, participant decisions and completed documents.+ * Zero when group signing is disabled. Polls in the background* while enabled. Unsettled while auth, config or sessions load, or the session* lookup fails; consumers may retain their previous count until it settles.*/-export function useSigningBadgeState(): { count: number; settled: boolean } {+export function useSigningBadgeState(): {+ count: number;+ settled: boolean;+ items: SigningMenuItem[];+} {const { loading: authLoading } = useAuth();const { enabled, settled: availabilitySettled } = useGroupSigningState();const { signRequests, mySessions, settled } = useSigningSessions({@@ -23,26 +26,15 @@ export function useSigningBadgeState(): { count: number; settled: boolean } {autoRefreshInterval: enabled ? 60000 : 0,});- // Re-read the per-session "seen" markers whenever they change.- useSyncExternalStore(- subscribeSigningSeen,- getSigningSeenVersion,- getSigningSeenVersion,+ const sessions = useMemo(+ () => (enabled ? collectSigningItems(signRequests, mySessions) : []),+ [enabled, signRequests, mySessions],);-- const incoming = signRequests.filter(- (request) =>- request.myStatus !== "SIGNED" && request.myStatus !== "DECLINED",- ).length;-- const ownerUpdates = mySessions.filter(- (session) =>- !session.finalized &&- session.signedCount > getLastSeenSignedCount(session.sessionId),- ).length;+ const items = useSigningActivity(sessions);return {- count: enabled ? incoming + ownerUpdates : 0,+ items,+ count: items.filter((item) => item.unread).length,settled: !authLoading && availabilitySettled && (!enabled || settled),};}diff --git a/frontend/editor/src/core/hooks/signing/useSigningSessionController.test.tsx b/frontend/editor/src/core/hooks/signing/useSigningSessionController.test.tsxnew file mode 100644index 0000000000..1cfe8323eb--- /dev/null+++ b/frontend/editor/src/core/hooks/signing/useSigningSessionController.test.tsx@@ -0,0 +1,610 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import { useSigningSessionController } from "@app/hooks/signing/useSigningSessionController";+import type {+ SignRequestSummary,+ SessionDetail,+ SessionSummary,+ SigningParticipantPreview,+} from "@app/types/signingSession";++import { hasUnseenSigningActivity } from "@app/services/signingSeenStore";+import { expectConsole } from "@app/tests/failOnConsole";++const mocks = vi.hoisted(() => ({+ get: vi.fn(),+ post: vi.fn(),+ setOverlay: vi.fn(),+ refetch: vi.fn(),+ alert: vi.fn(),+ accountId: "alice" as string | number,+ signRequests: [] as SignRequestSummary[],+ mySessions: [] as SessionSummary[],+}));+vi.mock("@app/auth/UseSession", () => ({+ useAuth: () => ({ user: { id: mocks.accountId } }),+}));+vi.mock("@app/services/apiClient", () => ({+ default: { get: mocks.get, post: mocks.post },+}));+vi.mock("@app/components/toast", () => ({ alert: mocks.alert }));+vi.mock("@app/services/fileStorage", () => ({ fileStorage: {} }));+vi.mock("@app/contexts/FileContext", () => ({+ useFileActions: () => ({ actions: {} }),+}));+vi.mock("@app/hooks/tools/shared/useViewScopedFiles", () => ({+ useViewScopedFiles: () => [],+}));+vi.mock("@app/contexts/SigningOverlayContext", () => ({+ useSigningOverlay: () => ({ setOverlay: mocks.setOverlay }),+}));+vi.mock("@app/hooks/signing/useSigningSessions", () => ({+ useSigningSessions: () => ({+ signRequests: mocks.signRequests,+ mySessions: mocks.mySessions,+ loading: false,+ refetch: mocks.refetch,+ }),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const request: SignRequestSummary = {+ sessionId: "one",+ documentName: "Test.pdf",+ ownerUsername: "Alice",+ createdAt: "2026-09-24",+ dueDate: "",+ myStatus: "PENDING",+};++beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ mocks.accountId = "alice";+ mocks.signRequests = [];+ mocks.mySessions = [];+});++it("acknowledges a final document only after the participant can open it", async () => {+ const completed = {+ ...request,+ myStatus: "SIGNED" as const,+ finalized: true,+ closed: true,+ };+ mocks.get.mockImplementation(async (url: string) => ({+ data: url.endsWith("/document") ? new Blob(["pdf"]) : completed,+ }));+ const { result } = renderHook(() => useSigningSessionController(true));+ expect(+ hasUnseenSigningActivity("alice", { ...completed, kind: "request" }),+ ).toBe(true);+ await act(async () => {+ await result.current.openSignRequest(completed);+ });+ expect(result.current.requestData?.canSign).toBe(false);+ expect(+ hasUnseenSigningActivity("alice", { ...completed, kind: "request" }),+ ).toBe(false);+});++it("acknowledges owner activity visible in their signing preview without reading unseen decisions", async () => {+ const peer = {+ id: 2,+ status: "SIGNED" as const,+ lastUpdated: "2026-10-01T10:00:00",+ };+ const ownerSession: SessionSummary = {+ ...request,+ participantCount: 3,+ signedCount: 1,+ finalized: false,+ participants: [peer],+ };+ mocks.mySessions = [ownerSession];+ let preview: SigningParticipantPreview[] = [{ ...peer, name: "Bob" }];+ mocks.get.mockImplementation(async (url: string) => ({+ data: url.endsWith("/document")+ ? new Blob(["pdf"])+ : { ...request, canSign: true, participants: preview },+ }));+ const { result, rerender } = renderHook(() =>+ useSigningSessionController(true),+ );+ await act(async () => {+ await result.current.openSignRequest(request);+ });+ expect(+ hasUnseenSigningActivity("alice", {+ ...ownerSession,+ kind: "session",+ ownRequest: request,+ }),+ ).toBe(false);++ const decline = {+ id: 3,+ status: "DECLINED" as const,+ lastUpdated: "2026-10-01T11:00:00",+ };+ const changed = { ...ownerSession, participants: [peer, decline] };+ mocks.mySessions = [changed];+ rerender();+ await act(async () => {+ await result.current.requestData!.onRefresh();+ });+ expect(+ hasUnseenSigningActivity("alice", { ...changed, kind: "session" }),+ ).toBe(true);+ preview = [...preview, { ...decline, name: "Carol" }];+ await act(async () => {+ await result.current.requestData!.onRefresh();+ });+ expect(+ hasUnseenSigningActivity("alice", { ...changed, kind: "session" }),+ ).toBe(false);+});++it("keeps a submitted owner signature read when the list catches up after the preview", async () => {+ const participant = {+ id: 1,+ name: "Alice",+ status: "PENDING" as const,+ lastUpdated: "2026-10-01T10:00:00",+ };+ const ownerSession: SessionSummary = {+ ...request,+ participantCount: 1,+ signedCount: 0,+ finalized: false,+ participants: [participant],+ };+ mocks.mySessions = [ownerSession];+ let signed = false;+ mocks.post.mockImplementation(async () => {+ signed = true;+ });+ mocks.get.mockImplementation(async (url: string) => ({+ data: url.endsWith("/document")+ ? new Blob(["pdf"])+ : {+ ...request,+ canSign: !signed,+ myStatus: signed ? "SIGNED" : "PENDING",+ participants: [+ { ...participant, status: signed ? "SIGNED" : "PENDING" },+ ],+ },+ }));+ const { result, rerender } = renderHook(() =>+ useSigningSessionController(true),+ );+ await act(async () => {+ await result.current.openSignRequest(request);+ });+ await act(async () => {+ await result.current.requestData!.onSign(new FormData());+ });+ const updatedSession: SessionSummary = {+ ...ownerSession,+ signedCount: 1,+ participants: [+ { ...participant, status: "SIGNED", lastUpdated: "2026-10-01T11:00:00" },+ ],+ };+ mocks.mySessions = [updatedSession];+ rerender();+ expect(+ hasUnseenSigningActivity("alice", { ...updatedSession, kind: "session" }),+ ).toBe(false);++ act(() => result.current.backToList());+ const unseenDecision: SessionSummary = {+ ...updatedSession,+ participants: [+ ...updatedSession.participants!,+ { id: 2, status: "DECLINED", lastUpdated: "2026-10-01T12:00:00" },+ ],+ };+ mocks.mySessions = [unseenDecision];+ rerender();+ expect(+ hasUnseenSigningActivity("alice", { ...unseenDecision, kind: "session" }),+ ).toBe(true);+});++it.each(["1", 1])(+ "lets an owner with account ID %s open their signing request and return to management after submitting",+ async (accountId) => {+ mocks.accountId = accountId;+ const session: SessionDetail = {+ ...request,+ ownerEmail: "",+ message: "",+ updatedAt: request.createdAt,+ finalized: false,+ participants: [+ {+ id: 10,+ userId: 1,+ name: "Alice",+ email: "Alice",+ status: "PENDING",+ lastUpdated: request.createdAt,+ },+ ],+ };+ const summary = { ...session, participantCount: 1, signedCount: 0 };+ mocks.signRequests = [request];+ mocks.mySessions = [summary];+ mocks.get.mockImplementation(async (url: string) => ({+ data:+ url.endsWith("/pdf") || url.endsWith("/document")+ ? new Blob(["pdf"])+ : url.includes("/sign-requests/")+ ? {+ ...request,+ myStatus: session.participants[0].status,+ canSign: session.participants[0].status !== "SIGNED",+ }+ : session,+ }));+ mocks.post.mockImplementation(async () => {+ session.participants[0].status = "SIGNED";+ mocks.signRequests = [{ ...request, myStatus: "SIGNED" }];+ });+ const { result } = renderHook(() => useSigningSessionController(true));+ await act(async () => {+ await result.current.openSession(summary);+ });+ expect(result.current.detailData?.onOpenMyRequest).toBeTypeOf("function");+ await act(async () => {+ result.current.detailData!.onOpenMyRequest!();+ });+ expect(result.current.view).toBe("request");+ expect(result.current.requestData?.canSign).toBe(true);+ expect(result.current.requestData?.onManageSession).toBeTypeOf("function");+ await act(async () => {+ await result.current.requestData!.onSign(new FormData());+ });+ await act(async () => {+ result.current.requestData!.onManageSession!();+ });+ expect(result.current.view).toBe("detail");+ expect(result.current.detailData?.session.participants[0].status).toBe(+ "SIGNED",+ );+ expect(result.current.detailData?.onOpenMyRequest).toBeUndefined();+ },+);++it("does not reopen a request after the user returns to the session list", async () => {+ let complete!: (value: { data: Blob }) => void;+ mocks.get.mockImplementation((url: string) =>+ url.endsWith("/document")+ ? new Promise((resolve) => {+ complete = resolve;+ })+ : Promise.resolve({ data: { ...request, canSign: true } }),+ );+ const { result } = renderHook(() => useSigningSessionController(true));+ let opening!: Promise<void>;+ act(() => {+ opening = result.current.openSignRequest(request);+ });+ act(() => result.current.backToList());+ await act(async () => {+ complete({ data: new Blob(["pdf"]) });+ await opening;+ });+ expect(result.current.view).toBe("list");+ expect(result.current.requestData).toBeNull();+ expect(+ hasUnseenSigningActivity("alice", { ...request, kind: "request" }),+ ).toBe(true);+ expect(mocks.setOverlay).toHaveBeenLastCalledWith(null);+});++it("releases pending document loads when the workspace unmounts", async () => {+ let complete!: (value: { data: Blob }) => void;+ mocks.get.mockImplementation((url: string) =>+ url.endsWith("/document")+ ? new Promise((resolve) => {+ complete = resolve;+ })+ : Promise.resolve({ data: { ...request, canSign: true } }),+ );+ const { result, unmount } = renderHook(() =>+ useSigningSessionController(true),+ );+ const opening = result.current.openSignRequest(request);+ unmount();+ await act(async () => {+ complete({ data: new Blob(["pdf"]) });+ await opening;+ });+ expect(mocks.setOverlay).toHaveBeenCalledTimes(1);+ expect(mocks.setOverlay).toHaveBeenLastCalledWith(null);+});++it("acknowledges a request only after its detail and PDF have opened", async () => {+ mocks.get.mockImplementation((url: string) =>+ Promise.resolve({+ data: url.endsWith("/document")+ ? new Blob(["pdf"])+ : { ...request, canSign: true },+ }),+ );+ const { result } = renderHook(() => useSigningSessionController(true));+ expect(+ hasUnseenSigningActivity("alice", { ...request, kind: "request" }),+ ).toBe(true);+ await act(async () => {+ await result.current.openSignRequest(request);+ });+ expect(result.current.view).toBe("request");+ expect(result.current.requestData?.onManageSession).toBeUndefined();+ expect(+ hasUnseenSigningActivity("alice", { ...request, kind: "request" }),+ ).toBe(false);+});++it("acknowledges an expired invitation even when the empty document error arrives first", async () => {+ expectConsole.error(/Failed to load sign request/);+ let failDetail!: (reason: unknown) => void;+ mocks.get.mockImplementation((url: string) =>+ url.endsWith("/document")+ ? Promise.reject({+ isAxiosError: true,+ response: { status: 403, data: new Blob() },+ })+ : new Promise((_, reject) => {+ failDetail = reject;+ }),+ );+ const { result } = renderHook(() => useSigningSessionController(true));+ let opening!: Promise<void>;+ act(() => {+ opening = result.current.openSignRequest(request);+ });+ await act(async () => {+ failDetail({+ isAxiosError: true,+ response: {+ status: 403,+ data: 'Access denied or sign request not found: 403 FORBIDDEN "Participant access expired"',+ },+ });+ await opening;+ });+ expect(result.current.view).toBe("list");+ expect(result.current.requestData).toBeNull();+ expect(+ hasUnseenSigningActivity("alice", { ...request, kind: "request" }),+ ).toBe(false);+ expect(mocks.alert).toHaveBeenLastCalledWith(+ expect.objectContaining({ body: "signRequest.accessExpired" }),+ );+ expect(mocks.refetch).toHaveBeenCalledOnce();+ expect(mocks.get).toHaveBeenCalledWith(expect.stringContaining("/document"), {+ responseType: "blob",+ suppressErrorToast: true,+ });+});++it.each([+ { isAxiosError: true, response: { status: 500, data: "Server unavailable" } },+ { isAxiosError: true, response: { status: 403, data: "Access denied" } },+ new Error("Network unavailable"),+])(+ "retains unread activity when loading fails without confirmed expiry: %j",+ async (error) => {+ expectConsole.error(/Failed to load sign request/);+ mocks.get.mockRejectedValue(error);+ const { result } = renderHook(() => useSigningSessionController(true));+ await act(async () => {+ await result.current.openSignRequest(request);+ });+ expect(+ hasUnseenSigningActivity("alice", { ...request, kind: "request" }),+ ).toBe(true);+ expect(mocks.alert).toHaveBeenLastCalledWith(+ expect.objectContaining({ body: "signRequest.fetchFailed" }),+ );+ },+);++it("does not acknowledge a late expiry response after leaving the request", async () => {+ let failDetail!: (reason: unknown) => void;+ mocks.get.mockImplementation((url: string) =>+ url.endsWith("/document")+ ? Promise.resolve({ data: new Blob(["pdf"]) })+ : new Promise((_, reject) => {+ failDetail = reject;+ }),+ );+ const { result } = renderHook(() => useSigningSessionController(true));+ let opening!: Promise<void>;+ act(() => {+ opening = result.current.openSignRequest(request);+ });+ act(() => result.current.backToList());+ await act(async () => {+ failDetail({+ isAxiosError: true,+ response: { status: 403, data: "Participant access expired" },+ });+ await opening;+ });+ expect(+ hasUnseenSigningActivity("alice", { ...request, kind: "request" }),+ ).toBe(true);+ expect(mocks.alert).not.toHaveBeenCalled();+});++it("does not acknowledge participant updates from a refresh after leaving the session", async () => {+ const detail: SessionDetail = {+ sessionId: "owner",+ documentName: "Test.pdf",+ ownerEmail: "[email protected]",+ message: "",+ dueDate: "",+ createdAt: "2026-10-01",+ updatedAt: "2026-10-01",+ finalized: false,+ participants: [+ {+ id: 1,+ userId: 2,+ email: "[email protected]",+ name: "Bob",+ status: "PENDING",+ lastUpdated: "2026-10-01",+ },+ ],+ };+ const summary: SessionSummary = {+ ...detail,+ participantCount: 1,+ signedCount: 0,+ };+ mocks.get.mockImplementation((url: string) =>+ Promise.resolve({+ data: url.endsWith("/pdf") ? new Blob(["pdf"]) : detail,+ }),+ );+ const { result } = renderHook(() => useSigningSessionController(true));+ await act(async () => {+ await result.current.openSession(summary);+ });+ let finish!: (value: { data: SessionDetail }) => void;+ mocks.get.mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ let refreshing!: Promise<void>;+ act(() => {+ refreshing = result.current.detailData!.onRefresh();+ });+ act(() => result.current.backToList());+ const changed: SessionDetail = {+ ...detail,+ participants: [+ {+ ...detail.participants[0],+ status: "DECLINED",+ lastUpdated: "2026-10-02",+ },+ ],+ };+ await act(async () => {+ finish({ data: changed });+ await refreshing;+ });+ expect(result.current.view).toBe("list");+ expect(+ hasUnseenSigningActivity("alice", {+ ...summary,+ participants: changed.participants,+ kind: "session",+ }),+ ).toBe(true);+});++it("keeps the participant in the preview after signing and refreshes submitted marks", async () => {+ let signed = false;+ const peer = { id: 2, name: "Bob", status: "SIGNED", wetSignatures: [] };+ mocks.post.mockImplementation(async () => {+ signed = true;+ });+ mocks.get.mockImplementation(async (url: string) => ({+ data: url.endsWith("/document")+ ? new Blob(["original"])+ : {+ ...request,+ myStatus: signed ? "SIGNED" : "VIEWED",+ canSign: !signed,+ participants: [peer],+ },+ }));+ const { result } = renderHook(() => useSigningSessionController(true));+ await act(async () => {+ await result.current.openSignRequest(request);+ });+ const original = result.current.requestData!.pdfFile;+ await act(async () => {+ await result.current.requestData!.onSign(new FormData());+ });+ expect(result.current.view).toBe("request");+ expect(result.current.requestData?.canSign).toBe(false);+ expect(result.current.requestData?.signRequest.myStatus).toBe("SIGNED");+ expect(result.current.requestData?.signRequest.participants).toEqual([peer]);+ expect(result.current.requestData?.pdfFile).toBe(original);+});++it("refreshes participant progress without replacing the document or draft, then loads the finalized PDF", async () => {+ let finalized = false;+ let participants: { id: number; name: string; status: string }[] = [];+ mocks.get.mockImplementation(async (url: string) => ({+ data: url.endsWith("/document")+ ? new Blob([finalized ? "final" : "original"])+ : { ...request, finalized, canSign: !finalized, participants },+ }));+ const { result } = renderHook(() => useSigningSessionController(true));+ await act(async () => {+ await result.current.openSignRequest(request);+ });+ const original = result.current.requestData!.pdfFile;+ participants = [{ id: 2, name: "Bob", status: "SIGNED" }];+ mocks.setOverlay.mockClear();+ await act(async () => {+ await result.current.requestData!.onRefresh();+ });+ expect(result.current.requestData?.signRequest.participants).toEqual(+ participants,+ );+ expect(result.current.requestData?.pdfFile).toBe(original);+ expect(mocks.setOverlay).not.toHaveBeenCalled();+ finalized = true;+ await act(async () => {+ await result.current.requestData!.onRefresh();+ });+ expect(result.current.requestData?.canSign).toBe(false);+ expect(result.current.requestData?.signRequest.finalized).toBe(true);+ expect(result.current.requestData?.pdfFile).not.toBe(original);+ expect(result.current.requestData?.pdfFile.size).toBe(5);+});++it("discards a participant refresh that completes after leaving the request", async () => {+ mocks.get.mockImplementation(async (url: string) => ({+ data: url.endsWith("/document")+ ? new Blob(["original"])+ : { ...request, canSign: true },+ }));+ const { result } = renderHook(() => useSigningSessionController(true));+ await act(async () => {+ await result.current.openSignRequest(request);+ });+ let resolve!: (value: unknown) => void;+ mocks.get.mockImplementation(+ () =>+ new Promise((done) => {+ resolve = done;+ }),+ );+ let refresh!: Promise<void>;+ act(() => {+ refresh = result.current.requestData!.onRefresh();+ });+ act(() => result.current.backToList());+ await act(async () => {+ resolve({ data: { ...request, myStatus: "SIGNED" } });+ await refresh;+ });+ expect(result.current.requestData).toBeNull();+ expect(result.current.view).toBe("list");+ expect(mocks.setOverlay).toHaveBeenLastCalledWith(null);+});diff --git a/frontend/editor/src/core/hooks/signing/useSigningSessionController.ts b/frontend/editor/src/core/hooks/signing/useSigningSessionController.tsindex 81e07e60b5..1293d71c9f 100644--- a/frontend/editor/src/core/hooks/signing/useSigningSessionController.ts+++ b/frontend/editor/src/core/hooks/signing/useSigningSessionController.ts@@ -11,17 +11,18 @@ import {SessionSummary,SessionDetail,} from "@app/types/signingSession";-import type { SignaturePreview } from "@app/components/viewer/viewerTypes";-import { getFileColor } from "@app/components/pageEditor/fileColors";-import { useNavigationActions } from "@app/contexts/NavigationContext";+import { getSubmittedSignaturePreviews } from "@app/utils/signingPreviews";+import { needsSignature } from "@app/utils/signingItems";+import type { StirlingFile } from "@app/types/fileContext";import { useFileActions } from "@app/contexts/FileContext";import { useSigningOverlay } from "@app/contexts/SigningOverlayContext";import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";import { useSigningSessions } from "@app/hooks/signing/useSigningSessions";-import { markSessionSeen } from "@app/services/signingSeenStore";+import { markSigningItemSeen } from "@app/services/signingSeenStore";+import { useAuth } from "@app/auth/UseSession";import type { SignatureSettings } from "@app/components/tools/certSign/SignatureSettingsInput";-/** Which Shared Signing screen the sidebar tool is currently showing. */+/** The session workflow currently shown in the workspace. */export type SigningView = "list" | "detail" | "request";/** The owner's appearance settings as session workflowMetadata; unset keys are omitted, not null. */@@ -40,7 +41,7 @@ export function buildWorkflowMetadata();}-/** Data the session-detail sidebar panel needs to render and act. */+/** Data the session-detail panel needs to render and act. */export interface SigningDetailData {session: SessionDetail;pdfFile: File | null;@@ -54,64 +55,91 @@ export interface SigningDetailData {onDelete: () => Promise<void>;onBack: () => void;onRefresh: () => Promise<void>;+ onOpenMyRequest?: () => void;}-/** Data the sign-request sidebar panel needs to render and act. */+/** Data the sign-request panel needs to render and act. */export interface SigningRequestData {signRequest: SignRequestDetail;pdfFile: File;onSign: (certificateData: FormData) => Promise<void>;onDecline: () => Promise<void>;+ onRefresh: () => Promise<void>;onBack: () => void;+ onOpenFiles?: () => void;+ onManageSession?: () => void;canSign: boolean;}-function countSignedParticipants(session: SessionDetail): number {- return session.participants.filter((p) => p.status === "SIGNED").length;+function acknowledgeSession(+ accountId: string | null,+ session: SessionDetail,+ ownRequest?: SignRequestSummary,+): void {+ markSigningItemSeen(accountId, {+ ...session,+ kind: "session",+ ownRequest,+ participantCount: session.participants.length,+ signedCount: session.participants.filter((p) => p.status === "SIGNED")+ .length,+ });}-// Read-only overlay previews for every participant's already-placed wet-// signatures, coloured per participant (matches the participant list dots).-function computeWetSignaturePreviews(- session: SessionDetail,-): SignaturePreview[] {- const previews: SignaturePreview[] = [];- session.participants.forEach((participant, participantIndex) => {- if (participant.wetSignatures && participant.wetSignatures.length > 0) {- const color = getFileColor(participantIndex);- const participantName = participant.name || participant.email;- participant.wetSignatures.forEach((wetSig, sigIndex) => {- previews.push({- id: `participant-${participant.userId}-sig-${sigIndex}`,- pageIndex: wetSig.page,- x: wetSig.x,- y: wetSig.y,- width: wetSig.width,- height: wetSig.height,- signatureData: wetSig.data,- signatureType: "image" as const,- color,- participantName,- });- });- }+function acknowledgeRequest(+ accountId: string | null,+ request: SignRequestDetail,+ ownedSessions: SessionSummary[],+): void {+ markSigningItemSeen(accountId, { ...request, kind: "request" });+ const session = ownedSessions.find(+ (owned) => owned.sessionId === request.sessionId,+ );+ if (!session || !request.participants) return;+ // Polls can race: acknowledge only decisions actually present in the opened preview.+ const visibleParticipants = session.participants?.filter((participant) =>+ request.participants?.some(+ (visible) =>+ visible.id === participant.id && visible.status === participant.status,+ ),+ );+ markSigningItemSeen(accountId, {+ ...session,+ kind: "session",+ participants: visibleParticipants,+ signedCount: request.participants.filter(+ (participant) => participant.status === "SIGNED",+ ).length,});- return previews;}-/** Owns Shared Signing state: data fetch, session creation, and opening a request/session into the sidebar tool (driving the viewer overlay). */-export function useSigningSessionController(enabled: boolean) {+function isParticipantAccessExpired(error: unknown): boolean {+ return (+ isAxiosError(error) &&+ error.response?.status === 403 &&+ typeof error.response.data === "string" &&+ error.response.data.includes("Participant access expired")+ );+}++/** Fetches sessions, creates requests and supplies documents and overlays to the signing workspace. */+export function useSigningSessionController(+ enabled: boolean,+ onOpenFiles?: () => void,+) {const { t } = useTranslation();+ const { user } = useAuth();+ const accountId = user?.id ?? null;const { signRequests, mySessions, loading, refetch } = useSigningSessions({enabled,autoRefreshInterval: enabled ? 15000 : 0,});+ const ownedSessionsRef = useRef(mySessions);const { actions: fileActions } = useFileActions();// In viewer mode this is the single displayed file; matches how tools scope// their input (see useBaseTool / useViewScopedFiles). Creating a session// requires exactly one file.const selectedFiles = useViewScopedFiles();- const { actions: navigationActions } = useNavigationActions();const { setOverlay } = useSigningOverlay();const [creating, setCreating] = useState(false);@@ -120,41 +148,124 @@ export function useSigningSessionController(enabled: boolean) {const [requestData, setRequestData] = useState<SigningRequestData | null>(null,);+ useEffect(() => {+ ownedSessionsRef.current = mySessions;+ if (view === "request" && requestData) {+ acknowledgeRequest(accountId, requestData.signRequest, mySessions);+ }+ }, [accountId, mySessions, requestData, view]);// The session currently shown in the detail view. A refresh checks this at// resolve time so a request dispatched before navigation is discarded rather// than painting its data onto whatever is now on screen.const openDetailSessionIdRef = useRef<string | null>(null);+ const openVersion = useRef(0);+ const requestRefreshVersion = useRef(0);+ const openRequestSessionIdRef = useRef<string | null>(null);- // Leaving the tool (panel unmounts) must not leave the signing document and- // overlays lingering on the shared viewer.+ // Leaving the workspace releases its document and signature overlays.useEffect(() => {- return () => setOverlay(null);+ return () => {+ openVersion.current += 1;+ setOverlay(null);+ };}, [setOverlay]);const backToList = useCallback(() => {+ openVersion.current += 1;openDetailSessionIdRef.current = null;+ openRequestSessionIdRef.current = null;setOverlay(null);setDetailData(null);setRequestData(null);setView("list");}, [setOverlay]);- // --- Action handlers (invoked from the sidebar panels) ----const handleSign = async (sessionId: string, certificateData: FormData) => {+ const version = openVersion.current;+ requestRefreshVersion.current += 1;await apiClient.post(`/api/v1/security/cert-sign/sign-requests/${sessionId}/sign`,certificateData,+ { suppressErrorToast: true },);alert({alertType: "success",title: t("success"),- body: t("signRequest.signed", "Document signed successfully"),+ body: t("signMenu.submitted", "Submitted · awaiting finalization"),expandable: false,durationMs: 2500,});- backToList();- await refetch();+ if (version === openVersion.current) {+ setRequestData((previous) =>+ previous+ ? {+ ...previous,+ canSign: false,+ signRequest: {+ ...previous.signRequest,+ myStatus: "SIGNED",+ canSign: false,+ },+ }+ : previous,+ );+ await refreshSignRequest(sessionId);+ }+ void refetch();+ };++ const refreshSignRequest = async (sessionId: string) => {+ const version = openVersion.current;+ const refreshVersion = ++requestRefreshVersion.current;+ const isCurrent = () =>+ version === openVersion.current &&+ refreshVersion === requestRefreshVersion.current &&+ openRequestSessionIdRef.current === sessionId;+ try {+ const { data: detail } = await apiClient.get<SignRequestDetail>(+ `/api/v1/security/cert-sign/sign-requests/${sessionId}`,+ { suppressErrorToast: true },+ );+ if (!isCurrent()) return;+ let finalFile: File | undefined;+ if (detail.finalized) {+ const response = await apiClient.get(+ `/api/v1/security/cert-sign/sign-requests/${sessionId}/document`,+ { responseType: "blob", suppressErrorToast: true },+ );+ finalFile = new File([response.data], detail.documentName, {+ type: "application/pdf",+ });+ }+ if (!isCurrent()) return;+ setRequestData((previous) =>+ previous+ ? {+ ...previous,+ signRequest: detail,+ pdfFile: finalFile ?? previous.pdfFile,+ canSign: detail.canSign === true && !detail.finalized,+ }+ : previous,+ );+ acknowledgeRequest(accountId, detail, ownedSessionsRef.current);+ } catch (error) {+ if (!isCurrent()) return;+ if (+ isAxiosError(error) &&+ [403, 404].includes(error.response?.status ?? 0)+ ) {+ backToList();+ void refetch();+ }+ alert({+ alertType: "error",+ title: t("common.error"),+ body: t("signRequest.fetchFailed", "Failed to load sign request"),+ expandable: false,+ durationMs: 3000,+ });+ }};const handleDecline = async (sessionId: string) => {@@ -192,6 +303,7 @@ export function useSigningSessionController(enabled: boolean) {durationMs: 2500,});backToList();+ onOpenFiles?.();await refetch();};@@ -217,6 +329,7 @@ export function useSigningSessionController(enabled: boolean) {durationMs: 2500,});backToList();+ onOpenFiles?.();};const handleRefreshSession = async (sessionId: string) => {@@ -224,15 +337,19 @@ export function useSigningSessionController(enabled: boolean) {`/api/v1/security/cert-sign/sessions/${sessionId}`,);const session = response.data;- markSessionSeen(session.sessionId, countSignedParticipants(session));// Discard a refresh that resolves after the user navigated away, so we// never paint this session's data onto another document.if (openDetailSessionIdRef.current !== session.sessionId) return;+ acknowledgeSession(+ accountId,+ session,+ signRequests.find((request) => request.sessionId === sessionId),+ );setDetailData((prev) => (prev ? { ...prev, session } : prev));// Keep the read-only overlay in sync as participants sign.setOverlay((prev) =>prev- ? { ...prev, signaturePreviews: computeWetSignaturePreviews(session) }+ ? { ...prev, signaturePreviews: getSubmittedSignaturePreviews(session) }: prev,);};@@ -252,6 +369,7 @@ export function useSigningSessionController(enabled: boolean) {requests,);await handleRefreshSession(sessionId);+ await refetch();};const handleRemoveParticipant = async (@@ -277,45 +395,67 @@ export function useSigningSessionController(enabled: boolean) {await refetch();};- // --- Open into the sidebar detail/request views ----const openSignRequest = async (request: SignRequestSummary) => {+ const version = ++openVersion.current;try {- const [detailResponse, pdfResponse] = await Promise.all([+ const [detailResult, pdfResult] = await Promise.allSettled([apiClient.get<SignRequestDetail>(`/api/v1/security/cert-sign/sign-requests/${request.sessionId}`,+ { suppressErrorToast: true },),apiClient.get(`/api/v1/security/cert-sign/sign-requests/${request.sessionId}/document`,- { responseType: "blob" },+ { responseType: "blob", suppressErrorToast: true },),]);+ if (version !== openVersion.current) return;+ // Document errors omit the expiry reason; prefer the detail error regardless of response order.+ if (detailResult.status === "rejected") throw detailResult.reason;+ if (pdfResult.status === "rejected") throw pdfResult.reason;+ const detailResponse = detailResult.value;+ const pdfResponse = pdfResult.value;const pdfFile = new File([pdfResponse.data],detailResponse.data.documentName,{ type: "application/pdf" },);const canSign =- detailResponse.data.myStatus === "PENDING" ||- detailResponse.data.myStatus === "NOTIFIED" ||- detailResponse.data.myStatus === "VIEWED";+ detailResponse.data.canSign === true && !detailResponse.data.finalized;// Leaving the detail view: stop any in-flight detail refresh from applying.openDetailSessionIdRef.current = null;+ openRequestSessionIdRef.current = request.sessionId;// Seed the viewer with the document immediately; the request panel enriches// the overlay with interactive placement props once it mounts.- setOverlay({ file: pdfFile });+ setOverlay({+ file: pdfFile,+ readOnlySignaturePreviews: getSubmittedSignaturePreviews(+ detailResponse.data,+ ),+ });setRequestData({signRequest: detailResponse.data,+ onOpenFiles,pdfFile,onSign: (certData: FormData) => handleSign(request.sessionId, certData),onDecline: () => handleDecline(request.sessionId),+ onRefresh: () => refreshSignRequest(request.sessionId),onBack: backToList,canSign,});setView("request");- navigationActions.setWorkbench("viewer");+ acknowledgeRequest(+ accountId,+ detailResponse.data,+ ownedSessionsRef.current,+ );} catch (error) {+ if (version !== openVersion.current) return;+ const accessExpired = isParticipantAccessExpired(error);+ if (accessExpired) {+ markSigningItemSeen(accountId, { ...request, kind: "request" });+ void refetch();+ }console.error("Failed to load sign request:",error instanceof Error ? error.message : error,@@ -323,7 +463,12 @@ export function useSigningSessionController(enabled: boolean) {alert({alertType: "error",title: t("common.error"),- body: t("signRequest.fetchFailed", "Failed to load sign request"),+ body: accessExpired+ ? t(+ "signRequest.accessExpired",+ "Your access to this signing request has expired. Ask the sender for a new request.",+ )+ : t("signRequest.fetchFailed", "Failed to load sign request"),expandable: false,durationMs: 3000,});@@ -331,15 +476,11 @@ export function useSigningSessionController(enabled: boolean) {};const openSession = async (session: SessionSummary) => {+ const version = ++openVersion.current;try {const detailResponse = await apiClient.get<SessionDetail>(`/api/v1/security/cert-sign/sessions/${session.sessionId}`,);- // Owner is now viewing this session — clear its "new signatures" badge.- markSessionSeen(- session.sessionId,- countSignedParticipants(detailResponse.data),- );let pdfFile: File | null = null;if (detailResponse.data.finalized) {try {@@ -351,6 +492,7 @@ export function useSigningSessionController(enabled: boolean) {type: "application/pdf",});} catch (pdfError) {+ if (version !== openVersion.current) return;if (isAxiosError(pdfError) && pdfError.response?.status === 404) {alert({alertType: "warning",@@ -380,10 +522,17 @@ export function useSigningSessionController(enabled: boolean) {}}+ if (version !== openVersion.current) return;+ acknowledgeSession(+ accountId,+ detailResponse.data,+ signRequests.find((request) => request.sessionId === session.sessionId),+ );openDetailSessionIdRef.current = session.sessionId;+ openRequestSessionIdRef.current = null;setOverlay({file: pdfFile,- signaturePreviews: computeWetSignaturePreviews(detailResponse.data),+ signaturePreviews: getSubmittedSignaturePreviews(detailResponse.data),signaturePreviewsReadOnly: true,});setDetailData({@@ -402,8 +551,8 @@ export function useSigningSessionController(enabled: boolean) {onRefresh: () => handleRefreshSession(session.sessionId),});setView("detail");- navigationActions.setWorkbench("viewer");} catch (error) {+ if (version !== openVersion.current) return;console.error("Failed to load session:",error instanceof Error ? error.message : error,@@ -421,19 +570,19 @@ export function useSigningSessionController(enabled: boolean) {}};- // --- Create a new signing request from the currently selected file ----const createSession = async (signatureSettings: SignatureSettings,selectedUserIds: number[],dueDate: string,+ document?: StirlingFile,): Promise<boolean> => {- if (selectedUserIds.length === 0 || selectedFiles.length !== 1) {+ const selectedFile =+ document ?? (selectedFiles.length === 1 ? selectedFiles[0] : null);+ if (selectedUserIds.length === 0 || !selectedFile) {return false;}setCreating(true);try {- const selectedFile = selectedFiles[0];const stirlingFile = await fileStorage.getStirlingFile(selectedFile.fileId,);@@ -481,6 +630,20 @@ export function useSigningSessionController(enabled: boolean) {}};+ const ownRequest = signRequests.find(+ (request) => request.sessionId === detailData?.session.sessionId,+ );+ const canSignOwnSession =+ !detailData?.session.finalized &&+ detailData?.session.participants.some(+ (participant) =>+ String(participant.userId) === String(accountId) &&+ ["PENDING", "NOTIFIED", "VIEWED"].includes(participant.status),+ );+ const ownedSession = mySessions.find(+ (session) => session.sessionId === requestData?.signRequest.sessionId,+ );+return {signRequests,mySessions,@@ -491,8 +654,25 @@ export function useSigningSessionController(enabled: boolean) {openSignRequest,openSession,view,- detailData,- requestData,+ detailData: detailData+ ? {+ ...detailData,+ onOpenMyRequest:+ canSignOwnSession &&+ ownRequest &&+ needsSignature({ ...ownRequest, kind: "request" })+ ? () => void openSignRequest(ownRequest)+ : undefined,+ }+ : null,+ requestData: requestData+ ? {+ ...requestData,+ onManageSession: ownedSession+ ? () => void openSession(ownedSession)+ : undefined,+ }+ : null,backToList,};}diff --git a/frontend/editor/src/core/pages/HomePage.test.tsx b/frontend/editor/src/core/pages/HomePage.test.tsxnew file mode 100644index 0000000000..1b876b8417--- /dev/null+++ b/frontend/editor/src/core/pages/HomePage.test.tsx@@ -0,0 +1,189 @@+import { useEffect, useState, type ReactNode } from "react";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { MantineProvider } from "@mantine/core";+import { MemoryRouter } from "react-router-dom";+import { beforeEach, expect, it, vi } from "vitest";+import HomePage from "@app/pages/HomePage";++const state = vi.hoisted(() => ({+ mobile: false,+ workbench: "signing",+ mounted: vi.fn(),+ unmounted: vi.fn(),+ actions: {+ viewDerivedFromPathRef: { current: "/shared-sign" },+ setWorkbench: vi.fn(),+ setToolAndWorkbench: vi.fn(),+ },+ workflow: {+ selectedTool: null,+ selectedToolKey: null,+ readerMode: false,+ setReaderMode: vi.fn(),+ setLeftPanelView: vi.fn(),+ handleToolSelect: vi.fn(),+ handleBackToTools: vi.fn(),+ toolAvailability: {},+ customWorkbenchViews: [],+ toolRegistry: {},+ },+}));++vi.mock("@app/hooks/useIsMobile", () => ({+ useIsMobile: () => state.mobile,+ useIsTouch: () => false,+}));+vi.mock("@app/contexts/ToolWorkflowContext", () => ({+ useToolWorkflow: () => state.workflow,+}));+vi.mock("@app/contexts/NavigationContext", () => ({+ useNavigationState: () => ({ workbench: state.workbench }),+ useNavigationActions: () => ({ actions: state.actions }),+ useNavigationGuard: () => ({ requestNavigation: vi.fn() }),+}));+vi.mock("@app/contexts/SidebarContext", () => ({+ useSidebarContext: () => ({ sidebarRefs: {} }),+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config: {} }),+}));+vi.mock("@app/contexts/PreferencesContext", () => ({+ usePreferences: () => ({ preferences: { defaultStartupView: "tools" } }),+}));+vi.mock("@app/contexts/file/fileHooks", () => ({+ useFileContext: () => ({ activeFiles: [] }),+}));+vi.mock("@app/contexts/ViewerContext", () => ({+ useViewer: () => ({+ searchInterfaceActions: {},+ setActiveFileIndex: vi.fn(),+ }),+}));+vi.mock("@app/contexts/TitleBarStripContext", () => ({+ useTitleBarStrip: () => ({ enabled: false }),+}));+vi.mock("@app/contexts/QuickNavHostContext", () => ({+ useQuickNavHost: () => null,+}));+vi.mock("@app/hooks/useDocumentMeta", () => ({ useDocumentMeta: vi.fn() }));+vi.mock("@app/hooks/useBaseUrl", () => ({+ useBaseUrl: () => "http://localhost",+}));+vi.mock("@app/hooks/signing/useOpenSigning", () => ({+ useOpenSigning: vi.fn(),+}));+vi.mock("@app/hooks/useProcessingFolderCreation", () => ({+ useProcessingFolderCreation: () => ({ dialog: null }),+}));+vi.mock("@app/components/policies/usePoliciesEnabled", () => ({+ usePoliciesEnabled: () => false,+}));+vi.mock("@app/components/policies/PolicyAutoRunController", () => ({+ PolicyAutoRunController: () => null,+}));+vi.mock("@app/components/shared/quickNav/QuickNavHostBridge", () => ({+ QuickNavHostBridge: () => null,+}));+vi.mock("@app/components/shared/signing/SignMenu", () => ({+ SignMenu: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@app/components/home/HomePageExtensions", () => ({+ HomePageExtensions: () => null,+}));+vi.mock("@app/components/FileManager", () => ({ default: () => null }));+vi.mock("@app/components/shared/FileSidebar", () => ({ default: () => null }));+vi.mock("@app/components/shared/MobileUploadModal", () => ({+ default: () => null,+}));+vi.mock("@app/components/viewer/readerRail/ReaderRail", () => ({+ ReaderRail: () => null,+}));+vi.mock("@app/components/viewer/readerRail/ReaderSuperSearch", () => ({+ ReaderSuperSearch: () => null,+}));+vi.mock("@app/components/tools/RightSidebar", () => ({+ default: () => <aside aria-label="Tool panel" />,+}));+vi.mock("@app/contexts/FilesPageContext", () => ({+ FilesPageProvider: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("@app/components/layout/Workbench", () => ({+ default: function StatefulWorkbench() {+ const [view, setView] = useState("Signing sessions");+ const [draft, setDraft] = useState("");+ useEffect(() => {+ state.mounted();+ return () => state.unmounted();+ }, []);+ return (+ <main aria-label="Workbench">+ <h1>{view}</h1>+ <button onClick={() => setView("Request signatures")}>+ New request+ </button>+ <input+ aria-label="Draft"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ </main>+ );+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+ state.mobile = false;+ state.workbench = "signing";+ state.actions.viewDerivedFromPathRef.current = "/shared-sign";+});++function Page() {+ return (+ <MemoryRouter initialEntries={["/shared-sign"]}>+ <MantineProvider env="test">+ <HomePage />+ </MantineProvider>+ </MemoryRouter>+ );+}++it.each([false, true])(+ "preserves signing view and draft across repeated breakpoint changes (starts mobile: %s)",+ async (startsMobile) => {+ state.mobile = startsMobile;+ const user = userEvent.setup();+ const { rerender } = render(<Page />);+ await user.click(screen.getByRole("button", { name: "New request" }));+ await user.type(+ screen.getByRole("textbox", { name: "Draft" }),+ "Unsaved request",+ );+ const workbench = screen.getByRole("main", { name: "Workbench" });++ for (const mobile of [!startsMobile, startsMobile, !startsMobile]) {+ state.mobile = mobile;+ rerender(<Page />);+ expect(+ screen.getByRole("heading", { name: "Request signatures" }),+ ).toBeVisible();+ expect(screen.getByRole("textbox", { name: "Draft" })).toHaveValue(+ "Unsaved request",+ );+ expect(screen.getByRole("main", { name: "Workbench" })).toBe(workbench);+ expect(screen.getAllByRole("main", { name: "Workbench" })).toHaveLength(+ 1,+ );+ expect(+ screen.queryByRole("button", { name: "signMenu.title" }) !== null,+ ).toBe(mobile);+ expect(screen.queryByRole("tablist")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("complementary", { name: "Tool panel" }),+ ).not.toBeInTheDocument();+ }+ expect(state.mounted).toHaveBeenCalledTimes(1);+ expect(state.unmounted).not.toHaveBeenCalled();+ },+);diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsxindex 76e808601e..4eb8fdcf32 100644--- a/frontend/editor/src/core/pages/HomePage.tsx+++ b/frontend/editor/src/core/pages/HomePage.tsx@@ -49,6 +49,9 @@ import { PolicyAutoRunController } from "@app/components/policies/PolicyAutoRunCimport { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";+import { useQuickNavHost } from "@app/contexts/QuickNavHostContext";+import { SignMenu } from "@app/components/shared/signing/SignMenu";+import { useOpenSigning } from "@app/hooks/signing/useOpenSigning";import { usePreferences } from "@app/contexts/PreferencesContext";import {getToolDisabledReason,@@ -160,6 +163,9 @@ export default function HomePage() {const { activeFiles } = useFileContext();const navigationState = useNavigationState();const { requestNavigation } = useNavigationGuard();+ const quickNavHost = useQuickNavHost();+ const openSigning = useOpenSigning();+ const [mobileSignOpen, setMobileSignOpen] = useState(false);// From the processor's Reader entry. Ref-guarded: one-shot, and StrictMode double-invokes.const consumedReaderRequest = useRef(false);@@ -192,9 +198,16 @@ export default function HomePage() {}, [readerMode, searchInterfaceActions]);const goToDefaultState = useCallback(() => {+ if (navigationState.workbench === "signing") navigate(EDITOR_BASENAME);handleBackToTools();actions.setWorkbench(getDefaultWorkbenchForFileCount(activeFiles.length));- }, [handleBackToTools, actions, activeFiles.length]);+ }, [+ handleBackToTools,+ actions,+ activeFiles.length,+ navigationState.workbench,+ navigate,+ ]);const { preferences } = usePreferences();const goToStartupView = useCallback(() => {@@ -224,7 +237,12 @@ export default function HomePage() {if (navigationState.workbench !== "myFiles") {actions.setWorkbench("myFiles");}- } else if (navigationState.workbench === "myFiles") {+ } else if (location.pathname === "/shared-sign") {+ actions.setToolAndWorkbench(null, "signing");+ } else if (+ navigationState.workbench === "myFiles" ||+ navigationState.workbench === "signing"+ ) {// A restore is reopening a recorded view onto files still loading. Leave the// path unmarked so the correction runs once those files land.if (isApplyingRestoredView()) return;@@ -356,8 +374,11 @@ export default function HomePage() {isMobile,]);- const hideToolPanel =+ const isWorkspaceHub =navigationState.workbench === "myFiles" ||+ navigationState.workbench === "signing";+ const hideToolPanel =+ isWorkspaceHub ||(customWorkbenchViews.find((v) => v.workbenchId === navigationState.workbench,)?.hideToolPanel ??@@ -367,7 +388,7 @@ export default function HomePage() {const quickNavToolReasons = useMemo(() => {const reasons: QuickNavToolReasons = {};- for (const id of ["automate", "sharedSign"] as const) {+ for (const id of ["automate"] as const) {const tool = toolRegistry[id];if (!tool) continue;const disabledReason = getToolDisabledReason(@@ -438,7 +459,7 @@ export default function HomePage() {// Mobile's bottom bar sets no view of its own, so leaving the library is the path// moving; the reconciliation effect takes the view with it.const leaveMyFiles = useCallback(() => {- if (navigationState.workbench === "myFiles") navigate(EDITOR_BASENAME);+ if (isWorkspaceHub) navigate(EDITOR_BASENAME);}, [navigationState.workbench, navigate]);useEffect(() => {@@ -576,6 +597,105 @@ export default function HomePage() {: baseUrl,});+ const mobileNavigation = (+ <div className="mobile-bottom-bar">+ <SignMenu+ opened={mobileSignOpen}+ onClose={() => setMobileSignOpen(false)}+ reasons={quickNavHost?.toolReasons ?? {}}+ items={quickNavHost?.signingItems ?? []}+ onOpenSigning={openSigning}+ onSelect={(tool) => {+ handleToolSelect(tool);+ setActiveMobileView("tools");+ }}+ >+ <Button+ variant="tertiary"+ className="mobile-bottom-button"+ aria-label={+ quickNavHost?.signingBadge+ ? t(+ "signMenu.triggerUnreadCount",+ "Sign · {{count}} unread sessions",+ { count: quickNavHost.signingBadge },+ )+ : t("signMenu.title", "Sign")+ }+ onClick={() => setMobileSignOpen((open) => !open)}+ >+ <Icon name="pen-tool" size="1.5rem" />+ {quickNavHost && quickNavHost.signingBadge > 0 && (+ <span className="sign-menu__trigger-badge" aria-hidden>+ {quickNavHost.signingBadge}+ </span>+ )}+ <span className="mobile-bottom-button-label">+ {t("signMenu.title", "Sign")}+ </span>+ </Button>+ </SignMenu>+ <Button+ variant="tertiary"+ className="mobile-bottom-button"+ aria-label={t("quickAccess.allTools", "Tools")}+ onClick={() => {+ leaveMyFiles();+ handleBackToTools();+ if (isMobile) {+ setActiveMobileView("tools");+ }+ }}+ >+ <Icon name="layout-grid" size={"1.5rem"} />+ <span className="mobile-bottom-button-label">+ {t("quickAccess.allTools", "Tools")}+ </span>+ </Button>+ {toolAvailability["automate"]?.available !== false && (+ <Button+ variant="tertiary"+ className="mobile-bottom-button"+ aria-label={t("quickAccess.automate", "Automate")}+ onClick={() => {+ leaveMyFiles();+ handleToolSelect("automate");+ if (isMobile) {+ setActiveMobileView("tools");+ }+ }}+ >+ <Icon name="waypoints" size="1.5rem" />+ <span className="mobile-bottom-button-label">+ {t("quickAccess.automate", "Automate")}+ </span>+ </Button>+ )}+ <Button+ variant="tertiary"+ className="mobile-bottom-button"+ aria-label={t("home.mobile.openFiles", "Open files")}+ onClick={() => navigate("/files")}+ >+ <Icon name="folder" size="1.5rem" />+ <span className="mobile-bottom-button-label">+ {t("quickAccess.files", "Files")}+ </span>+ </Button>+ <Button+ variant="tertiary"+ className="mobile-bottom-button"+ aria-label={t("quickAccess.config", "Config")}+ onClick={openSettings}+ >+ <Icon name="settings" size="1.5rem" />+ <span className="mobile-bottom-button-label">+ {t("quickAccess.config", "Config")}+ </span>+ </Button>+ </div>+ );+return (<div className="h-screen overflow-hidden"><HomePageExtensions />@@ -598,15 +718,13 @@ export default function HomePage() {}/><FilesPageProvider>- {isMobile ? (- <div- className="mobile-layout"- data-files-mode={navigationState.workbench === "myFiles"}- >+ {/* Keep signing in the same tree across breakpoints to preserve drafts and placed signatures. */}+ {isMobile && navigationState.workbench !== "signing" ? (+ <div className="mobile-layout" data-files-mode={isWorkspaceHub}>{/* The library brings its own tabs and folder path, so thetools/workspace toggle would only cost it vertical space. Everyother view keeps the toggle. */}- {navigationState.workbench !== "myFiles" && (+ {!isWorkspaceHub && (<div className="mobile-toggle"><div className="mobile-brand"><LogoIcon className="mobile-brand-icon" />@@ -641,7 +759,7 @@ export default function HomePage() {</div></div>)}- {navigationState.workbench === "myFiles" ? (+ {isWorkspaceHub ? (/* /files takes the whole viewport. Skipping the slider keepsthe FileManagerView from being trapped inside a 100vwhorizontal-scroll container (which truncated buttons and@@ -692,79 +810,22 @@ export default function HomePage() {)}</div>)}- <div className="mobile-bottom-bar">- <Button- variant="tertiary"- className="mobile-bottom-button"- aria-label={t("quickAccess.allTools", "Tools")}- onClick={() => {- leaveMyFiles();- handleBackToTools();- if (isMobile) {- setActiveMobileView("tools");- }- }}- >- <Icon name="layout-grid" size={"1.5rem"} />- <span className="mobile-bottom-button-label">- {t("quickAccess.allTools", "Tools")}- </span>- </Button>- {toolAvailability["automate"]?.available !== false && (- <Button- variant="tertiary"- className="mobile-bottom-button"- aria-label={t("quickAccess.automate", "Automate")}- onClick={() => {- leaveMyFiles();- handleToolSelect("automate");- if (isMobile) {- setActiveMobileView("tools");- }- }}- >- <Icon name="waypoints" size="1.5rem" />- <span className="mobile-bottom-button-label">- {t("quickAccess.automate", "Automate")}- </span>- </Button>- )}- <Button- variant="tertiary"- className="mobile-bottom-button"- aria-label={t("home.mobile.openFiles", "Open files")}- onClick={() => navigate("/files")}- >- <Icon name="folder" size="1.5rem" />- <span className="mobile-bottom-button-label">- {t("quickAccess.files", "Files")}- </span>- </Button>- <Button- variant="tertiary"- className="mobile-bottom-button"- aria-label={t("quickAccess.config", "Config")}- onClick={openSettings}- >- <Icon name="settings" size="1.5rem" />- <span className="mobile-bottom-button-label">- {t("quickAccess.config", "Config")}- </span>- </Button>- </div>+ {mobileNavigation}</div>) : (<Group- align="flex-start"+ align={isMobile ? "stretch" : "flex-start"}gap={0}+ wrap="nowrap"h="100%"className="flex-nowrap flex"bg="var(--c-bg)"data-wings={wingsPhase ?? undefined}+ style={{ flexDirection: isMobile ? "column" : "row" }}>{/* Reading leaves the document and nothing beside it, so the wing goesrather than shrinking to a rail. Everywhere else it is fixed open. */}- {wingsMounted && (+ {wingsMounted && navigationState.workbench !== "signing" && (<div className="workspace-frame"><MyFilesAwareFileSidebarref={quickAccessRef}@@ -776,6 +837,7 @@ export default function HomePage() {</div>)}<Workbench />+ {isMobile && mobileNavigation}{/* The reader's rail takes the slot the tool panel holds otherwise: thepanel's controls are the editor's, and reading wants the viewer's.Both render together only while the panel is on its way out. */}diff --git a/frontend/editor/src/core/services/signingSeenStore.test.ts b/frontend/editor/src/core/services/signingSeenStore.test.tsnew file mode 100644index 0000000000..78f6693f4b--- /dev/null+++ b/frontend/editor/src/core/services/signingSeenStore.test.ts@@ -0,0 +1,228 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import {+ hasUnseenSigningActivity,+ markSigningItemSeen,+ subscribeSigningSeen,+} from "@app/services/signingSeenStore";+import { collectSigningItems, type SigningItem } from "@app/utils/signingItems";++const session = {+ kind: "session",+ sessionId: "owned",+ documentName: "Private.pdf",+ createdAt: "2026-10-01",+ participantCount: 2,+ signedCount: 0,+ finalized: false,+ participants: [+ { id: 1, status: "VIEWED", lastUpdated: "2026-10-01T10:00:00" },+ { id: 2, status: "PENDING", lastUpdated: "2026-10-01T10:00:00" },+ ],+} satisfies SigningItem;+const request = {+ kind: "request",+ sessionId: "owned",+ documentName: "Private.pdf",+ createdAt: "2026-10-01",+ ownerUsername: "Owner",+ dueDate: "",+ myStatus: "PENDING",+} satisfies SigningItem;++beforeEach(() => localStorage.clear());+afterEach(() => vi.restoreAllMocks());++it("notifies participants again when their reviewed request is finalized, until the final PDF is viewed", () => {+ const signed: SigningItem = { ...request, myStatus: "SIGNED" };+ markSigningItemSeen("alice", signed);+ const completed = { ...signed, finalized: true, closed: true };+ expect(hasUnseenSigningActivity("alice", completed)).toBe(true);+ expect(hasUnseenSigningActivity(null, completed)).toBe(false);+ expect(+ hasUnseenSigningActivity("alice", { ...completed, accessExpired: true }),+ ).toBe(false);+ expect(+ hasUnseenSigningActivity("alice", { ...completed, myStatus: "DECLINED" }),+ ).toBe(false);+ markSigningItemSeen("alice", completed);+ expect(hasUnseenSigningActivity("alice", completed)).toBe(false);+ markSigningItemSeen("alice", signed);+ expect(hasUnseenSigningActivity("alice", completed)).toBe(false);+ expect(hasUnseenSigningActivity("bob", completed)).toBe(true);+});++it("accepts existing read records when detecting completion", () => {+ markSigningItemSeen("alice", request);+ const key = localStorage.key(0)!;+ localStorage.setItem(key, JSON.stringify({ signedCount: 0, decisions: [] }));+ expect(hasUnseenSigningActivity("alice", request)).toBe(false);+ expect(+ hasUnseenSigningActivity("alice", { ...request, finalized: true }),+ ).toBe(true);+});++it("counts both roles once and clears both notifications when the combined session is read", () => {+ const signed = {+ ...session,+ signedCount: 1,+ participants: [+ { id: 2, status: "SIGNED" as const, lastUpdated: "2026-10-01T11:00:00" },+ ],+ };+ const items = collectSigningItems([request], [signed]);+ expect(+ items.filter((item) => hasUnseenSigningActivity("alice", item)),+ ).toHaveLength(1);+ markSigningItemSeen("alice", items[0]);+ expect(hasUnseenSigningActivity("alice", request)).toBe(false);+ expect(hasUnseenSigningActivity("alice", items[0])).toBe(false);+ expect(hasUnseenSigningActivity("bob", items[0])).toBe(true);+ const [later] = collectSigningItems(+ [request],+ [+ {+ ...signed,+ signedCount: 2,+ participants: [+ ...signed.participants,+ { id: 1, status: "SIGNED", lastUpdated: "2026-10-01T12:00:00" },+ ],+ },+ ],+ );+ expect(hasUnseenSigningActivity("alice", later)).toBe(true);+});++it("does not notify for expired access even if the invitation has never been opened", () => {+ expect(hasUnseenSigningActivity("alice", { ...request, closed: true })).toBe(+ false,+ );+ expect(+ hasUnseenSigningActivity("alice", { ...request, accessExpired: true }),+ ).toBe(false);+ expect(+ hasUnseenSigningActivity("alice", { ...request, dueDate: "2000-01-01" }),+ ).toBe(true);+});++it("flags new requests until successfully viewed, separately for each account and role", () => {+ expect(hasUnseenSigningActivity("alice", request)).toBe(true);+ markSigningItemSeen("alice", session);+ expect(hasUnseenSigningActivity("alice", request)).toBe(true);+ markSigningItemSeen("alice", request);+ expect(hasUnseenSigningActivity("alice", request)).toBe(false);+ expect(hasUnseenSigningActivity("bob", request)).toBe(true);+ expect(hasUnseenSigningActivity(null, request)).toBe(false);+ expect(+ hasUnseenSigningActivity("alice", { ...request, sessionId: "new" }),+ ).toBe(true);+ expect(+ hasUnseenSigningActivity("bob", { ...request, myStatus: "VIEWED" }),+ ).toBe(false);+});++it("detects a signature and a later decline without relying on the signed count changing", () => {+ expect(hasUnseenSigningActivity("alice", session)).toBe(false);+ markSigningItemSeen("alice", session);+ const signed = {+ ...session,+ kind: "session",+ signedCount: 1,+ participants: [+ { id: 1, status: "SIGNED", lastUpdated: "2026-10-01T11:00:00" },+ session.participants[1],+ ],+ } satisfies SigningItem;+ expect(hasUnseenSigningActivity("alice", signed)).toBe(true);+ markSigningItemSeen("alice", signed);+ expect(hasUnseenSigningActivity("alice", signed)).toBe(false);+ const declined = {+ ...signed,+ kind: "session",+ participants: [+ signed.participants[0],+ { id: 2, status: "DECLINED", lastUpdated: "2026-10-01T12:00:00" },+ ],+ } satisfies SigningItem;+ expect(hasUnseenSigningActivity("alice", declined)).toBe(true);+ markSigningItemSeen("alice", declined);+ expect(hasUnseenSigningActivity("alice", declined)).toBe(false);+ markSigningItemSeen("alice", session);+ expect(hasUnseenSigningActivity("alice", declined)).toBe(false);+});++it("distinguishes participant decisions when aggregate counts stay unchanged", () => {+ const first = {+ ...session,+ kind: "session",+ participants: [+ { id: 1, status: "DECLINED", lastUpdated: "2026-10-01T11:00:00" },+ ],+ } satisfies SigningItem;+ markSigningItemSeen("alice", first);+ expect(+ hasUnseenSigningActivity("alice", {+ ...first,+ kind: "session",+ participants: [+ { id: 2, status: "DECLINED", lastUpdated: "2026-10-01T12:00:00" },+ ],+ }),+ ).toBe(true);+});++it("clears unread activity on ready sessions without requiring finalization", () => {+ const ready: SigningItem = {+ ...session,+ signedCount: 2,+ participants: undefined,+ };+ expect(hasUnseenSigningActivity("alice", ready)).toBe(true);+ markSigningItemSeen("alice", ready);+ expect(hasUnseenSigningActivity("alice", ready)).toBe(false);+ expect(hasUnseenSigningActivity("bob", { ...ready, finalized: true })).toBe(+ false,+ );+ expect(+ hasUnseenSigningActivity("bob", { ...request, myStatus: "DECLINED" }),+ ).toBe(false);+ expect(+ hasUnseenSigningActivity("bob", { ...request, myStatus: "SIGNED" }),+ ).toBe(false);+});++it("persists only decision identifiers and handles malformed stored values", () => {+ markSigningItemSeen("alice", session);+ const key = localStorage.key(0)!;+ expect(localStorage.getItem(key)).not.toContain("Private.pdf");+ localStorage.setItem(key, '{"signedCount":0,"decisions":"invalid"}');+ expect(+ hasUnseenSigningActivity("alice", { ...session, signedCount: 1 }),+ ).toBe(true);+});++it("keeps read state in memory when persistent writes are unavailable", () => {+ const setItem = vi.spyOn(localStorage, "setItem").mockImplementation(() => {+ throw new Error("Storage disabled");+ });+ markSigningItemSeen("private-mode", request);+ expect(setItem).toHaveBeenCalledOnce();+ expect(localStorage.length).toBe(0);+ expect(hasUnseenSigningActivity("private-mode", request)).toBe(false);+});++it("keeps cross-tab subscriptions alive when an earlier subscriber unmounts", () => {+ const first = vi.fn();+ const second = vi.fn();+ const stopFirst = subscribeSigningSeen(first);+ const stopSecond = subscribeSigningSeen(second);+ stopFirst();+ window.dispatchEvent(+ new StorageEvent("storage", { key: "stirling.signing.seenActivity.test" }),+ );+ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledOnce();+ stopSecond();+ window.dispatchEvent(new StorageEvent("storage", { key: null }));+ expect(second).toHaveBeenCalledOnce();+});diff --git a/frontend/editor/src/core/services/signingSeenStore.ts b/frontend/editor/src/core/services/signingSeenStore.tsindex 04df413323..635acc818f 100644--- a/frontend/editor/src/core/services/signingSeenStore.ts+++ b/frontend/editor/src/core/services/signingSeenStore.ts@@ -1,52 +1,160 @@-/**- * Tracks how many signatures the user had already seen on each signing session- * they own. Used to surface a badge when participants have signed a session- * since the owner last opened it. Persisted in localStorage so "seen" survives- * reloads; a module-level version counter lets hooks re-read reactively.- */+import {+ canReceiveSigningActivity,+ type SigningItem,+} from "@app/utils/signingItems";-const STORAGE_KEY = "stirling.signing.lastSeenSigned";+const STORAGE_PREFIX = "stirling.signing.seenActivity.";-type SeenMap = Record<string, number>;+interface SeenActivity {+ signedCount: number;+ decisions: string[];+ finalized: boolean;+}let version = 0;const listeners = new Set<() => void>();+const memory = new Map<string, SeenActivity>();+const failedWrites = new Set<string>();++function storageKey(accountId: string, item: SigningItem): string {+ return (+ STORAGE_PREFIX + JSON.stringify([accountId, item.kind, item.sessionId])+ );+}++function snapshot(item: SigningItem): SeenActivity {+ return item.kind === "request"+ ? { signedCount: 0, decisions: [], finalized: Boolean(item.finalized) }+ : {+ signedCount: item.signedCount,+ finalized: item.finalized,+ decisions: (item.participants ?? [])+ .filter(+ (participant) =>+ participant.status === "SIGNED" ||+ participant.status === "DECLINED",+ )+ .map((participant) =>+ JSON.stringify([+ participant.id,+ participant.status,+ participant.lastUpdated,+ ]),+ )+ .sort(),+ };+}-function read(): SeenMap {+function read(key: string): SeenActivity | undefined {+ if (failedWrites.has(key)) return memory.get(key);try {- const raw = localStorage.getItem(STORAGE_KEY);- return raw ? (JSON.parse(raw) as SeenMap) : {};+ const value: unknown = JSON.parse(localStorage.getItem(key) ?? "null");+ if (+ value &&+ typeof value === "object" &&+ "signedCount" in value &&+ typeof value.signedCount === "number" &&+ "decisions" in value &&+ Array.isArray(value.decisions) &&+ value.decisions.every((entry) => typeof entry === "string")+ ) {+ return {+ signedCount: value.signedCount,+ decisions: value.decisions,+ finalized: "finalized" in value && value.finalized === true,+ };+ }+ return undefined;} catch {- return {};+ return memory.get(key);}}-/** Signed count the owner last saw for a session (0 if never opened). */-export function getLastSeenSignedCount(sessionId: string): number {- return read()[sessionId] ?? 0;+function notify(): void {+ version += 1;+ listeners.forEach((listener) => listener());}-/** Record the signed count the owner just saw for a session. */-export function markSessionSeen(sessionId: string, signedCount: number): void {+/** Unread includes invitations, participant decisions and completed documents awaiting review. */+export function hasUnseenSigningActivity(+ accountId: string | null,+ item: SigningItem,+): boolean {+ if (!accountId || !canReceiveSigningActivity(item)) return false;+ const seen = read(storageKey(accountId, item));+ if (item.kind === "request" && item.finalized) {+ return !seen?.finalized;+ }+ if (item.kind === "request") {+ return (+ !seen && (item.myStatus === "PENDING" || item.myStatus === "NOTIFIED")+ );+ }+ const current = snapshot(item);+ return (+ Boolean(+ item.ownRequest &&+ hasUnseenSigningActivity(accountId, {+ ...item.ownRequest,+ kind: "request",+ }),+ ) ||+ current.signedCount > (seen?.signedCount ?? 0) ||+ current.decisions.some((decision) => !seen?.decisions.includes(decision))+ );+}++/** Call after showing the detail or its access-expiry notice. Persist no document names, emails or credentials. */+export function markSigningItemSeen(+ accountId: string | null,+ item: SigningItem,+): void {+ if (!accountId) return;+ if (item.kind === "session" && item.ownRequest) {+ markSigningItemSeen(accountId, { ...item.ownRequest, kind: "request" });+ }+ const key = storageKey(accountId, item);+ const current = snapshot(item);+ const previous = read(key);+ // A stale list/response must not resurrect a decision that was already reviewed.+ const next = {+ signedCount: Math.max(previous?.signedCount ?? 0, current.signedCount),+ finalized: Boolean(previous?.finalized || current.finalized),+ decisions: [+ ...new Set([...(previous?.decisions ?? []), ...current.decisions]),+ ].sort(),+ };+ if (JSON.stringify(previous) === JSON.stringify(next)) return;+ memory.set(key, next);try {- const map = read();- if (map[sessionId] === signedCount) return;- map[sessionId] = signedCount;- localStorage.setItem(STORAGE_KEY, JSON.stringify(map));+ localStorage.setItem(key, JSON.stringify(next));+ failedWrites.delete(key);} catch {- // Storage may be unavailable (private mode); badge degrades gracefully.+ // Private-mode storage failures retain read state for this app session.+ failedWrites.add(key);+ }+ notify();+}++function onStorage(event: StorageEvent): void {+ if (event.key === null || event.key.startsWith(STORAGE_PREFIX)) {+ memory.clear();+ failedWrites.clear();+ notify();}- version += 1;- listeners.forEach((listener) => listener());}-/** Subscribe to "seen" changes (for useSyncExternalStore). */+/** Includes read acknowledgements from other tabs on the same origin. */export function subscribeSigningSeen(listener: () => void): () => void {listeners.add(listener);- return () => listeners.delete(listener);+ if (listeners.size === 1) window.addEventListener("storage", onStorage);+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) window.removeEventListener("storage", onStorage);+ };}-/** Monotonic version, bumped whenever a session is marked seen. */+/** Changes when local or cross-tab read state changes; used by useSyncExternalStore. */export function getSigningSeenVersion(): number {return version;}diff --git a/frontend/editor/src/core/services/workbenchSession.test.ts b/frontend/editor/src/core/services/workbenchSession.test.tsindex 8e931ba9ae..f1311c35f5 100644--- a/frontend/editor/src/core/services/workbenchSession.test.ts+++ b/frontend/editor/src/core/services/workbenchSession.test.ts@@ -103,12 +103,13 @@ describe("record hygiene", () => {it("drops the previous record when a write fails, rather than leaving it stale", () => {writeWorkbenchSession({ fileIds: ["old"], selectedFileIds: [] });const setItem = vi- .spyOn(Storage.prototype, "setItem")+ .spyOn(Object.getPrototypeOf(sessionStorage), "setItem").mockImplementation(() => {throw new Error("QuotaExceededError");});writeWorkbenchSession({ fileIds: ["new"], selectedFileIds: [] });+ expect(setItem).toHaveBeenCalledOnce();setItem.mockRestore();// Better to restore nothing than to restore a workbench the user has moved on from.diff --git a/frontend/editor/src/core/theme/colors.css b/frontend/editor/src/core/theme/colors.cssindex df4c5b3812..43de570fcf 100644--- a/frontend/editor/src/core/theme/colors.css+++ b/frontend/editor/src/core/theme/colors.css@@ -55,6 +55,7 @@ html[data-app-theme="light"] {are: the ground does not change, so the ink must not either. */--c-text-on-light: var(--p-ink);--c-accent-on-light: var(--p-blue-700);+ --c-document-bg: var(--p-white);/* Highlight/flash (search hits, compare jump-to) — same in both themes. */--c-highlight: var(--p-flash-yellow);/* Stirling brand red (auth CTAs) — a fixed brand colour, same in both themes. */diff --git a/frontend/editor/src/core/tools/SharedSign.tsx b/frontend/editor/src/core/tools/SharedSign.tsxdeleted file mode 100644index f6cfd5812b..0000000000--- a/frontend/editor/src/core/tools/SharedSign.tsx+++ /dev/null@@ -1,390 +0,0 @@-import { useMemo, useState } from "react";-import {- Alert,- Badge,- Center,- Group,- Loader,- Paper,- Stack,- Text,-} from "@mantine/core";-import { Button } from "@app/ui/Button";-import { Chip } from "@app/ui/Chip";-import { SegmentedControl } from "@app/ui/SegmentedControl";-import { useTranslation } from "react-i18next";-import { Icon } from "@app/ui/Icon";-import type { BaseToolProps } from "@app/types/tool";-import { useGroupSigningEnabled } from "@app/hooks/useGroupSigningEnabled";-import { useAuth } from "@app/auth/UseSession";-import { useViewScopedFiles } from "@app/hooks/tools/shared/useViewScopedFiles";-import { useSigningSessionController } from "@app/hooks/signing/useSigningSessionController";-import { CreateSessionFlow } from "@app/components/shared/signing/CreateSessionFlow";-import { SessionDetailPanel } from "@app/components/tools/certSign/panels/SessionDetailPanel";-import SignRequestPanel from "@app/components/tools/certSign/panels/SignRequestPanel";-import type {- SignRequestSummary,- SessionSummary,-} from "@app/types/signingSession";--type Tab = "active" | "completed";--type SessionItem =- | (SignRequestSummary & { itemType: "signRequest" })- | (SessionSummary & { itemType: "mySession" });--function sortByRecency(items: SessionItem[]): SessionItem[] {- return [...items].sort(- (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),- );-}--const SharedSign = (_props: BaseToolProps) => {- const { t } = useTranslation();- const groupSigningEnabled = useGroupSigningEnabled();- const { isAnonymous } = useAuth();- const controller = useSigningSessionController(groupSigningEnabled);- const selectedFiles = useViewScopedFiles();-- const [tab, setTab] = useState<Tab>("active");- const [filters, setFilters] = useState<string[]>([]);- const [showCreate, setShowCreate] = useState(false);- const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);- const [dueDate, setDueDate] = useState("");-- // Switching tabs clears filters (the available chips differ per tab).- const changeTab = (value: Tab) => {- setTab(value);- setFilters([]);- };-- const { signRequests, mySessions } = controller;-- const activeItems = useMemo<SessionItem[]>(- () =>- sortByRecency([- ...signRequests- .filter((r) => r.myStatus !== "SIGNED" && r.myStatus !== "DECLINED")- .map((r) => ({ ...r, itemType: "signRequest" as const })),- ...mySessions- .filter((s) => !s.finalized)- .map((s) => ({ ...s, itemType: "mySession" as const })),- ]),- [signRequests, mySessions],- );-- const completedItems = useMemo<SessionItem[]>(- () =>- sortByRecency([- ...signRequests- .filter((r) => r.myStatus === "SIGNED" || r.myStatus === "DECLINED")- .map((r) => ({ ...r, itemType: "signRequest" as const })),- ...mySessions- .filter((s) => s.finalized)- .map((s) => ({ ...s, itemType: "mySession" as const })),- ]),- [signRequests, mySessions],- );-- const statusFor = (item: SessionItem): { color: string; label: string } => {- if (item.itemType === "mySession") {- const s = item as SessionSummary;- if (s.finalized) {- return { color: "green", label: t("certSign.finalized", "Finalized") };- }- const signed = s.signedCount ?? 0;- const total = s.participantCount ?? 0;- if (total > 0 && signed === total) {- return {- color: "green",- label: t("certSign.readyToFinalize", "Ready to finalize"),- };- }- if (total > 0) {- return {- color: signed > 0 ? "yellow" : "blue",- label: t(- "certSign.signatureProgress",- "{{signedCount}}/{{totalCount}} signatures",- { signedCount: signed, totalCount: total },- ),- };- }- return {- color: "blue",- label: t("certSign.awaitingSignatures", "Awaiting signatures"),- };- }- const req = item as SignRequestSummary;- switch (req.myStatus) {- case "SIGNED":- return { color: "green", label: t("certSign.signed", "Signed") };- case "DECLINED":- return { color: "red", label: t("certSign.declined", "Declined") };- case "VIEWED":- return { color: "blue", label: t("certSign.viewed", "Viewed") };- default:- return { color: "orange", label: t("certSign.pending", "Pending") };- }- };-- const onItemClick = (item: SessionItem) => {- if (item.itemType === "signRequest") {- void controller.openSignRequest(item);- } else {- void controller.openSession(item);- }- };-- if (!groupSigningEnabled && isAnonymous) {- return (- <Stack p="md">- <Alert- color="yellow"- title={t("sharedSign.signInRequiredTitle", "Sign in required")}- >- {t(- "sharedSign.signInRequiredBody",- "Sign in to request signatures and see requests sent to you.",- )}- </Alert>- </Stack>- );- }-- if (!groupSigningEnabled) {- return (- <Stack p="md">- <Alert- color="yellow"- title={t("sharedSign.disabledTitle", "Not enabled")}- >- {t(- "sharedSign.disabledBody",- "Collaborative signing isn't enabled on this server.",- )}- </Alert>- </Stack>- );- }-- if (controller.view === "detail" && controller.detailData) {- return <SessionDetailPanel data={controller.detailData} />;- }-- if (controller.view === "request" && controller.requestData) {- return <SignRequestPanel data={controller.requestData} />;- }-- if (showCreate) {- return (- <Stack p="md" gap="md">- <Group>- <Button- variant="tertiary"- size="sm"- leftSection={<Icon name="arrow-left" size={"1rem"} />}- onClick={() => setShowCreate(false)}- >- {t("sharedSign.backToSessions", "Back to sessions")}- </Button>- </Group>- <CreateSessionFlow- selectedFiles={selectedFiles}- selectedUserIds={selectedUserIds}- onSelectedUserIdsChange={setSelectedUserIds}- dueDate={dueDate}- onDueDateChange={setDueDate}- creating={controller.creating}- onSubmit={(settings) => {- void controller- .createSession(settings, selectedUserIds, dueDate)- .then((ok) => {- if (ok) {- setShowCreate(false);- setSelectedUserIds([]);- setDueDate("");- changeTab("active");- }- });- }}- />- </Stack>- );- }-- const filterOptions =- tab === "active"- ? [- { key: "mine", label: t("sharedSign.filterMine", "Mine") },- { key: "overdue", label: t("sharedSign.filterOverdue", "Overdue") },- ]- : [- { key: "mine", label: t("sharedSign.filterMine", "Mine") },- { key: "signed", label: t("sharedSign.filterSigned", "Signed") },- {- key: "declined",- label: t("sharedSign.filterDeclined", "Declined"),- },- ];-- const applyFilters = (list: SessionItem[]): SessionItem[] => {- let result = list;- const now = Date.now();- if (filters.includes("mine")) {- result = result.filter((s) => s.itemType === "mySession");- }- if (filters.includes("overdue")) {- // Only sign requests carry a dueDate; owned sessions (SessionSummary) don't- // expose one in the list payload, so overdue filtering requires a backend change.- result = result.filter(- (s) =>- s.itemType === "signRequest" &&- Boolean(s.dueDate) &&- new Date(s.dueDate).getTime() < now,- );- }- if (filters.includes("signed")) {- result = result.filter(- (s) => (s as SignRequestSummary).myStatus === "SIGNED",- );- }- if (filters.includes("declined")) {- result = result.filter(- (s) => (s as SignRequestSummary).myStatus === "DECLINED",- );- }- return result;- };-- const items = applyFilters(tab === "active" ? activeItems : completedItems);-- return (- <Stack p="md" gap="md">- <SegmentedControl- fullWidth- value={tab}- onChange={(value) => changeTab(value)}- options={[- { label: t("sharedSign.tab.active", "Active"), value: "active" },- {- label: t("sharedSign.tab.completed", "Completed"),- value: "completed",- },- ]}- />-- <Button- variant="tertiary"- leftSection={<Icon name="plus" size={"1.1rem"} />}- onClick={() => setShowCreate(true)}- >- {t("sharedSign.newRequest", "Request signatures")}- </Button>-- <Group gap="xs">- {filterOptions.map((f) => {- const active = filters.includes(f.key);- return (- <Chip- key={f.key}- size="xs"- variant={active ? "primary" : "secondary"}- onClick={() =>- setFilters((prev) =>- prev.includes(f.key)- ? prev.filter((k) => k !== f.key)- : [...prev, f.key],- )- }- >- {f.label}- </Chip>- );- })}- </Group>-- {controller.loading && items.length === 0 ? (- <Center py="xl">- <Loader size="sm" />- </Center>- ) : items.length === 0 ? (- <Text size="sm" c="dimmed" ta="center" py="xl">- {tab === "active"- ? t(- "sharedSign.empty.active",- "No pending sign requests or active sessions",- )- : t("sharedSign.empty.completed", "No completed sessions")}- </Text>- ) : (- <Stack gap="sm">- {items.map((item) => {- const status = statusFor(item);- const parts: string[] = [];- if (item.itemType === "signRequest") {- const req = item as SignRequestSummary;- parts.push(- t("sharedSign.fromOwner", "From {{owner}}", {- owner: req.ownerUsername ?? t("unknown", "Unknown"),- }),- );- if (req.dueDate) {- parts.push(- t("sharedSign.due", "Due {{date}}", {- date: new Date(req.dueDate).toLocaleDateString(),- }),- );- }- } else {- const s = item as SessionSummary;- parts.push(- t("sharedSign.createdOn", "Created {{date}}", {- date: new Date(s.createdAt).toLocaleDateString(),- }),- );- if (- s.signedCount !== undefined &&- s.participantCount !== undefined- ) {- parts.push(- t("sharedSign.signedCount", "{{signed}}/{{total}} signed", {- signed: s.signedCount,- total: s.participantCount,- }),- );- }- }- const subtitle = parts.join(" • ");- return (- <Paper- key={`${item.itemType}-${item.sessionId}`}- withBorder- radius="md"- p="sm"- onClick={() => onItemClick(item)}- style={{ cursor: "pointer" }}- >- <Group justify="space-between" wrap="nowrap" align="flex-start">- <Stack gap={2} style={{ minWidth: 0 }}>- <Text size="sm" fw={500} truncate>- {item.documentName}- </Text>- <Text size="xs" c="dimmed" truncate>- {subtitle}- </Text>- </Stack>- <Badge size="sm" color={status.color} variant="light">- {status.label}- </Badge>- </Group>- </Paper>- );- })}- </Stack>- )}- </Stack>- );-};--export default SharedSign;diff --git a/frontend/editor/src/core/types/signingSession.ts b/frontend/editor/src/core/types/signingSession.tsindex f2e4e83d1e..e01eee795d 100644--- a/frontend/editor/src/core/types/signingSession.ts+++ b/frontend/editor/src/core/types/signingSession.ts@@ -1,20 +1,23 @@export interface WetSignatureMetadata {type: "canvas" | "image" | "text";- data: string; // Base64-encoded image data or text content+ data: string; // Base64 image data URL, including rasterized typed textpage: number; // Zero-indexed page number- x: number; // X coordinate in PDF points- y: number; // Y coordinate in PDF points (top-left origin)- width: number; // Width in PDF points- height: number; // Height in PDF points+ x: number; // Fraction of page width, from the left+ y: number; // Fraction of page height, from the top+ width: number; // Fraction of page width+ height: number; // Fraction of page height}export interface SessionSummary {+ status?: "IN_PROGRESS" | "COMPLETED" | "CANCELLED";sessionId: string;documentName: string;createdAt: string;participantCount: number;signedCount: number;+ participants?: Pick<ParticipantInfo, "id" | "status" | "lastUpdated">[];finalized: boolean;+ dueDate?: string;}export interface SessionDetail {@@ -61,6 +64,11 @@ export interface SignRequestSummary {createdAt: string;dueDate: string;myStatus: "PENDING" | "NOTIFIED" | "VIEWED" | "SIGNED" | "DECLINED";+ finalized?: boolean;+ /** Server-evaluated access expiry, independent of the advisory due date. */+ accessExpired?: boolean;+ /** Closed for this participant, including non-signing roles; submitted signatures alone do not close it. */+ closed?: boolean;}export interface SignRequestDetail {@@ -71,6 +79,9 @@ export interface SignRequestDetail {dueDate: string;createdAt: string;myStatus: "PENDING" | "NOTIFIED" | "VIEWED" | "SIGNED" | "DECLINED";+ finalized?: boolean;+ canSign?: boolean;+ participants?: SigningParticipantPreview[];// Signature appearance settings (read-only, configured by owner)showSignature?: boolean;pageNumber?: number;@@ -78,3 +89,9 @@ export interface SignRequestDetail {location?: string;showLogo?: boolean;}++/** Public participant progress; contains neither certificate credentials nor share tokens. */+export type SigningParticipantPreview = Pick<+ ParticipantInfo,+ "id" | "name" | "status" | "wetSignatures"+>;diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.tsindex 430b3937a2..04eed03fec 100644--- a/frontend/editor/src/core/types/toolApiTypes.ts+++ b/frontend/editor/src/core/types/toolApiTypes.ts@@ -1413,10 +1413,12 @@ export interface WorkflowCreationRequest {workflowType?: "SIGNING" | "REVIEW" | "APPROVAL";}export interface SecurityCertSignValidateCertificateRequest {+ certFile?: File;certType: string;jksFile?: File;p12File?: File;password?: string;+ privateKeyFile?: File;}export type SecurityGetInfoOnPdfRequest = Record<string, never>;export type SecurityRemoveCertSignRequest = Record<string, never>;@@ -1913,7 +1915,12 @@ export const TOOL_FILE_FIELDS = {"p12File","jksFile",],- "/api/v1/security/cert-sign/validate-certificate": ["p12File", "jksFile"],+ "/api/v1/security/cert-sign/validate-certificate": [+ "p12File",+ "privateKeyFile",+ "certFile",+ "jksFile",+ ],"/api/v1/security/validate-signature": ["certFile"],} as const satisfies Partial<Record<ToolEndpoint, readonly string[]>>;diff --git a/frontend/editor/src/core/types/toolId.ts b/frontend/editor/src/core/types/toolId.tsindex 6d210681a1..de647e2b6e 100644--- a/frontend/editor/src/core/types/toolId.ts+++ b/frontend/editor/src/core/types/toolId.ts@@ -14,7 +14,6 @@ export type ToolKind = "regular" | "super" | "link";export const CORE_REGULAR_TOOL_IDS = ["certSign","sign",- "sharedSign","addText","addPassword","removePassword",diff --git a/frontend/editor/src/core/types/workbench.ts b/frontend/editor/src/core/types/workbench.tsindex 7529f78f5c..cc249eed25 100644--- a/frontend/editor/src/core/types/workbench.ts+++ b/frontend/editor/src/core/types/workbench.ts@@ -4,6 +4,7 @@ export const BASE_WORKBENCH_TYPES = ["pageEditor","fileEditor","myFiles",+ "signing",] as const;export type BaseWorkbenchType = (typeof BASE_WORKBENCH_TYPES)[number];diff --git a/frontend/editor/src/core/ui/DataTable.css b/frontend/editor/src/core/ui/DataTable.cssindex fcdee564ac..8b17a41631 100644--- a/frontend/editor/src/core/ui/DataTable.css+++ b/frontend/editor/src/core/ui/DataTable.css@@ -147,6 +147,16 @@padding: 0.375rem 0.625rem;}+.sui-datatable--comfortable .sui-datatable__toolbar {+ padding: 1rem 1.125rem;+}+.sui-datatable--comfortable .sui-datatable__th {+ padding: 0.75rem 1.125rem;+}+.sui-datatable--comfortable .sui-datatable__td {+ padding: 0.875rem 1.125rem;+}+/* Interactive rows */.sui-datatable__row--interactive {cursor: pointer;@@ -345,6 +355,22 @@min-width: 2.5rem;}+.sui-dtc__status-progress {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ min-width: 12rem;+}+.sui-dtc__status-progress-heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+}+.sui-dtc__status-progress .sui-dtc__progress-pct {+ font-size: 0.6875rem;+}+.sui-dtc__links {display: flex;align-items: center;@@ -380,3 +406,12 @@.sui-dtc__select {min-width: 13rem;}++.sui-dtc__unread {+ display: inline-block;+ width: 7px;+ height: 7px;+ flex-shrink: 0;+ border-radius: 50%;+ background: var(--c-accent-fg);+}diff --git a/frontend/editor/src/core/ui/DataTable.stories.tsx b/frontend/editor/src/core/ui/DataTable.stories.tsxindex 630537ace9..e0667fc16d 100644--- a/frontend/editor/src/core/ui/DataTable.stories.tsx+++ b/frontend/editor/src/core/ui/DataTable.stories.tsx@@ -249,7 +249,6 @@ export const WithToolbar: Story = {),};-/** The one look choice: the `compact` variant. */export const Compact: Story = {render: () => (<DataTable<Region>@@ -260,3 +259,38 @@ export const Compact: Story = {/>),};++export const ComfortableWithProgress: Story = {+ render: () => (+ <DataTable+ variant="comfortable"+ columns={[+ column.entity<{ name: string; signed: number; total: number }>({+ key: "document",+ header: "Document",+ primary: (row) => row.name,+ }),+ column.badge<{ name: string; signed: number; total: number }>({+ key: "status",+ header: "Status",+ get: (row) => ({+ tone: row.signed === row.total ? "success" : "info",+ label:+ row.signed === row.total+ ? "Ready to finalize"+ : "Awaiting signatures",+ progress: {+ value: row.signed / row.total,+ label: `${row.signed} / ${row.total} signed`,+ },+ }),+ }),+ ]}+ rows={[+ { name: "Agreement.pdf", signed: 1, total: 3 },+ { name: "Approval.pdf", signed: 2, total: 2 },+ ]}+ rowKey={(row) => row.name}+ />+ ),+};diff --git a/frontend/editor/src/core/ui/DataTable.tsx b/frontend/editor/src/core/ui/DataTable.tsxindex e8b5f7f986..0dc52496e5 100644--- a/frontend/editor/src/core/ui/DataTable.tsx+++ b/frontend/editor/src/core/ui/DataTable.tsx@@ -58,7 +58,7 @@ const DATA_TABLE_FEATURES = tableFeatures({type DataTableFeatures = typeof DATA_TABLE_FEATURES;/** Closed appearance dial — the only look choice a call-site may make. */-export type DataTableVariant = "default" | "compact";+export type DataTableVariant = "default" | "compact" | "comfortable";/*** A collapsible section of rows under a locked header. Group headers arediff --git a/frontend/editor/src/core/ui/Dropdown.test.tsx b/frontend/editor/src/core/ui/Dropdown.test.tsxnew file mode 100644index 0000000000..4cc78b6301--- /dev/null+++ b/frontend/editor/src/core/ui/Dropdown.test.tsx@@ -0,0 +1,115 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { Dropdown } from "@app/ui/Dropdown";++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe = vi.fn();+ disconnect = vi.fn();+ unobserve = vi.fn();+ },+ );+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++it("preserves command-menu keyboard navigation and closes on selection", () => {+ const onSelect = vi.fn();+ render(+ <Dropdown.Root defaultOpen>+ <Dropdown.Trigger>+ <button>Commands</button>+ </Dropdown.Trigger>+ <Dropdown.Menu autoFocus>+ <Dropdown.Item disabled>Unavailable</Dropdown.Item>+ <Dropdown.Item>First</Dropdown.Item>+ <Dropdown.Item onSelect={onSelect}>Second</Dropdown.Item>+ </Dropdown.Menu>+ </Dropdown.Root>,+ );+ expect(screen.getByRole("button", { name: "Commands" })).toHaveAttribute(+ "aria-haspopup",+ "menu",+ );+ expect(screen.getByRole("menuitem", { name: "First" })).toHaveFocus();+ fireEvent.keyDown(screen.getByRole("menu"), { key: "ArrowDown" });+ const second = screen.getByRole("menuitem", { name: "Second" });+ expect(second).toHaveFocus();+ fireEvent.click(second);+ expect(onSelect).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();+});++it.each([+ {+ width: 1280,+ height: 720,+ triggerY: 400,+ panelWidth: 400,+ panelHeight: 660,+ top: "52px",+ bottom: "auto",+ left: "52px",+ maxHeight: "704px",+ },+ {+ width: 390,+ height: 844,+ triggerY: 800,+ panelWidth: 366,+ panelHeight: 660,+ top: "auto",+ bottom: "48px",+ left: "8px",+ maxHeight: "788px",+ },+])(+ "keeps a side popover inside a $width by $height viewport",+ ({+ width,+ height,+ triggerY,+ panelWidth,+ panelHeight,+ top,+ bottom,+ left,+ maxHeight,+ }) => {+ vi.stubGlobal("innerWidth", width);+ vi.stubGlobal("innerHeight", height);+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(+ new DOMRect(0, triggerY, 48, 36),+ );+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(+ panelWidth,+ );+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(+ panelHeight,+ );+ render(+ <Dropdown.Root defaultOpen align="start">+ <Dropdown.Trigger popupRole="dialog">+ <button>Open sessions</button>+ </Dropdown.Trigger>+ <Dropdown.Menu role="dialog" ariaLabel="Sessions" placement="side">+ <button>Browse</button>+ </Dropdown.Menu>+ </Dropdown.Root>,+ );+ expect(+ screen.getByRole("button", { name: "Open sessions" }),+ ).toHaveAttribute("aria-haspopup", "dialog");+ expect(screen.getByRole("dialog", { name: "Sessions" })).toHaveStyle({+ top,+ bottom,+ left,+ maxHeight,+ });+ },+);diff --git a/frontend/editor/src/core/ui/Dropdown.tsx b/frontend/editor/src/core/ui/Dropdown.tsxindex 25019d7c3c..2f34ea5268 100644--- a/frontend/editor/src/core/ui/Dropdown.tsx+++ b/frontend/editor/src/core/ui/Dropdown.tsx@@ -122,6 +122,7 @@ function Root({}export interface DropdownTriggerProps {+ popupRole?: "menu" | "dialog";/** A single button-like element. Receives onClick + aria props. */children: ReactElement<{onClick?: (e: React.MouseEvent) => void;@@ -132,7 +133,7 @@ export interface DropdownTriggerProps {}>;}-function Trigger({ children }: DropdownTriggerProps) {+function Trigger({ children, popupRole = "menu" }: DropdownTriggerProps) {const { open, setOpen, triggerRef, menuId } = useDropdownCtx();if (!isValidElement(children)) {throw new Error(@@ -145,7 +146,7 @@ function Trigger({ children }: DropdownTriggerProps) {children.props.onClick?.(e);setOpen(!open);},- "aria-haspopup": "menu",+ "aria-haspopup": popupRole,"aria-expanded": open,"aria-controls": menuId,});@@ -156,9 +157,24 @@ export interface DropdownMenuProps {className?: string;/** Optional min-width override (px or CSS length). */width?: string | number;+ /** Move keyboard focus into a command menu when it opens. */+ autoFocus?: boolean;+ /** Rich popovers use dialog semantics and their own control-specific keyboard handling. */+ role?: "menu" | "dialog";+ ariaLabel?: string;+ /** Prefer beside a rail trigger; fall back above/below when the viewport is too narrow. */+ placement?: "vertical" | "side";}-function Menu({ children, className, width }: DropdownMenuProps) {+function Menu({+ children,+ className,+ width,+ autoFocus = false,+ role = "menu",+ ariaLabel,+ placement = "vertical",+}: DropdownMenuProps) {const { open, menuId, align, triggerRef, menuRef } = useDropdownCtx();// Fixed position tracked to the trigger. Portaling to <body> keeps the menu// out of any `overflow` ancestor (e.g. a table's horizontal scroll area),@@ -170,6 +186,17 @@ function Menu({ children, className, width }: DropdownMenuProps) {right?: number;maxHeight: number;} | null>(null);+ const positioned = pos !== null;+ const focusedOnOpen = useRef(false);+ useEffect(() => {+ if (!open) focusedOnOpen.current = false;+ if (open && pos && autoFocus && !focusedOnOpen.current) {+ menuRef.current+ ?.querySelector<HTMLButtonElement>("button:not(:disabled)")+ ?.focus();+ focusedOnOpen.current = true;+ }+ }, [open, pos, autoFocus, menuRef]);useLayoutEffect(() => {if (!open) return;@@ -179,6 +206,22 @@ function Menu({ children, className, width }: DropdownMenuProps) {const r = el.getBoundingClientRect();const gap = 4;const margin = 8;+ const panelWidth = menuRef.current?.offsetWidth || 400;+ if (+ placement === "side" &&+ r.right + gap + panelWidth <= window.innerWidth - margin+ ) {+ const panelHeight = menuRef.current?.offsetHeight || 0;+ setPos({+ left: r.right + gap,+ top: Math.max(+ margin,+ Math.min(r.top, window.innerHeight - margin - panelHeight),+ ),+ maxHeight: window.innerHeight - margin * 2,+ });+ return;+ }const spaceBelow = window.innerHeight - r.bottom - margin;const spaceAbove = r.top - margin;// Flip above when there's more room there, so a trigger near the viewport@@ -187,7 +230,15 @@ function Menu({ children, className, width }: DropdownMenuProps) {const horizontal =align === "end"? { right: window.innerWidth - r.right }- : { left: r.left };+ : {+ left:+ placement === "side"+ ? Math.max(+ margin,+ Math.min(r.left, window.innerWidth - margin - panelWidth),+ )+ : r.left,+ };setPos({...horizontal,...(below@@ -197,14 +248,17 @@ function Menu({ children, className, width }: DropdownMenuProps) {});};place();+ const observer = placement === "side" ? new ResizeObserver(place) : null;+ if (menuRef.current) observer?.observe(menuRef.current);// Track the trigger while scrolling/resizing (capture catches inner scrollers).window.addEventListener("scroll", place, true);window.addEventListener("resize", place);return () => {window.removeEventListener("scroll", place, true);window.removeEventListener("resize", place);+ observer?.disconnect();};- }, [open, align, triggerRef]);+ }, [open, align, triggerRef, menuRef, placement, positioned]);if (!open || !pos) return null;const style: React.CSSProperties = {@@ -216,7 +270,7 @@ function Menu({ children, className, width }: DropdownMenuProps) {left: pos.left ?? "auto",right: pos.right ?? "auto",maxHeight: pos.maxHeight,- overflowY: "auto",+ overflowY: role === "menu" ? "auto" : undefined,...(width !== undefined? { minWidth: typeof width === "number" ? `${width}px` : width }: {}),@@ -224,10 +278,37 @@ function Menu({ children, className, width }: DropdownMenuProps) {return createPortal(<divid={menuId}- role="menu"+ role={role}+ aria-label={ariaLabel}ref={menuRef}className={["sui-dd__menu", className ?? ""].filter(Boolean).join(" ")}style={style}+ onKeyDown={(event) => {+ if (+ !autoFocus ||+ role !== "menu" ||+ !["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)+ )+ return;+ const items = Array.from(+ event.currentTarget.querySelectorAll<HTMLButtonElement>(+ "button:not(:disabled)",+ ),+ );+ if (!items.length) return;+ event.preventDefault();+ const index = items.findIndex(+ (item) => item === document.activeElement,+ );+ const next =+ event.key === "Home"+ ? 0+ : event.key === "End"+ ? items.length - 1+ : (index + (event.key === "ArrowDown" ? 1 : -1) + items.length) %+ items.length;+ items[next].focus();+ }}>{children}</div>,diff --git a/frontend/editor/src/core/ui/dataTableColumns.tsx b/frontend/editor/src/core/ui/dataTableColumns.tsxindex 91e8af3e29..4926a13c5d 100644--- a/frontend/editor/src/core/ui/dataTableColumns.tsx+++ b/frontend/editor/src/core/ui/dataTableColumns.tsx@@ -272,7 +272,12 @@ function number<T>(function badge<T>(o: Common & {- get: (row: T) => { tone: StatusTone; label: string };+ get: (row: T) => {+ tone: StatusTone;+ label: string;+ /** Optional completion bar below the status; value is 0–1 and label describes the completed count. */+ progress?: { value: number; label: string };+ };sortBy?: (row: T) => SortValue;},): DataTableColumn<T> {@@ -284,11 +289,25 @@ function badge<T>(sortFn: "alphanumeric",renderCell: (r) => {const b = o.get(r);- return (+ const status = (<StatusBadge tone={b.tone} size="sm">{b.label}</StatusBadge>);+ if (!b.progress) return status;+ return (+ <div className="sui-dtc__status-progress">+ <div className="sui-dtc__status-progress-heading">+ {status}+ <span className="sui-dtc__progress-pct">{b.progress.label}</span>+ </div>+ <ProgressBar+ value={b.progress.value}+ label={b.progress.label}+ height={4}+ />+ </div>+ );},});}@@ -377,6 +396,8 @@ function entity<T>(primary: (row: T) => string;/** Muted inline suffix after the name, its own node (e.g. "(you)"). */suffix?: (row: T) => string | null | undefined;+ /** When present, shows an unread dot and exposes this explanation to assistive technology. */+ unreadLabel?: (row: T) => string | null | undefined;/** Secondary muted line under the name. */note?: (row: T) => string | null | undefined;sortBy?: (row: T) => SortValue;@@ -391,6 +412,7 @@ function entity<T>(renderCell: (r) => {const icon = o.icon?.(r);const suffix = o.suffix?.(r);+ const unreadLabel = o.unreadLabel?.(r);const note = o.note?.(r);return (<div className="sui-dtc__entity">@@ -402,6 +424,14 @@ function entity<T>(<div className="sui-dtc__entity-body"><span className="sui-dtc__entity-head"><span className="sui-dtc__entity-name">{o.primary(r)}</span>+ {unreadLabel && (+ <span+ className="sui-dtc__unread"+ role="img"+ aria-label={unreadLabel}+ title={unreadLabel}+ />+ )}{suffix && (<span className="sui-dtc__entity-suffix">{suffix}</span>)}diff --git a/frontend/editor/src/core/utils/homePageNavigation.ts b/frontend/editor/src/core/utils/homePageNavigation.tsindex 7a91bfec65..ef112bdf00 100644--- a/frontend/editor/src/core/utils/homePageNavigation.ts+++ b/frontend/editor/src/core/utils/homePageNavigation.ts@@ -28,7 +28,7 @@ export function getStartupNavigationAction(// The user is browsing their file library - don't auto-switch them out of// the file manager just because a new upload landed.- if (currentWorkbench === "myFiles") {+ if (currentWorkbench === "myFiles" || currentWorkbench === "signing") {return null;}diff --git a/frontend/editor/src/core/utils/pendingSigningIntent.ts b/frontend/editor/src/core/utils/pendingSigningIntent.tsnew file mode 100644index 0000000000..0a2e90e4d8--- /dev/null+++ b/frontend/editor/src/core/utils/pendingSigningIntent.ts@@ -0,0 +1,26 @@+import { useSyncExternalStore } from "react";++export type SigningIntent =+ | "create"+ | "list"+ | { kind: "request" | "session"; sessionId: string };+let pending: SigningIntent | null = null;+const listeners = new Set<() => void>();+const subscribe = (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+};+const snapshot = () => pending;++/** Carries a rail action across an editor mount; session details are fetched in the workspace. */+export function requestSigningIntent(intent: SigningIntent | null): void {+ pending = intent;+ listeners.forEach((listener) => listener());+}++/** Read and clear after the workspace receives the action. */+export function usePendingSigningIntent(): SigningIntent | null {+ return useSyncExternalStore(subscribe, snapshot, snapshot);+}diff --git a/frontend/editor/src/core/utils/signingItems.test.ts b/frontend/editor/src/core/utils/signingItems.test.tsnew file mode 100644index 0000000000..052f6d2e8a--- /dev/null+++ b/frontend/editor/src/core/utils/signingItems.test.ts@@ -0,0 +1,174 @@+import { describe, expect, it } from "vitest";+import {+ collectSigningItems,+ getSigningItemToOpen,+ isSigningItemClosed,+ needsSignature,+ type SigningItem,+} from "@app/utils/signingItems";+import {+ EMPTY_QUICK_NAV_ACCOUNT,+ updateQuickNavAccount,+} from "@app/contexts/quickNavAccount";+import { getStartupNavigationAction } from "@app/utils/homePageNavigation";++const request = {+ kind: "request",+ sessionId: "request-1",+ documentName: "Agreement.pdf",+ ownerUsername: "Owner",+ createdAt: "2026-09-24",+ dueDate: "",+ myStatus: "PENDING",+} satisfies SigningItem;+const session = {+ kind: "session",+ sessionId: "session-1",+ documentName: "Owned.pdf",+ createdAt: "2026-09-25",+ participantCount: 2,+ signedCount: 1,+ finalized: false,+} satisfies SigningItem;++describe("signing workspace entry points", () => {+ it("closes server-reported participant restrictions and cancelled or completed workflows", () => {+ expect(isSigningItemClosed({ ...request, closed: true })).toBe(true);+ expect(needsSignature({ ...request, closed: true })).toBe(false);+ expect(+ isSigningItemClosed({ ...session, kind: "session", status: "CANCELLED" }),+ ).toBe(true);+ expect(+ isSigningItemClosed({ ...session, kind: "session", status: "COMPLETED" }),+ ).toBe(true);+ expect(+ isSigningItemClosed({+ ...session,+ kind: "session",+ status: "IN_PROGRESS",+ }),+ ).toBe(false);+ });+ it("closes expired participant access without closing the owner session or treating due dates as expiry", () => {+ const expired = { ...request, accessExpired: true };+ expect(isSigningItemClosed(expired)).toBe(true);+ expect(needsSignature(expired)).toBe(false);+ expect(isSigningItemClosed({ ...expired, myStatus: "SIGNED" })).toBe(true);+ const overdue = { ...request, dueDate: "2000-01-01", accessExpired: false };+ expect(isSigningItemClosed(overdue)).toBe(false);+ expect(needsSignature(overdue)).toBe(true);+ expect(+ isSigningItemClosed({ ...session, sessionId: request.sessionId }),+ ).toBe(false);+ });+ it("collapses duplicate historical invitations before rendering and filtering", () => {+ expect(collectSigningItems([request, { ...request }], [])).toEqual([+ request,+ ]);+ });+ it("keeps every session and request, including closed items", () => {+ const requests = Array.from({ length: 8 }, (_, index) => ({+ ...request,+ sessionId: `request-${index}`,+ }));+ expect(+ collectSigningItems(requests, [+ session,+ { ...session, sessionId: "closed", finalized: true },+ ]),+ ).toHaveLength(10);+ });+ it("keeps ready and submitted sessions active, with finalized and declined invitations closed", () => {+ expect(isSigningItemClosed(request)).toBe(false);+ expect(isSigningItemClosed({ ...request, myStatus: "SIGNED" })).toBe(false);+ expect(isSigningItemClosed({ ...session, signedCount: 2 })).toBe(false);+ expect(isSigningItemClosed({ ...request, myStatus: "DECLINED" })).toBe(+ true,+ );+ expect(isSigningItemClosed({ ...session, finalized: true })).toBe(true);+ });+ it("combines the owner's roles into one stable session, opening signing before management", () => {+ const ownRequest = { ...request, sessionId: session.sessionId };+ const items = collectSigningItems([ownRequest], [session]);+ expect(items).toEqual([{ ...session, ownRequest }]);+ expect(needsSignature(items[0])).toBe(true);+ expect(getSigningItemToOpen(items[0])).toEqual(ownRequest);+ const [signed] = collectSigningItems(+ [{ ...ownRequest, myStatus: "SIGNED" }],+ [session],+ );+ expect(signed.kind).toBe("session");+ expect(needsSignature(signed)).toBe(false);+ expect(getSigningItemToOpen(signed)).toBe(signed);+ });++ it.each([+ { myStatus: "DECLINED" as const },+ { accessExpired: true },+ { closed: true },+ ])(+ "keeps owner management active when their invitation is restricted: %j",+ (restriction) => {+ const [item] = collectSigningItems(+ [{ ...request, sessionId: session.sessionId, ...restriction }],+ [session],+ );+ expect(isSigningItemClosed(item)).toBe(false);+ expect(needsSignature(item)).toBe(false);+ expect(getSigningItemToOpen(item)).toBe(item);+ },+ );++ it.each([+ { ...session, finalized: true },+ { ...session, status: "CANCELLED" as const },+ ])(+ "closes one combined entry even if its pending invitation is stale",+ (closed) => {+ const items = collectSigningItems(+ [{ ...request, sessionId: session.sessionId }],+ [closed],+ );+ expect(items).toHaveLength(1);+ expect(isSigningItemClosed(items[0])).toBe(true);+ expect(needsSignature(items[0])).toBe(false);+ },+ );++ it("honors finalized participant state while the owner list is catching up", () => {+ const [item] = collectSigningItems(+ [{ ...request, sessionId: session.sessionId, finalized: true }],+ [session],+ );+ expect(isSigningItemClosed(item)).toBe(true);+ expect(getSigningItemToOpen(item).kind).toBe("session");+ });++ it("does not leak session names into another account or after logout", () => {+ const alice = updateQuickNavAccount(EMPTY_QUICK_NAV_ACCOUNT, {+ accountId: "alice",+ signingItems: [{ ...request, unread: true }],+ signingBadge: 1,+ });+ expect(+ updateQuickNavAccount(alice, { accountId: "bob" }).signingItems,+ ).toEqual([]);+ expect(+ updateQuickNavAccount(alice, { accountId: null }).signingItems,+ ).toEqual([]);+ expect(+ updateQuickNavAccount(alice, {+ identity: { displayName: "Alice", profilePictureUrl: null },+ }).signingItems,+ ).toEqual([{ ...request, unread: true }]);+ });++ it("keeps request creation open when an upload adds files", () => {+ expect(getStartupNavigationAction(0, 1, null, "signing")).toBeNull();+ expect(getStartupNavigationAction(1, 2, null, "signing")).toBeNull();+ expect(getStartupNavigationAction(0, 1, null, "viewer")).toEqual({+ workbench: "viewer",+ activeFileIndex: 0,+ });+ });+});diff --git a/frontend/editor/src/core/utils/signingItems.ts b/frontend/editor/src/core/utils/signingItems.tsnew file mode 100644index 0000000000..909f569bc4--- /dev/null+++ b/frontend/editor/src/core/utils/signingItems.ts@@ -0,0 +1,80 @@+import type {+ SessionSummary,+ SignRequestSummary,+} from "@app/types/signingSession";++export type SigningItem =+ | (SignRequestSummary & { kind: "request" })+ | (SessionSummary & { kind: "session"; ownRequest?: SignRequestSummary });++export type SigningMenuItem = SigningItem & { unread: boolean };++/** One entry per document workflow; owned sessions retain the owner's participant action. */+export function collectSigningItems(+ requests: SignRequestSummary[],+ sessions: SessionSummary[],+): SigningItem[] {+ const items = new Map<string, SigningItem>(+ requests.map((request) => [+ request.sessionId,+ { ...request, kind: "request" },+ ]),+ );+ const requestsById = new Map(+ requests.map((request) => [request.sessionId, request]),+ );+ for (const session of sessions) {+ const ownRequest = requestsById.get(session.sessionId);+ items.set(session.sessionId, {+ ...session,+ kind: "session",+ ...(ownRequest ? { ownRequest } : {}),+ finalized: session.finalized || Boolean(ownRequest?.finalized),+ });+ }+ return [...items.values()].sort(+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),+ );+}++/** Participant closure includes access and role restrictions; the owner's workflow can remain active. */+export function isSigningItemClosed(item: SigningItem): boolean {+ return (+ Boolean(item.finalized) ||+ (item.kind === "session" &&+ item.status !== undefined &&+ item.status !== "IN_PROGRESS") ||+ (item.kind === "request" &&+ (item.myStatus === "DECLINED" ||+ Boolean(item.accessExpired) ||+ Boolean(item.closed)))+ );+}++/** Completed participant documents can notify; expired access and other closed workflows cannot. */+export function canReceiveSigningActivity(item: SigningItem): boolean {+ return (+ !isSigningItemClosed(item) ||+ (item.kind === "request" &&+ Boolean(item.finalized) &&+ !item.accessExpired &&+ item.myStatus !== "DECLINED")+ );+}++export function needsSignature(item: SigningItem): boolean {+ if (isSigningItemClosed(item)) return false;+ const request = item.kind === "request" ? item : item.ownRequest;+ return (+ request !== undefined &&+ !isSigningItemClosed({ ...request, kind: "request" }) &&+ request.myStatus !== "SIGNED"+ );+}++/** Prioritizes an owner's pending signature, then returns to session management. */+export function getSigningItemToOpen(item: SigningItem): SigningItem {+ return item.kind === "session" && item.ownRequest && needsSignature(item)+ ? { ...item.ownRequest, kind: "request" }+ : item;+}diff --git a/frontend/editor/src/core/utils/signingPreviews.ts b/frontend/editor/src/core/utils/signingPreviews.tsnew file mode 100644index 0000000000..feae979a9b--- /dev/null+++ b/frontend/editor/src/core/utils/signingPreviews.ts@@ -0,0 +1,28 @@+import type { SignaturePreview } from "@app/components/viewer/viewerTypes";+import { getFileColor } from "@app/components/pageEditor/fileColors";+import type { SigningParticipantPreview } from "@app/types/signingSession";++/** Only submitted marks overlay the original PDF; finalized PDFs already contain those marks. */+export function getSubmittedSignaturePreviews(session: {+ finalized?: boolean;+ participants?: SigningParticipantPreview[];+}): SignaturePreview[] {+ if (session.finalized) return [];+ return (session.participants ?? []).flatMap(+ (participant, participantIndex) =>+ participant.status !== "SIGNED"+ ? []+ : (participant.wetSignatures ?? []).map((mark, index) => ({+ id: `participant-${participant.id}-sig-${index}`,+ pageIndex: mark.page,+ x: mark.x,+ y: mark.y,+ width: mark.width,+ height: mark.height,+ signatureData: mark.data,+ signatureType: "image" as const,+ color: getFileColor(participantIndex),+ participantName: participant.name,+ })),+ );+}diff --git a/frontend/editor/src/core/utils/signingStatus.ts b/frontend/editor/src/core/utils/signingStatus.tsnew file mode 100644index 0000000000..be9517a865--- /dev/null+++ b/frontend/editor/src/core/utils/signingStatus.ts@@ -0,0 +1,76 @@+import type { TFunction } from "i18next";+import type { SigningItem } from "@app/utils/signingItems";+import { isSigningItemClosed, needsSignature } from "@app/utils/signingItems";+import type {+ SessionSummary,+ SignRequestSummary,+} from "@app/types/signingSession";++export function signingStatus(+ item: SigningItem,+ t: TFunction,+): { color: string; label: string } {+ if (item.kind === "session") {+ if (needsSignature(item)) {+ return {+ color: "orange",+ label: t("signWorkspace.needsYou", "Needs your signature"),+ };+ }+ const s = item as SessionSummary;+ if (s.finalized) {+ return { color: "green", label: t("certSign.finalized", "Finalized") };+ }+ if (isSigningItemClosed(item)) {+ return { color: "orange", label: t("signMenu.closedStatus", "Closed") };+ }+ const signed = s.signedCount ?? 0;+ const total = s.participantCount ?? 0;+ if (total > 0 && signed === total) {+ return {+ color: "green",+ label: t("certSign.readyToFinalize", "Ready to finalize"),+ };+ }+ if (total > 0) {+ return {+ color: signed > 0 ? "yellow" : "blue",+ label: t(+ "certSign.signatureProgress",+ "{{signedCount}}/{{totalCount}} signatures",+ { signedCount: signed, totalCount: total },+ ),+ };+ }+ return {+ color: "blue",+ label: t("certSign.awaitingSignatures", "Awaiting signatures"),+ };+ }+ const req = item as SignRequestSummary;+ if (req.accessExpired) {+ return {+ color: "orange",+ label: t("signRequest.expired", "Access expired"),+ };+ }+ if (req.finalized) {+ return { color: "green", label: t("certSign.finalized", "Finalized") };+ }+ if (req.closed && req.myStatus !== "DECLINED") {+ return { color: "orange", label: t("signMenu.closedStatus", "Closed") };+ }+ switch (req.myStatus) {+ case "SIGNED":+ return {+ color: "blue",+ label: t("signMenu.submitted", "Submitted · awaiting finalization"),+ };+ case "DECLINED":+ return { color: "red", label: t("certSign.declined", "Declined") };+ case "VIEWED":+ return { color: "blue", label: t("certSign.viewed", "Viewed") };+ default:+ return { color: "orange", label: t("certSign.pending", "Pending") };+ }+}diff --git a/frontend/editor/src/portal/components/users/InviteMemberModal.test.tsx b/frontend/editor/src/portal/components/users/InviteMemberModal.test.tsxindex 468a9f535a..4e50d78d8a 100644--- a/frontend/editor/src/portal/components/users/InviteMemberModal.test.tsx+++ b/frontend/editor/src/portal/components/users/InviteMemberModal.test.tsx@@ -48,6 +48,39 @@ function renderModal(props: Partial<ComponentProps<typeof InviteMemberModal>>) {}describe("InviteMemberModal — add-user method gating", () => {+ it.each([+ { text: "Alex Morgan", direct: true, email: false, field: "Username" },+ {+ text: "[email protected]",+ direct: true,+ email: false,+ field: "Username",+ },+ {+ text: "[email protected]",+ direct: true,+ email: true,+ field: "Email address",+ },+ { text: "Alex Morgan", direct: false, email: true, field: "Email address" },+ ])(+ "preserves search text for the available method: $text / $field",+ async ({ text, direct, email, field }) => {+ const user = userEvent.setup();+ renderModal({+ initialValue: text,+ canDirectCreate: direct,+ canEmailInvite: email,+ });+ const input = screen.getByRole("textbox", { name: new RegExp(field) });+ expect(input).toHaveValue(text);+ expect(createMember).not.toHaveBeenCalled();+ await user.clear(input);+ await user.type(input, "[email protected]");+ expect(input).toHaveValue("[email protected]");+ },+ );+it("SaaS (email only): no method toggle, opens to the email field", () => {renderModal({ canDirectCreate: false, canEmailInvite: true });expect(screen.queryByText("How to add them")).not.toBeInTheDocument();diff --git a/frontend/editor/src/portal/components/users/InviteMemberModal.tsx b/frontend/editor/src/portal/components/users/InviteMemberModal.tsxindex 570fa79b48..b0b76006d5 100644--- a/frontend/editor/src/portal/components/users/InviteMemberModal.tsx+++ b/frontend/editor/src/portal/components/users/InviteMemberModal.tsx@@ -33,9 +33,11 @@ interface InviteMemberModalProps {manageGrants?: boolean;/** Non-blocking notice back to the parent (e.g. a deferred Processor grant). */onNotice?: (message: string) => void;- /** Force the initial mode (mainly for Storybook). Defaults to "direct" when account- * creation is available, else "email". */+ /** Requested method, used only if the server supports it. Otherwise the search text+ * and available methods determine the initial selection. */initialMode?: "email" | "direct";+ /** Unvalidated search text, editable in either invitation method. */+ initialValue?: string;}type InviteRole = "member" | "admin";@@ -78,6 +80,7 @@ export function InviteMemberModal({manageGrants = false,onNotice,initialMode,+ initialValue = "",}: InviteMemberModalProps) {const { t } = useTranslation();const { tier } = useTier();@@ -100,7 +103,12 @@ export function InviteMemberModal({// SaaS offers email; self-hosted also offers email once SMTP + invites are configured.const directAvailable = canDirectCreate;const emailAvailable = canEmailInvite;- const preferredMode: Mode = directAvailable ? "direct" : "email";+ const preferredMode: Mode =+ emailAvailable && EMAIL_RE.test(initialValue.trim())+ ? "email"+ : directAvailable+ ? "direct"+ : "email";useEffect(() => {if (!open) return;@@ -194,6 +202,14 @@ export function InviteMemberModal({const resetTimerRef = useRef<number | null>(null);+ useEffect(() => {+ if (!open) return;+ if (resetTimerRef.current !== null)+ window.clearTimeout(resetTimerRef.current);+ setEmail(initialValue);+ setUsername(initialValue);+ }, [open, initialValue]);+useEffect(() => {return () => {if (resetTimerRef.current !== null) {diff --git a/frontend/editor/src/portal/components/users/InviteTeammateFlow.test.tsx b/frontend/editor/src/portal/components/users/InviteTeammateFlow.test.tsxnew file mode 100644index 0000000000..4acb90ca67--- /dev/null+++ b/frontend/editor/src/portal/components/users/InviteTeammateFlow.test.tsx@@ -0,0 +1,173 @@+import { beforeEach, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { InviteTeammateForm } from "@portal/components/users/InviteTeammateFlow";+import { createMember } from "@portal/api/users";+import { usersBackend } from "@app/portal/usersBackend";++const state = vi.hoisted(() => ({+ admin: true,+ teamLead: false,+ email: false,+ direct: true,+ saas: false,+ loading: false,+ error: false,+ full: false,+ refresh: vi.fn(),+}));+vi.mock("@portal/components/settings/PortalRosterHost", () => ({+ PortalRosterHost: () => null,+}));+vi.mock("@portal/contexts/TierContext", () => ({+ useTier: () => ({ tier: "free" }),+}));+vi.mock("@app/portal/usersCapabilities", () => ({+ usersCapabilities: {+ get listingRequiresAdmin() {+ return !state.saas;+ },+ get directCreate() {+ return !state.saas;+ },+ get adminRole() {+ return !state.saas;+ },+ emailInvite: true,+ },+}));+vi.mock("@portal/views/usersData", () => ({+ useUsersData: () => ({+ usersState: {+ loading: state.loading,+ error: state.error ? new Error("offline") : null,+ data: {+ members: [+ {+ id: "1",+ isSelf: true,+ role: state.admin ? "admin" : "member",+ teamLead: state.teamLead,+ teamId: 7,+ },+ ],+ emailInvitesEnabled: state.email,+ summary: { seatsUsed: 1, seatLimit: state.full ? 1 : null },+ },+ },+ teamsState: {+ loading: false,+ error: null,+ data: [{ id: 7, name: "Legal", userCount: 1, owners: [] }],+ },+ authState: {+ loading: false,+ error: null,+ data: { canDirectCreate: state.direct, hasOauth: false, hasSaml: false },+ },+ refresh: state.refresh,+ }),+}));+vi.mock("@portal/api/users", () => ({+ createMember: vi.fn().mockResolvedValue("alex"),+ fetchUsers: vi.fn(),+ ROLE_LABEL: { member: "Member", admin: "Admin" },+}));+vi.mock("@app/portal/usersBackend", () => ({+ usersBackend: { inviteMember: vi.fn().mockResolvedValue({}) },+}));+vi.mock("@portal/api/access", () => ({ createGrant: vi.fn() }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string) => fallback ?? key,+ }),+}));++beforeEach(() => {+ vi.clearAllMocks();+ Object.assign(state, {+ admin: true,+ teamLead: false,+ email: false,+ direct: true,+ saas: false,+ loading: false,+ error: false,+ full: false,+ });+});+function show(initialValue = "alex") {+ const onInvited = vi.fn();+ const onClose = vi.fn();+ render(+ <MantineProvider env="test">+ <InviteTeammateForm+ initialValue={initialValue}+ onInvited={onInvited}+ onClose={onClose}+ />+ </MantineProvider>,+ );+ return { onInvited, onClose };+}++it("creates a self-hosted account in the current team and refreshes the signing picker", async () => {+ const { onInvited, onClose } = show();+ expect(screen.getByRole("textbox", { name: /Username/ })).toHaveValue("alex");+ fireEvent.change(screen.getByLabelText(/Password/), {+ target: { value: "test-only-password" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Create account" }));+ await waitFor(() =>+ expect(createMember).toHaveBeenCalledWith(+ expect.objectContaining({ username: "alex", teamId: 7, role: "member" }),+ ),+ );+ expect(onInvited).toHaveBeenCalledOnce();+ expect(onClose).toHaveBeenCalledOnce();+ expect(state.refresh).toHaveBeenCalledOnce();+ expect(usersBackend.inviteMember).not.toHaveBeenCalled();+});++it("uses SaaS team invitations even when self-hosted mail is disabled", async () => {+ Object.assign(state, {+ saas: true,+ admin: false,+ teamLead: true,+ direct: false,+ });+ const { onInvited } = show("[email protected]");+ expect(screen.getByRole("textbox", { name: /Email address/ })).toHaveValue(+ "[email protected]",+ );+ expect(screen.queryByLabelText(/Password/)).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Send invite" }));+ await waitFor(() =>+ expect(usersBackend.inviteMember).toHaveBeenCalledWith(+ "[email protected]",+ "member",+ 7,+ ),+ );+ expect(createMember).not.toHaveBeenCalled();+ expect(onInvited).toHaveBeenCalledOnce();+});++it.each(["loading", "error", "full", "member", "disabled"])(+ "prevents invitation when %s",+ (condition) => {+ if (condition === "member") state.admin = false;+ else if (condition === "disabled") state.direct = false;+ else if (condition === "loading") state.loading = true;+ else if (condition === "error") state.error = true;+ else state.full = true;+ const { onClose } = show();+ expect(+ screen.queryByRole("button", { name: /Create account|Send invite/ }),+ ).not.toBeInTheDocument();+ expect(createMember).not.toHaveBeenCalled();+ expect(usersBackend.inviteMember).not.toHaveBeenCalled();+ fireEvent.click(screen.getAllByRole("button", { name: "Close" })[0]);+ expect(onClose).toHaveBeenCalledOnce();+ },+);diff --git a/frontend/editor/src/portal/components/users/InviteTeammateFlow.tsx b/frontend/editor/src/portal/components/users/InviteTeammateFlow.tsxnew file mode 100644index 0000000000..2066dcc02a--- /dev/null+++ b/frontend/editor/src/portal/components/users/InviteTeammateFlow.tsx@@ -0,0 +1,99 @@+import { useTranslation } from "react-i18next";+import { Button, Modal } from "@app/ui";+import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";+import { PortalRosterHost } from "@portal/components/settings/PortalRosterHost";+import { useUsersData } from "@portal/views/usersData";+import { usersCapabilities as caps } from "@app/portal/usersCapabilities";++interface InviteTeammateFlowProps {+ initialValue: string;+ onClose: () => void;+ onInvited: () => void;+}++/** Requires roster providers; only offers methods permitted by the loaded account and server. */+export function InviteTeammateForm({+ initialValue,+ onClose,+ onInvited,+}: InviteTeammateFlowProps) {+ const { t } = useTranslation();+ const { usersState, teamsState, authState, refresh } = useUsersData();+ const loading = usersState.loading || teamsState.loading || authState.loading;+ const error = usersState.error || teamsState.error || authState.error;+ const viewer = usersState.data?.members.find((member) => member.isSelf);+ const canManage =+ viewer?.role === "admin" ||+ (!caps.listingRequiresAdmin && viewer?.teamLead === true);+ const canDirectCreate =+ canManage && caps.directCreate && authState.data?.canDirectCreate === true;+ const canEmailInvite =+ canManage &&+ caps.emailInvite &&+ (!caps.directCreate || usersState.data?.emailInvitesEnabled === true);+ const summary = usersState.data?.summary;+ const seatsFull =+ summary?.seatLimit != null && summary.seatsUsed >= summary.seatLimit;++ if (loading || error || (!canDirectCreate && !canEmailInvite) || seatsFull) {+ return (+ <Modal+ open+ onClose={onClose}+ title={t("signWorkspace.inviteTeammate", "Add a teammate")}+ >+ {loading ? (+ <p role="status">{t("common.loading", "Loading...")}</p>+ ) : (+ <p role="alert">+ {error+ ? t(+ "signWorkspace.inviteLoadError",+ "Could not load invitation options. Close this dialog and try again.",+ )+ : seatsFull+ ? t(+ "users.seats.full",+ "Every licensed seat is in use. Free one up, or raise the seat count, to add anyone else.",+ )+ : t(+ "signWorkspace.inviteUnavailable",+ "Adding teammates is not available for your account or server configuration.",+ )}+ </p>+ )}+ <Button variant="secondary" onClick={onClose}>+ {t("common.close", "Close")}+ </Button>+ </Modal>+ );+ }++ return (+ <InviteMemberModal+ open+ onClose={onClose}+ onInvited={() => {+ refresh();+ onInvited();+ }}+ initialValue={initialValue}+ teams={teamsState.data ?? []}+ defaultTeamId={viewer?.teamId}+ canDirectCreate={canDirectCreate}+ canEmailInvite={canEmailInvite}+ hasOauth={authState.data?.hasOauth}+ hasSaml={authState.data?.hasSaml}+ adminRole={caps.adminRole}+ />+ );+}++/** Reuses the roster's deployment adapters without navigating away from the request. */+export default function InviteTeammateFlow(props: InviteTeammateFlowProps) {+ return (+ <PortalRosterHost>+ <InviteTeammateForm {...props} />+ </PortalRosterHost>+ );+}diff --git a/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx b/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsxindex 0dc2384392..04b4e094bc 100644--- a/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx+++ b/frontend/editor/src/proprietary/components/notifications/notificationActions.test.tsx@@ -393,13 +393,14 @@ describe("useNotificationActions", () => {it("says it cannot hand the document over rather than navigating to nothing", async () => {// Spied on the prototype: jsdom's storage is a proxy, so an own-property spy does not take.const setItem = vi- .spyOn(Storage.prototype, "setItem")+ .spyOn(Object.getPrototypeOf(window.sessionStorage), "setItem").mockImplementation(() => {throw new Error("denied");});const outcome = await registry(inProcessor).VIEW_FILE?.run(context());+ expect(setItem).toHaveBeenCalledOnce();expect(outcome).toEqual({ok: false,message:diff --git a/frontend/editor/src/proprietary/components/shared/InviteTeammateButton.test.tsx b/frontend/editor/src/proprietary/components/shared/InviteTeammateButton.test.tsxnew file mode 100644index 0000000000..7174b54b46--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/InviteTeammateButton.test.tsx@@ -0,0 +1,141 @@+import { useState } from "react";+import { beforeEach, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import UserSelector from "@app/components/shared/UserSelector";+import { fetchUsers } from "@app/api/users";+import { qk } from "@app/query/keys";++const auth = vi.hoisted(() => ({+ isAdmin: true,+ isTeamLeader: false,+ isAnonymous: false,+}));+vi.mock("@app/auth/UseSession", () => ({+ useAuth: () => ({ ...auth, loading: false, user: { id: "1" } }),+}));+vi.mock("@app/contexts/SaaSTeamContext", () => ({ useSaaSTeam: () => auth }));+vi.mock("@app/api/users", () => ({ fetchUsers: vi.fn() }));+vi.mock("@portal/components/users/InviteTeammateFlow", () => ({+ default: ({+ initialValue,+ onClose,+ onInvited,+ }: {+ initialValue: string;+ onClose: () => void;+ onInvited: () => void;+ }) => (+ <div role="dialog" aria-label="Invite teammate">+ <input aria-label="Invite value" value={initialValue} readOnly />+ <button onClick={onClose}>Cancel invite</button>+ <button+ onClick={() => {+ onInvited();+ onClose();+ }}+ >+ Complete invite+ </button>+ </div>+ ),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback?: string, values?: Record<string, string>) =>+ (fallback ?? key).replace("{{name}}", values?.name ?? ""),+ }),+}));++const people = [+ {+ userId: 1,+ username: "owner",+ displayName: "Owner",+ teamName: "Default",+ enabled: true,+ },+];+function Picker({ disabled }: { disabled: boolean }) {+ const [value, setValue] = useState([1]);+ return (+ <UserSelector+ presentation="cards"+ value={value}+ onChange={setValue}+ disabled={disabled}+ />+ );+}+function show(disabled = false, users = people) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },+ });+ client.setQueryData(qk.users(), users);+ return render(+ <QueryClientProvider client={client}>+ <MantineProvider env="test">+ <Picker disabled={disabled} />+ </MantineProvider>+ </QueryClientProvider>,+ );+}+beforeEach(() => {+ vi.clearAllMocks();+ auth.isAdmin = true;+ auth.isTeamLeader = false;+ auth.isAnonymous = false;+ vi.mocked(fetchUsers).mockResolvedValue(people);+});++it("carries arbitrary search text into the invite flow and retains selected participants on cancel", async () => {+ show();+ fireEvent.change(+ screen.getByRole("textbox", { name: "Search people or teams" }),+ { target: { value: "Alex + team & friends" } },+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Add teammate: Alex + team & friends" }),+ );+ expect(await screen.findByLabelText("Invite value")).toHaveValue(+ "Alex + team & friends",+ );+ fireEvent.click(screen.getByRole("button", { name: "Cancel invite" }));+ expect(+ screen.getByRole("textbox", { name: "Search people or teams" }),+ ).toHaveValue("Alex + team & friends");+ fireEvent.change(+ screen.getByRole("textbox", { name: "Search people or teams" }),+ { target: { value: "" } },+ );+ expect(screen.getByRole("checkbox", { name: /Owner/ })).toBeChecked();+ expect(fetchUsers).not.toHaveBeenCalled();+});++it("offers an empty invite even with no participants and refreshes after success", async () => {+ show(false, []);+ fireEvent.click(screen.getByRole("button", { name: "Add a teammate" }));+ expect(await screen.findByLabelText("Invite value")).toHaveValue("");+ fireEvent.click(screen.getByRole("button", { name: "Complete invite" }));+ await waitFor(() => expect(fetchUsers).toHaveBeenCalledOnce());+ expect(await screen.findByRole("checkbox", { name: /Owner/ })).toBeChecked();+});++it("offers invites to team leaders but not ordinary members or guests", () => {+ auth.isAdmin = false;+ const member = show();+ expect(+ screen.queryByRole("button", { name: "Add a teammate" }),+ ).not.toBeInTheDocument();+ member.unmount();+ auth.isTeamLeader = true;+ const leader = show(true);+ expect(screen.getByRole("button", { name: "Add a teammate" })).toBeDisabled();+ leader.unmount();+ auth.isAnonymous = true;+ show();+ expect(+ screen.queryByRole("button", { name: "Add a teammate" }),+ ).not.toBeInTheDocument();+});diff --git a/frontend/editor/src/proprietary/components/shared/InviteTeammateButton.tsx b/frontend/editor/src/proprietary/components/shared/InviteTeammateButton.tsxnew file mode 100644index 0000000000..72fb6530b7--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/InviteTeammateButton.tsx@@ -0,0 +1,63 @@+import { lazy, Suspense, useState } from "react";+import { useTranslation } from "react-i18next";+import type { InviteTeammateButtonProps } from "@core/components/shared/InviteTeammateButton";+import { useAuth } from "@app/auth/UseSession";+import { useSaaSTeam } from "@app/contexts/SaaSTeamContext";+import { Button, Modal } from "@app/ui";+import { Icon } from "@app/ui/Icon";++const InviteTeammateFlow = lazy(+ () => import("@portal/components/users/InviteTeammateFlow"),+);++/** Keeps the signing draft mounted while the deployment's account flow is open. */+export function InviteTeammateButton({+ search,+ disabled,+ onInvited,+}: InviteTeammateButtonProps) {+ const { t } = useTranslation();+ const { isAdmin, isAnonymous, loading } = useAuth();+ const { isTeamLeader } = useSaaSTeam();+ const [inviteValue, setInviteValue] = useState<string | null>(null);+ if (loading || isAnonymous || (!isAdmin && !isTeamLeader)) return null;++ const close = () => setInviteValue(null);+ return (+ <>+ <Button+ variant="secondary"+ fullWidth+ overflow="wrap"+ disabled={disabled}+ leftSection={<Icon name="user-plus" size={18} />}+ onClick={() => setInviteValue(search.trim())}+ >+ {search.trim()+ ? t("signWorkspace.invitePerson", "Add teammate: {{name}}", {+ name: search.trim(),+ })+ : t("signWorkspace.inviteTeammate", "Add a teammate")}+ </Button>+ {inviteValue !== null && (+ <Suspense+ fallback={+ <Modal+ open+ onClose={close}+ title={t("signWorkspace.inviteTeammate", "Add a teammate")}+ >+ <p role="status">{t("common.loading", "Loading...")}</p>+ </Modal>+ }+ >+ <InviteTeammateFlow+ initialValue={inviteValue}+ onClose={close}+ onInvited={onInvited}+ />+ </Suspense>+ )}+ </>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.tsxindex c99fa2dcf8..fbd84d6e0b 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/AdminSystemSection.tsx@@ -471,11 +471,6 @@ export default function AdminSystemSection() {"admin.settings.storage.description","Where files are stored, and whether people can share them by link or email.",)}- badge={- <Badge component="span" color="orange" size="sm">- {t("toolPanel.alpha", "Alpha")}- </Badge>- }><StorageSharingCardsettings={storage}@@ -549,21 +544,6 @@ export default function AdminSystemSection() {"admin.settings.features.serverCertificate.description",'Generate the certificate that backs the "Sign with Stirling-PDF" signing feature.',)}- badge={- <Badge- component="span"- color="grape"- size="sm"- style={{ cursor: "pointer" }}- onClick={() => navigate("/settings/adminPlan")}- title={t(- "admin.settings.badge.clickToUpgrade",- "Click to view plan details",- )}- >- PRO- </Badge>- }><ServerCertificateCard {...generalCard} /></SettingsCard>diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/server/StorageSharingCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/server/StorageSharingCard.tsxindex 976f148c78..b03d97df86 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/server/StorageSharingCard.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/server/StorageSharingCard.tsx@@ -159,7 +159,7 @@ export function StorageSharingCard({<SettingsToggleRowlabel={t(- "admin.settings.storage.signing.enabled.label",+ "admin.settings.storage.signing.enabled.title","Enable Group Signing",)}info={t(diff --git a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx b/frontend/editor/src/proprietary/components/viewer/Viewer.tsxindex 414c13b018..731ca4bd3c 100644--- a/frontend/editor/src/proprietary/components/viewer/Viewer.tsx+++ b/frontend/editor/src/proprietary/components/viewer/Viewer.tsx@@ -14,6 +14,7 @@ import { PolicyEnforcementOverlay } from "@app/components/viewer/PolicyEnforcemetype SignatureOverlayPassThrough = Pick<EmbedPdfViewerProps,| "signaturePreviews"+ | "readOnlySignaturePreviews"| "signaturePreviewsReadOnly"| "signaturePlacementMode"| "signaturePlacementData"