Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ffe29828d2 | ||
|
|
c2a63cf425 | ||
|
|
c3456adc2b | ||
|
|
179b569769 | ||
|
|
341adaa07d | ||
|
|
feebfe82fa |
@@ -5,6 +5,7 @@ frontend/dist
|
||||
frontend/build
|
||||
frontend/.vite
|
||||
frontend/.tauri
|
||||
frontend/src-tauri/target
|
||||
|
||||
# Gradle build artifacts
|
||||
.gradle
|
||||
|
||||
@@ -180,7 +180,7 @@ jobs:
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
file: ./docker/embedded/Dockerfile
|
||||
push: true
|
||||
tags: ${{ secrets.DOCKER_HUB_USERNAME }}/test:pr-${{ needs.check-comment.outputs.pr_number }}
|
||||
build-args: VERSION_TAG=alpha
|
||||
|
||||
@@ -262,7 +262,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
docker-rev: ["Dockerfile", "Dockerfile.ultra-lite", "Dockerfile.fat"]
|
||||
docker-rev: ["docker/embedded/Dockerfile", "docker/embedded/Dockerfile.ultra-lite", "docker/embedded/Dockerfile.fat"]
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
@@ -301,7 +301,7 @@ jobs:
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/backend/${{ matrix.docker-rev }}
|
||||
file: ./${{ matrix.docker-rev }}
|
||||
push: false
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
@@ -5,6 +5,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- V2-master
|
||||
- alljavadocker
|
||||
|
||||
# cancel in-progress jobs if a new job is triggered
|
||||
# This is useful to avoid running multiple builds for the same branch if a new commit is pushed
|
||||
@@ -93,10 +94,10 @@ jobs:
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
type=raw,value=latest
|
||||
|
||||
- name: Generate tags for latest (V2-demo branch - test)
|
||||
- name: Generate tags for latest (alljavadocker branch - test)
|
||||
id: meta-test
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
if: github.ref == 'refs/heads/V2-demo'
|
||||
if: github.ref == 'refs/heads/alljavadocker'
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/stirling-tools/stirling-pdf-test
|
||||
@@ -110,7 +111,7 @@ jobs:
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/Dockerfile.unified
|
||||
file: ./docker/embedded/Dockerfile
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -149,10 +150,10 @@ jobs:
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-fat
|
||||
type=raw,value=latest-fat
|
||||
|
||||
- name: Generate tags for latest-fat (V2-demo branch - test)
|
||||
- name: Generate tags for latest-fat (alljavadocker branch - test)
|
||||
id: meta-fat-test
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
if: github.ref == 'refs/heads/V2-demo'
|
||||
if: github.ref == 'refs/heads/alljavadocker'
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/stirling-tools/stirling-pdf-test
|
||||
@@ -166,7 +167,7 @@ jobs:
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/Dockerfile.unified
|
||||
file: ./docker/embedded/Dockerfile.fat
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -203,10 +204,10 @@ jobs:
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-ultra-lite
|
||||
type=raw,value=latest-ultra-lite
|
||||
|
||||
- name: Generate tags for ultra-lite (V2-demo branch - test)
|
||||
- name: Generate tags for ultra-lite (alljavadocker branch - test)
|
||||
id: meta-lite-test
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
if: github.ref == 'refs/heads/V2-demo'
|
||||
if: github.ref == 'refs/heads/alljavadocker'
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/stirling-tools/stirling-pdf-test
|
||||
@@ -220,7 +221,7 @@ jobs:
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/Dockerfile.unified-lite
|
||||
file: ./docker/embedded/Dockerfile.ultra-lite
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
@@ -107,7 +107,7 @@ jobs:
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
file: ./docker/embedded/Dockerfile
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -152,7 +152,7 @@ jobs:
|
||||
if: github.ref != 'refs/heads/main'
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.ultra-lite
|
||||
file: ./docker/embedded/Dockerfile.ultra-lite
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
@@ -183,7 +183,7 @@ jobs:
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./Dockerfile.fat
|
||||
file: ./docker/embedded/Dockerfile.fat
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
@@ -66,7 +66,7 @@ jobs:
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
file: ./docker/embedded/Dockerfile
|
||||
push: true
|
||||
tags: ${{ secrets.DOCKER_HUB_USERNAME }}/test:test-${{ github.sha }}
|
||||
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
|
||||
@@ -590,7 +590,6 @@ public class ApplicationProperties {
|
||||
private boolean ssoAutoLogin;
|
||||
private boolean database;
|
||||
private CustomMetadata customMetadata = new CustomMetadata();
|
||||
private Chatbot chatbot = new Chatbot();
|
||||
|
||||
@Data
|
||||
public static class CustomMetadata {
|
||||
@@ -609,62 +608,6 @@ public class ApplicationProperties {
|
||||
: producer;
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Chatbot {
|
||||
private boolean enabled;
|
||||
private boolean alphaWarning = true;
|
||||
private Cache cache = new Cache();
|
||||
private Models models = new Models();
|
||||
private Rag rag = new Rag();
|
||||
private Ocr ocr = new Ocr();
|
||||
private Audit audit = new Audit();
|
||||
private long maxPromptCharacters = 4000;
|
||||
private double minConfidenceNano = 0.65;
|
||||
private boolean streamingEnabled = false;
|
||||
private Usage usage = new Usage();
|
||||
|
||||
@Data
|
||||
public static class Cache {
|
||||
private long ttlMinutes = 720;
|
||||
private long maxEntries = 200;
|
||||
private long maxDocumentCharacters = 200000;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Models {
|
||||
private String provider = "openai";
|
||||
private String primary = "gpt-5-nano";
|
||||
private String fallback = "gpt-5-mini";
|
||||
private String embedding = "text-embedding-3-small";
|
||||
private double topP = 0.95;
|
||||
private long connectTimeoutMillis = 10000;
|
||||
private long readTimeoutMillis = 60000;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Rag {
|
||||
private int chunkSizeTokens = 512;
|
||||
private int chunkOverlapTokens = 128;
|
||||
private int topK = 8;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Ocr {
|
||||
private boolean enabledByDefault;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Audit {
|
||||
private boolean enabled = true;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Usage {
|
||||
private long perUserMonthlyTokens = 200000;
|
||||
private double warnAtRatio = 0.7;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -39,6 +39,7 @@ public class RequestUriUtils {
|
||||
// Specific static files bundled with the frontend
|
||||
if (normalizedUri.equals("/robots.txt")
|
||||
|| normalizedUri.equals("/favicon.ico")
|
||||
|| normalizedUri.equals("/manifest.json")
|
||||
|| normalizedUri.equals("/site.webmanifest")
|
||||
|| normalizedUri.equals("/manifest-classic.json")
|
||||
|| normalizedUri.equals("/index.html")) {
|
||||
|
||||
+48
-7
@@ -1,20 +1,61 @@
|
||||
package stirling.software.SPDF.controller.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@Controller
|
||||
public class ReactRoutingController {
|
||||
|
||||
@GetMapping(
|
||||
"/{path:^(?!api|static|robots\\.txt|favicon\\.ico|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js)[^\\.]*$}")
|
||||
public String forwardRootPaths() {
|
||||
return "forward:/index.html";
|
||||
@Value("${server.servlet.context-path:/}")
|
||||
private String contextPath;
|
||||
|
||||
@GetMapping(value = {"/", "/index.html"}, produces = MediaType.TEXT_HTML_VALUE)
|
||||
public ResponseEntity<String> serveIndexHtml(HttpServletRequest request)
|
||||
throws IOException {
|
||||
ClassPathResource resource = new ClassPathResource("static/index.html");
|
||||
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
String html = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
// Replace %BASE_URL% with the actual context path for base href
|
||||
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
|
||||
html = html.replace("%BASE_URL%", baseUrl);
|
||||
// Also rewrite any existing <base> tag (Vite may have baked one in)
|
||||
html =
|
||||
html.replaceFirst(
|
||||
"<base href=\\\"[^\\\"]*\\\"\\s*/?>",
|
||||
"<base href=\\\"" + baseUrl + "\\\" />");
|
||||
|
||||
// Inject context path as a global variable for API calls
|
||||
String contextPathScript =
|
||||
"<script>window.STIRLING_PDF_API_BASE_URL = '" + baseUrl + "';</script>";
|
||||
html = html.replace("</head>", contextPathScript + "</head>");
|
||||
|
||||
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(html);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping(
|
||||
"/{path:^(?!api|static|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js)[^\\.]*}/{subpath:^(?!.*\\.).*$}")
|
||||
public String forwardNestedPaths() {
|
||||
return "forward:/index.html";
|
||||
"/{path:^(?!api|static|robots\\.txt|favicon\\.ico|manifest.*\\.json|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*$}")
|
||||
public ResponseEntity<String> forwardRootPaths(HttpServletRequest request)
|
||||
throws IOException {
|
||||
return serveIndexHtml(request);
|
||||
}
|
||||
|
||||
@GetMapping(
|
||||
"/{path:^(?!api|static|pipeline|pdfjs|pdfjs-legacy|fonts|images|files|css|js|assets|locales|modern-logo|classic-logo|Login|og_images|samples)[^\\.]*}/{subpath:^(?!.*\\.).*$}")
|
||||
public ResponseEntity<String> forwardNestedPaths(HttpServletRequest request)
|
||||
throws IOException {
|
||||
return serveIndexHtml(request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,9 @@ logging.level.org.springframework.security=WARN
|
||||
logging.level.org.hibernate=WARN
|
||||
logging.level.org.eclipse.jetty=WARN
|
||||
#logging.level.org.springframework.security.oauth2=DEBUG
|
||||
#logging.level.org.springframework.security=DEBUG
|
||||
#logging.level.org.opensaml=DEBUG
|
||||
logging.level.stirling.software.proprietary.security=DEBUG
|
||||
#logging.level.stirling.software.proprietary.security=DEBUG
|
||||
logging.level.com.zaxxer.hikari=WARN
|
||||
logging.level.stirling.software.SPDF.service.PdfJsonConversionService=INFO
|
||||
logging.level.stirling.software.common.service.JobExecutorService=INFO
|
||||
@@ -51,39 +52,9 @@ server.servlet.session.timeout:30m
|
||||
springdoc.api-docs.path=/v1/api-docs
|
||||
# Set the URL of the OpenAPI JSON for the Swagger UI
|
||||
springdoc.swagger-ui.url=/v1/api-docs
|
||||
|
||||
# Spring AI OpenAI Configuration
|
||||
# Uses GPT-5-nano as primary model and GPT-5-mini as fallback (configured in settings.yml)
|
||||
spring.ai.openai.enabled=true
|
||||
#spring.ai.openai.api-key=# todo <API-KEY-HERE>
|
||||
spring.ai.openai.base-url=https://api.openai.com
|
||||
spring.ai.openai.chat.enabled=true
|
||||
spring.ai.openai.chat.options.model=gpt-5-nano
|
||||
# Note: Some models only support default temperature value of 1.0
|
||||
spring.ai.openai.chat.options.temperature=1.0
|
||||
# For newer models, use max-completion-tokens instead of max-tokens
|
||||
spring.ai.openai.chat.options.max-completion-tokens=4000
|
||||
spring.ai.openai.embedding.enabled=true
|
||||
spring.ai.openai.embedding.options.model=text-embedding-ada-002
|
||||
# Increase timeout for OpenAI API calls (default is 10 seconds)
|
||||
spring.ai.openai.chat.options.connection-timeout=60s
|
||||
spring.ai.openai.chat.options.read-timeout=60s
|
||||
spring.ai.openai.embedding.options.connection-timeout=60s
|
||||
spring.ai.openai.embedding.options.read-timeout=60s
|
||||
|
||||
# Spring AI Ollama Configuration (disabled to avoid bean conflicts)
|
||||
spring.ai.ollama.enabled=false
|
||||
spring.ai.ollama.base-url=http://localhost:11434
|
||||
spring.ai.ollama.chat.enabled=false
|
||||
spring.ai.ollama.chat.options.model=llama3
|
||||
spring.ai.ollama.chat.options.temperature=1.0
|
||||
spring.ai.ollama.embedding.enabled=false
|
||||
spring.ai.ollama.embedding.options.model=nomic-embed-text
|
||||
|
||||
# Force OpenAPI 3.0 specification version
|
||||
springdoc.swagger-ui.path=/swagger-ui.html
|
||||
# Force OpenAPI 3.0 specification version
|
||||
springdoc.api-docs.version=OPENAPI_3_0
|
||||
|
||||
posthog.api.key=phc_fiR65u5j6qmXTYL56MNrLZSWqLaDW74OrZH0Insd2xq
|
||||
posthog.host=https://eu.i.posthog.com
|
||||
|
||||
|
||||
@@ -91,32 +91,6 @@ premium:
|
||||
author: username
|
||||
creator: Stirling-PDF
|
||||
producer: Stirling-PDF
|
||||
chatbot:
|
||||
enabled: false # Master toggle for Stirling PDF chatbot feature
|
||||
alphaWarning: true # Display alpha-state warning before any processing
|
||||
cache:
|
||||
ttlMinutes: 720 # Cache entry lifetime (12h)
|
||||
maxEntries: 200 # Maximum number of cached documents per node
|
||||
maxDocumentCharacters: 600000 # Reject uploads exceeding this character count
|
||||
models:
|
||||
primary: gpt-5-nano # Default lightweight model
|
||||
fallback: gpt-5-mini # Escalation model for complex prompts
|
||||
embedding: text-embedding-3-small # Embedding model for vector store usage
|
||||
temperature: 0.2 # Sampling temperature for LLM responses
|
||||
topP: 0.95 # Top-p (nucleus) sampling for LLM responses
|
||||
rag:
|
||||
chunkSizeTokens: 512 # Token window used when chunking text
|
||||
chunkOverlapTokens: 128 # Overlap between successive chunks
|
||||
topK: 8 # Number of chunks to retrieve per query
|
||||
ocr:
|
||||
enabledByDefault: false # Whether OCR pre-processing is opted-in automatically
|
||||
audit:
|
||||
enabled: true # Emit audit records for chatbot activity
|
||||
maxPromptCharacters: 4000 # Server-side guardrail for incoming prompts
|
||||
minConfidenceNano: 0.65 # Minimum nano confidence to avoid escalation
|
||||
usage:
|
||||
perUserMonthlyTokens: 200000 # Monthly RAG + chat token budget per user
|
||||
warnAtRatio: 0.7 # Warn users when usage exceeds 70%
|
||||
enterpriseFeatures:
|
||||
audit:
|
||||
enabled: true # Enable audit logging
|
||||
|
||||
@@ -41,8 +41,6 @@ dependencies {
|
||||
api 'org.springframework:spring-webmvc'
|
||||
api 'org.springframework.session:spring-session-core'
|
||||
api "org.springframework.security:spring-security-core:$springSecuritySamlVersion"
|
||||
api "org.springframework.security:spring-security-web:$springSecuritySamlVersion"
|
||||
api "org.springframework.security:spring-security-config:$springSecuritySamlVersion"
|
||||
api "org.springframework.security:spring-security-saml2-service-provider:$springSecuritySamlVersion"
|
||||
api 'org.springframework.boot:spring-boot-starter-jetty'
|
||||
api 'org.springframework.boot:spring-boot-starter-security'
|
||||
@@ -52,16 +50,12 @@ dependencies {
|
||||
api 'org.springframework.boot:spring-boot-starter-cache'
|
||||
api 'com.github.ben-manes.caffeine:caffeine'
|
||||
api 'io.swagger.core.v3:swagger-core-jakarta:2.2.38'
|
||||
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
|
||||
implementation 'org.springframework.ai:spring-ai-starter-model-ollama'
|
||||
implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis'
|
||||
implementation 'redis.clients:jedis:5.1.0'
|
||||
implementation 'com.bucket4j:bucket4j_jdk17-core:8.15.0'
|
||||
|
||||
// https://mvnrepository.com/artifact/com.bucket4j/bucket4j_jdk17
|
||||
implementation 'org.bouncycastle:bcprov-jdk18on:1.82'
|
||||
|
||||
// implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.1.3.RELEASE' // Removed - UI moved to React frontend
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.1.3.RELEASE'
|
||||
api 'io.micrometer:micrometer-registry-prometheus'
|
||||
implementation 'com.unboundid.product.scim2:scim2-sdk-client:4.0.0'
|
||||
|
||||
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
package stirling.software.proprietary.config;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import redis.clients.jedis.Connection;
|
||||
import redis.clients.jedis.DefaultJedisClientConfig;
|
||||
import redis.clients.jedis.HostAndPort;
|
||||
import redis.clients.jedis.JedisClientConfig;
|
||||
import redis.clients.jedis.JedisPooled;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(value = "premium.proFeatures.chatbot.enabled", havingValue = "true")
|
||||
@Slf4j
|
||||
public class ChatbotRedisConfig {
|
||||
|
||||
@Value("${spring.data.redis.host:localhost}")
|
||||
private String redisHost;
|
||||
|
||||
@Value("${spring.data.redis.port:6379}")
|
||||
private int redisPort;
|
||||
|
||||
@Value("${spring.data.redis.password:}")
|
||||
private String redisPassword;
|
||||
|
||||
@Value("${spring.data.redis.timeout:60000}")
|
||||
private int redisTimeout;
|
||||
|
||||
@Value("${spring.data.redis.ssl.enabled:false}")
|
||||
private boolean sslEnabled;
|
||||
|
||||
@Bean
|
||||
public JedisPooled jedisPooled() {
|
||||
try {
|
||||
log.info("Creating JedisPooled connection to {}:{}", redisHost, redisPort);
|
||||
|
||||
// Create pool configuration
|
||||
GenericObjectPoolConfig<Connection> poolConfig = new GenericObjectPoolConfig<>();
|
||||
poolConfig.setMaxTotal(50);
|
||||
poolConfig.setMaxIdle(25);
|
||||
poolConfig.setMinIdle(5);
|
||||
poolConfig.setTestOnBorrow(true);
|
||||
poolConfig.setTestOnReturn(true);
|
||||
poolConfig.setTestWhileIdle(true);
|
||||
|
||||
// Create host and port configuration
|
||||
HostAndPort hostAndPort = new HostAndPort(redisHost, redisPort);
|
||||
|
||||
// Create client configuration with authentication if password is provided
|
||||
JedisClientConfig clientConfig;
|
||||
if (redisPassword != null && !redisPassword.trim().isEmpty()) {
|
||||
clientConfig =
|
||||
DefaultJedisClientConfig.builder()
|
||||
.password(redisPassword)
|
||||
.connectionTimeoutMillis(redisTimeout)
|
||||
.socketTimeoutMillis(redisTimeout)
|
||||
.ssl(sslEnabled)
|
||||
.build();
|
||||
} else {
|
||||
clientConfig =
|
||||
DefaultJedisClientConfig.builder()
|
||||
.connectionTimeoutMillis(redisTimeout)
|
||||
.socketTimeoutMillis(redisTimeout)
|
||||
.ssl(sslEnabled)
|
||||
.build();
|
||||
}
|
||||
|
||||
// Create JedisPooled with configuration
|
||||
JedisPooled jedisPooled = new JedisPooled(poolConfig, hostAndPort, clientConfig);
|
||||
|
||||
// Test the connection
|
||||
try {
|
||||
jedisPooled.ping();
|
||||
log.info("Successfully connected to Redis at {}:{}", redisHost, redisPort);
|
||||
} catch (Exception pingException) {
|
||||
log.warn(
|
||||
"Redis ping failed at {}:{} - {}. Redis might be unavailable.",
|
||||
redisHost,
|
||||
redisPort,
|
||||
pingException.getMessage());
|
||||
// Close the pool if ping fails
|
||||
try {
|
||||
jedisPooled.close();
|
||||
} catch (Exception closeException) {
|
||||
// Ignore close exceptions
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return jedisPooled;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to create JedisPooled connection", e);
|
||||
// Return null to fall back to SimpleVectorStore
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package stirling.software.proprietary.config;
|
||||
|
||||
import org.springframework.ai.embedding.EmbeddingModel;
|
||||
import org.springframework.ai.vectorstore.SimpleVectorStore;
|
||||
import org.springframework.ai.vectorstore.VectorStore;
|
||||
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import redis.clients.jedis.JedisPooled;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnProperty(value = "premium.proFeatures.chatbot.enabled", havingValue = "true")
|
||||
@Slf4j
|
||||
public class ChatbotVectorStoreConfig {
|
||||
|
||||
private static final String DEFAULT_INDEX = "stirling-chatbot-index";
|
||||
private static final String DEFAULT_PREFIX = "stirling:chatbot:";
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public VectorStore chatbotVectorStore(
|
||||
@Autowired(required = false) JedisPooled jedisPooled, EmbeddingModel embeddingModel) {
|
||||
if (jedisPooled != null) {
|
||||
try {
|
||||
log.info("Initialising Redis vector store for chatbot usage");
|
||||
return RedisVectorStore.builder(jedisPooled, embeddingModel)
|
||||
.indexName(DEFAULT_INDEX)
|
||||
.prefix(DEFAULT_PREFIX)
|
||||
.initializeSchema(true)
|
||||
.build();
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn(
|
||||
"Redis vector store unavailable ({}). Falling back to SimpleVectorStore.",
|
||||
sanitize(ex.getMessage()));
|
||||
}
|
||||
} else {
|
||||
log.info("No Redis connection detected; using SimpleVectorStore for chatbot.");
|
||||
}
|
||||
|
||||
return SimpleVectorStore.builder(embeddingModel).build();
|
||||
}
|
||||
|
||||
private String sanitize(String message) {
|
||||
return message == null ? "unknown error" : message.replaceAll("\\s+", " ").trim();
|
||||
}
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
package stirling.software.proprietary.config;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.embedding.EmbeddingModel;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* Spring AI Configuration for Stirling PDF Chatbot
|
||||
*
|
||||
* <p>This configuration enables Spring AI auto-configuration for chatbot features. The actual
|
||||
* ChatModel and EmbeddingModel beans are provided by Spring Boot's auto-configuration based on the
|
||||
* spring.ai.* properties in application-proprietary.properties
|
||||
*
|
||||
* <p>For OpenAI: - spring.ai.openai.enabled=true - spring.ai.openai.api-key=your-api-key
|
||||
*
|
||||
* <p>For Ollama (as fallback): - spring.ai.ollama.enabled=true -
|
||||
* spring.ai.ollama.base-url=http://localhost:11434
|
||||
*/
|
||||
@Configuration
|
||||
@Slf4j
|
||||
public class SpringAIConfig {
|
||||
|
||||
public SpringAIConfig() {
|
||||
log.info("Spring AI Configuration enabled for Stirling PDF Chatbot");
|
||||
log.info(
|
||||
"ChatModel and EmbeddingModel beans will be auto-configured based on spring.ai.* properties");
|
||||
}
|
||||
|
||||
/** Primary ChatModel bean that delegates to OpenAI's auto-configured bean */
|
||||
@Bean
|
||||
@Primary
|
||||
public ChatModel primaryChatModel(@Qualifier("openAiChatModel") ChatModel openAiChatModel) {
|
||||
log.info("Using OpenAI ChatModel as primary");
|
||||
return openAiChatModel;
|
||||
}
|
||||
|
||||
/** Primary EmbeddingModel bean that delegates to OpenAI's auto-configured bean */
|
||||
@Bean
|
||||
@Primary
|
||||
public EmbeddingModel primaryEmbeddingModel(
|
||||
@Qualifier("openAiEmbeddingModel") EmbeddingModel openAiEmbeddingModel) {
|
||||
log.info("Using OpenAI EmbeddingModel as primary");
|
||||
return openAiEmbeddingModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom RestTemplate for Spring AI OpenAI client with increased timeouts. This helps prevent
|
||||
* timeout errors when processing large documents or complex queries.
|
||||
*/
|
||||
@Bean(name = "openAiRestTemplate")
|
||||
public RestTemplate openAiRestTemplate(RestTemplateBuilder builder) {
|
||||
log.info("Creating custom RestTemplate for OpenAI with 60s timeouts");
|
||||
return builder.connectTimeout(Duration.ofSeconds(60))
|
||||
.readTimeout(Duration.ofSeconds(60))
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom RestClient for Spring AI OpenAI with increased timeouts. Spring AI 1.0.3+ prefers
|
||||
* RestClient over RestTemplate.
|
||||
*/
|
||||
@Bean(name = "openAiRestClient")
|
||||
public RestClient openAiRestClient() {
|
||||
log.info("Creating custom RestClient for OpenAI with 60s timeouts");
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(Duration.ofSeconds(60));
|
||||
factory.setReadTimeout(Duration.ofSeconds(60));
|
||||
|
||||
return RestClient.builder().requestFactory(factory).build();
|
||||
}
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package stirling.software.proprietary.configuration;
|
||||
|
||||
import java.net.http.HttpClient;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.web.client.RestClientCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.JdkClientHttpRequestFactory;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium.ProFeatures;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium.ProFeatures.Chatbot;
|
||||
|
||||
@Configuration
|
||||
@ConditionalOnClass(RestClientCustomizer.class)
|
||||
@ConditionalOnProperty(value = "spring.ai.openai.enabled", havingValue = "true")
|
||||
public class ChatbotAiClientConfiguration {
|
||||
|
||||
@Bean
|
||||
public RestClientCustomizer chatbotRestClientCustomizer(
|
||||
ApplicationProperties applicationProperties) {
|
||||
long connectTimeout = resolveConnectTimeout(applicationProperties);
|
||||
long readTimeout = resolveReadTimeout(applicationProperties);
|
||||
return builder -> builder.requestFactory(createRequestFactory(connectTimeout, readTimeout));
|
||||
}
|
||||
|
||||
private JdkClientHttpRequestFactory createRequestFactory(
|
||||
long connectTimeoutMillis, long readTimeoutMillis) {
|
||||
HttpClient httpClient =
|
||||
HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofMillis(connectTimeoutMillis))
|
||||
.build();
|
||||
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient);
|
||||
factory.setReadTimeout((int) readTimeoutMillis);
|
||||
return factory;
|
||||
}
|
||||
|
||||
private long resolveConnectTimeout(ApplicationProperties properties) {
|
||||
long configured = resolveChatbot(properties).getModels().getConnectTimeoutMillis();
|
||||
return configured > 0 ? configured : 30000L;
|
||||
}
|
||||
|
||||
private long resolveReadTimeout(ApplicationProperties properties) {
|
||||
long configured = resolveChatbot(properties).getModels().getReadTimeoutMillis();
|
||||
return configured > 0 ? configured : 120000L;
|
||||
}
|
||||
|
||||
private Chatbot resolveChatbot(ApplicationProperties properties) {
|
||||
return Optional.ofNullable(properties)
|
||||
.map(ApplicationProperties::getPremium)
|
||||
.map(Premium::getProFeatures)
|
||||
.map(ProFeatures::getChatbot)
|
||||
.orElseGet(Chatbot::new);
|
||||
}
|
||||
}
|
||||
-138
@@ -1,138 +0,0 @@
|
||||
package stirling.software.proprietary.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotChunkRequest;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotQueryRequest;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotResponse;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionCreateRequest;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionResponse;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotUsageSummary;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotCacheService;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.ChatbotSettings;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotService;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotSessionRegistry;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotStreamingIngestionService;
|
||||
import stirling.software.proprietary.service.chatbot.exception.ChatbotException;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/v1/internal/chatbot")
|
||||
public class ChatbotController {
|
||||
|
||||
private final ChatbotService chatbotService;
|
||||
private final ChatbotSessionRegistry sessionRegistry;
|
||||
private final ChatbotCacheService cacheService;
|
||||
private final ChatbotStreamingIngestionService streamingIngestionService;
|
||||
private final ChatbotFeatureProperties featureProperties;
|
||||
|
||||
@PostMapping("/session")
|
||||
public ResponseEntity<ChatbotSessionResponse> createSession(
|
||||
@RequestBody ChatbotSessionCreateRequest request) {
|
||||
ChatbotSession session = chatbotService.createSession(request);
|
||||
ChatbotSettings settings = featureProperties.current();
|
||||
ChatbotSessionResponse response = toResponse(session, settings);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(response);
|
||||
}
|
||||
|
||||
@PostMapping("/query")
|
||||
public ResponseEntity<ChatbotResponse> query(@RequestBody ChatbotQueryRequest request) {
|
||||
ChatbotResponse response = chatbotService.ask(request);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@PostMapping("/session/chunk")
|
||||
public ResponseEntity<ChatbotSessionResponse> streamChunk(
|
||||
@RequestBody ChatbotChunkRequest request) {
|
||||
ChatbotSessionResponse response = streamingIngestionService.ingestChunk(request);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@GetMapping("/session/{sessionId}")
|
||||
public ResponseEntity<ChatbotSessionResponse> getSession(@PathVariable String sessionId) {
|
||||
ChatbotSettings settings = featureProperties.current();
|
||||
ChatbotSession session =
|
||||
sessionRegistry
|
||||
.findById(sessionId)
|
||||
.orElseThrow(() -> new ChatbotException("Session not found"));
|
||||
ChatbotSessionResponse response = toResponse(session, settings);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@GetMapping("/document/{documentId}")
|
||||
public ResponseEntity<ChatbotSessionResponse> getSessionByDocument(
|
||||
@PathVariable String documentId) {
|
||||
ChatbotSettings settings = featureProperties.current();
|
||||
ChatbotSession session =
|
||||
sessionRegistry
|
||||
.findByDocumentId(documentId)
|
||||
.orElseThrow(() -> new ChatbotException("Session not found"));
|
||||
return ResponseEntity.ok(toResponse(session, settings));
|
||||
}
|
||||
|
||||
@DeleteMapping("/session/{sessionId}")
|
||||
public ResponseEntity<Void> closeSession(@PathVariable String sessionId) {
|
||||
chatbotService.close(sessionId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
private List<String> sessionWarnings(ChatbotSettings settings, ChatbotSession session) {
|
||||
List<String> warnings = new ArrayList<>();
|
||||
|
||||
if (session != null && session.isImageContentDetected()) {
|
||||
warnings.add("Images detected - Images are not currently supported.");
|
||||
}
|
||||
|
||||
warnings.add("Images are not yet supported. Only extracted text is sent for analysis.");
|
||||
if (session != null && session.isOcrRequested()) {
|
||||
warnings.add("OCR requested – uses credits .");
|
||||
}
|
||||
|
||||
if (session != null && session.getUsageSummary() != null) {
|
||||
ChatbotUsageSummary usage = session.getUsageSummary();
|
||||
if (usage.isLimitExceeded()) {
|
||||
warnings.add("Monthly chatbot allocation exceeded – requests may be throttled.");
|
||||
} else if (usage.isNearingLimit()) {
|
||||
warnings.add("You are approaching the monthly chatbot allocation.");
|
||||
}
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
private ChatbotSessionResponse toResponse(ChatbotSession session, ChatbotSettings settings) {
|
||||
return ChatbotSessionResponse.builder()
|
||||
.sessionId(session.getSessionId())
|
||||
.documentId(session.getDocumentId())
|
||||
.alphaWarning(settings.alphaWarning())
|
||||
.ocrRequested(session.isOcrRequested())
|
||||
.imageContentDetected(session.isImageContentDetected())
|
||||
.textCharacters(session.getTextCharacters())
|
||||
.estimatedTokens(session.getEstimatedTokens())
|
||||
.maxCachedCharacters(cacheService.getMaxDocumentCharacters())
|
||||
.createdAt(session.getCreatedAt())
|
||||
.warnings(sessionWarnings(settings, session))
|
||||
.metadata(new HashMap<>(session.getMetadata()))
|
||||
.usageSummary(session.getUsageSummary())
|
||||
.status(session.getStatus())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package stirling.software.proprietary.controller;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
import org.eclipse.jetty.client.HttpResponseException;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotService;
|
||||
import stirling.software.proprietary.service.chatbot.exception.ChatbotException;
|
||||
import stirling.software.proprietary.service.chatbot.exception.NoTextDetectedException;
|
||||
|
||||
@RestControllerAdvice(assignableTypes = ChatbotController.class)
|
||||
@Slf4j
|
||||
// @ConditionalOnProperty(value = "premium.proFeatures.chatbot.enabled", havingValue = "true")
|
||||
@ConditionalOnBean(ChatbotService.class)
|
||||
public class ChatbotExceptionHandler {
|
||||
|
||||
@ExceptionHandler(NoTextDetectedException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleNoText(NoTextDetectedException ex) {
|
||||
return buildResponse(HttpStatus.UNPROCESSABLE_ENTITY, ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(ChatbotException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleChatbot(ChatbotException ex) {
|
||||
log.debug("Chatbot exception: {}", ex.getMessage());
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleIllegalArgument(IllegalArgumentException ex) {
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ex.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpResponseException.class)
|
||||
public ResponseEntity<Map<String, Object>> handleProvider(HttpResponseException ex) {
|
||||
log.warn("Chatbot provider error", ex);
|
||||
return buildResponse(
|
||||
HttpStatus.BAD_GATEWAY,
|
||||
"Chatbot provider rejected the request: " + ex.getMessage());
|
||||
}
|
||||
|
||||
private ResponseEntity<Map<String, Object>> buildResponse(HttpStatus status, String message) {
|
||||
Map<String, Object> payload =
|
||||
Map.of(
|
||||
"timestamp", Instant.now().toString(),
|
||||
"status", status.value(),
|
||||
"error", message);
|
||||
return ResponseEntity.status(status).body(payload);
|
||||
}
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatbotChunkRequest {
|
||||
|
||||
private String sessionId;
|
||||
private String documentId;
|
||||
private String userId;
|
||||
private String chunkText;
|
||||
private int chunkOrder;
|
||||
private Map<String, String> metadata;
|
||||
private boolean finalChunk;
|
||||
private boolean ocrRequested;
|
||||
private boolean imagesDetected;
|
||||
private long totalCharactersHint;
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatbotDocumentCacheEntry {
|
||||
|
||||
private String cacheKey;
|
||||
private String sessionId;
|
||||
private String documentId;
|
||||
private Map<String, String> metadata;
|
||||
private boolean ocrApplied;
|
||||
private boolean imageContentDetected;
|
||||
private long textCharacters;
|
||||
private Instant storedAt;
|
||||
|
||||
public Map<String, String> getMetadata() {
|
||||
return metadata == null ? Collections.emptyMap() : metadata;
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/** Simple record representing a stored chatbot conversation turn. */
|
||||
public record ChatbotHistoryEntry(
|
||||
String role, String content, String documentId, String documentName, Instant timestamp) {}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatbotQueryRequest {
|
||||
|
||||
private String sessionId;
|
||||
private String prompt;
|
||||
private boolean allowEscalation;
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatbotResponse {
|
||||
|
||||
private String sessionId;
|
||||
private String modelUsed;
|
||||
private double confidence;
|
||||
private String answer;
|
||||
private boolean escalated;
|
||||
private boolean servedFromNanoOnly;
|
||||
private boolean cacheHit;
|
||||
private Instant respondedAt;
|
||||
private List<String> warnings;
|
||||
private Map<String, Object> metadata;
|
||||
private long promptTokens;
|
||||
private long completionTokens;
|
||||
private long totalTokens;
|
||||
private ChatbotUsageSummary usageSummary;
|
||||
|
||||
public List<String> getWarnings() {
|
||||
return warnings == null ? Collections.emptyList() : warnings;
|
||||
}
|
||||
|
||||
public Map<String, Object> getMetadata() {
|
||||
return metadata == null ? Collections.emptyMap() : metadata;
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class ChatbotSession {
|
||||
|
||||
private String sessionId;
|
||||
private String documentId;
|
||||
private String userId;
|
||||
private Map<String, String> metadata;
|
||||
private boolean ocrRequested;
|
||||
private boolean warningsAccepted;
|
||||
private boolean alphaWarningRequired;
|
||||
private boolean imageContentDetected;
|
||||
private long textCharacters;
|
||||
private long estimatedTokens;
|
||||
private String cacheKey;
|
||||
private String vectorStoreId;
|
||||
private Instant createdAt;
|
||||
private ChatbotUsageSummary usageSummary;
|
||||
private ChatbotSessionStatus status;
|
||||
|
||||
public static String randomSessionId() {
|
||||
return UUID.randomUUID().toString();
|
||||
}
|
||||
|
||||
public Map<String, String> getMetadata() {
|
||||
return metadata == null ? Collections.emptyMap() : metadata;
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatbotSessionCreateRequest {
|
||||
|
||||
private String sessionId;
|
||||
private String documentId;
|
||||
private String userId;
|
||||
private String text;
|
||||
private Map<String, String> metadata;
|
||||
private boolean ocrRequested;
|
||||
private boolean warningsAccepted;
|
||||
private boolean imagesDetected;
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatbotSessionResponse {
|
||||
|
||||
private String sessionId;
|
||||
private String documentId;
|
||||
private boolean alphaWarning;
|
||||
private boolean ocrRequested;
|
||||
private boolean imageContentDetected;
|
||||
private long maxCachedCharacters;
|
||||
private long textCharacters;
|
||||
private long estimatedTokens;
|
||||
private Instant createdAt;
|
||||
private List<String> warnings;
|
||||
private Map<String, String> metadata;
|
||||
private ChatbotUsageSummary usageSummary;
|
||||
private ChatbotSessionStatus status;
|
||||
|
||||
public List<String> getWarnings() {
|
||||
return warnings == null ? Collections.emptyList() : warnings;
|
||||
}
|
||||
|
||||
public Map<String, String> getMetadata() {
|
||||
return metadata == null ? Collections.emptyMap() : metadata;
|
||||
}
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
public enum ChatbotSessionStatus {
|
||||
PROCESSING,
|
||||
READY
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package stirling.software.proprietary.model.chatbot;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChatbotUsageSummary {
|
||||
|
||||
private long allocatedTokens;
|
||||
private long consumedTokens;
|
||||
private long remainingTokens;
|
||||
private double usageRatio;
|
||||
private boolean nearingLimit;
|
||||
private boolean limitExceeded;
|
||||
private long lastIncrementTokens;
|
||||
private String window;
|
||||
}
|
||||
+12
-18
@@ -59,7 +59,6 @@ import stirling.software.proprietary.security.service.JwtServiceInterface;
|
||||
import stirling.software.proprietary.security.service.LoginAttemptService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
|
||||
import stirling.software.proprietary.service.UserLicenseSettingsService;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@@ -85,7 +84,8 @@ public class SecurityConfiguration {
|
||||
private final GrantedAuthoritiesMapper oAuth2userAuthoritiesMapper;
|
||||
private final RelyingPartyRegistrationRepository saml2RelyingPartyRegistrations;
|
||||
private final OpenSaml4AuthenticationRequestResolver saml2AuthenticationRequestResolver;
|
||||
private final UserLicenseSettingsService licenseSettingsService;
|
||||
private final stirling.software.proprietary.service.UserLicenseSettingsService
|
||||
licenseSettingsService;
|
||||
|
||||
public SecurityConfiguration(
|
||||
PersistentLoginRepository persistentLoginRepository,
|
||||
@@ -106,7 +106,8 @@ public class SecurityConfiguration {
|
||||
RelyingPartyRegistrationRepository saml2RelyingPartyRegistrations,
|
||||
@Autowired(required = false)
|
||||
OpenSaml4AuthenticationRequestResolver saml2AuthenticationRequestResolver,
|
||||
UserLicenseSettingsService licenseSettingsService) {
|
||||
stirling.software.proprietary.service.UserLicenseSettingsService
|
||||
licenseSettingsService) {
|
||||
this.userDetailsService = userDetailsService;
|
||||
this.userService = userService;
|
||||
this.loginEnabledValue = loginEnabledValue;
|
||||
@@ -220,19 +221,9 @@ public class SecurityConfiguration {
|
||||
csrf.ignoringRequestMatchers(
|
||||
request -> {
|
||||
String uri = request.getRequestURI();
|
||||
String contextPath = request.getContextPath();
|
||||
String trimmedUri =
|
||||
uri.startsWith(contextPath)
|
||||
? uri.substring(
|
||||
contextPath.length())
|
||||
: uri;
|
||||
|
||||
// Ignore CSRF for auth endpoints + oauth/saml
|
||||
if (trimmedUri.startsWith("/api/v1/auth/")
|
||||
|| trimmedUri.startsWith("/oauth2")
|
||||
|| trimmedUri.startsWith("/saml2")
|
||||
|| trimmedUri.startsWith(
|
||||
"/login/oauth2/code/")) {
|
||||
// Ignore CSRF for auth endpoints
|
||||
if (uri.startsWith("/api/v1/auth/")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -333,10 +324,14 @@ public class SecurityConfiguration {
|
||||
.authenticated());
|
||||
// Handle User/Password Logins
|
||||
if (securityProperties.isUserPass()) {
|
||||
// v2: Authentication is handled via API (/api/v1/auth/login), not form login
|
||||
// We configure form login to handle Spring Security redirects,
|
||||
// but use /perform_login as the processing URL so /login remains a React route
|
||||
http.formLogin(
|
||||
formLogin ->
|
||||
formLogin
|
||||
.loginPage("/login")
|
||||
.loginPage("/login") // Redirect here when unauthenticated
|
||||
.loginProcessingUrl("/perform_login") // Process form posts here (not /login)
|
||||
.successHandler(
|
||||
new CustomAuthenticationSuccessHandler(
|
||||
loginAttemptService,
|
||||
@@ -369,8 +364,7 @@ public class SecurityConfiguration {
|
||||
securityProperties.getOauth2(),
|
||||
userService,
|
||||
jwtService,
|
||||
licenseSettingsService,
|
||||
applicationProperties))
|
||||
licenseSettingsService))
|
||||
.failureHandler(new CustomOAuth2AuthenticationFailureHandler())
|
||||
// Add existing Authorities from the database
|
||||
.userInfoEndpoint(
|
||||
|
||||
+13
@@ -56,6 +56,19 @@ public interface UserRepository extends JpaRepository<User, Long> {
|
||||
+ "OR LOWER(u.authenticationType) IN ('sso', 'oauth2', 'saml2')")
|
||||
List<User> findAllSsoUsers();
|
||||
|
||||
/**
|
||||
* Finds SSO users who have never created a session (pending activation) and are not yet
|
||||
* grandfathered.
|
||||
*/
|
||||
@Query(
|
||||
"SELECT u FROM User u "
|
||||
+ "LEFT JOIN SessionEntity s ON u.username = s.principalName "
|
||||
+ "WHERE (u.ssoProvider IS NOT NULL "
|
||||
+ "OR LOWER(u.authenticationType) IN ('sso', 'oauth2', 'saml2')) "
|
||||
+ "AND (u.oauthGrandfathered IS NULL OR u.oauthGrandfathered = false) "
|
||||
+ "AND s.sessionId IS NULL")
|
||||
List<User> findPendingSsoUsersWithoutSession();
|
||||
|
||||
/**
|
||||
* Counts all SSO users - those with sso_provider set OR authenticationType is sso/oauth2/saml2.
|
||||
*/
|
||||
|
||||
+1
-5
@@ -105,22 +105,18 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
}
|
||||
|
||||
try {
|
||||
log.debug("Validating JWT token");
|
||||
jwtService.validateToken(jwtToken);
|
||||
log.debug("JWT token validated successfully");
|
||||
} catch (AuthenticationFailureException e) {
|
||||
log.warn("JWT validation failed: {}", e.getMessage());
|
||||
log.debug("JWT validation failed: {}", e.getMessage());
|
||||
handleAuthenticationFailure(request, response, e);
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, Object> claims = jwtService.extractClaims(jwtToken);
|
||||
String tokenUsername = claims.get("sub").toString();
|
||||
log.debug("JWT token username: {}", tokenUsername);
|
||||
|
||||
try {
|
||||
authenticate(request, claims);
|
||||
log.debug("Authentication successful for user: {}", tokenUsername);
|
||||
} catch (SQLException | UnsupportedProviderException e) {
|
||||
log.error("Error processing user authentication for user: {}", tokenUsername, e);
|
||||
handleAuthenticationFailure(
|
||||
|
||||
+2
-3
@@ -38,7 +38,6 @@ import stirling.software.proprietary.security.model.AuthenticationType;
|
||||
import stirling.software.proprietary.security.service.JwtServiceInterface;
|
||||
import stirling.software.proprietary.security.service.LoginAttemptService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.service.UserLicenseSettingsService;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class CustomOAuth2AuthenticationSuccessHandler
|
||||
@@ -51,8 +50,8 @@ public class CustomOAuth2AuthenticationSuccessHandler
|
||||
private final ApplicationProperties.Security.OAUTH2 oauth2Properties;
|
||||
private final UserService userService;
|
||||
private final JwtServiceInterface jwtService;
|
||||
private final UserLicenseSettingsService licenseSettingsService;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
private final stirling.software.proprietary.service.UserLicenseSettingsService
|
||||
licenseSettingsService;
|
||||
|
||||
@Override
|
||||
@Audited(type = AuditEventType.USER_LOGIN, level = AuditLevel.BASIC)
|
||||
|
||||
+1
-5
@@ -50,7 +50,6 @@ public class JwtService implements JwtServiceInterface {
|
||||
KeyPersistenceServiceInterface keyPersistenceService) {
|
||||
this.v2Enabled = v2Enabled;
|
||||
this.keyPersistenceService = keyPersistenceService;
|
||||
log.info("JwtService initialized");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -256,11 +255,9 @@ public class JwtService implements JwtServiceInterface {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7); // Remove "Bearer " prefix
|
||||
log.debug("JWT token extracted from Authorization header");
|
||||
return token;
|
||||
}
|
||||
|
||||
log.debug("No JWT token found in Authorization header");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -283,10 +280,9 @@ public class JwtService implements JwtServiceInterface {
|
||||
.parse(token)
|
||||
.getHeader()
|
||||
.get("kid");
|
||||
log.debug("Extracted key ID from token: {}", keyId);
|
||||
return keyId;
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract key ID from token header: {}", e.getMessage());
|
||||
log.debug("Failed to extract key ID from token header: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
-1
@@ -55,7 +55,6 @@ public class KeyPairCleanupService {
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("Removing keys older than retention period");
|
||||
removeKeys(eligibleKeys);
|
||||
keyPersistenceService.refreshActiveKeyPair();
|
||||
}
|
||||
|
||||
+26
@@ -778,4 +778,30 @@ public class UserService implements UserServiceInterface {
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grandfathers SSO users who have never created a session (invited/pending accounts). These
|
||||
* users would otherwise be blocked when SSO requires a paid license despite existing before the
|
||||
* policy change.
|
||||
*
|
||||
* @return Number of pending users updated
|
||||
*/
|
||||
@Transactional
|
||||
public int grandfatherPendingSsoUsersWithoutSession() {
|
||||
List<User> pendingUsers = userRepository.findPendingSsoUsersWithoutSession();
|
||||
int updated = 0;
|
||||
|
||||
for (User user : pendingUsers) {
|
||||
if (!user.isOauthGrandfathered()) {
|
||||
user.setOauthGrandfathered(true);
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
if (updated > 0) {
|
||||
userRepository.saveAll(pendingUsers);
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
}
|
||||
|
||||
+12
-4
@@ -192,10 +192,18 @@ public class UserLicenseSettingsService {
|
||||
+ "They will retain OAuth access even without a paid license. "
|
||||
+ "New users will require a paid license for OAuth.",
|
||||
updated);
|
||||
} else if (grandfatheredCount > 0) {
|
||||
log.debug(
|
||||
"OAuth grandfathering already completed: {} users grandfathered",
|
||||
grandfatheredCount);
|
||||
}
|
||||
|
||||
// Grandfather pending users (invited but never logged in)
|
||||
// The query filters to non-grandfathered users only, so this is idempotent
|
||||
if (grandfatheredCount > 0 || oauthUsersCount > 0) {
|
||||
int pendingUpdated = userService.grandfatherPendingSsoUsersWithoutSession();
|
||||
if (pendingUpdated > 0) {
|
||||
log.warn(
|
||||
"OAuth GRANDFATHERING: Marked {} pending SSO users (no prior sessions) as"
|
||||
+ " grandfathered.",
|
||||
pendingUpdated);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium.ProFeatures;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium.ProFeatures.Chatbot;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotDocumentCacheEntry;
|
||||
|
||||
@Service
|
||||
// @ConditionalOnProperty(value = "premium.proFeatures.chatbot.enabled", havingValue = "true")
|
||||
@Slf4j
|
||||
public class ChatbotCacheService {
|
||||
|
||||
private final Cache<String, ChatbotDocumentCacheEntry>
|
||||
documentCache; // todo: can redis be used instead?
|
||||
private final long maxDocumentCharacters;
|
||||
private final Map<String, String> sessionToCacheKey = new ConcurrentHashMap<>();
|
||||
|
||||
public ChatbotCacheService(ApplicationProperties applicationProperties) {
|
||||
Chatbot chatbotConfig = resolveChatbot(applicationProperties);
|
||||
ApplicationProperties.Premium.ProFeatures.Chatbot.Cache cacheSettings =
|
||||
chatbotConfig.getCache();
|
||||
this.maxDocumentCharacters = cacheSettings.getMaxDocumentCharacters();
|
||||
long ttlMinutes = Math.max(cacheSettings.getTtlMinutes(), 1);
|
||||
long maxEntries = Math.max(cacheSettings.getMaxEntries(), 1);
|
||||
long maxTotalCharacters =
|
||||
Math.max(cacheSettings.getMaxDocumentCharacters() * maxEntries, 1);
|
||||
|
||||
this.documentCache =
|
||||
Caffeine.newBuilder()
|
||||
.maximumWeight(maxTotalCharacters)
|
||||
.weigher(
|
||||
(String key, ChatbotDocumentCacheEntry entry) ->
|
||||
(int)
|
||||
Math.min(
|
||||
entry.getTextCharacters()
|
||||
+ estimateMetadataWeight(entry),
|
||||
Integer.MAX_VALUE))
|
||||
.expireAfterWrite(Duration.ofMinutes(ttlMinutes))
|
||||
.recordStats()
|
||||
.build();
|
||||
log.info(
|
||||
"Initialised chatbot document cache with maxEntries={} ttlMinutes={} maxChars={} maxWeight={} characters",
|
||||
maxEntries,
|
||||
ttlMinutes,
|
||||
maxDocumentCharacters,
|
||||
maxTotalCharacters);
|
||||
}
|
||||
|
||||
public long getMaxDocumentCharacters() {
|
||||
return maxDocumentCharacters;
|
||||
}
|
||||
|
||||
private long estimateMetadataWeight(ChatbotDocumentCacheEntry entry) {
|
||||
if (entry == null || entry.getMetadata() == null) {
|
||||
return 0L;
|
||||
}
|
||||
return entry.getMetadata().entrySet().stream()
|
||||
.mapToLong(e -> safeLength(e.getKey()) + safeLength(e.getValue()))
|
||||
.sum();
|
||||
}
|
||||
|
||||
private long safeLength(String value) {
|
||||
return value == null ? 0L : value.length();
|
||||
}
|
||||
|
||||
public String register(
|
||||
String sessionId,
|
||||
String documentId,
|
||||
Map<String, String> metadata,
|
||||
boolean ocrApplied,
|
||||
boolean imageContentDetected,
|
||||
long textCharacters) {
|
||||
Objects.requireNonNull(sessionId, "sessionId must not be null");
|
||||
Objects.requireNonNull(documentId, "documentId must not be null");
|
||||
String cacheKey =
|
||||
sessionToCacheKey.computeIfAbsent(sessionId, k -> UUID.randomUUID().toString());
|
||||
ChatbotDocumentCacheEntry entry =
|
||||
ChatbotDocumentCacheEntry.builder()
|
||||
.cacheKey(cacheKey)
|
||||
.sessionId(sessionId)
|
||||
.documentId(documentId)
|
||||
.metadata(metadata)
|
||||
.ocrApplied(ocrApplied)
|
||||
.imageContentDetected(imageContentDetected)
|
||||
.textCharacters(textCharacters)
|
||||
.storedAt(Instant.now())
|
||||
.build();
|
||||
documentCache.put(cacheKey, entry);
|
||||
return cacheKey;
|
||||
}
|
||||
|
||||
public Optional<ChatbotDocumentCacheEntry> resolveByCacheKey(String cacheKey) {
|
||||
return Optional.ofNullable(documentCache.getIfPresent(cacheKey));
|
||||
}
|
||||
|
||||
public Optional<ChatbotDocumentCacheEntry> resolveBySessionId(String sessionId) {
|
||||
return Optional.ofNullable(sessionToCacheKey.get(sessionId))
|
||||
.flatMap(this::resolveByCacheKey);
|
||||
}
|
||||
|
||||
public void invalidateSession(String sessionId) {
|
||||
Optional.ofNullable(sessionToCacheKey.remove(sessionId))
|
||||
.ifPresent(documentCache::invalidate);
|
||||
}
|
||||
|
||||
public void invalidateCacheKey(String cacheKey) {
|
||||
documentCache.invalidate(cacheKey);
|
||||
sessionToCacheKey.values().removeIf(value -> value.equals(cacheKey));
|
||||
}
|
||||
|
||||
public Map<String, ChatbotDocumentCacheEntry> snapshot() {
|
||||
return Map.copyOf(documentCache.asMap());
|
||||
}
|
||||
|
||||
private Chatbot resolveChatbot(ApplicationProperties properties) {
|
||||
if (properties == null) {
|
||||
return new Chatbot();
|
||||
}
|
||||
Premium premium = properties.getPremium();
|
||||
if (premium == null) {
|
||||
return new Chatbot();
|
||||
}
|
||||
ProFeatures pro = premium.getProFeatures();
|
||||
if (pro == null) {
|
||||
return new Chatbot();
|
||||
}
|
||||
Chatbot chatbot = pro.getChatbot();
|
||||
return chatbot == null ? new Chatbot() : chatbot;
|
||||
}
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
@Component
|
||||
public class ChatbotContextCompressor {
|
||||
|
||||
private static final int DEFAULT_SUMMARY_LIMIT = 3000;
|
||||
private static final int MIN_CHUNK_SNIPPET = 160;
|
||||
|
||||
public String summarize(List<Document> documents, int requestedLimit) {
|
||||
if (CollectionUtils.isEmpty(documents)) {
|
||||
return "No contextual snippets available for this session.";
|
||||
}
|
||||
int maxChars =
|
||||
requestedLimit > 0
|
||||
? Math.min(requestedLimit, DEFAULT_SUMMARY_LIMIT)
|
||||
: DEFAULT_SUMMARY_LIMIT;
|
||||
StringBuilder builder = new StringBuilder();
|
||||
int perChunkLimit = Math.max(MIN_CHUNK_SNIPPET, maxChars / Math.max(documents.size(), 1));
|
||||
for (Document doc : documents) {
|
||||
if (builder.length() >= maxChars) {
|
||||
break;
|
||||
}
|
||||
String chunkOrder = doc.getMetadata().getOrDefault("chunkOrder", "?").toString();
|
||||
String text = trimContent(doc.getText(), perChunkLimit);
|
||||
builder.append("Chunk ").append(chunkOrder).append(": ").append(text).append('\n');
|
||||
}
|
||||
if (builder.length() == 0) {
|
||||
return "Unable to summarise context; original content unavailable.";
|
||||
}
|
||||
return builder.substring(0, Math.min(builder.length(), maxChars)).trim();
|
||||
}
|
||||
|
||||
private String trimContent(String content, int perChunkLimit) {
|
||||
if (content == null || content.isBlank()) {
|
||||
return "(empty chunk)";
|
||||
}
|
||||
String normalized = content.replaceAll("\\s+", " ").trim();
|
||||
if (normalized.length() <= perChunkLimit) {
|
||||
return normalized;
|
||||
}
|
||||
return normalized.substring(0, Math.max(0, perChunkLimit - 3)) + "...";
|
||||
}
|
||||
}
|
||||
-645
@@ -1,645 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.springframework.ai.chat.messages.SystemMessage;
|
||||
import org.springframework.ai.chat.messages.UserMessage;
|
||||
import org.springframework.ai.chat.metadata.Usage;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.ollama.OllamaChatModel;
|
||||
import org.springframework.ai.openai.OpenAiChatModel;
|
||||
import org.springframework.ai.openai.OpenAiChatOptions;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotDocumentCacheEntry;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotHistoryEntry;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotQueryRequest;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotResponse;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionStatus;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotUsageSummary;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.ChatbotSettings;
|
||||
import stirling.software.proprietary.service.chatbot.exception.ChatbotException;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChatbotConversationService {
|
||||
|
||||
private static final int SUMMARY_TRIGGER_MULTIPLIER = 3;
|
||||
private static final int SUMMARY_TRANSCRIPT_MAX_CHARS = 4000;
|
||||
|
||||
private final ChatModel chatModel;
|
||||
private final ChatbotSessionRegistry sessionRegistry;
|
||||
private final ChatbotCacheService cacheService;
|
||||
private final ChatbotFeatureProperties featureProperties;
|
||||
private final ChatbotRetrievalService retrievalService;
|
||||
private final ChatbotContextCompressor contextCompressor;
|
||||
private final ChatbotMemoryService memoryService;
|
||||
private final ChatbotUsageService usageService;
|
||||
private final ChatbotConversationStore conversationStore;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AtomicBoolean modelSwitchVerified = new AtomicBoolean(false);
|
||||
|
||||
public ChatbotResponse handleQuery(ChatbotQueryRequest request) {
|
||||
ChatbotSettings settings = featureProperties.current();
|
||||
if (!settings.enabled()) {
|
||||
throw new ChatbotException("Chatbot feature is disabled");
|
||||
}
|
||||
if (!StringUtils.hasText(request.getPrompt())) {
|
||||
throw new ChatbotException("Prompt cannot be empty");
|
||||
}
|
||||
if (request.getPrompt().length() > settings.maxPromptCharacters()) {
|
||||
throw new ChatbotException("Prompt exceeds maximum allowed characters");
|
||||
}
|
||||
ChatbotSession session =
|
||||
sessionRegistry
|
||||
.findById(request.getSessionId())
|
||||
.orElseThrow(() -> new ChatbotException("Unknown chatbot session"));
|
||||
|
||||
if (session.getStatus() == null) {
|
||||
session.setStatus(ChatbotSessionStatus.READY);
|
||||
}
|
||||
if (session.getStatus() == ChatbotSessionStatus.PROCESSING) {
|
||||
throw new ChatbotException("Chatbot session is still processing the document.");
|
||||
}
|
||||
|
||||
ensureModelSwitchCapability(settings);
|
||||
|
||||
ChatbotDocumentCacheEntry cacheEntry =
|
||||
cacheService
|
||||
.resolveBySessionId(request.getSessionId())
|
||||
.orElseThrow(() -> new ChatbotException("Session cache not found"));
|
||||
|
||||
List<String> warnings = buildWarnings(settings, session);
|
||||
|
||||
List<Document> context =
|
||||
retrievalService.retrieveTopK(
|
||||
request.getSessionId(), request.getPrompt(), settings);
|
||||
String precomputedSummary = session.getMetadata().get("content.summary");
|
||||
String contextSummary =
|
||||
StringUtils.hasText(precomputedSummary)
|
||||
? precomputedSummary
|
||||
: contextCompressor.summarize(
|
||||
context, (int) Math.max(settings.maxPromptCharacters() / 2, 1000));
|
||||
List<ChatbotHistoryEntry> conversationHistory =
|
||||
loadConversationHistory(session.getSessionId());
|
||||
String conversationSummary = loadConversationSummary(session.getSessionId());
|
||||
|
||||
ModelReply nanoReply =
|
||||
invokeModel(
|
||||
settings,
|
||||
settings.models().primary(),
|
||||
request.getPrompt(),
|
||||
session,
|
||||
context,
|
||||
contextSummary,
|
||||
cacheEntry.getMetadata(),
|
||||
conversationHistory,
|
||||
conversationSummary);
|
||||
|
||||
boolean shouldEscalate =
|
||||
request.isAllowEscalation()
|
||||
&& (nanoReply.requiresEscalation()
|
||||
|| nanoReply.confidence() < settings.minConfidenceNano()
|
||||
|| request.getPrompt().length() > settings.maxPromptCharacters());
|
||||
|
||||
ModelReply finalReply = nanoReply;
|
||||
boolean escalated = false;
|
||||
if (shouldEscalate) {
|
||||
escalated = true;
|
||||
finalReply =
|
||||
invokeModel(
|
||||
settings,
|
||||
settings.models().fallback(),
|
||||
request.getPrompt(),
|
||||
session,
|
||||
context,
|
||||
contextSummary,
|
||||
cacheEntry.getMetadata(),
|
||||
conversationHistory,
|
||||
conversationSummary);
|
||||
}
|
||||
|
||||
ChatbotUsageSummary usageSummary =
|
||||
usageService.registerGeneration(
|
||||
session.getUserId(),
|
||||
finalReply.promptTokens(),
|
||||
finalReply.completionTokens());
|
||||
session.setUsageSummary(usageSummary);
|
||||
|
||||
memoryService.recordTurn(session, request.getPrompt(), finalReply.answer());
|
||||
recordHistoryTurn(session, "user", request.getPrompt());
|
||||
recordHistoryTurn(session, "assistant", finalReply.answer());
|
||||
summarizeConversation(settings, session);
|
||||
enforceHistoryRetention(session);
|
||||
|
||||
return ChatbotResponse.builder()
|
||||
.sessionId(request.getSessionId())
|
||||
.modelUsed(
|
||||
shouldEscalate ? settings.models().fallback() : settings.models().primary())
|
||||
.confidence(finalReply.confidence())
|
||||
.answer(finalReply.answer())
|
||||
.escalated(escalated)
|
||||
.servedFromNanoOnly(!escalated)
|
||||
.cacheHit(true)
|
||||
.respondedAt(Instant.now())
|
||||
.warnings(warnings)
|
||||
.metadata(buildMetadata(settings, session, finalReply, context.size(), escalated))
|
||||
.promptTokens(finalReply.promptTokens())
|
||||
.completionTokens(finalReply.completionTokens())
|
||||
.totalTokens(finalReply.totalTokens())
|
||||
.usageSummary(usageSummary)
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<String> buildWarnings(ChatbotSettings settings, ChatbotSession session) {
|
||||
List<String> warnings = new ArrayList<>();
|
||||
warnings.add("Chatbot is in alpha – behaviour may change.");
|
||||
|
||||
if (session.isImageContentDetected()) {
|
||||
warnings.add("Image content is not yet supported.");
|
||||
}
|
||||
if (session.isOcrRequested()) {
|
||||
warnings.add("OCR costs may apply for this session.");
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildMetadata(
|
||||
ChatbotSettings settings,
|
||||
ChatbotSession session,
|
||||
ModelReply reply,
|
||||
int contextSize,
|
||||
boolean escalated) {
|
||||
Map<String, Object> metadata = new HashMap<>();
|
||||
metadata.put("contextSize", contextSize);
|
||||
metadata.put("requiresEscalation", reply.requiresEscalation());
|
||||
metadata.put("escalated", escalated);
|
||||
metadata.put("rationale", reply.rationale());
|
||||
metadata.put("modelProvider", settings.models().provider().name());
|
||||
metadata.put("imageContentDetected", session.isImageContentDetected());
|
||||
metadata.put("charactersCached", session.getTextCharacters());
|
||||
metadata.put("promptTokens", reply.promptTokens());
|
||||
metadata.put("completionTokens", reply.completionTokens());
|
||||
metadata.put("totalTokens", reply.totalTokens());
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private void ensureModelSwitchCapability(ChatbotSettings settings) {
|
||||
ChatbotSettings.ModelProvider provider = settings.models().provider();
|
||||
|
||||
switch (provider) {
|
||||
case OPENAI -> {
|
||||
if (!(chatModel instanceof OpenAiChatModel)) {
|
||||
throw new ChatbotException(
|
||||
"Chatbot requires an OpenAI chat model to support runtime model switching.");
|
||||
}
|
||||
}
|
||||
case OLLAMA -> {
|
||||
if (!(chatModel instanceof OllamaChatModel)) {
|
||||
throw new ChatbotException(
|
||||
"Chatbot is configured for Ollama but no Ollama chat model bean is available.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (modelSwitchVerified.compareAndSet(false, true)) {
|
||||
log.info(
|
||||
"Verified runtime model override support for provider {} ({} -> {})",
|
||||
provider,
|
||||
settings.models().primary(),
|
||||
settings.models().fallback());
|
||||
}
|
||||
}
|
||||
|
||||
private ModelReply invokeModel(
|
||||
ChatbotSettings settings,
|
||||
String model,
|
||||
String prompt,
|
||||
ChatbotSession session,
|
||||
List<Document> context,
|
||||
String contextSummary,
|
||||
Map<String, String> metadata,
|
||||
List<ChatbotHistoryEntry> history,
|
||||
String conversationSummary) {
|
||||
Prompt requestPrompt =
|
||||
buildPrompt(
|
||||
settings,
|
||||
model,
|
||||
prompt,
|
||||
session,
|
||||
context,
|
||||
contextSummary,
|
||||
metadata,
|
||||
history,
|
||||
conversationSummary);
|
||||
ChatResponse response;
|
||||
|
||||
try {
|
||||
response = chatModel.call(requestPrompt);
|
||||
} catch (org.eclipse.jetty.client.HttpResponseException ex) {
|
||||
throw new ChatbotException(
|
||||
"Chat model rejected the request: " + sanitizeRemoteMessage(ex.getMessage()),
|
||||
ex);
|
||||
} catch (RuntimeException ex) {
|
||||
throw new ChatbotException(
|
||||
"Failed to contact chat model provider: "
|
||||
+ sanitizeRemoteMessage(ex.getMessage()),
|
||||
ex);
|
||||
}
|
||||
long promptTokens = 0L;
|
||||
long completionTokens = 0L;
|
||||
long totalTokens = 0L;
|
||||
|
||||
if (response != null && response.getMetadata() != null) {
|
||||
Usage usage = response.getMetadata().getUsage();
|
||||
|
||||
if (usage != null) {
|
||||
promptTokens = toLong(usage.getPromptTokens());
|
||||
completionTokens = toLong(usage.getCompletionTokens());
|
||||
totalTokens =
|
||||
usage.getTotalTokens() != null
|
||||
? usage.getTotalTokens()
|
||||
: promptTokens + completionTokens;
|
||||
}
|
||||
}
|
||||
String content =
|
||||
Optional.ofNullable(response)
|
||||
.map(ChatResponse::getResults)
|
||||
.filter(results -> !results.isEmpty())
|
||||
.map(results -> results.get(0).getOutput().getText())
|
||||
.orElse("");
|
||||
return parseModelResponse(content, promptTokens, completionTokens, totalTokens);
|
||||
}
|
||||
|
||||
private Prompt buildPrompt(
|
||||
ChatbotSettings settings,
|
||||
String model,
|
||||
String question,
|
||||
ChatbotSession session,
|
||||
List<Document> context,
|
||||
String contextSummary,
|
||||
Map<String, String> metadata,
|
||||
List<ChatbotHistoryEntry> history,
|
||||
String conversationSummary) {
|
||||
String chunkOutline = buildChunkOutline(context);
|
||||
String chunkExcerpts = buildChunkExcerpts(context);
|
||||
String metadataSummary =
|
||||
metadata.entrySet().stream()
|
||||
.map(entry -> entry.getKey() + ": " + entry.getValue())
|
||||
.reduce((left, right) -> left + ", " + right)
|
||||
.orElse("none");
|
||||
String recentTurns = buildConversationOutline(history);
|
||||
|
||||
String imageDirective =
|
||||
session.isImageContentDetected()
|
||||
? "Images were detected in this PDF. You must explain that image analysis is not available."
|
||||
: "No images detected in this PDF.";
|
||||
|
||||
String systemPrompt =
|
||||
"You are Stirling PDF Bot. Use provided context strictly. "
|
||||
+ "Respond in compact JSON with fields answer (string), confidence (0..1), requiresEscalation (boolean), rationale (string). "
|
||||
+ "Explain limitations when context insufficient. Always note that image analysis is not supported yet.";
|
||||
|
||||
String userPrompt =
|
||||
"Document metadata: "
|
||||
+ metadataSummary
|
||||
+ "\nOCR applied: "
|
||||
+ session.isOcrRequested()
|
||||
+ "\n"
|
||||
+ imageDirective
|
||||
+ "\nConversation summary:\n"
|
||||
+ (StringUtils.hasText(conversationSummary)
|
||||
? conversationSummary
|
||||
: "No persistent summary available.")
|
||||
+ "\nRecent conversation turns:\n"
|
||||
+ recentTurns
|
||||
+ "\nContext summary:\n"
|
||||
+ contextSummary
|
||||
+ "\nContext outline:\n"
|
||||
+ chunkOutline
|
||||
+ "\nSelected excerpts:\n"
|
||||
+ chunkExcerpts
|
||||
+ "Question: "
|
||||
+ question;
|
||||
|
||||
OpenAiChatOptions options = buildChatOptions(settings, model);
|
||||
|
||||
return new Prompt(
|
||||
List.of(new SystemMessage(systemPrompt), new UserMessage(userPrompt)), options);
|
||||
}
|
||||
|
||||
private OpenAiChatOptions buildChatOptions(ChatbotSettings settings, String model) {
|
||||
OpenAiChatOptions.Builder builder = OpenAiChatOptions.builder().model(model);
|
||||
String normalizedModel = model == null ? "" : model.toLowerCase();
|
||||
boolean reasoningModel = normalizedModel.startsWith("gpt-5-");
|
||||
if (!reasoningModel) {
|
||||
builder.topP(settings.models().topP());
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
private String buildChunkOutline(List<Document> context) {
|
||||
if (context == null || context.isEmpty()) {
|
||||
return "No chunks retrieved for this question.";
|
||||
}
|
||||
StringBuilder outline = new StringBuilder();
|
||||
for (Document chunk : context) {
|
||||
String order = chunk.getMetadata().getOrDefault("chunkOrder", "?").toString();
|
||||
String snippet = resolveSnippet(chunk, 240);
|
||||
outline.append("- Chunk ").append(order).append(": ").append(snippet).append("\n");
|
||||
}
|
||||
return outline.toString();
|
||||
}
|
||||
|
||||
private String buildChunkExcerpts(List<Document> context) {
|
||||
if (context == null || context.isEmpty()) {
|
||||
return "No excerpts available.";
|
||||
}
|
||||
StringBuilder excerpts = new StringBuilder();
|
||||
for (Document chunk : context) {
|
||||
String order = chunk.getMetadata().getOrDefault("chunkOrder", "?").toString();
|
||||
String snippet = resolveSnippet(chunk, 400);
|
||||
if (!StringUtils.hasText(snippet)) {
|
||||
continue;
|
||||
}
|
||||
excerpts.append("[Chunk ").append(order).append("] ").append(snippet).append("\n");
|
||||
}
|
||||
if (!StringUtils.hasText(excerpts)) {
|
||||
return "Chunks retrieved but no text excerpts available.";
|
||||
}
|
||||
return excerpts.toString();
|
||||
}
|
||||
|
||||
private String resolveSnippet(Document chunk, int maxLen) {
|
||||
Object snippetObj = chunk.getMetadata().get("chunkSnippet");
|
||||
String snippet =
|
||||
snippetObj instanceof String ? (String) snippetObj : chunk.getText();
|
||||
if (!StringUtils.hasText(snippet)) {
|
||||
return "(empty)";
|
||||
}
|
||||
String normalized = snippet.replaceAll("\\s+", " ").trim();
|
||||
if (normalized.length() > maxLen) {
|
||||
return normalized.substring(0, maxLen - 3) + "...";
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private String buildConversationOutline(List<ChatbotHistoryEntry> history) {
|
||||
if (history == null || history.isEmpty()) {
|
||||
return "No earlier turns stored for this session.";
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (ChatbotHistoryEntry entry : history) {
|
||||
if (entry == null || !StringUtils.hasText(entry.content())) {
|
||||
continue;
|
||||
}
|
||||
builder.append(entry.role()).append(": ").append(entry.content().trim());
|
||||
if (StringUtils.hasText(entry.documentName())) {
|
||||
builder.append(" (doc: ").append(entry.documentName()).append(")");
|
||||
}
|
||||
builder.append("\n");
|
||||
}
|
||||
if (!StringUtils.hasText(builder)) {
|
||||
return "Conversation history available but empty after filtering.";
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private ModelReply parseModelResponse(
|
||||
String raw, long promptTokens, long completionTokens, long totalTokens) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
throw new ChatbotException("Model returned empty response");
|
||||
}
|
||||
try {
|
||||
JsonNode node = objectMapper.readTree(raw);
|
||||
String answer =
|
||||
Optional.ofNullable(node.get("answer")).map(JsonNode::asText).orElse(raw);
|
||||
double confidence =
|
||||
Optional.ofNullable(node.get("confidence"))
|
||||
.map(JsonNode::asDouble)
|
||||
.orElse(0.0D);
|
||||
boolean requiresEscalation =
|
||||
Optional.ofNullable(node.get("requiresEscalation"))
|
||||
.map(JsonNode::asBoolean)
|
||||
.orElse(false);
|
||||
String rationale =
|
||||
Optional.ofNullable(node.get("rationale"))
|
||||
.map(JsonNode::asText)
|
||||
.orElse("Model did not provide rationale");
|
||||
return new ModelReply(
|
||||
answer,
|
||||
confidence,
|
||||
requiresEscalation,
|
||||
rationale,
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
totalTokens);
|
||||
} catch (IOException ex) {
|
||||
log.warn("Failed to parse model JSON response, returning raw text", ex);
|
||||
return new ModelReply(
|
||||
raw,
|
||||
0.0D,
|
||||
true,
|
||||
"Unable to parse JSON response",
|
||||
promptTokens,
|
||||
completionTokens,
|
||||
totalTokens);
|
||||
}
|
||||
}
|
||||
|
||||
private record ModelReply(
|
||||
String answer,
|
||||
double confidence,
|
||||
boolean requiresEscalation,
|
||||
String rationale,
|
||||
long promptTokens,
|
||||
long completionTokens,
|
||||
long totalTokens) {}
|
||||
|
||||
private String sanitizeRemoteMessage(String message) {
|
||||
if (!StringUtils.hasText(message)) {
|
||||
return "unexpected provider error";
|
||||
}
|
||||
return message.replaceAll("(?i)api[-_ ]?key\\s*=[^\\s]+", "api-key=***");
|
||||
}
|
||||
|
||||
private long toLong(Integer value) {
|
||||
return value == null ? 0L : value.longValue();
|
||||
}
|
||||
|
||||
private List<ChatbotHistoryEntry> loadConversationHistory(String sessionId) {
|
||||
if (conversationStore == null || !StringUtils.hasText(sessionId)) {
|
||||
return List.of();
|
||||
}
|
||||
try {
|
||||
return conversationStore.getRecentTurns(sessionId, conversationStore.defaultWindow());
|
||||
} catch (RuntimeException ex) {
|
||||
log.debug("Conversation history unavailable: {}", ex.getMessage());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private String loadConversationSummary(String sessionId) {
|
||||
if (conversationStore == null || !StringUtils.hasText(sessionId)) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return conversationStore.loadSummary(sessionId);
|
||||
} catch (RuntimeException ex) {
|
||||
log.debug("Conversation summary unavailable: {}", ex.getMessage());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private void recordHistoryTurn(ChatbotSession session, String role, String content) {
|
||||
if (conversationStore == null
|
||||
|| session == null
|
||||
|| !StringUtils.hasText(session.getSessionId())
|
||||
|| !StringUtils.hasText(content)) {
|
||||
return;
|
||||
}
|
||||
String documentName =
|
||||
Optional.ofNullable(session.getMetadata())
|
||||
.map(meta -> meta.getOrDefault("documentName", ""))
|
||||
.orElse("");
|
||||
ChatbotHistoryEntry entry =
|
||||
conversationStore.createEntry(role, content, session.getDocumentId(), documentName);
|
||||
try {
|
||||
conversationStore.appendTurn(session.getSessionId(), entry);
|
||||
} catch (RuntimeException ex) {
|
||||
log.debug("Failed to persist chatbot conversation turn: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void summarizeConversation(ChatbotSettings settings, ChatbotSession session) {
|
||||
if (conversationStore == null
|
||||
|| session == null
|
||||
|| !StringUtils.hasText(session.getSessionId())) {
|
||||
return;
|
||||
}
|
||||
|
||||
int window = conversationStore.defaultWindow();
|
||||
long historySize = conversationStore.historyLength(session.getSessionId());
|
||||
if (historySize < Math.max(window * SUMMARY_TRIGGER_MULTIPLIER, window + 1)) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<ChatbotHistoryEntry> entries =
|
||||
conversationStore.getRecentTurns(
|
||||
session.getSessionId(), conversationStore.retentionWindow());
|
||||
if (entries.isEmpty() || entries.size() <= window) {
|
||||
return;
|
||||
}
|
||||
|
||||
int cutoff = entries.size() - window;
|
||||
List<ChatbotHistoryEntry> summarizable = entries.subList(0, cutoff);
|
||||
String existingSummary = loadConversationSummary(session.getSessionId());
|
||||
String updatedSummary = summarizeHistory(settings, session, summarizable, existingSummary);
|
||||
if (StringUtils.hasText(updatedSummary)) {
|
||||
try {
|
||||
conversationStore.storeSummary(session.getSessionId(), updatedSummary);
|
||||
conversationStore.trimHistory(session.getSessionId(), window);
|
||||
} catch (RuntimeException ex) {
|
||||
log.debug("Failed to persist chatbot summary: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String summarizeHistory(
|
||||
ChatbotSettings settings,
|
||||
ChatbotSession session,
|
||||
List<ChatbotHistoryEntry> entries,
|
||||
String existingSummary) {
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
return existingSummary;
|
||||
}
|
||||
String priorSummary =
|
||||
StringUtils.hasText(existingSummary)
|
||||
? existingSummary
|
||||
: "No previous summary available.";
|
||||
String transcript = buildSummaryTranscript(entries);
|
||||
if (!StringUtils.hasText(transcript)) {
|
||||
return existingSummary;
|
||||
}
|
||||
String systemPrompt =
|
||||
"You maintain a concise running summary of Stirling PDF Bot conversations. "
|
||||
+ "Capture user goals, referenced documents, and key conclusions in under 200 words.";
|
||||
String userPrompt =
|
||||
"Existing summary:\n"
|
||||
+ priorSummary
|
||||
+ "\n\nNew conversation turns:\n"
|
||||
+ transcript
|
||||
+ "\n\nRespond with the updated summary only.";
|
||||
Prompt prompt =
|
||||
new Prompt(
|
||||
List.of(new SystemMessage(systemPrompt), new UserMessage(userPrompt)),
|
||||
buildChatOptions(settings, settings.models().primary()));
|
||||
try {
|
||||
ChatResponse response = chatModel.call(prompt);
|
||||
return Optional.ofNullable(response)
|
||||
.map(ChatResponse::getResults)
|
||||
.filter(results -> !results.isEmpty())
|
||||
.map(results -> results.get(0).getOutput().getText())
|
||||
.map(String::trim)
|
||||
.filter(StringUtils::hasText)
|
||||
.orElse(existingSummary);
|
||||
} catch (RuntimeException ex) {
|
||||
log.debug("Conversation summarisation failed: {}", ex.getMessage());
|
||||
return existingSummary;
|
||||
}
|
||||
}
|
||||
|
||||
private String buildSummaryTranscript(List<ChatbotHistoryEntry> entries) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (ChatbotHistoryEntry entry : entries) {
|
||||
if (entry == null || !StringUtils.hasText(entry.content())) {
|
||||
continue;
|
||||
}
|
||||
if (builder.length() >= SUMMARY_TRANSCRIPT_MAX_CHARS) {
|
||||
builder.append("\n[conversation truncated]");
|
||||
break;
|
||||
}
|
||||
builder.append(entry.role()).append(": ").append(entry.content().trim());
|
||||
if (StringUtils.hasText(entry.documentName())) {
|
||||
builder.append(" (doc: ").append(entry.documentName()).append(")");
|
||||
}
|
||||
builder.append("\n");
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
private void enforceHistoryRetention(ChatbotSession session) {
|
||||
if (conversationStore == null
|
||||
|| session == null
|
||||
|| !StringUtils.hasText(session.getSessionId())) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
conversationStore.trimHistory(
|
||||
session.getSessionId(), conversationStore.retentionWindow());
|
||||
} catch (RuntimeException ex) {
|
||||
log.debug("Failed to enforce chatbot history retention: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
-187
@@ -1,187 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotHistoryEntry;
|
||||
|
||||
import redis.clients.jedis.JedisPooled;
|
||||
|
||||
/**
|
||||
* Lightweight Redis-backed conversation store that keeps a short rolling window and summary for
|
||||
* each chatbot session. This lays the groundwork for richer memory handling without yet impacting
|
||||
* the main conversation flow.
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class ChatbotConversationStore {
|
||||
|
||||
private static final String HISTORY_KEY = "chatbot:sessions:%s:history";
|
||||
private static final String SUMMARY_KEY = "chatbot:sessions:%s:summary";
|
||||
private static final Duration DEFAULT_TTL = Duration.ofHours(24);
|
||||
private static final int DEFAULT_WINDOW = 10;
|
||||
private static final int RETENTION_MULTIPLIER = 5;
|
||||
private static final int RETENTION_WINDOW = DEFAULT_WINDOW * RETENTION_MULTIPLIER;
|
||||
|
||||
private final JedisPooled jedis;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ChatbotConversationStore(
|
||||
ObjectProvider<JedisPooled> jedisProvider, ObjectMapper objectMapper) {
|
||||
this.jedis = jedisProvider.getIfAvailable();
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public void appendTurn(String sessionId, ChatbotHistoryEntry entry) {
|
||||
if (!redisReady() || !StringUtils.hasText(sessionId) || entry == null) {
|
||||
return;
|
||||
}
|
||||
execute(
|
||||
() -> {
|
||||
try {
|
||||
String payload = objectMapper.writeValueAsString(entry);
|
||||
String key = historyKey(sessionId);
|
||||
jedis.rpush(key, payload);
|
||||
jedis.expire(key, (int) DEFAULT_TTL.getSeconds());
|
||||
jedis.expire(summaryKey(sessionId), (int) DEFAULT_TTL.getSeconds());
|
||||
} catch (JsonProcessingException ex) {
|
||||
log.debug("Failed to serialise chatbot turn", ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public List<ChatbotHistoryEntry> getRecentTurns(String sessionId, int limit) {
|
||||
if (!redisReady() || !StringUtils.hasText(sessionId)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return execute(
|
||||
() -> {
|
||||
String key = historyKey(sessionId);
|
||||
long size = jedis.llen(key);
|
||||
if (size <= 0) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
long start = Math.max(0, size - Math.max(limit, 1));
|
||||
List<String> raw = jedis.lrange(key, start, size);
|
||||
if (CollectionUtils.isEmpty(raw)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<ChatbotHistoryEntry> entries = new ArrayList<>(raw.size());
|
||||
for (String chunk : raw) {
|
||||
try {
|
||||
entries.add(objectMapper.readValue(chunk, ChatbotHistoryEntry.class));
|
||||
} catch (JsonProcessingException ex) {
|
||||
log.debug("Ignoring malformed chatbot history payload", ex);
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
},
|
||||
Collections.emptyList());
|
||||
}
|
||||
|
||||
public void trimHistory(String sessionId, int retainEntries) {
|
||||
if (!redisReady() || !StringUtils.hasText(sessionId) || retainEntries <= 0) {
|
||||
return;
|
||||
}
|
||||
execute(
|
||||
() -> {
|
||||
String key = historyKey(sessionId);
|
||||
jedis.ltrim(key, -retainEntries, -1);
|
||||
});
|
||||
}
|
||||
|
||||
public void storeSummary(String sessionId, String summary) {
|
||||
if (!redisReady() || !StringUtils.hasText(sessionId)) {
|
||||
return;
|
||||
}
|
||||
execute(() -> jedis.setex(summaryKey(sessionId), (int) DEFAULT_TTL.getSeconds(), summary));
|
||||
}
|
||||
|
||||
public String loadSummary(String sessionId) {
|
||||
if (!redisReady() || !StringUtils.hasText(sessionId)) {
|
||||
return "";
|
||||
}
|
||||
return execute(() -> jedis.get(summaryKey(sessionId)), "");
|
||||
}
|
||||
|
||||
public void clear(String sessionId) {
|
||||
if (!redisReady() || !StringUtils.hasText(sessionId)) {
|
||||
return;
|
||||
}
|
||||
execute(
|
||||
() -> {
|
||||
jedis.del(historyKey(sessionId));
|
||||
jedis.del(summaryKey(sessionId));
|
||||
});
|
||||
}
|
||||
|
||||
public int defaultWindow() {
|
||||
return DEFAULT_WINDOW;
|
||||
}
|
||||
|
||||
public int retentionWindow() {
|
||||
return RETENTION_WINDOW;
|
||||
}
|
||||
|
||||
public long historyLength(String sessionId) {
|
||||
if (!redisReady() || !StringUtils.hasText(sessionId)) {
|
||||
return 0L;
|
||||
}
|
||||
return execute(() -> jedis.llen(historyKey(sessionId)), 0L);
|
||||
}
|
||||
|
||||
private boolean redisReady() {
|
||||
return jedis != null;
|
||||
}
|
||||
|
||||
private String historyKey(String sessionId) {
|
||||
return HISTORY_KEY.formatted(sessionId);
|
||||
}
|
||||
|
||||
private String summaryKey(String sessionId) {
|
||||
return SUMMARY_KEY.formatted(sessionId);
|
||||
}
|
||||
|
||||
private void execute(Runnable action) {
|
||||
if (!redisReady()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
action.run();
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("Redis conversation store unavailable: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T execute(Supplier<T> supplier, T fallback) {
|
||||
if (!redisReady()) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return supplier.get();
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("Redis conversation store unavailable: {}", ex.getMessage());
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/** Convenience factory to create entries for manual tests. */
|
||||
public ChatbotHistoryEntry createEntry(
|
||||
String role, String content, String documentId, String documentName) {
|
||||
return new ChatbotHistoryEntry(role, content, documentId, documentName, Instant.now());
|
||||
}
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium.ProFeatures;
|
||||
import stirling.software.common.model.ApplicationProperties.Premium.ProFeatures.Chatbot;
|
||||
|
||||
@Component
|
||||
public class ChatbotFeatureProperties {
|
||||
|
||||
private final ApplicationProperties applicationProperties;
|
||||
|
||||
public ChatbotFeatureProperties(ApplicationProperties applicationProperties) {
|
||||
this.applicationProperties = applicationProperties;
|
||||
}
|
||||
|
||||
public ChatbotSettings current() {
|
||||
Chatbot chatbot = resolveChatbot();
|
||||
ChatbotSettings.ModelSettings modelSettings =
|
||||
new ChatbotSettings.ModelSettings(
|
||||
resolveProvider(chatbot.getModels().getProvider()),
|
||||
chatbot.getModels().getPrimary(),
|
||||
chatbot.getModels().getFallback(),
|
||||
chatbot.getModels().getEmbedding(),
|
||||
chatbot.getModels().getTopP());
|
||||
return new ChatbotSettings(
|
||||
chatbot.isEnabled(),
|
||||
chatbot.isAlphaWarning(),
|
||||
chatbot.getMaxPromptCharacters(),
|
||||
chatbot.getMinConfidenceNano(),
|
||||
chatbot.isStreamingEnabled(),
|
||||
modelSettings,
|
||||
new ChatbotSettings.RagSettings(
|
||||
chatbot.getRag().getChunkSizeTokens(),
|
||||
chatbot.getRag().getChunkOverlapTokens(),
|
||||
chatbot.getRag().getTopK()),
|
||||
new ChatbotSettings.CacheSettings(
|
||||
chatbot.getCache().getTtlMinutes(),
|
||||
chatbot.getCache().getMaxEntries(),
|
||||
chatbot.getCache().getMaxDocumentCharacters()),
|
||||
new ChatbotSettings.OcrSettings(chatbot.getOcr().isEnabledByDefault()),
|
||||
new ChatbotSettings.AuditSettings(chatbot.getAudit().isEnabled()),
|
||||
new ChatbotSettings.UsageSettings(
|
||||
chatbot.getUsage().getPerUserMonthlyTokens(),
|
||||
chatbot.getUsage().getWarnAtRatio()));
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return current().enabled();
|
||||
}
|
||||
|
||||
private Chatbot resolveChatbot() {
|
||||
return Optional.ofNullable(applicationProperties)
|
||||
.map(ApplicationProperties::getPremium)
|
||||
.map(Premium::getProFeatures)
|
||||
.map(ProFeatures::getChatbot)
|
||||
.orElseGet(Chatbot::new);
|
||||
}
|
||||
|
||||
private ChatbotSettings.ModelProvider resolveProvider(String configuredProvider) {
|
||||
if (!StringUtils.hasText(configuredProvider)) {
|
||||
return ChatbotSettings.ModelProvider.OPENAI;
|
||||
}
|
||||
try {
|
||||
return ChatbotSettings.ModelProvider.valueOf(configuredProvider.trim().toUpperCase());
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return ChatbotSettings.ModelProvider.OPENAI;
|
||||
}
|
||||
}
|
||||
|
||||
public record ChatbotSettings(
|
||||
boolean enabled,
|
||||
boolean alphaWarning,
|
||||
long maxPromptCharacters,
|
||||
double minConfidenceNano,
|
||||
boolean streamingEnabled,
|
||||
ModelSettings models,
|
||||
RagSettings rag,
|
||||
CacheSettings cache,
|
||||
OcrSettings ocr,
|
||||
AuditSettings audit,
|
||||
UsageSettings usage) {
|
||||
|
||||
public record ModelSettings(
|
||||
ModelProvider provider,
|
||||
String primary,
|
||||
String fallback,
|
||||
String embedding,
|
||||
double topP) {}
|
||||
|
||||
public record RagSettings(int chunkSizeTokens, int chunkOverlapTokens, int topK) {}
|
||||
|
||||
public record CacheSettings(long ttlMinutes, long maxEntries, long maxDocumentCharacters) {}
|
||||
|
||||
public record OcrSettings(boolean enabledByDefault) {}
|
||||
|
||||
public record AuditSettings(boolean enabled) {}
|
||||
|
||||
public record UsageSettings(long perUserMonthlyTokens, double warnAtRatio) {}
|
||||
|
||||
public enum ModelProvider {
|
||||
OPENAI,
|
||||
OLLAMA
|
||||
}
|
||||
}
|
||||
}
|
||||
-172
@@ -1,172 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.vectorstore.VectorStore;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionStatus;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionCreateRequest;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.ChatbotSettings;
|
||||
import stirling.software.proprietary.service.chatbot.exception.ChatbotException;
|
||||
import stirling.software.proprietary.service.chatbot.exception.NoTextDetectedException;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class ChatbotIngestionService {
|
||||
|
||||
private final ChatbotCacheService cacheService;
|
||||
private final ChatbotSessionRegistry sessionRegistry;
|
||||
private final ChatbotFeatureProperties featureProperties;
|
||||
private final VectorStore vectorStore;
|
||||
private final ChatbotUsageService usageService;
|
||||
|
||||
public ChatbotSession ingest(ChatbotSessionCreateRequest request) {
|
||||
ChatbotSettings settings = featureProperties.current();
|
||||
if (!settings.enabled()) {
|
||||
throw new ChatbotException("Chatbot feature is disabled");
|
||||
}
|
||||
if (!request.isWarningsAccepted() && settings.alphaWarning()) {
|
||||
throw new ChatbotException("Alpha warning must be accepted before use");
|
||||
}
|
||||
if (!StringUtils.hasText(request.getText())) {
|
||||
throw new NoTextDetectedException(
|
||||
"No text detected in document payload. Images are currently unsupported – enable OCR to continue.");
|
||||
}
|
||||
|
||||
long characterLimit = cacheService.getMaxDocumentCharacters();
|
||||
long textCharacters = request.getText().length();
|
||||
if (textCharacters > characterLimit) {
|
||||
throw new ChatbotException(
|
||||
"Document text exceeds maximum allowed characters: " + characterLimit);
|
||||
}
|
||||
|
||||
String sessionId =
|
||||
StringUtils.hasText(request.getSessionId())
|
||||
? request.getSessionId()
|
||||
: ChatbotSession.randomSessionId();
|
||||
boolean imagesDetected = request.isImagesDetected();
|
||||
boolean ocrApplied = request.isOcrRequested();
|
||||
Map<String, String> metadata = new HashMap<>();
|
||||
if (request.getMetadata() != null) {
|
||||
metadata.putAll(request.getMetadata());
|
||||
}
|
||||
metadata.put("content.imagesDetected", Boolean.toString(imagesDetected));
|
||||
metadata.put("content.characterCount", String.valueOf(textCharacters));
|
||||
metadata.put(
|
||||
"content.extractionSource", ocrApplied ? "ocr-text-layer" : "embedded-text-layer");
|
||||
Map<String, String> immutableMetadata = Map.copyOf(metadata);
|
||||
|
||||
List<Document> documents =
|
||||
buildDocuments(
|
||||
sessionId, request.getDocumentId(), request.getText(), metadata, settings);
|
||||
try {
|
||||
vectorStore.add(documents);
|
||||
} catch (RuntimeException ex) {
|
||||
throw new ChatbotException(
|
||||
"Failed to index document content in vector store: "
|
||||
+ sanitizeRemoteMessage(ex.getMessage()),
|
||||
ex);
|
||||
}
|
||||
|
||||
String cacheKey =
|
||||
cacheService.register(
|
||||
sessionId,
|
||||
request.getDocumentId(),
|
||||
immutableMetadata,
|
||||
ocrApplied,
|
||||
imagesDetected,
|
||||
textCharacters);
|
||||
|
||||
long estimatedTokens = Math.max(1L, Math.round(textCharacters / 4.0));
|
||||
|
||||
ChatbotSession session =
|
||||
ChatbotSession.builder()
|
||||
.sessionId(sessionId)
|
||||
.documentId(request.getDocumentId())
|
||||
.userId(request.getUserId())
|
||||
.metadata(new ConcurrentHashMap<>(metadata))
|
||||
.ocrRequested(ocrApplied)
|
||||
.imageContentDetected(imagesDetected)
|
||||
.textCharacters(textCharacters)
|
||||
.estimatedTokens(estimatedTokens)
|
||||
.warningsAccepted(request.isWarningsAccepted())
|
||||
.alphaWarningRequired(settings.alphaWarning())
|
||||
.cacheKey(cacheKey)
|
||||
.createdAt(Instant.now())
|
||||
.status(ChatbotSessionStatus.READY)
|
||||
.build();
|
||||
session.setUsageSummary(
|
||||
usageService.registerIngestion(session.getUserId(), estimatedTokens));
|
||||
sessionRegistry.register(session);
|
||||
log.info(
|
||||
"Registered chatbot session {} for document {} with {} RAG chunks",
|
||||
sessionId,
|
||||
request.getDocumentId(),
|
||||
documents.size());
|
||||
return session;
|
||||
}
|
||||
|
||||
private List<Document> buildDocuments(
|
||||
String sessionId,
|
||||
String documentId,
|
||||
String text,
|
||||
Map<String, String> metadata,
|
||||
ChatbotSettings settings) {
|
||||
List<Document> documents = new ArrayList<>();
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return documents;
|
||||
}
|
||||
|
||||
int chunkChars = Math.max(512, settings.rag().chunkSizeTokens() * 4);
|
||||
int overlapChars = Math.max(64, settings.rag().chunkOverlapTokens() * 4);
|
||||
|
||||
int index = 0;
|
||||
int order = 0;
|
||||
while (index < text.length()) {
|
||||
int end = Math.min(text.length(), index + chunkChars);
|
||||
String chunk = text.substring(index, end).trim();
|
||||
if (!chunk.isEmpty()) {
|
||||
Document document = new Document(chunk);
|
||||
document.getMetadata().putAll(metadata);
|
||||
document.getMetadata().put("sessionId", sessionId);
|
||||
document.getMetadata().put("documentId", documentId);
|
||||
document.getMetadata().put("chunkOrder", Integer.toString(order));
|
||||
documents.add(document);
|
||||
order++;
|
||||
}
|
||||
if (end == text.length()) {
|
||||
break;
|
||||
}
|
||||
int nextIndex = end - overlapChars;
|
||||
if (nextIndex <= index) {
|
||||
nextIndex = end;
|
||||
}
|
||||
index = nextIndex;
|
||||
}
|
||||
|
||||
if (documents.isEmpty()) {
|
||||
throw new ChatbotException("Unable to split document text into searchable chunks");
|
||||
}
|
||||
return documents;
|
||||
}
|
||||
|
||||
private String sanitizeRemoteMessage(String message) {
|
||||
if (!StringUtils.hasText(message)) {
|
||||
return "unexpected provider error";
|
||||
}
|
||||
return message.replaceAll("(?i)api[-_ ]?key\\s*=[^\\s]+", "api-key=***");
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.vectorstore.VectorStore;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ChatbotMemoryService {
|
||||
|
||||
private final VectorStore vectorStore;
|
||||
|
||||
public void recordTurn(ChatbotSession session, String prompt, String answer) {
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
if (!StringUtils.hasText(prompt) && !StringUtils.hasText(answer)) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> metadata = new HashMap<>();
|
||||
metadata.put("sessionId", session.getSessionId());
|
||||
metadata.put("documentId", session.getDocumentId());
|
||||
metadata.put("turnType", "conversation");
|
||||
metadata.put("turnTimestamp", Instant.now().toString());
|
||||
metadata.put("userId", session.getUserId());
|
||||
|
||||
StringBuilder contentBuilder = new StringBuilder();
|
||||
if (StringUtils.hasText(prompt)) {
|
||||
contentBuilder.append("User: ").append(prompt.trim()).append("\n");
|
||||
}
|
||||
if (StringUtils.hasText(answer)) {
|
||||
contentBuilder.append("Assistant: ").append(answer.trim());
|
||||
}
|
||||
try {
|
||||
vectorStore.add(List.of(new Document(contentBuilder.toString(), metadata)));
|
||||
} catch (RuntimeException ex) {
|
||||
log.warn("Failed to persist chatbot conversation turn: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
-94
@@ -1,94 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.vectorstore.SearchRequest;
|
||||
import org.springframework.ai.vectorstore.VectorStore;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.ChatbotSettings;
|
||||
import stirling.software.proprietary.service.chatbot.exception.ChatbotException;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class ChatbotRetrievalService {
|
||||
|
||||
private final ChatbotCacheService cacheService;
|
||||
private final VectorStore vectorStore;
|
||||
private final Cache<String, List<Document>> retrievalCache =
|
||||
Caffeine.newBuilder().maximumSize(200).expireAfterWrite(30, TimeUnit.SECONDS).build();
|
||||
|
||||
public List<Document> retrieveTopK(String sessionId, String query, ChatbotSettings settings) {
|
||||
cacheService
|
||||
.resolveBySessionId(sessionId)
|
||||
.orElseThrow(() -> new ChatbotException("Unknown chatbot session"));
|
||||
|
||||
int topK = Math.max(settings.rag().topK(), 1);
|
||||
String sanitizedQuery = StringUtils.hasText(query) ? query : "";
|
||||
String filterExpression = "metadata.sessionId == '" + escape(sessionId) + "'";
|
||||
String cacheKey = cacheKey(sessionId, sanitizedQuery, topK);
|
||||
List<Document> cached = retrievalCache.getIfPresent(cacheKey);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
SearchRequest searchRequest =
|
||||
SearchRequest.builder()
|
||||
.query(sanitizedQuery)
|
||||
.topK(topK)
|
||||
.filterExpression(filterExpression)
|
||||
.similarityThreshold(0.7f)
|
||||
.build();
|
||||
List<Document> results;
|
||||
|
||||
try {
|
||||
results = vectorStore.similaritySearch(searchRequest);
|
||||
} catch (RuntimeException ex) {
|
||||
throw new ChatbotException(
|
||||
"Failed to perform vector similarity search: "
|
||||
+ sanitizeRemoteMessage(ex.getMessage()),
|
||||
ex);
|
||||
}
|
||||
results =
|
||||
results.stream()
|
||||
.filter(
|
||||
doc ->
|
||||
sessionId.equals(
|
||||
doc.getMetadata().getOrDefault("sessionId", "")))
|
||||
.limit(topK)
|
||||
.toList();
|
||||
if (results.isEmpty()) {
|
||||
log.warn("No context available for chatbot session {}", sessionId);
|
||||
}
|
||||
|
||||
List<Document> immutableResults = List.copyOf(results);
|
||||
retrievalCache.put(cacheKey, immutableResults);
|
||||
return immutableResults;
|
||||
}
|
||||
|
||||
private String sanitizeRemoteMessage(String message) {
|
||||
if (!StringUtils.hasText(message)) {
|
||||
return "unexpected provider error";
|
||||
}
|
||||
return message.replaceAll("(?i)api[-_ ]?key\\s*=[^\\s]+", "api-key=***");
|
||||
}
|
||||
|
||||
private String escape(String value) {
|
||||
return value.replace("'", "\\'");
|
||||
}
|
||||
|
||||
private String cacheKey(String sessionId, String query, int topK) {
|
||||
return sessionId + "::" + Objects.hash(query, topK);
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotQueryRequest;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotResponse;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionCreateRequest;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.service.AuditService;
|
||||
import stirling.software.proprietary.service.chatbot.exception.ChatbotException;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class ChatbotService {
|
||||
|
||||
private final ChatbotIngestionService ingestionService;
|
||||
private final ChatbotConversationService conversationService;
|
||||
private final ChatbotSessionRegistry sessionRegistry;
|
||||
private final ChatbotCacheService cacheService;
|
||||
private final ChatbotFeatureProperties featureProperties;
|
||||
private final AuditService auditService;
|
||||
private final UserService userService;
|
||||
|
||||
public ChatbotSession createSession(ChatbotSessionCreateRequest request) {
|
||||
if (!StringUtils.hasText(request.getUserId())) {
|
||||
request.setUserId(userService.getCurrentUsername());
|
||||
}
|
||||
ChatbotSession session = ingestionService.ingest(request);
|
||||
log.debug("Chatbot session {} initialised", session.getSessionId());
|
||||
audit(
|
||||
"CHATBOT_SESSION_CREATED",
|
||||
session.getSessionId(),
|
||||
Map.of(
|
||||
"documentId", session.getDocumentId(),
|
||||
"ocrRequested", session.isOcrRequested(),
|
||||
"imagesDetected", session.isImageContentDetected(),
|
||||
"textCharacters", session.getTextCharacters()));
|
||||
return session;
|
||||
}
|
||||
|
||||
public ChatbotResponse ask(ChatbotQueryRequest request) {
|
||||
ChatbotResponse response = conversationService.handleQuery(request);
|
||||
audit(
|
||||
"CHATBOT_QUERY",
|
||||
request.getSessionId(),
|
||||
Map.of(
|
||||
"modelUsed", response.getModelUsed(),
|
||||
"escalated", response.isEscalated(),
|
||||
"confidence", response.getConfidence()));
|
||||
return response;
|
||||
}
|
||||
|
||||
public void close(String sessionId) {
|
||||
sessionRegistry
|
||||
.findById(sessionId)
|
||||
.orElseThrow(() -> new ChatbotException("Session not found for closure"));
|
||||
sessionRegistry.remove(sessionId);
|
||||
cacheService.invalidateSession(sessionId);
|
||||
audit("CHATBOT_SESSION_CLOSED", sessionId, Map.of());
|
||||
log.debug("Chatbot session {} closed", sessionId);
|
||||
}
|
||||
|
||||
private void audit(String action, String sessionId, Map<String, Object> data) {
|
||||
if (!featureProperties.current().audit().enabled()) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> payload = new HashMap<>(data == null ? Map.of() : data);
|
||||
payload.put("sessionId", sessionId);
|
||||
auditService.audit(stirling.software.proprietary.audit.AuditEventType.PDF_PROCESS, payload);
|
||||
}
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
|
||||
@Component
|
||||
public class ChatbotSessionRegistry {
|
||||
|
||||
private final Map<String, ChatbotSession> sessionStore = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> documentToSession = new ConcurrentHashMap<>();
|
||||
|
||||
public void register(ChatbotSession session) {
|
||||
sessionStore.put(session.getSessionId(), session);
|
||||
if (session.getDocumentId() != null) {
|
||||
documentToSession.put(session.getDocumentId(), session.getSessionId());
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<ChatbotSession> findById(String sessionId) {
|
||||
return Optional.ofNullable(sessionStore.get(sessionId));
|
||||
}
|
||||
|
||||
public void remove(String sessionId) {
|
||||
Optional.ofNullable(sessionStore.remove(sessionId))
|
||||
.map(ChatbotSession::getDocumentId)
|
||||
.ifPresent(documentToSession::remove);
|
||||
}
|
||||
|
||||
public Optional<ChatbotSession> findByDocumentId(String documentId) {
|
||||
return Optional.ofNullable(documentToSession.get(documentId)).flatMap(this::findById);
|
||||
}
|
||||
|
||||
public void removeByDocumentId(String documentId) {
|
||||
Optional.ofNullable(documentToSession.remove(documentId)).ifPresent(sessionStore::remove);
|
||||
}
|
||||
|
||||
public Map<String, ChatbotSession> snapshot() {
|
||||
return Map.copyOf(sessionStore);
|
||||
}
|
||||
}
|
||||
-275
@@ -1,275 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.springframework.ai.document.Document;
|
||||
import org.springframework.ai.vectorstore.VectorStore;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotChunkRequest;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionResponse;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionStatus;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotUsageSummary;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.ChatbotSettings;
|
||||
import stirling.software.proprietary.service.chatbot.exception.ChatbotException;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class ChatbotStreamingIngestionService {
|
||||
|
||||
private static final int MAX_CHUNKS_PER_WINDOW = 25;
|
||||
private static final long RATE_WINDOW_MS = 2_000L;
|
||||
private static final long STALE_THRESHOLD_MS = Duration.ofMinutes(10).toMillis();
|
||||
private static final int MAX_SUMMARY_CHARS = 4_000;
|
||||
private static final int SNIPPET_CHARS = 320;
|
||||
|
||||
private final ChatbotFeatureProperties featureProperties;
|
||||
private final ChatbotSessionRegistry sessionRegistry;
|
||||
private final ChatbotCacheService cacheService;
|
||||
private final VectorStore vectorStore;
|
||||
private final ChatbotUsageService usageService;
|
||||
private final ConcurrentHashMap<String, IngestionTracker> trackers =
|
||||
new ConcurrentHashMap<>();
|
||||
private final ChatbotUsageService usageService;
|
||||
|
||||
public ChatbotSessionResponse ingestChunk(ChatbotChunkRequest request) {
|
||||
ChatbotSettings settings = featureProperties.current();
|
||||
if (!settings.streamingEnabled()) {
|
||||
throw new ChatbotException("Streaming ingestion is disabled in this environment.");
|
||||
}
|
||||
if (!StringUtils.hasText(request.getChunkText())) {
|
||||
throw new ChatbotException("Chunk payload must contain text.");
|
||||
}
|
||||
ChatbotSession session = resolveSession(request);
|
||||
processChunk(session, request);
|
||||
if (request.isFinalChunk()) {
|
||||
finalizeSession(session);
|
||||
}
|
||||
return buildResponse(session, settings);
|
||||
}
|
||||
|
||||
private ChatbotSession resolveSession(ChatbotChunkRequest request) {
|
||||
if (StringUtils.hasText(request.getSessionId())) {
|
||||
return sessionRegistry
|
||||
.findById(request.getSessionId())
|
||||
.orElseThrow(() -> new ChatbotException("Unknown chatbot session"));
|
||||
}
|
||||
if (!StringUtils.hasText(request.getDocumentId())) {
|
||||
throw new ChatbotException("Document ID is required for the first chunk.");
|
||||
}
|
||||
String sessionId = UUID.randomUUID().toString();
|
||||
Map<String, String> metadata =
|
||||
request.getMetadata() == null
|
||||
? new ConcurrentHashMap<>()
|
||||
: new ConcurrentHashMap<>(request.getMetadata());
|
||||
ChatbotSession session =
|
||||
ChatbotSession.builder()
|
||||
.sessionId(sessionId)
|
||||
.documentId(request.getDocumentId())
|
||||
.userId(request.getUserId())
|
||||
.metadata(metadata)
|
||||
.ocrRequested(request.isOcrRequested())
|
||||
.imageContentDetected(request.isImagesDetected())
|
||||
.warningsAccepted(true)
|
||||
.alphaWarningRequired(featureProperties.current().alphaWarning())
|
||||
.textCharacters(0L)
|
||||
.estimatedTokens(0L)
|
||||
.createdAt(Instant.now())
|
||||
.status(ChatbotSessionStatus.PROCESSING)
|
||||
.build();
|
||||
sessionRegistry.register(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
private void processChunk(ChatbotSession session, ChatbotChunkRequest request) {
|
||||
ChatbotSessionStatus status = session.getStatus();
|
||||
if (status == ChatbotSessionStatus.READY && !request.isFinalChunk()) {
|
||||
throw new ChatbotException("Session already finalised, cannot accept more chunks.");
|
||||
}
|
||||
|
||||
IngestionTracker tracker = trackerFor(session.getSessionId());
|
||||
tracker.record(request.getChunkText());
|
||||
|
||||
Document chunkDocument = new Document(request.getChunkText());
|
||||
Map<String, Object> docMetadata = chunkDocument.getMetadata();
|
||||
docMetadata.putAll(session.getMetadata());
|
||||
docMetadata.put("sessionId", session.getSessionId());
|
||||
docMetadata.put("documentId", session.getDocumentId());
|
||||
docMetadata.put("chunkOrder", Integer.toString(request.getChunkOrder()));
|
||||
docMetadata.put("chunkSnippet", tracker.lastSnippet());
|
||||
|
||||
try {
|
||||
vectorStore.add(List.of(chunkDocument));
|
||||
} catch (RuntimeException ex) {
|
||||
throw new ChatbotException(
|
||||
"Failed to index streamed chunk: " + sanitize(ex.getMessage()), ex);
|
||||
}
|
||||
|
||||
session.setTextCharacters(
|
||||
session.getTextCharacters() + request.getChunkText().length());
|
||||
session.setEstimatedTokens(Math.max(1L, Math.round(session.getTextCharacters() / 4.0)));
|
||||
|
||||
if (request.getMetadata() != null && !request.getMetadata().isEmpty()) {
|
||||
session.getMetadata().putAll(request.getMetadata());
|
||||
}
|
||||
session.setImageContentDetected(
|
||||
session.isImageContentDetected() || request.isImagesDetected());
|
||||
session.setOcrRequested(session.isOcrRequested() || request.isOcrRequested());
|
||||
session.getMetadata().put("content.summary", tracker.summary());
|
||||
}
|
||||
|
||||
private void finalizeSession(ChatbotSession session) {
|
||||
session.setStatus(ChatbotSessionStatus.READY);
|
||||
if (!StringUtils.hasText(session.getCacheKey())) {
|
||||
String cacheKey =
|
||||
cacheService.register(
|
||||
session.getSessionId(),
|
||||
session.getDocumentId(),
|
||||
new HashMap<>(session.getMetadata()),
|
||||
session.isOcrRequested(),
|
||||
session.isImageContentDetected(),
|
||||
session.getTextCharacters());
|
||||
session.setCacheKey(cacheKey);
|
||||
}
|
||||
session.setUsageSummary(
|
||||
usageService.registerIngestion(
|
||||
session.getUserId(), session.getEstimatedTokens()));
|
||||
trackers.remove(session.getSessionId());
|
||||
}
|
||||
|
||||
private ChatbotSessionResponse buildResponse(
|
||||
ChatbotSession session, ChatbotSettings settings) {
|
||||
return ChatbotSessionResponse.builder()
|
||||
.sessionId(session.getSessionId())
|
||||
.documentId(session.getDocumentId())
|
||||
.alphaWarning(settings.alphaWarning())
|
||||
.ocrRequested(session.isOcrRequested())
|
||||
.imageContentDetected(session.isImageContentDetected())
|
||||
.textCharacters(session.getTextCharacters())
|
||||
.estimatedTokens(session.getEstimatedTokens())
|
||||
.createdAt(session.getCreatedAt())
|
||||
.maxCachedCharacters(cacheService.getMaxDocumentCharacters())
|
||||
.warnings(streamingWarnings(session))
|
||||
.metadata(new HashMap<>(session.getMetadata()))
|
||||
.usageSummary(session.getUsageSummary())
|
||||
.status(session.getStatus())
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<String> streamingWarnings(ChatbotSession session) {
|
||||
List<String> warnings = new ArrayList<>();
|
||||
if (session.isImageContentDetected()) {
|
||||
warnings.add("Image content detected – images are currently ignored.");
|
||||
}
|
||||
if (session.isOcrRequested()) {
|
||||
warnings.add("OCR was requested for this session.");
|
||||
}
|
||||
return warnings;
|
||||
}
|
||||
|
||||
private String sanitize(String message) {
|
||||
if (!StringUtils.hasText(message)) {
|
||||
return "unexpected error";
|
||||
}
|
||||
return message.replaceAll("(?i)api[-_ ]?key\\s*=[^\\s]+", "api-key=***");
|
||||
}
|
||||
|
||||
private IngestionTracker trackerFor(String sessionId) {
|
||||
return trackers.computeIfAbsent(sessionId, id -> new IngestionTracker());
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${chatbot.streaming.cleanup-interval:300000}")
|
||||
public void cleanupStaleSessions() {
|
||||
if (!featureProperties.current().streamingEnabled()) {
|
||||
return;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
trackers.forEach(
|
||||
(sessionId, tracker) -> {
|
||||
if (now - tracker.lastUpdated() > STALE_THRESHOLD_MS) {
|
||||
trackers.remove(sessionId);
|
||||
sessionRegistry.remove(sessionId);
|
||||
cacheService.invalidateSession(sessionId);
|
||||
log.warn(
|
||||
"Streaming session {} cleaned up after {} ms of inactivity",
|
||||
sessionId,
|
||||
now - tracker.lastUpdated());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private final class IngestionTracker {
|
||||
|
||||
private long windowStart = System.currentTimeMillis();
|
||||
private int chunksInWindow = 0;
|
||||
private long lastUpdated = System.currentTimeMillis();
|
||||
private final StringBuilder summaryBuilder = new StringBuilder();
|
||||
private String lastSnippet = "";
|
||||
|
||||
synchronized void record(String chunkText) {
|
||||
long now = System.currentTimeMillis();
|
||||
lastUpdated = now;
|
||||
if (now - windowStart > RATE_WINDOW_MS) {
|
||||
windowStart = now;
|
||||
chunksInWindow = 0;
|
||||
}
|
||||
if (chunksInWindow >= MAX_CHUNKS_PER_WINDOW) {
|
||||
throw new ChatbotException(
|
||||
"Too many chunk uploads in a short period. Please slow down.");
|
||||
}
|
||||
chunksInWindow++;
|
||||
lastSnippet = snippet(chunkText);
|
||||
appendSummary(lastSnippet);
|
||||
}
|
||||
|
||||
private void appendSummary(String snippet) {
|
||||
if (!StringUtils.hasText(snippet)) {
|
||||
return;
|
||||
}
|
||||
if (summaryBuilder.length() >= MAX_SUMMARY_CHARS) {
|
||||
return;
|
||||
}
|
||||
summaryBuilder.append(snippet);
|
||||
if (summaryBuilder.length() > MAX_SUMMARY_CHARS) {
|
||||
summaryBuilder.setLength(MAX_SUMMARY_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
String summary() {
|
||||
return summaryBuilder.toString();
|
||||
}
|
||||
|
||||
long lastUpdated() {
|
||||
return lastUpdated;
|
||||
}
|
||||
|
||||
String lastSnippet() {
|
||||
return lastSnippet;
|
||||
}
|
||||
|
||||
private String snippet(String text) {
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return "";
|
||||
}
|
||||
String normalized = text.replaceAll("\\s+", " ").trim();
|
||||
if (normalized.length() > SNIPPET_CHARS) {
|
||||
return normalized.substring(0, SNIPPET_CHARS - 3) + "...";
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import java.time.YearMonth;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotUsageSummary;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.ChatbotSettings;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class ChatbotUsageService {
|
||||
|
||||
private final ChatbotFeatureProperties featureProperties;
|
||||
|
||||
private final Map<String, UsageWindow> usageByUser = new ConcurrentHashMap<>();
|
||||
|
||||
public ChatbotUsageSummary registerIngestion(String userId, long estimatedTokens) {
|
||||
return incrementUsage(userId, Math.max(estimatedTokens, 0L));
|
||||
}
|
||||
|
||||
public ChatbotUsageSummary registerGeneration(
|
||||
String userId, long promptTokens, long completionTokens) {
|
||||
long total = Math.max(promptTokens + completionTokens, 0L);
|
||||
return incrementUsage(userId, total);
|
||||
}
|
||||
|
||||
public ChatbotUsageSummary currentUsage(String userId) {
|
||||
String key = normalizeUserId(userId);
|
||||
UsageWindow window = usageByUser.get(key);
|
||||
if (window == null) {
|
||||
return buildSummary(key, 0L, 0L);
|
||||
}
|
||||
return buildSummary(key, window.tokens.get(), 0L);
|
||||
}
|
||||
|
||||
private ChatbotUsageSummary incrementUsage(String userId, long deltaTokens) {
|
||||
String key = normalizeUserId(userId);
|
||||
YearMonth now = YearMonth.now(ZoneOffset.UTC);
|
||||
UsageWindow window =
|
||||
usageByUser.compute(
|
||||
key,
|
||||
(ignored, existing) -> {
|
||||
if (existing == null || !existing.window.equals(now)) {
|
||||
existing = new UsageWindow(now);
|
||||
}
|
||||
if (deltaTokens > 0) {
|
||||
existing.tokens.addAndGet(deltaTokens);
|
||||
}
|
||||
return existing;
|
||||
});
|
||||
return buildSummary(key, window.tokens.get(), deltaTokens);
|
||||
}
|
||||
|
||||
private ChatbotUsageSummary buildSummary(String userKey, long consumed, long deltaTokens) {
|
||||
ChatbotSettings settings = featureProperties.current();
|
||||
long allocation = Math.max(settings.usage().perUserMonthlyTokens(), 1L);
|
||||
double ratio = allocation == 0 ? 1.0 : (double) consumed / allocation;
|
||||
long remaining = Math.max(allocation - consumed, 0L);
|
||||
boolean limitExceeded = consumed > allocation;
|
||||
boolean nearingLimit = ratio >= settings.usage().warnAtRatio();
|
||||
return ChatbotUsageSummary.builder()
|
||||
.allocatedTokens(allocation)
|
||||
.consumedTokens(consumed)
|
||||
.remainingTokens(remaining)
|
||||
.usageRatio(Math.min(ratio, 1.0))
|
||||
.nearingLimit(nearingLimit)
|
||||
.limitExceeded(limitExceeded)
|
||||
.lastIncrementTokens(deltaTokens)
|
||||
.window(currentWindowDescription(userKey))
|
||||
.build();
|
||||
}
|
||||
|
||||
private String currentWindowDescription(String userKey) {
|
||||
UsageWindow window = usageByUser.get(userKey);
|
||||
if (window == null) {
|
||||
return YearMonth.now(ZoneOffset.UTC).toString();
|
||||
}
|
||||
return window.window.toString();
|
||||
}
|
||||
|
||||
private String normalizeUserId(String userId) {
|
||||
if (!StringUtils.hasText(userId)) {
|
||||
return "anonymous";
|
||||
}
|
||||
return userId.trim().toLowerCase();
|
||||
}
|
||||
|
||||
private static final class UsageWindow {
|
||||
private final YearMonth window;
|
||||
private final AtomicLong tokens = new AtomicLong();
|
||||
|
||||
private UsageWindow(YearMonth window) {
|
||||
this.window = window;
|
||||
}
|
||||
}
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot.exception;
|
||||
|
||||
public class ChatbotException extends RuntimeException {
|
||||
|
||||
public ChatbotException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public ChatbotException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot.exception;
|
||||
|
||||
public class NoTextDetectedException extends ChatbotException {
|
||||
|
||||
public NoTextDetectedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
# Spring AI OpenAI Configuration
|
||||
# Uses GPT-5-nano as primary model and GPT-5-mini as fallback (configured in settings.yml)
|
||||
spring.ai.openai.enabled=true
|
||||
#spring.ai.openai.api-key=# todo <API-KEY-HERE>
|
||||
spring.ai.openai.base-url=https://api.openai.com
|
||||
spring.ai.openai.chat.enabled=true
|
||||
spring.ai.openai.chat.options.model=gpt-5-nano
|
||||
# Note: Some models only support default temperature value of 1.0
|
||||
spring.ai.openai.chat.options.temperature=1.0
|
||||
# For newer models, use max-completion-tokens instead of max-tokens
|
||||
spring.ai.openai.chat.options.max-completion-tokens=4000
|
||||
spring.ai.openai.embedding.enabled=true
|
||||
spring.ai.openai.embedding.options.model=text-embedding-ada-002
|
||||
# Increase timeout for OpenAI API calls (default is 10 seconds)
|
||||
spring.ai.openai.chat.options.connection-timeout=60s
|
||||
spring.ai.openai.chat.options.read-timeout=60s
|
||||
spring.ai.openai.embedding.options.connection-timeout=60s
|
||||
spring.ai.openai.embedding.options.read-timeout=60s
|
||||
|
||||
# Spring AI Ollama Configuration (disabled to avoid bean conflicts)
|
||||
spring.ai.ollama.enabled=false
|
||||
spring.ai.ollama.base-url=http://localhost:11434
|
||||
spring.ai.ollama.chat.enabled=false
|
||||
spring.ai.ollama.chat.options.model=llama3
|
||||
spring.ai.ollama.chat.options.temperature=1.0
|
||||
spring.ai.ollama.embedding.enabled=false
|
||||
spring.ai.ollama.embedding.options.model=nomic-embed-text
|
||||
|
||||
spring.data.redis.host=localhost
|
||||
spring.data.redis.port=6379
|
||||
spring.data.redis.password=
|
||||
spring.data.redis.timeout=60000
|
||||
spring.data.redis.ssl.enabled=false
|
||||
|
||||
+69
@@ -2,6 +2,9 @@ package stirling.software.proprietary.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
@@ -198,4 +201,70 @@ class UserLicenseSettingsServiceTest {
|
||||
|
||||
assertEquals(5, result, "Should fall back to default 5 users if grandfathered is 0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void grandfatherExistingOAuthUsers_runsOnlyWhenNoneGrandfathered() {
|
||||
// With grandfatheredCount == 0, should run grandfathering for all users
|
||||
when(userService.countOAuthUsers()).thenReturn(10L);
|
||||
when(userService.countGrandfatheredOAuthUsers()).thenReturn(0L);
|
||||
when(userService.grandfatherAllOAuthUsers()).thenReturn(10);
|
||||
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(0);
|
||||
|
||||
service.grandfatherExistingOAuthUsers();
|
||||
|
||||
verify(userService, times(1)).grandfatherAllOAuthUsers();
|
||||
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
void grandfatherExistingOAuthUsers_skipsMainButRunsPendingWhenSomeAlreadyGrandfathered() {
|
||||
// V2→V2.1 upgrade: some users already grandfathered, but pending users need to be checked
|
||||
when(userService.countOAuthUsers()).thenReturn(10L);
|
||||
when(userService.countGrandfatheredOAuthUsers()).thenReturn(4L);
|
||||
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(2);
|
||||
|
||||
service.grandfatherExistingOAuthUsers();
|
||||
|
||||
verify(userService, never()).grandfatherAllOAuthUsers();
|
||||
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
void grandfatherExistingOAuthUsers_stillChecksPendingWhenAllUsersGrandfathered() {
|
||||
// All active users grandfathered, but still check for pending users
|
||||
when(userService.countOAuthUsers()).thenReturn(10L);
|
||||
when(userService.countGrandfatheredOAuthUsers()).thenReturn(10L);
|
||||
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(0);
|
||||
|
||||
service.grandfatherExistingOAuthUsers();
|
||||
|
||||
verify(userService, never()).grandfatherAllOAuthUsers();
|
||||
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
void grandfatherExistingOAuthUsers_skipsWhenNoOAuthUsers() {
|
||||
when(userService.countOAuthUsers()).thenReturn(0L);
|
||||
when(userService.countGrandfatheredOAuthUsers()).thenReturn(0L);
|
||||
|
||||
service.grandfatherExistingOAuthUsers();
|
||||
|
||||
verify(userService, never()).grandfatherAllOAuthUsers();
|
||||
verify(userService, never()).grandfatherPendingSsoUsersWithoutSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
void grandfatherExistingOAuthUsers_grandfathersPendingUsersOnFirstRun() {
|
||||
// Pending users (invited but never logged in) should be grandfathered
|
||||
// during the initial grandfathering run (when grandfatheredCount == 0)
|
||||
when(userService.countOAuthUsers()).thenReturn(5L);
|
||||
when(userService.countGrandfatheredOAuthUsers()).thenReturn(0L);
|
||||
when(userService.grandfatherAllOAuthUsers()).thenReturn(5);
|
||||
when(userService.grandfatherPendingSsoUsersWithoutSession()).thenReturn(3);
|
||||
|
||||
service.grandfatherExistingOAuthUsers();
|
||||
|
||||
verify(userService, times(1)).grandfatherAllOAuthUsers();
|
||||
verify(userService, times(1)).grandfatherPendingSsoUsersWithoutSession();
|
||||
}
|
||||
}
|
||||
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotDocumentCacheEntry;
|
||||
|
||||
class ChatbotCacheServiceTest {
|
||||
|
||||
private ApplicationProperties properties;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
properties = new ApplicationProperties();
|
||||
ApplicationProperties.Premium premium = new ApplicationProperties.Premium();
|
||||
ApplicationProperties.Premium.ProFeatures pro =
|
||||
new ApplicationProperties.Premium.ProFeatures();
|
||||
ApplicationProperties.Premium.ProFeatures.Chatbot chatbot =
|
||||
new ApplicationProperties.Premium.ProFeatures.Chatbot();
|
||||
chatbot.setEnabled(true);
|
||||
chatbot.getCache().setMaxDocumentCharacters(50);
|
||||
chatbot.getCache().setMaxEntries(10);
|
||||
chatbot.getCache().setTtlMinutes(60);
|
||||
pro.setChatbot(chatbot);
|
||||
premium.setProFeatures(pro);
|
||||
properties.setPremium(premium);
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerAndResolveSession() {
|
||||
ChatbotCacheService cacheService = new ChatbotCacheService(properties);
|
||||
String cacheKey =
|
||||
cacheService.register(
|
||||
"session1",
|
||||
"doc1",
|
||||
Map.of("title", "Sample"),
|
||||
false,
|
||||
false,
|
||||
"hello world".length());
|
||||
assertTrue(cacheService.resolveBySessionId("session1").isPresent());
|
||||
ChatbotDocumentCacheEntry entry = cacheService.resolveByCacheKey(cacheKey).orElseThrow();
|
||||
assertEquals("doc1", entry.getDocumentId());
|
||||
assertEquals("Sample", entry.getMetadata().get("title"));
|
||||
assertEquals("hello world".length(), entry.getTextCharacters());
|
||||
assertTrue(!entry.isImageContentDetected());
|
||||
}
|
||||
}
|
||||
-143
@@ -1,143 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.ai.chat.messages.AssistantMessage;
|
||||
import org.springframework.ai.chat.model.ChatModel;
|
||||
import org.springframework.ai.chat.model.ChatResponse;
|
||||
import org.springframework.ai.chat.model.Generation;
|
||||
import org.springframework.ai.chat.prompt.Prompt;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotHistoryEntry;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ChatbotConversationServiceTest {
|
||||
|
||||
@Mock private ChatModel chatModel;
|
||||
@Mock private ChatbotSessionRegistry sessionRegistry;
|
||||
@Mock private ChatbotCacheService cacheService;
|
||||
@Mock private ChatbotFeatureProperties featureProperties;
|
||||
@Mock private ChatbotRetrievalService retrievalService;
|
||||
@Mock private ChatbotContextCompressor contextCompressor;
|
||||
@Mock private ChatbotMemoryService memoryService;
|
||||
@Mock private ChatbotUsageService usageService;
|
||||
@Mock private ChatbotConversationStore conversationStore;
|
||||
|
||||
private ChatbotConversationService conversationService;
|
||||
private ChatbotSettings defaultSettings;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
conversationService =
|
||||
new ChatbotConversationService(
|
||||
chatModel,
|
||||
sessionRegistry,
|
||||
cacheService,
|
||||
featureProperties,
|
||||
retrievalService,
|
||||
contextCompressor,
|
||||
memoryService,
|
||||
usageService,
|
||||
conversationStore,
|
||||
new ObjectMapper());
|
||||
|
||||
defaultSettings =
|
||||
new ChatbotSettings(
|
||||
true,
|
||||
true,
|
||||
4000,
|
||||
0.65D,
|
||||
false,
|
||||
new ChatbotSettings.ModelSettings(
|
||||
ChatbotSettings.ModelProvider.OPENAI,
|
||||
"gpt-5-nano",
|
||||
"gpt-5-mini",
|
||||
"embed",
|
||||
0.95D),
|
||||
new ChatbotSettings.RagSettings(512, 128, 4),
|
||||
new ChatbotSettings.CacheSettings(60, 10, 1000),
|
||||
new ChatbotSettings.OcrSettings(false),
|
||||
new ChatbotSettings.AuditSettings(false),
|
||||
new ChatbotSettings.UsageSettings(100_000L, 0.7D));
|
||||
}
|
||||
|
||||
@Test
|
||||
void summarizesAndTrimsHistoryWhenThresholdReached() {
|
||||
ChatbotSession session =
|
||||
ChatbotSession.builder()
|
||||
.sessionId("session-1")
|
||||
.documentId("doc-123")
|
||||
.metadata(Map.of("documentName", "Quarterly Report"))
|
||||
.build();
|
||||
|
||||
when(conversationStore.defaultWindow()).thenReturn(2);
|
||||
when(conversationStore.retentionWindow()).thenReturn(10);
|
||||
when(conversationStore.historyLength("session-1")).thenReturn(6L);
|
||||
when(conversationStore.getRecentTurns("session-1", 10))
|
||||
.thenReturn(historyEntries(6, "doc-123", "Quarterly Report"));
|
||||
when(conversationStore.loadSummary("session-1")).thenReturn("previous summary");
|
||||
when(chatModel.call(any(Prompt.class)))
|
||||
.thenReturn(
|
||||
new ChatResponse(
|
||||
List.of(new Generation(new AssistantMessage("updated summary")))));
|
||||
|
||||
ReflectionTestUtils.invokeMethod(
|
||||
conversationService, "summarizeConversation", defaultSettings, session);
|
||||
|
||||
verify(chatModel, times(1)).call(any(Prompt.class));
|
||||
verify(conversationStore).storeSummary("session-1", "updated summary");
|
||||
verify(conversationStore).trimHistory("session-1", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsSummarizationWhenHistoryBelowThreshold() {
|
||||
ChatbotSession session =
|
||||
ChatbotSession.builder().sessionId("session-2").documentId("doc").build();
|
||||
|
||||
when(conversationStore.defaultWindow()).thenReturn(4);
|
||||
when(conversationStore.historyLength("session-2")).thenReturn(5L);
|
||||
|
||||
ReflectionTestUtils.invokeMethod(
|
||||
conversationService, "summarizeConversation", defaultSettings, session);
|
||||
|
||||
verify(chatModel, never()).call(any(org.springframework.ai.chat.prompt.Prompt.class));
|
||||
verify(conversationStore, never()).storeSummary(anyString(), anyString());
|
||||
verify(conversationStore, never()).trimHistory(anyString(), anyInt());
|
||||
}
|
||||
|
||||
private List<ChatbotHistoryEntry> historyEntries(
|
||||
int count, String documentId, String documentName) {
|
||||
List<ChatbotHistoryEntry> entries = new ArrayList<>();
|
||||
for (int i = 0; i < count; i++) {
|
||||
entries.add(
|
||||
new ChatbotHistoryEntry(
|
||||
i % 2 == 0 ? "user" : "assistant",
|
||||
"message-" + i,
|
||||
documentId,
|
||||
documentName,
|
||||
Instant.now().minusSeconds(60L - i)));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
package stirling.software.proprietary.service.chatbot;
|
||||
|
||||
import static org.mockito.Mockito.any;
|
||||
import static org.mockito.Mockito.eq;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotQueryRequest;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotResponse;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSession;
|
||||
import stirling.software.proprietary.model.chatbot.ChatbotSessionCreateRequest;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.service.AuditService;
|
||||
import stirling.software.proprietary.service.chatbot.ChatbotFeatureProperties.ChatbotSettings;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ChatbotServiceTest {
|
||||
|
||||
@Mock private ChatbotIngestionService ingestionService;
|
||||
@Mock private ChatbotConversationService conversationService;
|
||||
@Mock private ChatbotSessionRegistry sessionRegistry;
|
||||
@Mock private ChatbotCacheService cacheService;
|
||||
@Mock private ChatbotFeatureProperties featureProperties;
|
||||
@Mock private AuditService auditService;
|
||||
@Mock private UserService userService;
|
||||
|
||||
@InjectMocks private ChatbotService chatbotService;
|
||||
|
||||
private ChatbotSettings auditEnabledSettings;
|
||||
private ChatbotSettings auditDisabledSettings;
|
||||
|
||||
@BeforeEach
|
||||
void init() {
|
||||
auditEnabledSettings =
|
||||
new ChatbotSettings(
|
||||
true,
|
||||
true,
|
||||
4000,
|
||||
0.5D,
|
||||
false,
|
||||
new ChatbotSettings.ModelSettings(
|
||||
ChatbotSettings.ModelProvider.OPENAI,
|
||||
"gpt-5-nano",
|
||||
"gpt-5-mini",
|
||||
"embed",
|
||||
0.95D),
|
||||
new ChatbotSettings.RagSettings(512, 128, 4),
|
||||
new ChatbotSettings.CacheSettings(60, 10, 1000),
|
||||
new ChatbotSettings.OcrSettings(false),
|
||||
new ChatbotSettings.AuditSettings(true),
|
||||
new ChatbotSettings.UsageSettings(100000L, 0.7D));
|
||||
|
||||
auditDisabledSettings =
|
||||
new ChatbotSettings(
|
||||
true,
|
||||
true,
|
||||
4000,
|
||||
0.5D,
|
||||
false,
|
||||
new ChatbotSettings.ModelSettings(
|
||||
ChatbotSettings.ModelProvider.OPENAI,
|
||||
"gpt-5-nano",
|
||||
"gpt-5-mini",
|
||||
"embed",
|
||||
0.95D),
|
||||
new ChatbotSettings.RagSettings(512, 128, 4),
|
||||
new ChatbotSettings.CacheSettings(60, 10, 1000),
|
||||
new ChatbotSettings.OcrSettings(false),
|
||||
new ChatbotSettings.AuditSettings(false),
|
||||
new ChatbotSettings.UsageSettings(100000L, 0.7D));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSessionEmitsAuditWhenEnabled() {
|
||||
ChatbotSession session =
|
||||
ChatbotSession.builder()
|
||||
.sessionId("session-1")
|
||||
.documentId("doc-1")
|
||||
.ocrRequested(true)
|
||||
.createdAt(Instant.now())
|
||||
.build();
|
||||
when(ingestionService.ingest(any())).thenReturn(session);
|
||||
when(featureProperties.current()).thenReturn(auditEnabledSettings);
|
||||
when(userService.getCurrentUsername()).thenReturn("tester");
|
||||
|
||||
chatbotService.createSession(
|
||||
ChatbotSessionCreateRequest.builder().text("abc").warningsAccepted(true).build());
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> payloadCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
verify(auditService)
|
||||
.audit(
|
||||
eq(stirling.software.proprietary.audit.AuditEventType.PDF_PROCESS),
|
||||
payloadCaptor.capture());
|
||||
Map<String, Object> payload = payloadCaptor.getValue();
|
||||
verify(cacheService, times(0)).invalidateSession(any());
|
||||
verify(userService).getCurrentUsername();
|
||||
org.junit.jupiter.api.Assertions.assertEquals("session-1", payload.get("sessionId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void querySkipsAuditWhenDisabled() {
|
||||
ChatbotQueryRequest request =
|
||||
ChatbotQueryRequest.builder()
|
||||
.sessionId("session-2")
|
||||
.prompt("Hello?")
|
||||
.allowEscalation(true)
|
||||
.build();
|
||||
ChatbotResponse response =
|
||||
ChatbotResponse.builder()
|
||||
.sessionId("session-2")
|
||||
.modelUsed("gpt-5-nano")
|
||||
.confidence(0.8D)
|
||||
.build();
|
||||
when(conversationService.handleQuery(request)).thenReturn(response);
|
||||
when(featureProperties.current()).thenReturn(auditDisabledSettings);
|
||||
|
||||
chatbotService.ask(request);
|
||||
|
||||
verify(auditService, times(0))
|
||||
.audit(eq(stirling.software.proprietary.audit.AuditEventType.PDF_PROCESS), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeSessionInvalidatesCache() {
|
||||
ChatbotSession session =
|
||||
ChatbotSession.builder().sessionId("session-3").documentId("doc").build();
|
||||
when(sessionRegistry.findById("session-3")).thenReturn(Optional.of(session));
|
||||
when(featureProperties.current()).thenReturn(auditEnabledSettings);
|
||||
|
||||
chatbotService.close("session-3");
|
||||
|
||||
verify(sessionRegistry).remove("session-3");
|
||||
verify(cacheService).invalidateSession("session-3");
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import com.github.jk1.license.render.*
|
||||
|
||||
ext {
|
||||
springBootVersion = "3.5.6"
|
||||
springAiVersion = "1.0.3"
|
||||
pdfboxVersion = "3.0.5"
|
||||
imageioVersion = "3.12.0"
|
||||
lombokVersion = "1.18.42"
|
||||
@@ -94,8 +93,6 @@ subprojects {
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = 'https://repo.spring.io/release' }
|
||||
maven { url 'https://repo.spring.io/milestone' }
|
||||
}
|
||||
|
||||
configurations.configureEach {
|
||||
@@ -110,7 +107,6 @@ subprojects {
|
||||
dependencyManagement {
|
||||
imports {
|
||||
mavenBom "org.springframework.boot:spring-boot-dependencies:$springBootVersion"
|
||||
mavenBom "org.springframework.ai:spring-ai-bom:$springAiVersion"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -587,8 +587,3 @@ In your Thymeleaf templates, use the `#{key}` syntax to reference the new transl
|
||||
```
|
||||
|
||||
Remember, never hard-code text in your templates or Java code. Always use translation keys to ensure proper localization.
|
||||
|
||||
### Chatbot Feature Configuration
|
||||
|
||||
- The chatbot backend is disabled unless `premium.proFeatures.chatbot.enabled` is true in `configs/settings.yml`.
|
||||
- Provide an OpenAI-compatible key via `SPRING_AI_OPENAI_API_KEY` (or `spring.ai.openai.api-key`) and set `spring.ai.openai.enabled=true` when you want chatbot beans to load. Leaving this property disabled allows the rest of Stirling-PDF to run without AI credentials.
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# Stirling-PDF Dockerfile - Full version with embedded frontend
|
||||
# Single JAR contains both frontend and backend
|
||||
|
||||
# Stage 1: Build application with embedded frontend
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
|
||||
# Install Node.js and npm for frontend build
|
||||
RUN apt-get update && apt-get install -y \
|
||||
curl \
|
||||
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
|
||||
&& apt-get install -y nodejs \
|
||||
&& npm --version \
|
||||
&& node --version \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy gradle files for dependency resolution
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
COPY gradlew .
|
||||
COPY gradle gradle/
|
||||
COPY app/core/build.gradle core/.
|
||||
COPY app/common/build.gradle common/.
|
||||
COPY app/proprietary/build.gradle proprietary/.
|
||||
RUN ./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube || return 0
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy entire project
|
||||
COPY . .
|
||||
|
||||
# Build JAR with embedded frontend (includes security features controlled at runtime)
|
||||
RUN DISABLE_ADDITIONAL_FEATURES=false \
|
||||
STIRLING_PDF_DESKTOP_UI=false \
|
||||
./gradlew clean build -PbuildWithFrontend=true -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||
|
||||
# Stage 2: Runtime image
|
||||
FROM alpine:3.22.1
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
# Labels
|
||||
LABEL org.opencontainers.image.title="Stirling-PDF"
|
||||
LABEL org.opencontainers.image.description="Stirling-PDF with embedded frontend - Full version"
|
||||
LABEL org.opencontainers.image.source="https://github.com/Stirling-Tools/Stirling-PDF"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
LABEL org.opencontainers.image.vendor="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.url="https://www.stirlingpdf.com"
|
||||
LABEL org.opencontainers.image.documentation="https://docs.stirlingpdf.com"
|
||||
LABEL maintainer="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.authors="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.version="${VERSION_TAG}"
|
||||
LABEL org.opencontainers.image.keywords="PDF, manipulation, API, Spring Boot, React"
|
||||
|
||||
# Copy scripts and fonts
|
||||
COPY scripts /scripts
|
||||
COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
|
||||
|
||||
# Copy built JAR from build stage
|
||||
COPY --from=build /app/app/core/build/libs/*.jar /app.jar
|
||||
COPY --from=build /app/build/libs/restart-helper.jar /restart-helper.jar
|
||||
|
||||
# Environment Variables
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=1000 \
|
||||
PGID=1000 \
|
||||
UMASK=022 \
|
||||
PYTHONPATH=/usr/lib/libreoffice/program:/opt/venv/lib/python3.12/site-packages \
|
||||
UNO_PATH=/usr/lib/libreoffice/program \
|
||||
URE_BOOTSTRAP=file:///usr/lib/libreoffice/program/fundamentalrc \
|
||||
PATH=$PATH:/opt/venv/bin \
|
||||
STIRLING_TEMPFILES_DIRECTORY=/tmp/stirling-pdf \
|
||||
TMPDIR=/tmp/stirling-pdf \
|
||||
TEMP=/tmp/stirling-pdf \
|
||||
TMP=/tmp/stirling-pdf
|
||||
|
||||
# Install all dependencies
|
||||
RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
|
||||
echo "@community https://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories && \
|
||||
echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" | tee -a /etc/apk/repositories && \
|
||||
apk upgrade --no-cache -a && \
|
||||
apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
tini \
|
||||
bash \
|
||||
curl \
|
||||
shadow \
|
||||
su-exec \
|
||||
openssl \
|
||||
openssl-dev \
|
||||
openjdk21-jre \
|
||||
# Doc conversion
|
||||
gcompat \
|
||||
libc6-compat \
|
||||
libreoffice \
|
||||
ghostscript \
|
||||
fontforge \
|
||||
# pdftohtml
|
||||
poppler-utils \
|
||||
# OCR MY PDF
|
||||
unpaper \
|
||||
tesseract-ocr-data-eng \
|
||||
tesseract-ocr-data-chi_sim \
|
||||
tesseract-ocr-data-deu \
|
||||
tesseract-ocr-data-fra \
|
||||
tesseract-ocr-data-por \
|
||||
ocrmypdf \
|
||||
# CV
|
||||
py3-opencv \
|
||||
python3 \
|
||||
py3-pip \
|
||||
py3-pillow@testing \
|
||||
py3-pdf2image@testing && \
|
||||
python3 -m venv /opt/venv && \
|
||||
/opt/venv/bin/pip install --upgrade pip setuptools && \
|
||||
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
|
||||
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||
ln -s /usr/lib/libreoffice/program /opt/venv/lib/python3.12/site-packages/LibreOffice && \
|
||||
mv /usr/share/tessdata /usr/share/tessdata-original && \
|
||||
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
|
||||
fc-cache -f -v && \
|
||||
chmod +x /scripts/* && \
|
||||
# User permissions
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /usr/share/fonts/opentype/noto /configs /customFiles /tmp/stirling-pdf && \
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
|
||||
|
||||
EXPOSE 8080/tcp
|
||||
|
||||
# Set user and run command
|
||||
ENTRYPOINT ["tini", "--", "/scripts/init.sh"]
|
||||
CMD ["sh", "-c", "java -Dfile.encoding=UTF-8 -Djava.io.tmpdir=/tmp/stirling-pdf -jar /app.jar & /opt/venv/bin/unoserver --port 2003 --interface 127.0.0.1"]
|
||||
@@ -0,0 +1,142 @@
|
||||
# Stirling-PDF Dockerfile - Fat version with embedded frontend
|
||||
# Single JAR contains both frontend and backend with extra fonts for air-gapped environments
|
||||
|
||||
# Stage 1: Build application with embedded frontend
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
|
||||
# Install Node.js and npm for frontend build
|
||||
RUN apt-get update && apt-get install -y \
|
||||
curl \
|
||||
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
|
||||
&& apt-get install -y nodejs \
|
||||
&& npm --version \
|
||||
&& node --version \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy gradle files for dependency resolution
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
COPY gradlew .
|
||||
COPY gradle gradle/
|
||||
COPY app/core/build.gradle core/.
|
||||
COPY app/common/build.gradle common/.
|
||||
COPY app/proprietary/build.gradle proprietary/.
|
||||
RUN ./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube || return 0
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy entire project
|
||||
COPY . .
|
||||
|
||||
# Build JAR with embedded frontend (includes security features controlled at runtime)
|
||||
RUN DISABLE_ADDITIONAL_FEATURES=false \
|
||||
STIRLING_PDF_DESKTOP_UI=false \
|
||||
./gradlew clean build -PbuildWithFrontend=true -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||
|
||||
# Stage 2: Runtime image
|
||||
FROM alpine:3.22.1
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
# Labels
|
||||
LABEL org.opencontainers.image.title="Stirling-PDF Fat"
|
||||
LABEL org.opencontainers.image.description="Stirling-PDF with embedded frontend - Fat version with extra fonts for air-gapped environments"
|
||||
LABEL org.opencontainers.image.source="https://github.com/Stirling-Tools/Stirling-PDF"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
LABEL org.opencontainers.image.vendor="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.url="https://www.stirlingpdf.com"
|
||||
LABEL org.opencontainers.image.documentation="https://docs.stirlingpdf.com"
|
||||
LABEL maintainer="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.authors="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.version="${VERSION_TAG}"
|
||||
LABEL org.opencontainers.image.keywords="PDF, manipulation, fat, air-gapped, API, Spring Boot, React"
|
||||
|
||||
# Copy scripts and fonts
|
||||
COPY scripts /scripts
|
||||
COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
|
||||
|
||||
# Copy built JAR from build stage
|
||||
COPY --from=build /app/app/core/build/libs/*.jar /app.jar
|
||||
COPY --from=build /app/build/libs/restart-helper.jar /restart-helper.jar
|
||||
|
||||
# Environment Variables
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=1000 \
|
||||
PGID=1000 \
|
||||
UMASK=022 \
|
||||
FAT_DOCKER=true \
|
||||
INSTALL_BOOK_AND_ADVANCED_HTML_OPS=false \
|
||||
PYTHONPATH=/usr/lib/libreoffice/program:/opt/venv/lib/python3.12/site-packages \
|
||||
UNO_PATH=/usr/lib/libreoffice/program \
|
||||
URE_BOOTSTRAP=file:///usr/lib/libreoffice/program/fundamentalrc \
|
||||
PATH=$PATH:/opt/venv/bin \
|
||||
STIRLING_TEMPFILES_DIRECTORY=/tmp/stirling-pdf \
|
||||
TMPDIR=/tmp/stirling-pdf \
|
||||
TEMP=/tmp/stirling-pdf \
|
||||
TMP=/tmp/stirling-pdf
|
||||
|
||||
# Install all dependencies plus extra fonts for air-gapped environments
|
||||
RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
|
||||
echo "@community https://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories && \
|
||||
echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" | tee -a /etc/apk/repositories && \
|
||||
apk upgrade --no-cache -a && \
|
||||
apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
tini \
|
||||
bash \
|
||||
curl \
|
||||
shadow \
|
||||
su-exec \
|
||||
openssl \
|
||||
openssl-dev \
|
||||
openjdk21-jre \
|
||||
# Doc conversion
|
||||
gcompat \
|
||||
libc6-compat \
|
||||
libreoffice \
|
||||
ghostscript \
|
||||
fontforge \
|
||||
# pdftohtml
|
||||
poppler-utils \
|
||||
# OCR MY PDF
|
||||
unpaper \
|
||||
tesseract-ocr-data-eng \
|
||||
tesseract-ocr-data-chi_sim \
|
||||
tesseract-ocr-data-deu \
|
||||
tesseract-ocr-data-fra \
|
||||
tesseract-ocr-data-por \
|
||||
ocrmypdf \
|
||||
# Extra fonts for fat version
|
||||
font-terminus font-dejavu font-noto font-noto-cjk font-awesome font-noto-extra font-liberation font-linux-libertine \
|
||||
# CV
|
||||
py3-opencv \
|
||||
python3 \
|
||||
py3-pip \
|
||||
py3-pillow@testing \
|
||||
py3-pdf2image@testing && \
|
||||
python3 -m venv /opt/venv && \
|
||||
/opt/venv/bin/pip install --upgrade pip setuptools && \
|
||||
/opt/venv/bin/pip install --no-cache-dir --upgrade unoserver weasyprint && \
|
||||
ln -s /usr/lib/libreoffice/program/uno.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||
ln -s /usr/lib/libreoffice/program /opt/venv/lib/python3.12/site-packages/LibreOffice && \
|
||||
mv /usr/share/tessdata /usr/share/tessdata-original && \
|
||||
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
|
||||
fc-cache -f -v && \
|
||||
chmod +x /scripts/* && \
|
||||
# User permissions
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /usr/share/fonts/opentype/noto /configs /customFiles /tmp/stirling-pdf && \
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
|
||||
|
||||
EXPOSE 8080/tcp
|
||||
|
||||
# Set user and run command
|
||||
ENTRYPOINT ["tini", "--", "/scripts/init.sh"]
|
||||
CMD ["sh", "-c", "java -Dfile.encoding=UTF-8 -Djava.io.tmpdir=/tmp/stirling-pdf -jar /app.jar & /opt/venv/bin/unoserver --port 2003 --interface 127.0.0.1"]
|
||||
@@ -0,0 +1,104 @@
|
||||
# Stirling-PDF Dockerfile - Ultra-lite version with embedded frontend
|
||||
# Single JAR contains both frontend and backend with minimal dependencies
|
||||
|
||||
# Stage 1: Build application with embedded frontend
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
|
||||
# Install Node.js and npm for frontend build
|
||||
RUN apt-get update && apt-get install -y \
|
||||
curl \
|
||||
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
|
||||
&& apt-get install -y nodejs \
|
||||
&& npm --version \
|
||||
&& node --version \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy gradle files for dependency resolution
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
COPY gradlew .
|
||||
COPY gradle gradle/
|
||||
COPY app/core/build.gradle core/.
|
||||
COPY app/common/build.gradle common/.
|
||||
COPY app/proprietary/build.gradle proprietary/.
|
||||
RUN ./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube || return 0
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy entire project
|
||||
COPY . .
|
||||
|
||||
# Build ultra-lite JAR with embedded frontend (minimal features)
|
||||
RUN DISABLE_ADDITIONAL_FEATURES=true \
|
||||
STIRLING_PDF_DESKTOP_UI=false \
|
||||
./gradlew clean build -PbuildWithFrontend=true -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||
|
||||
# Stage 2: Runtime image
|
||||
FROM alpine:3.22.1
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
# Labels
|
||||
LABEL org.opencontainers.image.title="Stirling-PDF Ultra-Lite"
|
||||
LABEL org.opencontainers.image.description="Stirling-PDF with embedded frontend - Ultra-lite version with minimal dependencies"
|
||||
LABEL org.opencontainers.image.source="https://github.com/Stirling-Tools/Stirling-PDF"
|
||||
LABEL org.opencontainers.image.licenses="MIT"
|
||||
LABEL org.opencontainers.image.vendor="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.url="https://www.stirlingpdf.com"
|
||||
LABEL org.opencontainers.image.documentation="https://docs.stirlingpdf.com"
|
||||
LABEL maintainer="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.authors="Stirling-Tools"
|
||||
LABEL org.opencontainers.image.version="${VERSION_TAG}"
|
||||
LABEL org.opencontainers.image.keywords="PDF, manipulation, ultra-lite, API, Spring Boot, React"
|
||||
|
||||
# Copy scripts
|
||||
COPY scripts/init-without-ocr.sh /scripts/init-without-ocr.sh
|
||||
COPY scripts/installFonts.sh /scripts/installFonts.sh
|
||||
|
||||
# Copy built JAR from build stage
|
||||
COPY --from=build /app/app/core/build/libs/*.jar /app.jar
|
||||
COPY --from=build /app/build/libs/restart-helper.jar /restart-helper.jar
|
||||
|
||||
# Environment Variables
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=1000 \
|
||||
PGID=1000 \
|
||||
UMASK=022 \
|
||||
STIRLING_TEMPFILES_DIRECTORY=/tmp/stirling-pdf \
|
||||
TMPDIR=/tmp/stirling-pdf \
|
||||
TEMP=/tmp/stirling-pdf \
|
||||
TMP=/tmp/stirling-pdf \
|
||||
ENDPOINTS_GROUPS_TO_REMOVE=CLI
|
||||
|
||||
# Install minimal dependencies
|
||||
RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/apk/repositories && \
|
||||
echo "@community https://dl-cdn.alpinelinux.org/alpine/edge/community" | tee -a /etc/apk/repositories && \
|
||||
echo "@testing https://dl-cdn.alpinelinux.org/alpine/edge/testing" | tee -a /etc/apk/repositories && \
|
||||
apk upgrade --no-cache -a && \
|
||||
apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
tini \
|
||||
bash \
|
||||
curl \
|
||||
shadow \
|
||||
su-exec \
|
||||
openjdk21-jre && \
|
||||
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
|
||||
mkdir -p /usr/share/fonts/opentype/noto && \
|
||||
chmod +x /scripts/*.sh && \
|
||||
# User permissions
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /configs /customFiles /pipeline /tmp/stirling-pdf && \
|
||||
chown stirlingpdfuser:stirlingpdfgroup /app.jar /restart-helper.jar
|
||||
|
||||
EXPOSE 8080/tcp
|
||||
|
||||
# Set user and run command
|
||||
ENTRYPOINT ["tini", "--", "/scripts/init-without-ocr.sh"]
|
||||
CMD ["java", "-Dfile.encoding=UTF-8", "-Djava.io.tmpdir=/tmp/stirling-pdf", "-jar", "/app.jar"]
|
||||
+4
-4
@@ -3,21 +3,21 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<base href="%BASE_URL%" />
|
||||
<link rel="icon" href="/modern-logo/favicon.ico" />
|
||||
<link rel="icon" href="modern-logo/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="The Free Adobe Acrobat alternative (10M+ Downloads)"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="/modern-logo/logo192.png" />
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<link rel="apple-touch-icon" href="modern-logo/logo192.png" />
|
||||
<link rel="manifest" href="manifest.json" />
|
||||
|
||||
<title>Stirling PDF</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/index.tsx"></script>
|
||||
<script type="module" src="src/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Generated
+176
-183
@@ -11,25 +11,26 @@
|
||||
"dependencies": {
|
||||
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@embedpdf/core": "^1.4.1",
|
||||
"@embedpdf/engines": "^1.4.1",
|
||||
"@embedpdf/plugin-annotation": "^1.4.1",
|
||||
"@embedpdf/plugin-bookmark": "^1.4.1",
|
||||
"@embedpdf/plugin-export": "^1.4.1",
|
||||
"@embedpdf/plugin-history": "^1.4.1",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.4.1",
|
||||
"@embedpdf/plugin-loader": "^1.4.1",
|
||||
"@embedpdf/plugin-pan": "^1.4.1",
|
||||
"@embedpdf/plugin-render": "^1.4.1",
|
||||
"@embedpdf/plugin-rotate": "^1.4.1",
|
||||
"@embedpdf/plugin-scroll": "^1.4.1",
|
||||
"@embedpdf/plugin-search": "^1.4.1",
|
||||
"@embedpdf/plugin-selection": "^1.4.1",
|
||||
"@embedpdf/plugin-spread": "^1.4.1",
|
||||
"@embedpdf/plugin-thumbnail": "^1.4.1",
|
||||
"@embedpdf/plugin-tiling": "^1.4.1",
|
||||
"@embedpdf/plugin-viewport": "^1.4.1",
|
||||
"@embedpdf/plugin-zoom": "^1.4.1",
|
||||
"@embedpdf/core": "^1.5.0",
|
||||
"@embedpdf/engines": "^1.5.0",
|
||||
"@embedpdf/plugin-annotation": "^1.5.0",
|
||||
"@embedpdf/plugin-bookmark": "^1.5.0",
|
||||
"@embedpdf/plugin-export": "^1.5.0",
|
||||
"@embedpdf/plugin-history": "^1.5.0",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.5.0",
|
||||
"@embedpdf/plugin-loader": "^1.5.0",
|
||||
"@embedpdf/plugin-pan": "^1.5.0",
|
||||
"@embedpdf/plugin-print": "^1.5.0",
|
||||
"@embedpdf/plugin-render": "^1.5.0",
|
||||
"@embedpdf/plugin-rotate": "^1.5.0",
|
||||
"@embedpdf/plugin-scroll": "^1.5.0",
|
||||
"@embedpdf/plugin-search": "^1.5.0",
|
||||
"@embedpdf/plugin-selection": "^1.5.0",
|
||||
"@embedpdf/plugin-spread": "^1.5.0",
|
||||
"@embedpdf/plugin-thumbnail": "^1.5.0",
|
||||
"@embedpdf/plugin-tiling": "^1.5.0",
|
||||
"@embedpdf/plugin-viewport": "^1.5.0",
|
||||
"@embedpdf/plugin-zoom": "^1.5.0",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@iconify/react": "^6.0.2",
|
||||
@@ -455,7 +456,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
@@ -499,7 +499,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
@@ -576,14 +575,13 @@
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/@embedpdf/core": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/core/-/core-1.4.1.tgz",
|
||||
"integrity": "sha512-TGpxn2CvAKRnOJWJ3bsK+dKBiCp75ehxftRUmv7wAmPomhnG5XrDfoWJungvO+zbbqAwso6PocdeXINVt3hlAw==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/core/-/core-1.5.0.tgz",
|
||||
"integrity": "sha512-Yrh9XoVaT8cUgzgqpJ7hx5wg6BqQrCFirqqlSwVb+Ly9oNn4fZbR9GycIWmzJOU5XBnaOJjXfQSaDyoNP0woNA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/engines": "1.4.1",
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/engines": "1.5.0",
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"preact": "^10.26.4",
|
||||
@@ -594,13 +592,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/engines": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/engines/-/engines-1.4.1.tgz",
|
||||
"integrity": "sha512-yugIb5OwTI/1VnAaEvSYxAd2DvYBPkV/D7wytagyaOq98o3sqzcY2Q9zHt+LhnawA5KKG1e/FDPjCd4qm8gsvg==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/engines/-/engines-1.5.0.tgz",
|
||||
"integrity": "sha512-/GzhjHFHWfOaX7vjgFJX/pyq668wYjoda1bZ9MpwF/EF000Wwy2Q0AOhprjldPFz8ASKjwKwqsXmaqrK99yOAQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1",
|
||||
"@embedpdf/pdfium": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0",
|
||||
"@embedpdf/pdfium": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"preact": "^10.26.4",
|
||||
@@ -611,31 +609,31 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/models": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/models/-/models-1.4.1.tgz",
|
||||
"integrity": "sha512-2nTg8Q1qpplBvspZJXMCZOA+/OILpfdNRPddlplxZXY/Upx0rzKXx/e6pXWW7AuOgtfGneT4h9tMs3A595/PdQ==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/models/-/models-1.5.0.tgz",
|
||||
"integrity": "sha512-x/1li3jdag+IzfZkcfRLKLqASLep4v6dgVi3z0JArwaicFra8k1IY2xaVTrwcZyx7pRb/rxvoO9yLHW0Y34NFw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@embedpdf/pdfium": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/pdfium/-/pdfium-1.4.1.tgz",
|
||||
"integrity": "sha512-BekKEK4UNCwzj7xOffKn6WpL0FQHxq+mTj2iGI3N7OwAX2J/BO2G+rDOB+lvojQG+Dkpg8uqm427ZKJDRyLgVQ==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/pdfium/-/pdfium-1.5.0.tgz",
|
||||
"integrity": "sha512-PI32t2U4ThZC907n2Iwr8E5WqmC574G83u3V9ysNFl29N9kasrY9RiLSzU4W/yQvXPjIbpQHBsbMKXLjCFBI9w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-annotation": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-annotation/-/plugin-annotation-1.4.1.tgz",
|
||||
"integrity": "sha512-d4HibNy6ecyDqx2Y2R8VjaqppSdjNofAJmU6VenOd88wn080sAUqvnkeVJ6ehJH5BoND4ymQrcAkcbVeYK0myA==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-annotation/-/plugin-annotation-1.5.0.tgz",
|
||||
"integrity": "sha512-mxEPI6xYwOGaf9fYfoywuj6nwA10eHFPBuN066MzwphDk6DOHJGZ3Vq8zNQBXh20c/Lb25PL718D7MZWxZLUHg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1",
|
||||
"@embedpdf/utils": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0",
|
||||
"@embedpdf/utils": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-history": "1.4.1",
|
||||
"@embedpdf/plugin-interaction-manager": "1.4.1",
|
||||
"@embedpdf/plugin-selection": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-history": "1.5.0",
|
||||
"@embedpdf/plugin-interaction-manager": "1.5.0",
|
||||
"@embedpdf/plugin-selection": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -643,15 +641,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-bookmark": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-bookmark/-/plugin-bookmark-1.4.1.tgz",
|
||||
"integrity": "sha512-WnfBJdv+Eq5zsMfwDZ5RlXZMGpvKm/ccL6jlTVwtELBhu3wvhjjbBmZdheEOzHMC3VXMNYDMjCeaXkUG4nWoDA==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-bookmark/-/plugin-bookmark-1.5.0.tgz",
|
||||
"integrity": "sha512-s3C9PtVesy5X8Ds/C9TEElFiqfKGRklG/uNPTROpNoolfpi0h7qX2xqqh/9+FzKH2nHjVcPB7Pp432v16h7eRA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -659,15 +657,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-export": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-export/-/plugin-export-1.4.1.tgz",
|
||||
"integrity": "sha512-g89fREFM/zkt2Ai2Q5dWwDkhXgC/JmVyUniaMgm1fTG/MZ0Z05E7f34DUzX/CKcJyVjxEgl6tojBTMeUbm15bA==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-export/-/plugin-export-1.5.0.tgz",
|
||||
"integrity": "sha512-luk68mNW9l2X31qk4b02phKaqDl9aDXUAgHVz1EWrgwXQ3Oz9WEdu60utYARYDiepDo3Caadll8RwctYSf/anA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -676,16 +674,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-history": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-history/-/plugin-history-1.4.1.tgz",
|
||||
"integrity": "sha512-5WLDiNMH6tACkLGGv/lJtNsDeozOhSbrh0mjD1btHun8u7Yscu/Vf8tdJRUOsd+nULivo2nQ2NFNKu0OTbVo8w==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-history/-/plugin-history-1.5.0.tgz",
|
||||
"integrity": "sha512-p7PTNNaIr4gH3jLwX+eLJe1DeUXgi21kVGN6SRx/pocH8esg4jqoOeD/YiRRZoZnPOiy0jBXVhkPkwSmY7a2hQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -693,16 +690,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-interaction-manager": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-interaction-manager/-/plugin-interaction-manager-1.4.1.tgz",
|
||||
"integrity": "sha512-Ng02S9SFIAi9JZS5rI+NXSnZZ1Yk9YYRw4MlN2pig49qOyivZdz0oScZaYxQPewo8ccJkLeghjdeWswOBW/6cA==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-interaction-manager/-/plugin-interaction-manager-1.5.0.tgz",
|
||||
"integrity": "sha512-ckHgTfvkW6c5Ta7Mc+Dl9C2foVnvEpqEJ84wyBnqrU0OWbe/jsiPhyKBVeartMGqNI/kVfaQTXupyrKhekAVmg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -711,16 +707,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-loader": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-loader/-/plugin-loader-1.4.1.tgz",
|
||||
"integrity": "sha512-m3ZOk8JygsLxoa4cZ+0BVB5pfRWuBCg2/gPqjhoFZNKTqAFw4J6HGUrhYKg94GRYe+w1cTJl/NbTBYuU5DOrsA==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-loader/-/plugin-loader-1.5.0.tgz",
|
||||
"integrity": "sha512-P4YpIZfaW69etYIjphyaL4cGl2pB14h3OdTE0tRQ2pZYZHFLTvlt4q9B3PVSdhlSrHK5nob7jfLGon2U7xCslg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -729,17 +724,17 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-pan": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-pan/-/plugin-pan-1.4.1.tgz",
|
||||
"integrity": "sha512-zmOZJ9dUqXiaV0F5GPf/5WTWf3jAEkiv153Tl3x8HT9Rfff+WQhV48NruCIBAy/T4jVt4aH7D1zt/B/ftvcdkA==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-pan/-/plugin-pan-1.5.0.tgz",
|
||||
"integrity": "sha512-EMQ08dHqLkZmFVuLOO6h3AAinFPQoA1r6OlL9z+p0sswq31JAgd4X7+xjYIpI01z/V3+cTzPHzp7qwob5E4tbA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-interaction-manager": "1.4.1",
|
||||
"@embedpdf/plugin-viewport": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-interaction-manager": "1.5.0",
|
||||
"@embedpdf/plugin-viewport": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -747,17 +742,33 @@
|
||||
"vue": ">=3.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-render": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-render/-/plugin-render-1.4.1.tgz",
|
||||
"integrity": "sha512-gKCdNKw6WBHBEpTc2DLBWIWOxzsNnaNbpfeY6C4f2Bum0EO+XW3Hl2oIx1uaRHjIhhnXso1J3QweqelsPwDGwg==",
|
||||
"node_modules/@embedpdf/plugin-print": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-print/-/plugin-print-1.5.0.tgz",
|
||||
"integrity": "sha512-rjorvNxAZfO9X4cFZVU9fHnldMWqMceJGmr3mH+yj7KdHePvNDDP+omyZyZKtxlUZENaeDI2h6k5z0GbhBz6sQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=18.0.0",
|
||||
"react-dom": ">=18.0.0",
|
||||
"svelte": ">=5 <6",
|
||||
"vue": ">=3.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-render": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-render/-/plugin-render-1.5.0.tgz",
|
||||
"integrity": "sha512-ywwSj0ByrlkvrJIHKRzqxARkOZriki8VJUC+T4MV8fGyF4CzvCRJyKlPktahFz+VxhoodqTh7lBCib68dH+GvA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -766,15 +777,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-rotate": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-rotate/-/plugin-rotate-1.4.1.tgz",
|
||||
"integrity": "sha512-hVzHkKwMNH3tUhxqJGsj5qTLpYZXbj6E74AEcG0w/fz5FrK7EnofPqt0gRfYmIzxnQGIh+39BRtcp8gmx8UNnw==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-rotate/-/plugin-rotate-1.5.0.tgz",
|
||||
"integrity": "sha512-5EmBCsq0VfrE3xWY6ofuVm8S6aK95EbAycRIk1wczcmTdvpsuXZ6P2ZaECUgYMcpZ6uAg4/kGf8X8VVZuCihSQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -783,17 +794,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-scroll": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-scroll/-/plugin-scroll-1.4.1.tgz",
|
||||
"integrity": "sha512-Y9O+matB4j4fLim5s/jn7qIi+lMC9vmDJRpJhiWe8bvD9oYLP2xfD/DdhFgAjRKcNhPoxC+j8q8QN5BMeGAv2Q==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-scroll/-/plugin-scroll-1.5.0.tgz",
|
||||
"integrity": "sha512-RNmTZCZ8X1mA8cw9M7TMDuhO9GtkOalGha2bBL3En3D1IlDRS7PzNNMSMV7eqT7OQICSTltlpJ8p8Qi5esvL/Q==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-viewport": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-viewport": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -802,16 +812,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-search": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-search/-/plugin-search-1.4.1.tgz",
|
||||
"integrity": "sha512-8JG4CbOcUsLuT0vHJJ4cECmu+Yn53EokWFUVXi2Mo/XvHjhrQuWmD7+y6s/qQPEpctFYWmUCXTDAX9ynPud+2Q==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-search/-/plugin-search-1.5.0.tgz",
|
||||
"integrity": "sha512-TB5b0H8Iobx/azVUBIlG2ClaKtf0y3/Xi3E/iB8BwvkIE2+g6EGfp8IMXIn8WDXST6bbvJEP31Ab0Ilp6SVkiw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-loader": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-loader": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -820,18 +830,17 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-selection": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-selection/-/plugin-selection-1.4.1.tgz",
|
||||
"integrity": "sha512-lo5Ytk1PH0PrRKv6zKVupm4t02VGsqIrnSIeP6NO8Ujx0wfqEhj//sqIuO/EwfFVJD8lcQIP9UUo9y8baCrEog==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-selection/-/plugin-selection-1.5.0.tgz",
|
||||
"integrity": "sha512-zrxLBAZQoPswDuf9q9DrYaQc6B0Ysc2U1hueTjNH/4+ydfl0BFXZkKR63C2e3YmWtXvKjkoIj0GyPzsiBORLUw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-interaction-manager": "1.4.1",
|
||||
"@embedpdf/plugin-viewport": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-interaction-manager": "1.5.0",
|
||||
"@embedpdf/plugin-viewport": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -840,16 +849,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-spread": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-spread/-/plugin-spread-1.4.1.tgz",
|
||||
"integrity": "sha512-l+SrDVGTiiItkt2cEtzv7V/X5HhmLbYHcQ8CFobGeIKdJtzKS1Nu/JSKqg7Ki7eCNgyPL1yMNfNE92bNKYVN4w==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-spread/-/plugin-spread-1.5.0.tgz",
|
||||
"integrity": "sha512-3EU5Cp+fPQSiMjvMR/P2kXxXry/RlnxHLs4JeskAaH95QcqWW3VD+DrHkWSiLFkdhI18rNNGNlMc5RvDGvbXGQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-loader": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-loader": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -858,16 +867,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-thumbnail": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-thumbnail/-/plugin-thumbnail-1.4.1.tgz",
|
||||
"integrity": "sha512-bN3msjI0PovazgbPK3LyugYVTwIDo0RyBUhBaG42FgJxeY3hmFOWTPgfUH1QF7twHlySnksIvHRFYR3nViryVw==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-thumbnail/-/plugin-thumbnail-1.5.0.tgz",
|
||||
"integrity": "sha512-Z2qpyyr5s2M6460KDGu1Vk6rdbQFIoCpnyFAT6e7UaTIKkqJSNpmjqMsBU5PosYCFu/cClpHPvS7tg9/IKAk6g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-render": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-render": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -876,18 +885,18 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-tiling": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-tiling/-/plugin-tiling-1.4.1.tgz",
|
||||
"integrity": "sha512-wgTfj5T8HV6KP61iiR63DVNrbVp8sPxTqa1Sm+2/D0jY+EPSSCmpt1/qYWiAXd1X+t78foOjCnfbo7fEMn5/pg==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-tiling/-/plugin-tiling-1.5.0.tgz",
|
||||
"integrity": "sha512-0Vx9elHNpMM+zv8hEoZXBEm8Q0+4kU52LxOlTYRr1A5FskF836sUct6g1ngwK1bmfbAfpz+62PnYI2EeilDZig==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-render": "1.4.1",
|
||||
"@embedpdf/plugin-scroll": "1.4.1",
|
||||
"@embedpdf/plugin-viewport": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-render": "1.5.0",
|
||||
"@embedpdf/plugin-scroll": "1.5.0",
|
||||
"@embedpdf/plugin-viewport": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -896,16 +905,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-viewport": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-viewport/-/plugin-viewport-1.4.1.tgz",
|
||||
"integrity": "sha512-+TgFHKPCLTBiDYe2DdsmTS37hwQgcZ3dYIc7bE0l5cp+GVwouu1h0MTmjL+90loizeWwCiu10E/zXR6hz+CUaQ==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-viewport/-/plugin-viewport-1.5.0.tgz",
|
||||
"integrity": "sha512-G8GDyYRhfehw72+r4qKkydnA5+AU8qH67g01Y12b0DzI0VIzymh/05Z4dK8DsY3jyWPXJfw2hlg5+KDHaMBHgQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1"
|
||||
"@embedpdf/models": "1.5.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -914,19 +922,19 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/plugin-zoom": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-zoom/-/plugin-zoom-1.4.1.tgz",
|
||||
"integrity": "sha512-9HocmXnPZxqN06q7kyNAmLjgDHOEW8/8QfgNE3nMpRyNHIgnAjxvsWc9lApgp5ErDPG0cSDt0Cduil6nB3wSBQ==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/plugin-zoom/-/plugin-zoom-1.5.0.tgz",
|
||||
"integrity": "sha512-LiDkCd5/IXg2CRORl1Yikan2op+AYXSxhHzCFatyBdwzVj+n4y9I74OwCI62Mar8WDAIMyXZDCQxGPToSm+zDw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@embedpdf/models": "1.4.1",
|
||||
"@embedpdf/models": "1.5.0",
|
||||
"hammerjs": "^2.0.8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@embedpdf/core": "1.4.1",
|
||||
"@embedpdf/plugin-interaction-manager": "1.4.1",
|
||||
"@embedpdf/plugin-scroll": "1.4.1",
|
||||
"@embedpdf/plugin-viewport": "1.4.1",
|
||||
"@embedpdf/core": "1.5.0",
|
||||
"@embedpdf/plugin-interaction-manager": "1.5.0",
|
||||
"@embedpdf/plugin-scroll": "1.5.0",
|
||||
"@embedpdf/plugin-viewport": "1.5.0",
|
||||
"preact": "^10.26.4",
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0",
|
||||
@@ -935,9 +943,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@embedpdf/utils": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/utils/-/utils-1.4.1.tgz",
|
||||
"integrity": "sha512-vvJ51Qsz3PyJWR2YvDMMpJXg4+YqdV7Vn2cusmW9sx+4EnAiBiw0HevEE+FepgFV8k+A0WbwXzmsujDIQJ7R4A==",
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@embedpdf/utils/-/utils-1.5.0.tgz",
|
||||
"integrity": "sha512-L6jsAPQPGM8ne+MMFAd5gqXb1RNEgNyh16VvVUVKcVnJlBhwil59nVeEQ0cwPhjF5qVeY6MQDIOjBzJqkgXOYg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"preact": "^10.26.4",
|
||||
@@ -1056,7 +1064,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@emotion/react/-/react-11.14.0.tgz",
|
||||
"integrity": "sha512-O000MLDBDdk/EohJPFUqvnp4qnHeYkVP5B0xEG0D/L7cOKP9kefu2DXn8dj74cQfsEzUqh+sr1RzFqiL1o+PpA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@emotion/babel-plugin": "^11.13.5",
|
||||
@@ -1100,7 +1107,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@emotion/styled/-/styled-11.14.1.tgz",
|
||||
"integrity": "sha512-qEEJt42DuToa3gurlH4Qqc1kVpNq8wO8cJtDzU46TjlzWjDlsVyevtYCRijVq3SrHsROS+gVQ8Fnea108GnKzw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"@emotion/babel-plugin": "^11.13.5",
|
||||
@@ -2131,7 +2137,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@mantine/core/-/core-8.3.6.tgz",
|
||||
"integrity": "sha512-paTl+0x+O/QtgMtqVJaG8maD8sfiOdgPmLOyG485FmeGZ1L3KMdEkhxZtmdGlDFsLXhmMGQ57ducT90bvhXX5A==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@floating-ui/react": "^0.27.16",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -2182,7 +2187,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@mantine/hooks/-/hooks-8.3.6.tgz",
|
||||
"integrity": "sha512-liHfaWXHAkLjJy+Bkr29UsCwAoDQ/a64WrM67lksx8F0qqyjR5RQH8zVlhuOjdpQnwtlUkE/YiTvbJiPcoI0bw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"react": "^18.x || ^19.x"
|
||||
}
|
||||
@@ -2250,7 +2254,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@mui/material/-/material-7.3.5.tgz",
|
||||
"integrity": "sha512-8VVxFmp1GIm9PpmnQoCoYo0UWHoOrdA57tDL62vkpzEgvb/d71Wsbv4FRg7r1Gyx7PuSo0tflH34cdl/NvfHNQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.28.4",
|
||||
"@mui/core-downloads-tracker": "^7.3.5",
|
||||
@@ -3183,7 +3186,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-7.9.0.tgz",
|
||||
"integrity": "sha512-ggs5k+/0FUJcIgNY08aZTqpBTtbExkJMYMLSMwyucrhtWexVOEY1KJmhBsxf+E/Q15f5rbwBpj+t0t2AW2oCsQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12.16"
|
||||
}
|
||||
@@ -3302,6 +3304,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.6.tgz",
|
||||
"integrity": "sha512-4awhxtMh4cx9blePWl10HRHj8Iivtqj+2QdDCSMDzxG+XKa9+VCNupQuCuvzEhYPzZSrX+0gC+0lHA/0fFKKQQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"acorn": "^8.9.0"
|
||||
}
|
||||
@@ -4078,7 +4081,6 @@
|
||||
"integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.10.4",
|
||||
"@babel/runtime": "^7.12.5",
|
||||
@@ -4407,7 +4409,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.2.tgz",
|
||||
"integrity": "sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"csstype": "^3.0.2"
|
||||
}
|
||||
@@ -4418,7 +4419,6 @@
|
||||
"integrity": "sha512-9KQPoO6mZCi7jcIStSnlOWn2nEF3mNmyr3rIAsGnAbQKYbRLyqmeSc39EVgtxXVia+LMT8j3knZLAZAh+xLmrw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^19.2.0"
|
||||
}
|
||||
@@ -4488,7 +4488,6 @@
|
||||
"integrity": "sha512-6m1I5RmHBGTnUGS113G04DMu3CpSdxCAU/UvtjNWL4Nuf3MW9tQhiJqRlHzChIkhy6kZSAQmc+I1bcGjE3yNKg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.46.3",
|
||||
"@typescript-eslint/types": "8.46.3",
|
||||
@@ -5202,6 +5201,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.5.24.tgz",
|
||||
"integrity": "sha512-BM8kBhtlkkbnyl4q+HiF5R5BL0ycDPfihowulm02q3WYp2vxgPcJuZO866qa/0u3idbMntKEtVNuAUp5bw4teg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/shared": "3.5.24"
|
||||
}
|
||||
@@ -5211,6 +5211,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.5.24.tgz",
|
||||
"integrity": "sha512-RYP/byyKDgNIqfX/gNb2PB55dJmM97jc9wyF3jK7QUInYKypK2exmZMNwnjueWwGceEkP6NChd3D2ZVEp9undQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/reactivity": "3.5.24",
|
||||
"@vue/shared": "3.5.24"
|
||||
@@ -5221,6 +5222,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.5.24.tgz",
|
||||
"integrity": "sha512-Z8ANhr/i0XIluonHVjbUkjvn+CyrxbXRIxR7wn7+X7xlcb7dJsfITZbkVOeJZdP8VZwfrWRsWdShH6pngMxRjw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/reactivity": "3.5.24",
|
||||
"@vue/runtime-core": "3.5.24",
|
||||
@@ -5233,6 +5235,7 @@
|
||||
"resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.5.24.tgz",
|
||||
"integrity": "sha512-Yh2j2Y4G/0/4z/xJ1Bad4mxaAk++C2v4kaa8oSYTMJBJ00/ndPuxCnWeot0/7/qafQFLh5pr6xeV6SdMcE/G1w==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/compiler-ssr": "3.5.24",
|
||||
"@vue/shared": "3.5.24"
|
||||
@@ -5259,7 +5262,6 @@
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -5667,6 +5669,7 @@
|
||||
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
|
||||
"integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
@@ -5943,7 +5946,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.8.19",
|
||||
"caniuse-lite": "^1.0.30001751",
|
||||
@@ -6991,8 +6993,7 @@
|
||||
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1521046.tgz",
|
||||
"integrity": "sha512-vhE6eymDQSKWUXwwA37NtTTVEzjtGVfDr3pRbsWEQ5onH/Snp2c+2xZHWJJawG/0hCCJLRGt4xVtEVUVILol4w==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"peer": true
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/dezalgo": {
|
||||
"version": "1.0.4",
|
||||
@@ -7387,7 +7388,6 @@
|
||||
"integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.8.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -7558,7 +7558,6 @@
|
||||
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@rtsao/scc": "^1.1.0",
|
||||
"array-includes": "^3.1.9",
|
||||
@@ -7725,7 +7724,8 @@
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
|
||||
"integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/espree": {
|
||||
"version": "10.4.0",
|
||||
@@ -7790,6 +7790,7 @@
|
||||
"resolved": "https://registry.npmjs.org/esrap/-/esrap-2.1.2.tgz",
|
||||
"integrity": "sha512-DgvlIQeowRNyvLPWW4PT7Gu13WznY288Du086E751mwwbsgr29ytBiYeLzAGIo0qk3Ujob0SDk8TiSaM5WQzNg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@jridgewell/sourcemap-codec": "^1.4.15"
|
||||
}
|
||||
@@ -8880,7 +8881,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.27.6"
|
||||
},
|
||||
@@ -9357,6 +9357,7 @@
|
||||
"resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
|
||||
"integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "^1.0.6"
|
||||
}
|
||||
@@ -9677,7 +9678,6 @@
|
||||
"integrity": "sha512-Pcfm3eZ+eO4JdZCXthW9tCDT3nF4K+9dmeZ+5X39n+Kqz0DDIABRP5CAEOHRFZk8RGuC2efksTJxrjp8EXCunQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@acemir/cssom": "^0.9.19",
|
||||
"@asamuzakjp/dom-selector": "^6.7.3",
|
||||
@@ -10264,7 +10264,8 @@
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
|
||||
"integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "6.0.0",
|
||||
@@ -11410,7 +11411,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -11690,7 +11690,6 @@
|
||||
"resolved": "https://registry.npmjs.org/preact/-/preact-10.27.2.tgz",
|
||||
"integrity": "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/preact"
|
||||
@@ -12073,7 +12072,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
|
||||
"integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -12083,7 +12081,6 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",
|
||||
"integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
@@ -13595,6 +13592,7 @@
|
||||
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz",
|
||||
"integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
@@ -13803,7 +13801,6 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -14105,7 +14102,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -14187,7 +14183,6 @@
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"napi-postinstall": "^0.3.0"
|
||||
},
|
||||
@@ -14392,7 +14387,6 @@
|
||||
"integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.25.0",
|
||||
"fdir": "^6.5.0",
|
||||
@@ -14544,7 +14538,6 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -14558,7 +14551,6 @@
|
||||
"integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/chai": "^5.2.2",
|
||||
"@vitest/expect": "3.2.4",
|
||||
@@ -15170,7 +15162,8 @@
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.4.tgz",
|
||||
"integrity": "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/zod": {
|
||||
"version": "3.25.76",
|
||||
|
||||
+20
-19
@@ -7,25 +7,26 @@
|
||||
"dependencies": {
|
||||
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@embedpdf/core": "^1.4.1",
|
||||
"@embedpdf/engines": "^1.4.1",
|
||||
"@embedpdf/plugin-annotation": "^1.4.1",
|
||||
"@embedpdf/plugin-bookmark": "^1.4.1",
|
||||
"@embedpdf/plugin-export": "^1.4.1",
|
||||
"@embedpdf/plugin-history": "^1.4.1",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.4.1",
|
||||
"@embedpdf/plugin-loader": "^1.4.1",
|
||||
"@embedpdf/plugin-pan": "^1.4.1",
|
||||
"@embedpdf/plugin-render": "^1.4.1",
|
||||
"@embedpdf/plugin-rotate": "^1.4.1",
|
||||
"@embedpdf/plugin-scroll": "^1.4.1",
|
||||
"@embedpdf/plugin-search": "^1.4.1",
|
||||
"@embedpdf/plugin-selection": "^1.4.1",
|
||||
"@embedpdf/plugin-spread": "^1.4.1",
|
||||
"@embedpdf/plugin-thumbnail": "^1.4.1",
|
||||
"@embedpdf/plugin-tiling": "^1.4.1",
|
||||
"@embedpdf/plugin-viewport": "^1.4.1",
|
||||
"@embedpdf/plugin-zoom": "^1.4.1",
|
||||
"@embedpdf/core": "^1.5.0",
|
||||
"@embedpdf/engines": "^1.5.0",
|
||||
"@embedpdf/plugin-annotation": "^1.5.0",
|
||||
"@embedpdf/plugin-bookmark": "^1.5.0",
|
||||
"@embedpdf/plugin-export": "^1.5.0",
|
||||
"@embedpdf/plugin-history": "^1.5.0",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.5.0",
|
||||
"@embedpdf/plugin-loader": "^1.5.0",
|
||||
"@embedpdf/plugin-pan": "^1.5.0",
|
||||
"@embedpdf/plugin-print": "^1.5.0",
|
||||
"@embedpdf/plugin-render": "^1.5.0",
|
||||
"@embedpdf/plugin-rotate": "^1.5.0",
|
||||
"@embedpdf/plugin-scroll": "^1.5.0",
|
||||
"@embedpdf/plugin-search": "^1.5.0",
|
||||
"@embedpdf/plugin-selection": "^1.5.0",
|
||||
"@embedpdf/plugin-spread": "^1.5.0",
|
||||
"@embedpdf/plugin-thumbnail": "^1.5.0",
|
||||
"@embedpdf/plugin-tiling": "^1.5.0",
|
||||
"@embedpdf/plugin-viewport": "^1.5.0",
|
||||
"@embedpdf/plugin-zoom": "^1.5.0",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@iconify/react": "^6.0.2",
|
||||
|
||||
@@ -3899,6 +3899,7 @@ toggleSidebar = "Toggle Sidebar"
|
||||
exportSelected = "Export Selected Pages"
|
||||
toggleAnnotations = "Toggle Annotations Visibility"
|
||||
annotationMode = "Toggle Annotation Mode"
|
||||
print = "Print PDF"
|
||||
draw = "Draw"
|
||||
save = "Save"
|
||||
saveChanges = "Save Changes"
|
||||
|
||||
@@ -3,7 +3,7 @@ import { AppProviders } from "@app/components/AppProviders";
|
||||
import { AppLayout } from "@app/components/AppLayout";
|
||||
import { LoadingFallback } from "@app/components/shared/LoadingFallback";
|
||||
import HomePage from "@app/pages/HomePage";
|
||||
import OnboardingTour from "@app/components/onboarding/OnboardingTour";
|
||||
import Onboarding from "@app/components/onboarding/Onboarding";
|
||||
|
||||
// Import global styles
|
||||
import "@app/styles/tailwind.css";
|
||||
@@ -19,7 +19,7 @@ export default function App() {
|
||||
<AppProviders>
|
||||
<AppLayout>
|
||||
<HomePage />
|
||||
<OnboardingTour />
|
||||
<Onboarding />
|
||||
</AppLayout>
|
||||
</AppProviders>
|
||||
</Suspense>
|
||||
|
||||
@@ -12,10 +12,8 @@ import { AppConfigProvider, AppConfigProviderProps, AppConfigRetryOptions } from
|
||||
import { RightRailProvider } from "@app/contexts/RightRailContext";
|
||||
import { ViewerProvider } from "@app/contexts/ViewerContext";
|
||||
import { SignatureProvider } from "@app/contexts/SignatureContext";
|
||||
import { OnboardingProvider } from "@app/contexts/OnboardingContext";
|
||||
import { TourOrchestrationProvider } from "@app/contexts/TourOrchestrationContext";
|
||||
import { AdminTourOrchestrationProvider } from "@app/contexts/AdminTourOrchestrationContext";
|
||||
import { ChatbotProvider } from "@app/contexts/ChatbotContext";
|
||||
import { PageEditorProvider } from "@app/contexts/PageEditorContext";
|
||||
import { BannerProvider } from "@app/contexts/BannerContext";
|
||||
import ErrorBoundary from "@app/components/shared/ErrorBoundary";
|
||||
@@ -78,7 +76,6 @@ export function AppProviders({ children, appConfigRetryOptions, appConfigProvide
|
||||
<RainbowThemeProvider>
|
||||
<ErrorBoundary>
|
||||
<BannerProvider>
|
||||
<OnboardingProvider>
|
||||
<AppConfigProvider
|
||||
retryOptions={appConfigRetryOptions}
|
||||
{...appConfigProviderProps}
|
||||
@@ -99,9 +96,7 @@ export function AppProviders({ children, appConfigRetryOptions, appConfigProvide
|
||||
<RightRailProvider>
|
||||
<TourOrchestrationProvider>
|
||||
<AdminTourOrchestrationProvider>
|
||||
<ChatbotProvider>
|
||||
{children}
|
||||
</ChatbotProvider>
|
||||
{children}
|
||||
</AdminTourOrchestrationProvider>
|
||||
</TourOrchestrationProvider>
|
||||
</RightRailProvider>
|
||||
@@ -116,7 +111,6 @@ export function AppProviders({ children, appConfigRetryOptions, appConfigProvide
|
||||
</ToolRegistryProvider>
|
||||
</FileContextProvider>
|
||||
</AppConfigProvider>
|
||||
</OnboardingProvider>
|
||||
</BannerProvider>
|
||||
</ErrorBoundary>
|
||||
</RainbowThemeProvider>
|
||||
|
||||
@@ -1,644 +0,0 @@
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';
|
||||
import {
|
||||
Badge,
|
||||
Box,
|
||||
Button,
|
||||
Divider,
|
||||
Group,
|
||||
Modal,
|
||||
ScrollArea,
|
||||
Select,
|
||||
Stack,
|
||||
Switch,
|
||||
Text,
|
||||
Textarea,
|
||||
} from '@mantine/core';
|
||||
import { useMediaQuery, useViewportSize } from '@mantine/hooks';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import SmartToyRoundedIcon from '@mui/icons-material/SmartToyRounded';
|
||||
import WarningAmberRoundedIcon from '@mui/icons-material/WarningAmberRounded';
|
||||
import SendRoundedIcon from '@mui/icons-material/SendRounded';
|
||||
import RefreshRoundedIcon from '@mui/icons-material/RefreshRounded';
|
||||
|
||||
import { useChatbot } from '@app/contexts/ChatbotContext';
|
||||
import { useFileState } from '@app/contexts/FileContext';
|
||||
import {
|
||||
ChatbotMessageResponse,
|
||||
ChatbotSessionInfo,
|
||||
ChatbotUsageSummary,
|
||||
sendChatbotPrompt,
|
||||
} from '@app/services/chatbotService';
|
||||
import { useToast } from '@app/components/toast';
|
||||
import type { StirlingFile } from '@app/types/fileContext';
|
||||
import { useSidebarContext } from '@app/contexts/SidebarContext';
|
||||
|
||||
interface ChatMessage {
|
||||
id: string;
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
confidence?: number;
|
||||
modelUsed?: string;
|
||||
createdAt: Date;
|
||||
documentId?: string;
|
||||
documentName?: string;
|
||||
}
|
||||
|
||||
function createMessageId() {
|
||||
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
return `msg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 7)}`;
|
||||
}
|
||||
|
||||
const MAX_PROMPT_CHARS = 4000;
|
||||
const ALPHA_ACK_KEY = 'stirling.chatbot.alphaAck';
|
||||
|
||||
const ChatbotDrawer = () => {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
const { width: viewportWidth, height: viewportHeight } = useViewportSize();
|
||||
const {
|
||||
isOpen,
|
||||
closeChat,
|
||||
preferredFileId,
|
||||
setPreferredFileId,
|
||||
sessions: preparedSessions,
|
||||
requestPreprocessing,
|
||||
} = useChatbot();
|
||||
const { selectors } = useFileState();
|
||||
const { sidebarRefs } = useSidebarContext();
|
||||
const { show } = useToast();
|
||||
const files = selectors.getFiles();
|
||||
const [selectedFileId, setSelectedFileId] = useState<string | undefined>();
|
||||
const [alphaAccepted, setAlphaAccepted] = useState(false);
|
||||
const [runOcr, setRunOcr] = useState(false);
|
||||
const [isStartingSession, setIsStartingSession] = useState(false);
|
||||
const [isSendingMessage, setIsSendingMessage] = useState(false);
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [prompt, setPrompt] = useState('');
|
||||
const [warnings, setWarnings] = useState<string[]>([]);
|
||||
const scrollViewportRef = useRef<HTMLDivElement>(null);
|
||||
const [panelAnchor, setPanelAnchor] = useState<{ right: number; top: number } | null>(null);
|
||||
const usageAlertState = useRef<'none' | 'warned' | 'limit'>('none');
|
||||
|
||||
const selectedFile = useMemo<StirlingFile | undefined>(
|
||||
() => files.find((file) => file.fileId === selectedFileId),
|
||||
[files, selectedFileId]
|
||||
);
|
||||
const selectedSessionEntry = selectedFileId
|
||||
? preparedSessions[selectedFileId]
|
||||
: undefined;
|
||||
const sessionStatus = selectedSessionEntry?.status ?? 'idle';
|
||||
const sessionError = selectedSessionEntry?.error;
|
||||
const sessionInfo: ChatbotSessionInfo | null = selectedSessionEntry?.session ?? null;
|
||||
const selectedDocumentName = selectedFile?.name ?? selectedSessionEntry?.fileName;
|
||||
const contextStats =
|
||||
selectedSessionEntry?.status === 'ready' && selectedSessionEntry?.characterCount !== undefined
|
||||
? {
|
||||
pageCount: selectedSessionEntry.pageCount ?? 0,
|
||||
characterCount: selectedSessionEntry.characterCount ?? 0,
|
||||
}
|
||||
: null;
|
||||
const preparationWarnings = selectedSessionEntry?.warnings ?? [];
|
||||
const derivedStatusMessage = useMemo(() => {
|
||||
if (!alphaAccepted) {
|
||||
return t('chatbot.autoSyncPrompt', 'Acknowledge the alpha notice to start syncing automatically.');
|
||||
}
|
||||
if (sessionStatus === 'processing' || isStartingSession) {
|
||||
return t('chatbot.status.syncing', 'Preparing document for chat…');
|
||||
}
|
||||
if (sessionStatus === 'error') {
|
||||
return sessionError || t('chatbot.errors.preprocessing', 'Unable to prepare this document.');
|
||||
}
|
||||
if (sessionStatus === 'unsupported') {
|
||||
return sessionError || t('chatbot.errors.unsupported', 'Unsupported document type.');
|
||||
}
|
||||
return null;
|
||||
}, [alphaAccepted, sessionStatus, sessionError, isStartingSession, t]);
|
||||
const assistantWarnings = useMemo(
|
||||
() => [...preparationWarnings, ...warnings.filter(Boolean)],
|
||||
[preparationWarnings, warnings]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
return;
|
||||
}
|
||||
const storedAck =
|
||||
typeof window !== 'undefined'
|
||||
? window.localStorage.getItem(ALPHA_ACK_KEY) === 'true'
|
||||
: false;
|
||||
setAlphaAccepted(storedAck);
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredFileId) {
|
||||
setSelectedFileId(preferredFileId);
|
||||
setPreferredFileId(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedFileId && files.length > 0) {
|
||||
setSelectedFileId(files[0].fileId);
|
||||
}
|
||||
}, [isOpen, preferredFileId, setPreferredFileId, files, selectedFileId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
return;
|
||||
}
|
||||
if (scrollViewportRef.current) {
|
||||
scrollViewportRef.current.scrollTo({
|
||||
top: scrollViewportRef.current.scrollHeight,
|
||||
behavior: 'smooth',
|
||||
});
|
||||
}
|
||||
}, [messages, isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
usageAlertState.current = 'none';
|
||||
if (sessionInfo) {
|
||||
maybeShowUsageWarning(sessionInfo.usageSummary);
|
||||
}
|
||||
}, [sessionInfo?.sessionId]);
|
||||
|
||||
const maybeShowUsageWarning = (usage?: ChatbotUsageSummary | null) => {
|
||||
if (!usage) {
|
||||
return;
|
||||
}
|
||||
if (usage.limitExceeded && usageAlertState.current !== 'limit') {
|
||||
usageAlertState.current = 'limit';
|
||||
show({
|
||||
alertType: 'warning',
|
||||
title: t('chatbot.usage.limitReachedTitle', 'Chatbot limit reached'),
|
||||
body: t(
|
||||
'chatbot.usage.limitReachedBody',
|
||||
'You have exceeded the current monthly allocation for the chatbot. Further responses may be throttled.'
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (usage.nearingLimit && usageAlertState.current === 'none') {
|
||||
usageAlertState.current = 'warned';
|
||||
show({
|
||||
alertType: 'warning',
|
||||
title: t('chatbot.usage.nearingLimitTitle', 'Approaching usage limit'),
|
||||
body: t(
|
||||
'chatbot.usage.nearingLimitBody',
|
||||
'You are nearing your monthly chatbot allocation. Consider limiting very large requests.'
|
||||
),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (isMobile || !isOpen) {
|
||||
setPanelAnchor(null);
|
||||
return;
|
||||
}
|
||||
const panelEl = sidebarRefs.toolPanelRef.current;
|
||||
if (!panelEl) {
|
||||
setPanelAnchor(null);
|
||||
return;
|
||||
}
|
||||
const updateAnchor = () => {
|
||||
const rect = panelEl.getBoundingClientRect();
|
||||
setPanelAnchor({
|
||||
right: rect.right,
|
||||
top: rect.top,
|
||||
});
|
||||
};
|
||||
updateAnchor();
|
||||
const observer = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => updateAnchor()) : null;
|
||||
observer?.observe(panelEl);
|
||||
const handleResize = () => updateAnchor();
|
||||
window.addEventListener('resize', handleResize);
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener('resize', handleResize);
|
||||
};
|
||||
}, [isMobile, isOpen, sidebarRefs.toolPanelRef]);
|
||||
|
||||
const ensureFileSelected = () => {
|
||||
if (!selectedFile) {
|
||||
show({
|
||||
alertType: 'warning',
|
||||
title: t('chatbot.toasts.noFileTitle', 'No PDF selected'),
|
||||
body: t('chatbot.toasts.noFileBody', 'Please choose a document before starting the chatbot.'),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleAlphaAccept = (checked: boolean) => {
|
||||
setAlphaAccepted(checked);
|
||||
if (typeof window !== 'undefined') {
|
||||
if (checked) {
|
||||
window.localStorage.setItem(ALPHA_ACK_KEY, 'true');
|
||||
} else {
|
||||
window.localStorage.removeItem(ALPHA_ACK_KEY);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleManualPrepare = async (forceOcr?: boolean) => {
|
||||
if (!ensureFileSelected() || !selectedFileId) {
|
||||
return;
|
||||
}
|
||||
setIsStartingSession(true);
|
||||
try {
|
||||
await requestPreprocessing(selectedFileId, { force: true, forceOcr: forceOcr ?? runOcr });
|
||||
usageAlertState.current = 'none';
|
||||
} catch (error) {
|
||||
console.error('[Chatbot] Failed to prepare document', error);
|
||||
show({
|
||||
alertType: 'error',
|
||||
title: t('chatbot.toasts.failedSessionTitle', 'Could not prepare document'),
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
} finally {
|
||||
setIsStartingSession(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSendMessage = async () => {
|
||||
if (!sessionInfo || sessionStatus !== 'ready') {
|
||||
show({
|
||||
alertType: 'neutral',
|
||||
title: t('chatbot.toasts.noSessionTitle', 'Sync your document first'),
|
||||
body: t('chatbot.toasts.noSessionBody', 'Send your PDF to the chatbot before asking questions.'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!prompt.trim()) {
|
||||
return;
|
||||
}
|
||||
const trimmedPrompt = prompt.slice(0, MAX_PROMPT_CHARS);
|
||||
const userMessage: ChatMessage = {
|
||||
id: createMessageId(),
|
||||
role: 'user',
|
||||
content: trimmedPrompt,
|
||||
createdAt: new Date(),
|
||||
documentId: selectedFileId,
|
||||
documentName: selectedDocumentName,
|
||||
};
|
||||
setMessages((prev) => [...prev, userMessage]);
|
||||
setPrompt('');
|
||||
setIsSendingMessage(true);
|
||||
|
||||
try {
|
||||
const reply = await sendChatbotPrompt({
|
||||
sessionId: sessionInfo.sessionId,
|
||||
prompt: trimmedPrompt,
|
||||
allowEscalation: true,
|
||||
});
|
||||
maybeShowUsageWarning(reply.usageSummary);
|
||||
setWarnings(reply.warnings ?? []);
|
||||
const assistant = convertAssistantMessage(reply);
|
||||
setMessages((prev) => [...prev, assistant]);
|
||||
} catch (error) {
|
||||
console.error('[Chatbot] Failed to send prompt', error);
|
||||
show({
|
||||
alertType: 'error',
|
||||
title: t('chatbot.toasts.failedPromptTitle', 'Unable to ask question'),
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
// Revert optimistic user message
|
||||
setMessages((prev) => prev.filter((message) => message.id !== userMessage.id));
|
||||
} finally {
|
||||
setIsSendingMessage(false);
|
||||
}
|
||||
};
|
||||
|
||||
const convertAssistantMessage = (reply: ChatbotMessageResponse): ChatMessage => ({
|
||||
id: createMessageId(),
|
||||
role: 'assistant',
|
||||
content: reply.answer,
|
||||
confidence: reply.confidence,
|
||||
modelUsed: reply.modelUsed,
|
||||
createdAt: new Date(),
|
||||
documentId: selectedFileId,
|
||||
documentName: selectedDocumentName,
|
||||
});
|
||||
|
||||
const fileOptions = useMemo(
|
||||
() =>
|
||||
files.map((file) => ({
|
||||
value: file.fileId,
|
||||
label: `${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`,
|
||||
})),
|
||||
[files]
|
||||
);
|
||||
|
||||
const disablePromptInput =
|
||||
!sessionInfo || sessionStatus !== 'ready' || isStartingSession || isSendingMessage;
|
||||
const canSend = !disablePromptInput && prompt.trim().length > 0;
|
||||
|
||||
const handlePromptKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (
|
||||
event.key === 'Enter' &&
|
||||
!event.shiftKey &&
|
||||
!event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey
|
||||
) {
|
||||
if (canSend) {
|
||||
event.preventDefault();
|
||||
handleSendMessage();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const drawerTitle = (
|
||||
<Group gap="xs">
|
||||
<SmartToyRoundedIcon fontSize="small" />
|
||||
<Text fw={600}>{t('chatbot.title', 'Stirling PDF Bot')}</Text>
|
||||
<Badge color="yellow" size="sm">{t('chatbot.alphaBadge', 'Alpha')}</Badge>
|
||||
</Group>
|
||||
);
|
||||
|
||||
|
||||
const safeViewportWidth =
|
||||
viewportWidth || (typeof window !== 'undefined' ? window.innerWidth : 1280);
|
||||
const safeViewportHeight =
|
||||
viewportHeight || (typeof window !== 'undefined' ? window.innerHeight : 900);
|
||||
const desktopLeft = !isMobile ? (panelAnchor ? panelAnchor.right + 16 : 280) : undefined;
|
||||
const desktopBottom = !isMobile ? 24 : undefined;
|
||||
const desktopWidth = !isMobile
|
||||
? Math.min(440, Math.max(320, safeViewportWidth - (desktopLeft ?? 24) - 240))
|
||||
: undefined;
|
||||
const desktopHeightPx = !isMobile
|
||||
? Math.max(520, Math.min(safeViewportHeight - 48, Math.round(safeViewportHeight * 0.85)))
|
||||
: undefined;
|
||||
|
||||
const renderMessageBubble = (message: ChatMessage) => {
|
||||
const isUser = message.role === 'user';
|
||||
const bubbleColor = isUser ? '#1f7ae0' : '#f3f4f6';
|
||||
const textColor = isUser ? '#fff' : '#1f1f1f';
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={message.id + message.role + message.createdAt.getTime()}
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: isUser ? 'flex-end' : 'flex-start',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
p="sm"
|
||||
maw="85%"
|
||||
bg={bubbleColor}
|
||||
style={{
|
||||
borderRadius: 14,
|
||||
borderTopRightRadius: isUser ? 4 : 14,
|
||||
borderTopLeftRadius: isUser ? 14 : 4,
|
||||
boxShadow: '0 2px 12px rgba(16,24,40,0.06)',
|
||||
}}
|
||||
>
|
||||
<Group justify="space-between" mb={4} gap="xs" align="flex-start">
|
||||
<Text size="xs" c={isUser ? 'rgba(255,255,255,0.8)' : 'dimmed'} tt="uppercase">
|
||||
{isUser ? t('chatbot.userLabel', 'You') : t('chatbot.botLabel', 'Stirling Bot')}
|
||||
</Text>
|
||||
{!isUser && message.confidence !== undefined && (
|
||||
<Badge
|
||||
size="xs"
|
||||
variant="light"
|
||||
color={message.confidence >= 0.6 ? 'green' : 'yellow'}
|
||||
>
|
||||
{t('chatbot.confidence', 'Confidence: {{value}}%', {
|
||||
value: Math.round(message.confidence * 100),
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
<Text size="sm" c={textColor} style={{ whiteSpace: 'pre-wrap' }}>
|
||||
{message.content}
|
||||
</Text>
|
||||
{!isUser && message.modelUsed && (
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{t('chatbot.modelTag', 'Model: {{name}}', { name: message.modelUsed })}
|
||||
</Text>
|
||||
)}
|
||||
{message.documentName && (
|
||||
<Badge
|
||||
size="xs"
|
||||
variant="light"
|
||||
color={isUser ? 'blue' : 'gray'}
|
||||
mt={6}
|
||||
>
|
||||
{message.documentName}
|
||||
</Badge>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
opened={isOpen}
|
||||
onClose={closeChat}
|
||||
withCloseButton
|
||||
radius="lg"
|
||||
overlayProps={{ opacity: 0.5, blur: 2 }}
|
||||
fullScreen={isMobile}
|
||||
centered={isMobile}
|
||||
title={drawerTitle}
|
||||
styles={{
|
||||
content: {
|
||||
width: isMobile ? '100%' : desktopWidth,
|
||||
left: isMobile ? undefined : desktopLeft,
|
||||
right: isMobile ? 0 : undefined,
|
||||
margin: isMobile ? undefined : 0,
|
||||
top: isMobile ? undefined : undefined,
|
||||
bottom: isMobile ? 0 : desktopBottom,
|
||||
position: isMobile ? undefined : 'fixed',
|
||||
height: isMobile ? '100%' : desktopHeightPx ? `${desktopHeightPx}px` : '75vh',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
body: {
|
||||
paddingTop: 'var(--mantine-spacing-md)',
|
||||
paddingBottom: 'var(--mantine-spacing-md)',
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
},
|
||||
}}
|
||||
transitionProps={{ transition: 'slide-left', duration: 200 }}
|
||||
>
|
||||
<Stack gap="sm" h="100%" style={{ minHeight: 0 }}>
|
||||
<Box
|
||||
p="sm"
|
||||
style={{
|
||||
border: '1px solid var(--border-subtle)',
|
||||
borderRadius: 8,
|
||||
backgroundColor: 'var(--bg-subtle)',
|
||||
display: 'flex',
|
||||
gap: '0.5rem',
|
||||
alignItems: 'flex-start',
|
||||
}}
|
||||
>
|
||||
<WarningAmberRoundedIcon fontSize="small" style={{ color: 'var(--text-warning)' }} />
|
||||
<Box>
|
||||
<Text fw={600}>{t('chatbot.alphaTitle', 'Experimental feature')}</Text>
|
||||
<Text size="sm">
|
||||
{t(
|
||||
'chatbot.alphaDescription',
|
||||
'This chatbot is in alpha. It currently ignores images and may produce inaccurate answers.'
|
||||
)}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Group align="flex-end" justify="space-between" gap="md" wrap="wrap">
|
||||
<Select
|
||||
label={t('chatbot.fileLabel', 'Document')}
|
||||
placeholder={t('chatbot.filePlaceholder', 'Select an uploaded PDF')}
|
||||
data={fileOptions}
|
||||
value={selectedFileId}
|
||||
onChange={(value) => setSelectedFileId(value || undefined)}
|
||||
nothingFoundMessage={t('chatbot.noFiles', 'Upload a PDF from File Manager to start chatting.')}
|
||||
style={{ flex: '1 1 200px' }}
|
||||
/>
|
||||
<Stack gap={4} style={{ minWidth: 180 }}>
|
||||
<Switch
|
||||
checked={alphaAccepted}
|
||||
onChange={(event) => handleAlphaAccept(event.currentTarget.checked)}
|
||||
label={t('chatbot.acceptAlphaLabel', 'I acknowledge this experimental feature')}
|
||||
/>
|
||||
<Switch
|
||||
checked={runOcr}
|
||||
onChange={(event) => setRunOcr(event.currentTarget.checked)}
|
||||
label={t('chatbot.ocrToggle', 'Run OCR before extracting text')}
|
||||
/>
|
||||
</Stack>
|
||||
</Group>
|
||||
|
||||
<Button
|
||||
fullWidth
|
||||
variant="filled"
|
||||
leftSection={<RefreshRoundedIcon fontSize="small" />}
|
||||
loading={isStartingSession || sessionStatus === 'processing'}
|
||||
onClick={() => handleManualPrepare()}
|
||||
disabled={!selectedFile || !alphaAccepted || sessionStatus === 'processing'}
|
||||
>
|
||||
{sessionStatus === 'ready'
|
||||
? t('chatbot.refreshButton', 'Reprocess document')
|
||||
: t('chatbot.startButton', 'Prepare document for chat')}
|
||||
</Button>
|
||||
|
||||
{derivedStatusMessage && (
|
||||
<Box
|
||||
p="sm"
|
||||
style={{
|
||||
border: '1px solid var(--border-subtle)',
|
||||
borderRadius: 8,
|
||||
backgroundColor: 'var(--bg-muted)',
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
size="sm"
|
||||
c={
|
||||
sessionStatus === 'error' || sessionStatus === 'unsupported'
|
||||
? 'var(--text-warning)'
|
||||
: 'blue'
|
||||
}
|
||||
>
|
||||
{derivedStatusMessage}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{sessionInfo && contextStats && (
|
||||
<Box>
|
||||
<Text fw={600}>{t('chatbot.sessionSummary', 'Context summary')}</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t('chatbot.contextDetails', '{{pages}} pages · {{chars}} characters synced', {
|
||||
pages: contextStats.pageCount,
|
||||
chars: contextStats.characterCount.toLocaleString(),
|
||||
})}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Divider label={t('chatbot.conversationTitle', 'Conversation')} />
|
||||
|
||||
<Box style={{ flex: 1, minHeight: 0 }}>
|
||||
<ScrollArea viewportRef={scrollViewportRef} style={{ height: '100%' }}>
|
||||
<Stack gap="sm" pr="xs">
|
||||
{assistantWarnings.length > 0 &&
|
||||
assistantWarnings.map((warning) => (
|
||||
<Box
|
||||
key={warning}
|
||||
p="sm"
|
||||
bg="var(--bg-muted)"
|
||||
style={{ borderRadius: 12, border: '1px dashed var(--border-subtle)' }}
|
||||
>
|
||||
<Group gap="xs" align="flex-start">
|
||||
<WarningAmberRoundedIcon fontSize="small" style={{ color: 'var(--text-warning)' }} />
|
||||
<Text size="sm">{warning}</Text>
|
||||
</Group>
|
||||
</Box>
|
||||
))}
|
||||
{messages.length === 0 && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t('chatbot.emptyState', 'Ask a question about your PDF to start the conversation.')}
|
||||
</Text>
|
||||
)}
|
||||
{messages.map(renderMessageBubble)}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
</Box>
|
||||
|
||||
<Stack
|
||||
gap="xs"
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
border: '1px solid var(--border-subtle)',
|
||||
borderRadius: 12,
|
||||
padding: '0.75rem',
|
||||
background: 'var(--bg-toolbar)',
|
||||
}}
|
||||
>
|
||||
<Textarea
|
||||
placeholder={t('chatbot.promptPlaceholder', 'Ask anything about this PDF…')}
|
||||
minRows={2}
|
||||
autosize
|
||||
maxRows={6}
|
||||
value={prompt}
|
||||
maxLength={MAX_PROMPT_CHARS}
|
||||
onChange={(event) => setPrompt(event.currentTarget.value)}
|
||||
disabled={disablePromptInput}
|
||||
onKeyDown={handlePromptKeyDown}
|
||||
/>
|
||||
<Group justify="space-between">
|
||||
<Text size="xs" c="dimmed">
|
||||
{t('chatbot.promptCounter', '{{used}} / {{limit}} characters', {
|
||||
used: prompt.length,
|
||||
limit: MAX_PROMPT_CHARS,
|
||||
})}
|
||||
</Text>
|
||||
<Button
|
||||
rightSection={<SendRoundedIcon fontSize="small" />}
|
||||
onClick={handleSendMessage}
|
||||
loading={isSendingMessage}
|
||||
disabled={!canSend}
|
||||
>
|
||||
{t('chatbot.sendButton', 'Send')}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Modal>
|
||||
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChatbotDrawer;
|
||||
@@ -1,33 +0,0 @@
|
||||
import { FLOW_SEQUENCES, type SlideId } from '@app/components/onboarding/onboardingFlowConfig';
|
||||
|
||||
export type FlowType = 'login-admin' | 'login-user' | 'no-login' | 'no-login-admin';
|
||||
|
||||
export interface FlowConfig {
|
||||
type: FlowType;
|
||||
ids: SlideId[];
|
||||
}
|
||||
|
||||
export function resolveFlow(enableLogin: boolean, isAdmin: boolean, selfReportedAdmin: boolean): FlowConfig {
|
||||
if (!enableLogin) {
|
||||
return selfReportedAdmin
|
||||
? {
|
||||
type: 'no-login-admin',
|
||||
ids: [...FLOW_SEQUENCES.noLoginBase, ...FLOW_SEQUENCES.noLoginAdmin],
|
||||
}
|
||||
: {
|
||||
type: 'no-login',
|
||||
ids: FLOW_SEQUENCES.noLoginBase,
|
||||
};
|
||||
}
|
||||
|
||||
return isAdmin
|
||||
? {
|
||||
type: 'login-admin',
|
||||
ids: FLOW_SEQUENCES.loginAdmin,
|
||||
}
|
||||
: {
|
||||
type: 'login-user',
|
||||
ids: FLOW_SEQUENCES.loginUser,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ButtonDefinition, type FlowState } from '@app/components/onboarding/onb
|
||||
import type { LicenseNotice } from '@app/types/types';
|
||||
import type { ButtonAction } from '@app/components/onboarding/onboardingFlowConfig';
|
||||
|
||||
interface RenderButtonsProps {
|
||||
interface SlideButtonsProps {
|
||||
slideDefinition: {
|
||||
buttons: ButtonDefinition[];
|
||||
id: string;
|
||||
@@ -16,7 +16,7 @@ interface RenderButtonsProps {
|
||||
onAction: (action: ButtonAction) => void;
|
||||
}
|
||||
|
||||
export function renderButtons({ slideDefinition, licenseNotice, flowState, onAction }: RenderButtonsProps) {
|
||||
export function SlideButtons({ slideDefinition, licenseNotice, flowState, onAction }: SlideButtonsProps) {
|
||||
const { t } = useTranslation();
|
||||
const leftButtons = slideDefinition.buttons.filter((btn) => btn.group === 'left');
|
||||
const rightButtons = slideDefinition.buttons.filter((btn) => btn.group === 'right');
|
||||
@@ -105,5 +105,4 @@ export function renderButtons({ slideDefinition, licenseNotice, flowState, onAct
|
||||
<Group gap={12}>{rightButtons.map(renderButton)}</Group>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { LicenseNotice } from '@app/types/types';
|
||||
|
||||
export interface InitialOnboardingModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
onRequestServerLicense?: (options?: { deferUntilTourComplete?: boolean; selfReportedAdmin?: boolean }) => void;
|
||||
onLicenseNoticeUpdate?: (licenseNotice: LicenseNotice) => void;
|
||||
}
|
||||
|
||||
export interface OnboardingState {
|
||||
step: number;
|
||||
selectedRole: 'admin' | 'user' | null;
|
||||
selfReportedAdmin: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_STATE: OnboardingState = {
|
||||
step: 0,
|
||||
selectedRole: null,
|
||||
selfReportedAdmin: false,
|
||||
};
|
||||
|
||||
-381
@@ -1,381 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useState, useRef } from 'react';
|
||||
import { usePreferences } from '@app/contexts/PreferencesContext';
|
||||
import { useOnboarding } from '@app/contexts/OnboardingContext';
|
||||
import { useOs } from '@app/hooks/useOs';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
SLIDE_DEFINITIONS,
|
||||
type ButtonAction,
|
||||
type FlowState,
|
||||
type SlideId,
|
||||
} from '@app/components/onboarding/onboardingFlowConfig';
|
||||
import type { LicenseNotice } from '@app/types/types';
|
||||
import { resolveFlow } from '@app/components/onboarding/InitialOnboardingModal/flowResolver';
|
||||
import { useServerExperience } from '@app/hooks/useServerExperience';
|
||||
import { DEFAULT_STATE, type InitialOnboardingModalProps, type OnboardingState } from '@app/components/onboarding/InitialOnboardingModal/types';
|
||||
import { DOWNLOAD_URLS } from '@app/constants/downloads';
|
||||
|
||||
interface UseInitialOnboardingStateResult {
|
||||
state: OnboardingState;
|
||||
totalSteps: number;
|
||||
slideDefinition: (typeof SLIDE_DEFINITIONS)[SlideId];
|
||||
currentSlide: ReturnType<(typeof SLIDE_DEFINITIONS)[SlideId]['createSlide']>;
|
||||
licenseNotice: LicenseNotice;
|
||||
flowState: FlowState;
|
||||
closeAndMarkSeen: () => void;
|
||||
handleButtonAction: (action: ButtonAction) => void;
|
||||
}
|
||||
|
||||
export function useInitialOnboardingState({
|
||||
opened,
|
||||
onClose,
|
||||
onRequestServerLicense,
|
||||
onLicenseNoticeUpdate,
|
||||
}: InitialOnboardingModalProps): UseInitialOnboardingStateResult | null {
|
||||
const { preferences, updatePreference } = usePreferences();
|
||||
const { startTour } = useOnboarding();
|
||||
const {
|
||||
loginEnabled: loginEnabledFromServer,
|
||||
configIsAdmin,
|
||||
totalUsers: serverTotalUsers,
|
||||
userCountResolved: serverUserCountResolved,
|
||||
freeTierLimit,
|
||||
hasPaidLicense,
|
||||
scenarioKey,
|
||||
setSelfReportedAdmin,
|
||||
isNewServer,
|
||||
} = useServerExperience();
|
||||
const osType = useOs();
|
||||
const navigate = useNavigate();
|
||||
const selectedDownloadUrlRef = useRef<string>('');
|
||||
|
||||
const [state, setState] = useState<OnboardingState>(DEFAULT_STATE);
|
||||
|
||||
const resetState = useCallback(() => {
|
||||
setState(DEFAULT_STATE);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!opened) {
|
||||
resetState();
|
||||
}
|
||||
}, [opened, resetState]);
|
||||
|
||||
const handleRoleSelect = useCallback(
|
||||
(role: 'admin' | 'user' | null) => {
|
||||
const isAdminSelection = role === 'admin';
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
selectedRole: role,
|
||||
selfReportedAdmin: isAdminSelection,
|
||||
}));
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
if (isAdminSelection) {
|
||||
window.localStorage.setItem('stirling-self-reported-admin', 'true');
|
||||
} else {
|
||||
window.localStorage.removeItem('stirling-self-reported-admin');
|
||||
}
|
||||
}
|
||||
|
||||
setSelfReportedAdmin(isAdminSelection);
|
||||
},
|
||||
[setSelfReportedAdmin],
|
||||
);
|
||||
|
||||
const closeAndMarkSeen = useCallback(() => {
|
||||
if (!preferences.hasSeenIntroOnboarding) {
|
||||
updatePreference('hasSeenIntroOnboarding', true);
|
||||
}
|
||||
onClose();
|
||||
}, [onClose, preferences.hasSeenIntroOnboarding, updatePreference]);
|
||||
|
||||
const isAdmin = configIsAdmin;
|
||||
const enableLogin = loginEnabledFromServer;
|
||||
|
||||
const effectiveEnableLogin = enableLogin;
|
||||
const effectiveIsAdmin = isAdmin;
|
||||
const shouldAssumeAdminForNewServer = Boolean(isNewServer) && !effectiveEnableLogin;
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldAssumeAdminForNewServer && !state.selfReportedAdmin) {
|
||||
handleRoleSelect('admin');
|
||||
}
|
||||
}, [handleRoleSelect, shouldAssumeAdminForNewServer, state.selfReportedAdmin]);
|
||||
|
||||
const shouldUseServerCount =
|
||||
(effectiveEnableLogin && effectiveIsAdmin) || !effectiveEnableLogin;
|
||||
const licenseUserCountFromServer =
|
||||
shouldUseServerCount && serverUserCountResolved ? serverTotalUsers : null;
|
||||
|
||||
const effectiveLicenseUserCount = licenseUserCountFromServer ?? null;
|
||||
|
||||
const os = useMemo(() => {
|
||||
switch (osType) {
|
||||
case 'windows':
|
||||
return { label: 'Windows', url: DOWNLOAD_URLS.WINDOWS };
|
||||
case 'mac-apple':
|
||||
return { label: 'Mac (Apple Silicon)', url: DOWNLOAD_URLS.MAC_APPLE_SILICON };
|
||||
case 'mac-intel':
|
||||
return { label: 'Mac (Intel)', url: DOWNLOAD_URLS.MAC_INTEL };
|
||||
case 'linux-x64':
|
||||
case 'linux-arm64':
|
||||
return { label: 'Linux', url: DOWNLOAD_URLS.LINUX_DOCS };
|
||||
default:
|
||||
return { label: '', url: '' };
|
||||
}
|
||||
}, [osType]);
|
||||
|
||||
const osOptions = useMemo(() => {
|
||||
const options = [
|
||||
{ label: 'Windows', url: DOWNLOAD_URLS.WINDOWS, value: 'windows' },
|
||||
{ label: 'Mac (Apple Silicon)', url: DOWNLOAD_URLS.MAC_APPLE_SILICON, value: 'mac-apple' },
|
||||
{ label: 'Mac (Intel)', url: DOWNLOAD_URLS.MAC_INTEL, value: 'mac-intel' },
|
||||
{ label: 'Linux', url: DOWNLOAD_URLS.LINUX_DOCS, value: 'linux' },
|
||||
];
|
||||
return options.filter(opt => opt.url);
|
||||
}, []);
|
||||
|
||||
const resolvedFlow = useMemo(
|
||||
() => resolveFlow(effectiveEnableLogin, effectiveIsAdmin, state.selfReportedAdmin),
|
||||
[effectiveEnableLogin, effectiveIsAdmin, state.selfReportedAdmin],
|
||||
);
|
||||
const shouldSkipSecurityCheck = shouldAssumeAdminForNewServer;
|
||||
const flowSlideIds = useMemo(
|
||||
() =>
|
||||
shouldSkipSecurityCheck
|
||||
? resolvedFlow.ids.filter((id) => id !== 'security-check')
|
||||
: resolvedFlow.ids,
|
||||
[resolvedFlow.ids, shouldSkipSecurityCheck],
|
||||
);
|
||||
const flowType = resolvedFlow.type;
|
||||
const totalSteps = flowSlideIds.length;
|
||||
const maxIndex = Math.max(totalSteps - 1, 0);
|
||||
|
||||
useEffect(() => {
|
||||
if (state.step >= flowSlideIds.length) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
step: Math.max(flowSlideIds.length - 1, 0),
|
||||
}));
|
||||
}
|
||||
}, [flowSlideIds.length, state.step]);
|
||||
|
||||
const currentSlideId = flowSlideIds[state.step] ?? flowSlideIds[flowSlideIds.length - 1];
|
||||
const slideDefinition = SLIDE_DEFINITIONS[currentSlideId];
|
||||
|
||||
if (!slideDefinition) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const scenarioProvidesInfo =
|
||||
scenarioKey && scenarioKey !== 'unknown' && scenarioKey !== 'licensed';
|
||||
const scenarioIndicatesAdmin = scenarioProvidesInfo
|
||||
? scenarioKey!.includes('admin')
|
||||
: state.selfReportedAdmin || effectiveIsAdmin;
|
||||
const scenarioIndicatesOverLimit = scenarioProvidesInfo
|
||||
? scenarioKey!.includes('over-limit')
|
||||
: effectiveLicenseUserCount != null && effectiveLicenseUserCount > freeTierLimit;
|
||||
const scenarioRequiresLicense =
|
||||
scenarioKey === 'licensed' ? false : scenarioKey === 'unknown' ? !hasPaidLicense : true;
|
||||
|
||||
const shouldShowServerLicenseInfo = scenarioIndicatesAdmin && scenarioRequiresLicense;
|
||||
|
||||
const licenseNotice = useMemo<LicenseNotice>(
|
||||
() => ({
|
||||
totalUsers: effectiveLicenseUserCount,
|
||||
freeTierLimit,
|
||||
isOverLimit: scenarioIndicatesOverLimit,
|
||||
requiresLicense: shouldShowServerLicenseInfo,
|
||||
}),
|
||||
[
|
||||
effectiveLicenseUserCount,
|
||||
freeTierLimit,
|
||||
scenarioIndicatesOverLimit,
|
||||
shouldShowServerLicenseInfo,
|
||||
],
|
||||
);
|
||||
|
||||
const requestServerLicenseIfNeeded = useCallback(
|
||||
(options?: { deferUntilTourComplete?: boolean; selfReportedAdmin?: boolean }) => {
|
||||
if (!shouldShowServerLicenseInfo) {
|
||||
return;
|
||||
}
|
||||
onRequestServerLicense?.(options);
|
||||
},
|
||||
[onRequestServerLicense, shouldShowServerLicenseInfo],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
onLicenseNoticeUpdate?.(licenseNotice);
|
||||
}, [licenseNotice, onLicenseNoticeUpdate]);
|
||||
|
||||
// Initialize ref with default URL
|
||||
useEffect(() => {
|
||||
if (!selectedDownloadUrlRef.current && os.url) {
|
||||
selectedDownloadUrlRef.current = os.url;
|
||||
}
|
||||
}, [os.url]);
|
||||
|
||||
const handleDownloadUrlChange = useCallback((url: string) => {
|
||||
selectedDownloadUrlRef.current = url;
|
||||
}, []);
|
||||
|
||||
const currentSlide = slideDefinition.createSlide({
|
||||
osLabel: os.label,
|
||||
osUrl: os.url,
|
||||
osOptions,
|
||||
onDownloadUrlChange: handleDownloadUrlChange,
|
||||
selectedRole: state.selectedRole,
|
||||
onRoleSelect: handleRoleSelect,
|
||||
licenseNotice,
|
||||
loginEnabled: effectiveEnableLogin,
|
||||
});
|
||||
|
||||
const goNext = useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
step: Math.min(prev.step + 1, maxIndex),
|
||||
}));
|
||||
}, [maxIndex]);
|
||||
|
||||
const goPrev = useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
step: Math.max(prev.step - 1, 0),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const launchTour = useCallback(
|
||||
(mode: 'admin' | 'tools', options?: { closeOnboardingSlides?: boolean }) => {
|
||||
if (options?.closeOnboardingSlides) {
|
||||
closeAndMarkSeen();
|
||||
}
|
||||
|
||||
startTour(mode, {
|
||||
source: 'initial-onboarding-modal',
|
||||
metadata: {
|
||||
hasCompletedOnboarding: preferences.hasCompletedOnboarding,
|
||||
toolPanelModePromptSeen: preferences.toolPanelModePromptSeen,
|
||||
selfReportedAdmin: state.selfReportedAdmin,
|
||||
},
|
||||
});
|
||||
},
|
||||
[closeAndMarkSeen, preferences.hasCompletedOnboarding, preferences.toolPanelModePromptSeen, startTour, state.selfReportedAdmin],
|
||||
);
|
||||
|
||||
const handleButtonAction = useCallback(
|
||||
(action: ButtonAction) => {
|
||||
const currentSlideIdLocal = currentSlideId;
|
||||
const shouldAutoLaunchLoginUserTour =
|
||||
flowType === 'login-user' && currentSlideIdLocal === 'desktop-install';
|
||||
|
||||
switch (action) {
|
||||
case 'next':
|
||||
if (shouldAutoLaunchLoginUserTour) {
|
||||
launchTour('tools', { closeOnboardingSlides: true });
|
||||
return;
|
||||
}
|
||||
goNext();
|
||||
return;
|
||||
case 'prev':
|
||||
goPrev();
|
||||
return;
|
||||
case 'close':
|
||||
closeAndMarkSeen();
|
||||
return;
|
||||
case 'download-selected': {
|
||||
const downloadUrl = selectedDownloadUrlRef.current || os.url || currentSlide.downloadUrl;
|
||||
if (downloadUrl) {
|
||||
window.open(downloadUrl, '_blank', 'noopener');
|
||||
}
|
||||
if (shouldAutoLaunchLoginUserTour) {
|
||||
launchTour('tools', { closeOnboardingSlides: true });
|
||||
return;
|
||||
}
|
||||
goNext();
|
||||
return;
|
||||
}
|
||||
case 'complete-close':
|
||||
updatePreference('hasCompletedOnboarding', true);
|
||||
closeAndMarkSeen();
|
||||
return;
|
||||
case 'security-next':
|
||||
if (!state.selectedRole) {
|
||||
return;
|
||||
}
|
||||
if (state.selectedRole === 'admin') {
|
||||
goNext();
|
||||
} else {
|
||||
launchTour('tools', { closeOnboardingSlides: true });
|
||||
}
|
||||
return;
|
||||
case 'launch-admin':
|
||||
requestServerLicenseIfNeeded({
|
||||
deferUntilTourComplete: true,
|
||||
selfReportedAdmin: state.selfReportedAdmin || effectiveIsAdmin,
|
||||
});
|
||||
launchTour('admin', { closeOnboardingSlides: true });
|
||||
return;
|
||||
case 'launch-tools':
|
||||
launchTour('tools', { closeOnboardingSlides: true });
|
||||
return;
|
||||
case 'launch-auto': {
|
||||
const launchMode = state.selfReportedAdmin || effectiveIsAdmin ? 'admin' : 'tools';
|
||||
if (launchMode === 'admin') {
|
||||
requestServerLicenseIfNeeded({
|
||||
deferUntilTourComplete: true,
|
||||
selfReportedAdmin: state.selfReportedAdmin || effectiveIsAdmin,
|
||||
});
|
||||
}
|
||||
launchTour(launchMode, { closeOnboardingSlides: true });
|
||||
return;
|
||||
}
|
||||
case 'skip-to-license':
|
||||
updatePreference('hasCompletedOnboarding', true);
|
||||
requestServerLicenseIfNeeded({
|
||||
deferUntilTourComplete: false,
|
||||
selfReportedAdmin: state.selfReportedAdmin || effectiveIsAdmin,
|
||||
});
|
||||
closeAndMarkSeen();
|
||||
return;
|
||||
case 'see-plans':
|
||||
closeAndMarkSeen();
|
||||
navigate('/settings/adminPlan');
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
},
|
||||
[
|
||||
closeAndMarkSeen,
|
||||
currentSlide,
|
||||
effectiveIsAdmin,
|
||||
flowType,
|
||||
goNext,
|
||||
goPrev,
|
||||
launchTour,
|
||||
navigate,
|
||||
requestServerLicenseIfNeeded,
|
||||
onRequestServerLicense,
|
||||
os.url,
|
||||
state.selectedRole,
|
||||
state.selfReportedAdmin,
|
||||
updatePreference,
|
||||
],
|
||||
);
|
||||
|
||||
const flowState: FlowState = { selectedRole: state.selectedRole };
|
||||
|
||||
return {
|
||||
state,
|
||||
totalSteps,
|
||||
slideDefinition,
|
||||
currentSlide,
|
||||
licenseNotice,
|
||||
flowState,
|
||||
closeAndMarkSeen,
|
||||
handleButtonAction,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
import { useEffect, useMemo, useCallback, useState } from 'react';
|
||||
import { type StepType } from '@reactour/tour';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import { isAuthRoute } from '@app/constants/routes';
|
||||
import { dispatchTourState } from '@app/constants/events';
|
||||
import { useOnboardingOrchestrator } from '@app/components/onboarding/orchestrator/useOnboardingOrchestrator';
|
||||
import { markStepSeen } from '@app/components/onboarding/orchestrator/onboardingStorage';
|
||||
import OnboardingTour, { type AdvanceArgs, type CloseArgs } from '@app/components/onboarding/OnboardingTour';
|
||||
import OnboardingModalSlide from '@app/components/onboarding/OnboardingModalSlide';
|
||||
import {
|
||||
useServerLicenseRequest,
|
||||
useTourRequest,
|
||||
} from '@app/components/onboarding/useOnboardingEffects';
|
||||
import { useOnboardingDownload } from '@app/components/onboarding/useOnboardingDownload';
|
||||
import { SLIDE_DEFINITIONS, type SlideId, type ButtonAction } from '@app/components/onboarding/onboardingFlowConfig';
|
||||
import ToolPanelModePrompt from '@app/components/tools/ToolPanelModePrompt';
|
||||
import { useTourOrchestration } from '@app/contexts/TourOrchestrationContext';
|
||||
import { useAdminTourOrchestration } from '@app/contexts/AdminTourOrchestrationContext';
|
||||
import { createUserStepsConfig } from '@app/components/onboarding/userStepsConfig';
|
||||
import { createAdminStepsConfig } from '@app/components/onboarding/adminStepsConfig';
|
||||
import { removeAllGlows } from '@app/components/onboarding/tourGlow';
|
||||
import { useFilesModalContext } from '@app/contexts/FilesModalContext';
|
||||
import { useServerExperience } from '@app/hooks/useServerExperience';
|
||||
import AdminAnalyticsChoiceModal from '@app/components/shared/AdminAnalyticsChoiceModal';
|
||||
import '@app/components/onboarding/OnboardingTour.css';
|
||||
|
||||
export default function Onboarding() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { state, actions } = useOnboardingOrchestrator();
|
||||
const serverExperience = useServerExperience();
|
||||
const onAuthRoute = isAuthRoute(location.pathname);
|
||||
const { currentStep, isActive, isLoading, runtimeState, activeFlow } = state;
|
||||
|
||||
const { osInfo, osOptions, setSelectedDownloadUrl, handleDownloadSelected } = useOnboardingDownload();
|
||||
const { showLicenseSlide, licenseNotice: externalLicenseNotice, closeLicenseSlide } = useServerLicenseRequest();
|
||||
const { tourRequested: externalTourRequested, requestedTourType, clearTourRequest } = useTourRequest();
|
||||
|
||||
const handleRoleSelect = useCallback((role: 'admin' | 'user' | null) => {
|
||||
actions.updateRuntimeState({ selectedRole: role });
|
||||
serverExperience.setSelfReportedAdmin(role === 'admin');
|
||||
}, [actions, serverExperience]);
|
||||
|
||||
const handlePasswordChanged = useCallback(() => {
|
||||
actions.updateRuntimeState({ requiresPasswordChange: false });
|
||||
window.location.href = '/login';
|
||||
}, [actions]);
|
||||
|
||||
const handleButtonAction = useCallback((action: ButtonAction) => {
|
||||
switch (action) {
|
||||
case 'next':
|
||||
case 'complete-close':
|
||||
actions.complete();
|
||||
break;
|
||||
case 'prev':
|
||||
actions.prev();
|
||||
break;
|
||||
case 'close':
|
||||
actions.skip();
|
||||
break;
|
||||
case 'download-selected':
|
||||
handleDownloadSelected();
|
||||
actions.complete();
|
||||
break;
|
||||
case 'security-next':
|
||||
if (!runtimeState.selectedRole) return;
|
||||
if (runtimeState.selectedRole !== 'admin') {
|
||||
actions.updateRuntimeState({ tourRequested: true, tourType: 'tools' });
|
||||
}
|
||||
actions.complete();
|
||||
break;
|
||||
case 'launch-admin':
|
||||
actions.updateRuntimeState({ tourRequested: true, tourType: 'admin' });
|
||||
actions.complete();
|
||||
break;
|
||||
case 'launch-tools':
|
||||
actions.updateRuntimeState({ tourRequested: true, tourType: 'tools' });
|
||||
actions.complete();
|
||||
break;
|
||||
case 'launch-auto': {
|
||||
const tourType = serverExperience.effectiveIsAdmin || runtimeState.selectedRole === 'admin' ? 'admin' : 'tools';
|
||||
actions.updateRuntimeState({ tourRequested: true, tourType });
|
||||
actions.complete();
|
||||
break;
|
||||
}
|
||||
case 'skip-to-license':
|
||||
markStepSeen('tour');
|
||||
actions.updateRuntimeState({ tourRequested: false });
|
||||
actions.complete();
|
||||
break;
|
||||
case 'see-plans':
|
||||
actions.complete();
|
||||
navigate('/settings/adminPlan');
|
||||
break;
|
||||
}
|
||||
}, [actions, handleDownloadSelected, navigate, runtimeState.selectedRole, serverExperience.effectiveIsAdmin]);
|
||||
|
||||
const isRTL = typeof document !== 'undefined' ? document.documentElement.dir === 'rtl' : false;
|
||||
const [isTourOpen, setIsTourOpen] = useState(false);
|
||||
|
||||
useEffect(() => dispatchTourState(isTourOpen), [isTourOpen]);
|
||||
|
||||
const { openFilesModal, closeFilesModal } = useFilesModalContext();
|
||||
const tourOrch = useTourOrchestration();
|
||||
const adminTourOrch = useAdminTourOrchestration();
|
||||
|
||||
const userStepsConfig = useMemo(
|
||||
() => createUserStepsConfig({
|
||||
t,
|
||||
actions: {
|
||||
saveWorkbenchState: tourOrch.saveWorkbenchState,
|
||||
closeFilesModal,
|
||||
backToAllTools: tourOrch.backToAllTools,
|
||||
selectCropTool: tourOrch.selectCropTool,
|
||||
loadSampleFile: tourOrch.loadSampleFile,
|
||||
switchToViewer: tourOrch.switchToViewer,
|
||||
switchToPageEditor: tourOrch.switchToPageEditor,
|
||||
switchToActiveFiles: tourOrch.switchToActiveFiles,
|
||||
selectFirstFile: tourOrch.selectFirstFile,
|
||||
pinFile: tourOrch.pinFile,
|
||||
modifyCropSettings: tourOrch.modifyCropSettings,
|
||||
executeTool: tourOrch.executeTool,
|
||||
openFilesModal,
|
||||
},
|
||||
}),
|
||||
[t, tourOrch, closeFilesModal, openFilesModal]
|
||||
);
|
||||
|
||||
const adminStepsConfig = useMemo(
|
||||
() => createAdminStepsConfig({
|
||||
t,
|
||||
actions: {
|
||||
saveAdminState: adminTourOrch.saveAdminState,
|
||||
openConfigModal: adminTourOrch.openConfigModal,
|
||||
navigateToSection: adminTourOrch.navigateToSection,
|
||||
scrollNavToSection: adminTourOrch.scrollNavToSection,
|
||||
},
|
||||
}),
|
||||
[t, adminTourOrch]
|
||||
);
|
||||
|
||||
const tourSteps = useMemo<StepType[]>(() => {
|
||||
const config = runtimeState.tourType === 'admin' ? adminStepsConfig : userStepsConfig;
|
||||
return Object.values(config);
|
||||
}, [adminStepsConfig, runtimeState.tourType, userStepsConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentStep?.id === 'tour' && !isTourOpen) {
|
||||
markStepSeen('tour');
|
||||
setIsTourOpen(true);
|
||||
}
|
||||
}, [currentStep, isTourOpen, activeFlow]);
|
||||
|
||||
useEffect(() => {
|
||||
if (externalTourRequested) {
|
||||
actions.updateRuntimeState({ tourRequested: true, tourType: requestedTourType });
|
||||
markStepSeen('tour');
|
||||
setIsTourOpen(true);
|
||||
clearTourRequest();
|
||||
}
|
||||
}, [externalTourRequested, requestedTourType, actions, clearTourRequest]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTourOpen) removeAllGlows();
|
||||
return () => removeAllGlows();
|
||||
}, [isTourOpen]);
|
||||
|
||||
const finishTour = useCallback(() => {
|
||||
setIsTourOpen(false);
|
||||
if (runtimeState.tourType === 'admin') {
|
||||
adminTourOrch.restoreAdminState();
|
||||
} else {
|
||||
tourOrch.restoreWorkbenchState();
|
||||
}
|
||||
markStepSeen('tour');
|
||||
if (currentStep?.id === 'tour') actions.complete();
|
||||
}, [actions, adminTourOrch, currentStep?.id, runtimeState.tourType, tourOrch]);
|
||||
|
||||
const handleAdvanceTour = useCallback((args: AdvanceArgs) => {
|
||||
const { setCurrentStep, currentStep: tourCurrentStep, steps, setIsOpen } = args;
|
||||
if (steps && tourCurrentStep === steps.length - 1) {
|
||||
setIsOpen(false);
|
||||
finishTour();
|
||||
} else if (steps) {
|
||||
setCurrentStep((s) => (s === steps.length - 1 ? 0 : s + 1));
|
||||
}
|
||||
}, [finishTour]);
|
||||
|
||||
const handleCloseTour = useCallback((args: CloseArgs) => {
|
||||
args.setIsOpen(false);
|
||||
finishTour();
|
||||
}, [finishTour]);
|
||||
|
||||
const currentSlideDefinition = useMemo(() => {
|
||||
if (!currentStep || currentStep.type !== 'modal-slide' || !currentStep.slideId) {
|
||||
return null;
|
||||
}
|
||||
return SLIDE_DEFINITIONS[currentStep.slideId as SlideId];
|
||||
}, [currentStep]);
|
||||
|
||||
const currentSlideContent = useMemo(() => {
|
||||
if (!currentSlideDefinition) return null;
|
||||
return currentSlideDefinition.createSlide({
|
||||
osLabel: osInfo.label,
|
||||
osUrl: osInfo.url,
|
||||
osOptions,
|
||||
onDownloadUrlChange: setSelectedDownloadUrl,
|
||||
selectedRole: runtimeState.selectedRole,
|
||||
onRoleSelect: handleRoleSelect,
|
||||
licenseNotice: runtimeState.licenseNotice,
|
||||
loginEnabled: serverExperience.loginEnabled,
|
||||
firstLoginUsername: runtimeState.firstLoginUsername,
|
||||
onPasswordChanged: handlePasswordChanged,
|
||||
usingDefaultCredentials: runtimeState.usingDefaultCredentials,
|
||||
});
|
||||
}, [currentSlideDefinition, osInfo, osOptions, runtimeState.selectedRole, runtimeState.licenseNotice, handleRoleSelect, serverExperience.loginEnabled, setSelectedDownloadUrl, runtimeState.firstLoginUsername, handlePasswordChanged]);
|
||||
|
||||
const modalSlideCount = useMemo(() => {
|
||||
return activeFlow.filter((step) => step.type === 'modal-slide').length;
|
||||
}, [activeFlow]);
|
||||
|
||||
const currentModalSlideIndex = useMemo(() => {
|
||||
if (!currentStep || currentStep.type !== 'modal-slide') return 0;
|
||||
const modalSlides = activeFlow.filter((step) => step.type === 'modal-slide');
|
||||
return modalSlides.findIndex((step) => step.id === currentStep.id);
|
||||
}, [activeFlow, currentStep]);
|
||||
|
||||
if (onAuthRoute) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (showLicenseSlide) {
|
||||
const slideDefinition = SLIDE_DEFINITIONS['server-license'];
|
||||
const effectiveLicenseNotice = externalLicenseNotice || runtimeState.licenseNotice;
|
||||
const slideContent = slideDefinition.createSlide({
|
||||
osLabel: '',
|
||||
osUrl: '',
|
||||
osOptions: [],
|
||||
onDownloadUrlChange: () => {},
|
||||
selectedRole: null,
|
||||
onRoleSelect: () => {},
|
||||
licenseNotice: effectiveLicenseNotice,
|
||||
loginEnabled: serverExperience.loginEnabled,
|
||||
});
|
||||
|
||||
return (
|
||||
<OnboardingModalSlide
|
||||
slideDefinition={slideDefinition}
|
||||
slideContent={slideContent}
|
||||
runtimeState={{ ...runtimeState, licenseNotice: effectiveLicenseNotice }}
|
||||
modalSlideCount={1}
|
||||
currentModalSlideIndex={0}
|
||||
onSkip={closeLicenseSlide}
|
||||
onAction={(action) => {
|
||||
if (action === 'see-plans') {
|
||||
closeLicenseSlide();
|
||||
navigate('/settings/adminPlan');
|
||||
} else {
|
||||
closeLicenseSlide();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading || !isActive || !currentStep) {
|
||||
return (
|
||||
<OnboardingTour
|
||||
isOpen={isTourOpen}
|
||||
tourSteps={tourSteps}
|
||||
tourType={runtimeState.tourType}
|
||||
isRTL={isRTL}
|
||||
t={t}
|
||||
onAdvance={handleAdvanceTour}
|
||||
onClose={handleCloseTour}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
switch (currentStep.type) {
|
||||
case 'tool-prompt':
|
||||
return <ToolPanelModePrompt forceOpen={true} onComplete={actions.complete} />;
|
||||
|
||||
case 'tour':
|
||||
return (
|
||||
<OnboardingTour
|
||||
isOpen={true}
|
||||
tourSteps={tourSteps}
|
||||
tourType={runtimeState.tourType}
|
||||
isRTL={isRTL}
|
||||
t={t}
|
||||
onAdvance={handleAdvanceTour}
|
||||
onClose={handleCloseTour}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'analytics-modal':
|
||||
return <AdminAnalyticsChoiceModal opened={true} onClose={actions.complete} />;
|
||||
|
||||
case 'modal-slide':
|
||||
if (!currentSlideDefinition || !currentSlideContent) return null;
|
||||
return (
|
||||
<OnboardingModalSlide
|
||||
slideDefinition={currentSlideDefinition}
|
||||
slideContent={currentSlideContent}
|
||||
runtimeState={runtimeState}
|
||||
modalSlideCount={modalSlideCount}
|
||||
currentModalSlideIndex={currentModalSlideIndex}
|
||||
onSkip={actions.skip}
|
||||
onAction={handleButtonAction}
|
||||
/>
|
||||
);
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+55
-41
@@ -1,33 +1,44 @@
|
||||
/**
|
||||
* OnboardingModalSlide Component
|
||||
*
|
||||
* Renders a single modal slide in the onboarding flow.
|
||||
* Handles the hero image, content, stepper, and button actions.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Modal, Stack } from '@mantine/core';
|
||||
import DiamondOutlinedIcon from '@mui/icons-material/DiamondOutlined';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
|
||||
import type { SlideDefinition, ButtonAction } from '@app/components/onboarding/onboardingFlowConfig';
|
||||
import type { OnboardingRuntimeState } from '@app/components/onboarding/orchestrator/onboardingConfig';
|
||||
import type { SlideConfig } from '@app/types/types';
|
||||
import AnimatedSlideBackground from '@app/components/onboarding/slides/AnimatedSlideBackground';
|
||||
import OnboardingStepper from '@app/components/onboarding/OnboardingStepper';
|
||||
import { renderButtons } from '@app/components/onboarding/InitialOnboardingModal/renderButtons';
|
||||
import styles from '@app/components/onboarding/InitialOnboardingModal/InitialOnboardingModal.module.css';
|
||||
import type { InitialOnboardingModalProps } from '@app/components/onboarding/InitialOnboardingModal/types';
|
||||
import { useInitialOnboardingState } from '@app/components/onboarding/InitialOnboardingModal/useInitialOnboardingState';
|
||||
import { SlideButtons } from '@app/components/onboarding/InitialOnboardingModal/renderButtons';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { BASE_PATH } from '@app/constants/app';
|
||||
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '@app/styles/zIndex';
|
||||
import styles from '@app/components/onboarding/InitialOnboardingModal/InitialOnboardingModal.module.css';
|
||||
|
||||
export default function InitialOnboardingModal(props: InitialOnboardingModalProps) {
|
||||
const flow = useInitialOnboardingState(props);
|
||||
interface OnboardingModalSlideProps {
|
||||
slideDefinition: SlideDefinition;
|
||||
slideContent: SlideConfig;
|
||||
runtimeState: OnboardingRuntimeState;
|
||||
modalSlideCount: number;
|
||||
currentModalSlideIndex: number;
|
||||
onSkip: () => void;
|
||||
onAction: (action: ButtonAction) => void;
|
||||
}
|
||||
|
||||
if (!flow) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const {
|
||||
state,
|
||||
totalSteps,
|
||||
currentSlide,
|
||||
slideDefinition,
|
||||
licenseNotice,
|
||||
flowState,
|
||||
closeAndMarkSeen,
|
||||
handleButtonAction,
|
||||
} = flow;
|
||||
export default function OnboardingModalSlide({
|
||||
slideDefinition,
|
||||
slideContent,
|
||||
runtimeState,
|
||||
modalSlideCount,
|
||||
currentModalSlideIndex,
|
||||
onSkip,
|
||||
onAction,
|
||||
}: OnboardingModalSlideProps) {
|
||||
|
||||
const renderHero = () => {
|
||||
if (slideDefinition.hero.type === 'dual-icon') {
|
||||
@@ -48,6 +59,9 @@ export default function InitialOnboardingModal(props: InitialOnboardingModalProp
|
||||
{slideDefinition.hero.type === 'shield' && (
|
||||
<LocalIcon icon="verified-user-outline" width={64} height={64} className={styles.heroIcon} />
|
||||
)}
|
||||
{slideDefinition.hero.type === 'lock' && (
|
||||
<LocalIcon icon="lock-outline" width={64} height={64} className={styles.heroIcon} />
|
||||
)}
|
||||
{slideDefinition.hero.type === 'diamond' && <DiamondOutlinedIcon sx={{ fontSize: 64, color: '#000000' }} />}
|
||||
{slideDefinition.hero.type === 'logo' && (
|
||||
<img src={`${BASE_PATH}/branding/StirlingPDFLogoNoTextLightHC.svg`} alt="Stirling logo" />
|
||||
@@ -58,8 +72,8 @@ export default function InitialOnboardingModal(props: InitialOnboardingModalProp
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={props.opened}
|
||||
onClose={closeAndMarkSeen}
|
||||
opened={true}
|
||||
onClose={onSkip}
|
||||
closeOnClickOutside={false}
|
||||
centered
|
||||
size="lg"
|
||||
@@ -67,48 +81,48 @@ export default function InitialOnboardingModal(props: InitialOnboardingModalProp
|
||||
withCloseButton={false}
|
||||
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
|
||||
styles={{
|
||||
body: { padding: 0 },
|
||||
content: { overflow: 'hidden', border: 'none', background: 'var(--bg-surface)' },
|
||||
body: { padding: 0, maxHeight: '90vh', overflow: 'hidden' },
|
||||
content: { overflow: 'hidden', border: 'none', background: 'var(--bg-surface)', maxHeight: '90vh' },
|
||||
}}
|
||||
>
|
||||
<Stack gap={0} className={styles.modalContent}>
|
||||
<div className={styles.heroWrapper}>
|
||||
<AnimatedSlideBackground
|
||||
gradientStops={currentSlide.background.gradientStops}
|
||||
circles={currentSlide.background.circles}
|
||||
gradientStops={slideContent.background.gradientStops}
|
||||
circles={slideContent.background.circles}
|
||||
isActive
|
||||
slideKey={currentSlide.key}
|
||||
slideKey={slideContent.key}
|
||||
/>
|
||||
<div className={styles.heroLogo} key={`logo-${currentSlide.key}`}>
|
||||
<div className={styles.heroLogo} key={`logo-${slideContent.key}`}>
|
||||
{renderHero()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.modalBody}>
|
||||
<div className={styles.modalBody} style={{ overflowY: 'auto', maxHeight: 'calc(90vh - 220px)' }}>
|
||||
<Stack gap={16}>
|
||||
<div
|
||||
key={`title-${currentSlide.key}`}
|
||||
key={`title-${slideContent.key}`}
|
||||
className={`${styles.title} ${styles.titleText}`}
|
||||
>
|
||||
{currentSlide.title}
|
||||
{slideContent.title}
|
||||
</div>
|
||||
|
||||
<div className={styles.bodyText}>
|
||||
<div key={`body-${currentSlide.key}`} className={`${styles.bodyCopy} ${styles.bodyCopyInner}`}>
|
||||
{currentSlide.body}
|
||||
<div key={`body-${slideContent.key}`} className={`${styles.bodyCopy} ${styles.bodyCopyInner}`}>
|
||||
{slideContent.body}
|
||||
</div>
|
||||
<style>{`div strong{color: var(--onboarding-title); font-weight: 600;}`}</style>
|
||||
</div>
|
||||
|
||||
<OnboardingStepper totalSteps={totalSteps} activeStep={state.step} />
|
||||
<OnboardingStepper totalSteps={modalSlideCount} activeStep={currentModalSlideIndex} />
|
||||
|
||||
<div className={styles.buttonContainer}>
|
||||
{renderButtons({
|
||||
slideDefinition,
|
||||
licenseNotice,
|
||||
flowState,
|
||||
onAction: handleButtonAction,
|
||||
})}
|
||||
<SlideButtons
|
||||
slideDefinition={slideDefinition}
|
||||
licenseNotice={runtimeState.licenseNotice}
|
||||
flowState={{ selectedRole: runtimeState.selectedRole }}
|
||||
onAction={onAction}
|
||||
/>
|
||||
</div>
|
||||
</Stack>
|
||||
</div>
|
||||
@@ -1,231 +1,151 @@
|
||||
import React, { useEffect, useMemo } from "react";
|
||||
import { TourProvider, type StepType } from '@reactour/tour';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
/**
|
||||
* OnboardingTour Component
|
||||
*
|
||||
* Reusable tour wrapper that encapsulates all Reactour configuration.
|
||||
* Used by the main Onboarding component for both the 'tour' step and
|
||||
* when the tour is open but onboarding is inactive.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { TourProvider, useTour, type StepType } from '@reactour/tour';
|
||||
import { CloseButton, ActionIcon } from '@mantine/core';
|
||||
import ArrowForwardIcon from '@mui/icons-material/ArrowForward';
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import InitialOnboardingModal from '@app/components/onboarding/InitialOnboardingModal';
|
||||
import ServerLicenseModal from '@app/components/onboarding/ServerLicenseModal';
|
||||
import '@app/components/onboarding/OnboardingTour.css';
|
||||
import ToolPanelModePrompt from '@app/components/tools/ToolPanelModePrompt';
|
||||
import { useFilesModalContext } from '@app/contexts/FilesModalContext';
|
||||
import { useTourOrchestration } from '@app/contexts/TourOrchestrationContext';
|
||||
import { useAdminTourOrchestration } from '@app/contexts/AdminTourOrchestrationContext';
|
||||
import { useOnboardingFlow } from '@app/components/onboarding/hooks/useOnboardingFlow';
|
||||
import { createUserStepsConfig } from '@app/components/onboarding/userStepsConfig';
|
||||
import { createAdminStepsConfig } from '@app/components/onboarding/adminStepsConfig';
|
||||
import { removeAllGlows } from '@app/components/onboarding/tourGlow';
|
||||
import TourContent from '@app/components/onboarding/TourContent';
|
||||
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
|
||||
import '@app/components/onboarding/OnboardingTour.css';
|
||||
import i18n from "@app/i18n";
|
||||
import CheckIcon from '@mui/icons-material/Check';
|
||||
import type { TFunction } from 'i18next';
|
||||
import i18n from '@app/i18n';
|
||||
|
||||
export default function OnboardingTour() {
|
||||
const { t } = useTranslation();
|
||||
const flow = useOnboardingFlow();
|
||||
const { openFilesModal, closeFilesModal } = useFilesModalContext();
|
||||
const {
|
||||
saveWorkbenchState,
|
||||
restoreWorkbenchState,
|
||||
backToAllTools,
|
||||
selectCropTool,
|
||||
loadSampleFile,
|
||||
switchToViewer,
|
||||
switchToPageEditor,
|
||||
switchToActiveFiles,
|
||||
selectFirstFile,
|
||||
pinFile,
|
||||
modifyCropSettings,
|
||||
executeTool,
|
||||
} = useTourOrchestration();
|
||||
const {
|
||||
saveAdminState,
|
||||
restoreAdminState,
|
||||
openConfigModal,
|
||||
navigateToSection,
|
||||
scrollNavToSection,
|
||||
} = useAdminTourOrchestration();
|
||||
/**
|
||||
* TourContent - Controls the tour visibility
|
||||
* Syncs the forceOpen prop with the reactour tour state.
|
||||
*/
|
||||
function TourContent({ forceOpen = false }: { forceOpen?: boolean }) {
|
||||
const { setIsOpen, setCurrentStep } = useTour();
|
||||
const previousIsOpenRef = React.useRef(forceOpen);
|
||||
|
||||
const isRTL = typeof document !== 'undefined' ? document.documentElement.dir === 'rtl' : false;
|
||||
React.useEffect(() => {
|
||||
const wasClosedNowOpen = !previousIsOpenRef.current && forceOpen;
|
||||
previousIsOpenRef.current = forceOpen;
|
||||
|
||||
useEffect(() => {
|
||||
if (!flow.isTourOpen) {
|
||||
removeAllGlows();
|
||||
if (wasClosedNowOpen) {
|
||||
setCurrentStep(0);
|
||||
}
|
||||
return () => removeAllGlows();
|
||||
}, [flow.isTourOpen]);
|
||||
setIsOpen(forceOpen);
|
||||
}, [forceOpen, setIsOpen, setCurrentStep]);
|
||||
|
||||
const userStepsConfig = useMemo(
|
||||
() =>
|
||||
createUserStepsConfig({
|
||||
t,
|
||||
actions: {
|
||||
saveWorkbenchState,
|
||||
closeFilesModal,
|
||||
backToAllTools,
|
||||
selectCropTool,
|
||||
loadSampleFile,
|
||||
switchToViewer,
|
||||
switchToPageEditor,
|
||||
switchToActiveFiles,
|
||||
selectFirstFile,
|
||||
pinFile,
|
||||
modifyCropSettings,
|
||||
executeTool,
|
||||
openFilesModal,
|
||||
},
|
||||
}),
|
||||
[
|
||||
t,
|
||||
backToAllTools,
|
||||
closeFilesModal,
|
||||
executeTool,
|
||||
loadSampleFile,
|
||||
modifyCropSettings,
|
||||
openFilesModal,
|
||||
pinFile,
|
||||
saveWorkbenchState,
|
||||
selectCropTool,
|
||||
selectFirstFile,
|
||||
switchToActiveFiles,
|
||||
switchToPageEditor,
|
||||
switchToViewer,
|
||||
],
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const adminStepsConfig = useMemo(
|
||||
() =>
|
||||
createAdminStepsConfig({
|
||||
t,
|
||||
actions: {
|
||||
saveAdminState,
|
||||
openConfigModal,
|
||||
navigateToSection,
|
||||
scrollNavToSection,
|
||||
},
|
||||
}),
|
||||
[navigateToSection, openConfigModal, saveAdminState, scrollNavToSection, t],
|
||||
);
|
||||
interface AdvanceArgs {
|
||||
setCurrentStep: (value: number | ((prev: number) => number)) => void;
|
||||
currentStep: number;
|
||||
steps?: StepType[];
|
||||
setIsOpen: (value: boolean) => void;
|
||||
}
|
||||
|
||||
const steps = useMemo<StepType[]>(() => {
|
||||
const config = flow.tourType === 'admin' ? adminStepsConfig : userStepsConfig;
|
||||
return Object.values(config);
|
||||
}, [adminStepsConfig, flow.tourType, userStepsConfig]);
|
||||
interface CloseArgs {
|
||||
setIsOpen: (value: boolean) => void;
|
||||
}
|
||||
|
||||
const advanceTour = ({
|
||||
setCurrentStep,
|
||||
currentStep,
|
||||
steps,
|
||||
setIsOpen,
|
||||
}: {
|
||||
setCurrentStep: (value: number | ((prev: number) => number)) => void;
|
||||
currentStep: number;
|
||||
steps?: StepType[];
|
||||
setIsOpen: (value: boolean) => void;
|
||||
}) => {
|
||||
if (steps && currentStep === steps.length - 1) {
|
||||
setIsOpen(false);
|
||||
if (flow.tourType === 'admin') {
|
||||
restoreAdminState();
|
||||
} else {
|
||||
restoreWorkbenchState();
|
||||
}
|
||||
flow.handleTourCompletion();
|
||||
} else if (steps) {
|
||||
setCurrentStep((s) => (s === steps.length - 1 ? 0 : s + 1));
|
||||
}
|
||||
};
|
||||
interface OnboardingTourProps {
|
||||
tourSteps: StepType[];
|
||||
tourType: 'admin' | 'tools';
|
||||
isRTL: boolean;
|
||||
t: TFunction;
|
||||
isOpen: boolean;
|
||||
onAdvance: (args: AdvanceArgs) => void;
|
||||
onClose: (args: CloseArgs) => void;
|
||||
}
|
||||
|
||||
const handleCloseTour = ({ setIsOpen }: { setIsOpen: (value: boolean) => void }) => {
|
||||
setIsOpen(false);
|
||||
if (flow.tourType === 'admin') {
|
||||
restoreAdminState();
|
||||
} else {
|
||||
restoreWorkbenchState();
|
||||
}
|
||||
flow.handleTourCompletion();
|
||||
};
|
||||
export default function OnboardingTour({
|
||||
tourSteps,
|
||||
tourType,
|
||||
isRTL,
|
||||
t,
|
||||
isOpen,
|
||||
onAdvance,
|
||||
onClose,
|
||||
}: OnboardingTourProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<InitialOnboardingModal {...flow.initialModalProps} />
|
||||
<ToolPanelModePrompt onComplete={flow.handleToolPromptComplete} />
|
||||
<TourProvider
|
||||
key={`${flow.tourType}-${i18n.language}`}
|
||||
steps={steps}
|
||||
maskClassName={flow.maskClassName}
|
||||
onClickClose={handleCloseTour}
|
||||
onClickMask={advanceTour}
|
||||
onClickHighlighted={(e, clickProps) => {
|
||||
e.stopPropagation();
|
||||
advanceTour(clickProps);
|
||||
}}
|
||||
keyboardHandler={(e, clickProps, status) => {
|
||||
if (e.key === 'ArrowRight' && !status?.isRightDisabled && clickProps) {
|
||||
e.preventDefault();
|
||||
advanceTour(clickProps);
|
||||
} else if (e.key === 'Escape' && !status?.isEscDisabled && clickProps) {
|
||||
e.preventDefault();
|
||||
handleCloseTour(clickProps);
|
||||
}
|
||||
}}
|
||||
rtl={isRTL}
|
||||
styles={{
|
||||
popover: (base) => ({
|
||||
...base,
|
||||
backgroundColor: 'var(--mantine-color-body)',
|
||||
color: 'var(--mantine-color-text)',
|
||||
borderRadius: '8px',
|
||||
padding: '20px',
|
||||
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
|
||||
maxWidth: '400px',
|
||||
}),
|
||||
maskArea: (base) => ({
|
||||
...base,
|
||||
rx: 8,
|
||||
}),
|
||||
badge: (base) => ({
|
||||
...base,
|
||||
backgroundColor: 'var(--mantine-primary-color-filled)',
|
||||
}),
|
||||
controls: (base) => ({
|
||||
...base,
|
||||
justifyContent: 'center',
|
||||
}),
|
||||
}}
|
||||
highlightedMaskClassName="tour-highlight-glow"
|
||||
showNavigation={true}
|
||||
showBadge={false}
|
||||
showCloseButton={true}
|
||||
disableInteraction={true}
|
||||
disableDotsNavigation={false}
|
||||
prevButton={() => null}
|
||||
nextButton={({ currentStep, stepsLength, setCurrentStep, setIsOpen }) => {
|
||||
const isLast = currentStep === stepsLength - 1;
|
||||
const ArrowIcon = isRTL ? ArrowBackIcon : ArrowForwardIcon;
|
||||
return (
|
||||
<ActionIcon
|
||||
onClick={() => advanceTour({ setCurrentStep, currentStep, steps, setIsOpen })}
|
||||
variant="subtle"
|
||||
size="lg"
|
||||
aria-label={isLast ? t('onboarding.finish', 'Finish') : t('onboarding.next', 'Next')}
|
||||
>
|
||||
{isLast ? <CheckIcon /> : <ArrowIcon />}
|
||||
</ActionIcon>
|
||||
);
|
||||
}}
|
||||
components={{
|
||||
Close: ({ onClick }) => (
|
||||
<CloseButton onClick={onClick} size="md" style={{ position: 'absolute', top: '8px', right: '8px' }} />
|
||||
),
|
||||
Content: ({ content }: { content: string }) => (
|
||||
<div style={{ paddingRight: '16px' }} dangerouslySetInnerHTML={{ __html: content }} />
|
||||
),
|
||||
}}
|
||||
>
|
||||
<TourContent />
|
||||
</TourProvider>
|
||||
<ServerLicenseModal {...flow.serverLicenseModalProps} />
|
||||
</>
|
||||
<TourProvider
|
||||
key={`${tourType}-${i18n.language}`}
|
||||
steps={tourSteps}
|
||||
maskClassName={tourType === 'admin' ? 'admin-tour-mask' : undefined}
|
||||
onClickClose={onClose}
|
||||
onClickMask={onAdvance}
|
||||
onClickHighlighted={(e, clickProps) => {
|
||||
e.stopPropagation();
|
||||
onAdvance(clickProps);
|
||||
}}
|
||||
keyboardHandler={(e, clickProps, status) => {
|
||||
if (e.key === 'ArrowRight' && !status?.isRightDisabled && clickProps) {
|
||||
e.preventDefault();
|
||||
onAdvance(clickProps);
|
||||
} else if (e.key === 'Escape' && !status?.isEscDisabled && clickProps) {
|
||||
e.preventDefault();
|
||||
onClose(clickProps);
|
||||
}
|
||||
}}
|
||||
rtl={isRTL}
|
||||
styles={{
|
||||
popover: (base) => ({
|
||||
...base,
|
||||
backgroundColor: 'var(--mantine-color-body)',
|
||||
color: 'var(--mantine-color-text)',
|
||||
borderRadius: '8px',
|
||||
padding: '20px',
|
||||
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
|
||||
maxWidth: '400px',
|
||||
}),
|
||||
maskArea: (base) => ({
|
||||
...base,
|
||||
rx: 8,
|
||||
}),
|
||||
badge: (base) => ({
|
||||
...base,
|
||||
backgroundColor: 'var(--mantine-primary-color-filled)',
|
||||
}),
|
||||
controls: (base) => ({
|
||||
...base,
|
||||
justifyContent: 'center',
|
||||
}),
|
||||
}}
|
||||
highlightedMaskClassName="tour-highlight-glow"
|
||||
showNavigation={true}
|
||||
showBadge={false}
|
||||
showCloseButton={true}
|
||||
disableInteraction={true}
|
||||
disableDotsNavigation={false}
|
||||
prevButton={() => null}
|
||||
nextButton={({ currentStep: tourCurrentStep, stepsLength, setCurrentStep, setIsOpen }) => {
|
||||
const isLast = tourCurrentStep === stepsLength - 1;
|
||||
const ArrowIcon = isRTL ? ArrowBackIcon : ArrowForwardIcon;
|
||||
return (
|
||||
<ActionIcon
|
||||
onClick={() => onAdvance({ setCurrentStep, currentStep: tourCurrentStep, steps: tourSteps, setIsOpen })}
|
||||
variant="subtle"
|
||||
size="lg"
|
||||
aria-label={isLast ? t('onboarding.finish', 'Finish') : t('onboarding.next', 'Next')}
|
||||
>
|
||||
{isLast ? <CheckIcon /> : <ArrowIcon />}
|
||||
</ActionIcon>
|
||||
);
|
||||
}}
|
||||
components={{
|
||||
Close: ({ onClick }) => (
|
||||
<CloseButton onClick={onClick} size="md" style={{ position: 'absolute', top: '8px', right: '8px' }} />
|
||||
),
|
||||
Content: ({ content }: { content: string }) => (
|
||||
<div style={{ paddingRight: '16px' }} dangerouslySetInnerHTML={{ __html: content }} />
|
||||
),
|
||||
}}
|
||||
>
|
||||
<TourContent forceOpen={true} />
|
||||
</TourProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export type { AdvanceArgs, CloseArgs };
|
||||
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Modal, Button, Group, Stack } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import AnimatedSlideBackground from '@app/components/onboarding/slides/AnimatedSlideBackground';
|
||||
import ServerLicenseSlide from '@app/components/onboarding/slides/ServerLicenseSlide';
|
||||
import { LicenseNotice } from '@app/types/types';
|
||||
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '@app/styles/zIndex';
|
||||
import { BASE_PATH } from '@app/constants/app';
|
||||
import styles from '@app/components/onboarding/InitialOnboardingModal/InitialOnboardingModal.module.css';
|
||||
|
||||
interface ServerLicenseModalProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
onSeePlans?: () => void;
|
||||
licenseNotice: LicenseNotice;
|
||||
}
|
||||
|
||||
export default function ServerLicenseModal({
|
||||
opened,
|
||||
onClose,
|
||||
onSeePlans,
|
||||
licenseNotice,
|
||||
}: ServerLicenseModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const slide = React.useMemo(() => ServerLicenseSlide({ licenseNotice }), [licenseNotice]);
|
||||
const primaryLabel = licenseNotice.isOverLimit
|
||||
? t('onboarding.serverLicense.upgrade', 'Upgrade now →')
|
||||
: t('onboarding.serverLicense.seePlans', 'See Plans →');
|
||||
const secondaryLabel = t('onboarding.serverLicense.skip', 'Skip for now');
|
||||
|
||||
const handleSeePlans = () => {
|
||||
onSeePlans?.();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const secondaryStyles = {
|
||||
root: {
|
||||
background: 'var(--onboarding-secondary-button-bg)',
|
||||
border: '1px solid var(--onboarding-secondary-button-border)',
|
||||
color: 'var(--onboarding-secondary-button-text)',
|
||||
},
|
||||
};
|
||||
|
||||
const primaryStyles = {
|
||||
root: {
|
||||
background: 'var(--onboarding-primary-button-bg)',
|
||||
color: 'var(--onboarding-primary-button-text)',
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
centered
|
||||
size="lg"
|
||||
radius="lg"
|
||||
withCloseButton={false}
|
||||
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
|
||||
styles={{
|
||||
body: { padding: 0 },
|
||||
content: { overflow: 'hidden', border: 'none', background: 'var(--bg-surface)' },
|
||||
}}
|
||||
>
|
||||
<Stack gap={0}>
|
||||
<div className={styles.heroWrapper}>
|
||||
<AnimatedSlideBackground
|
||||
gradientStops={slide.background.gradientStops}
|
||||
circles={slide.background.circles}
|
||||
isActive
|
||||
slideKey={slide.key}
|
||||
/>
|
||||
<div className={styles.heroLogo}>
|
||||
<div className={styles.heroIconsContainer}>
|
||||
<div className={styles.iconWrapper}>
|
||||
<img src={`${BASE_PATH}/modern-logo/logo512.png`} alt="Stirling icon" className={styles.downloadIcon} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ padding: 24 }}>
|
||||
<Stack gap={16}>
|
||||
<div
|
||||
className={styles.title}
|
||||
style={{
|
||||
fontFamily: 'Inter, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif',
|
||||
fontWeight: 600,
|
||||
fontSize: 22,
|
||||
color: 'var(--onboarding-title)',
|
||||
}}
|
||||
>
|
||||
{slide.title}
|
||||
</div>
|
||||
<div
|
||||
className={styles.bodyCopy}
|
||||
style={{
|
||||
fontFamily: 'Inter, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif',
|
||||
fontSize: 16,
|
||||
color: 'var(--onboarding-body)',
|
||||
lineHeight: 1.5,
|
||||
}}
|
||||
>
|
||||
{slide.body}
|
||||
</div>
|
||||
<Group justify="space-between">
|
||||
<Button styles={secondaryStyles} onClick={onClose}>
|
||||
{secondaryLabel}
|
||||
</Button>
|
||||
<Button styles={primaryStyles} onClick={handleSeePlans}>
|
||||
{primaryLabel}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</div>
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import React from 'react';
|
||||
import { useTour } from '@reactour/tour';
|
||||
import { useOnboarding } from '@app/contexts/OnboardingContext';
|
||||
|
||||
export default function TourContent() {
|
||||
const { isOpen } = useOnboarding();
|
||||
const { setIsOpen, setCurrentStep } = useTour();
|
||||
const previousIsOpenRef = React.useRef(isOpen);
|
||||
|
||||
React.useEffect(() => {
|
||||
const wasClosedNowOpen = !previousIsOpenRef.current && isOpen;
|
||||
previousIsOpenRef.current = isOpen;
|
||||
|
||||
if (wasClosedNowOpen) {
|
||||
setCurrentStep(0);
|
||||
}
|
||||
setIsOpen(isOpen);
|
||||
}, [isOpen, setIsOpen, setCurrentStep]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import { Modal, Title, Text, Button, Stack, Group } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '@app/styles/zIndex';
|
||||
|
||||
interface TourWelcomeModalProps {
|
||||
opened: boolean;
|
||||
onStartTour: () => void;
|
||||
onMaybeLater: () => void;
|
||||
onDontShowAgain: () => void;
|
||||
}
|
||||
|
||||
export default function TourWelcomeModal({
|
||||
opened,
|
||||
onStartTour,
|
||||
onMaybeLater,
|
||||
onDontShowAgain,
|
||||
}: TourWelcomeModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={onMaybeLater}
|
||||
centered
|
||||
size="md"
|
||||
radius="lg"
|
||||
withCloseButton={false}
|
||||
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
|
||||
>
|
||||
<Stack gap="lg">
|
||||
<Stack gap="xs">
|
||||
<Title order={2}>
|
||||
{t('onboarding.welcomeModal.title', 'Welcome to Stirling PDF!')}
|
||||
</Title>
|
||||
<Text size="md" c="dimmed">
|
||||
{t('onboarding.welcomeModal.description',
|
||||
"Would you like to take a quick 1-minute tour to learn the key features and how to get started?"
|
||||
)}
|
||||
</Text>
|
||||
<Text
|
||||
size="md"
|
||||
c="dimmed"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: t('onboarding.welcomeModal.helpHint',
|
||||
'You can always access this tour later from the <strong>Help</strong> button in the bottom left.'
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Stack gap="sm">
|
||||
<Button
|
||||
onClick={onStartTour}
|
||||
size="md"
|
||||
variant="filled"
|
||||
fullWidth
|
||||
>
|
||||
{t('onboarding.welcomeModal.startTour', 'Start Tour')}
|
||||
</Button>
|
||||
|
||||
<Group grow>
|
||||
<Button
|
||||
onClick={onMaybeLater}
|
||||
size="md"
|
||||
variant="light"
|
||||
>
|
||||
{t('onboarding.welcomeModal.maybeLater', 'Maybe Later')}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={onDontShowAgain}
|
||||
size="md"
|
||||
variant="light"
|
||||
>
|
||||
{t('onboarding.welcomeModal.dontShowAgain', "Don't Show Again")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,19 @@
|
||||
import type { StepType } from '@reactour/tour';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { AdminTourStep } from '@app/components/onboarding/tourSteps';
|
||||
import { addGlowToElements, removeAllGlows } from '@app/components/onboarding/tourGlow';
|
||||
|
||||
export enum AdminTourStep {
|
||||
WELCOME,
|
||||
CONFIG_BUTTON,
|
||||
SETTINGS_OVERVIEW,
|
||||
TEAMS_AND_USERS,
|
||||
SYSTEM_CUSTOMIZATION,
|
||||
DATABASE_SECTION,
|
||||
CONNECTIONS_SECTION,
|
||||
ADMIN_TOOLS,
|
||||
WRAP_UP,
|
||||
}
|
||||
|
||||
interface AdminStepActions {
|
||||
saveAdminState: () => void;
|
||||
openConfigModal: () => void;
|
||||
|
||||
@@ -1,304 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { usePreferences } from '@app/contexts/PreferencesContext';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
import { useOnboarding } from '@app/contexts/OnboardingContext';
|
||||
import type { LicenseNotice } from '@app/types/types';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import {
|
||||
ONBOARDING_SESSION_BLOCK_KEY,
|
||||
ONBOARDING_SESSION_EVENT,
|
||||
SERVER_LICENSE_REQUEST_EVENT,
|
||||
type ServerLicenseRequestPayload,
|
||||
} from '@app/constants/events';
|
||||
import { useServerExperience } from '@app/hooks/useServerExperience';
|
||||
|
||||
// Auth routes where onboarding should NOT show
|
||||
const AUTH_ROUTES = ['/login', '/signup', '/auth', '/invite'];
|
||||
|
||||
// Check if user has an auth token (to avoid flash before redirect)
|
||||
function hasAuthToken(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return !!localStorage.getItem('stirling_jwt');
|
||||
}
|
||||
|
||||
interface InitialModalHandlers {
|
||||
opened: boolean;
|
||||
onLicenseNoticeUpdate: (notice: LicenseNotice) => void;
|
||||
onRequestServerLicense: (options?: { deferUntilTourComplete?: boolean; selfReportedAdmin?: boolean }) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface ServerLicenseModalHandlers {
|
||||
opened: boolean;
|
||||
licenseNotice: LicenseNotice;
|
||||
onClose: () => void;
|
||||
onSeePlans: () => void;
|
||||
}
|
||||
|
||||
export function useOnboardingFlow() {
|
||||
const { preferences, updatePreference } = usePreferences();
|
||||
const { config, loading: configLoading } = useAppConfig();
|
||||
const { completeTour, tourType, isOpen } = useOnboarding();
|
||||
const location = useLocation();
|
||||
|
||||
// Check if we're on an auth route (login, signup, etc.)
|
||||
const isOnAuthRoute = AUTH_ROUTES.some(route => location.pathname.startsWith(route));
|
||||
|
||||
// Check if login is enabled but user doesn't have a token
|
||||
// This prevents a flash of the modal before redirect to /login
|
||||
const loginEnabled = config?.enableLogin === true;
|
||||
const isUnauthenticatedWithLoginEnabled = loginEnabled && !hasAuthToken();
|
||||
|
||||
// Don't show intro onboarding:
|
||||
// 1. On explicit auth routes (/login, /signup, etc.)
|
||||
// 2. While config is still loading
|
||||
// 3. When login is enabled but user isn't authenticated (would redirect to /login)
|
||||
// This ensures:
|
||||
// - If login is enabled: user must be logged in before seeing onboarding
|
||||
// - If login is disabled: homepage must have rendered first
|
||||
const shouldShowIntro = !preferences.hasSeenIntroOnboarding
|
||||
&& !isOnAuthRoute
|
||||
&& !configLoading
|
||||
&& !isUnauthenticatedWithLoginEnabled;
|
||||
const isAdminUser = !!config?.isAdmin;
|
||||
const { hasPaidLicense } = useServerExperience();
|
||||
|
||||
const [licenseNotice, setLicenseNotice] = useState<LicenseNotice>({
|
||||
totalUsers: null,
|
||||
freeTierLimit: 5,
|
||||
isOverLimit: false,
|
||||
requiresLicense: false,
|
||||
});
|
||||
const [serverLicenseIntent, setServerLicenseIntent] = useState<'idle' | 'pending' | 'deferred'>('idle');
|
||||
const [serverLicenseSource, setServerLicenseSource] = useState<'config' | 'self-reported' | null>(null);
|
||||
const [isServerLicenseOpen, setIsServerLicenseOpen] = useState(false);
|
||||
const [hasShownServerLicense, setHasShownServerLicense] = useState(false);
|
||||
const [toolPromptCompleted, setToolPromptCompleted] = useState(
|
||||
preferences.toolPanelModePromptSeen || preferences.hasSelectedToolPanelMode,
|
||||
);
|
||||
const introWasOpenRef = useRef(false);
|
||||
const navigate = useNavigate();
|
||||
const onboardingSessionMarkedRef = useRef(false);
|
||||
|
||||
const handleInitialModalClose = useCallback(() => {
|
||||
if (!preferences.hasSeenIntroOnboarding) {
|
||||
updatePreference('hasSeenIntroOnboarding', true);
|
||||
}
|
||||
}, [preferences.hasSeenIntroOnboarding, updatePreference]);
|
||||
|
||||
const handleLicenseNoticeUpdate = useCallback((notice: LicenseNotice) => {
|
||||
setLicenseNotice(notice);
|
||||
}, []);
|
||||
|
||||
const handleToolPromptComplete = useCallback(() => {
|
||||
setToolPromptCompleted(true);
|
||||
}, []);
|
||||
|
||||
const requestServerLicense = useCallback(
|
||||
({
|
||||
deferUntilTourComplete = false,
|
||||
selfReportedAdmin = false,
|
||||
}: { deferUntilTourComplete?: boolean; selfReportedAdmin?: boolean } = {}) => {
|
||||
const qualifies = isAdminUser || selfReportedAdmin;
|
||||
if (!qualifies) {
|
||||
return;
|
||||
}
|
||||
if (hasPaidLicense || !licenseNotice.requiresLicense) {
|
||||
return;
|
||||
}
|
||||
setServerLicenseSource(isAdminUser ? 'config' : 'self-reported');
|
||||
setServerLicenseIntent((prev) => {
|
||||
if (prev === 'pending') {
|
||||
return prev;
|
||||
}
|
||||
if (prev === 'deferred') {
|
||||
return deferUntilTourComplete ? prev : 'pending';
|
||||
}
|
||||
if (prev === 'idle') {
|
||||
return deferUntilTourComplete ? 'deferred' : 'pending';
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
},
|
||||
[hasPaidLicense, isAdminUser, licenseNotice.requiresLicense],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleServerLicenseRequested = (event: Event) => {
|
||||
const { detail } = event as CustomEvent<ServerLicenseRequestPayload>;
|
||||
|
||||
if (detail?.licenseNotice) {
|
||||
setLicenseNotice((prev) => ({
|
||||
...prev,
|
||||
...detail.licenseNotice,
|
||||
totalUsers:
|
||||
detail.licenseNotice?.totalUsers ?? prev.totalUsers,
|
||||
freeTierLimit:
|
||||
detail.licenseNotice?.freeTierLimit ?? prev.freeTierLimit,
|
||||
isOverLimit:
|
||||
detail.licenseNotice?.isOverLimit ?? prev.isOverLimit,
|
||||
requiresLicense:
|
||||
detail.licenseNotice?.requiresLicense ?? prev.requiresLicense,
|
||||
}));
|
||||
}
|
||||
|
||||
requestServerLicense({
|
||||
deferUntilTourComplete: detail?.deferUntilTourComplete ?? false,
|
||||
selfReportedAdmin: detail?.selfReportedAdmin ?? false,
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener(
|
||||
SERVER_LICENSE_REQUEST_EVENT,
|
||||
handleServerLicenseRequested as EventListener,
|
||||
);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(
|
||||
SERVER_LICENSE_REQUEST_EVENT,
|
||||
handleServerLicenseRequested as EventListener,
|
||||
);
|
||||
};
|
||||
}, [requestServerLicense]);
|
||||
|
||||
useEffect(() => {
|
||||
const isEligibleAdmin =
|
||||
isAdminUser || serverLicenseSource === 'self-reported' || licenseNotice.requiresLicense;
|
||||
if (
|
||||
introWasOpenRef.current &&
|
||||
!shouldShowIntro &&
|
||||
isEligibleAdmin &&
|
||||
toolPromptCompleted &&
|
||||
!hasShownServerLicense &&
|
||||
licenseNotice.requiresLicense &&
|
||||
serverLicenseIntent === 'idle'
|
||||
) {
|
||||
if (!serverLicenseSource) {
|
||||
setServerLicenseSource(isAdminUser ? 'config' : 'self-reported');
|
||||
}
|
||||
setServerLicenseIntent('pending');
|
||||
}
|
||||
introWasOpenRef.current = shouldShowIntro;
|
||||
}, [
|
||||
hasShownServerLicense,
|
||||
isAdminUser,
|
||||
serverLicenseIntent,
|
||||
shouldShowIntro,
|
||||
serverLicenseSource,
|
||||
toolPromptCompleted,
|
||||
licenseNotice.requiresLicense,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const isEligibleAdmin =
|
||||
isAdminUser || serverLicenseSource === 'self-reported' || licenseNotice.requiresLicense;
|
||||
if (
|
||||
serverLicenseIntent !== 'idle' &&
|
||||
!shouldShowIntro &&
|
||||
!isOpen &&
|
||||
!isServerLicenseOpen &&
|
||||
isEligibleAdmin &&
|
||||
toolPromptCompleted &&
|
||||
licenseNotice.requiresLicense
|
||||
) {
|
||||
setIsServerLicenseOpen(true);
|
||||
setServerLicenseIntent(serverLicenseIntent === 'deferred' ? 'pending' : 'idle');
|
||||
}
|
||||
}, [
|
||||
isAdminUser,
|
||||
isOpen,
|
||||
isServerLicenseOpen,
|
||||
serverLicenseIntent,
|
||||
shouldShowIntro,
|
||||
serverLicenseSource,
|
||||
toolPromptCompleted,
|
||||
licenseNotice.requiresLicense,
|
||||
]);
|
||||
|
||||
const handleServerLicenseClose = useCallback(() => {
|
||||
setIsServerLicenseOpen(false);
|
||||
setHasShownServerLicense(true);
|
||||
setServerLicenseIntent('idle');
|
||||
setServerLicenseSource(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (onboardingSessionMarkedRef.current) {
|
||||
return;
|
||||
}
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
if (shouldShowIntro || isOpen) {
|
||||
onboardingSessionMarkedRef.current = true;
|
||||
window.sessionStorage.setItem(ONBOARDING_SESSION_BLOCK_KEY, 'true');
|
||||
window.dispatchEvent(new CustomEvent(ONBOARDING_SESSION_EVENT));
|
||||
}
|
||||
}, [isOpen, shouldShowIntro]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
if (!shouldShowIntro && !isOpen) {
|
||||
window.sessionStorage.removeItem(ONBOARDING_SESSION_BLOCK_KEY);
|
||||
window.dispatchEvent(new CustomEvent(ONBOARDING_SESSION_EVENT));
|
||||
}
|
||||
}, [isOpen, shouldShowIntro]);
|
||||
|
||||
const handleServerLicenseSeePlans = useCallback(() => {
|
||||
handleServerLicenseClose();
|
||||
navigate('/settings/adminPlan');
|
||||
}, [handleServerLicenseClose, navigate]);
|
||||
|
||||
const handleTourCompletion = useCallback(() => {
|
||||
completeTour();
|
||||
if (serverLicenseIntent === 'deferred') {
|
||||
setServerLicenseIntent('pending');
|
||||
} else if (tourType === 'admin' && (isAdminUser || serverLicenseSource === 'self-reported')) {
|
||||
setServerLicenseSource((prev) => prev ?? (isAdminUser ? 'config' : 'self-reported'));
|
||||
setServerLicenseIntent((prev) => (prev === 'pending' ? prev : 'pending'));
|
||||
}
|
||||
}, [
|
||||
completeTour,
|
||||
isAdminUser,
|
||||
serverLicenseIntent,
|
||||
serverLicenseSource,
|
||||
tourType,
|
||||
]);
|
||||
|
||||
const initialModalProps: InitialModalHandlers = useMemo(
|
||||
() => ({
|
||||
opened: shouldShowIntro,
|
||||
onLicenseNoticeUpdate: handleLicenseNoticeUpdate,
|
||||
onRequestServerLicense: requestServerLicense,
|
||||
onClose: handleInitialModalClose,
|
||||
}),
|
||||
[handleInitialModalClose, handleLicenseNoticeUpdate, requestServerLicense, shouldShowIntro],
|
||||
);
|
||||
|
||||
const serverLicenseModalProps: ServerLicenseModalHandlers = useMemo(
|
||||
() => ({
|
||||
opened: isServerLicenseOpen,
|
||||
licenseNotice,
|
||||
onClose: handleServerLicenseClose,
|
||||
onSeePlans: handleServerLicenseSeePlans,
|
||||
}),
|
||||
[handleServerLicenseClose, handleServerLicenseSeePlans, isServerLicenseOpen, licenseNotice],
|
||||
);
|
||||
|
||||
return {
|
||||
tourType,
|
||||
isTourOpen: isOpen,
|
||||
maskClassName: tourType === 'admin' ? 'admin-tour-mask' : undefined,
|
||||
initialModalProps,
|
||||
handleToolPromptComplete,
|
||||
serverLicenseModalProps,
|
||||
handleTourCompletion,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,16 +3,18 @@ import DesktopInstallSlide from '@app/components/onboarding/slides/DesktopInstal
|
||||
import SecurityCheckSlide from '@app/components/onboarding/slides/SecurityCheckSlide';
|
||||
import PlanOverviewSlide from '@app/components/onboarding/slides/PlanOverviewSlide';
|
||||
import ServerLicenseSlide from '@app/components/onboarding/slides/ServerLicenseSlide';
|
||||
import FirstLoginSlide from '@app/components/onboarding/slides/FirstLoginSlide';
|
||||
import { SlideConfig, LicenseNotice } from '@app/types/types';
|
||||
|
||||
export type SlideId =
|
||||
| 'first-login'
|
||||
| 'welcome'
|
||||
| 'desktop-install'
|
||||
| 'security-check'
|
||||
| 'admin-overview'
|
||||
| 'server-license';
|
||||
|
||||
export type HeroType = 'rocket' | 'dual-icon' | 'shield' | 'diamond' | 'logo';
|
||||
export type HeroType = 'rocket' | 'dual-icon' | 'shield' | 'diamond' | 'logo' | 'lock';
|
||||
|
||||
export type ButtonAction =
|
||||
| 'next'
|
||||
@@ -46,6 +48,10 @@ export interface SlideFactoryParams {
|
||||
onRoleSelect: (role: 'admin' | 'user' | null) => void;
|
||||
licenseNotice?: LicenseNotice;
|
||||
loginEnabled?: boolean;
|
||||
// First login params
|
||||
firstLoginUsername?: string;
|
||||
onPasswordChanged?: () => void;
|
||||
usingDefaultCredentials?: boolean;
|
||||
}
|
||||
|
||||
export interface HeroDefinition {
|
||||
@@ -71,6 +77,17 @@ export interface SlideDefinition {
|
||||
}
|
||||
|
||||
export const SLIDE_DEFINITIONS: Record<SlideId, SlideDefinition> = {
|
||||
'first-login': {
|
||||
id: 'first-login',
|
||||
createSlide: ({ firstLoginUsername, onPasswordChanged, usingDefaultCredentials }) =>
|
||||
FirstLoginSlide({
|
||||
username: firstLoginUsername || '',
|
||||
onPasswordChanged: onPasswordChanged || (() => {}),
|
||||
usingDefaultCredentials: usingDefaultCredentials || false,
|
||||
}),
|
||||
hero: { type: 'lock' },
|
||||
buttons: [], // Form has its own submit button
|
||||
},
|
||||
'welcome': {
|
||||
id: 'welcome',
|
||||
createSlide: () => WelcomeSlide(),
|
||||
@@ -197,11 +214,3 @@ export const SLIDE_DEFINITIONS: Record<SlideId, SlideDefinition> = {
|
||||
},
|
||||
};
|
||||
|
||||
export const FLOW_SEQUENCES = {
|
||||
loginAdmin: ['welcome', 'desktop-install', 'admin-overview'] as SlideId[],
|
||||
loginUser: ['welcome', 'desktop-install'] as SlideId[],
|
||||
noLoginBase: ['welcome', 'desktop-install', 'security-check'] as SlideId[],
|
||||
noLoginAdmin: ['admin-overview'] as SlideId[],
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
export type OnboardingStepId =
|
||||
| 'first-login'
|
||||
| 'welcome'
|
||||
| 'desktop-install'
|
||||
| 'security-check'
|
||||
| 'admin-overview'
|
||||
| 'tool-layout'
|
||||
| 'tour'
|
||||
| 'server-license'
|
||||
| 'analytics-choice';
|
||||
|
||||
export type OnboardingStepType =
|
||||
| 'modal-slide'
|
||||
| 'tool-prompt'
|
||||
| 'tour'
|
||||
| 'analytics-modal';
|
||||
|
||||
export interface OnboardingRuntimeState {
|
||||
selectedRole: 'admin' | 'user' | null;
|
||||
tourRequested: boolean;
|
||||
tourType: 'admin' | 'tools';
|
||||
isDesktopApp: boolean;
|
||||
analyticsNotConfigured: boolean;
|
||||
analyticsEnabled: boolean;
|
||||
licenseNotice: {
|
||||
totalUsers: number | null;
|
||||
freeTierLimit: number;
|
||||
isOverLimit: boolean;
|
||||
requiresLicense: boolean;
|
||||
};
|
||||
requiresPasswordChange: boolean;
|
||||
firstLoginUsername: string;
|
||||
usingDefaultCredentials: boolean;
|
||||
}
|
||||
|
||||
export interface OnboardingConditionContext extends OnboardingRuntimeState {
|
||||
loginEnabled: boolean;
|
||||
effectiveIsAdmin: boolean;
|
||||
}
|
||||
|
||||
export interface OnboardingStep {
|
||||
id: OnboardingStepId;
|
||||
type: OnboardingStepType;
|
||||
condition: (ctx: OnboardingConditionContext) => boolean;
|
||||
slideId?: 'first-login' | 'welcome' | 'desktop-install' | 'security-check' | 'admin-overview' | 'server-license';
|
||||
}
|
||||
|
||||
export const DEFAULT_RUNTIME_STATE: OnboardingRuntimeState = {
|
||||
selectedRole: null,
|
||||
tourRequested: false,
|
||||
tourType: 'tools',
|
||||
isDesktopApp: false,
|
||||
analyticsNotConfigured: false,
|
||||
analyticsEnabled: false,
|
||||
licenseNotice: {
|
||||
totalUsers: null,
|
||||
freeTierLimit: 5,
|
||||
isOverLimit: false,
|
||||
requiresLicense: false,
|
||||
},
|
||||
requiresPasswordChange: false,
|
||||
firstLoginUsername: '',
|
||||
usingDefaultCredentials: false,
|
||||
};
|
||||
|
||||
export const ONBOARDING_STEPS: OnboardingStep[] = [
|
||||
{
|
||||
id: 'first-login',
|
||||
type: 'modal-slide',
|
||||
slideId: 'first-login',
|
||||
condition: (ctx) => ctx.requiresPasswordChange,
|
||||
},
|
||||
{
|
||||
id: 'welcome',
|
||||
type: 'modal-slide',
|
||||
slideId: 'welcome',
|
||||
condition: () => true,
|
||||
},
|
||||
{
|
||||
id: 'desktop-install',
|
||||
type: 'modal-slide',
|
||||
slideId: 'desktop-install',
|
||||
condition: (ctx) => !ctx.isDesktopApp,
|
||||
},
|
||||
{
|
||||
id: 'security-check',
|
||||
type: 'modal-slide',
|
||||
slideId: 'security-check',
|
||||
condition: (ctx) => !ctx.loginEnabled && !ctx.isDesktopApp,
|
||||
},
|
||||
{
|
||||
id: 'admin-overview',
|
||||
type: 'modal-slide',
|
||||
slideId: 'admin-overview',
|
||||
condition: (ctx) => ctx.effectiveIsAdmin,
|
||||
},
|
||||
{
|
||||
id: 'tool-layout',
|
||||
type: 'tool-prompt',
|
||||
condition: () => true,
|
||||
},
|
||||
{
|
||||
id: 'tour',
|
||||
type: 'tour',
|
||||
condition: (ctx) => ctx.tourRequested || !ctx.effectiveIsAdmin,
|
||||
},
|
||||
{
|
||||
id: 'server-license',
|
||||
type: 'modal-slide',
|
||||
slideId: 'server-license',
|
||||
condition: (ctx) => ctx.effectiveIsAdmin && ctx.licenseNotice.requiresLicense,
|
||||
},
|
||||
{
|
||||
id: 'analytics-choice',
|
||||
type: 'analytics-modal',
|
||||
condition: (ctx) => ctx.effectiveIsAdmin && ctx.analyticsNotConfigured,
|
||||
},
|
||||
];
|
||||
|
||||
export function getStepById(id: OnboardingStepId): OnboardingStep | undefined {
|
||||
return ONBOARDING_STEPS.find((step) => step.id === id);
|
||||
}
|
||||
|
||||
export function getStepIndex(id: OnboardingStepId): number {
|
||||
return ONBOARDING_STEPS.findIndex((step) => step.id === id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { type OnboardingStepId, ONBOARDING_STEPS } from '@app/components/onboarding/orchestrator/onboardingConfig';
|
||||
|
||||
const STORAGE_PREFIX = 'onboarding';
|
||||
|
||||
export function getStorageKey(stepId: OnboardingStepId): string {
|
||||
return `${STORAGE_PREFIX}::${stepId}`;
|
||||
}
|
||||
|
||||
export function hasSeenStep(stepId: OnboardingStepId): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
try {
|
||||
return localStorage.getItem(getStorageKey(stepId)) === 'true';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function markStepSeen(stepId: OnboardingStepId): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
localStorage.setItem(getStorageKey(stepId), 'true');
|
||||
} catch (error) {
|
||||
console.error('[onboardingStorage] Error marking step as seen:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export function resetStepSeen(stepId: OnboardingStepId): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
localStorage.removeItem(getStorageKey(stepId));
|
||||
} catch (error) {
|
||||
console.error('[onboardingStorage] Error resetting step seen:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export function resetAllOnboardingProgress(): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
const prefix = `${STORAGE_PREFIX}::`;
|
||||
const keysToRemove: string[] = [];
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
if (key?.startsWith(prefix)) keysToRemove.push(key);
|
||||
}
|
||||
keysToRemove.forEach((key) => localStorage.removeItem(key));
|
||||
} catch (error) {
|
||||
console.error('[onboardingStorage] Error resetting all onboarding progress:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export function getOnboardingStorageState(): Record<string, boolean> {
|
||||
const state: Record<string, boolean> = {};
|
||||
ONBOARDING_STEPS.forEach((step) => {
|
||||
state[step.id] = hasSeenStep(step.id);
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
export function migrateFromLegacyPreferences(): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const migrationKey = `${STORAGE_PREFIX}::migrated`;
|
||||
|
||||
try {
|
||||
// Skip if already migrated
|
||||
if (localStorage.getItem(migrationKey) === 'true') return;
|
||||
|
||||
const prefsRaw = localStorage.getItem('stirlingpdf_preferences');
|
||||
if (prefsRaw) {
|
||||
const prefs = JSON.parse(prefsRaw) as Record<string, unknown>;
|
||||
|
||||
// Migrate based on legacy flags
|
||||
if (prefs.hasSeenIntroOnboarding === true) {
|
||||
markStepSeen('welcome');
|
||||
markStepSeen('desktop-install');
|
||||
markStepSeen('security-check');
|
||||
markStepSeen('admin-overview');
|
||||
}
|
||||
|
||||
if (prefs.toolPanelModePromptSeen === true || prefs.hasSelectedToolPanelMode === true) {
|
||||
markStepSeen('tool-layout');
|
||||
}
|
||||
|
||||
if (prefs.hasCompletedOnboarding === true) {
|
||||
markStepSeen('tour');
|
||||
markStepSeen('analytics-choice');
|
||||
markStepSeen('server-license');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Mark migration complete
|
||||
localStorage.setItem(migrationKey, 'true');
|
||||
} catch {
|
||||
// If migration fails, onboarding will show again - safer than hiding it
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useServerExperience } from '@app/hooks/useServerExperience';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
|
||||
import {
|
||||
ONBOARDING_STEPS,
|
||||
type OnboardingStepId,
|
||||
type OnboardingStep,
|
||||
type OnboardingRuntimeState,
|
||||
type OnboardingConditionContext,
|
||||
DEFAULT_RUNTIME_STATE,
|
||||
} from '@app/components/onboarding/orchestrator/onboardingConfig';
|
||||
import {
|
||||
hasSeenStep,
|
||||
markStepSeen,
|
||||
migrateFromLegacyPreferences,
|
||||
} from '@app/components/onboarding/orchestrator/onboardingStorage';
|
||||
import { accountService } from '@app/services/accountService';
|
||||
|
||||
const AUTH_ROUTES = ['/login', '/signup', '/auth', '/invite'];
|
||||
const SESSION_TOUR_REQUESTED = 'onboarding::session::tour-requested';
|
||||
const SESSION_TOUR_TYPE = 'onboarding::session::tour-type';
|
||||
const SESSION_SELECTED_ROLE = 'onboarding::session::selected-role';
|
||||
|
||||
// Check if user has an auth token (to avoid flash before redirect)
|
||||
function hasAuthToken(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return !!localStorage.getItem('stirling_jwt');
|
||||
}
|
||||
|
||||
// Get initial runtime state from session storage (survives remounts)
|
||||
function getInitialRuntimeState(baseState: OnboardingRuntimeState): OnboardingRuntimeState {
|
||||
if (typeof window === 'undefined') {
|
||||
return baseState;
|
||||
}
|
||||
|
||||
try {
|
||||
const tourRequested = sessionStorage.getItem(SESSION_TOUR_REQUESTED) === 'true';
|
||||
const tourType = (sessionStorage.getItem(SESSION_TOUR_TYPE) as 'admin' | 'tools') || 'tools';
|
||||
const selectedRole = sessionStorage.getItem(SESSION_SELECTED_ROLE) as 'admin' | 'user' | null;
|
||||
|
||||
return {
|
||||
...baseState,
|
||||
tourRequested,
|
||||
tourType,
|
||||
selectedRole,
|
||||
};
|
||||
} catch {
|
||||
return baseState;
|
||||
}
|
||||
}
|
||||
|
||||
function persistRuntimeState(state: Partial<OnboardingRuntimeState>): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
try {
|
||||
if (state.tourRequested !== undefined) {
|
||||
sessionStorage.setItem(SESSION_TOUR_REQUESTED, state.tourRequested ? 'true' : 'false');
|
||||
}
|
||||
if (state.tourType !== undefined) {
|
||||
sessionStorage.setItem(SESSION_TOUR_TYPE, state.tourType);
|
||||
}
|
||||
if (state.selectedRole !== undefined) {
|
||||
if (state.selectedRole) {
|
||||
sessionStorage.setItem(SESSION_SELECTED_ROLE, state.selectedRole);
|
||||
} else {
|
||||
sessionStorage.removeItem(SESSION_SELECTED_ROLE);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[useOnboardingOrchestrator] Error persisting runtime state:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function clearRuntimeStateSession(): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
try {
|
||||
sessionStorage.removeItem(SESSION_TOUR_REQUESTED);
|
||||
sessionStorage.removeItem(SESSION_TOUR_TYPE);
|
||||
sessionStorage.removeItem(SESSION_SELECTED_ROLE);
|
||||
} catch {
|
||||
// Ignore errors
|
||||
}
|
||||
}
|
||||
|
||||
export interface OnboardingOrchestratorState {
|
||||
/** Whether onboarding is currently active */
|
||||
isActive: boolean;
|
||||
/** The current step being shown (null if no step is active) */
|
||||
currentStep: OnboardingStep | null;
|
||||
/** Index of current step in the active flow (for display purposes) */
|
||||
currentStepIndex: number;
|
||||
/** Total number of steps in the active flow */
|
||||
totalSteps: number;
|
||||
/** Runtime state that affects conditions */
|
||||
runtimeState: OnboardingRuntimeState;
|
||||
/** All steps that will be shown in this flow (filtered by conditions) */
|
||||
activeFlow: OnboardingStep[];
|
||||
/** Whether all steps have been seen */
|
||||
isComplete: boolean;
|
||||
/** Whether we're still initializing */
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export interface OnboardingOrchestratorActions {
|
||||
/** Move to the next step */
|
||||
next: () => void;
|
||||
/** Move to the previous step */
|
||||
prev: () => void;
|
||||
/** Skip the current step (marks as seen but doesn't complete) */
|
||||
skip: () => void;
|
||||
/** Mark current step as seen and move to next */
|
||||
complete: () => void;
|
||||
/** Update runtime state (e.g., after role selection) */
|
||||
updateRuntimeState: (updates: Partial<OnboardingRuntimeState>) => void;
|
||||
/** Force re-evaluation of the flow (used when conditions change) */
|
||||
refreshFlow: () => void;
|
||||
/** Manually start a specific step (for external triggers) */
|
||||
startStep: (stepId: OnboardingStepId) => void;
|
||||
/** Close/pause onboarding (can be resumed later) */
|
||||
pause: () => void;
|
||||
/** Resume onboarding from where it was paused */
|
||||
resume: () => void;
|
||||
}
|
||||
|
||||
export interface UseOnboardingOrchestratorResult {
|
||||
state: OnboardingOrchestratorState;
|
||||
actions: OnboardingOrchestratorActions;
|
||||
}
|
||||
|
||||
export interface UseOnboardingOrchestratorOptions {
|
||||
/** Override the default runtime state (used by desktop to set isDesktopApp: true) */
|
||||
defaultRuntimeState?: OnboardingRuntimeState;
|
||||
}
|
||||
|
||||
export function useOnboardingOrchestrator(
|
||||
options?: UseOnboardingOrchestratorOptions
|
||||
): UseOnboardingOrchestratorResult {
|
||||
const defaultState = options?.defaultRuntimeState ?? DEFAULT_RUNTIME_STATE;
|
||||
const serverExperience = useServerExperience();
|
||||
const { config, loading: configLoading } = useAppConfig();
|
||||
const location = useLocation();
|
||||
|
||||
const [runtimeState, setRuntimeState] = useState<OnboardingRuntimeState>(() =>
|
||||
getInitialRuntimeState(defaultState)
|
||||
);
|
||||
const [isPaused, setIsPaused] = useState(false);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [currentStepIndex, setCurrentStepIndex] = useState(-1);
|
||||
const migrationDone = useRef(false);
|
||||
const initialIndexSet = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!migrationDone.current) {
|
||||
migrateFromLegacyPreferences();
|
||||
migrationDone.current = true;
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setRuntimeState((prev) => ({
|
||||
...prev,
|
||||
analyticsEnabled: config?.enableAnalytics === true,
|
||||
analyticsNotConfigured: config?.enableAnalytics == null,
|
||||
licenseNotice: {
|
||||
totalUsers: serverExperience.totalUsers,
|
||||
freeTierLimit: serverExperience.freeTierLimit,
|
||||
isOverLimit: serverExperience.overFreeTierLimit ?? false,
|
||||
requiresLicense: !serverExperience.hasPaidLicense && (
|
||||
serverExperience.overFreeTierLimit === true ||
|
||||
(serverExperience.effectiveIsAdmin && serverExperience.userCountResolved)
|
||||
),
|
||||
},
|
||||
}));
|
||||
}, [
|
||||
config?.enableAnalytics,
|
||||
serverExperience.totalUsers,
|
||||
serverExperience.freeTierLimit,
|
||||
serverExperience.overFreeTierLimit,
|
||||
serverExperience.hasPaidLicense,
|
||||
serverExperience.effectiveIsAdmin,
|
||||
serverExperience.userCountResolved,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const checkFirstLogin = async () => {
|
||||
if (config?.enableLogin !== true || !hasAuthToken()) return;
|
||||
|
||||
try {
|
||||
const [accountData, loginPageData] = await Promise.all([
|
||||
accountService.getAccountData(),
|
||||
accountService.getLoginPageData(),
|
||||
]);
|
||||
|
||||
setRuntimeState((prev) => ({
|
||||
...prev,
|
||||
requiresPasswordChange: accountData.changeCredsFlag,
|
||||
firstLoginUsername: accountData.username,
|
||||
usingDefaultCredentials: loginPageData.showDefaultCredentials,
|
||||
}));
|
||||
} catch {
|
||||
// Account endpoint failed - user not logged in or security disabled
|
||||
}
|
||||
};
|
||||
|
||||
if (!configLoading) {
|
||||
checkFirstLogin();
|
||||
}
|
||||
}, [config?.enableLogin, configLoading]);
|
||||
|
||||
const isOnAuthRoute = AUTH_ROUTES.some((route) => location.pathname.startsWith(route));
|
||||
const loginEnabled = config?.enableLogin === true;
|
||||
const isUnauthenticatedWithLoginEnabled = loginEnabled && !hasAuthToken();
|
||||
const shouldBlockOnboarding = isOnAuthRoute || configLoading || isUnauthenticatedWithLoginEnabled;
|
||||
|
||||
const conditionContext = useMemo<OnboardingConditionContext>(() => ({
|
||||
...serverExperience,
|
||||
...runtimeState,
|
||||
effectiveIsAdmin: serverExperience.effectiveIsAdmin ||
|
||||
(!serverExperience.loginEnabled && runtimeState.selectedRole === 'admin'),
|
||||
}), [serverExperience, runtimeState]);
|
||||
|
||||
const activeFlow = useMemo(() => {
|
||||
return ONBOARDING_STEPS.filter((step) => step.condition(conditionContext));
|
||||
}, [conditionContext]);
|
||||
|
||||
// Wait for config AND admin status before calculating initial step
|
||||
const adminStatusResolved = !configLoading && (
|
||||
config?.enableLogin === false ||
|
||||
config?.enableLogin === undefined ||
|
||||
config?.isAdmin !== undefined
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (configLoading || !adminStatusResolved || activeFlow.length === 0) return;
|
||||
|
||||
let firstUnseenIndex = -1;
|
||||
for (let i = 0; i < activeFlow.length; i++) {
|
||||
if (!hasSeenStep(activeFlow[i].id)) {
|
||||
firstUnseenIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (firstUnseenIndex === -1) {
|
||||
setCurrentStepIndex(activeFlow.length);
|
||||
initialIndexSet.current = true;
|
||||
} else if (!initialIndexSet.current) {
|
||||
setCurrentStepIndex(firstUnseenIndex);
|
||||
initialIndexSet.current = true;
|
||||
}
|
||||
}, [activeFlow, configLoading, adminStatusResolved]);
|
||||
|
||||
const totalSteps = activeFlow.length;
|
||||
|
||||
const allStepsAlreadySeen = useMemo(() => {
|
||||
if (activeFlow.length === 0) return false;
|
||||
return activeFlow.every(step => hasSeenStep(step.id));
|
||||
}, [activeFlow]);
|
||||
|
||||
const isComplete = isInitialized && initialIndexSet.current &&
|
||||
(currentStepIndex >= totalSteps || allStepsAlreadySeen);
|
||||
const currentStep = (currentStepIndex >= 0 && currentStepIndex < totalSteps && !allStepsAlreadySeen)
|
||||
? activeFlow[currentStepIndex]
|
||||
: null;
|
||||
const isActive = !shouldBlockOnboarding && !isPaused && !isComplete && isInitialized && currentStep !== null;
|
||||
const isLoading = configLoading || !adminStatusResolved || !isInitialized ||
|
||||
!initialIndexSet.current || (currentStepIndex === -1 && activeFlow.length > 0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!configLoading && !isInitialized) setIsInitialized(true);
|
||||
}, [configLoading, isInitialized]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isComplete) clearRuntimeStateSession();
|
||||
}, [isComplete]);
|
||||
|
||||
const next = useCallback(() => {
|
||||
if (currentStep) markStepSeen(currentStep.id);
|
||||
setCurrentStepIndex((prev) => Math.min(prev + 1, totalSteps));
|
||||
}, [currentStep, totalSteps]);
|
||||
|
||||
const prev = useCallback(() => {
|
||||
setCurrentStepIndex((prev) => Math.max(prev - 1, 0));
|
||||
}, []);
|
||||
|
||||
const skip = useCallback(() => {
|
||||
if (currentStep) markStepSeen(currentStep.id);
|
||||
setCurrentStepIndex((prev) => Math.min(prev + 1, totalSteps));
|
||||
}, [currentStep, totalSteps]);
|
||||
|
||||
const complete = useCallback(() => {
|
||||
if (currentStep) markStepSeen(currentStep.id);
|
||||
setCurrentStepIndex((prev) => Math.min(prev + 1, totalSteps));
|
||||
}, [currentStep, totalSteps]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentStep || isLoading) {
|
||||
return;
|
||||
}
|
||||
if (hasSeenStep(currentStep.id)) {
|
||||
complete();
|
||||
}
|
||||
}, [currentStep, isLoading, complete]);
|
||||
|
||||
const updateRuntimeState = useCallback((updates: Partial<OnboardingRuntimeState>) => {
|
||||
persistRuntimeState(updates);
|
||||
setRuntimeState((prev) => ({ ...prev, ...updates }));
|
||||
}, []);
|
||||
|
||||
const refreshFlow = useCallback(() => {
|
||||
initialIndexSet.current = false;
|
||||
setCurrentStepIndex(-1);
|
||||
}, []);
|
||||
|
||||
const startStep = useCallback((stepId: OnboardingStepId) => {
|
||||
const index = activeFlow.findIndex((step) => step.id === stepId);
|
||||
if (index !== -1) {
|
||||
setCurrentStepIndex(index);
|
||||
setIsPaused(false);
|
||||
}
|
||||
}, [activeFlow]);
|
||||
|
||||
const pause = useCallback(() => setIsPaused(true), []);
|
||||
const resume = useCallback(() => setIsPaused(false), []);
|
||||
|
||||
const state: OnboardingOrchestratorState = {
|
||||
isActive,
|
||||
currentStep,
|
||||
currentStepIndex,
|
||||
totalSteps,
|
||||
runtimeState,
|
||||
activeFlow,
|
||||
isComplete,
|
||||
isLoading,
|
||||
};
|
||||
|
||||
const actions: OnboardingOrchestratorActions = {
|
||||
next,
|
||||
prev,
|
||||
skip,
|
||||
complete,
|
||||
updateRuntimeState,
|
||||
refreshFlow,
|
||||
startStep,
|
||||
pause,
|
||||
resume,
|
||||
};
|
||||
|
||||
return { state, actions };
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Stack, PasswordInput, Button, Alert, Text } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { SlideConfig } from '@app/types/types';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { UNIFIED_CIRCLE_CONFIG } from '@app/components/onboarding/slides/unifiedBackgroundConfig';
|
||||
import { accountService } from '@app/services/accountService';
|
||||
import { alert as showToast } from '@app/components/toast';
|
||||
import styles from '@app/components/onboarding/InitialOnboardingModal/InitialOnboardingModal.module.css';
|
||||
|
||||
interface FirstLoginSlideProps {
|
||||
username: string;
|
||||
onPasswordChanged: () => void;
|
||||
usingDefaultCredentials?: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_PASSWORD = 'stirling';
|
||||
|
||||
function FirstLoginForm({ username, onPasswordChanged, usingDefaultCredentials = false }: FirstLoginSlideProps) {
|
||||
const { t } = useTranslation();
|
||||
// If using default credentials, pre-fill with "stirling" - user won't see this field
|
||||
const [currentPassword, setCurrentPassword] = useState(usingDefaultCredentials ? DEFAULT_PASSWORD : '');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleSubmit = async () => {
|
||||
// Validation
|
||||
if ((!usingDefaultCredentials && !currentPassword) || !newPassword || !confirmPassword) {
|
||||
setError(t('firstLogin.allFieldsRequired', 'All fields are required'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword !== confirmPassword) {
|
||||
setError(t('firstLogin.passwordsDoNotMatch', 'New passwords do not match'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword.length < 8) {
|
||||
setError(t('firstLogin.passwordTooShort', 'Password must be at least 8 characters'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (newPassword === currentPassword) {
|
||||
setError(t('firstLogin.passwordMustBeDifferent', 'New password must be different from current password'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
|
||||
await accountService.changePasswordOnLogin(currentPassword, newPassword);
|
||||
|
||||
showToast({
|
||||
alertType: 'success',
|
||||
title: t('firstLogin.passwordChangedSuccess', 'Password changed successfully! Please log in again.')
|
||||
});
|
||||
|
||||
// Clear form
|
||||
setCurrentPassword('');
|
||||
setNewPassword('');
|
||||
setConfirmPassword('');
|
||||
|
||||
// Wait a moment for the user to see the success message
|
||||
setTimeout(() => {
|
||||
onPasswordChanged();
|
||||
}, 1500);
|
||||
} catch (err) {
|
||||
console.error('Failed to change password:', err);
|
||||
// Extract error message from axios response if available
|
||||
const axiosError = err as { response?: { data?: { message?: string } } };
|
||||
setError(
|
||||
axiosError.response?.data?.message ||
|
||||
t('firstLogin.passwordChangeFailed', 'Failed to change password. Please check your current password.')
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.securitySlideContent}>
|
||||
<div className={styles.securityCard}>
|
||||
<Stack gap="md">
|
||||
<div className={styles.securityAlertRow}>
|
||||
<LocalIcon icon="info-rounded" width={20} height={20} style={{ color: '#3B82F6', flexShrink: 0 }} />
|
||||
<span>
|
||||
{t(
|
||||
'firstLogin.welcomeMessage',
|
||||
'For security reasons, you must change your password on your first login.'
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Text size="sm" fw={500}>
|
||||
{t('firstLogin.loggedInAs', 'Logged in as')}: <strong>{username}</strong>
|
||||
</Text>
|
||||
|
||||
{error && (
|
||||
<Alert
|
||||
icon={<LocalIcon icon="error-rounded" width="1rem" height="1rem" />}
|
||||
color="red"
|
||||
variant="light"
|
||||
>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Only show current password field if not using default credentials */}
|
||||
{!usingDefaultCredentials && (
|
||||
<PasswordInput
|
||||
label={t('firstLogin.currentPassword', 'Current Password')}
|
||||
placeholder={t('firstLogin.enterCurrentPassword', 'Enter your current password')}
|
||||
value={currentPassword}
|
||||
onChange={(e) => setCurrentPassword(e.currentTarget.value)}
|
||||
required
|
||||
styles={{
|
||||
input: { height: 44 },
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PasswordInput
|
||||
label={t('firstLogin.newPassword', 'New Password')}
|
||||
placeholder={t('firstLogin.enterNewPassword', 'Enter new password (min 8 characters)')}
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.currentTarget.value)}
|
||||
required
|
||||
styles={{
|
||||
input: { height: 44 },
|
||||
}}
|
||||
/>
|
||||
|
||||
<PasswordInput
|
||||
label={t('firstLogin.confirmPassword', 'Confirm New Password')}
|
||||
placeholder={t('firstLogin.reEnterNewPassword', 'Re-enter new password')}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.currentTarget.value)}
|
||||
required
|
||||
styles={{
|
||||
input: { height: 44 },
|
||||
}}
|
||||
/>
|
||||
|
||||
<Button
|
||||
fullWidth
|
||||
onClick={handleSubmit}
|
||||
loading={loading}
|
||||
disabled={!newPassword || !confirmPassword}
|
||||
size="md"
|
||||
mt="xs"
|
||||
>
|
||||
{t('firstLogin.changePassword', 'Change Password')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function FirstLoginSlide({
|
||||
username,
|
||||
onPasswordChanged,
|
||||
usingDefaultCredentials = false,
|
||||
}: FirstLoginSlideProps): SlideConfig {
|
||||
return {
|
||||
key: 'first-login',
|
||||
title: 'Set Your Password',
|
||||
body: (
|
||||
<FirstLoginForm
|
||||
username={username}
|
||||
onPasswordChanged={onPasswordChanged}
|
||||
usingDefaultCredentials={usingDefaultCredentials}
|
||||
/>
|
||||
),
|
||||
background: {
|
||||
gradientStops: ['#059669', '#0891B2'], // Green to teal - security/trust colors
|
||||
circles: UNIFIED_CIRCLE_CONFIG,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
export enum TourStep {
|
||||
ALL_TOOLS,
|
||||
SELECT_CROP_TOOL,
|
||||
TOOL_INTERFACE,
|
||||
FILES_BUTTON,
|
||||
FILE_SOURCES,
|
||||
WORKBENCH,
|
||||
VIEW_SWITCHER,
|
||||
VIEWER,
|
||||
PAGE_EDITOR,
|
||||
ACTIVE_FILES,
|
||||
FILE_CHECKBOX,
|
||||
SELECT_CONTROLS,
|
||||
CROP_SETTINGS,
|
||||
RUN_BUTTON,
|
||||
RESULTS,
|
||||
FILE_REPLACEMENT,
|
||||
PIN_BUTTON,
|
||||
WRAP_UP,
|
||||
}
|
||||
|
||||
export enum AdminTourStep {
|
||||
WELCOME,
|
||||
CONFIG_BUTTON,
|
||||
SETTINGS_OVERVIEW,
|
||||
TEAMS_AND_USERS,
|
||||
SYSTEM_CUSTOMIZATION,
|
||||
DATABASE_SECTION,
|
||||
CONNECTIONS_SECTION,
|
||||
ADMIN_TOOLS,
|
||||
WRAP_UP,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* useOnboardingDownload Hook
|
||||
*
|
||||
* Encapsulates OS detection and download URL logic for the desktop install slide.
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { useOs } from '@app/hooks/useOs';
|
||||
import { DOWNLOAD_URLS } from '@app/constants/downloads';
|
||||
|
||||
interface OsInfo {
|
||||
label: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface OsOption {
|
||||
label: string;
|
||||
url: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface UseOnboardingDownloadResult {
|
||||
osInfo: OsInfo;
|
||||
osOptions: OsOption[];
|
||||
selectedDownloadUrl: string;
|
||||
setSelectedDownloadUrl: (url: string) => void;
|
||||
handleDownloadSelected: () => void;
|
||||
}
|
||||
|
||||
export function useOnboardingDownload(): UseOnboardingDownloadResult {
|
||||
const osType = useOs();
|
||||
const [selectedDownloadUrl, setSelectedDownloadUrl] = useState<string>('');
|
||||
|
||||
const osInfo = useMemo<OsInfo>(() => {
|
||||
switch (osType) {
|
||||
case 'windows':
|
||||
return { label: 'Windows', url: DOWNLOAD_URLS.WINDOWS };
|
||||
case 'mac-apple':
|
||||
return { label: 'Mac (Apple Silicon)', url: DOWNLOAD_URLS.MAC_APPLE_SILICON };
|
||||
case 'mac-intel':
|
||||
return { label: 'Mac (Intel)', url: DOWNLOAD_URLS.MAC_INTEL };
|
||||
case 'linux-x64':
|
||||
case 'linux-arm64':
|
||||
return { label: 'Linux', url: DOWNLOAD_URLS.LINUX_DOCS };
|
||||
default:
|
||||
return { label: '', url: '' };
|
||||
}
|
||||
}, [osType]);
|
||||
|
||||
const osOptions = useMemo<OsOption[]>(() => [
|
||||
{ label: 'Windows', url: DOWNLOAD_URLS.WINDOWS, value: 'windows' },
|
||||
{ label: 'Mac (Apple Silicon)', url: DOWNLOAD_URLS.MAC_APPLE_SILICON, value: 'mac-apple' },
|
||||
{ label: 'Mac (Intel)', url: DOWNLOAD_URLS.MAC_INTEL, value: 'mac-intel' },
|
||||
{ label: 'Linux', url: DOWNLOAD_URLS.LINUX_DOCS, value: 'linux' },
|
||||
].filter((opt) => opt.url), []);
|
||||
|
||||
// Initialize selected URL from detected OS
|
||||
useEffect(() => {
|
||||
if (!selectedDownloadUrl && osInfo.url) {
|
||||
setSelectedDownloadUrl(osInfo.url);
|
||||
}
|
||||
}, [osInfo.url, selectedDownloadUrl]);
|
||||
|
||||
const handleDownloadSelected = useCallback(() => {
|
||||
const downloadUrl = selectedDownloadUrl || osInfo.url;
|
||||
if (downloadUrl) {
|
||||
window.open(downloadUrl, '_blank', 'noopener');
|
||||
}
|
||||
}, [selectedDownloadUrl, osInfo.url]);
|
||||
|
||||
return {
|
||||
osInfo,
|
||||
osOptions,
|
||||
selectedDownloadUrl,
|
||||
setSelectedDownloadUrl,
|
||||
handleDownloadSelected,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useEffect, useCallback, useState } from 'react';
|
||||
import {
|
||||
SERVER_LICENSE_REQUEST_EVENT,
|
||||
START_TOUR_EVENT,
|
||||
type ServerLicenseRequestPayload,
|
||||
type TourType,
|
||||
type StartTourPayload,
|
||||
} from '@app/constants/events';
|
||||
import type { OnboardingRuntimeState } from '@app/components/onboarding/orchestrator/onboardingConfig';
|
||||
|
||||
export function useServerLicenseRequest(): {
|
||||
showLicenseSlide: boolean;
|
||||
licenseNotice: OnboardingRuntimeState['licenseNotice'] | null;
|
||||
closeLicenseSlide: () => void;
|
||||
} {
|
||||
const [showLicenseSlide, setShowLicenseSlide] = useState(false);
|
||||
const [licenseNotice, setLicenseNotice] = useState<OnboardingRuntimeState['licenseNotice'] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const handleLicenseRequest = (event: Event) => {
|
||||
const { detail } = event as CustomEvent<ServerLicenseRequestPayload>;
|
||||
|
||||
if (detail?.licenseNotice) {
|
||||
setLicenseNotice({
|
||||
totalUsers: detail.licenseNotice.totalUsers ?? null,
|
||||
freeTierLimit: detail.licenseNotice.freeTierLimit ?? 5,
|
||||
isOverLimit: detail.licenseNotice.isOverLimit ?? false,
|
||||
requiresLicense: true,
|
||||
});
|
||||
}
|
||||
|
||||
setShowLicenseSlide(true);
|
||||
};
|
||||
|
||||
window.addEventListener(SERVER_LICENSE_REQUEST_EVENT, handleLicenseRequest);
|
||||
return () => window.removeEventListener(SERVER_LICENSE_REQUEST_EVENT, handleLicenseRequest);
|
||||
}, []);
|
||||
|
||||
const closeLicenseSlide = useCallback(() => {
|
||||
setShowLicenseSlide(false);
|
||||
}, []);
|
||||
|
||||
return { showLicenseSlide, licenseNotice, closeLicenseSlide };
|
||||
}
|
||||
|
||||
export function useTourRequest(): {
|
||||
tourRequested: boolean;
|
||||
requestedTourType: TourType;
|
||||
clearTourRequest: () => void;
|
||||
} {
|
||||
const [tourRequested, setTourRequested] = useState(false);
|
||||
const [requestedTourType, setRequestedTourType] = useState<TourType>('tools');
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const handleTourRequest = (event: Event) => {
|
||||
const { detail } = event as CustomEvent<StartTourPayload>;
|
||||
setRequestedTourType(detail?.tourType ?? 'tools');
|
||||
setTourRequested(true);
|
||||
};
|
||||
|
||||
window.addEventListener(START_TOUR_EVENT, handleTourRequest);
|
||||
return () => window.removeEventListener(START_TOUR_EVENT, handleTourRequest);
|
||||
}, []);
|
||||
|
||||
const clearTourRequest = useCallback(() => {
|
||||
setTourRequested(false);
|
||||
}, []);
|
||||
|
||||
return { tourRequested, requestedTourType, clearTourRequest };
|
||||
}
|
||||
@@ -1,6 +1,26 @@
|
||||
import type { StepType } from '@reactour/tour';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { TourStep } from '@app/components/onboarding/tourSteps';
|
||||
|
||||
export enum TourStep {
|
||||
ALL_TOOLS,
|
||||
SELECT_CROP_TOOL,
|
||||
TOOL_INTERFACE,
|
||||
FILES_BUTTON,
|
||||
FILE_SOURCES,
|
||||
WORKBENCH,
|
||||
VIEW_SWITCHER,
|
||||
VIEWER,
|
||||
PAGE_EDITOR,
|
||||
ACTIVE_FILES,
|
||||
FILE_CHECKBOX,
|
||||
SELECT_CONTROLS,
|
||||
CROP_SETTINGS,
|
||||
RUN_BUTTON,
|
||||
RESULTS,
|
||||
FILE_REPLACEMENT,
|
||||
PIN_BUTTON,
|
||||
WRAP_UP,
|
||||
}
|
||||
|
||||
interface UserStepActions {
|
||||
saveWorkbenchState: () => void;
|
||||
|
||||
@@ -7,7 +7,7 @@ import { NavKey, VALID_NAV_KEYS } from '@app/components/shared/config/types';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
import '@app/components/shared/AppConfigModal.css';
|
||||
import { useIsMobile } from '@app/hooks/useIsMobile';
|
||||
import { Z_INDEX_OVER_FULLSCREEN_SURFACE, Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
|
||||
import { Z_INDEX_CONFIG_MODAL, Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
|
||||
import { useLicenseAlert } from '@app/hooks/useLicenseAlert';
|
||||
import { UnsavedChangesProvider, useUnsavedChanges } from '@app/contexts/UnsavedChangesContext';
|
||||
|
||||
@@ -122,7 +122,7 @@ const AppConfigModalInner: React.FC<AppConfigModalProps> = ({ opened, onClose })
|
||||
centered
|
||||
radius="lg"
|
||||
withCloseButton={false}
|
||||
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
|
||||
zIndex={Z_INDEX_CONFIG_MODAL}
|
||||
overlayProps={{ opacity: 0.35, blur: 2 }}
|
||||
padding={0}
|
||||
fullScreen={isMobile}
|
||||
|
||||
@@ -130,11 +130,6 @@ export const InfoBanner: React.FC<InfoBannerProps> = ({
|
||||
onClick={onButtonClick}
|
||||
loading={loading}
|
||||
leftSection={<LocalIcon icon={buttonIcon} width="0.9rem" height="0.9rem" />}
|
||||
styles={{
|
||||
label: {
|
||||
color: textColor ?? toneStyle.text,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{buttonText}
|
||||
</Button>
|
||||
|
||||
@@ -15,8 +15,8 @@ import AllToolsNavButton from '@app/components/shared/AllToolsNavButton';
|
||||
import ActiveToolButton from "@app/components/shared/quickAccessBar/ActiveToolButton";
|
||||
import AppConfigModal from '@app/components/shared/AppConfigModal';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
import { useOnboarding } from '@app/contexts/OnboardingContext';
|
||||
import { useLicenseAlert } from "@app/hooks/useLicenseAlert";
|
||||
import { requestStartTour } from '@app/constants/events';
|
||||
|
||||
import {
|
||||
isNavButtonActive,
|
||||
@@ -34,7 +34,6 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
const { handleReaderToggle, handleToolSelect, selectedToolKey, leftPanelView, toolRegistry, readerMode, resetTool } = useToolWorkflow();
|
||||
const { getToolNavigation } = useSidebarNavigation();
|
||||
const { config } = useAppConfig();
|
||||
const { startTour } = useOnboarding();
|
||||
const licenseAlert = useLicenseAlert();
|
||||
const [configModalOpen, setConfigModalOpen] = useState(false);
|
||||
const [activeButton, setActiveButton] = useState<string>('tools');
|
||||
@@ -269,7 +268,7 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
<div
|
||||
key={buttonConfig.id}
|
||||
data-tour="help-button"
|
||||
onClick={() => startTour('tools')}
|
||||
onClick={() => requestStartTour('tools')}
|
||||
>
|
||||
{renderNavButton(buttonConfig, index)}
|
||||
</div>
|
||||
@@ -286,7 +285,7 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item
|
||||
leftSection={<LocalIcon icon="view-carousel-rounded" width="1.25rem" height="1.25rem" />}
|
||||
onClick={() => startTour('tools')}
|
||||
onClick={() => requestStartTour('tools')}
|
||||
>
|
||||
<div>
|
||||
<div style={{ fontWeight: 500 }}>
|
||||
@@ -299,7 +298,7 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
leftSection={<LocalIcon icon="admin-panel-settings-rounded" width="1.25rem" height="1.25rem" />}
|
||||
onClick={() => startTour('admin')}
|
||||
onClick={() => requestStartTour('admin')}
|
||||
>
|
||||
<div>
|
||||
<div style={{ fontWeight: 500 }}>
|
||||
|
||||
@@ -20,7 +20,6 @@ import DarkModeIcon from '@mui/icons-material/DarkMode';
|
||||
import LightModeIcon from '@mui/icons-material/LightMode';
|
||||
|
||||
import { useSidebarContext } from '@app/contexts/SidebarContext';
|
||||
import { useChatbot } from '@app/contexts/ChatbotContext';
|
||||
import { RightRailButtonConfig, RightRailRenderContext, RightRailSection } from '@app/types/rightRail';
|
||||
import { useRightRailTooltipSide } from '@app/hooks/useRightRailTooltipSide';
|
||||
|
||||
@@ -52,7 +51,6 @@ export default function RightRail() {
|
||||
const viewerContext = React.useContext(ViewerContext);
|
||||
const { toggleTheme, themeMode } = useRainbowThemeContext();
|
||||
const { buttons, actions, allButtonsDisabled } = useRightRail();
|
||||
const { openChat } = useChatbot();
|
||||
|
||||
const { pageEditorFunctions, toolPanelMode, leftPanelView } = useToolWorkflow();
|
||||
const disableForFullscreen = toolPanelMode === 'fullscreen' && leftPanelView === 'toolPicker';
|
||||
@@ -67,8 +65,6 @@ export default function RightRail() {
|
||||
const pageEditorTotalPages = pageEditorFunctions?.totalPages ?? 0;
|
||||
const pageEditorSelectedCount = pageEditorFunctions?.selectedPageIds?.length ?? 0;
|
||||
const exportState = viewerContext?.getExportState?.();
|
||||
const chatLabel = t('chatbot.viewerButton', 'Chat about this PDF');
|
||||
const viewerActiveFile = activeFiles[viewerContext?.activeFileIndex ?? 0];
|
||||
|
||||
const totalItems = useMemo(() => {
|
||||
if (currentView === 'pageEditor') return pageEditorTotalPages;
|
||||
@@ -244,24 +240,6 @@ export default function RightRail() {
|
||||
tooltipPosition,
|
||||
tooltipOffset
|
||||
)}
|
||||
{renderWithTooltip(
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
radius="md"
|
||||
className="right-rail-icon"
|
||||
onClick={() => {
|
||||
if (viewerActiveFile) {
|
||||
openChat({ source: 'viewer', fileId: viewerActiveFile.fileId });
|
||||
} else {
|
||||
openChat({ source: 'viewer' });
|
||||
}
|
||||
}}
|
||||
disabled={!viewerActiveFile}
|
||||
>
|
||||
<LocalIcon icon="smart-toy-rounded" width="1.5rem" height="1.5rem" />
|
||||
</ActionIcon>,
|
||||
chatLabel
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="right-rail-spacer" />
|
||||
|
||||
@@ -3,65 +3,39 @@ import { Badge, Button, Card, Group, Modal, Stack, Text } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
|
||||
import { usePreferences } from '@app/contexts/PreferencesContext';
|
||||
import { useOnboarding } from '@app/contexts/OnboardingContext';
|
||||
import '@app/components/tools/ToolPanelModePrompt.css';
|
||||
import { type ToolPanelMode } from '@app/constants/toolPanel';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
|
||||
interface ToolPanelModePromptProps {
|
||||
onComplete?: () => void;
|
||||
/** If true, the modal will be forced open (used by orchestrator) */
|
||||
forceOpen?: boolean;
|
||||
}
|
||||
|
||||
const ToolPanelModePrompt = ({ onComplete }: ToolPanelModePromptProps = {}) => {
|
||||
/**
|
||||
* ToolPanelModePrompt - Lets users choose between sidebar and fullscreen tool modes
|
||||
*
|
||||
* The orchestrator controls this via forceOpen prop. When shown standalone (legacy),
|
||||
* it uses internal state based on preferences.
|
||||
*/
|
||||
const ToolPanelModePrompt = ({ onComplete, forceOpen }: ToolPanelModePromptProps = {}) => {
|
||||
const { t } = useTranslation();
|
||||
const { toolPanelMode, setToolPanelMode } = useToolWorkflow();
|
||||
const { preferences, updatePreference } = usePreferences();
|
||||
const {
|
||||
startTour,
|
||||
startAfterToolModeSelection,
|
||||
setStartAfterToolModeSelection,
|
||||
pendingTourRequest,
|
||||
} = useOnboarding();
|
||||
const [opened, setOpened] = useState(false);
|
||||
const { config } = useAppConfig();
|
||||
const isAdmin = !!config?.isAdmin;
|
||||
const [internalOpened, setInternalOpened] = useState(false);
|
||||
|
||||
// Only show after the new 3-slide onboarding has been completed
|
||||
// Only show after the intro onboarding has been completed (legacy standalone mode)
|
||||
const shouldShowPrompt = !preferences.toolPanelModePromptSeen && preferences.hasSeenIntroOnboarding;
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldShowPrompt) {
|
||||
setOpened(true);
|
||||
if (shouldShowPrompt && forceOpen === undefined) {
|
||||
setInternalOpened(true);
|
||||
}
|
||||
}, [shouldShowPrompt]);
|
||||
}, [shouldShowPrompt, forceOpen]);
|
||||
|
||||
const resolveRequestedTourType = (): 'admin' | 'tools' => {
|
||||
if (pendingTourRequest?.type) {
|
||||
return pendingTourRequest.type;
|
||||
}
|
||||
if (pendingTourRequest?.metadata && 'selfReportedAdmin' in pendingTourRequest.metadata) {
|
||||
return pendingTourRequest.metadata.selfReportedAdmin ? 'admin' : 'tools';
|
||||
}
|
||||
return isAdmin ? 'admin' : 'tools';
|
||||
};
|
||||
|
||||
const resumeDeferredTour = (context?: { selection?: ToolPanelMode; dismissed?: boolean }) => {
|
||||
if (!startAfterToolModeSelection) {
|
||||
return;
|
||||
}
|
||||
setStartAfterToolModeSelection(false);
|
||||
const targetType = resolveRequestedTourType();
|
||||
startTour(targetType, {
|
||||
skipToolPromptRequirement: true,
|
||||
source: 'tool-panel-mode-prompt',
|
||||
metadata: {
|
||||
...pendingTourRequest?.metadata,
|
||||
resumedFromToolPrompt: true,
|
||||
...(context?.selection ? { selection: context.selection } : {}),
|
||||
...(context?.dismissed ? { dismissed: true } : {}),
|
||||
},
|
||||
});
|
||||
};
|
||||
// If forceOpen is provided, use it; otherwise use internal state
|
||||
const opened = forceOpen ?? internalOpened;
|
||||
const setOpened = forceOpen !== undefined ? () => {} : setInternalOpened;
|
||||
|
||||
const handleSelect = (mode: ToolPanelMode) => {
|
||||
setToolPanelMode(mode);
|
||||
@@ -69,8 +43,6 @@ const ToolPanelModePrompt = ({ onComplete }: ToolPanelModePromptProps = {}) => {
|
||||
updatePreference('toolPanelModePromptSeen', true);
|
||||
updatePreference('hasSelectedToolPanelMode', true);
|
||||
setOpened(false);
|
||||
|
||||
resumeDeferredTour({ selection: mode });
|
||||
onComplete?.();
|
||||
};
|
||||
|
||||
@@ -83,7 +55,6 @@ const ToolPanelModePrompt = ({ onComplete }: ToolPanelModePromptProps = {}) => {
|
||||
updatePreference('hasSelectedToolPanelMode', true);
|
||||
updatePreference('toolPanelModePromptSeen', true);
|
||||
setOpened(false);
|
||||
resumeDeferredTour({ dismissed: true });
|
||||
onComplete?.();
|
||||
};
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import { ThumbnailPluginPackage } from '@embedpdf/plugin-thumbnail/react';
|
||||
import { RotatePluginPackage, Rotate } from '@embedpdf/plugin-rotate/react';
|
||||
import { ExportPluginPackage } from '@embedpdf/plugin-export/react';
|
||||
import { BookmarkPluginPackage } from '@embedpdf/plugin-bookmark';
|
||||
import { PrintPluginPackage } from '@embedpdf/plugin-print/react';
|
||||
|
||||
// Import annotation plugins
|
||||
import { HistoryPluginPackage } from '@embedpdf/plugin-history/react';
|
||||
@@ -41,6 +42,7 @@ import { HistoryAPIBridge } from '@app/components/viewer/HistoryAPIBridge';
|
||||
import type { SignatureAPI, HistoryAPI } from '@app/components/viewer/viewerTypes';
|
||||
import { ExportAPIBridge } from '@app/components/viewer/ExportAPIBridge';
|
||||
import { BookmarkAPIBridge } from '@app/components/viewer/BookmarkAPIBridge';
|
||||
import { PrintAPIBridge } from '@app/components/viewer/PrintAPIBridge';
|
||||
import { isPdfFile } from '@app/utils/fileUtils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LinkLayer } from '@app/components/viewer/LinkLayer';
|
||||
@@ -95,7 +97,10 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, onSignatur
|
||||
strategy: ScrollStrategy.Vertical,
|
||||
initialPage: 0,
|
||||
}),
|
||||
createPluginRegistration(RenderPluginPackage),
|
||||
createPluginRegistration(RenderPluginPackage, {
|
||||
withForms: true,
|
||||
withAnnotations: true,
|
||||
}),
|
||||
|
||||
// Register interaction manager (required for zoom and selection features)
|
||||
createPluginRegistration(InteractionManagerPluginPackage),
|
||||
@@ -156,6 +161,9 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, onSignatur
|
||||
createPluginRegistration(ExportPluginPackage, {
|
||||
defaultFileName: 'document.pdf',
|
||||
}),
|
||||
|
||||
// Register print plugin for printing PDFs
|
||||
createPluginRegistration(PrintPluginPackage),
|
||||
];
|
||||
}, [pdfUrl]);
|
||||
|
||||
@@ -301,6 +309,7 @@ export function LocalEmbedPDF({ file, url, enableAnnotations = false, onSignatur
|
||||
{enableAnnotations && <HistoryAPIBridge ref={historyApiRef} />}
|
||||
<ExportAPIBridge />
|
||||
<BookmarkAPIBridge />
|
||||
<PrintAPIBridge />
|
||||
<GlobalPointerProvider>
|
||||
<Viewport
|
||||
style={{
|
||||
|
||||
@@ -85,7 +85,10 @@ export function LocalEmbedPDFWithAnnotations({
|
||||
strategy: ScrollStrategy.Vertical,
|
||||
initialPage: 0,
|
||||
}),
|
||||
createPluginRegistration(RenderPluginPackage),
|
||||
createPluginRegistration(RenderPluginPackage, {
|
||||
withForms: true,
|
||||
withAnnotations: true,
|
||||
}),
|
||||
|
||||
// Register interaction manager (required for annotations)
|
||||
createPluginRegistration(InteractionManagerPluginPackage),
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useEffect } from 'react';
|
||||
import { usePrintCapability } from '@embedpdf/plugin-print/react';
|
||||
import { useViewer } from '@app/contexts/ViewerContext';
|
||||
|
||||
/**
|
||||
* Component that runs inside EmbedPDF context and exposes print API to ViewerContext
|
||||
*/
|
||||
export function PrintAPIBridge() {
|
||||
const { provides: print } = usePrintCapability();
|
||||
const { registerBridge } = useViewer();
|
||||
|
||||
useEffect(() => {
|
||||
if (print) {
|
||||
// Register this bridge with ViewerContext
|
||||
registerBridge('print', {
|
||||
state: {},
|
||||
api: {
|
||||
print: () => print.print(),
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [print, registerBridge]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -7,16 +7,12 @@ import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { Tooltip } from '@app/components/shared/Tooltip';
|
||||
import { SearchInterface } from '@app/components/viewer/SearchInterface';
|
||||
import ViewerAnnotationControls from '@app/components/shared/rightRail/ViewerAnnotationControls';
|
||||
import { useFileState } from '@app/contexts/FileContext';
|
||||
import { useSidebarContext } from '@app/contexts/SidebarContext';
|
||||
import { useRightRailTooltipSide } from '@app/hooks/useRightRailTooltipSide';
|
||||
|
||||
export function useViewerRightRailButtons() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const viewer = useViewer();
|
||||
const { selectors } = useFileState();
|
||||
const filesSignature = selectors.getFilesSignature();
|
||||
const files = useMemo(() => selectors.getFiles(), [selectors, filesSignature]);
|
||||
const [isPanning, setIsPanning] = useState<boolean>(() => viewer.getPanState()?.isPanning ?? false);
|
||||
const { sidebarRefs } = useSidebarContext();
|
||||
const { position: tooltipPosition } = useRightRailTooltipSide(sidebarRefs, 12);
|
||||
@@ -28,6 +24,7 @@ export function useViewerRightRailButtons() {
|
||||
const rotateRightLabel = t('rightRail.rotateRight', 'Rotate Right');
|
||||
const sidebarLabel = t('rightRail.toggleSidebar', 'Toggle Sidebar');
|
||||
const bookmarkLabel = t('rightRail.toggleBookmarks', 'Toggle Bookmarks');
|
||||
const printLabel = t('rightRail.print', 'Print PDF');
|
||||
|
||||
const viewerButtons = useMemo<RightRailButtonWithAction[]>(() => {
|
||||
return [
|
||||
@@ -131,6 +128,17 @@ export function useViewerRightRailButtons() {
|
||||
viewer.toggleBookmarkSidebar();
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'viewer-print',
|
||||
icon: <LocalIcon icon="print" width="1.5rem" height="1.5rem" />,
|
||||
tooltip: printLabel,
|
||||
ariaLabel: printLabel,
|
||||
section: 'top' as const,
|
||||
order: 56,
|
||||
onClick: () => {
|
||||
viewer.printActions.print();
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'viewer-annotation-controls',
|
||||
section: 'top' as const,
|
||||
@@ -140,19 +148,7 @@ export function useViewerRightRailButtons() {
|
||||
)
|
||||
}
|
||||
];
|
||||
}, [
|
||||
t,
|
||||
i18n.language,
|
||||
viewer,
|
||||
isPanning,
|
||||
searchLabel,
|
||||
panLabel,
|
||||
rotateLeftLabel,
|
||||
rotateRightLabel,
|
||||
sidebarLabel,
|
||||
bookmarkLabel,
|
||||
tooltipPosition,
|
||||
]);
|
||||
}, [t, i18n.language, viewer, isPanning, searchLabel, panLabel, rotateLeftLabel, rotateRightLabel, sidebarLabel, bookmarkLabel, printLabel, tooltipPosition]);
|
||||
|
||||
useRightRailButtons(viewerButtons);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,24 @@
|
||||
|
||||
// Base path from Vite config - build-time constant, normalized (no trailing slash)
|
||||
// When no subpath, use empty string instead of '.' to avoid relative path issues
|
||||
export const BASE_PATH = (import.meta.env.BASE_URL || '/').replace(/\/$/, '').replace(/^\.$/, '');
|
||||
// Base path - read from <base> tag at runtime to support dynamic subpaths
|
||||
// Falls back to Vite's BASE_URL for build-time subpaths
|
||||
// Normalized: no trailing slash, empty string instead of '.' or '/'
|
||||
function getBasePath(): string {
|
||||
// Try to read from <base> tag first (runtime subpath support)
|
||||
if (typeof document !== 'undefined') {
|
||||
const baseElement = document.querySelector('base');
|
||||
if (baseElement) {
|
||||
const href = baseElement.getAttribute('href');
|
||||
if (href && href !== '%BASE_URL%') {
|
||||
return href.replace(/\/$/, '').replace(/^\.$/, '').replace(/^\/$/, '');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to Vite's BASE_URL (build-time subpath)
|
||||
return (import.meta.env.BASE_URL || '/').replace(/\/$/, '').replace(/^\.$/, '').replace(/^\/$/, '');
|
||||
}
|
||||
|
||||
export const BASE_PATH = getBasePath();
|
||||
|
||||
// EmbedPDF needs time to remove annotations internally before a recreation runs.
|
||||
// Without the buffer we occasionally end up with duplicate annotations or stale image data.
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { LicenseNotice } from '@app/types/types';
|
||||
|
||||
export const ONBOARDING_SESSION_BLOCK_KEY = 'stirling-onboarding-session-active';
|
||||
export const ONBOARDING_SESSION_EVENT = 'stirling:onboarding-session-started';
|
||||
export const SERVER_LICENSE_REQUEST_EVENT = 'stirling:server-license-requested';
|
||||
export const UPGRADE_BANNER_TEST_EVENT = 'stirling:upgrade-banner-test';
|
||||
export const UPGRADE_BANNER_ALERT_EVENT = 'stirling:upgrade-banner-alert';
|
||||
export const START_TOUR_EVENT = 'stirling:start-tour';
|
||||
export const TOUR_STATE_EVENT = 'stirling:tour-state';
|
||||
|
||||
export interface ServerLicenseRequestPayload {
|
||||
licenseNotice?: Partial<LicenseNotice>;
|
||||
@@ -25,3 +25,29 @@ export interface UpgradeBannerAlertPayload {
|
||||
freeTierLimit?: number;
|
||||
}
|
||||
|
||||
export type TourType = 'admin' | 'tools';
|
||||
|
||||
export interface StartTourPayload {
|
||||
tourType: TourType;
|
||||
}
|
||||
|
||||
export interface TourStatePayload {
|
||||
isOpen: boolean;
|
||||
}
|
||||
|
||||
/** Helper to dispatch the start tour event */
|
||||
export function requestStartTour(tourType: TourType): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<StartTourPayload>(START_TOUR_EVENT, { detail: { tourType } })
|
||||
);
|
||||
}
|
||||
|
||||
/** Helper to dispatch tour state changes (for hiding cookie consent during tour) */
|
||||
export function dispatchTourState(isOpen: boolean): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<TourStatePayload>(TOUR_STATE_EVENT, { detail: { isOpen } })
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Route constants used across the application
|
||||
*/
|
||||
|
||||
/**
|
||||
* Routes where onboarding, cookie consent, and upgrade banners should not appear.
|
||||
* These are authentication-related pages where users are not yet logged in or
|
||||
* the main app chrome is not displayed.
|
||||
*/
|
||||
export const AUTH_ROUTES = [
|
||||
'/login',
|
||||
'/signup',
|
||||
'/auth',
|
||||
'/invite',
|
||||
'/forgot-password',
|
||||
'/reset-password',
|
||||
];
|
||||
|
||||
/**
|
||||
* Check if a pathname matches any auth route
|
||||
*/
|
||||
export function isAuthRoute(pathname: string): boolean {
|
||||
return AUTH_ROUTES.some((route) => pathname.startsWith(route));
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user