#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
Rank recommended tools from real usage (#7395)
Anthony Stirling491617efbf18
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 485320d39c..4a49f61dd7 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@@ -64,6 +64,7 @@ public class ApplicationProperties {private Ui ui = new Ui();private Endpoints endpoints = new Endpoints();private Metrics metrics = new Metrics();+ private ToolRecommendations toolRecommendations = new ToolRecommendations();private AutomaticallyGenerated automaticallyGenerated = new AutomaticallyGenerated();private Mail mail = new Mail();@@ -1595,6 +1596,37 @@ public class ApplicationProperties {private boolean enabled = true;}+ @Data+ public static class ToolRecommendations {+ // Extra off-switch on top of system.enableAnalytics, which must also consent to tracking.+ private boolean enabled = true;+ // How long usage and workflow rollups are kept before the retention sweep removes them.+ private int retentionDays = 180;+ // Scoring lookback window; events in the recent window count double.+ private int windowDays = 30;+ private int recentWindowDays = 7;++ // The getters below clamp rather than reject: a mistyped window should narrow the ranking,+ // never stop the app booting.++ public int getWindowDays() {+ return Math.max(1, windowDays);+ }++ /** Beyond the scoring window every event would be "recent", which says nothing. */+ public int getRecentWindowDays() {+ return Math.min(Math.max(0, recentWindowDays), getWindowDays());+ }++ /**+ * Zero or less disables the sweep. Otherwise it never runs inside the scoring window, so+ * retention cannot delete the days the ranking is still reading.+ */+ public int getRetentionDays() {+ return retentionDays <= 0 ? retentionDays : Math.max(retentionDays, getWindowDays());+ }+ }+@Datapublic static class AutomaticallyGenerated {@ToString.Exclude private String key;diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex e7a6057a8c..f096b0ad72 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -328,6 +328,12 @@ endpoints:metrics:enabled: true # 'true' to enable Info APIs (`/api/*`) endpoints, 'false' to disable+toolRecommendations:+ enabled: true # 'true' to rank the recommended-tools list from real usage (per user, team and install) and record which tool sequences get applied to a document; 'false' keeps the static list and records nothing. Also requires system.enableAnalytics: true, since usage is recorded per user. Nothing is recorded when security.enableLogin is 'false', since there is no user to attribute a run to+ retentionDays: 180 # days of daily usage and workflow rollups to keep before the retention sweep removes them; 0 or less never sweeps, and anything below windowDays is raised to it+ windowDays: 30 # scoring lookback window in days+ recentWindowDays: 7 # events within this many days count double when scoring; capped at windowDays+# Automatically Generated Settings (Do Not Edit Directly)# Generated on first boot and written back here. In a cluster EVERY node must carry the SAME key and# UUID (env: AUTOMATICALLYGENERATED_KEY / AUTOMATICALLYGENERATED_UUID) or nodes cannot read each other's data.diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ToolRecommendationController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ToolRecommendationController.javanew file mode 100644index 0000000000..b34364fec8--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ToolRecommendationController.java@@ -0,0 +1,104 @@+package stirling.software.proprietary.controller.api;++import java.util.List;+import java.util.Optional;++import org.springframework.http.HttpStatus;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.GetMapping;+import org.springframework.web.bind.annotation.PostMapping;+import org.springframework.web.bind.annotation.RequestBody;+import org.springframework.web.bind.annotation.RequestParam;++import io.swagger.v3.oas.annotations.Operation;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.annotations.api.ProprietaryUiDataApi;+import stirling.software.common.service.UserServiceInterface;+import stirling.software.proprietary.service.ToolRecommendationService;+import stirling.software.proprietary.service.ToolRecommendationService.ToolRecommendation;+import stirling.software.proprietary.service.ToolUsageTrackingService;++/**+ * Records tool completions and serves the dynamic "recommended tools" list. Available on every+ * license tier, and only ever for a user the server itself authenticated.+ *+ * <p>With login disabled there is no such user, so both endpoints answer 501 and the browser falls+ * back to the curated list. Keying rows on a browser-declared identity instead would hand an+ * unauthenticated caller an unbounded set of principals to write rows under, and the ranking it+ * bought would be per-browser anyway - which is what the curated list already gives for free.+ */+@Slf4j+@ProprietaryUiDataApi+@RequiredArgsConstructor+public class ToolRecommendationController {++ private final ToolUsageTrackingService trackingService;+ private final ToolRecommendationService recommendationService;+ private final Optional<UserServiceInterface> userService;++ public record RecommendationsResponse(List<ToolRecommendation> recommendations) {}++ /**+ * @param priorChains the tools already applied to each input document, oldest step first and+ * excluding this run - one entry per input document, empty for a fresh upload.+ */+ public record UsageRequest(String toolKey, List<List<String>> priorChains) {}++ @GetMapping("/tool-recommendations")+ @Operation(+ summary = "Get recommended tools",+ description =+ "Returns tools ranked by usage patterns: what this user, their team, and the"+ + " whole install use, weighted towards what typically follows the"+ + " current tool. Answers 501 when the install records no usage, or"+ + " when login is disabled and there is no user to rank for.")+ public ResponseEntity<RecommendationsResponse> getRecommendations(+ @RequestParam(value = "currentTool", required = false) String currentTool,+ @RequestParam(value = "limit", defaultValue = "6") int limit) {+ String principal = currentPrincipal();+ if (principal == null || !trackingService.isRecordingEnabled()) {+ return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).build();+ }+ String context = trackingService.isKnownToolKey(currentTool) ? currentTool : null;+ try {+ return ResponseEntity.ok(+ new RecommendationsResponse(+ recommendationService.getRecommendations(principal, context, limit)));+ } catch (Exception e) {+ // Recommendations are advisory; never break the UI over them.+ log.warn("Failed to compute tool recommendations: {}", e.getMessage());+ return ResponseEntity.ok(new RecommendationsResponse(List.of()));+ }+ }++ @PostMapping("/tool-recommendations/usage")+ @Operation(+ summary = "Record a completed tool run",+ description =+ "Safe to call fire-and-forget after every tool completion. priorChains carries"+ + " what each input document had already been through, so transitions"+ + " and workflows follow the file rather than the click order.")+ public ResponseEntity<Void> recordUsage(@RequestBody UsageRequest request) {+ if (request == null || !trackingService.isKnownToolKey(request.toolKey())) {+ return ResponseEntity.badRequest().build();+ }+ String principal = currentPrincipal();+ if (principal == null || !trackingService.isRecordingEnabled()) {+ // 501 latches the client, so an install that records nothing stops receiving posts.+ return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).build();+ }+ trackingService.recordUsage(principal, request.toolKey(), request.priorChains());+ return ResponseEntity.noContent().build();+ }++ /** The authenticated username, or null when nobody is signed in. */+ private String currentPrincipal() {+ return userService+ .map(UserServiceInterface::getCurrentUsername)+ .filter(name -> !name.isBlank() && !"anonymousUser".equals(name))+ .orElse(null);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolChainStat.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolChainStat.javanew file mode 100644index 0000000000..f302eb9d22--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolChainStat.java@@ -0,0 +1,96 @@+package stirling.software.proprietary.model;++import java.io.Serializable;+import java.util.List;++import jakarta.persistence.Column;+import jakarta.persistence.Entity;+import jakarta.persistence.Id;+import jakarta.persistence.IdClass;+import jakarta.persistence.Index;+import jakarta.persistence.Table;++import lombok.Getter;+import lombok.NoArgsConstructor;+import lombok.Setter;++/**+ * One UTC day's tally of an ordered sequence of tools applied to a single document. Where {@link+ * ToolUsageStat} only remembers the step before, this remembers the whole path a document took, so+ * a repeated end-to-end workflow ("compress, then watermark, then add a password") is visible as+ * one recurring chain rather than a scatter of pairs.+ *+ * <p>Chains are recorded as prefixes: a document that reaches step three has also been counted at+ * steps one and two, so {@code count} reads as "documents that got at least this far".+ */+@Entity+@Table(+ name = "tool_chain_stats",+ indexes = {+ @Index(name = "idx_tool_chain_day", columnList = "epoch_day"),+ @Index(name = "idx_tool_chain_principal_day", columnList = "principal, epoch_day"),+ @Index(name = "idx_tool_chain_length_day", columnList = "chain_length, epoch_day")+ })+@IdClass(ToolChainStatId.class)+@Getter+@Setter+@NoArgsConstructor+public class ToolChainStat implements Serializable {++ private static final long serialVersionUID = 1L;++ /** Cannot occur inside a tool key, which is restricted to letters, digits, {@code _} and -. */+ public static final String SEPARATOR = ">";++ /** Bounds the primary key; longer chains are recorded as their trailing window. */+ public static final int MAX_CHAIN_TOOLS = 8;++ /**+ * Comfortably clear of the longest chain the tool registry can produce - eight keys of at most+ * {@code ToolKeyRegistry.MAX_KEY_LENGTH} characters is nearer 160 - so a chain built from known+ * keys always stores. Tool keys are ASCII, so this is also the byte length, and the composite+ * key stays far inside Postgres's index-entry limit.+ */+ public static final int MAX_CHAIN_KEY_LENGTH = 520;++ @Id+ @Column(name = "principal", length = 255)+ private String principal;++ /** The ordered tool keys joined by {@link #SEPARATOR}, oldest step first. */+ @Id+ @Column(name = "chain_key", length = MAX_CHAIN_KEY_LENGTH)+ private String chainKey;++ @Id+ @Column(name = "epoch_day")+ private long epochDay;++ /**+ * Denormalised so "chains of at least N steps" is an indexed read rather than a string scan.+ */+ @Column(name = "chain_length")+ private int chainLength;++ @Column(name = "count")+ private long count;++ public ToolChainStat(+ String principal, String chainKey, long epochDay, int chainLength, long count) {+ this.principal = principal;+ this.chainKey = chainKey;+ this.epochDay = epochDay;+ this.chainLength = chainLength;+ this.count = count;+ }++ public static String toChainKey(List<String> tools) {+ return String.join(SEPARATOR, tools);+ }++ public static List<String> fromChainKey(String chainKey) {+ return chainKey == null || chainKey.isEmpty()+ ? List.of()+ : List.of(chainKey.split(SEPARATOR));+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolChainStatId.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolChainStatId.javanew file mode 100644index 0000000000..35a4689dec--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolChainStatId.java@@ -0,0 +1,19 @@+package stirling.software.proprietary.model;++import java.io.Serializable;++import lombok.AllArgsConstructor;+import lombok.Data;+import lombok.NoArgsConstructor;++@Data+@NoArgsConstructor+@AllArgsConstructor+public class ToolChainStatId implements Serializable {++ private static final long serialVersionUID = 1L;++ private String principal;+ private String chainKey;+ private long epochDay;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolUsageStat.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolUsageStat.javanew file mode 100644index 0000000000..0404d15604--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolUsageStat.java@@ -0,0 +1,72 @@+package stirling.software.proprietary.model;++import java.io.Serializable;++import jakarta.persistence.Column;+import jakarta.persistence.Entity;+import jakarta.persistence.Id;+import jakarta.persistence.IdClass;+import jakarta.persistence.Index;+import jakarta.persistence.Table;++import lombok.Getter;+import lombok.NoArgsConstructor;+import lombok.Setter;++/**+ * One UTC day's tally of "this principal ran toolKey, having just come from fromTool". Frequency is+ * this table grouped by tool; transitions are it filtered by fromTool - so one row per completion+ * serves both recommendation signals, and a busy day stays a handful of rows rather than thousands.+ *+ * <p>{@link #NO_PREVIOUS_TOOL} marks a run with no distinct predecessor. It is the empty string,+ * which no valid tool key can be.+ *+ * <p>{@code principal} is always a username the server authenticated. Nothing is recorded for a+ * caller the server cannot name, so rows here are never client-declared identities.+ */+@Entity+@Table(+ name = "tool_usage_stats",+ indexes = {+ @Index(name = "idx_tool_usage_day", columnList = "epoch_day"),+ @Index(name = "idx_tool_usage_principal_day", columnList = "principal, epoch_day"),+ @Index(name = "idx_tool_usage_from_day", columnList = "from_tool, epoch_day")+ })+@IdClass(ToolUsageStatId.class)+@Getter+@Setter+@NoArgsConstructor+public class ToolUsageStat implements Serializable {++ private static final long serialVersionUID = 1L;++ public static final String NO_PREVIOUS_TOOL = "";++ @Id+ @Column(name = "principal", length = 255)+ private String principal;++ @Id+ @Column(name = "from_tool", length = 64)+ private String fromTool;++ @Id+ @Column(name = "tool_key", length = 64)+ private String toolKey;++ @Id+ @Column(name = "epoch_day")+ private long epochDay;++ @Column(name = "count")+ private long count;++ public ToolUsageStat(+ String principal, String fromTool, String toolKey, long epochDay, long count) {+ this.principal = principal;+ this.fromTool = fromTool;+ this.toolKey = toolKey;+ this.epochDay = epochDay;+ this.count = count;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolUsageStatId.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolUsageStatId.javanew file mode 100644index 0000000000..0baabf267b--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/ToolUsageStatId.java@@ -0,0 +1,20 @@+package stirling.software.proprietary.model;++import java.io.Serializable;++import lombok.AllArgsConstructor;+import lombok.Data;+import lombok.NoArgsConstructor;++@Data+@NoArgsConstructor+@AllArgsConstructor+public class ToolUsageStatId implements Serializable {++ private static final long serialVersionUID = 1L;++ private String principal;+ private String fromTool;+ private String toolKey;+ private long epochDay;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepository.javanew file mode 100644index 0000000000..35987f0211--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolChainStatRepository.java@@ -0,0 +1,98 @@+package stirling.software.proprietary.repository;++import java.util.Collection;+import java.util.List;++import org.springframework.data.domain.Pageable;+import org.springframework.data.jpa.repository.JpaRepository;+import org.springframework.data.jpa.repository.Modifying;+import org.springframework.data.jpa.repository.Query;+import org.springframework.data.repository.query.Param;+import org.springframework.stereotype.Repository;+import org.springframework.transaction.annotation.Transactional;++import stirling.software.proprietary.model.ToolChainStat;+import stirling.software.proprietary.model.ToolChainStatId;++/**+ * Aggregates return rows of [chainKey, chainLength, totalCount] ordered by count, so the caller can+ * take the top N workflows without loading the table.+ */+@Repository+public interface ToolChainStatRepository extends JpaRepository<ToolChainStat, ToolChainStatId> {++ String SELECT_TOP =+ "SELECT c.chainKey, MAX(c.chainLength), SUM(c.count) FROM ToolChainStat c WHERE ";++ String GROUP_ORDER = " GROUP BY c.chainKey ORDER BY SUM(c.count) DESC, c.chainKey ASC";++ @Query(+ SELECT_TOP+ + "c.principal = :principal AND c.epochDay >= :cutoff "+ + "AND c.chainLength >= :minLength"+ + GROUP_ORDER)+ List<Object[]> topByPrincipal(+ @Param("principal") String principal,+ @Param("cutoff") long cutoff,+ @Param("minLength") int minLength,+ Pageable pageable);++ @Query(+ SELECT_TOP+ + "c.principal IN :principals AND c.epochDay >= :cutoff "+ + "AND c.chainLength >= :minLength"+ + GROUP_ORDER)+ List<Object[]> topByPrincipals(+ @Param("principals") Collection<String> principals,+ @Param("cutoff") long cutoff,+ @Param("minLength") int minLength,+ Pageable pageable);++ @Query(SELECT_TOP + "c.epochDay >= :cutoff AND c.chainLength >= :minLength" + GROUP_ORDER)+ List<Object[]> topGlobal(+ @Param("cutoff") long cutoff, @Param("minLength") int minLength, Pageable pageable);++ /** Returns 0 when today's row does not exist yet, telling the caller to insert it. */+ @Modifying(clearAutomatically = true)+ @Transactional+ @Query(+ "UPDATE ToolChainStat c SET c.count = c.count + :delta "+ + "WHERE c.principal = :principal AND c.chainKey = :chainKey "+ + "AND c.epochDay = :epochDay")+ int incrementCount(+ @Param("principal") String principal,+ @Param("chainKey") String chainKey,+ @Param("epochDay") long epochDay,+ @Param("delta") long delta);++ /**+ * Native insert so a concurrent first-run-of-day loses the primary key race instead of silently+ * overwriting the winner - {@code save()} would merge, resetting their count.+ */+ @Modifying(clearAutomatically = true)+ @Transactional+ @Query(+ value =+ "INSERT INTO tool_chain_stats (principal, chain_key, epoch_day, chain_length,"+ + " count) VALUES (:principal, :chainKey, :epochDay, :chainLength,"+ + " :delta)",+ nativeQuery = true)+ void insertCount(+ @Param("principal") String principal,+ @Param("chainKey") String chainKey,+ @Param("epochDay") long epochDay,+ @Param("chainLength") int chainLength,+ @Param("delta") long delta);++ @Modifying(clearAutomatically = true)+ @Transactional+ @Query("DELETE FROM ToolChainStat c WHERE c.epochDay < :cutoff")+ int deleteOlderThan(@Param("cutoff") long cutoff);++ // Erasure: rows key on the raw username, so a recreated name would inherit the history.+ // No clearAutomatically: a clear would detach the User deleteUser deletes right after this.+ @Modifying+ @Transactional+ @Query("DELETE FROM ToolChainStat c WHERE c.principal = :principal")+ int deleteByPrincipal(@Param("principal") String principal);+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepository.javanew file mode 100644index 0000000000..d45e27a74e--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/repository/ToolUsageStatRepository.java@@ -0,0 +1,126 @@+package stirling.software.proprietary.repository;++import java.util.Collection;+import java.util.List;++import org.springframework.data.jpa.repository.JpaRepository;+import org.springframework.data.jpa.repository.Modifying;+import org.springframework.data.jpa.repository.Query;+import org.springframework.data.repository.query.Param;+import org.springframework.stereotype.Repository;+import org.springframework.transaction.annotation.Transactional;++import stirling.software.proprietary.model.ToolUsageStat;+import stirling.software.proprietary.model.ToolUsageStatId;++/**+ * Frequency aggregates return rows of [toolKey, recentCount, totalCount] over the scoring window,+ * so callers can weight recent activity without a second query.+ *+ * <p>Transition aggregates deliberately do not filter on the tool asked about. They return the+ * whole [fromTool, toolKey, recentCount, totalCount] matrix for the window, so one scan answers+ * "what follows X" for every X. Filtering per source tool would mean one scan - and one cache entry+ * - per distinct value a caller asks about, which is a scan the caller gets to trigger.+ */+@Repository+public interface ToolUsageStatRepository extends JpaRepository<ToolUsageStat, ToolUsageStatId> {++ String RECENT = "SUM(CASE WHEN s.epochDay >= :recentCutoff THEN s.count ELSE 0 END), ";++ String SELECT_TOTALS =+ "SELECT s.toolKey, " + RECENT + "SUM(s.count) FROM ToolUsageStat s WHERE ";++ String GROUP = " GROUP BY s.toolKey";++ String SELECT_EDGES =+ "SELECT s.fromTool, s.toolKey, " + RECENT + "SUM(s.count) FROM ToolUsageStat s WHERE ";++ /** Rows with no predecessor are frequency, not transitions, and would never be looked up. */+ String HAS_SOURCE = "s.fromTool <> '' AND ";++ String GROUP_EDGES = " GROUP BY s.fromTool, s.toolKey";++ @Query(SELECT_TOTALS + "s.principal = :principal AND s.epochDay >= :cutoff" + GROUP)+ List<Object[]> sumByPrincipal(+ @Param("principal") String principal,+ @Param("cutoff") long cutoff,+ @Param("recentCutoff") long recentCutoff);++ @Query(SELECT_TOTALS + "s.principal IN :principals AND s.epochDay >= :cutoff" + GROUP)+ List<Object[]> sumByPrincipals(+ @Param("principals") Collection<String> principals,+ @Param("cutoff") long cutoff,+ @Param("recentCutoff") long recentCutoff);++ @Query(SELECT_TOTALS + "s.epochDay >= :cutoff" + GROUP)+ List<Object[]> sumGlobal(+ @Param("cutoff") long cutoff, @Param("recentCutoff") long recentCutoff);++ @Query(+ SELECT_EDGES+ + HAS_SOURCE+ + "s.principal = :principal AND s.epochDay >= :cutoff"+ + GROUP_EDGES)+ List<Object[]> edgesByPrincipal(+ @Param("principal") String principal,+ @Param("cutoff") long cutoff,+ @Param("recentCutoff") long recentCutoff);++ @Query(+ SELECT_EDGES+ + HAS_SOURCE+ + "s.principal IN :principals AND s.epochDay >= :cutoff"+ + GROUP_EDGES)+ List<Object[]> edgesByPrincipals(+ @Param("principals") Collection<String> principals,+ @Param("cutoff") long cutoff,+ @Param("recentCutoff") long recentCutoff);++ @Query(SELECT_EDGES + HAS_SOURCE + "s.epochDay >= :cutoff" + GROUP_EDGES)+ List<Object[]> edgesGlobal(+ @Param("cutoff") long cutoff, @Param("recentCutoff") long recentCutoff);++ /** Returns 0 when today's row does not exist yet, telling the caller to insert it. */+ @Modifying(clearAutomatically = true)+ @Transactional+ @Query(+ "UPDATE ToolUsageStat s SET s.count = s.count + :delta "+ + "WHERE s.principal = :principal AND s.fromTool = :fromTool "+ + "AND s.toolKey = :toolKey AND s.epochDay = :epochDay")+ int incrementCount(+ @Param("principal") String principal,+ @Param("fromTool") String fromTool,+ @Param("toolKey") String toolKey,+ @Param("epochDay") long epochDay,+ @Param("delta") long delta);++ /**+ * Native insert so a concurrent first-run-of-day loses the primary key race instead of silently+ * overwriting the winner - {@code save()} would merge, resetting their count.+ */+ @Modifying(clearAutomatically = true)+ @Transactional+ @Query(+ value =+ "INSERT INTO tool_usage_stats (principal, from_tool, tool_key, epoch_day,"+ + " count) VALUES (:principal, :fromTool, :toolKey, :epochDay, :delta)",+ nativeQuery = true)+ void insertCount(+ @Param("principal") String principal,+ @Param("fromTool") String fromTool,+ @Param("toolKey") String toolKey,+ @Param("epochDay") long epochDay,+ @Param("delta") long delta);++ @Modifying(clearAutomatically = true)+ @Transactional+ @Query("DELETE FROM ToolUsageStat s WHERE s.epochDay < :cutoff")+ int deleteOlderThan(@Param("cutoff") long cutoff);++ // Erasure: rows key on the raw username, so a recreated name would inherit the ranking.+ // No clearAutomatically: a clear would detach the User deleteUser deletes right after this.+ @Modifying+ @Transactional+ @Query("DELETE FROM ToolUsageStat s WHERE s.principal = :principal")+ int deleteByPrincipal(@Param("principal") String principal);+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.javaindex 2094d94d9b..32d6e9bbdb 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/database/repository/UserRepository.java@@ -7,6 +7,7 @@ import java.util.Optional;import java.util.UUID;import java.util.stream.Stream;+import org.springframework.data.domain.Pageable;import org.springframework.data.jpa.repository.EntityGraph;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Modifying;@@ -60,6 +61,13 @@ public interface UserRepository extends JpaRepository<User, Long> {"SELECT u FROM User u JOIN FETCH u.authorities JOIN FETCH u.team WHERE u.team.id = :teamId")List<User> findAllByTeamId(@Param("teamId") Long teamId);+ /** Usernames alone, ordered and limited by the database, for callers that need no entities. */+ @Query(+ "SELECT u.username FROM User u WHERE u.team.id IN :teamIds AND u.username IS NOT NULL"+ + " ORDER BY u.username")+ List<String> findUsernamesByTeamIds(+ @Param("teamIds") Collection<Long> teamIds, Pageable pageable);+long countByTeam(Team team);/** Count real users, excluding a reserved username such as the internal API user. */diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/TeamMembershipRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/TeamMembershipRepository.javaindex 2cfc12dd45..e530a94979 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/TeamMembershipRepository.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/repository/TeamMembershipRepository.java@@ -1,8 +1,10 @@package stirling.software.proprietary.security.repository;+import java.util.Collection;import java.util.List;import java.util.Optional;+import org.springframework.data.domain.Pageable;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Modifying;import org.springframework.data.jpa.repository.Query;@@ -42,6 +44,18 @@ public interface TeamMembershipRepository extends JpaRepository<TeamMembership,@Query("SELECT tm FROM TeamMembership tm JOIN FETCH tm.team WHERE tm.user.id = :userId")List<TeamMembership> findByUserId(@Param("userId") Long userId);+ /** Team ids alone, for callers that only need to know which rosters a user belongs to. */+ @Query(+ "SELECT tm.team.id FROM TeamMembership tm WHERE upper(tm.user.username) = upper(:username)")+ List<Long> findTeamIdsByUsername(@Param("username") String username);++ /** Usernames alone, ordered and limited by the database, for callers that need no entities. */+ @Query(+ "SELECT tm.user.username FROM TeamMembership tm WHERE tm.team.id IN :teamIds"+ + " AND tm.user.username IS NOT NULL ORDER BY tm.user.username")+ List<String> findUsernamesByTeamIds(+ @Param("teamIds") Collection<Long> teamIds, Pageable pageable);+/*** Find all members with a specific role in a team*diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.javaindex 71b6264ceb..622a919e3f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java@@ -48,6 +48,8 @@ import stirling.software.proprietary.access.repository.ResourceGrantRepository;import stirling.software.proprietary.integration.model.IntegrationConfig;import stirling.software.proprietary.integration.repository.IntegrationConfigRepository;import stirling.software.proprietary.model.Team;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;import stirling.software.proprietary.security.database.repository.AuthorityRepository;import stirling.software.proprietary.security.database.repository.PersistentLoginRepository;import stirling.software.proprietary.security.database.repository.UserRepository;@@ -102,6 +104,8 @@ public class UserService implements UserServiceInterface {private final IntegrationConfigRepository integrationConfigRepository;private final TeamMembershipService teamMembershipService;private final ApiKeyAuthenticationService apiKeyAuthenticationService;+ private final ToolUsageStatRepository toolUsageStatRepository;+ private final ToolChainStatRepository toolChainStatRepository;// ObjectProvider breaks the cycle: UserLicenseSettingsService injects this service to count// users, and saveUserCore needs it back to enforce the limit. Same pattern that service already@@ -276,6 +280,10 @@ public class UserService implements UserServiceInterface {private void deleteUserRelatedData(User user) {log.info("Deleting all associated data for user: {}", user.getUsername());+ // Tool usage keys on the username, so a recreated name would inherit it+ toolUsageStatRepository.deleteByPrincipal(user.getUsername());+ toolChainStatRepository.deleteByPrincipal(user.getUsername());+// Drop ACL grants held by this user and detach grants they issuedresourceGrantRepository.deleteByPrincipalTypeAndPrincipalId(PrincipalType.USER, user.getId());@@ -415,9 +423,16 @@ public class UserService implements UserServiceInterface {if (!isUsernameValid(newUsername)) {throw new IllegalArgumentException(getInvalidUsernameMessage());}+ String previousUsername = user.getUsername();orgOwnerService.renamed(user.getId(), newUsername);user.setUsername(newUsername);userRepository.save(user);+ if (previousUsername != null && !previousUsername.equals(newUsername)) {+ // Tool usage keys on the username, so the old name's rows would be inherited by+ // whoever is given that name next.+ toolUsageStatRepository.deleteByPrincipal(previousUsername);+ toolChainStatRepository.deleteByPrincipal(previousUsername);+ }exportAfterCommit();}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.javanew file mode 100644index 0000000000..37c02298f2--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolKeyRegistry.java@@ -0,0 +1,114 @@+package stirling.software.proprietary.service;++import java.util.Set;++import org.springframework.stereotype.Component;++/**+ * The tool keys this install will record and rank. Usage rows are keyed by whatever the browser+ * says finished, so without a closed set any caller could write keys no tool will ever match: they+ * would sit in the rankings taking slots the UI then drops, and each distinct one served as {@code+ * currentTool} would open its own cached aggregate over the stats table.+ *+ * <p>Hand-maintained mirror of {@code frontend/editor/src/core/types/toolId.ts} and the proprietary+ * and prototype overrides beside it. {@code ToolKeyRegistryTest} parses those files and fails when+ * the two drift, so adding a tool to the frontend fails the build until it is added here.+ */+@Component+public class ToolKeyRegistry {++ static final Set<String> DEFAULT_KEYS =+ Set.of(+ // CORE_REGULAR_TOOL_IDS+ "certSign",+ "sign",+ "sharedSign",+ "addText",+ "addPassword",+ "removePassword",+ "removePages",+ "removeBlanks",+ "removeAnnotations",+ "removeImage",+ "changePermissions",+ "watermark",+ "sanitize",+ "split",+ "merge",+ "convert",+ "ocr",+ "addImage",+ "rotate",+ "autoRotate",+ "annotate",+ "scannerImageSplit",+ "editTableOfContents",+ "scannerEffect",+ "autoRename",+ "pageLayout",+ "scalePages",+ "adjustContrast",+ "crop",+ "pdfToSinglePage",+ "repair",+ "compare",+ "addPageNumbers",+ "redact",+ "flatten",+ "removeCertSign",+ "unlockPDFForms",+ "compress",+ "classify",+ "extractPages",+ "reorganizePages",+ "extractImages",+ "addStamp",+ "addAttachments",+ "createPortfolio",+ "changeMetadata",+ "overlayPdfs",+ "getPdfInfo",+ "validateSignature",+ "timestampPdf",+ "replaceColor",+ "showJS",+ "bookletImposition",+ "pdfTextEditor",+ "formFill",+ "autoFormDetection",+ // CORE_SUPER_TOOL_IDS+ "multiTool",+ "read",+ "automate",+ // CORE_LINK_TOOL_IDS+ "devApi",+ "devFolderScanning",+ "devSsoGuide",+ "devAirgapped",+ // Build-specific overrides: proprietary and prototype super tools+ "ai-workflow",+ "pdfCommentAgent");++ /** Longest key the set can hold, so storage can be sized from the data rather than a guess. */+ public static final int MAX_KEY_LENGTH =+ DEFAULT_KEYS.stream().mapToInt(String::length).max().orElse(0);++ private final Set<String> keys;++ public ToolKeyRegistry() {+ this.keys = DEFAULT_KEYS;+ }++ private ToolKeyRegistry(Set<String> keys) {+ this.keys = Set.copyOf(keys);+ }++ /** A registry over an arbitrary key set, so tests can use names of their own. */+ static ToolKeyRegistry forKeys(Set<String> keys) {+ return new ToolKeyRegistry(keys);+ }++ public boolean isKnown(String toolKey) {+ return toolKey != null && keys.contains(toolKey);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolRecommendationService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolRecommendationService.javanew file mode 100644index 0000000000..d344cd3775--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolRecommendationService.java@@ -0,0 +1,211 @@+package stirling.software.proprietary.service;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;++import org.springframework.core.env.Environment;+import org.springframework.stereotype.Service;+import org.springframework.transaction.annotation.Transactional;++import lombok.RequiredArgsConstructor;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.service.ToolUsageSignalService.TeamScope;+import stirling.software.proprietary.service.ToolUsageSignalService.ToolChainSummary;++/**+ * Scores "what tool next". Transitions out of the current tool dominate, then the caller's own+ * usage, their team's, and the whole install's. Scoring itself is cheap and uncached; the costly+ * aggregates are cached inside {@link ToolUsageSignalService} and shared by everyone.+ */+@Service+@RequiredArgsConstructor+public class ToolRecommendationService {++ // Relative signal strengths; transition-from-current-tool dominates by design.+ static final double WEIGHT_TRANSITION_USER = 5.0;+ static final double WEIGHT_TRANSITION_TEAM = 3.0;+ static final double WEIGHT_TRANSITION_GLOBAL = 2.0;+ static final double WEIGHT_FREQUENCY_USER = 2.0;+ static final double WEIGHT_FREQUENCY_TEAM = 1.25;+ static final double WEIGHT_FREQUENCY_GLOBAL = 0.75;++ static final int DEFAULT_LIMIT = 6;+ static final int MAX_LIMIT = 20;++ /** A single tool is not a workflow; two is the shortest thing worth automating. */+ static final int MIN_WORKFLOW_TOOLS = 2;++ private final ToolUsageSignalService signals;+ private final ToolKeyRegistry toolKeys;+ private final ApplicationProperties applicationProperties;+ private final Environment environment;++ public record ToolRecommendation(String toolKey, double score) {}++ /** Where an observed workflow was seen, narrowest scope first. */+ public enum WorkflowScope {+ USER,+ TEAM,+ GLOBAL+ }++ /**+ * A sequence of tools repeatedly applied to the same document - the raw material for turning a+ * habit into a pipeline.+ */+ public record ToolWorkflow(List<String> tools, long count, WorkflowScope scope) {}++ /**+ * Whether the install-wide tier may be consulted. On a self-hosted install "everyone here" is+ * one organisation and is exactly the signal wanted. In SaaS it is every customer on the+ * platform, so one tenant's aggregate usage would rank another's tools; there, a caller sees+ * only themselves and their teams.+ */+ boolean installWideSignalAllowed() {+ return !Arrays.asList(environment.getActiveProfiles()).contains("saas");+ }++ /**+ * The most repeated document workflows, the caller's own first and then topped up with their+ * team's and the install's. Chains already seen at a narrower scope are not repeated, so each+ * entry answers "who does this" as well as "what is it".+ */+ @Transactional(readOnly = true)+ public List<ToolWorkflow> getWorkflows(String principal, int minLength, int limit) {+ if (!ToolUsageTrackingService.isUsageDataAllowed(applicationProperties)+ || principal == null) {+ return List.of();+ }+ int capped = limit <= 0 ? DEFAULT_LIMIT : Math.min(limit, MAX_LIMIT);+ int minTools = Math.max(MIN_WORKFLOW_TOOLS, minLength);+ long cutoff =+ ToolUsageTrackingService.currentEpochDay()+ - applicationProperties.getToolRecommendations().getWindowDays();++ List<ToolWorkflow> workflows = new ArrayList<>();+ Set<List<String>> seen = new HashSet<>();+ collect(+ workflows,+ seen,+ signals.userChains(principal, cutoff, minTools, capped),+ WorkflowScope.USER,+ capped);+ TeamScope team = signals.resolveTeamScope(principal);+ if (team.hasMembers() && workflows.size() < capped) {+ collect(+ workflows,+ seen,+ signals.teamChains(team, cutoff, minTools, capped),+ WorkflowScope.TEAM,+ capped);+ }+ if (installWideSignalAllowed() && workflows.size() < capped) {+ collect(+ workflows,+ seen,+ signals.globalChains(cutoff, minTools, capped),+ WorkflowScope.GLOBAL,+ capped);+ }+ return List.copyOf(workflows);+ }++ private static void collect(+ List<ToolWorkflow> into,+ Set<List<String>> seen,+ List<ToolChainSummary> chains,+ WorkflowScope scope,+ int limit) {+ for (ToolChainSummary chain : chains) {+ if (into.size() >= limit) {+ return;+ }+ if (seen.add(chain.tools())) {+ into.add(new ToolWorkflow(chain.tools(), chain.count(), scope));+ }+ }+ }++ @Transactional(readOnly = true)+ public List<ToolRecommendation> getRecommendations(+ String principal, String currentTool, int limit) {+ // Serving a ranking built from tracked history needs the same consent that recorded it.+ if (!ToolUsageTrackingService.isUsageDataAllowed(applicationProperties)+ || principal == null) {+ return List.of();+ }+ long today = ToolUsageTrackingService.currentEpochDay();+ long cutoff = today - applicationProperties.getToolRecommendations().getWindowDays();+ long recent = today - applicationProperties.getToolRecommendations().getRecentWindowDays();+ boolean installWide = installWideSignalAllowed();+ TeamScope team = signals.resolveTeamScope(principal);++ Map<String, Double> scores = new HashMap<>();+ if (currentTool != null) {+ merge(+ scores,+ from(signals.userTransitions(principal, cutoff, recent), currentTool),+ WEIGHT_TRANSITION_USER);+ if (team.hasMembers()) {+ merge(+ scores,+ from(signals.teamTransitions(team, cutoff, recent), currentTool),+ WEIGHT_TRANSITION_TEAM);+ }+ if (installWide) {+ merge(+ scores,+ from(signals.globalTransitions(cutoff, recent), currentTool),+ WEIGHT_TRANSITION_GLOBAL);+ }+ }+ merge(scores, signals.userFrequency(principal, cutoff, recent), WEIGHT_FREQUENCY_USER);+ if (team.hasMembers()) {+ merge(scores, signals.teamFrequency(team, cutoff, recent), WEIGHT_FREQUENCY_TEAM);+ }+ if (installWide) {+ merge(scores, signals.globalFrequency(cutoff, recent), WEIGHT_FREQUENCY_GLOBAL);+ }++ // Never answer "what next" with the tool the user is already in. Keys are checked again+ // on the way out so rows left by a tool that has since been removed stay out of the UI.+ return scores.entrySet().stream()+ .filter(e -> !e.getKey().equals(currentTool))+ .filter(e -> toolKeys.isKnown(e.getKey()))+ .sorted(+ Map.Entry.<String, Double>comparingByValue()+ .reversed()+ .thenComparing(Map.Entry.comparingByKey()))+ .limit(limit <= 0 ? DEFAULT_LIMIT : Math.min(limit, MAX_LIMIT))+ .map(e -> new ToolRecommendation(e.getKey(), round(e.getValue())))+ .toList();+ }++ /** One source tool's row of the transition matrix; empty when nothing has followed it yet. */+ private static Map<String, Double> from(+ Map<String, Map<String, Double>> transitions, String currentTool) {+ return transitions.getOrDefault(currentTool, Map.of());+ }++ /**+ * Adds one signal to the running scores, normalized against its own maximum so an install's+ * millions of runs cannot outweigh the handful that are personally the caller's.+ */+ private void merge(Map<String, Double> scores, Map<String, Double> signal, double weight) {+ double max = signal.values().stream().mapToDouble(Double::doubleValue).max().orElse(0);+ if (max <= 0) {+ return;+ }+ signal.forEach((tool, value) -> scores.merge(tool, weight * (value / max), Double::sum));+ }++ private static double round(double value) {+ return Math.round(value * 1000.0) / 1000.0;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolUsageSignalService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolUsageSignalService.javanew file mode 100644index 0000000000..84d8e8c3e5--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolUsageSignalService.java@@ -0,0 +1,356 @@+package stirling.software.proprietary.service;++import java.time.Duration;+import java.util.ArrayList;+import java.util.Collection;+import java.util.HashMap;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.function.Supplier;++import org.springframework.data.domain.PageRequest;+import org.springframework.data.domain.Pageable;+import org.springframework.stereotype.Service;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.github.benmanes.caffeine.cache.Cache;+import com.github.benmanes.caffeine.cache.Caffeine;++import lombok.extern.slf4j.Slf4j;++import stirling.software.common.cluster.KeyValueCache;+import stirling.software.proprietary.model.ToolChainStat;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.repository.TeamMembershipRepository;++/**+ * Serves the scoring signals as tool -> weighted count maps. A caller's own signals are cheap+ * indexed reads and stay uncached so their activity shows up immediately. Team and install-wide+ * aggregates scan far more rows, so they are cached and shared: 50,000 users browsing tools cost+ * one scan per TTL, not 50,000.+ *+ * <p>The bounded Caffeine cache per node is the whole mechanism. Behind it, {@link KeyValueCache}+ * is an optional bonus: where a cluster backplane is configured, a scan one node paid for serves+ * the others too. Nothing requires it - with no such bean, or a broken one, each node simply does+ * its own scan per TTL, which is what it would have done anyway.+ */+@Slf4j+@Service+public class ToolUsageSignalService {++ static final String CACHE_NAME = "toolRecommendationSignals";++ private static final Duration TTL = Duration.ofMinutes(5);++ /** Bounded so a long-lived node cannot accumulate a cache entry per team per day forever. */+ private static final int MAX_LOCAL_ENTRIES = 10_000;++ // Bounds the IN clause for very large teams; signal saturates well before this.+ private static final int MAX_TEAM_PRINCIPALS = 500;++ private static final TypeReference<Map<String, Double>> TOOL_SCORES = new TypeReference<>() {};++ private static final TypeReference<Map<String, Map<String, Double>>> TOOL_EDGES =+ new TypeReference<>() {};++ private static final TypeReference<List<ToolChainSummary>> CHAIN_SUMMARIES =+ new TypeReference<>() {};++ /**+ * Owned rather than injected: these are private cache payloads, so they must not follow+ * whatever the application's mapper is configured to do with dates or unknown fields. The app+ * has no ObjectMapper bean in any case - the other services here do the same.+ */+ private static final ObjectMapper MAPPER = new ObjectMapper();++ private final ToolUsageStatRepository usageRepository;+ private final ToolChainStatRepository chainRepository;+ private final Optional<UserRepository> userRepository;+ private final Optional<TeamMembershipRepository> membershipRepository;+ private final Optional<KeyValueCache> sharedCache;++ private final Cache<String, Object> localCache =+ Caffeine.newBuilder().maximumSize(MAX_LOCAL_ENTRIES).expireAfterWrite(TTL).build();++ public ToolUsageSignalService(+ ToolUsageStatRepository usageRepository,+ ToolChainStatRepository chainRepository,+ Optional<UserRepository> userRepository,+ Optional<TeamMembershipRepository> membershipRepository,+ Optional<KeyValueCache> sharedCache) {+ this.usageRepository = usageRepository;+ this.chainRepository = chainRepository;+ this.userRepository = userRepository;+ this.membershipRepository = membershipRepository;+ this.sharedCache = sharedCache;+ }++ /** An observed workflow: the ordered tools, and how many documents took that path. */+ public record ToolChainSummary(List<String> tools, long count) {}++ /**+ * The teams a caller shares with other people, and everyone in them. Deliberately includes the+ * caller: the team aggregates are cached under the team ids alone, so the roster must be+ * identical for everyone on those teams or the first caller's list would be served to the rest.+ *+ * <p>{@code resolved} separates "this caller has no team" from "the lookup failed", so only the+ * first is worth remembering.+ */+ public record TeamScope(List<Long> teamIds, List<String> principals, boolean resolved) {++ public static TeamScope none() {+ return new TeamScope(List.of(), List.of(), true);+ }++ /** A lookup that failed rather than came back empty; never cached. */+ public static TeamScope unresolved() {+ return new TeamScope(List.of(), List.of(), false);+ }++ /** A one-person team is just the caller again, so it adds nothing to their own signal. */+ public boolean hasMembers() {+ return principals.size() > 1;+ }++ /** Identifies the roster, so everyone with the same team set shares a cache entry. */+ public String cacheKey() {+ StringBuilder key = new StringBuilder();+ for (Long id : teamIds) {+ key.append(id).append('-');+ }+ return key.toString();+ }+ }++ public Map<String, Double> userFrequency(String principal, long cutoff, long recentCutoff) {+ return weight(usageRepository.sumByPrincipal(principal, cutoff, recentCutoff));+ }++ /**+ * The caller's own "what followed what" matrix, keyed by the tool each transition came from.+ */+ public Map<String, Map<String, Double>> userTransitions(+ String principal, long cutoff, long recentCutoff) {+ return edges(usageRepository.edgesByPrincipal(principal, cutoff, recentCutoff));+ }++ public Map<String, Double> teamFrequency(TeamScope scope, long cutoff, long recentCutoff) {+ return cached(+ key("teamFreq", scope.cacheKey(), cutoff, recentCutoff),+ TOOL_SCORES,+ () ->+ weight(+ usageRepository.sumByPrincipals(+ scope.principals(), cutoff, recentCutoff)));+ }++ public Map<String, Map<String, Double>> teamTransitions(+ TeamScope scope, long cutoff, long recentCutoff) {+ return cached(+ key("teamTrans", scope.cacheKey(), cutoff, recentCutoff),+ TOOL_EDGES,+ () ->+ edges(+ usageRepository.edgesByPrincipals(+ scope.principals(), cutoff, recentCutoff)));+ }++ public Map<String, Double> globalFrequency(long cutoff, long recentCutoff) {+ return cached(+ key("globalFreq", cutoff, recentCutoff),+ TOOL_SCORES,+ () -> weight(usageRepository.sumGlobal(cutoff, recentCutoff)));+ }++ public Map<String, Map<String, Double>> globalTransitions(long cutoff, long recentCutoff) {+ return cached(+ key("globalTrans", cutoff, recentCutoff),+ TOOL_EDGES,+ () -> edges(usageRepository.edgesGlobal(cutoff, recentCutoff)));+ }++ public List<ToolChainSummary> userChains(+ String principal, long cutoff, int minLength, int limit) {+ return chains(chainRepository.topByPrincipal(principal, cutoff, minLength, page(limit)));+ }++ public List<ToolChainSummary> teamChains(+ TeamScope scope, long cutoff, int minLength, int limit) {+ return cached(+ key("teamChains", scope.cacheKey(), cutoff, minLength, limit),+ CHAIN_SUMMARIES,+ () ->+ chains(+ chainRepository.topByPrincipals(+ scope.principals(), cutoff, minLength, page(limit))));+ }++ public List<ToolChainSummary> globalChains(long cutoff, int minLength, int limit) {+ return cached(+ key("globalChains", cutoff, minLength, limit),+ CHAIN_SUMMARIES,+ () -> chains(chainRepository.topGlobal(cutoff, minLength, page(limit))));+ }++ private static String key(Object... parts) {+ StringBuilder key = new StringBuilder();+ for (Object part : parts) {+ key.append(part).append('|');+ }+ return key.toString();+ }++ /**+ * Local cache, then the cluster if there is one, then the query. Any cache failure falls+ * through to the query - the signal is advisory, and a backplane that is absent or broken must+ * not take the ranking down with it.+ */+ @SuppressWarnings("unchecked")+ private <T> T cached(String key, TypeReference<T> type, Supplier<T> loader) {+ Object local = localCache.getIfPresent(key);+ if (local != null) {+ return (T) local;+ }+ T value = fromClusterOrLoad(key, type, loader);+ localCache.put(key, value);+ return value;+ }++ private <T> T fromClusterOrLoad(String key, TypeReference<T> type, Supplier<T> loader) {+ if (sharedCache.isEmpty()) {+ return loader.get();+ }+ KeyValueCache cluster = sharedCache.get();+ try {+ Optional<String> shared = cluster.get(CACHE_NAME, key);+ if (shared.isPresent()) {+ return MAPPER.readValue(shared.get(), type);+ }+ } catch (Exception e) {+ log.debug("Shared signal cache read failed for {}: {}", key, e.getMessage());+ }+ T value = loader.get();+ try {+ cluster.put(CACHE_NAME, key, MAPPER.writeValueAsString(value), TTL);+ } catch (Exception e) {+ log.debug("Shared signal cache write failed for {}: {}", key, e.getMessage());+ }+ return value;+ }++ private static Pageable page(int limit) {+ return PageRequest.of(0, Math.max(1, limit));+ }++ /** Collapses [chainKey, chainLength, totalCount] rows; the query already ordered them. */+ private static List<ToolChainSummary> chains(List<Object[]> rows) {+ List<ToolChainSummary> summaries = new ArrayList<>(rows.size());+ for (Object[] row : rows) {+ long count = row[2] == null ? 0 : ((Number) row[2]).longValue();+ List<String> tools = ToolChainStat.fromChainKey((String) row[0]);+ if (count > 0 && tools.size() > 1) {+ summaries.add(new ToolChainSummary(tools, count));+ }+ }+ return List.copyOf(summaries);+ }++ /**+ * The teams the caller shares with other people. Reads {@code team_memberships}, which is the+ * real membership model in SaaS and where a self-hosted user's single team is mirrored, and+ * unions in the legacy {@code users.team_id} so an install whose memberships predate that table+ * still resolves.+ */+ public TeamScope resolveTeamScope(String principal) {+ if (userRepository.isEmpty()) {+ return TeamScope.none();+ }+ String cacheKey = key("team", principal);+ Object local = localCache.getIfPresent(cacheKey);+ if (local instanceof TeamScope scope) {+ return scope;+ }+ TeamScope scope = loadTeamScope(principal);+ // A failed lookup is not an answer; caching it would blank the team tier for a whole TTL.+ if (scope.resolved()) {+ localCache.put(cacheKey, scope);+ }+ return scope;+ }++ private TeamScope loadTeamScope(String principal) {+ try {+ Set<Long> teamIds = new LinkedHashSet<>();+ userRepository+ .get()+ .findByUsernameIgnoreCase(principal)+ .map(user -> user.getTeam() == null ? null : user.getTeam().getId())+ .ifPresent(teamIds::add);+ membershipRepository.ifPresent(+ repo -> teamIds.addAll(repo.findTeamIdsByUsername(principal)));+ teamIds.remove(null);+ if (teamIds.isEmpty()) {+ return TeamScope.none();+ }+ List<Long> sorted = teamIds.stream().sorted().toList();+ return new TeamScope(sorted, teamPrincipals(sorted), true);+ } catch (Exception e) {+ log.debug("Team resolution failed for {}: {}", principal, e.getMessage());+ return TeamScope.unresolved();+ }+ }++ /**+ * Usernames only, ordered and limited by the database: hydrating whole {@code User} entities to+ * read one column loads every member of what is, on a self-hosted install, the team everybody+ * is in.+ */+ private List<String> teamPrincipals(Collection<Long> teamIds) {+ Pageable cap = page(MAX_TEAM_PRINCIPALS);+ Set<String> principals =+ new LinkedHashSet<>(userRepository.get().findUsernamesByTeamIds(teamIds, cap));+ membershipRepository.ifPresent(+ repo -> principals.addAll(repo.findUsernamesByTeamIds(teamIds, cap)));+ return principals.stream().sorted().limit(MAX_TEAM_PRINCIPALS).toList();+ }++ /** Collapses [tool, recentCount, totalCount] rows; recent-window events count double. */+ private static Map<String, Double> weight(List<Object[]> rows) {+ Map<String, Double> weighted = new HashMap<>();+ for (Object[] row : rows) {+ double value = weightOf(row[1], row[2]);+ if (value > 0) {+ weighted.put((String) row[0], value);+ }+ }+ return weighted;+ }++ /**+ * Collapses [fromTool, tool, recentCount, totalCount] rows into a from -> tool -> weight map.+ */+ private static Map<String, Map<String, Double>> edges(List<Object[]> rows) {+ Map<String, Map<String, Double>> byFromTool = new HashMap<>();+ for (Object[] row : rows) {+ double value = weightOf(row[2], row[3]);+ if (value > 0) {+ byFromTool+ .computeIfAbsent((String) row[0], key -> new HashMap<>())+ .put((String) row[1], value);+ }+ }+ return byFromTool;+ }++ private static double weightOf(Object recentCount, Object totalCount) {+ long recent = recentCount == null ? 0 : ((Number) recentCount).longValue();+ long total = totalCount == null ? 0 : ((Number) totalCount).longValue();+ return total + recent;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolUsageTrackingService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolUsageTrackingService.javanew file mode 100644index 0000000000..0a8fdf6d2d--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/ToolUsageTrackingService.java@@ -0,0 +1,211 @@+package stirling.software.proprietary.service;++import java.time.LocalDate;+import java.time.ZoneOffset;+import java.util.ArrayList;+import java.util.Comparator;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;++import org.springframework.dao.DataIntegrityViolationException;+import org.springframework.scheduling.annotation.Scheduled;+import org.springframework.stereotype.Service;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.model.ToolChainStat;+import stirling.software.proprietary.model.ToolUsageStat;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;++/**+ * Records completed tool runs into daily rollup rows. One completion is one increment of one usage+ * row plus one row per distinct input document chain, which is negligible next to the PDF work that+ * produced it.+ *+ * <p>The caller supplies the tools already applied to each input <em>document</em>, so a transition+ * means "this is what came next for this file", not "this is what the user happened to click+ * before". The full chains are kept as well, because a workflow worth automating is a sequence, and+ * pairs cannot tell {@code A->B->C} on one document from {@code A->B} and {@code B->C} on two.+ */+@Slf4j+@Service+@RequiredArgsConstructor+public class ToolUsageTrackingService {++ /** Bounds the work one completion can trigger when many documents go in at once. */+ static final int MAX_CHAINS_PER_EVENT = 5;++ /**+ * How many of the submitted chains are looked at. De-duplication alone is no bound: identical+ * chains never reach {@link #MAX_CHAINS_PER_EVENT} distinct ones, so a caller could otherwise+ * make one request scan an arbitrarily long list.+ */+ static final int MAX_CHAINS_SCANNED = 100;++ private final ToolUsageStatRepository usageRepository;+ private final ToolChainStatRepository chainRepository;+ private final ToolKeyRegistry toolKeys;+ private final ApplicationProperties applicationProperties;++ /** Only keys a real tool answers to are recorded; see {@link ToolKeyRegistry}. */+ public boolean isKnownToolKey(String toolKey) {+ return toolKeys.isKnown(toolKey);+ }++ /** Per-principal usage is profiling, so admin analytics consent gates it too. */+ static boolean isUsageDataAllowed(ApplicationProperties properties) {+ return properties.getToolRecommendations().isEnabled()+ && properties.getSystem().isAnalyticsEnabled();+ }++ /** Lets the controller answer 501 so the browser stops posting on a declining install. */+ public boolean isRecordingEnabled() {+ return isUsageDataAllowed(applicationProperties);+ }++ /**+ * Counts one completed run of {@code toolKey} against each input document's history.+ *+ * @param priorChains the tools already applied to each input document, oldest step first and+ * excluding this run. One entry per distinct input document; empty for a fresh upload.+ */+ public void recordUsage(String principal, String toolKey, List<List<String>> priorChains) {+ if (!isUsageDataAllowed(applicationProperties)+ || principal == null+ || !isKnownToolKey(toolKey)) {+ return;+ }+ List<List<String>> chains = sanitiseChains(priorChains, toolKey);+ long epochDay = currentEpochDay();+ try {+ recordTransition(principal, toolKey, dominantPredecessor(chains), epochDay);+ for (List<String> prior : chains) {+ recordChain(principal, append(prior, toolKey), epochDay);+ }+ } catch (Exception e) {+ log.warn("Failed to record usage of {} for {}: {}", toolKey, principal, e.getMessage());+ }+ }++ /**+ * Normalises what the browser sent: drops anything that is not a tool key, keeps only the+ * trailing {@link ToolChainStat#MAX_CHAIN_TOOLS} steps (a chain that outgrows the key is still+ * a real subsequence), removes the run's own key from the tail so a re-run does not self-loop,+ * and de-duplicates so ten identically-processed inputs count as one workflow, not ten.+ */+ private List<List<String>> sanitiseChains(List<List<String>> priorChains, String toolKey) {+ if (priorChains == null || priorChains.isEmpty()) {+ return List.of(List.of());+ }+ Set<List<String>> distinct = new LinkedHashSet<>();+ int scanned = 0;+ for (List<String> chain : priorChains) {+ distinct.add(sanitiseChain(chain, toolKey));+ if (distinct.size() >= MAX_CHAINS_PER_EVENT || ++scanned >= MAX_CHAINS_SCANNED) {+ break;+ }+ }+ return List.copyOf(distinct);+ }++ private List<String> sanitiseChain(List<String> chain, String toolKey) {+ if (chain == null) {+ return List.of();+ }+ List<String> valid = chain.stream().filter(this::isKnownToolKey).toList();+ // Re-running the same tool is a correction, not a step: "compress, compress" is "compress".+ int end = valid.size();+ while (end > 0 && toolKey.equals(valid.get(end - 1))) {+ end--;+ }+ valid = valid.subList(0, end);+ // The chain grows by one when this run is appended, so leave room for it.+ int maxPrior = ToolChainStat.MAX_CHAIN_TOOLS - 1;+ if (valid.size() > maxPrior) {+ valid = valid.subList(valid.size() - maxPrior, valid.size());+ }+ return List.copyOf(valid);+ }++ /**+ * The predecessor credited in the pairwise table. Multi-input tools (merge) see several+ * documents at once; the longest chain is the most-processed document and so the best+ * representative of the workflow, with the key order breaking ties deterministically.+ */+ private static String dominantPredecessor(List<List<String>> chains) {+ // Reversed on the key so the tie-break picks the lowest one, since this takes the maximum.+ Comparator<List<String>> byLengthThenKey =+ Comparator.<List<String>>comparingInt(List::size)+ .thenComparing(ToolChainStat::toChainKey, Comparator.reverseOrder());+ return chains.stream()+ .filter(chain -> !chain.isEmpty())+ .max(byLengthThenKey)+ .map(chain -> chain.get(chain.size() - 1))+ .orElse(ToolUsageStat.NO_PREVIOUS_TOOL);+ }++ private static List<String> append(List<String> prior, String toolKey) {+ List<String> full = new ArrayList<>(prior);+ full.add(toolKey);+ return full;+ }++ private void recordTransition(+ String principal, String toolKey, String fromTool, long epochDay) {+ if (usageRepository.incrementCount(principal, fromTool, toolKey, epochDay, 1) == 0) {+ try {+ usageRepository.insertCount(principal, fromTool, toolKey, epochDay, 1);+ } catch (DataIntegrityViolationException e) {+ // Another request inserted the row first; add to theirs instead of clobbering it.+ usageRepository.incrementCount(principal, fromTool, toolKey, epochDay, 1);+ }+ }+ }++ /** A one-tool chain is just a frequency count, which the usage table already carries. */+ private void recordChain(String principal, List<String> chain, long epochDay) {+ if (chain.size() < 2) {+ return;+ }+ String chainKey = ToolChainStat.toChainKey(chain);+ if (chainKey.length() > ToolChainStat.MAX_CHAIN_KEY_LENGTH) {+ log.debug("Skipping oversized tool chain of {} steps", chain.size());+ return;+ }+ if (chainRepository.incrementCount(principal, chainKey, epochDay, 1) == 0) {+ try {+ chainRepository.insertCount(principal, chainKey, epochDay, chain.size(), 1);+ } catch (DataIntegrityViolationException e) {+ chainRepository.incrementCount(principal, chainKey, epochDay, 1);+ }+ }+ }++ /** Daily retention sweep; both tables hold one row per principal, key and day. */+ @Scheduled(cron = "0 15 3 * * *")+ public void cleanupOldStats() {+ int retentionDays = applicationProperties.getToolRecommendations().getRetentionDays();+ if (retentionDays <= 0) {+ return;+ }+ long cutoff = currentEpochDay() - retentionDays;+ try {+ int deleted =+ usageRepository.deleteOlderThan(cutoff)+ + chainRepository.deleteOlderThan(cutoff);+ if (deleted > 0) {+ log.info("Tool usage retention sweep removed {} rows", deleted);+ }+ } catch (Exception e) {+ log.error("Tool usage retention sweep failed", e);+ }+ }++ static long currentEpochDay() {+ return LocalDate.now(ZoneOffset.UTC).toEpochDay();+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ToolRecommendationControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ToolRecommendationControllerTest.javanew file mode 100644index 0000000000..d52b407454--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/ToolRecommendationControllerTest.java@@ -0,0 +1,250 @@+package stirling.software.proprietary.controller.api;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;++import java.util.List;+import java.util.Optional;++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.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.http.ResponseEntity;+import org.springframework.test.web.servlet.MockMvc;+import org.springframework.test.web.servlet.setup.MockMvcBuilders;++import stirling.software.common.service.UserServiceInterface;+import stirling.software.proprietary.controller.api.ToolRecommendationController.RecommendationsResponse;+import stirling.software.proprietary.controller.api.ToolRecommendationController.UsageRequest;+import stirling.software.proprietary.service.ToolRecommendationService;+import stirling.software.proprietary.service.ToolRecommendationService.ToolRecommendation;+import stirling.software.proprietary.service.ToolUsageTrackingService;++@ExtendWith(MockitoExtension.class)+class ToolRecommendationControllerTest {++ private static final String BASE_PATH = "/api/v1/proprietary/ui-data/tool-recommendations";++ /** One input document that has already been through compress. */+ private static final List<List<String>> CHAIN = List.of(List.of("compress"));++ private static final List<List<String>> JUNK_CHAIN = List.of(List.of("bad key!"));++ @Mock private ToolUsageTrackingService trackingService;+ @Mock private ToolRecommendationService recommendationService;+ @Mock private UserServiceInterface userService;++ private ToolRecommendationController controller;+ private MockMvc mockMvc;++ @BeforeEach+ void setUp() {+ controller =+ new ToolRecommendationController(+ trackingService, recommendationService, Optional.of(userService));+ mockMvc = MockMvcBuilders.standaloneSetup(controller).build();+ // Lenient: the 400 case is rejected before either gate is consulted.+ lenient().when(trackingService.isRecordingEnabled()).thenReturn(true);+ lenient().when(trackingService.isKnownToolKey(anyString())).thenReturn(true);+ lenient().when(trackingService.isKnownToolKey("bad key!")).thenReturn(false);+ lenient().when(trackingService.isKnownToolKey("not a tool!")).thenReturn(false);+ lenient().when(trackingService.isKnownToolKey(isNull())).thenReturn(false);+ }++ @Nested+ @DisplayName("GET recommendations")+ class GetRecommendations {++ @Test+ @DisplayName("returns the service's ranking for the logged-in user")+ void returnsRanking() {+ when(userService.getCurrentUsername()).thenReturn("alice");+ when(recommendationService.getRecommendations("alice", "compare", 6))+ .thenReturn(List.of(new ToolRecommendation("ocr", 5.0)));++ ResponseEntity<RecommendationsResponse> response =+ controller.getRecommendations("compare", 6);++ assertThat(response.getStatusCode().value()).isEqualTo(200);+ assertThat(response.getBody().recommendations())+ .containsExactly(new ToolRecommendation("ocr", 5.0));+ }++ @Test+ @DisplayName("a currentTool no tool answers to is treated as no context, not an error")+ void unknownCurrentToolIgnored() {+ when(userService.getCurrentUsername()).thenReturn("alice");+ when(recommendationService.getRecommendations(eq("alice"), isNull(), anyInt()))+ .thenReturn(List.of());++ ResponseEntity<RecommendationsResponse> response =+ controller.getRecommendations("not a tool!", 6);++ assertThat(response.getStatusCode().value()).isEqualTo(200);+ verify(recommendationService).getRecommendations("alice", null, 6);+ }++ @Test+ @DisplayName("a service failure degrades to an empty list, never an error page")+ void serviceFailureDegrades() {+ when(userService.getCurrentUsername()).thenReturn("alice");+ when(recommendationService.getRecommendations(anyString(), isNull(), anyInt()))+ .thenThrow(new RuntimeException("db down"));++ ResponseEntity<RecommendationsResponse> response =+ controller.getRecommendations(null, 6);++ assertThat(response.getStatusCode().value()).isEqualTo(200);+ assertThat(response.getBody().recommendations()).isEmpty();+ }++ @Test+ @DisplayName("with nobody signed in it answers 501 so the client stops asking")+ void noPrincipalReturns501() {+ when(userService.getCurrentUsername()).thenReturn(null);++ ResponseEntity<RecommendationsResponse> response =+ controller.getRecommendations("compare", 6);++ assertThat(response.getStatusCode().value()).isEqualTo(501);+ verifyNoInteractions(recommendationService);+ }++ @Test+ @DisplayName("an install that declined tracking answers 501 rather than an empty ranking")+ void declinedInstallReturns501() {+ when(userService.getCurrentUsername()).thenReturn("alice");+ when(trackingService.isRecordingEnabled()).thenReturn(false);++ ResponseEntity<RecommendationsResponse> response =+ controller.getRecommendations("compare", 6);++ assertThat(response.getStatusCode().value()).isEqualTo(501);+ verifyNoInteractions(recommendationService);+ }+ }++ @Nested+ @DisplayName("POST usage")+ class RecordUsage {++ @Test+ @DisplayName("valid events are recorded for the signed-in user")+ void recordsUsage() {+ when(userService.getCurrentUsername()).thenReturn("alice");++ ResponseEntity<Void> response = controller.recordUsage(new UsageRequest("ocr", CHAIN));++ assertThat(response.getStatusCode().value()).isEqualTo(204);+ verify(trackingService).recordUsage("alice", "ocr", CHAIN);+ }++ @Test+ @DisplayName("a tool key no tool answers to is rejected with 400")+ void unknownToolKeyRejected() {+ ResponseEntity<Void> response =+ controller.recordUsage(new UsageRequest("bad key!", null));++ assertThat(response.getStatusCode().value()).isEqualTo(400);+ verify(trackingService, never()).recordUsage(anyString(), anyString(), any());+ }++ @Test+ @DisplayName("chains are passed through for the service to validate")+ void chainsPassedThrough() {+ when(userService.getCurrentUsername()).thenReturn("alice");++ controller.recordUsage(new UsageRequest("ocr", JUNK_CHAIN));++ verify(trackingService).recordUsage("alice", "ocr", JUNK_CHAIN);+ }++ @Test+ @DisplayName("an install that declined tracking answers 501 so the client stops posting")+ void declinedInstallReturns501() {+ when(userService.getCurrentUsername()).thenReturn("alice");+ when(trackingService.isRecordingEnabled()).thenReturn(false);++ ResponseEntity<Void> response = controller.recordUsage(new UsageRequest("ocr", CHAIN));++ assertThat(response.getStatusCode().value()).isEqualTo(501);+ verify(trackingService, never()).recordUsage(anyString(), anyString(), any());+ }+ }++ @Nested+ @DisplayName("Cross-principal exposure")+ class CrossPrincipalExposure {++ /** The chain queries carry no tenant predicate, so no HTTP route may reach them. */+ @Test+ @DisplayName("no route serves other principals' chains")+ void workflowsRouteIsGone() throws Exception {+ mockMvc.perform(get(BASE_PATH + "/workflows").param("minLength", "2"))+ .andExpect(status().isNotFound());++ verifyNoInteractions(recommendationService);+ }+ }++ @Nested+ @DisplayName("Principal resolution")+ class PrincipalResolution {++ /**+ * Rows key on a username the server authenticated. With login disabled the only identity a+ * caller could offer is one they declared, which would let an unauthenticated client mint+ * principals to write rows under - so nothing is recorded at all.+ */+ @Test+ @DisplayName("no login means nothing is recorded")+ void noLoginRecordsNothing() {+ when(userService.getCurrentUsername()).thenReturn(null);++ ResponseEntity<Void> response = controller.recordUsage(new UsageRequest("ocr", CHAIN));++ assertThat(response.getStatusCode().value()).isEqualTo(501);+ verify(trackingService, never()).recordUsage(anyString(), anyString(), any());+ }++ @Test+ @DisplayName("Spring's anonymousUser placeholder is not treated as a username")+ void anonymousUserPlaceholderIgnored() {+ when(userService.getCurrentUsername()).thenReturn("anonymousUser");++ ResponseEntity<Void> response = controller.recordUsage(new UsageRequest("ocr", CHAIN));++ assertThat(response.getStatusCode().value()).isEqualTo(501);+ verify(trackingService, never()).recordUsage(anyString(), anyString(), any());+ }++ @Test+ @DisplayName("a core build with no user service records nothing")+ void withoutUserServiceRecordsNothing() {+ ToolRecommendationController coreController =+ new ToolRecommendationController(+ trackingService, recommendationService, Optional.empty());++ ResponseEntity<Void> response =+ coreController.recordUsage(new UsageRequest("ocr", CHAIN));++ assertThat(response.getStatusCode().value()).isEqualTo(501);+ verify(trackingService, never()).recordUsage(anyString(), anyString(), any());+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/repository/ToolRecommendationRepositoriesTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/repository/ToolRecommendationRepositoriesTest.javanew file mode 100644index 0000000000..c58622db5a--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/repository/ToolRecommendationRepositoriesTest.java@@ -0,0 +1,327 @@+package stirling.software.proprietary.repository;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;++import org.junit.jupiter.api.DisplayName;+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.persistence.autoconfigure.EntityScan;+import org.springframework.dao.DataIntegrityViolationException;+import org.springframework.data.domain.PageRequest;+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;++import stirling.software.proprietary.model.ToolChainStat;+import stirling.software.proprietary.model.ToolUsageStat;++/** Exercises the windowed CASE aggregation and increment queries against H2. */+@DataJpaTest+class ToolRecommendationRepositoriesTest {++ private static final long DAY = 20_000;+ private static final String NONE = ToolUsageStat.NO_PREVIOUS_TOOL;++ @Autowired private ToolUsageStatRepository usageRepository;+ @Autowired private ToolChainStatRepository chainRepository;++ private static Map<String, long[]> byTool(List<Object[]> rows) {+ return rows.stream()+ .collect(+ Collectors.toMap(+ r -> (String) r[0],+ r ->+ new long[] {+ ((Number) r[1]).longValue(), ((Number) r[2]).longValue()+ }));+ }++ @Test+ @DisplayName("frequency splits the recent window out of the total and ignores older rows")+ void usageSumsSplitRecentFromTotal() {+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 3));+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY - 10, 7));+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY - 60, 100));+ usageRepository.save(new ToolUsageStat("bob", NONE, "merge", DAY, 5));++ Map<String, long[]> sums =+ byTool(usageRepository.sumByPrincipal("alice", DAY - 30, DAY - 7));++ assertThat(sums).containsOnlyKeys("ocr");+ assertThat(sums.get("ocr")[0]).isEqualTo(3);+ assertThat(sums.get("ocr")[1]).isEqualTo(10);+ }++ /** [fromTool, tool, recent, total] rows as fromTool -> tool -> {recent, total}. */+ private static Map<String, Map<String, long[]>> byEdge(List<Object[]> rows) {+ Map<String, Map<String, long[]>> byFromTool = new HashMap<>();+ for (Object[] row : rows) {+ byFromTool+ .computeIfAbsent((String) row[0], key -> new HashMap<>())+ .put(+ (String) row[1],+ new long[] {+ ((Number) row[2]).longValue(), ((Number) row[3]).longValue()+ });+ }+ return byFromTool;+ }++ @Test+ @DisplayName("frequency sums a tool across every predecessor it followed")+ void frequencyGroupsAwayFromTool() {+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 2));+ usageRepository.save(new ToolUsageStat("alice", "compare", "ocr", DAY, 3));+ usageRepository.save(new ToolUsageStat("alice", "merge", "ocr", DAY, 4));++ Map<String, long[]> sums =+ byTool(usageRepository.sumByPrincipal("alice", DAY - 30, DAY - 7));++ assertThat(sums.get("ocr")[1]).isEqualTo(9);+ }++ @Test+ @DisplayName("scoping by principals covers a team without leaking other users")+ void usageSumsScopeByPrincipals() {+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 1));+ usageRepository.save(new ToolUsageStat("bob", NONE, "ocr", DAY, 2));+ usageRepository.save(new ToolUsageStat("carol", NONE, "ocr", DAY, 4));++ Map<String, long[]> team =+ byTool(usageRepository.sumByPrincipals(List.of("alice", "bob"), DAY - 30, DAY - 7));+ Map<String, long[]> global = byTool(usageRepository.sumGlobal(DAY - 30, DAY - 7));++ assertThat(team.get("ocr")[1]).isEqualTo(3);+ assertThat(global.get("ocr")[1]).isEqualTo(7);+ }++ @Test+ @DisplayName("one scan returns every source tool transition, scoped as asked")+ void transitionScansCoverEverySourceTool() {+ usageRepository.save(new ToolUsageStat("alice", "compare", "ocr", DAY, 2));+ usageRepository.save(new ToolUsageStat("alice", "compare", "ocr", DAY - 10, 3));+ usageRepository.save(new ToolUsageStat("alice", "compare", "merge", DAY, 1));+ usageRepository.save(new ToolUsageStat("alice", "split", "ocr", DAY, 9));+ usageRepository.save(new ToolUsageStat("bob", "compare", "ocr", DAY, 5));++ Map<String, Map<String, long[]>> mine =+ byEdge(usageRepository.edgesByPrincipal("alice", DAY - 30, DAY - 7));+ Map<String, Map<String, long[]>> everyone =+ byEdge(usageRepository.edgesGlobal(DAY - 30, DAY - 7));++ assertThat(mine.keySet()).containsExactlyInAnyOrder("compare", "split");+ assertThat(mine.get("compare").keySet()).containsExactlyInAnyOrder("ocr", "merge");+ assertThat(mine.get("compare").get("ocr")[0]).isEqualTo(2);+ assertThat(mine.get("compare").get("ocr")[1]).isEqualTo(5);+ assertThat(everyone.get("compare").get("ocr")[1]).isEqualTo(10);+ }++ @Test+ @DisplayName("scoping transitions by principals covers a team without leaking other users")+ void transitionScansScopeByPrincipals() {+ usageRepository.save(new ToolUsageStat("alice", "compare", "ocr", DAY, 2));+ usageRepository.save(new ToolUsageStat("carol", "compare", "ocr", DAY, 40));++ Map<String, Map<String, long[]>> team =+ byEdge(+ usageRepository.edgesByPrincipals(+ List.of("alice", "bob"), DAY - 30, DAY - 7));++ assertThat(team.get("compare").get("ocr")[1]).isEqualTo(2);+ }++ @Test+ @DisplayName("runs with no predecessor never surface as transitions")+ void sentinelRowsExcludedFromTransitions() {+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 5));++ assertThat(usageRepository.edgesByPrincipal("alice", DAY - 30, DAY - 7)).isEmpty();+ assertThat(byTool(usageRepository.sumByPrincipal("alice", DAY - 30, DAY - 7)))+ .containsKey("ocr");+ }++ @Test+ @DisplayName("increment updates only the exact row, reporting a miss otherwise")+ void incrementUpdatesExistingRowOnly() {+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 1));++ int hit = usageRepository.incrementCount("alice", NONE, "ocr", DAY, 4);+ int missDay = usageRepository.incrementCount("alice", NONE, "ocr", DAY + 1, 4);+ int missFrom = usageRepository.incrementCount("alice", "compare", "ocr", DAY, 4);++ assertThat(hit).isEqualTo(1);+ assertThat(missDay).isZero();+ assertThat(missFrom).isZero();+ List<ToolUsageStat> rows = usageRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getCount()).isEqualTo(5);+ }++ @Test+ @DisplayName("inserting over an existing row fails instead of clobbering its count")+ void insertNeverOverwritesAnExistingCount() {+ // The concurrency contract: a losing racer must hit the primary key, not+ // silently reset the winner's tally the way an entity merge would.+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 500));++ assertThatThrownBy(() -> usageRepository.insertCount("alice", NONE, "ocr", DAY, 1))+ .isInstanceOf(DataIntegrityViolationException.class);+ }++ @Test+ @DisplayName("insert creates the row when none exists")+ void insertCreatesMissingRow() {+ usageRepository.insertCount("alice", "compare", "ocr", DAY, 1);++ List<ToolUsageStat> rows = usageRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getFromTool()).isEqualTo("compare");+ assertThat(rows.get(0).getCount()).isEqualTo(1);+ }++ @Test+ @DisplayName("the retention sweep prunes only rows past the cutoff")+ void deleteOlderThanPrunes() {+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY - 200, 1));+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 1));++ assertThat(usageRepository.deleteOlderThan(DAY - 180)).isEqualTo(1);+ assertThat(usageRepository.findAll()).hasSize(1);+ }++ @Test+ @DisplayName("chains rank by total count and respect the minimum length")+ void chainsRankAndFilterByLength() {+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY, 2, 3));+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY - 5, 2, 4));+ chainRepository.save(new ToolChainStat("alice", "split>merge>ocr", DAY, 3, 5));+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY - 60, 2, 900));++ List<Object[]> top =+ chainRepository.topByPrincipal("alice", DAY - 30, 2, PageRequest.of(0, 10));+ List<Object[]> longOnly =+ chainRepository.topByPrincipal("alice", DAY - 30, 3, PageRequest.of(0, 10));++ assertThat(top).hasSize(2);+ assertThat(top.get(0)[0]).isEqualTo("compress>ocr");+ assertThat(((Number) top.get(0)[2]).longValue()).isEqualTo(7);+ assertThat(longOnly).hasSize(1);+ assertThat(longOnly.get(0)[0]).isEqualTo("split>merge>ocr");+ }++ @Test+ @DisplayName("the page size caps how many chains come back")+ void chainsRespectThePageSize() {+ chainRepository.save(new ToolChainStat("alice", "a>b", DAY, 2, 9));+ chainRepository.save(new ToolChainStat("alice", "c>d", DAY, 2, 8));+ chainRepository.save(new ToolChainStat("alice", "e>f", DAY, 2, 7));++ assertThat(chainRepository.topByPrincipal("alice", DAY - 30, 2, PageRequest.of(0, 2)))+ .hasSize(2);+ }++ @Test+ @DisplayName("chain scoping covers a team and the whole install separately")+ void chainsScopeByPrincipals() {+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY, 2, 1));+ chainRepository.save(new ToolChainStat("bob", "compress>ocr", DAY, 2, 2));+ chainRepository.save(new ToolChainStat("carol", "compress>ocr", DAY, 2, 4));++ List<Object[]> team =+ chainRepository.topByPrincipals(+ List.of("alice", "bob"), DAY - 30, 2, PageRequest.of(0, 10));+ List<Object[]> global = chainRepository.topGlobal(DAY - 30, 2, PageRequest.of(0, 10));++ assertThat(((Number) team.get(0)[2]).longValue()).isEqualTo(3);+ assertThat(((Number) global.get(0)[2]).longValue()).isEqualTo(7);+ }++ @Test+ @DisplayName("chain increment updates only the exact row, reporting a miss otherwise")+ void chainIncrementUpdatesExistingRowOnly() {+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY, 2, 1));++ int hit = chainRepository.incrementCount("alice", "compress>ocr", DAY, 4);+ int missDay = chainRepository.incrementCount("alice", "compress>ocr", DAY + 1, 4);+ int missChain = chainRepository.incrementCount("alice", "compress>merge", DAY, 4);++ assertThat(hit).isEqualTo(1);+ assertThat(missDay).isZero();+ assertThat(missChain).isZero();+ assertThat(chainRepository.findAll().get(0).getCount()).isEqualTo(5);+ }++ @Test+ @DisplayName("inserting over an existing chain fails instead of clobbering its count")+ void chainInsertNeverOverwritesAnExistingCount() {+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY, 2, 500));++ assertThatThrownBy(() -> chainRepository.insertCount("alice", "compress>ocr", DAY, 2, 1))+ .isInstanceOf(DataIntegrityViolationException.class);+ }++ @Test+ @DisplayName("the retention sweep prunes only chains past the cutoff")+ void chainDeleteOlderThanPrunes() {+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY - 200, 2, 1));+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY, 2, 1));++ assertThat(chainRepository.deleteOlderThan(DAY - 180)).isEqualTo(1);+ assertThat(chainRepository.findAll()).hasSize(1);+ }++ @Test+ @DisplayName("erasure removes a principal's chains and leaves everyone else's")+ void deleteByPrincipalErasesChains() {+ chainRepository.save(new ToolChainStat("alice", "compress>ocr", DAY, 2, 1));+ chainRepository.save(new ToolChainStat("alice", "split>merge", DAY, 2, 1));+ chainRepository.save(new ToolChainStat("bob", "compress>ocr", DAY, 2, 1));++ assertThat(chainRepository.deleteByPrincipal("alice")).isEqualTo(2);++ assertThat(chainRepository.findAll())+ .extracting(ToolChainStat::getPrincipal)+ .containsExactly("bob");+ }++ @Test+ @DisplayName("a chain key at the column limit still stores")+ void maxLengthChainKeyStores() {+ String key = "a".repeat(ToolChainStat.MAX_CHAIN_KEY_LENGTH);++ chainRepository.saveAndFlush(new ToolChainStat("alice", key, DAY, 6, 1));++ assertThat(chainRepository.findAll().get(0).getChainKey()).hasSize(key.length());+ }++ @Test+ @DisplayName("erasure removes a principal's usage rows and leaves everyone else's")+ void deleteByPrincipalErasesUsage() {+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", DAY, 1));+ usageRepository.save(new ToolUsageStat("alice", "compare", "merge", DAY - 5, 2));+ usageRepository.save(new ToolUsageStat("bob", NONE, "ocr", DAY, 3));++ assertThat(usageRepository.deleteByPrincipal("alice")).isEqualTo(2);++ assertThat(usageRepository.findAll())+ .extracting(ToolUsageStat::getPrincipal)+ .containsExactly("bob");+ assertThat(usageRepository.sumByPrincipal("alice", DAY - 30, DAY - 7)).isEmpty();+ }++ @SpringBootConfiguration+ @EntityScan(+ basePackages = {+ "stirling.software.proprietary.security.model",+ "stirling.software.proprietary.model",+ "stirling.software.proprietary.access.model"+ })+ @EnableJpaRepositories(basePackages = {"stirling.software.proprietary.repository"})+ static class TestApp {}+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/repository/ToolUsageErasureDeletesUserTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/repository/ToolUsageErasureDeletesUserTest.javanew file mode 100644index 0000000000..0bd6a82a4e--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/repository/ToolUsageErasureDeletesUserTest.java@@ -0,0 +1,133 @@+package stirling.software.proprietary.repository;++import static org.assertj.core.api.Assertions.assertThat;++import java.util.List;++import org.junit.jupiter.api.DisplayName;+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.persistence.autoconfigure.EntityScan;+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;++import jakarta.persistence.EntityManager;++import stirling.software.proprietary.model.ToolChainStat;+import stirling.software.proprietary.model.ToolUsageStat;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.Authority;+import stirling.software.proprietary.security.model.User;++/**+ * Replays the statement order of {@code UserService.deleteUser}: the two erasure queries run first,+ * then the same {@code User} instance is deleted. A persistence-context clear inside either erasure+ * would detach that instance and turn the delete into a merge, so this guards the whole sequence.+ */+@DataJpaTest+class ToolUsageErasureDeletesUserTest {++ private static final long DAY = 20_000;+ private static final String NONE = ToolUsageStat.NO_PREVIOUS_TOOL;++ @Autowired private UserRepository userRepository;+ @Autowired private ToolUsageStatRepository usageRepository;+ @Autowired private ToolChainStatRepository chainRepository;+ @Autowired private EntityManager entityManager;++ private Long seedUser(String username) {+ User user = new User();+ user.setUsername(username);+ user.setPassword("x");+ new Authority("ROLE_USER", user);+ user.getSettings().put("theme", "dark");+ entityManager.persist(user);++ usageRepository.save(new ToolUsageStat(username, NONE, "ocr", DAY, 1));+ usageRepository.save(new ToolUsageStat(username, "compare", "merge", DAY - 5, 2));+ chainRepository.save(new ToolChainStat(username, "compare>merge", DAY, 2, 2));+ entityManager.flush();+ entityManager.clear();+ return user.getId();+ }++ private long countSettings(Long userId) {+ return ((Number)+ entityManager+ .createNativeQuery(+ "SELECT COUNT(*) FROM user_settings WHERE user_id = :id")+ .setParameter("id", userId)+ .getSingleResult())+ .longValue();+ }++ @Test+ @DisplayName("erasing tool usage then deleting the user removes the user and all its rows")+ void erasureThenDeleteRemovesEverything() {+ Long deletedId = seedUser("tracked");+ Long keptId = seedUser("bystander");++ User user = userRepository.findByUsernameIgnoreCase("tracked").orElseThrow();++ usageRepository.deleteByPrincipal("tracked");+ chainRepository.deleteByPrincipal("tracked");++ // The erasures must leave the user managed, or delete() merges (and cascades) instead+ assertThat(entityManager.contains(user)).isTrue();++ userRepository.delete(user);+ entityManager.flush();+ entityManager.clear();++ assertThat(userRepository.findByUsernameIgnoreCase("tracked")).isEmpty();+ assertThat(+ entityManager+ .createQuery(+ "SELECT a FROM Authority a WHERE a.user.id = :id",+ Authority.class)+ .setParameter("id", deletedId)+ .getResultList())+ .isEmpty();+ assertThat(countSettings(deletedId)).isZero();+ assertThat(usageRepository.findAll())+ .extracting(ToolUsageStat::getPrincipal)+ .containsOnly("bystander");+ assertThat(chainRepository.findAll())+ .extracting(ToolChainStat::getPrincipal)+ .containsOnly("bystander");++ // The bystander is untouched by any of it+ assertThat(userRepository.findByUsernameIgnoreCase("bystander")).isPresent();+ assertThat(countSettings(keptId)).isEqualTo(1);+ }++ @Test+ @DisplayName("erasure does not detach unrelated entities loaded earlier in the transaction")+ void erasureLeavesTheContextIntact() {+ seedUser("tracked");++ User user = userRepository.findByUsernameIgnoreCase("tracked").orElseThrow();+ List<ToolUsageStat> before = usageRepository.findAll();++ usageRepository.deleteByPrincipal("tracked");+ chainRepository.deleteByPrincipal("tracked");++ assertThat(entityManager.contains(user)).isTrue();+ assertThat(before).isNotEmpty();+ }++ @SpringBootConfiguration+ @EntityScan(+ basePackages = {+ "stirling.software.proprietary.security.model",+ "stirling.software.proprietary.model",+ "stirling.software.proprietary.access.model"+ })+ @EnableJpaRepositories(+ basePackages = {+ "stirling.software.proprietary.repository",+ "stirling.software.proprietary.security.database.repository"+ })+ static class TestApp {}+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.javaindex dd0cb4f1ca..8d716f1c4f 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/service/UserServiceTest.java@@ -31,6 +31,8 @@ import stirling.software.common.model.enumeration.Role;import stirling.software.common.model.exception.UnsupportedProviderException;import stirling.software.proprietary.access.repository.ResourceGrantRepository;import stirling.software.proprietary.model.Team;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;import stirling.software.proprietary.security.database.repository.AuthorityRepository;import stirling.software.proprietary.security.database.repository.PersistentLoginRepository;import stirling.software.proprietary.security.database.repository.UserRepository;@@ -78,6 +80,8 @@ class UserServiceTest {@Mock private TeamMembershipService teamMembershipService;@Mock private ApiKeyAuthenticationService apiKeyAuthenticationService;+ @Mock private ToolUsageStatRepository toolUsageStatRepository;+ @Mock private ToolChainStatRepository toolChainStatRepository;@Mockprivate org.springframework.beans.factory.ObjectProvider<@@ -373,6 +377,56 @@ class UserServiceTest {verify(userService).invalidateUserSessions("target");}+ @Test+ void deleteUser_erasesToolUsage() {+ User user = new User();+ user.setId(4L);+ user.setUsername("tracked");++ when(userRepository.findByUsernameIgnoreCase("tracked")).thenReturn(Optional.of(user));+ when(workflowSessionRepository.findByOwnerOrderByCreatedAtDesc(user)).thenReturn(List.of());+ when(storedFileRepository.findAllByOwner(user)).thenReturn(List.of());+ when(fileShareRepository.findBySharedWithUser(user)).thenReturn(List.of());++ userService.deleteUser("tracked");++ // Every table keys on the username, so a recreated name would inherit the old profile+ verify(toolUsageStatRepository).deleteByPrincipal("tracked");+ verify(toolChainStatRepository).deleteByPrincipal("tracked");+ // The erasures must not displace the user row itself+ verify(userRepository).delete(user);+ }++ @Test+ void changeUsername_erasesToolUsageHeldUnderTheOldName()+ throws SQLException, UnsupportedProviderException {+ User user = new User();+ user.setId(5L);+ user.setUsername("oldname");++ userService.changeUsername(user, "newname");++ assertEquals("newname", user.getUsername());+ verify(userRepository).save(user);+ verify(toolUsageStatRepository).deleteByPrincipal("oldname");+ verify(toolChainStatRepository).deleteByPrincipal("oldname");+ verify(toolUsageStatRepository, never()).deleteByPrincipal("newname");+ verify(toolChainStatRepository, never()).deleteByPrincipal("newname");+ }++ @Test+ void changeUsername_toTheSameName_keepsToolUsage()+ throws SQLException, UnsupportedProviderException {+ User user = new User();+ user.setId(6L);+ user.setUsername("samename");++ userService.changeUsername(user, "samename");++ verify(toolUsageStatRepository, never()).deleteByPrincipal(any());+ verify(toolChainStatRepository, never()).deleteByPrincipal(any());+ }+@Testvoid deleteUser_withNoRelatedData_deletesUserSuccessfully() {User user = new User();diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolKeyRegistryTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolKeyRegistryTest.javanew file mode 100644index 0000000000..ccd7f7b42b--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolKeyRegistryTest.java@@ -0,0 +1,94 @@+package stirling.software.proprietary.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assumptions.assumeTrue;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.Paths;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;++/**+ * Binds {@link ToolKeyRegistry} to the frontend's tool ids. The registry is a hand-maintained copy+ * of a list that lives in TypeScript, so without this a tool added to the UI would silently stop+ * being recorded - the least visible failure this feature has, since the ranking would simply never+ * mention it.+ */+class ToolKeyRegistryTest {++ /** Each {@code export const SOMETHING_TOOL_IDS = [...] as const;} block. */+ private static final Pattern TOOL_ID_ARRAY =+ Pattern.compile(+ "export const \\w*TOOL_IDS\\s*=\\s*\\[(.*?)\\]\\s*as const;", Pattern.DOTALL);++ private static final Pattern QUOTED = Pattern.compile("\"([^\"]+)\"");++ /**+ * Every file that defines ids. The core file's proprietary and prototype imports resolve to+ * empty stubs; the build-specific overrides beside them are where those ids actually live.+ */+ private static final List<String> SOURCES =+ List.of(+ "frontend/editor/src/core/types/toolId.ts",+ "frontend/editor/src/proprietary/types/proprietaryToolId.ts",+ "frontend/editor/src/prototypes/types/prototypeToolId.ts");++ @Test+ @DisplayName("the registry lists exactly the tool ids the frontend can send")+ void registryMatchesFrontend() throws IOException {+ Path root = repositoryRoot();+ assumeTrue(root != null, "frontend sources not present in this build");++ Set<String> fromFrontend = new LinkedHashSet<>();+ for (String source : SOURCES) {+ fromFrontend.addAll(toolIdsIn(Files.readString(root.resolve(source))));+ }++ assertThat(fromFrontend).isNotEmpty();+ assertThat(ToolKeyRegistry.DEFAULT_KEYS)+ .as(+ "ToolKeyRegistry and the frontend tool ids have drifted; add the new id to"+ + " the registry so its usage is recorded")+ .containsExactlyInAnyOrderElementsOf(fromFrontend);+ }++ @Test+ @DisplayName("the chain column fits a full-length chain of the longest keys")+ void keysFitTheChainColumn() {+ assertThat(ToolKeyRegistry.MAX_KEY_LENGTH).isGreaterThan(0);+ assertThat(ToolKeyRegistry.DEFAULT_KEYS)+ .allSatisfy(key -> assertThat(key).doesNotContain(">"));+ }++ private static Set<String> toolIdsIn(String source) {+ Set<String> ids = new LinkedHashSet<>();+ Matcher arrays = TOOL_ID_ARRAY.matcher(source);+ while (arrays.find()) {+ Matcher quoted = QUOTED.matcher(arrays.group(1));+ while (quoted.find()) {+ ids.add(quoted.group(1));+ }+ }+ return ids;+ }++ /** Walks up from the working directory, which varies with how the test was launched. */+ private static Path repositoryRoot() {+ Path candidate = Paths.get("").toAbsolutePath();+ while (candidate != null) {+ if (Files.exists(candidate.resolve(SOURCES.get(0)))) {+ return candidate;+ }+ candidate = candidate.getParent();+ }+ return null;+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolRecommendationServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolRecommendationServiceTest.javanew file mode 100644index 0000000000..270452d6fe--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolRecommendationServiceTest.java@@ -0,0 +1,341 @@+package stirling.software.proprietary.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.ArgumentMatchers.anyLong;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.util.List;+import java.util.Map;+import java.util.Set;++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.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.mock.env.MockEnvironment;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.service.ToolRecommendationService.ToolRecommendation;+import stirling.software.proprietary.service.ToolRecommendationService.ToolWorkflow;+import stirling.software.proprietary.service.ToolRecommendationService.WorkflowScope;+import stirling.software.proprietary.service.ToolUsageSignalService.TeamScope;+import stirling.software.proprietary.service.ToolUsageSignalService.ToolChainSummary;++@ExtendWith(MockitoExtension.class)+class ToolRecommendationServiceTest {++ private static final String PRINCIPAL = "alice";++ /** Short stand-in names for real tools, so a ranking of eight stays readable. */+ private static final ToolKeyRegistry TOOL_KEYS =+ ToolKeyRegistry.forKeys(+ Set.of(+ "a",+ "b",+ "c",+ "d",+ "e",+ "f",+ "g",+ "h",+ "compare",+ "compress",+ "merge",+ "ocr",+ "split",+ "watermark"));++ private static final TeamScope TEAM = new TeamScope(List.of(7L), List.of("bob", "carol"), true);++ @Mock private ToolUsageSignalService signalService;++ private ApplicationProperties properties;+ private MockEnvironment environment;+ private ToolRecommendationService service;++ @BeforeEach+ void setUp() {+ properties = new ApplicationProperties();+ properties.getSystem().setEnableAnalytics(true);+ environment = new MockEnvironment();+ service = new ToolRecommendationService(signalService, TOOL_KEYS, properties, environment);+ lenient().when(signalService.resolveTeamScope(anyString())).thenReturn(TeamScope.none());+ lenient()+ .when(signalService.userFrequency(anyString(), anyLong(), anyLong()))+ .thenReturn(Map.of());+ lenient().when(signalService.globalFrequency(anyLong(), anyLong())).thenReturn(Map.of());+ lenient()+ .when(signalService.userTransitions(anyString(), anyLong(), anyLong()))+ .thenReturn(Map.of());+ lenient().when(signalService.globalTransitions(anyLong(), anyLong())).thenReturn(Map.of());+ lenient()+ .when(signalService.teamFrequency(any(TeamScope.class), anyLong(), anyLong()))+ .thenReturn(Map.of());+ lenient()+ .when(signalService.teamTransitions(any(TeamScope.class), anyLong(), anyLong()))+ .thenReturn(Map.of());+ }++ private static List<String> toolKeys(List<ToolRecommendation> recommendations) {+ return recommendations.stream().map(ToolRecommendation::toolKey).toList();+ }++ private static ToolChainSummary chain(long count, String... tools) {+ return new ToolChainSummary(List.of(tools), count);+ }++ @Nested+ @DisplayName("Workflows")+ class Workflows {++ @BeforeEach+ void noChainsAnywhere() {+ lenient()+ .when(signalService.userChains(anyString(), anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of());+ lenient()+ .when(+ signalService.teamChains(+ any(TeamScope.class), anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of());+ lenient()+ .when(signalService.globalChains(anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of());+ }++ @Test+ @DisplayName("the caller's own repeated workflows come first")+ void ownWorkflowsFirst() {+ when(signalService.userChains(eq(PRINCIPAL), anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(9, "compress", "watermark")));+ when(signalService.globalChains(anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(400, "split", "merge")));++ List<ToolWorkflow> result = service.getWorkflows(PRINCIPAL, 2, 6);++ assertThat(result)+ .containsExactly(+ new ToolWorkflow(+ List.of("compress", "watermark"), 9, WorkflowScope.USER),+ new ToolWorkflow(List.of("split", "merge"), 400, WorkflowScope.GLOBAL));+ }++ @Test+ @DisplayName("a workflow already seen at a narrower scope is not repeated")+ void narrowerScopeWins() {+ when(signalService.userChains(eq(PRINCIPAL), anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(2, "compress", "ocr")));+ when(signalService.globalChains(anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(900, "compress", "ocr")));++ assertThat(service.getWorkflows(PRINCIPAL, 2, 6))+ .containsExactly(+ new ToolWorkflow(List.of("compress", "ocr"), 2, WorkflowScope.USER));+ }++ @Test+ @DisplayName("team workflows are only consulted for a team with other members")+ void soloTeamIsSkipped() {+ when(signalService.resolveTeamScope(PRINCIPAL)).thenReturn(TeamScope.none());++ service.getWorkflows(PRINCIPAL, 2, 6);++ verify(signalService, never())+ .teamChains(any(TeamScope.class), anyLong(), anyInt(), anyInt());+ }++ @Test+ @DisplayName("a team's workflows sit between the caller's own and the install's")+ void teamWorkflowsRankBetween() {+ when(signalService.resolveTeamScope(PRINCIPAL)).thenReturn(TEAM);+ when(signalService.userChains(eq(PRINCIPAL), anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(1, "a", "b")));+ when(signalService.teamChains(eq(TEAM), anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(2, "c", "d")));+ when(signalService.globalChains(anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(3, "e", "f")));++ assertThat(service.getWorkflows(PRINCIPAL, 2, 6))+ .extracting(ToolWorkflow::scope)+ .containsExactly(WorkflowScope.USER, WorkflowScope.TEAM, WorkflowScope.GLOBAL);+ }++ @Test+ @DisplayName("a single tool is never returned as a workflow")+ void minimumLengthIsTwo() {+ service.getWorkflows(PRINCIPAL, 1, 6);++ verify(signalService)+ .userChains(+ eq(PRINCIPAL),+ anyLong(),+ eq(ToolRecommendationService.MIN_WORKFLOW_TOOLS),+ anyInt());+ }++ @Test+ @DisplayName("the limit is capped and never exceeded across scopes")+ void limitIsCapped() {+ when(signalService.userChains(eq(PRINCIPAL), anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(9, "a", "b"), chain(8, "c", "d")));+ when(signalService.globalChains(anyLong(), anyInt(), anyInt()))+ .thenReturn(List.of(chain(7, "e", "f")));++ assertThat(service.getWorkflows(PRINCIPAL, 2, 2)).hasSize(2);+ assertThat(service.getWorkflows(PRINCIPAL, 2, 999))+ .hasSizeLessThanOrEqualTo(ToolRecommendationService.MAX_LIMIT);+ }++ @Test+ @DisplayName("withheld analytics consent serves no workflow history")+ void consentGatesWorkflows() {+ properties.getSystem().setEnableAnalytics(false);++ assertThat(service.getWorkflows(PRINCIPAL, 2, 6)).isEmpty();+ verifyNoInteractions(signalService);+ }+ }++ @Nested+ @DisplayName("Scoring")+ class Scoring {++ @Test+ @DisplayName("transitions from the current tool outrank plain usage frequency")+ void transitionsOutrankFrequency() {+ when(signalService.userTransitions(eq(PRINCIPAL), anyLong(), anyLong()))+ .thenReturn(Map.of("compare", Map.of("ocr", 8.0)));+ when(signalService.userFrequency(eq(PRINCIPAL), anyLong(), anyLong()))+ .thenReturn(Map.of("merge", 150.0, "ocr", 3.0));++ List<ToolRecommendation> result = service.getRecommendations(PRINCIPAL, "compare", 6);++ assertThat(toolKeys(result)).containsExactly("ocr", "merge");+ }++ @Test+ @DisplayName("the user's own signal outranks an equally strong global signal")+ void userSignalOutranksGlobal() {+ when(signalService.userFrequency(eq(PRINCIPAL), anyLong(), anyLong()))+ .thenReturn(Map.of("split", 6.0));+ when(signalService.globalFrequency(anyLong(), anyLong()))+ .thenReturn(Map.of("compress", 6.0));++ List<ToolRecommendation> result = service.getRecommendations(PRINCIPAL, null, 6);++ assertThat(toolKeys(result)).containsExactly("split", "compress");+ }++ @Test+ @DisplayName("normalization stops huge global counts from swamping personal patterns")+ void globalCountsAreNormalized() {+ // Whole install uses compress a million times; the user personally always+ // reaches for OCR after compare. OCR must still win.+ when(signalService.userTransitions(eq(PRINCIPAL), anyLong(), anyLong()))+ .thenReturn(Map.of("compare", Map.of("ocr", 15.0)));+ when(signalService.globalFrequency(anyLong(), anyLong()))+ .thenReturn(Map.of("compress", 1_500_000.0));++ List<ToolRecommendation> result = service.getRecommendations(PRINCIPAL, "compare", 6);++ assertThat(toolKeys(result)).containsExactly("ocr", "compress");+ }++ @Test+ @DisplayName("team signals rank between personal and install-wide ones")+ void teamSignalsRankBetween() {+ when(signalService.resolveTeamScope(PRINCIPAL)).thenReturn(TEAM);+ when(signalService.userFrequency(eq(PRINCIPAL), anyLong(), anyLong()))+ .thenReturn(Map.of("split", 5.0));+ when(signalService.teamFrequency(eq(TEAM), anyLong(), anyLong()))+ .thenReturn(Map.of("merge", 5.0));+ when(signalService.globalFrequency(anyLong(), anyLong()))+ .thenReturn(Map.of("compress", 5.0));++ List<ToolRecommendation> result = service.getRecommendations(PRINCIPAL, null, 6);++ assertThat(toolKeys(result)).containsExactly("split", "merge", "compress");+ }++ @Test+ @DisplayName("no team queries run for a user without teammates")+ void teamQueriesSkippedWithoutTeam() {+ service.getRecommendations(PRINCIPAL, "compare", 6);++ verify(signalService, never())+ .teamFrequency(any(TeamScope.class), anyLong(), anyLong());+ verify(signalService, never())+ .teamTransitions(any(TeamScope.class), anyLong(), anyLong());+ }++ @Test+ @DisplayName("the current tool is never recommended back to the user")+ void currentToolExcluded() {+ when(signalService.userFrequency(eq(PRINCIPAL), anyLong(), anyLong()))+ .thenReturn(Map.of("compare", 55.0, "ocr", 3.0));++ List<ToolRecommendation> result = service.getRecommendations(PRINCIPAL, "compare", 6);++ assertThat(toolKeys(result)).containsExactly("ocr");+ }++ @Test+ @DisplayName("limit caps the list; non-positive limit falls back to the default")+ void limitApplied() {+ when(signalService.userFrequency(eq(PRINCIPAL), anyLong(), anyLong()))+ .thenReturn(+ Map.of(+ "a", 9.0, "b", 8.0, "c", 7.0, "d", 6.0, "e", 5.0, "f", 4.0, "g",+ 3.0, "h", 2.0));++ assertThat(service.getRecommendations(PRINCIPAL, null, 2)).hasSize(2);+ assertThat(service.getRecommendations(PRINCIPAL, null, 0))+ .hasSize(ToolRecommendationService.DEFAULT_LIMIT);+ assertThat(service.getRecommendations(PRINCIPAL, null, 999)).hasSize(8);+ }++ @Test+ @DisplayName("no usage data at all produces an empty list (frontend falls back)")+ void coldStartReturnsEmpty() {+ assertThat(service.getRecommendations(PRINCIPAL, "compare", 6)).isEmpty();+ }++ @Test+ @DisplayName("disabled feature returns empty without touching any signal")+ void disabledFeatureShortCircuits() {+ properties.getToolRecommendations().setEnabled(false);++ assertThat(service.getRecommendations(PRINCIPAL, "compare", 6)).isEmpty();+ verifyNoInteractions(signalService);+ }++ @Test+ @DisplayName("no analytics consent returns empty without touching any signal")+ void withheldAnalyticsConsentShortCircuits() {+ properties.getSystem().setEnableAnalytics(null);++ assertThat(service.getRecommendations(PRINCIPAL, "compare", 6)).isEmpty();+ verifyNoInteractions(signalService);+ }++ @Test+ @DisplayName("no transition queries run when there is no current tool")+ void noTransitionQueriesWithoutContext() {+ service.getRecommendations(PRINCIPAL, null, 6);++ verify(signalService, never()).userTransitions(anyString(), anyLong(), anyLong());+ verify(signalService, never()).globalTransitions(anyLong(), anyLong());+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsagePostgresConcurrencyTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsagePostgresConcurrencyTest.javanew file mode 100644index 0000000000..264c9142a4--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsagePostgresConcurrencyTest.java@@ -0,0 +1,223 @@+package stirling.software.proprietary.service;++import static org.assertj.core.api.Assertions.assertThat;++import java.util.List;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+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.data.jpa.repository.config.EnableJpaRepositories;+import org.springframework.test.context.DynamicPropertyRegistry;+import org.springframework.test.context.DynamicPropertySource;+import org.springframework.transaction.annotation.Propagation;+import org.springframework.transaction.annotation.Transactional;+import org.testcontainers.containers.PostgreSQLContainer;+import org.testcontainers.junit.jupiter.Container;+import org.testcontainers.junit.jupiter.Testcontainers;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.model.ToolChainStat;+import stirling.software.proprietary.model.ToolUsageStat;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;++/**+ * Multi-node safety: several application instances share one Postgres, so every write path has to+ * survive concurrent callers on separate connections. Runs against real Postgres because the+ * behaviour under test - a failed insert aborting its transaction, and row-level locking of {@code+ * count = count + 1} - is database-specific and cannot be trusted from H2 alone. Skipped when+ * Docker is unavailable.+ */+@DataJpaTest+@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)+@Testcontainers(disabledWithoutDocker = true)+class ToolUsagePostgresConcurrencyTest {++ private static final String NONE = ToolUsageStat.NO_PREVIOUS_TOOL;+ private static final int NODES = 16;+ private static final int RUNS_PER_NODE = 25;++ /** A single input document: fresh, or one that has already been compressed. */+ private static final List<List<String>> FRESH = List.of(List.of());++ private static final List<List<String>> AFTER_COMPARE = List.of(List.of("compare"));++ @Container+ static PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine");++ @DynamicPropertySource+ static void datasource(DynamicPropertyRegistry registry) {+ registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);+ registry.add("spring.datasource.username", POSTGRES::getUsername);+ registry.add("spring.datasource.password", POSTGRES::getPassword);+ registry.add("spring.datasource.driver-class-name", () -> "org.postgresql.Driver");+ registry.add("spring.jpa.hibernate.ddl-auto", () -> "create-drop");+ }++ @Autowired private ToolUsageStatRepository usageRepository;+ @Autowired private ToolChainStatRepository chainRepository;++ private ToolUsageTrackingService trackingService;++ @BeforeEach+ void setUp() {+ ApplicationProperties properties = new ApplicationProperties();+ properties.getSystem().setEnableAnalytics(true);+ trackingService =+ new ToolUsageTrackingService(+ usageRepository, chainRepository, new ToolKeyRegistry(), properties);+ }++ /** Runs {@code task} on {@code NODES} threads at once; returns how many threw. */+ private static int race(int threads, Runnable task) throws InterruptedException {+ ExecutorService pool = Executors.newFixedThreadPool(threads);+ CountDownLatch start = new CountDownLatch(1);+ CountDownLatch done = new CountDownLatch(threads);+ AtomicInteger failures = new AtomicInteger();+ for (int i = 0; i < threads; i++) {+ pool.submit(+ () -> {+ try {+ start.await();+ task.run();+ } catch (Exception e) {+ failures.incrementAndGet();+ } finally {+ done.countDown();+ }+ });+ }+ start.countDown();+ assertThat(done.await(60, TimeUnit.SECONDS)).isTrue();+ pool.shutdownNow();+ return failures.get();+ }++ @Test+ @Transactional(propagation = Propagation.NOT_SUPPORTED)+ @DisplayName("simultaneous nodes creating the day's first row lose no counts")+ void concurrentFirstRunOfDayKeepsEveryCount() throws InterruptedException {+ usageRepository.deleteAll();+ long day = ToolUsageTrackingService.currentEpochDay();++ // Every thread starts with no row present, so they all take the insert path at once:+ // exactly one wins the primary key and the rest must fall back to incrementing.+ int failures = race(NODES, () -> trackingService.recordUsage("alice", "compress", FRESH));++ assertThat(failures).isZero();+ List<ToolUsageStat> rows = usageRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getCount()).isEqualTo(NODES);+ assertThat(rows.get(0).getFromTool()).isEqualTo(NONE);+ assertThat(rows.get(0).getEpochDay()).isEqualTo(day);+ }++ @Test+ @Transactional(propagation = Propagation.NOT_SUPPORTED)+ @DisplayName("sustained concurrent writes tally exactly, with no lost updates")+ void concurrentIncrementsAreLossless() throws InterruptedException {+ usageRepository.deleteAll();+ chainRepository.deleteAll();++ int failures =+ race(+ NODES,+ () -> {+ for (int i = 0; i < RUNS_PER_NODE; i++) {+ trackingService.recordUsage("alice", "ocr", AFTER_COMPARE);+ }+ });++ assertThat(failures).isZero();+ List<ToolUsageStat> rows = usageRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getCount()).isEqualTo((long) NODES * RUNS_PER_NODE);+ assertThat(rows.get(0).getFromTool()).isEqualTo("compare");+ }++ @Test+ @Transactional(propagation = Propagation.NOT_SUPPORTED)+ @DisplayName("chain rows survive the same first-of-day insert race as usage rows")+ void concurrentChainWritesKeepEveryCount() throws InterruptedException {+ chainRepository.deleteAll();+ long day = ToolUsageTrackingService.currentEpochDay();++ int failures =+ race(NODES, () -> trackingService.recordUsage("alice", "ocr", AFTER_COMPARE));++ assertThat(failures).isZero();+ List<ToolChainStat> rows = chainRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getChainKey()).isEqualTo("compare>ocr");+ assertThat(rows.get(0).getChainLength()).isEqualTo(2);+ assertThat(rows.get(0).getCount()).isEqualTo(NODES);+ assertThat(rows.get(0).getEpochDay()).isEqualTo(day);+ }++ @Test+ @Transactional(propagation = Propagation.NOT_SUPPORTED)+ @DisplayName("the native chain insert matches the schema Hibernate generates on Postgres")+ void nativeChainInsertMatchesGeneratedSchema() {+ chainRepository.deleteAll();+ long day = ToolUsageTrackingService.currentEpochDay();++ chainRepository.insertCount("alice", "compare>ocr", day, 2, 3);++ List<ToolChainStat> rows = chainRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getCount()).isEqualTo(3);+ assertThat(rows.get(0).getChainLength()).isEqualTo(2);+ }++ @Test+ @Transactional(propagation = Propagation.NOT_SUPPORTED)+ @DisplayName("the retention sweep is idempotent when every node runs it together")+ void concurrentRetentionSweepsAreIdempotent() throws InterruptedException {+ usageRepository.deleteAll();+ long day = ToolUsageTrackingService.currentEpochDay();+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", day - 400, 5));+ usageRepository.save(new ToolUsageStat("alice", NONE, "ocr", day, 7));++ int failures = race(NODES, () -> trackingService.cleanupOldStats());++ assertThat(failures).isZero();+ List<ToolUsageStat> rows = usageRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getCount()).isEqualTo(7);+ }++ @Test+ @Transactional(propagation = Propagation.NOT_SUPPORTED)+ @DisplayName("the native insert matches the schema Hibernate generates on Postgres")+ void nativeInsertMatchesGeneratedSchema() {+ usageRepository.deleteAll();+ long day = ToolUsageTrackingService.currentEpochDay();++ usageRepository.insertCount("alice", "compare", "ocr", day, 3);++ List<ToolUsageStat> rows = usageRepository.findAll();+ assertThat(rows).hasSize(1);+ assertThat(rows.get(0).getCount()).isEqualTo(3);+ }++ @SpringBootConfiguration+ @EntityScan(+ basePackages = {+ "stirling.software.proprietary.security.model",+ "stirling.software.proprietary.model",+ "stirling.software.proprietary.access.model"+ })+ @EnableJpaRepositories(basePackages = {"stirling.software.proprietary.repository"})+ static class TestApp {}+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageSignalCachingTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageSignalCachingTest.javanew file mode 100644index 0000000000..e0c222accd--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageSignalCachingTest.java@@ -0,0 +1,235 @@+package stirling.software.proprietary.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyCollection;+import static org.mockito.ArgumentMatchers.anyLong;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.time.Duration;+import java.util.List;+import java.util.Optional;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;++import stirling.software.common.cluster.KeyValueCache;+import stirling.software.common.cluster.inprocess.InProcessKeyValueCache;+import stirling.software.proprietary.model.Team;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.repository.TeamMembershipRepository;+import stirling.software.proprietary.service.ToolUsageSignalService.TeamScope;++/**+ * The team and install-wide aggregates are the only expensive queries in this feature. These tests+ * pin down what the two cache tiers buy: repeat callers on one node cost one scan, and a second+ * node sharing a backplane does not pay for that scan again.+ */+class ToolUsageSignalCachingTest {++ private ToolUsageStatRepository usageRepository;+ private ToolChainStatRepository chainRepository;+ private UserRepository userRepository;+ private TeamMembershipRepository membershipRepository;+ private KeyValueCache backplane;++ private ToolUsageSignalService node;++ @BeforeEach+ void setUp() {+ usageRepository = mock(ToolUsageStatRepository.class);+ chainRepository = mock(ToolChainStatRepository.class);+ userRepository = mock(UserRepository.class);+ membershipRepository = mock(TeamMembershipRepository.class);+ backplane = new InProcessKeyValueCache();++ lenient()+ .when(usageRepository.sumGlobal(anyLong(), anyLong()))+ .thenReturn(List.<Object[]>of(new Object[] {"compress", 5L, 50L}));+ lenient()+ .when(usageRepository.edgesGlobal(anyLong(), anyLong()))+ .thenReturn(List.<Object[]>of(new Object[] {"compare", "ocr", 2L, 8L}));+ lenient()+ .when(usageRepository.sumByPrincipals(anyCollection(), anyLong(), anyLong()))+ .thenReturn(List.<Object[]>of(new Object[] {"merge", 1L, 4L}));+ lenient()+ .when(membershipRepository.findTeamIdsByUsername(anyString()))+ .thenReturn(List.of());+ lenient()+ .when(membershipRepository.findUsernamesByTeamIds(anyCollection(), any()))+ .thenReturn(List.of());++ node = nodeSharing(backplane);+ }++ /** Another application instance: its own local cache, the same cluster backplane. */+ private ToolUsageSignalService nodeSharing(KeyValueCache shared) {+ return nodeWith(Optional.of(shared));+ }++ private ToolUsageSignalService nodeWith(Optional<KeyValueCache> shared) {+ return new ToolUsageSignalService(+ usageRepository,+ chainRepository,+ Optional.of(userRepository),+ Optional.of(membershipRepository),+ shared);+ }++ private void teamOf(String username, long teamId, List<String> roster) {+ Team team = new Team();+ team.setId(teamId);+ User user = new User();+ user.setUsername(username);+ user.setTeam(team);+ when(userRepository.findByUsernameIgnoreCase(username)).thenReturn(Optional.of(user));+ lenient()+ .when(userRepository.findUsernamesByTeamIds(eq(List.of(teamId)), any()))+ .thenReturn(roster);+ }++ @Test+ @DisplayName("500 users asking for the global signal cost one install-wide scan")+ void globalFrequencyScansOncePerWindow() {+ for (int i = 0; i < 500; i++) {+ assertThat(node.globalFrequency(10, 20)).containsEntry("compress", 55.0);+ }++ verify(usageRepository, times(1)).sumGlobal(10, 20);+ }++ @Test+ @DisplayName("one scan serves every source tool, so a caller cannot ask for another")+ void transitionsScanOnceForAllSourceTools() {+ for (int i = 0; i < 100; i++) {+ assertThat(node.globalTransitions(10, 20)).containsKey("compare");+ }++ verify(usageRepository, times(1)).edgesGlobal(10, 20);+ }++ @Test+ @DisplayName("a second node reuses the scan the first one paid for")+ void clusterNodesShareOneScan() {+ ToolUsageSignalService otherNode = nodeSharing(backplane);++ assertThat(node.globalFrequency(10, 20)).containsEntry("compress", 55.0);+ assertThat(otherNode.globalFrequency(10, 20)).containsEntry("compress", 55.0);++ verify(usageRepository, times(1)).sumGlobal(10, 20);+ }++ @Test+ @DisplayName("without a shared backplane each node pays for its own scan")+ void separateBackplanesDoNotShare() {+ ToolUsageSignalService otherNode = nodeSharing(new InProcessKeyValueCache());++ node.globalFrequency(10, 20);+ otherNode.globalFrequency(10, 20);++ verify(usageRepository, times(2)).sumGlobal(10, 20);+ }++ @Test+ @DisplayName("no backplane at all still caches locally, since the cluster tier is a bonus")+ void noBackplaneStillCachesLocally() {+ ToolUsageSignalService standalone = nodeWith(Optional.empty());++ assertThat(standalone.globalFrequency(10, 20)).containsEntry("compress", 55.0);+ assertThat(standalone.globalFrequency(10, 20)).containsEntry("compress", 55.0);++ verify(usageRepository, times(1)).sumGlobal(10, 20);+ }++ @Test+ @DisplayName("a broken backplane costs a query, never an error")+ void brokenBackplaneFallsThroughToTheQuery() {+ KeyValueCache broken = mock(KeyValueCache.class);+ when(broken.get(anyString(), anyString())).thenThrow(new RuntimeException("valkey down"));+ lenient()+ .doThrow(new RuntimeException("valkey down"))+ .when(broken)+ .put(anyString(), anyString(), anyString(), any(Duration.class));++ assertThat(nodeSharing(broken).globalFrequency(10, 20)).containsEntry("compress", 55.0);+ }++ @Test+ @DisplayName("team aggregates are shared by every member of that team")+ void teamAggregatesCachePerTeam() {+ TeamScope teamSeven = new TeamScope(List.of(7L), List.of("bob", "carol"), true);+ TeamScope teamEight = new TeamScope(List.of(8L), List.of("dave"), true);++ for (int i = 0; i < 50; i++) {+ node.teamFrequency(teamSeven, 10, 20);+ }+ node.teamFrequency(teamEight, 10, 20);++ verify(usageRepository, times(1)).sumByPrincipals(List.of("bob", "carol"), 10, 20);+ verify(usageRepository, times(1)).sumByPrincipals(List.of("dave"), 10, 20);+ }++ @Test+ @DisplayName("a new day's window is a new cache key, so data does not go stale forever")+ void windowChangeMissesCache() {+ node.globalFrequency(10, 20);+ node.globalFrequency(11, 21);++ verify(usageRepository, times(1)).sumGlobal(10, 20);+ verify(usageRepository, times(1)).sumGlobal(11, 21);+ }++ @Test+ @DisplayName("a transient team lookup failure is not cached as 'this user has no team'")+ void failedTeamResolutionIsNotCached() {+ Team team = new Team();+ team.setId(7L);+ User alice = new User();+ alice.setUsername("alice");+ alice.setTeam(team);+ // Chained, not re-stubbed: re-stubbing would invoke the throwing answer to do it.+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenThrow(new RuntimeException("pool exhausted"))+ .thenReturn(Optional.of(alice));+ when(userRepository.findUsernamesByTeamIds(eq(List.of(7L)), any()))+ .thenReturn(List.of("alice", "bob"));++ TeamScope duringOutage = node.resolveTeamScope("alice");++ assertThat(duringOutage.hasMembers()).isFalse();+ assertThat(duringOutage.resolved()).isFalse();+ assertThat(node.resolveTeamScope("alice").principals()).containsExactly("alice", "bob");+ }++ @Test+ @DisplayName("a successfully resolved team is cached")+ void resolvedTeamIsCached() {+ teamOf("alice", 7L, List.of("alice", "bob"));++ node.resolveTeamScope("alice");+ node.resolveTeamScope("alice");++ verify(userRepository, times(1)).findUsernamesByTeamIds(eq(List.of(7L)), any());+ }++ @Test+ @DisplayName("'this user has no team' is an answer, so it is cached too")+ void emptyTeamResolutionIsCached() {+ when(userRepository.findByUsernameIgnoreCase("solo")).thenReturn(Optional.empty());++ assertThat(node.resolveTeamScope("solo")).isEqualTo(TeamScope.none());+ assertThat(node.resolveTeamScope("solo")).isEqualTo(TeamScope.none());++ verify(userRepository, times(1)).findByUsernameIgnoreCase("solo");+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageSignalServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageSignalServiceTest.javanew file mode 100644index 0000000000..4124f3814b--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageSignalServiceTest.java@@ -0,0 +1,325 @@+package stirling.software.proprietary.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyCollection;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.lenient;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.util.Collection;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.stream.IntStream;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.ExtendWith;+import org.mockito.ArgumentCaptor;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.data.domain.Pageable;++import stirling.software.common.cluster.inprocess.InProcessKeyValueCache;+import stirling.software.proprietary.model.Team;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;+import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.repository.TeamMembershipRepository;+import stirling.software.proprietary.service.ToolUsageSignalService.TeamScope;+import stirling.software.proprietary.service.ToolUsageSignalService.ToolChainSummary;++@ExtendWith(MockitoExtension.class)+class ToolUsageSignalServiceTest {++ @Mock private ToolUsageStatRepository usageRepository;+ @Mock private ToolChainStatRepository chainRepository;+ @Mock private UserRepository userRepository;+ @Mock private TeamMembershipRepository membershipRepository;++ private ToolUsageSignalService service;++ @BeforeEach+ void setUp() {+ service = signalService(Optional.of(userRepository));+ // Most tests describe a self-hosted install, where the legacy team column is the roster.+ lenient().when(membershipRepository.findTeamIdsByUsername(any())).thenReturn(List.of());+ lenient()+ .when(membershipRepository.findUsernamesByTeamIds(anyCollection(), any()))+ .thenReturn(List.of());+ }++ private ToolUsageSignalService signalService(Optional<UserRepository> users) {+ return new ToolUsageSignalService(+ usageRepository,+ chainRepository,+ users,+ Optional.of(membershipRepository),+ Optional.of(new InProcessKeyValueCache()));+ }++ private static Object[] row(String tool, long recent, long total) {+ return new Object[] {tool, recent, total};+ }++ private static Object[] edgeRow(String fromTool, String tool, Long recent, Long total) {+ return new Object[] {fromTool, tool, recent, total};+ }++ private static Object[] chainRow(String chainKey, int length, long total) {+ return new Object[] {chainKey, length, total};+ }++ private static User user(String username, Team team) {+ User user = new User();+ user.setUsername(username);+ user.setTeam(team);+ return user;+ }++ private static Team team(long id) {+ Team team = new Team();+ team.setId(id);+ return team;+ }++ /** Stands in for the projection query, which returns usernames already ordered and capped. */+ private void teamRoster(long teamId, List<String> usernames) {+ when(userRepository.findUsernamesByTeamIds(eq(List.of(teamId)), any(Pageable.class)))+ .thenReturn(usernames);+ }++ @Test+ @DisplayName("recent-window events count double on top of the total")+ void recentEventsCountDouble() {+ when(usageRepository.sumByPrincipal("alice", 10, 20))+ .thenReturn(List.<Object[]>of(row("ocr", 3, 10), row("merge", 0, 10)));++ Map<String, Double> signal = service.userFrequency("alice", 10, 20);++ assertThat(signal).containsEntry("ocr", 13.0).containsEntry("merge", 10.0);+ }++ @Test+ @DisplayName("zero-count rows are dropped so they cannot skew normalization")+ void zeroRowsDropped() {+ when(usageRepository.sumGlobal(10, 20))+ .thenReturn(List.<Object[]>of(row("ocr", 0, 0), row("merge", 1, 2)));++ assertThat(service.globalFrequency(10, 20)).containsOnlyKeys("merge");+ }++ @Test+ @DisplayName("null aggregate values are treated as zero")+ void nullAggregatesTolerated() {+ when(usageRepository.edgesGlobal(10, 20))+ .thenReturn(List.<Object[]>of(edgeRow("compare", "ocr", null, 4L)));++ assertThat(service.globalTransitions(10, 20)).containsEntry("compare", Map.of("ocr", 4.0));+ }++ @Test+ @DisplayName("one scan returns every source tool's row, so no caller can ask for a new one")+ void transitionsComeBackAsAMatrix() {+ when(usageRepository.edgesGlobal(10, 20))+ .thenReturn(+ List.<Object[]>of(+ edgeRow("compress", "addPassword", 1L, 2L),+ edgeRow("compress", "split", 0L, 1L),+ edgeRow("ocr", "redact", 0L, 5L)));++ Map<String, Map<String, Double>> edges = service.globalTransitions(10, 20);++ assertThat(edges).containsOnlyKeys("compress", "ocr");+ assertThat(edges.get("compress"))+ .containsEntry("addPassword", 3.0)+ .containsEntry("split", 1.0);+ assertThat(edges.get("ocr")).containsEntry("redact", 5.0);+ verify(usageRepository, times(1)).edgesGlobal(10, 20);+ }++ @Test+ @DisplayName("every member of a team resolves to the same roster, so the cache key holds")+ void teamScopeIsIdenticalForEveryMember() {+ Team team = team(7L);+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenReturn(Optional.of(user("alice", team)));+ when(userRepository.findByUsernameIgnoreCase("bob"))+ .thenReturn(Optional.of(user("bob", team)));+ teamRoster(7L, List.of("alice", "bob"));++ TeamScope forAlice = service.resolveTeamScope("alice");+ TeamScope forBob = service.resolveTeamScope("bob");++ assertThat(forAlice).isEqualTo(forBob);+ assertThat(forAlice.teamIds()).containsExactly(7L);+ assertThat(forAlice.principals()).containsExactly("alice", "bob");+ assertThat(forAlice.hasMembers()).isTrue();+ }++ @Test+ @DisplayName("teams joined through memberships count, which is how SaaS models them")+ void membershipTeamsAreIncluded() {+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenReturn(Optional.of(user("alice", null)));+ when(membershipRepository.findTeamIdsByUsername("alice")).thenReturn(List.of(42L));+ when(userRepository.findUsernamesByTeamIds(eq(List.of(42L)), any(Pageable.class)))+ .thenReturn(List.of());+ when(membershipRepository.findUsernamesByTeamIds(eq(List.of(42L)), any(Pageable.class)))+ .thenReturn(List.of("alice", "bob"));++ TeamScope scope = service.resolveTeamScope("alice");++ assertThat(scope.teamIds()).containsExactly(42L);+ assertThat(scope.principals()).containsExactly("alice", "bob");+ assertThat(scope.hasMembers()).isTrue();+ }++ @Test+ @DisplayName("a team of one is just the caller, so it contributes no separate signal")+ void soloTeamHasNoSignal() {+ Team team = team(7L);+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenReturn(Optional.of(user("alice", team)));+ teamRoster(7L, List.of("alice"));++ assertThat(service.resolveTeamScope("alice").hasMembers()).isFalse();+ }++ @Test+ @DisplayName("a user with no team yields an empty scope")+ void noTeamYieldsEmptyScope() {+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenReturn(Optional.of(user("alice", null)));++ assertThat(service.resolveTeamScope("alice")).isEqualTo(TeamScope.none());+ }++ @Test+ @DisplayName("an empty scope is a resolved answer, so it is worth caching")+ void emptyScopeIsResolved() {+ when(userRepository.findByUsernameIgnoreCase("alice")).thenReturn(Optional.empty());++ assertThat(service.resolveTeamScope("alice").resolved()).isTrue();+ }++ @Test+ @DisplayName("a repository failure is unresolved, so a blip is never cached as 'no team'")+ void teamLookupFailureIsNotCacheable() {+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenThrow(new RuntimeException("db down"));++ TeamScope scope = service.resolveTeamScope("alice");++ assertThat(scope.hasMembers()).isFalse();+ assertThat(scope.resolved()).isFalse();+ }++ @Test+ @DisplayName("core builds without a user repository never attempt team scoping")+ void noUserRepositoryMeansNoTeam() {+ ToolUsageSignalService coreService = signalService(Optional.empty());++ assertThat(coreService.resolveTeamScope("alice")).isEqualTo(TeamScope.none());+ verifyNoInteractions(userRepository);+ }++ @Test+ @DisplayName("team aggregates query only the scope's principals")+ void teamAggregatesUseScopePrincipals() {+ TeamScope scope = new TeamScope(List.of(7L), List.of("bob", "carol"), true);+ when(usageRepository.sumByPrincipals(scope.principals(), 10, 20))+ .thenReturn(List.<Object[]>of(row("ocr", 1, 2)));++ assertThat(service.teamFrequency(scope, 10, 20)).containsEntry("ocr", 3.0);+ verify(usageRepository).sumByPrincipals(List.of("bob", "carol"), 10, 20);+ }++ @Test+ @DisplayName("teams with the same members share a cache key, and different ones do not")+ void cacheKeyIdentifiesTheRoster() {+ assertThat(new TeamScope(List.of(7L, 9L), List.of("a", "b"), true).cacheKey())+ .isEqualTo(new TeamScope(List.of(7L, 9L), List.of("a", "b"), true).cacheKey())+ .isNotEqualTo(new TeamScope(List.of(7L), List.of("a", "b"), true).cacheKey());+ }++ @Test+ @DisplayName("very large teams are capped so the IN clause stays bounded")+ void largeTeamsAreCapped() {+ Team team = team(7L);+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenReturn(Optional.of(user("alice", team)));+ List<String> members = IntStream.range(0, 900).mapToObj(i -> "user" + i).toList();+ when(userRepository.findUsernamesByTeamIds(eq(List.of(7L)), any(Pageable.class)))+ .thenReturn(members);++ assertThat(service.resolveTeamScope("alice").principals()).hasSize(500);+ }++ @Test+ @DisplayName("the roster is ordered and limited by the database, not after loading entities")+ void rosterIsPagedInTheDatabase() {+ Team team = team(7L);+ when(userRepository.findByUsernameIgnoreCase("alice"))+ .thenReturn(Optional.of(user("alice", team)));+ teamRoster(7L, List.of("alice", "bob"));++ service.resolveTeamScope("alice");++ ArgumentCaptor<Pageable> page = ArgumentCaptor.forClass(Pageable.class);+ ArgumentCaptor<Collection<Long>> ids = ArgumentCaptor.captor();+ verify(userRepository).findUsernamesByTeamIds(ids.capture(), page.capture());+ assertThat(ids.getValue()).containsExactly(7L);+ assertThat(page.getValue().getPageSize()).isEqualTo(500);+ }++ @Test+ @DisplayName("chain rows are decoded back into ordered tool lists")+ void chainRowsDecoded() {+ when(chainRepository.topByPrincipal(eq("alice"), eq(10L), eq(2), any(Pageable.class)))+ .thenReturn(List.<Object[]>of(chainRow("compress>watermark", 2, 4)));++ assertThat(service.userChains("alice", 10, 2, 6))+ .containsExactly(new ToolChainSummary(List.of("compress", "watermark"), 4));+ }++ @Test+ @DisplayName("the requested limit bounds the page asked of the database")+ void chainLimitBoundsThePage() {+ when(chainRepository.topGlobal(eq(10L), eq(2), any(Pageable.class))).thenReturn(List.of());++ service.globalChains(10, 2, 3);++ ArgumentCaptor<Pageable> page = ArgumentCaptor.forClass(Pageable.class);+ verify(chainRepository).topGlobal(eq(10L), eq(2), page.capture());+ assertThat(page.getValue().getPageSize()).isEqualTo(3);+ }++ @Test+ @DisplayName("single-tool and zero-count chain rows are not workflows")+ void nonWorkflowChainRowsDropped() {+ when(chainRepository.topByPrincipal(eq("alice"), eq(10L), eq(2), any(Pageable.class)))+ .thenReturn(+ List.<Object[]>of(+ chainRow("compress", 1, 9), chainRow("compress>ocr", 2, 0)));++ assertThat(service.userChains("alice", 10, 2, 6)).isEmpty();+ }++ @Test+ @DisplayName("user-scoped reads hit the database directly so new activity shows immediately")+ void userScopedReadsAreDirect() {+ when(usageRepository.sumByPrincipal("alice", 10, 20)).thenReturn(List.of());++ service.userFrequency("alice", 10, 20);+ service.userFrequency("alice", 10, 20);++ verify(usageRepository, times(2)).sumByPrincipal("alice", 10, 20);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageTrackingServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageTrackingServiceTest.javanew file mode 100644index 0000000000..3e4924d9c7--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/ToolUsageTrackingServiceTest.java@@ -0,0 +1,589 @@+package stirling.software.proprietary.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatCode;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyLong;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.argThat;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;+import java.util.Set;++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.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;+import org.springframework.dao.DataIntegrityViolationException;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.model.ToolChainStat;+import stirling.software.proprietary.model.ToolUsageStat;+import stirling.software.proprietary.repository.ToolChainStatRepository;+import stirling.software.proprietary.repository.ToolUsageStatRepository;++@ExtendWith(MockitoExtension.class)+class ToolUsageTrackingServiceTest {++ private static final String PRINCIPAL = "alice";+ private static final String NONE = ToolUsageStat.NO_PREVIOUS_TOOL;+ private static final long TODAY = ToolUsageTrackingService.currentEpochDay();++ /** One input document that has been through no tools yet. */+ private static final List<List<String>> FRESH = List.of(List.of());++ @Mock private ToolUsageStatRepository usageRepository;+ @Mock private ToolChainStatRepository chainRepository;++ /** The longest key the shipped registry holds, so chain trimming is tested at its worst. */+ private static final String LONGEST_KEY = "editTableOfContents";++ /**+ * Short stand-in names for real tools, so a chain of eight stays readable. The registry is the+ * only thing that decides what a tool key is, so the tests declare their own vocabulary.+ */+ private static final ToolKeyRegistry TOOL_KEYS =+ ToolKeyRegistry.forKeys(+ Set.of(+ "a",+ "b",+ "c",+ "d",+ "e",+ "f",+ "g",+ "h",+ "x",+ "t1",+ "t2",+ "t3",+ "t4",+ "t5",+ "t6",+ "t7",+ "t8",+ "t9",+ "t10",+ "tracked",+ "compress",+ "ocr",+ "merge",+ "split",+ "rotate",+ "watermark",+ "compare",+ "addPassword",+ "pdfTextEditor",+ LONGEST_KEY));++ private ApplicationProperties properties;+ private ToolUsageTrackingService service;++ @BeforeEach+ void setUp() {+ properties = new ApplicationProperties();+ properties.getSystem().setEnableAnalytics(true);+ service =+ new ToolUsageTrackingService(+ usageRepository, chainRepository, TOOL_KEYS, properties);+ }++ @SafeVarargs+ private static List<List<String>> chains(List<String>... documents) {+ return List.of(documents);+ }++ @Nested+ @DisplayName("Recording transitions")+ class RecordingTransitions {++ @Test+ @DisplayName("a fresh document increments the no-previous-tool row")+ void recordsPlainRun() {+ when(usageRepository.incrementCount(PRINCIPAL, NONE, "compare", TODAY, 1))+ .thenReturn(1);++ service.recordUsage(PRINCIPAL, "compare", FRESH);++ verify(usageRepository).incrementCount(PRINCIPAL, NONE, "compare", TODAY, 1);+ verifyNoInteractions(chainRepository);+ }++ @Test+ @DisplayName("the previous tool applied to the document is the transition edge")+ void recordsTransitionEdge() {+ when(usageRepository.incrementCount(PRINCIPAL, "compare", "ocr", TODAY, 1))+ .thenReturn(1);+ when(chainRepository.incrementCount(PRINCIPAL, "compare>ocr", TODAY, 1)).thenReturn(1);++ service.recordUsage(PRINCIPAL, "ocr", chains(List.of("compare")));++ verify(usageRepository).incrementCount(PRINCIPAL, "compare", "ocr", TODAY, 1);+ }++ @Test+ @DisplayName("only the document's last step counts, not the whole chain")+ void transitionUsesLastStepOnly() {+ when(usageRepository.incrementCount(PRINCIPAL, "watermark", "ocr", TODAY, 1))+ .thenReturn(1);+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);++ service.recordUsage(PRINCIPAL, "ocr", chains(List.of("compress", "watermark")));++ verify(usageRepository).incrementCount(PRINCIPAL, "watermark", "ocr", TODAY, 1);+ }++ @Test+ @DisplayName("re-running a tool on a document keeps the step before it")+ void repeatedStepCollapses() {+ when(usageRepository.incrementCount(PRINCIPAL, "ocr", "compress", TODAY, 1))+ .thenReturn(1);+ when(chainRepository.incrementCount(PRINCIPAL, "ocr>compress", TODAY, 1)).thenReturn(1);++ service.recordUsage(+ PRINCIPAL, "compress", chains(List.of("ocr", "compress", "compress")));++ verify(usageRepository).incrementCount(PRINCIPAL, "ocr", "compress", TODAY, 1);+ verify(chainRepository).incrementCount(PRINCIPAL, "ocr>compress", TODAY, 1);+ }++ @Test+ @DisplayName("a document whose only step was this tool records no self-transition")+ void noSelfTransition() {+ when(usageRepository.incrementCount(PRINCIPAL, NONE, "compare", TODAY, 1))+ .thenReturn(1);++ service.recordUsage(PRINCIPAL, "compare", chains(List.of("compare")));++ verify(usageRepository).incrementCount(PRINCIPAL, NONE, "compare", TODAY, 1);+ verifyNoInteractions(chainRepository);+ }++ @Test+ @DisplayName("several inputs still count as one run of the tool")+ void multiInputCountsOnce() {+ when(usageRepository.incrementCount(+ anyString(), anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);++ service.recordUsage(+ PRINCIPAL, "merge", chains(List.of("compress"), List.of("ocr", "rotate")));++ verify(usageRepository, times(1))+ .incrementCount(anyString(), anyString(), anyString(), anyLong(), anyLong());+ }++ @Test+ @DisplayName("the longest input chain supplies the transition for a multi-input run")+ void multiInputCreditsDominantDocument() {+ when(usageRepository.incrementCount(PRINCIPAL, "rotate", "merge", TODAY, 1))+ .thenReturn(1);+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);++ service.recordUsage(+ PRINCIPAL, "merge", chains(List.of("compress"), List.of("ocr", "rotate")));++ verify(usageRepository).incrementCount(PRINCIPAL, "rotate", "merge", TODAY, 1);+ }++ @Test+ @DisplayName("equal-length input chains break the tie deterministically")+ void multiInputTieIsStable() {+ when(usageRepository.incrementCount(PRINCIPAL, "compress", "merge", TODAY, 1))+ .thenReturn(1);+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);++ service.recordUsage(PRINCIPAL, "merge", chains(List.of("ocr"), List.of("compress")));+ service.recordUsage(PRINCIPAL, "merge", chains(List.of("compress"), List.of("ocr")));++ verify(usageRepository, times(2))+ .incrementCount(PRINCIPAL, "compress", "merge", TODAY, 1);+ }++ @Test+ @DisplayName("the day's first run inserts the row")+ void insertsFirstRunOfDay() {+ when(usageRepository.incrementCount(PRINCIPAL, "compare", "ocr", TODAY, 1))+ .thenReturn(0);+ when(chainRepository.incrementCount(PRINCIPAL, "compare>ocr", TODAY, 1)).thenReturn(1);++ service.recordUsage(PRINCIPAL, "ocr", chains(List.of("compare")));++ verify(usageRepository).insertCount(PRINCIPAL, "compare", "ocr", TODAY, 1);+ }++ @Test+ @DisplayName("the insert never goes through save(), which would merge over a live row")+ void insertDoesNotUseSave() {+ when(usageRepository.incrementCount(PRINCIPAL, NONE, "compare", TODAY, 1))+ .thenReturn(0);++ service.recordUsage(PRINCIPAL, "compare", FRESH);++ verify(usageRepository, never()).save(any(ToolUsageStat.class));+ }++ @Test+ @DisplayName("a concurrent insert falls back to incrementing the winner's row")+ void insertRaceFallsBackToUpdate() {+ when(usageRepository.incrementCount(PRINCIPAL, NONE, "compare", TODAY, 1))+ .thenReturn(0)+ .thenReturn(1);+ doThrow(new DataIntegrityViolationException("duplicate key"))+ .when(usageRepository)+ .insertCount(PRINCIPAL, NONE, "compare", TODAY, 1);++ service.recordUsage(PRINCIPAL, "compare", FRESH);++ verify(usageRepository, times(2)).incrementCount(PRINCIPAL, NONE, "compare", TODAY, 1);+ }++ @Test+ @DisplayName("a database failure never propagates to the caller")+ void databaseFailureSwallowed() {+ when(usageRepository.incrementCount(+ anyString(), anyString(), anyString(), anyLong(), anyLong()))+ .thenThrow(new RuntimeException("db down"));++ assertThatCode(() -> service.recordUsage(PRINCIPAL, "compare", FRESH))+ .doesNotThrowAnyException();+ }+ }++ @Nested+ @DisplayName("Recording chains")+ class RecordingChains {++ @BeforeEach+ void allowUsageWrites() {+ when(usageRepository.incrementCount(+ anyString(), anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);+ }++ @Test+ @DisplayName("the document's whole path is recorded, not just the last step")+ void recordsFullChain() {+ when(chainRepository.incrementCount(+ PRINCIPAL, "compress>watermark>addPassword", TODAY, 1))+ .thenReturn(1);++ service.recordUsage(PRINCIPAL, "addPassword", chains(List.of("compress", "watermark")));++ verify(chainRepository)+ .incrementCount(PRINCIPAL, "compress>watermark>addPassword", TODAY, 1);+ }++ @Test+ @DisplayName("the day's first sighting of a chain inserts it with its length")+ void insertsFirstChainOfDay() {+ when(chainRepository.incrementCount(PRINCIPAL, "compress>ocr", TODAY, 1)).thenReturn(0);++ service.recordUsage(PRINCIPAL, "ocr", chains(List.of("compress")));++ verify(chainRepository).insertCount(PRINCIPAL, "compress>ocr", TODAY, 2, 1);+ }++ @Test+ @DisplayName("a concurrent chain insert falls back to incrementing the winner's row")+ void chainInsertRaceFallsBackToUpdate() {+ when(chainRepository.incrementCount(PRINCIPAL, "compress>ocr", TODAY, 1))+ .thenReturn(0)+ .thenReturn(1);+ doThrow(new DataIntegrityViolationException("duplicate key"))+ .when(chainRepository)+ .insertCount(PRINCIPAL, "compress>ocr", TODAY, 2, 1);++ service.recordUsage(PRINCIPAL, "ocr", chains(List.of("compress")));++ verify(chainRepository, times(2)).incrementCount(PRINCIPAL, "compress>ocr", TODAY, 1);+ }++ @Test+ @DisplayName("every distinct input document contributes its own chain")+ void recordsOneChainPerDocument() {+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);++ service.recordUsage(+ PRINCIPAL, "merge", chains(List.of("compress"), List.of("ocr", "rotate")));++ verify(chainRepository).incrementCount(PRINCIPAL, "compress>merge", TODAY, 1);+ verify(chainRepository).incrementCount(PRINCIPAL, "ocr>rotate>merge", TODAY, 1);+ }++ @Test+ @DisplayName("documents that took the same path count as one workflow")+ void deduplicatesIdenticalChains() {+ when(chainRepository.incrementCount(PRINCIPAL, "compress>merge", TODAY, 1))+ .thenReturn(1);++ service.recordUsage(+ PRINCIPAL,+ "merge",+ chains(List.of("compress"), List.of("compress"), List.of("compress")));++ verify(chainRepository, times(1)).incrementCount(PRINCIPAL, "compress>merge", TODAY, 1);+ }++ @Test+ @DisplayName("a single input document writes no more chains than it has paths")+ void boundsChainsPerEvent() {+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);+ List<List<String>> many = new ArrayList<>();+ for (int i = 1; i <= ToolUsageTrackingService.MAX_CHAINS_PER_EVENT + 5; i++) {+ many.add(List.of("t" + i));+ }++ service.recordUsage(PRINCIPAL, "merge", many);++ verify(chainRepository, times(ToolUsageTrackingService.MAX_CHAINS_PER_EVENT))+ .incrementCount(anyString(), anyString(), anyLong(), anyLong());+ }++ @Test+ @DisplayName("duplicate chains cannot make one request scan an unbounded list")+ void boundsChainsScannedPerEvent() {+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);+ List<List<String>> many =+ new ArrayList<>(+ Collections.nCopies(+ ToolUsageTrackingService.MAX_CHAINS_SCANNED,+ List.of("compress")));+ many.add(List.of("split"));++ service.recordUsage(PRINCIPAL, "merge", many);++ verify(chainRepository).incrementCount(PRINCIPAL, "compress>merge", TODAY, 1);+ verify(chainRepository, never()).incrementCount(PRINCIPAL, "split>merge", TODAY, 1);+ }++ @Test+ @DisplayName("a long-running document is recorded as its trailing window")+ void keepsTrailingWindowOfLongChains() {+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);+ List<String> prior =+ List.of("t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10");++ service.recordUsage(PRINCIPAL, "ocr", chains(prior));++ verify(chainRepository)+ .incrementCount(PRINCIPAL, "t4>t5>t6>t7>t8>t9>t10>ocr", TODAY, 1);+ }++ @Test+ @DisplayName("the trailing window never outgrows the key column")+ void trailingWindowFitsTheColumn() {+ when(chainRepository.incrementCount(anyString(), anyString(), anyLong(), anyLong()))+ .thenReturn(1);+ List<String> prior = Collections.nCopies(20, LONGEST_KEY);++ service.recordUsage(PRINCIPAL, "ocr", chains(prior));++ verify(chainRepository)+ .incrementCount(+ anyString(),+ argThat(key -> key.length() <= ToolChainStat.MAX_CHAIN_KEY_LENGTH),+ anyLong(),+ anyLong());+ }++ @Test+ @DisplayName("junk steps are dropped without losing the rest of the chain")+ void dropsInvalidSteps() {+ when(chainRepository.incrementCount(PRINCIPAL, "compress>ocr", TODAY, 1)).thenReturn(1);++ service.recordUsage(+ PRINCIPAL, "ocr", chains(Arrays.asList("compress", "not a tool!", null)));++ verify(chainRepository).incrementCount(PRINCIPAL, "compress>ocr", TODAY, 1);+ }+ }++ @Nested+ @DisplayName("Validation and gating")+ class ValidationAndGating {++ @Test+ @DisplayName("invalid principals and tool keys are dropped")+ void invalidInputDropped() {+ service.recordUsage(PRINCIPAL, "not a tool!", FRESH);+ service.recordUsage(PRINCIPAL, null, FRESH);+ service.recordUsage(PRINCIPAL, "a".repeat(65), FRESH);+ service.recordUsage(null, "compare", FRESH);++ verifyNoInteractions(usageRepository, chainRepository);+ }++ @Test+ @DisplayName("a missing chain list is treated as a fresh document")+ void nullChainsKeepTheRun() {+ when(usageRepository.incrementCount(PRINCIPAL, NONE, "ocr", TODAY, 1)).thenReturn(1);++ service.recordUsage(PRINCIPAL, "ocr", null);++ verify(usageRepository).incrementCount(PRINCIPAL, NONE, "ocr", TODAY, 1);+ verifyNoInteractions(chainRepository);+ }++ @Test+ @DisplayName("an all-invalid chain drops the edge but keeps the run")+ void invalidPreviousKeepsRun() {+ when(usageRepository.incrementCount(PRINCIPAL, NONE, "ocr", TODAY, 1)).thenReturn(1);++ service.recordUsage(PRINCIPAL, "ocr", chains(List.of("bad key!")));++ verify(usageRepository).incrementCount(PRINCIPAL, NONE, "ocr", TODAY, 1);+ verifyNoInteractions(chainRepository);+ }++ @Test+ @DisplayName("disabled feature records nothing")+ void disabledFeatureRecordsNothing() {+ properties.getToolRecommendations().setEnabled(false);++ service.recordUsage(PRINCIPAL, "compare", chains(List.of("merge")));++ verifyNoInteractions(usageRepository, chainRepository);+ }++ @Test+ @DisplayName("no analytics consent records nothing, even with the feature enabled")+ void withheldAnalyticsConsentRecordsNothing() {+ properties.getSystem().setEnableAnalytics(null);+ service.recordUsage(PRINCIPAL, "compare", chains(List.of("merge")));++ properties.getSystem().setEnableAnalytics(false);+ service.recordUsage(PRINCIPAL, "compare", chains(List.of("merge")));++ assertThat(properties.getToolRecommendations().isEnabled()).isTrue();+ verifyNoInteractions(usageRepository, chainRepository);+ }++ @Test+ @DisplayName("only keys a real tool answers to are accepted")+ void keyValidation() {+ assertThat(service.isKnownToolKey("pdfTextEditor")).isTrue();+ assertThat(service.isKnownToolKey("notATool")).isFalse();+ assertThat(service.isKnownToolKey("")).isFalse();+ assertThat(service.isKnownToolKey(null)).isFalse();+ assertThat(service.isKnownToolKey("has space")).isFalse();+ }++ @Test+ @DisplayName("a key invented by the caller never reaches the tables")+ void unknownKeysAreNotRecorded() {+ service.recordUsage(PRINCIPAL, "definitelyNotATool", FRESH);++ verifyNoInteractions(usageRepository, chainRepository);+ }++ @Test+ @DisplayName("the chain separator can never appear inside a tool key")+ void separatorIsNotAValidToolKeyCharacter() {+ assertThat(service.isKnownToolKey("a" + ToolChainStat.SEPARATOR + "b")).isFalse();+ }++ @Test+ @DisplayName("the no-previous-tool sentinel can never collide with a real tool key")+ void sentinelIsNotAValidToolKey() {+ assertThat(service.isKnownToolKey(ToolUsageStat.NO_PREVIOUS_TOOL)).isFalse();+ }++ @Test+ @DisplayName("every shipped tool key is short enough to store a full chain of them")+ void shippedKeysFitTheChainColumn() {+ int longestChain = ToolChainStat.MAX_CHAIN_TOOLS * (ToolKeyRegistry.MAX_KEY_LENGTH + 1);++ assertThat(longestChain).isLessThanOrEqualTo(ToolChainStat.MAX_CHAIN_KEY_LENGTH);+ }+ }++ @Nested+ @DisplayName("Retention")+ class Retention {++ @Test+ @DisplayName("the sweep deletes rows older than the configured window from both tables")+ void sweepDeletesOldRows() {+ properties.getToolRecommendations().setRetentionDays(90);++ service.cleanupOldStats();++ verify(usageRepository).deleteOlderThan(TODAY - 90);+ verify(chainRepository).deleteOlderThan(TODAY - 90);+ }++ @Test+ @DisplayName("non-positive retention disables the sweep")+ void nonPositiveRetentionSkipsSweep() {+ properties.getToolRecommendations().setRetentionDays(0);++ service.cleanupOldStats();++ verify(usageRepository, never()).deleteOlderThan(anyLong());+ verify(chainRepository, never()).deleteOlderThan(anyLong());+ }++ @Test+ @DisplayName("a failing delete is logged, not thrown")+ void sweepFailureIsSwallowed() {+ when(usageRepository.deleteOlderThan(anyLong()))+ .thenThrow(new RuntimeException("db down"));++ assertThatCode(() -> service.cleanupOldStats()).doesNotThrowAnyException();+ }+ }++ @Nested+ @DisplayName("Chain keys")+ class ChainKeys {++ @Test+ @DisplayName("a chain key round-trips through its tool list")+ void roundTrips() {+ List<String> tools = List.of("compress", "watermark", "add-password");++ assertThat(ToolChainStat.fromChainKey(ToolChainStat.toChainKey(tools)))+ .isEqualTo(tools);+ }++ @Test+ @DisplayName("a full-length chain of maximum-length tool keys still fits the key column")+ void maxChainFitsTheKeyColumn() {+ // Pins the sizing relationship: anything that passes validation must be storable,+ // so the oversized-chain guard stays unreachable for legitimate input.+ List<String> tools = Collections.nCopies(ToolChainStat.MAX_CHAIN_TOOLS, "a".repeat(64));++ assertThat(ToolChainStat.toChainKey(tools).length())+ .isLessThanOrEqualTo(ToolChainStat.MAX_CHAIN_KEY_LENGTH);+ }++ @Test+ @DisplayName("an empty key is no chain at all")+ void emptyKey() {+ assertThat(ToolChainStat.fromChainKey("")).isEmpty();+ assertThat(ToolChainStat.fromChainKey(null)).isEmpty();+ }+ }+}diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.javaindex 028a48fd6f..b60b4efa86 100644--- a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java@@ -107,6 +107,8 @@ public final class SaasSchemaOwnership {"storage_cleanup_entries","stored_file_blobs","stored_files",+ "tool_chain_stats",+ "tool_usage_stats","user_license_settings","org_owner","user_server_certificates",diff --git a/frontend/editor/src/core/api/toolRecommendations.test.ts b/frontend/editor/src/core/api/toolRecommendations.test.tsnew file mode 100644index 0000000000..1c0ef245be--- /dev/null+++ b/frontend/editor/src/core/api/toolRecommendations.test.ts@@ -0,0 +1,161 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++import apiClient from "@app/services/apiClient";+import {+ fetchToolRecommendations,+ recordToolUsage,+ resetToolRecommendationsAvailabilityForTests,+} from "@app/api/toolRecommendations";++vi.mock("@app/services/apiClient", () => ({+ default: { get: vi.fn(), post: vi.fn() },+}));++const mockGet = vi.mocked(apiClient.get);+const mockPost = vi.mocked(apiClient.post);++const http404 = Object.assign(new Error("not found"), {+ response: { status: 404 },+});++const http501 = Object.assign(new Error("not implemented"), {+ response: { status: 501 },+});++describe("toolRecommendations api", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetToolRecommendationsAvailabilityForTests();+ });++ describe("fetchToolRecommendations", () => {+ it("returns the ranked list and passes the current tool", async () => {+ mockGet.mockResolvedValue({+ data: { recommendations: [{ toolKey: "ocr", score: 5 }] },+ });++ const result = await fetchToolRecommendations("compare", 6);++ expect(result).toEqual([{ toolKey: "ocr", score: 5 }]);+ const url = mockGet.mock.calls[0][0] as string;+ expect(url).toContain("currentTool=compare");+ expect(url).toContain("limit=6");+ });++ it("omits currentTool when there is no context", async () => {+ mockGet.mockResolvedValue({ data: { recommendations: [] } });++ await fetchToolRecommendations(null);++ expect(mockGet.mock.calls[0][0]).not.toContain("currentTool");+ });++ it("returns null on failure so callers fall back to the static list", async () => {+ mockGet.mockRejectedValue(new Error("network down"));++ expect(await fetchToolRecommendations("compare")).toBeNull();+ });++ it("stops after one 404 on a build that has no such API", async () => {+ mockGet.mockRejectedValue(http404);++ for (let i = 0; i < 5; i++) await fetchToolRecommendations("compare");++ // Core builds 404 from the first call, so one is proof enough.+ expect(mockGet).toHaveBeenCalledTimes(1);+ });++ it("gives a 404 a few tries once the API has answered before", async () => {+ mockGet.mockResolvedValueOnce({ data: { recommendations: [] } });+ await fetchToolRecommendations("compare");++ mockGet.mockRejectedValue(http404);+ for (let i = 0; i < 5; i++) await fetchToolRecommendations("compare");++ // One success, then three strikes: a lone 404 can be a proxy mid-deploy.+ expect(mockGet).toHaveBeenCalledTimes(4);+ });++ it("forgets earlier 404s once a call succeeds again", async () => {+ mockGet.mockResolvedValueOnce({ data: { recommendations: [] } });+ await fetchToolRecommendations("compare");++ mockGet.mockRejectedValueOnce(http404).mockRejectedValueOnce(http404);+ await fetchToolRecommendations("compare");+ await fetchToolRecommendations("compare");++ mockGet.mockResolvedValueOnce({ data: { recommendations: [] } });+ await fetchToolRecommendations("compare");++ mockGet.mockRejectedValue(http404);+ for (let i = 0; i < 5; i++) await fetchToolRecommendations("compare");++ expect(mockGet).toHaveBeenCalledTimes(7);+ });++ it("stops fetching after a 501 from an install with nothing to rank", async () => {+ mockGet.mockRejectedValue(http501);++ expect(await fetchToolRecommendations("compare")).toBeNull();+ expect(await fetchToolRecommendations("compare")).toBeNull();+ expect(mockGet).toHaveBeenCalledTimes(1);+ });++ it("keeps retrying after transient failures (no 404 latch)", async () => {+ mockGet.mockRejectedValue(new Error("network down"));++ await fetchToolRecommendations("compare");+ await fetchToolRecommendations("compare");++ expect(mockGet).toHaveBeenCalledTimes(2);+ });+ });++ describe("recordToolUsage", () => {+ it("posts the tool and each input document's prior chain", async () => {+ mockPost.mockResolvedValue({});++ await recordToolUsage("merge", [["compress"], ["ocr", "rotate"]]);++ expect(mockPost).toHaveBeenCalledWith(+ expect.stringContaining("/usage"),+ { toolKey: "merge", priorChains: [["compress"], ["ocr", "rotate"]] },+ expect.objectContaining({ suppressErrorToast: true }),+ );+ });++ it("posts an empty chain list for an untracked run", async () => {+ mockPost.mockResolvedValue({});++ await recordToolUsage("ocr");++ expect(mockPost.mock.calls[0][1]).toEqual({+ toolKey: "ocr",+ priorChains: [],+ });+ });++ it("swallows failures silently", async () => {+ mockPost.mockRejectedValue(new Error("boom"));++ await expect(recordToolUsage("ocr")).resolves.toBeUndefined();+ });++ it("skips the network entirely once the API is known to be missing", async () => {+ mockPost.mockRejectedValue(http404);++ for (let i = 0; i < 5; i++) await recordToolUsage("ocr");++ expect(mockPost).toHaveBeenCalledTimes(1);+ });++ it("stops posting after a 501 from an install that declined tracking", async () => {+ mockPost.mockRejectedValue(http501);++ await recordToolUsage("ocr");+ await recordToolUsage("ocr");++ expect(mockPost).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/frontend/editor/src/core/api/toolRecommendations.ts b/frontend/editor/src/core/api/toolRecommendations.tsnew file mode 100644index 0000000000..e4713a2c0f--- /dev/null+++ b/frontend/editor/src/core/api/toolRecommendations.ts@@ -0,0 +1,98 @@+import apiClient from "@app/services/apiClient";++export interface ToolRecommendationDto {+ toolKey: string;+ score: number;+}++const BASE_PATH = "/api/v1/proprietary/ui-data/tool-recommendations";++// Once the route has answered, a 404 is more likely a proxy hiccup mid-deploy+// than the API vanishing, so it takes a few before we write it off. A build+// without the API 404s from the very first call, and that one is conclusive.+const MISSING_ROUTE_STRIKES = 3;++let backendUnavailable = false;+let everAnswered = false;+let consecutiveNotFound = 0;++export function resetToolRecommendationsAvailabilityForTests(): void {+ backendUnavailable = false;+ everAnswered = false;+ consecutiveNotFound = 0;+}++function noteFailure(error: unknown): void {+ const status = (error as { response?: { status?: number } })?.response+ ?.status;+ if (status === 501) {+ // The install records no usage, or has no signed-in user to rank for.+ backendUnavailable = true;+ return;+ }+ if (status === 404) {+ consecutiveNotFound += 1;+ if (!everAnswered || consecutiveNotFound >= MISSING_ROUTE_STRIKES) {+ backendUnavailable = true;+ }+ return;+ }+ consecutiveNotFound = 0;+}++function noteSuccess(): void {+ everAnswered = true;+ consecutiveNotFound = 0;+}++/**+ * Ranked tools for the current context, or null when the backend cannot serve+ * them (core-only build, login disabled, usage tracking off, network failure)+ * so callers fall back to the static recommended list.+ */+export async function fetchToolRecommendations(+ currentTool: string | null,+ limit = 6,+): Promise<ToolRecommendationDto[] | null> {+ if (backendUnavailable) return null;+ try {+ const params = new URLSearchParams({ limit: String(limit) });+ if (currentTool) params.set("currentTool", currentTool);+ const response = await apiClient.get<{+ recommendations: ToolRecommendationDto[];+ }>(`${BASE_PATH}?${params}`, {+ suppressErrorToast: true,+ skipAuthRedirect: true,+ });+ noteSuccess();+ return response.data?.recommendations ?? [];+ } catch (error) {+ noteFailure(error);+ return null;+ }+}++/**+ * Fire-and-forget: usage tracking must never surface errors to the user.+ *+ * `priorChains` holds the tools already applied to each input document, oldest+ * step first and excluding this run - one entry per document, empty for a fresh+ * upload. That is what makes a recorded transition mean "next for this file"+ * rather than "next click".+ */+export async function recordToolUsage(+ toolKey: string,+ priorChains: string[][] = [],+): Promise<void> {+ if (backendUnavailable) return;+ try {+ await apiClient.post(+ `${BASE_PATH}/usage`,+ { toolKey, priorChains },+ { suppressErrorToast: true, skipAuthRedirect: true },+ );+ noteSuccess();+ } catch (error) {+ noteFailure(error);+ }+}diff --git a/frontend/editor/src/core/components/tools/shared/SuggestedToolsSection.tsx b/frontend/editor/src/core/components/tools/shared/SuggestedToolsSection.tsxindex 79be895590..96d33d0dfd 100644--- a/frontend/editor/src/core/components/tools/shared/SuggestedToolsSection.tsx+++ b/frontend/editor/src/core/components/tools/shared/SuggestedToolsSection.tsx@@ -17,26 +17,24 @@ export function SuggestedToolsSection(): React.ReactElement {</Text><Stack gap="xs">- {suggestedTools.map((tool) => {- const IconComponent = tool.icon;- return (- <Anchor- key={tool.id}- href={tool.href}- onClick={tool.onClick}- style={{ textDecoration: "none", color: "inherit" }}- >- <Card p="sm" withBorder style={{ cursor: "pointer" }}>- <Group gap="xs">- <ToolIcon icon={<IconComponent />} />- <Text size="sm" fw={500}>- {tool.title}- </Text>- </Group>- </Card>- </Anchor>- );- })}+ {suggestedTools.map((tool) => (+ <Anchor+ key={tool.id}+ href={tool.href}+ onClick={tool.onClick}+ data-tour={`suggested-tool-${tool.id}`}+ style={{ textDecoration: "none", color: "inherit" }}+ >+ <Card p="sm" withBorder style={{ cursor: "pointer" }}>+ <Group gap="xs">+ <ToolIcon icon={tool.icon} />+ <Text size="sm" fw={500}>+ {tool.title}+ </Text>+ </Group>+ </Card>+ </Anchor>+ ))}</Stack></Stack>);diff --git a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.tsindex 06df6519b6..a3fdaf124a 100644--- a/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts+++ b/frontend/editor/src/core/hooks/tools/shared/useToolOperation.ts@@ -46,6 +46,7 @@ import { createNewStirlingFileStub } from "@app/types/fileContext";import { ToolOperation } from "@app/types/file";import { ensureBackendReady } from "@app/services/backendReadinessGuard";import { trackEditorOperation } from "@app/services/analytics";+import { notifyToolCompleted } from "@app/services/toolUsageTracker";import { useWillUseCloud } from "@app/hooks/useWillUseCloud";import { useCreditCheck } from "@app/hooks/useCreditCheck";import { useToolRunComplete } from "@app/hooks/useToolRunComplete";@@ -509,7 +510,6 @@ export const useToolOperation = <TParams>(config.operationType,successSourceIds.length || validFiles.length,);-actions.setFiles(processedFiles);// Generate thumbnails and download URL concurrently@@ -551,6 +551,12 @@ export const useToolOperation = <TParams>(selectors,);+ // Set by both branches so the usage tracker can move each document's+ // tool chain from the inputs onto the outputs that replaced them.+ let producedFileIds: FileId[] = [];+ // Inputs left in the workbench - failed, or never attempted - keep their chain.+ let consumedInputIds: FileId[] = [];+if (isVersionOp) {// Output is a modified version of the input — link it to the input's version chain.// The input is removed from the workbench and replaced in-place by the output.@@ -598,6 +604,7 @@ export const useToolOperation = <TParams>(const toConsumeInputIds = successSourceIds.filter((id) =>inputFileIds.includes(id),);+ consumedInputIds = toConsumeInputIds;console.debug("[useToolOperation] Consuming files (version)", {inputCount: inputFileIds.length,toConsume: toConsumeInputIds.length,@@ -611,6 +618,7 @@ export const useToolOperation = <TParams>(// Tell the viewer to follow the replacement file — consumeFiles prepends the new file// to the list, so activeFileIndex would point to the wrong file without this.if (outputFileIds.length === 1) setActiveFileId(outputFileIds[0]);+ producedFileIds = outputFileIds;// Notify on desktop when processing completesawait notifyPdfProcessingComplete(outputFileIds.length);@@ -673,6 +681,7 @@ export const useToolOperation = <TParams>(const toConsumeInputIds = successSourceIds.filter((id) =>inputFileIds.includes(id),);+ consumedInputIds = toConsumeInputIds;console.debug("[useToolOperation] Consuming files (independent)", {inputCount: inputFileIds.length,toConsume: toConsumeInputIds.length,@@ -683,6 +692,7 @@ export const useToolOperation = <TParams>(outputStirlingFiles,outputStirlingFileStubs,);+ producedFileIds = outputFileIds;// Notify on desktop when processing completesawait notifyPdfProcessingComplete(outputFileIds.length);@@ -719,6 +729,17 @@ export const useToolOperation = <TParams>(})),});}++ // Feeds the recommended-tools ranking and the workflow history. Sent+ // after the branch so each input document's chain can be carried onto+ // the outputs that replaced it.+ notifyToolCompleted({+ toolId: config.operationType,+ inputs: inputStirlingFileStubs.filter((stub) =>+ consumedInputIds.includes(stub.id),+ ),+ outputFileIds: producedFileIds,+ });onToolRunComplete();}} catch (error) {diff --git a/frontend/editor/src/core/hooks/useSuggestedTools.test.ts b/frontend/editor/src/core/hooks/useSuggestedTools.test.tsnew file mode 100644index 0000000000..97118606fc--- /dev/null+++ b/frontend/editor/src/core/hooks/useSuggestedTools.test.ts@@ -0,0 +1,173 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { renderHook } from "@testing-library/react";++import { useSuggestedTools } from "@app/hooks/useSuggestedTools";+import { useToolRecommendations } from "@app/hooks/useToolRecommendations";+import { useNavigationState } from "@app/contexts/NavigationContext";+import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";+import type { ToolAvailabilityMap } from "@app/hooks/useToolManagement";+import type { ToolId } from "@app/types/toolId";+import type { ToolRegistryEntry } from "@app/data/toolsTaxonomy";++vi.mock("@app/hooks/useToolRecommendations", () => ({+ useToolRecommendations: vi.fn(),+}));+vi.mock("@app/contexts/NavigationContext", () => ({+ useNavigationState: vi.fn(),+}));+vi.mock("@app/contexts/ToolWorkflowContext", () => ({+ useToolWorkflow: vi.fn(),+}));+vi.mock("@app/hooks/useToolNavigation", () => ({+ useToolNavigation: () => ({+ getToolNavigation: (toolId: string) => ({+ href: `/${toolId}`,+ onClick: () => {},+ }),+ }),+}));++const mockRecommendations = vi.mocked(useToolRecommendations);+const mockNavigation = vi.mocked(useNavigationState);+const mockWorkflow = vi.mocked(useToolWorkflow);++/** A tool that can actually open, so it survives the availability filter. */+function entry(name: string): ToolRegistryEntry {+ return {+ name,+ icon: null,+ component: (() => null) as unknown as ToolRegistryEntry["component"],+ } as ToolRegistryEntry;+}++const REGISTRY: Partial<Record<ToolId, ToolRegistryEntry>> = {+ compress: entry("Compress"),+ convert: entry("Convert"),+ sanitize: entry("Sanitize"),+ split: entry("Split"),+ ocr: entry("OCR"),+ addPassword: entry("Add Password"),+ merge: entry("Merge"),+ rotate: entry("Rotate"),+ watermark: entry("Watermark"),+ // Workbench-only: no component, but still openable.+ multiTool: {+ name: "Multi Tool",+ icon: null,+ component: null,+ } as ToolRegistryEntry,+ // No component and no link - nothing to open.+ automate: {+ name: "Automate",+ icon: null,+ component: null,+ } as ToolRegistryEntry,+};++/** Every id at the same score, i.e. the data expressing no preference at all. */+function tied(...ids: string[]) {+ return ids.map((toolKey) => ({ toolKey, score: 2 }));+}++function setup(+ recommendations: { toolKey: string; score: number }[] | null,+ selectedTool: ToolId | null = null,+ toolAvailability: ToolAvailabilityMap = {},+) {+ mockRecommendations.mockReturnValue({ recommendations });+ mockNavigation.mockReturnValue({ selectedTool } as ReturnType<+ typeof useNavigationState+ >);+ mockWorkflow.mockReturnValue({+ getSelectedTool: (id: ToolId | null) =>+ id ? (REGISTRY[id] ?? null) : null,+ toolAvailability,+ } as unknown as ReturnType<typeof useToolWorkflow>);++ return renderHook(() => useSuggestedTools()).result.current.map((t) => t.id);+}++describe("useSuggestedTools", () => {+ beforeEach(() => vi.clearAllMocks());++ it("shows the curated list when the backend has no usage data", () => {+ expect(setup(null)).toEqual(["compress", "convert", "sanitize", "split"]);+ });++ it("leads with the usage ranking, then tops up from the curated list", () => {+ expect(+ setup([+ { toolKey: "addPassword", score: 9 },+ { toolKey: "merge", score: 4 },+ ]),+ ).toEqual(["addPassword", "merge", "compress", "convert"]);+ });++ it("never suggests the tool the user is currently in", () => {+ expect(+ setup(+ [+ { toolKey: "compress", score: 9 },+ { toolKey: "addPassword", score: 4 },+ ],+ "compress",+ ),+ ).toEqual(["addPassword", "convert", "sanitize", "split"]);+ });++ it("breaks ties on the curated order rather than the alphabet", () => {+ // Alphabetically this is merge, ocr, rotate, sanitize, split, watermark.+ const ids = setup(+ tied("watermark", "split", "merge", "ocr", "rotate", "sanitize"),+ );++ expect(ids).toEqual(["sanitize", "split", "ocr", "merge"]);+ });++ it("keeps a real score ahead of the curated order", () => {+ const ids = setup([+ { toolKey: "merge", score: 9 },+ { toolKey: "sanitize", score: 2 },+ { toolKey: "split", score: 2 },+ ]);++ expect(ids[0]).toBe("merge");+ });++ it("skips tools that are unknown or still coming soon", () => {+ expect(+ setup([+ { toolKey: "automate", score: 9 },+ { toolKey: "nonsense", score: 8 },+ { toolKey: "merge", score: 7 },+ ]),+ ).toEqual(["merge", "compress", "convert", "sanitize"]);+ });++ it("skips a tool this install cannot run", () => {+ const ids = setup([{ toolKey: "merge", score: 9 }], null, {+ merge: { available: false, reason: "disabledByAdmin" },+ convert: { available: false, reason: "missingDependency" },+ });++ expect(ids).toEqual(["compress", "sanitize", "split", "ocr"]);+ });++ it("keeps workbench-only tools, which have no component by design", () => {+ expect(+ setup([+ { toolKey: "multiTool", score: 9 },+ { toolKey: "merge", score: 4 },+ ]),+ ).toEqual(["multiTool", "merge", "compress", "convert"]);+ });++ it("does not repeat a ranked tool that is also in the curated list", () => {+ const ids = setup([+ { toolKey: "split", score: 9 },+ { toolKey: "compress", score: 4 },+ ]);+ expect(ids).toEqual(["split", "compress", "convert", "sanitize"]);+ expect(new Set(ids).size).toBe(ids.length);+ });+});diff --git a/frontend/editor/src/core/hooks/useSuggestedTools.ts b/frontend/editor/src/core/hooks/useSuggestedTools.tsindex d96cab3eeb..3688007bd2 100644--- a/frontend/editor/src/core/hooks/useSuggestedTools.ts+++ b/frontend/editor/src/core/hooks/useSuggestedTools.ts@@ -2,81 +2,106 @@ import { useMemo } from "react";import { useNavigationState } from "@app/contexts/NavigationContext";import { useToolNavigation } from "@app/hooks/useToolNavigation";import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";-import { ToolId } from "@app/types/toolId";--// Material UI Icons-import CompressIcon from "@mui/icons-material/Compress";-import SwapHorizIcon from "@mui/icons-material/SwapHoriz";-import CleaningServicesIcon from "@mui/icons-material/CleaningServices";-import CropIcon from "@mui/icons-material/Crop";-import TextFieldsIcon from "@mui/icons-material/TextFields";+import { useToolRecommendations } from "@app/hooks/useToolRecommendations";+import { isComingSoonTool } from "@app/data/toolsTaxonomy";+import { isValidToolId, ToolId } from "@app/types/toolId";export interface SuggestedTool {id: ToolId;title: string;- icon: React.ComponentType;+ icon: React.ReactNode;href: string;onClick: (e: React.MouseEvent) => void;}-const ALL_SUGGESTED_TOOLS: Omit<SuggestedTool, "href" | "onClick">[] = [- {- id: "compress",- title: "Compress",- icon: CompressIcon,- },- {- id: "convert",- title: "Convert",- icon: SwapHorizIcon,- },- {- id: "sanitize",- title: "Sanitize",- icon: CleaningServicesIcon,- },- {- id: "split",- title: "Split",- icon: CropIcon,- },- {- id: "ocr",- title: "OCR",- icon: TextFieldsIcon,- },+/**+ * Shown when usage tracking has nothing to say, and the order tied scores fall+ * back to - see {@link orderRanked}.+ */+const FALLBACK_TOOL_IDS: ToolId[] = [+ "compress",+ "convert",+ "sanitize",+ "split",+ "ocr",];+const SUGGESTION_COUNT = 4;++// Well past what is shown: tools on equal scores are reordered here, so they+// have to survive the server's own limit to be reordered at all.+const FETCH_LIMIT = 12;++function curatedRank(id: ToolId): number {+ const index = FALLBACK_TOOL_IDS.indexOf(id);+ return index === -1 ? FALLBACK_TOOL_IDS.length : index;+}++/**+ * Equal scores mean the usage data expressed no preference between those tools.+ * Sorting them by name would still produce a confident-looking list, just an+ * alphabetical one, so ties fall back to the curated order instead.+ */+function orderRanked(ranked: { toolKey: string; score: number }[]): ToolId[] {+ return ranked+ .filter((entry): entry is { toolKey: ToolId; score: number } =>+ isValidToolId(entry.toolKey),+ )+ .sort(+ (a, b) =>+ b.score - a.score ||+ curatedRank(a.toolKey) - curatedRank(b.toolKey) ||+ a.toolKey.localeCompare(b.toolKey),+ )+ .map((entry) => entry.toolKey);+}++/**+ * What to do next with the file that just came out of a tool.+ *+ * Ranked by how this user, their team and the install actually use tools after+ * the current one, and topped up from the curated list so the section never+ * shrinks. Falls back to the curated list entirely when the backend has no+ * usage data - a fresh install, tracking off, or no login to attribute runs to.+ */export function useSuggestedTools(): SuggestedTool[] {const { selectedTool } = useNavigationState();const { getToolNavigation } = useToolNavigation();- const { getSelectedTool } = useToolWorkflow();+ const { getSelectedTool, toolAvailability } = useToolWorkflow();+ const { recommendations } = useToolRecommendations(selectedTool, FETCH_LIMIT);return useMemo(() => {- // Filter out the current tool- const filteredTools = ALL_SUGGESTED_TOOLS.filter(- (tool) => tool.id !== selectedTool,- );+ const ordered = [+ ...orderRanked(recommendations ?? []),+ ...FALLBACK_TOOL_IDS,+ ];+ const suggestions: SuggestedTool[] = [];+ const seen = new Set<ToolId>();++ for (const id of ordered) {+ if (id === selectedTool || seen.has(id)) continue;+ const tool = getSelectedTool(id);+ // A card that cannot open anything is worse than a shorter list, and a+ // tool this install has disabled or cannot run is one of those.+ if (!tool || isComingSoonTool(id, tool)) continue;+ if (toolAvailability[id]?.available === false) continue;- // Add navigation props to each tool- return filteredTools.map((tool) => {- const toolRegistryEntry = getSelectedTool(tool.id);- if (!toolRegistryEntry) {- // Fallback for tools not in registry- return {- ...tool,- href: `/${tool.id}`,- onClick: (e: React.MouseEvent) => {- e.preventDefault();- },- };- }+ seen.add(id);+ suggestions.push({+ id,+ title: tool.name,+ icon: tool.icon,+ ...getToolNavigation(id, tool),+ });+ if (suggestions.length === SUGGESTION_COUNT) break;+ }- const navProps = getToolNavigation(tool.id, toolRegistryEntry);- return {- ...tool,- ...navProps,- };- });- }, [selectedTool, getToolNavigation, getSelectedTool]);+ return suggestions;+ }, [+ recommendations,+ selectedTool,+ getToolNavigation,+ getSelectedTool,+ toolAvailability,+ ]);}diff --git a/frontend/editor/src/core/hooks/useToolRecommendations.test.tsx b/frontend/editor/src/core/hooks/useToolRecommendations.test.tsxnew file mode 100644index 0000000000..57b5030a4e--- /dev/null+++ b/frontend/editor/src/core/hooks/useToolRecommendations.test.tsx@@ -0,0 +1,92 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { renderHook, waitFor, act } from "@testing-library/react";++import { TestQueryProvider } from "@app/tests/utils/TestQueryProvider";+import { fetchToolRecommendations } from "@app/api/toolRecommendations";+import { useToolRecommendations } from "@app/hooks/useToolRecommendations";+import {+ notifyToolCompleted,+ resetToolUsageTrackerForTests,+} from "@app/services/toolUsageTracker";++vi.mock("@app/api/toolRecommendations", () => ({+ fetchToolRecommendations: vi.fn(),+ recordToolUsage: vi.fn().mockResolvedValue(undefined),+}));++const mockFetch = vi.mocked(fetchToolRecommendations);++describe("useToolRecommendations", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetToolUsageTrackerForTests();+ });++ it("returns the backend ranking with its scores intact", async () => {+ const ranking = [+ { toolKey: "ocr", score: 5 },+ { toolKey: "merge", score: 3 },+ ];+ mockFetch.mockResolvedValue(ranking);++ const { result } = renderHook(() => useToolRecommendations(null), {+ wrapper: TestQueryProvider,+ });++ await waitFor(() =>+ expect(result.current.recommendations).toEqual(ranking),+ );+ });++ it("reports null when the backend is unavailable (static fallback)", async () => {+ mockFetch.mockResolvedValue(null);++ const { result } = renderHook(() => useToolRecommendations(null), {+ wrapper: TestQueryProvider,+ });++ await waitFor(() => expect(mockFetch).toHaveBeenCalled());+ expect(result.current.recommendations).toBeNull();+ });++ it("reports null on a cold start with no usage data", async () => {+ mockFetch.mockResolvedValue([]);++ const { result } = renderHook(() => useToolRecommendations(null), {+ wrapper: TestQueryProvider,+ });++ await waitFor(() => expect(mockFetch).toHaveBeenCalled());+ expect(result.current.recommendations).toBeNull();+ });++ it("asks in the context of the tool that is asking, not the last one to run", async () => {+ mockFetch.mockResolvedValue([]);++ renderHook(() => useToolRecommendations("split"), {+ wrapper: TestQueryProvider,+ });++ await waitFor(() => expect(mockFetch).toHaveBeenCalledWith("split", 8));+ });++ it("refetches once a tool completes, since that run is the newest evidence", async () => {+ mockFetch.mockResolvedValue([]);++ renderHook(() => useToolRecommendations("compare"), {+ wrapper: TestQueryProvider,+ });+ await waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1));++ act(() =>+ notifyToolCompleted({+ toolId: "compare",+ inputs: [],+ outputFileIds: [],+ }),+ );++ await waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(2));+ expect(mockFetch).toHaveBeenLastCalledWith("compare", 8);+ });+});diff --git a/frontend/editor/src/core/hooks/useToolRecommendations.ts b/frontend/editor/src/core/hooks/useToolRecommendations.tsnew file mode 100644index 0000000000..f4907c46aa--- /dev/null+++ b/frontend/editor/src/core/hooks/useToolRecommendations.ts@@ -0,0 +1,55 @@+import { useSyncExternalStore } from "react";++import { useQuery } from "@tanstack/react-query";++import {+ fetchToolRecommendations,+ type ToolRecommendationDto,+} from "@app/api/toolRecommendations";+import { qk } from "@app/query/keys";+import {+ getCompletionCount,+ subscribeToToolCompletions,+} from "@app/services/toolUsageTracker";+import { ToolId } from "@app/types/toolId";++const RECOMMENDATIONS_STALE_TIME = 2 * 60 * 1000;++/** Query-key stand-in for "ranked without a tool to follow". */+const NO_CONTEXT = "*";+export const DEFAULT_RECOMMENDATION_LIMIT = 8;++/**+ * Usage-ranked tools for the "what next" suggestions shown after a tool+ * finishes, or null when the backend has no data (or no recommendations API)+ * and the curated list should be shown instead.+ *+ * Scores come back with the ids: tools whose scores tie carry no preference of+ * their own, and the caller needs to know that rather than trust the order.+ *+ * `contextTool` is the tool whose panel is asking, so the ranking answers "what+ * follows this one". A completion refetches, because the run that just finished+ * is the newest evidence there is.+ */+export function useToolRecommendations(+ contextTool: ToolId | null,+ limit: number = DEFAULT_RECOMMENDATION_LIMIT,+): { recommendations: ToolRecommendationDto[] | null } {+ const completions = useSyncExternalStore(+ subscribeToToolCompletions,+ getCompletionCount,+ );++ const { data } = useQuery({+ queryKey: qk.toolRecommendations(+ contextTool ?? NO_CONTEXT,+ limit,+ completions,+ ),+ queryFn: () => fetchToolRecommendations(contextTool, limit),+ staleTime: RECOMMENDATIONS_STALE_TIME,+ retry: false,+ });++ return { recommendations: data && data.length > 0 ? data : null };+}diff --git a/frontend/editor/src/core/query/keys.ts b/frontend/editor/src/core/query/keys.tsindex a937f24217..0a759001fb 100644--- a/frontend/editor/src/core/query/keys.ts+++ b/frontend/editor/src/core/query/keys.ts@@ -17,5 +17,7 @@ export const qk = {["editor", "portalAccess", userId] as const,teamDetails: (teamId: number) => ["editor", "teamDetails", teamId] as const,teams: () => ["editor", "teams"] as const,+ toolRecommendations: (context: string, limit: number, completions: number) =>+ ["editor", "toolRecommendations", context, limit, completions] as const,users: () => ["editor", "users"] as const,} as const;diff --git a/frontend/editor/src/core/services/toolUsageTracker.test.ts b/frontend/editor/src/core/services/toolUsageTracker.test.tsnew file mode 100644index 0000000000..e6490abea5--- /dev/null+++ b/frontend/editor/src/core/services/toolUsageTracker.test.ts@@ -0,0 +1,146 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++import { recordToolUsage } from "@app/api/toolRecommendations";+import {+ getCompletionCount,+ getDocumentToolChain,+ notifyToolCompleted,+ resetToolUsageTrackerForTests,+ subscribeToToolCompletions,+} from "@app/services/toolUsageTracker";+import type { FileId } from "@app/types/file";+import type { ToolId } from "@app/types/toolId";++vi.mock("@app/api/toolRecommendations", () => ({+ recordToolUsage: vi.fn().mockResolvedValue(undefined),+}));++const mockRecord = vi.mocked(recordToolUsage);++const fileId = (id: string) => id as FileId;++/** A file the tracker has never seen, carrying only its persisted history. */+const uploaded = (id: string, history: ToolId[] = []) => ({+ id: fileId(id),+ toolHistory: history.map((toolId, index) => ({ toolId, timestamp: index })),+});++/** Runs a tool over `inputs`, producing `outputs`. */+const run = (+ toolId: ToolId,+ inputs: ReturnType<typeof uploaded>[],+ outputs: string[],+) =>+ notifyToolCompleted({ toolId, inputs, outputFileIds: outputs.map(fileId) });++describe("toolUsageTracker", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetToolUsageTrackerForTests();+ });++ it("records a fresh upload with no prior chain", () => {+ run("compare", [uploaded("a")], ["a2"]);++ expect(mockRecord).toHaveBeenCalledWith("compare", [[]]);+ expect(getCompletionCount()).toBe(1);+ });++ it("follows the document across operations that replace its id", () => {+ run("compress", [uploaded("a")], ["a2"]);+ run("ocr", [uploaded("a2")], ["a3"]);+ run("merge", [uploaded("a3")], ["a4"]);++ expect(mockRecord).toHaveBeenNthCalledWith(2, "ocr", [["compress"]]);+ expect(mockRecord).toHaveBeenLastCalledWith("merge", [["compress", "ocr"]]);+ });++ it("keeps each document's chain separate", () => {+ run("compress", [uploaded("a")], ["a2"]);+ // A different file: its chain must not inherit the compress above.+ run("ocr", [uploaded("b")], ["b2"]);+ run("watermark", [uploaded("a2")], ["a3"]);++ expect(mockRecord).toHaveBeenNthCalledWith(2, "ocr", [[]]);+ expect(mockRecord).toHaveBeenLastCalledWith("watermark", [["compress"]]);+ });++ it("seeds an unseen file from its persisted tool history", () => {+ run("watermark", [uploaded("a", ["compress", "ocr"])], ["a2"]);++ expect(mockRecord).toHaveBeenCalledWith("watermark", [["compress", "ocr"]]);+ });++ it("reports one chain per distinct input document", () => {+ run("compress", [uploaded("a")], ["a2"]);+ run("ocr", [uploaded("b")], ["b2"]);+ run("merge", [uploaded("a2"), uploaded("b2")], ["m"]);++ expect(mockRecord).toHaveBeenLastCalledWith("merge", [+ ["compress"],+ ["ocr"],+ ]);+ });++ it("collapses inputs that share a chain into one workflow", () => {+ run("compress", [uploaded("a")], ["a2"]);+ run("compress", [uploaded("b")], ["b2"]);+ run("merge", [uploaded("a2"), uploaded("b2")], ["m"]);++ expect(mockRecord).toHaveBeenLastCalledWith("merge", [["compress"]]);+ });++ it("carries the longest input chain onto a merged output", () => {+ run("compress", [uploaded("a")], ["a2"]);+ run("ocr", [uploaded("a2")], ["a3"]);+ run("merge", [uploaded("a3"), uploaded("b")], ["m"]);+ run("addPassword", [uploaded("m")], ["m2"]);++ expect(mockRecord).toHaveBeenLastCalledWith("addPassword", [+ ["compress", "ocr", "merge"],+ ]);+ });++ it("gives every output of a split the input's chain", () => {+ run("compress", [uploaded("a")], ["a2"]);+ run("split", [uploaded("a2")], ["p1", "p2"]);++ expect(getDocumentToolChain(uploaded("p1"))).toEqual(["compress", "split"]);+ expect(getDocumentToolChain(uploaded("p2"))).toEqual(["compress", "split"]);+ });++ it("leaves an input the tool never consumed with its chain intact", () => {+ run("compress", [uploaded("a")], ["a2"]);+ run("compress", [uploaded("b")], ["b2"]);+ // Only a2 succeeded, so b2 stays in the workbench and keeps its lineage.+ run("ocr", [uploaded("a2")], ["a3"]);++ expect(getDocumentToolChain(uploaded("b2"))).toEqual(["compress"]);+ });++ it("prefers the tracked chain over a stale persisted history", () => {+ run("compress", [uploaded("a")], ["a2"]);++ // The stub still carries the pre-operation history; the tracker is ahead.+ expect(getDocumentToolChain(uploaded("a2", ["ocr"]))).toEqual(["compress"]);+ });++ it("never rejects when recording fails", async () => {+ mockRecord.mockRejectedValueOnce(new Error("offline"));++ expect(() => run("compare", [uploaded("a")], ["a2"])).not.toThrow();+ await Promise.resolve();+ });++ it("notifies subscribers on every completion and stops after unsubscribe", () => {+ const listener = vi.fn();+ const unsubscribe = subscribeToToolCompletions(listener);++ run("compare", [uploaded("a")], ["a2"]);+ expect(listener).toHaveBeenCalledTimes(1);++ unsubscribe();+ run("ocr", [uploaded("a2")], ["a3"]);+ expect(listener).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/editor/src/core/services/toolUsageTracker.ts b/frontend/editor/src/core/services/toolUsageTracker.tsnew file mode 100644index 0000000000..192ca521e2--- /dev/null+++ b/frontend/editor/src/core/services/toolUsageTracker.ts@@ -0,0 +1,134 @@+import { recordToolUsage } from "@app/api/toolRecommendations";+import type { ToolId } from "@app/types/toolId";+import type { FileId, ToolOperation } from "@app/types/file";++// Module store rather than a context: tool completions happen deep in operation+// hooks, and every consumer only needs to know one happened. Which tool the+// suggestions are for comes from the panel showing them, not from here - the+// panel can belong to a tool that never runs through the operation hooks.+let completionCount = 0;+const listeners = new Set<() => void>();++/**+ * The tools applied to each live document, keyed by the file that currently+ * carries that lineage.+ *+ * A file's persisted `toolHistory` only follows its version chain, and the+ * operations most worth automating - convert, split, merge - deliberately start+ * a fresh chain, so history alone loses the document exactly where it gets+ * interesting. This map carries the lineage across that boundary by moving it+ * from a tool's inputs onto its outputs, and falls back to `toolHistory` for any+ * file it has not seen (a reload, or a version produced before this ran).+ */+const chainsByFileId = new Map<FileId, ToolId[]>();++// The workbench holds far fewer live files than this; the cap only stops a very+// long session from growing the map without bound.+const MAX_TRACKED_FILES = 500;++// The server keeps the trailing few steps; this just bounds the request body.+const MAX_CHAIN_LENGTH = 10;++export interface ToolCompletionInput {+ id: FileId;+ toolHistory?: ToolOperation[];+}++export interface ToolCompletion {+ toolId: ToolId;+ /** The documents the tool consumed. */+ inputs: ToolCompletionInput[];+ /** The documents it produced; they inherit the inputs' lineage. */+ outputFileIds: FileId[];+}++/** Bumped on every completion, so a ranking built before one can be refetched. */+export function getCompletionCount(): number {+ return completionCount;+}++/** The tools already applied to this document, newest step last. */+export function getDocumentToolChain(input: ToolCompletionInput): ToolId[] {+ const tracked = chainsByFileId.get(input.id);+ if (tracked) return tracked;+ return (input.toolHistory ?? []).map((operation) => operation.toolId);+}++export function subscribeToToolCompletions(listener: () => void): () => void {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+}++/**+ * Call once per successful tool run. The backend scores each input document's+ * chain, so a transition means "this is what came next for this file" and a+ * chain is a workflow that could be automated.+ */+export function notifyToolCompleted({+ toolId,+ inputs,+ outputFileIds,+}: ToolCompletion): void {+ const priorChains = distinctChains(inputs.map(getDocumentToolChain));+ const carried = trim([...dominantChain(priorChains), toolId]);++ // The inputs were consumed to produce the outputs, which now hold the lineage.+ for (const input of inputs) chainsByFileId.delete(input.id);+ for (const fileId of outputFileIds) rememberChain(fileId, carried);++ void recordToolUsage(toolId, priorChains);+ completionCount += 1;+ listeners.forEach((listener) => listener());+}++function rememberChain(fileId: FileId, chain: ToolId[]): void {+ chainsByFileId.delete(fileId);+ chainsByFileId.set(fileId, chain);+ while (chainsByFileId.size > MAX_TRACKED_FILES) {+ const oldest = chainsByFileId.keys().next();+ if (oldest.done) break;+ chainsByFileId.delete(oldest.value);+ }+}++function trim(chain: ToolId[]): ToolId[] {+ return chain.length > MAX_CHAIN_LENGTH+ ? chain.slice(chain.length - MAX_CHAIN_LENGTH)+ : chain;+}++/** Ten identically-processed inputs are one workflow, not ten. */+function distinctChains(chains: ToolId[][]): ToolId[][] {+ const byKey = new Map<string, ToolId[]>();+ for (const chain of chains) {+ const trimmed = trim(chain);+ byKey.set(trimmed.join(">"), trimmed);+ }+ return [...byKey.values()];+}++/**+ * Which lineage an output inherits when a tool took several documents in. The+ * longest chain is the most-processed input and so the best representative of+ * the workflow; the key order breaks ties so repeated merges stay consistent.+ */+function dominantChain(chains: ToolId[][]): ToolId[] {+ let best: ToolId[] = [];+ for (const chain of chains) {+ if (+ chain.length > best.length ||+ (chain.length === best.length && chain.join(">") < best.join(">"))+ ) {+ best = chain;+ }+ }+ return best;+}++export function resetToolUsageTrackerForTests(): void {+ completionCount = 0;+ chainsByFileId.clear();+ listeners.clear();+}diff --git a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsxindex 512259d5c5..affb5eb799 100644--- a/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx+++ b/frontend/editor/src/core/tests/convert/ConvertIntegration.test.tsx@@ -79,8 +79,14 @@ vi.mock("../../services/apiClient", () => ({// Import the mocked apiClientimport apiClient from "@app/services/apiClient";+import { notifyToolCompleted } from "@app/services/toolUsageTracker";const mockedApiClient = vi.mocked(apiClient, { deep: true });+// Usage-recommendation tracking would add its own posts to the apiClient spy.+vi.mock("../../services/toolUsageTracker", () => ({+ notifyToolCompleted: vi.fn(),+}));+// Mock only essential services that are actually called by the testsvi.mock("../../services/fileStorage", () => ({// FileContext subscribes to this to drop files whose bytes are unreadable.@@ -437,6 +443,16 @@ describe("Convert Tool Integration Tests", () => {// The output file must be persisted via fileStorage.persistVersionedOutputs// so downstream tools see it in the registry.expect(fileStorage.persistVersionedOutputs).toHaveBeenCalled();++ // The tracker must see the real input document and the output that+ // replaced it, so the recorded chain follows the file. Convert is exactly+ // the case that breaks the version chain, so the handover has to be here.+ const completion = vi.mocked(notifyToolCompleted).mock.calls[0][0];+ expect(completion.toolId).toBe("convert");+ expect(completion.inputs.map((input) => input.id)).toEqual([+ testFile.fileId,+ ]);+ expect(completion.outputFileIds).not.toHaveLength(0);});test("should handle API error responses correctly", async () => {diff --git a/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx b/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsxindex 2c94d29b97..a232656f3a 100644--- a/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx+++ b/frontend/editor/src/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx@@ -68,6 +68,11 @@ vi.mock("@app/hooks/useToolRunComplete", () => ({useToolRunComplete: () => onToolRunComplete,}));+// Usage-recommendation tracking would add its own posts to the apiClient spy.+vi.mock("../../services/toolUsageTracker", () => ({+ notifyToolCompleted: vi.fn(),+}));+// Mock only essential services that are actually called by the testsvi.mock("../../services/fileStorage", () => ({// FileContext subscribes to this to drop files whose bytes are unreadable.diff --git a/scripts/pre-commit/sort_locale_toml.py b/scripts/pre-commit/sort_locale_toml.pyindex 4b32b9f8e4..8465781b4f 100644--- a/scripts/pre-commit/sort_locale_toml.py+++ b/scripts/pre-commit/sort_locale_toml.py@@ -59,7 +59,10 @@ def sort_file(path: str, fix: bool) -> bool:raise SortError(f"{path}: refusing to sort, sorting would change the file's contents")if fix:- Path(path).write_text(expected, encoding="utf-8")+ # newline="" keeps LF: the default rewrites every line as CRLF on Windows,+ # which breaks readers that split on "\n".+ with Path(path).open("w", encoding="utf-8", newline="") as handle:+ handle.write(expected)return True