#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
AI settings: status card and connection mode chooser (#8102)
Anthony Stirlinge28914992b35
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.javaindex d7fb31fa42..9383f945ba 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java@@ -1,6 +1,7 @@package stirling.software.proprietary.accountlink;import java.io.IOException;+import java.util.Map;import org.springframework.beans.factory.ObjectProvider;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;@@ -23,8 +24,8 @@ import lombok.extern.slf4j.Slf4j;/*** Same-origin account-link surface on the self-hosted instance (combined billing).*- * <p>Owner-only class-wide: everything here is server-scoped, the free-tier meter included. Other- * users learn of the wall from the {@code reason} on the 402, not from here.+ * <p>Owner-only class-wide except {@link #linked()}: everything else is server-scoped, the+ * free-tier meter included. Other users learn of the wall from the {@code reason} on the 402.*/@Slf4j@Hidden@@ -162,6 +163,13 @@ public class AccountLinkController {return ResponseEntity.ok(service.status());}+ /** Any admin, not only the owner: the AI settings page needs it and a bare flag is harmless. */+ @GetMapping("/linked")+ @PreAuthorize("hasRole('ADMIN')")+ public ResponseEntity<Map<String, Boolean>> linked() {+ return ResponseEntity.ok(Map.of("linked", service.isLinked()));+ }+/** Refreshes cloud entitlement without changing the linked account. */@PostMapping("/recheck")public ResponseEntity<AccountLinkService.LinkStatus> recheck() {diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.javaindex 5acce9c744..c1f00cc54c 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkService.java@@ -72,6 +72,11 @@ public class AccountLinkService {return status();}+ /** Local only: unlike {@link #status()}, never refreshes entitlement from Stirling Cloud. */+ public boolean isLinked() {+ return credentialStore.isLinked();+ }+public LinkStatus status() {Optional<DeviceCredential> cred = credentialStore.get();if (cred.isPresent()) entitlementCache.current();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.javaindex ff2bcd2b74..92feabe50f 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/AiEngineController.java@@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;+import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PostMapping;@@ -58,6 +59,9 @@ import tools.jackson.databind.node.ObjectNode;@Tag(name = "AI Engine", description = "Endpoints for AI-powered PDF workflows")public class AiEngineController {+ /** Per probe, connect included, so a hung engine cannot hold a request for minutes. */+ static final Duration PROBE_TIMEOUT = Duration.ofSeconds(5);+private final AiEngineClient aiEngineClient;private final AiWorkflowService aiWorkflowService;private final ObjectMapper objectMapper;@@ -115,15 +119,16 @@ public class AiEngineController {summary = "AI engine health check",description = "Returns the health status of the AI engine including configured models")public ResponseEntity<String> health() throws IOException {- String response = aiEngineClient.get("/health", currentUserId());+ String response = aiEngineClient.get("/health", currentUserId(), PROBE_TIMEOUT);return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(response);}/*** Also probes a secret-gated route: the engine's {@code /health} skips the shared-secret check,- * so it stays green while real calls get 401.+ * so it stays green while real calls get 401. Admin-only, as each call makes 2-4 requests.*/@GetMapping("/status")+ @PreAuthorize("hasRole('ADMIN')")@Operation(summary = "AI engine status",description =@@ -160,7 +165,7 @@ public class AiEngineController {long startedAt = System.nanoTime();String health;try {- health = aiEngineClient.get("/health", userId);+ health = aiEngineClient.get("/health", userId, PROBE_TIMEOUT);} catch (IOException | RuntimeException e) {return status.reachable(false).error(describeFailure(e)).build();}@@ -184,7 +189,8 @@ public class AiEngineController {*/private Boolean probeCloudSharing(String userId) {try {- JsonNode body = objectMapper.readTree(aiEngineClient.get("/status", userId));+ JsonNode body =+ objectMapper.readTree(aiEngineClient.get("/status", userId, PROBE_TIMEOUT));JsonNode enabled = body.path("sharingEnabled");return enabled.isBoolean() ? enabled.asBoolean() : null;} catch (IOException | RuntimeException e) {@@ -199,7 +205,7 @@ public class AiEngineController {private Boolean probeAuthentication(String userId, AiEngineStatus.AiEngineStatusBuilder status) {try {- aiEngineClient.get("/api/v1/agents/capabilities", userId);+ aiEngineClient.get("/api/v1/agents/capabilities", userId, PROBE_TIMEOUT);return true;} catch (AiEngineClient.EngineRejectedCredentials e) {status.error(diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.javaindex d1fd6ab258..deb1189485 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/AiEngineClient.java@@ -219,6 +219,14 @@ public class AiEngineClient {}public String get(String path, String userId) throws IOException {+ return get(+ path,+ userId,+ Duration.ofSeconds(applicationProperties.getAiEngine().getTimeoutSeconds()));+ }++ /** GET with its own timeout, which also bounds the connect, so a probe cannot hang. */+ public String get(String path, String userId, Duration timeout) throws IOException {ApplicationProperties.AiEngine config = applicationProperties.getAiEngine();if (!config.isEnabled()) {throw new ResponseStatusException(@@ -233,7 +241,7 @@ public class AiEngineClient {HttpRequest.newBuilder().uri(URI.create(url)).header("Accept", "application/json")- .timeout(Duration.ofSeconds(config.getTimeoutSeconds()))+ .timeout(timeout).GET();addUserHeader(builder, userId);addEngineAuthHeader(builder, target);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerAuthorizationTest.javanew file mode 100644index 0000000000..79c810f672--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerAuthorizationTest.java@@ -0,0 +1,109 @@+package stirling.software.proprietary.accountlink;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.util.List;+import java.util.Map;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.aop.framework.ProxyFactory;+import org.springframework.beans.factory.ObjectProvider;+import org.springframework.context.support.StaticApplicationContext;+import org.springframework.security.access.AccessDeniedException;+import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;+import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor;+import org.springframework.security.authorization.method.PreAuthorizeAuthorizationManager;+import org.springframework.security.core.authority.SimpleGrantedAuthority;+import org.springframework.security.core.context.SecurityContextHolder;++import stirling.software.proprietary.service.OrgOwnerService;++/**+ * Runs the real {@code @PreAuthorize} expressions: {@code /linked} is open to every admin, while+ * the rest of the controller stays with the organisation owner.+ */+class AccountLinkControllerAuthorizationTest {++ private OrgOwnerService orgOwnerService;+ private AccountLinkController secured;++ @BeforeEach+ @SuppressWarnings("unchecked")+ void setUp() {+ AccountLinkService service = mock(AccountLinkService.class);+ when(service.isLinked()).thenReturn(true);+ when(service.status()).thenReturn(new AccountLinkService.LinkStatus(true, "d", 1L, null));+ orgOwnerService = mock(OrgOwnerService.class);++ StaticApplicationContext context = new StaticApplicationContext();+ context.getBeanFactory().registerSingleton("orgOwnerService", orgOwnerService);+ context.refresh();+ DefaultMethodSecurityExpressionHandler expressions =+ new DefaultMethodSecurityExpressionHandler();+ expressions.setApplicationContext(context);+ PreAuthorizeAuthorizationManager manager = new PreAuthorizeAuthorizationManager();+ manager.setExpressionHandler(expressions);++ ProxyFactory factory =+ new ProxyFactory(+ new AccountLinkController(+ service,+ mock(ConnectService.class),+ mock(LocalUsageService.class),+ mock(FreeTierUsageService.class),+ mock(ObjectProvider.class)));+ factory.setProxyTargetClass(true);+ factory.addAdvisor(AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager));+ secured = (AccountLinkController) factory.getProxy();+ }++ @AfterEach+ void clearAuthentication() {+ SecurityContextHolder.clearContext();+ }++ private void signInAs(String role, boolean owner) {+ SecurityContextHolder.getContext()+ .setAuthentication(+ new UsernamePasswordAuthenticationToken(+ "someone", "n/a", List.of(new SimpleGrantedAuthority(role))));+ when(orgOwnerService.isCurrentUser(any())).thenReturn(owner);+ }++ @Test+ void anAdminWhoIsNotTheOwnerCanSeeWhetherTheServerIsLinked() {+ signInAs("ROLE_ADMIN", false);++ assertThat(secured.linked().getBody()).isEqualTo(Map.of("linked", true));+ }++ @Test+ void anAdminWhoIsNotTheOwnerStillCannotReadTheFullStatus() {+ signInAs("ROLE_ADMIN", false);++ assertThrows(AccessDeniedException.class, () -> secured.status());+ }++ @Test+ void theOwnerCanReadBoth() {+ signInAs("ROLE_ADMIN", true);++ assertThat(secured.linked().getBody()).isEqualTo(Map.of("linked", true));+ assertThat(secured.status().getBody().linked()).isTrue();+ }++ @Test+ void aUserWhoIsNotAnAdminCannotAskEither() {+ signInAs("ROLE_USER", false);++ assertThrows(AccessDeniedException.class, () -> secured.linked());+ assertThrows(AccessDeniedException.class, () -> secured.status());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/AiEngineControllerStatusTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/AiEngineControllerStatusTest.javanew file mode 100644index 0000000000..784713ef59--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/controller/api/AiEngineControllerStatusTest.java@@ -0,0 +1,148 @@+package stirling.software.proprietary.controller.api;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.util.List;+import java.util.concurrent.Executor;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.aop.framework.ProxyFactory;+import org.springframework.security.access.AccessDeniedException;+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;+import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor;+import org.springframework.security.authorization.method.PreAuthorizeAuthorizationManager;+import org.springframework.security.core.authority.SimpleGrantedAuthority;+import org.springframework.security.core.context.SecurityContextHolder;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.service.JobOwnershipService;+import stirling.software.common.service.TaskManager;+import stirling.software.proprietary.model.api.ai.AiEngineStatus;+import stirling.software.proprietary.service.AiEngineClient;+import stirling.software.proprietary.service.AiEngineEndpointResolver;+import stirling.software.proprietary.service.AiEngineRouter;+import stirling.software.proprietary.service.AiFeatureGate;+import stirling.software.proprietary.service.AiWorkflowService;+import stirling.software.proprietary.service.CloudStatusProbe;++import tools.jackson.databind.json.JsonMapper;++/**+ * The status card's endpoint fans out to the engine (and to Stirling Cloud in cloud mode), so it is+ * admin-only and every probe carries a short timeout.+ */+class AiEngineControllerStatusTest {++ private AiEngineClient engine;+ private AiEngineRouter router;+ private CloudStatusProbe cloudProbe;+ private AiEngineController controller;++ @BeforeEach+ void setUp() throws Exception {+ ApplicationProperties props = new ApplicationProperties();+ props.getAiEngine().setEnabled(true);+ engine = mock(AiEngineClient.class);+ router = mock(AiEngineRouter.class);+ cloudProbe = mock(CloudStatusProbe.class);+ when(engine.get(eq("/health"), any(), any()))+ .thenReturn("{\"smartModel\":\"smart\",\"fastModel\":\"fast\"}");+ when(engine.get(eq("/api/v1/agents/capabilities"), any(), any())).thenReturn("{}");+ when(engine.get(eq("/status"), any(), any())).thenReturn("{\"sharingEnabled\":true}");+ controller =+ new AiEngineController(+ engine,+ mock(AiWorkflowService.class),+ JsonMapper.builder().build(),+ mock(Executor.class),+ mock(TaskManager.class),+ mock(JobOwnershipService.class),+ mock(AiEngineEndpointResolver.class),+ mock(AiFeatureGate.class),+ props,+ router,+ cloudProbe,+ null);+ }++ @AfterEach+ void clearAuthentication() {+ SecurityContextHolder.clearContext();+ }++ private static void signInAs(String role) {+ SecurityContextHolder.getContext()+ .setAuthentication(+ new UsernamePasswordAuthenticationToken(+ "someone", "n/a", List.of(new SimpleGrantedAuthority(role))));+ }++ /** The controller behind the same @PreAuthorize interceptor Spring installs. */+ private AiEngineController secured() {+ ProxyFactory factory = new ProxyFactory(controller);+ factory.setProxyTargetClass(true);+ factory.addAdvisor(+ AuthorizationManagerBeforeMethodInterceptor.preAuthorize(+ new PreAuthorizeAuthorizationManager()));+ return (AiEngineController) factory.getProxy();+ }++ @Test+ void statusRefusesUsersWhoAreNotAdmins() throws Exception {+ signInAs("ROLE_USER");++ assertThrows(AccessDeniedException.class, () -> secured().status());+ verify(engine, never()).get(anyString(), any(), any());+ }++ @Test+ void statusAnswersAdmins() {+ signInAs("ROLE_ADMIN");++ AiEngineStatus status = secured().status();++ assertTrue(status.isReachable());+ assertEquals("smart", status.getSmartModel());+ assertEquals(Boolean.TRUE, status.getAuthenticated());+ }++ @Test+ void selfHostedProbesUseTheShortTimeout() throws Exception {+ controller.status();++ verify(engine).get("/health", null, AiEngineController.PROBE_TIMEOUT);+ verify(engine).get("/api/v1/agents/capabilities", null, AiEngineController.PROBE_TIMEOUT);+ verify(engine, never()).get(anyString(), any());+ }++ @Test+ void cloudProbesUseTheShortTimeout() throws Exception {+ when(router.isCloudMode()).thenReturn(true);+ when(cloudProbe.isUp()).thenReturn(true);++ AiEngineStatus status = controller.status();++ assertEquals(Boolean.TRUE, status.getCloudSharingEnabled());+ verify(engine).get("/status", null, AiEngineController.PROBE_TIMEOUT);+ verify(engine).get("/health", null, AiEngineController.PROBE_TIMEOUT);+ verify(engine, never()).get(anyString(), any());+ }++ @Test+ void healthUsesTheShortTimeout() throws Exception {+ controller.health();++ verify(engine).get("/health", null, AiEngineController.PROBE_TIMEOUT);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.javaindex d309020a02..636732f613 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/AiEngineClientTest.java@@ -194,4 +194,26 @@ class AiEngineClientTest {assertEquals(null, captor.getValue().headers().firstValue("X-Engine-Auth").orElse(null));}++ @Test+ @SuppressWarnings("unchecked")+ void getWithTimeoutPutsThatTimeoutOnTheRequest() throws Exception {+ HttpResponse<String> ok = mock(HttpResponse.class);+ when(ok.statusCode()).thenReturn(200);+ when(ok.body()).thenReturn("{}");+ org.mockito.ArgumentCaptor<java.net.http.HttpRequest> captor =+ org.mockito.ArgumentCaptor.forClass(java.net.http.HttpRequest.class);+ when(httpClient.send(captor.capture(), any(HttpResponse.BodyHandler.class))).thenReturn(ok);++ client.get("/health", null, java.time.Duration.ofSeconds(2));+ client.get("/health", null);++ assertEquals(+ java.util.Optional.of(java.time.Duration.ofSeconds(2)),+ captor.getAllValues().get(0).timeout());+ assertEquals(+ java.util.Optional.of(java.time.Duration.ofSeconds(5)),+ captor.getAllValues().get(1).timeout(),+ "the two-argument get keeps the configured timeout");+ }}diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex eab7d7d35e..0906f8215e 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -729,6 +729,8 @@ permissionNotice = "The tessdata path is not writable. Downloads will be opened[admin.settings.ai]description = "Connect Stirling to the Python AI engine, choose its models, and set the guardrails it runs under."+managedByCloud = "Managed by Stirling Cloud in this mode."+managedByCloudShort = "Managed by Stirling Cloud"[admin.settings.ai.documents]description = "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved."@@ -770,13 +772,26 @@ label = "Top K"[admin.settings.ai.general]connection = "Connection"-description = "Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart."+description = "Choose where AI runs. Changes here apply on restart."+restartNote = "Changing the URL or any timeout takes effect after a restart."title = "AI Engine"[admin.settings.ai.general.capabilities]description = "Turn individual AI features on or off. Disabled features are hidden in the app."title = "Capabilities"+[admin.settings.ai.general.cloud]+note = "Models and provider keys are managed by Stirling Cloud, so those settings do not apply in this mode."++[admin.settings.ai.general.cloud.indexing]+description = "Every AI tool sends the page text it needs to answer. This decides whether Stirling Cloud may also keep that text, indexed, so later questions can search across the document."+help = "Off means document questions are unavailable. It does not stop text being sent - only stored."+label = "Let Stirling Cloud keep indexed documents"++[admin.settings.ai.general.cloudNote]+body = "The reasoning runs on Stirling's infrastructure, billed to the account this server is linked to. There is no container to run and no provider key to hold here. Whatever the AI reads is processed by Stirling Cloud rather than on your own hardware."+title = "About Stirling Cloud AI"+[admin.settings.ai.general.enabled]description = "Master switch. When off, no AI tools, agents, or engine calls are available."label = "Enable AI"@@ -809,9 +824,28 @@ label = "PDF comment agent"description = "Timeout for heavier agent operations such as document generation."label = "Long-running timeout (seconds)"+[admin.settings.ai.general.mode]+label = "Where AI runs"++[admin.settings.ai.general.mode.cloud]+description = "No container, no provider key, no model choice - the work runs on Stirling Cloud and is billed to the account this server is linked to."+linkCta = "Connect this server to a Stirling account"+notLinked = "Link an account first"+ownerOnly = "Only the organization owner can link this server to a Stirling account."+title = "Use Stirling Cloud AI"++[admin.settings.ai.general.mode.off]+description = "No AI tools anywhere in the app, and nothing leaves this server."+title = "Off"++[admin.settings.ai.general.mode.self]+description = "A container you host, pointed at a model provider of your choosing. Your key, your bill, your data path."+title = "Run your own engine"+[admin.settings.ai.general.note]-body = "The AI engine runs as a separate service. Its shared secret"-body2 = "is set via a container environment variable. Provider API keys can be entered on these pages or supplied as engine environment variables; keys entered here are pushed to the engine when saved."+docs = "Set-up guide"+intro = "A separate container you run next to Stirling. It does the reasoning; Stirling still does every page operation itself. It needs the same"+outro = "on both containers and a model provider key. Whatever the AI reads is sent to the provider you pick - an Ollama you host keeps every page in-house."title = "About the AI engine"[admin.settings.ai.general.streamTimeoutSeconds]@@ -891,6 +925,67 @@ body = "Changes are pushed to the AI engine automatically."bodyNoPush = "Settings saved. They will apply the next time the AI engine picks up its configuration."title = "AI settings saved"+[admin.settings.ai.status]+capabilities = "Capabilities"+capabilitiesValue = "{{on}} of {{total}} on"+checked = "checked"+checking = "Checking the engine…"+description = "Whether the engine is reachable, whether it accepts this server, and what it is running."+fastModel = "Fast model"+justNow = "just now"+latency = "Response time"+linkLabel = "Account link"+minutesAgo = "{{count}}m ago"+recheck = "Check again"+runningOn = "Running on"+secondsAgo = "{{count}}s ago"+secretLabel = "Shared secret"+smartModel = "Smart model"+title = "Status"+url = "Engine URL"++[admin.settings.ai.status.cloud]+hostDown = "Down"+hostLabel = "Stirling.com"+hostUp = "Up"+name = "Stirling Cloud"+sharingLabel = "AI sharing"+sharingOff = "Disabled"+sharingOn = "Enabled"++[admin.settings.ai.status.cloud.degraded]+body = "Stirling Cloud answered but refused this server. The account link may have been revoked."+title = "Stirling Cloud is refusing this server"++[admin.settings.ai.status.cloud.down]+body = "This server could not reach Stirling Cloud. Check the account link and that this server can reach the internet."+title = "Stirling Cloud unreachable"++[admin.settings.ai.status.cloud.ok]+body = "Stirling Cloud accepted this server. Nothing to run or patch here."+title = "Running on Stirling Cloud"++[admin.settings.ai.status.degraded]+body = "It answered the health check but rejected a real request. The two sides are using different shared secrets."+title = "Engine is up, but refusing this server"++[admin.settings.ai.status.down]+body = "Check the URL, that the engine container is running, and that you restarted after enabling AI."+title = "Engine unreachable"++[admin.settings.ai.status.off]+body = "Choose how AI runs below, then save and restart."+title = "AI is switched off"++[admin.settings.ai.status.ok]+body = "Health check and an authenticated request both succeeded."+title = "Engine running"++[admin.settings.ai.status.secret]+no = "Rejected"+unknown = "Unknown"+yes = "Accepted"+[admin.settings.badge]clickToUpgrade = "Click to view plan details"diff --git a/frontend/editor/src/core/tests/stubbed/ai-settings-status.spec.ts b/frontend/editor/src/core/tests/stubbed/ai-settings-status.spec.tsnew file mode 100644index 0000000000..d68af13b79--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/ai-settings-status.spec.ts@@ -0,0 +1,572 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";+import type { Page, Route } from "@playwright/test";++/**+ * The AI page's status card and mode chooser.+ *+ * The case that matters is `degraded`: the engine's own /health is exempt from the shared-secret+ * check, so before this card an admin with a mismatched secret saw a green "AI engine reachable"+ * toast while every real request was being refused. The card must say amber there.+ */++test.use({ stubOptions: { enableLogin: true, isAdmin: true }, seedJwt: true });++/** The organization owner, the only admin the account-link page is listed for. */+const OWNER = {+ id: 1,+ username: "owner",+ email: "[email protected]",+ roles: ["ROLE_ADMIN"],+ role: "ROLE_ADMIN",+ orgOwner: true,+};++const ENABLED_SETTINGS = {+ enabled: true,+ url: "http://stirling-engine:5001",+ timeoutSeconds: 120,+ longRunningTimeoutSeconds: 600,+ streamTimeoutSeconds: 1800,+ features: {+ chat: true,+ documentQuestions: true,+ createPdf: true,+ mathAuditor: true,+ pdfComment: true,+ classify: false,+ },+ models: {+ provider: "anthropic",+ smartModel: "claude-sonnet-5",+ fastModel: "claude-haiku-4-5",+ },+ rag: { embeddingProvider: "voyageai", embeddingModel: "voyage-4", topK: 20 },+ limits: { maxPages: 500, maxCharacters: 200000, modelMaxConcurrency: 4 },+};++async function openAiSettings(+ page: Page,+ status: Record<string, unknown>,+ settings: Record<string, unknown> = ENABLED_SETTINGS,+ // null leaves the link status unanswered, as it is while the request is in flight.+ linked: boolean | null = false,+) {+ await page.route("**/api/v1/account-link/linked", (route: Route) =>+ linked === null ? undefined : route.fulfill({ json: { linked } }),+ );+ await page.route(+ "**/api/v1/admin/settings/section/aiEngine",+ (route: Route) => route.fulfill({ json: settings }),+ );+ await page.route("**/api/v1/ai/status", (route: Route) =>+ route.fulfill({ json: status }),+ );+ await page.goto("/settings/adminAi");+ await expect(page.locator(".settings-page")).toBeVisible({ timeout: 30_000 });+ await page.locator(".settings-card").first().waitFor({ timeout: 20_000 });+}++/** The card with this heading, so a word the status strip also uses stays unambiguous. */+function cardNamed(page: Page, heading: string) {+ return page.locator(".settings-card").filter({ hasText: heading }).first();+}++/**+ * Its label carries the info-tooltip text too, and "Smart model max tokens" shares the prefix, so+ * match far enough in to land on the model field itself.+ */+function smartModelInput(page: Page) {+ return cardNamed(page, "Models & Providers").getByRole("textbox", {+ name: /^Smart model High-capability/,+ });+}++test("a healthy engine reports its models and an accepted secret", async ({+ page,+}) => {+ await openAiSettings(page, {+ enabled: true,+ reachable: true,+ latencyMs: 84,+ authenticated: true,+ smartModel: "claude-sonnet-5",+ fastModel: "claude-haiku-4-5",+ });++ await expect(page.getByText("Engine running").first()).toBeVisible();+ await expect(page.getByText("claude-sonnet-5").first()).toBeVisible();+ await expect(page.getByText("claude-haiku-4-5").first()).toBeVisible();+ await expect(page.getByText("Accepted").first()).toBeVisible();+ await expect(page.getByText("84 ms").first()).toBeVisible();+});++test("a rejected shared secret reads as a problem, not as healthy", async ({+ page,+}) => {+ await openAiSettings(page, {+ enabled: true,+ reachable: true,+ latencyMs: 61,+ authenticated: false,+ smartModel: "claude-sonnet-5",+ fastModel: "claude-haiku-4-5",+ error: "The engine rejected this server's shared secret.",+ });++ await expect(+ page.getByText("Engine is up, but refusing this server").first(),+ ).toBeVisible();+ await expect(+ page.getByText(/different shared secrets/i).first(),+ ).toBeVisible();+ await expect(page.getByText("Rejected").first()).toBeVisible();+ // The engine answered /health, so anything keyed off reachability alone would say "running".+ await expect(page.getByText("Engine running")).toHaveCount(0);+});++test("an unreachable engine says so and offers no stale detail", async ({+ page,+}) => {+ await openAiSettings(page, {+ enabled: true,+ reachable: false,+ error: "AI engine request timed out",+ });++ await expect(page.getByText("Engine unreachable").first()).toBeVisible();+ await expect(+ page.getByText("AI engine request timed out").first(),+ ).toBeVisible();+});++test("with AI off the card stays quiet and the facts are hidden", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: false, reachable: false },+ { ...ENABLED_SETTINGS, enabled: false },+ );++ await expect(page.getByText("AI is switched off").first()).toBeVisible();+ // Scoped to the status card: "Smart model" is also a field label further down the page.+ const statusCard = page.locator(".settings-card").first();+ await expect(statusCard.getByText("Smart model")).toHaveCount(0);+ await expect(statusCard.getByText("Engine URL")).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: /Check again/i }),+ ).toBeDisabled();+});++test("the status card adds a Status anchor to the section nav", async ({+ page,+}) => {+ await openAiSettings(page, {+ enabled: true,+ reachable: true,+ authenticated: true,+ });++ // Poll because the cards mount lazily, and trim because WebKit keeps the whitespace around+ // each heading that Chromium strips - the raw strings are not comparable across engines.+ await expect+ .poll(async () =>+ (await page.locator(".settings-card__toggle").allInnerTexts()).map((t) =>+ t.trim(),+ ),+ )+ .toEqual([+ "Status",+ "Connection",+ "Capabilities",+ "Models & Providers",+ "Documents & RAG",+ "Limits & Performance",+ ]);+});++test("the mode chooser owns the engine fields, and cloud is not selectable", async ({+ page,+}) => {+ await openAiSettings(page, {+ enabled: true,+ reachable: true,+ authenticated: true,+ });++ const self = page.getByRole("radio", { name: /Run your own engine/i });+ const off = page.getByRole("radio", { name: /^Off$/i });+ const cloud = page.getByRole("radio", { name: /Stirling Cloud AI/i });++ await expect(self).toBeChecked();+ await expect(cloud).toBeDisabled();+ await expect(page.getByLabel(/AI engine URL/i)).toBeVisible();++ // Switching off takes the engine fields with it - they belong to the option.+ await off.click();+ await expect(off).toBeChecked();+ await expect(page.getByLabel(/AI engine URL/i)).toHaveCount(0);++ await self.click();+ await expect(page.getByLabel(/AI engine URL/i)).toBeVisible();+});++test("the about notice offers no set-up guide until its docs page exists", async ({+ page,+}) => {+ await openAiSettings(page, {+ enabled: true,+ reachable: true,+ authenticated: true,+ });++ await expect(page.getByText("About the AI engine")).toBeVisible();+ await expect(page.getByRole("link", { name: /Set-up guide/i })).toHaveCount(+ 0,+ );+});++test("cloud AI is not selectable until the server is linked", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ false,+ );++ await expect(+ page.getByRole("radio", { name: /Stirling Cloud AI/i }),+ ).toBeDisabled();+ await expect(page.getByText(/Link an account first/i).first()).toBeVisible();+});++test("cloud AI stays disabled while the link status is unknown", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ null,+ );++ await expect(+ page.getByRole("radio", { name: /Stirling Cloud AI/i }),+ ).toBeDisabled();+ // Unknown is not unlinked, so there is nothing to prompt for yet.+ await expect(page.getByText(/Link an account first/i)).toHaveCount(0);+});++test("a linked server can pick cloud AI, and ingestion is off until asked for", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ true,+ );++ const cloud = page.getByRole("radio", { name: /Stirling Cloud AI/i });+ await expect(cloud).toBeEnabled();+ await cloud.click();+ await expect(cloud).toBeChecked();++ // The engine fields belong to the self-hosted option and go with it.+ await expect(page.getByLabel(/AI engine URL/i)).toHaveCount(0);++ // The switch that decides whether whole documents leave the building, off by default.+ const upload = page.getByRole("switch", {+ name: /Let Stirling Cloud keep indexed documents/i,+ });+ await expect(upload).not.toBeChecked();+ // Click the visible label wrapper, not the hidden input - the house pattern for Mantine+ // switches, because force-clicking the input does not register in Firefox.+ await page+ .locator(+ 'label:has(input[aria-label="Let Stirling Cloud keep indexed documents"])',+ )+ .click();+ await expect(upload).toBeChecked();+});++test("a server already in cloud mode opens on it", async ({ page }) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ {+ ...ENABLED_SETTINGS,+ mode: "CLOUD",+ cloudDocumentIndexing: true,+ },+ true,+ );++ await expect(+ page.getByRole("radio", { name: /Stirling Cloud AI/i }),+ ).toBeChecked();+ await expect(+ page.getByRole("switch", {+ name: /Let Stirling Cloud keep indexed documents/i,+ }),+ ).toBeChecked();+});++test.describe("as the organization owner", () => {+ test.use({ stubOptions: { enableLogin: true, isAdmin: true, user: OWNER } });++ test("an unlinked server is pointed at where to link one", async ({+ page,+ }) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ false,+ );++ const link = page.getByRole("link", {+ name: /Connect this server to a Stirling account/i,+ });+ await expect(link).toBeVisible();+ await expect(link).toHaveAttribute("href", "/settings/account-link");+ });+});++test.describe("as an admin who is not the owner", () => {+ test.use({+ stubOptions: {+ enableLogin: true,+ isAdmin: true,+ user: { ...OWNER, id: 2, username: "admin", orgOwner: false },+ },+ });++ test("an unlinked server says only the owner can link it", async ({+ page,+ }) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ false,+ );++ await expect(+ page.getByText(/Only the organization owner can link this server/i),+ ).toBeVisible();+ // The account-link page is not listed for them, so a link there would lead nowhere.+ await expect(+ page.getByRole("link", {+ name: /Connect this server to a Stirling account/i,+ }),+ ).toHaveCount(0);+ });++ test("a linked server offers cloud AI to them too", async ({ page }) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ true,+ );++ await expect(+ page.getByRole("radio", { name: /Stirling Cloud AI/i }),+ ).toBeEnabled();+ await expect(page.getByText(/Link an account first/i)).toHaveCount(0);+ });+});++test("cloud mode reports on Stirling Cloud, not on a local engine", async ({+ page,+}) => {+ await openAiSettings(+ page,+ {+ enabled: true,+ reachable: true,+ authenticated: true,+ smartModel: "managed-smart",+ },+ { ...ENABLED_SETTINGS, mode: "CLOUD" },+ true,+ );++ const statusCard = page.locator(".settings-card").first();+ await expect(+ statusCard.getByText("Running on Stirling Cloud", { exact: true }),+ ).toBeVisible();+ await expect(+ statusCard.getByText("Running on", { exact: true }),+ ).toBeVisible();+ await expect(+ statusCard.getByText("Account link", { exact: true }),+ ).toBeVisible();+ // The engine URL belongs to a server that is no longer doing the work.+ await expect(statusCard.getByText("Engine URL", { exact: true })).toHaveCount(+ 0,+ );+ await expect(+ statusCard.getByText("Shared secret", { exact: true }),+ ).toHaveCount(0);+});++test("cloud mode reports Stirling Cloud itself as its own status point", async ({+ page,+}) => {+ await openAiSettings(+ page,+ {+ enabled: true,+ reachable: true,+ authenticated: true,+ cloudUp: true,+ cloudSharingEnabled: true,+ },+ { ...ENABLED_SETTINGS, mode: "CLOUD" },+ true,+ );++ const statusCard = page.locator(".settings-card").first();+ await expect(+ statusCard.getByText("Stirling.com", { exact: true }),+ ).toBeVisible();+ await expect(statusCard.getByText("Up", { exact: true })).toBeVisible();+ await expect(+ statusCard.getByText("AI sharing", { exact: true }),+ ).toBeVisible();+ await expect(statusCard.getByText("Enabled", { exact: true })).toBeVisible();+});++test("sharing switched off reads as switched off, not as an outage", async ({+ page,+}) => {+ await openAiSettings(+ page,+ {+ enabled: true,+ reachable: false,+ cloudUp: true,+ cloudSharingEnabled: false,+ error: "Stirling Cloud AI sharing is switched off for linked servers.",+ },+ { ...ENABLED_SETTINGS, mode: "CLOUD" },+ true,+ );++ const statusCard = page.locator(".settings-card").first();+ // The host being up is the whole point: it separates "switched off" from "down".+ await expect(statusCard.getByText("Up", { exact: true })).toBeVisible();+ await expect(statusCard.getByText("Disabled", { exact: true })).toBeVisible();+ await expect(+ statusCard.getByText(+ "Stirling Cloud AI sharing is switched off for linked servers.",+ ),+ ).toBeVisible();+});++test("a Stirling Cloud outage shows the host down", async ({ page }) => {+ await openAiSettings(+ page,+ {+ enabled: true,+ reachable: false,+ cloudUp: false,+ error: "Stirling Cloud is not responding.",+ },+ { ...ENABLED_SETTINGS, mode: "CLOUD" },+ true,+ );++ const statusCard = page.locator(".settings-card").first();+ await expect(statusCard.getByText("Down", { exact: true })).toBeVisible();+ // Sharing is unknown while the host is unreachable, and must not read as "off".+ await expect(statusCard.getByText("Disabled", { exact: true })).toHaveCount(+ 0,+ );+});++test("self-hosted mode shows no Stirling Cloud status points", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ );++ const statusCard = page.locator(".settings-card").first();+ await expect(statusCard.getByText("AI sharing", { exact: true })).toHaveCount(+ 0,+ );+ await expect(+ statusCard.getByText("Stirling.com", { exact: true }),+ ).toHaveCount(0);+});++test("cloud mode makes the settings Stirling Cloud owns read-only", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ { ...ENABLED_SETTINGS, mode: "CLOUD" },+ true,+ );++ await expect(+ page.getByText("Managed by Stirling Cloud", { exact: true }).first(),+ ).toBeVisible();+ // Provider and embedding model are the cloud's to choose in this mode.+ await expect(smartModelInput(page)).toBeDisabled();+ await expect(+ cardNamed(page, "Documents & RAG").getByRole("textbox", {+ name: /^Embedding model/,+ }),+ ).toBeDisabled();+ // Capabilities and limits stay the admin's.+ await expect(+ // Mantine's NumberInput is a text input with inputmode=decimal, so its role is textbox.+ cardNamed(page, "Limits & Performance").getByRole("textbox", {+ name: /^Max pages per request/,+ }),+ ).toBeEnabled();+});++test("switching cloud AI off hands the model settings back", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ { ...ENABLED_SETTINGS, mode: "CLOUD" },+ true,+ );+ await expect(smartModelInput(page)).toBeDisabled();++ // Off keeps mode CLOUD so turning AI back on restores it; nothing is cloud-managed meanwhile.+ await page.getByRole("radio", { name: /^Off$/i }).click();+ await expect(smartModelInput(page)).toBeEnabled();+ await expect(+ page.getByText("Managed by Stirling Cloud", { exact: true }),+ ).toHaveCount(0);+});++test("self-hosted mode leaves the model settings editable", async ({+ page,+}) => {+ await openAiSettings(+ page,+ { enabled: true, reachable: true, authenticated: true },+ ENABLED_SETTINGS,+ true,+ );++ await expect(smartModelInput(page)).toBeEnabled();+ await expect(+ page.getByText("Managed by Stirling Cloud", { exact: true }),+ ).toHaveCount(0);+});diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiSection.tsxindex 2027559ae5..e0febdde22 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminAiSection.tsx@@ -2,6 +2,7 @@ import { useCallback, useState } from "react";import { useTranslation } from "react-i18next";import { SettingsCard } from "@app/components/shared/config/SettingsCard";import { Stack, Loader } from "@mantine/core";+import { StatusBadge } from "@app/ui/StatusBadge";import { alert } from "@app/components/toast";import RestartConfirmationModal from "@app/components/shared/config/RestartConfirmationModal";import { useRestartServer } from "@app/components/shared/config/useRestartServer";@@ -17,6 +18,8 @@ import {savedToastBody,} from "@app/components/shared/config/configSections/aiEngineSettings";import { AiConnectionCard } from "@app/components/shared/config/configSections/ai/AiConnectionCard";+import { AiStatusCard } from "@app/components/shared/config/configSections/ai/AiStatusCard";+import { AiAboutNotice } from "@app/components/shared/config/configSections/ai/AiAboutNotice";import { AiCapabilitiesCard } from "@app/components/shared/config/configSections/ai/AiCapabilitiesCard";import { AiModelsCard } from "@app/components/shared/config/configSections/ai/AiModelsCard";import { AiDocumentsCard } from "@app/components/shared/config/configSections/ai/AiDocumentsCard";@@ -26,6 +29,7 @@ import "@app/components/shared/config/configSections/ai/AdminAiSection.css";/** Keys the backend applies only on restart; everything else is pushed live. */const RESTART_KEYS = ["enabled",+ "mode","url","timeoutSeconds","longRunningTimeoutSeconds",@@ -83,6 +87,8 @@ export default function AdminAiSection() {const deltaSettings: Record<string, unknown> = {"aiEngine.enabled": s.enabled ?? false,+ "aiEngine.mode": s.mode ?? "SELF_HOSTED",+ "aiEngine.cloudDocumentIndexing": s.cloudDocumentIndexing ?? false,"aiEngine.url": s.url ?? "",// Timeouts must be >= 1s; a 0 would make every engine call fail/deadlock."aiEngine.timeoutSeconds": clampMin(s.timeoutSeconds, 1),@@ -208,19 +214,45 @@ export default function AdminAiSection() {}const card = { settings, setSettings, isFieldPending, loginEnabled };+ // Stirling Cloud picks the models and holds the provider keys, so these sections describe an+ // engine this server no longer talks to. Shown but inert, rather than hidden, so an admin can+ // still see what their own engine is set to before switching back.+ const cloudManaged = settings.enabled === true && settings.mode === "CLOUD";+ const managedNote = t(+ "admin.settings.ai.managedByCloud",+ "Managed by Stirling Cloud in this mode.",+ );+ // The badge slot sits in the card heading, so it takes a chip rather than a sentence.+ const managedBadge = cloudManaged ? (+ <StatusBadge tone="neutral" size="sm" showDot={false}>+ {t("admin.settings.ai.managedByCloudShort", "Managed by Stirling Cloud")}+ </StatusBadge>+ ) : undefined;return (<div className="settings-section-container"><Stack gap="lg" className="settings-section-content">+ <SettingsCard+ id="adminAiStatus"+ title={t("admin.settings.ai.status.title", "Status")}+ description={t(+ "admin.settings.ai.status.description",+ "Whether the engine is reachable, whether it accepts this server, and what it is running.",+ )}+ >+ <AiStatusCard settings={settings} />+ </SettingsCard>+<SettingsCardid="adminAiGeneral"title={t("admin.settings.ai.general.connection", "Connection")}description={t("admin.settings.ai.general.description",- "Connect Stirling to the Python AI engine and choose which AI capabilities are exposed. Changes apply on restart.",+ "Choose where AI runs. Changes here apply on restart.",)}><AiConnectionCard {...card} />+ <AiAboutNotice cloud={cloudManaged} /></SettingsCard><SettingsCard@@ -240,32 +272,52 @@ export default function AdminAiSection() {<SettingsCardid="adminAiModels"title={t("settings.ai.models", "Models & Providers")}- description={t(- "admin.settings.ai.models.description",- "Choose the LLM provider and the smart/fast models the AI engine uses. Applied to the AI engine when saved.",- )}+ description={+ cloudManaged+ ? managedNote+ : t(+ "admin.settings.ai.models.description",+ "Choose the LLM provider and the smart/fast models the AI engine uses. Applied to the AI engine when saved.",+ )+ }+ badge={managedBadge}>- <AiModelsCard- {...card}- apiKeyDirty={apiKeyDirty}- setApiKeyDirty={setApiKeyDirty}- />+ <fieldset+ disabled={cloudManaged}+ style={{ border: 0, margin: 0, padding: 0, minWidth: 0 }}+ >+ <AiModelsCard+ {...card}+ apiKeyDirty={apiKeyDirty}+ setApiKeyDirty={setApiKeyDirty}+ />+ </fieldset></SettingsCard><SettingsCardid="adminAiDocuments"title={t("settings.ai.documents", "Documents & RAG")}- description={t(- "admin.settings.ai.documents.description",- "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved.",- )}+ description={+ cloudManaged+ ? managedNote+ : t(+ "admin.settings.ai.documents.description",+ "Configure the embedding model and retrieval settings used to answer questions over documents. Applied to the AI engine when saved.",+ )+ }+ badge={managedBadge}>- <AiDocumentsCard- {...card}- embeddingModelChanged={embeddingModelChanged}- embeddingApiKeyDirty={embeddingApiKeyDirty}- setEmbeddingApiKeyDirty={setEmbeddingApiKeyDirty}- />+ <fieldset+ disabled={cloudManaged}+ style={{ border: 0, margin: 0, padding: 0, minWidth: 0 }}+ >+ <AiDocumentsCard+ {...card}+ embeddingModelChanged={embeddingModelChanged}+ embeddingApiKeyDirty={embeddingApiKeyDirty}+ setEmbeddingApiKeyDirty={setEmbeddingApiKeyDirty}+ />+ </fieldset></SettingsCard><SettingsCarddiff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiAboutNotice.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiAboutNotice.tsxnew file mode 100644index 0000000000..a4ca668072--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiAboutNotice.tsx@@ -0,0 +1,80 @@+import { useTranslation } from "react-i18next";+import { Alert, Group, Text, Code } from "@mantine/core";+import { Button } from "@app/ui/Button";+import { Icon } from "@app/ui/Icon";+import { handleExternalLinkClick } from "@app/platform/externalLinkClick";++/** Null until the docs page is written; setting it brings back the set-up guide button. */+export const AI_ENGINE_DOCS_URL: string | null = null;++/**+ * What the AI engine is, in the one place an admin is guaranteed to look.+ *+ * Replaces a note that led with the shared-secret environment variable - true, but meaningless to+ * anyone who did not already know there was a second container to run.+ */+export function AiAboutNotice({ cloud = false }: { cloud?: boolean }) {+ const { t } = useTranslation();++ if (cloud) {+ return (+ <Alert+ variant="light"+ color="blue"+ title={t(+ "admin.settings.ai.general.cloudNote.title",+ "About Stirling Cloud AI",+ )}+ icon={<Icon name="info" size="1rem" />}+ >+ <Text size="xs">+ {t(+ "admin.settings.ai.general.cloudNote.body",+ "The reasoning runs on Stirling's infrastructure, billed to the account this server is linked to. There is no container to run and no provider key to hold here. Whatever the AI reads is processed by Stirling Cloud rather than on your own hardware.",+ )}+ </Text>+ </Alert>+ );+ }++ return (+ <Alert+ variant="light"+ color="blue"+ title={t("admin.settings.ai.general.note.title", "About the AI engine")}+ icon={<Icon name="info" size="1rem" />}+ >+ <Group gap="md" align="center" wrap="nowrap">+ <Text size="xs" style={{ flexGrow: 1 }}>+ {t(+ "admin.settings.ai.general.note.intro",+ "A separate container you run next to Stirling. It does the reasoning; Stirling still does every page operation itself. It needs the same",+ )}{" "}+ <Code>STIRLING_ENGINE_SHARED_SECRET</Code>{" "}+ {t(+ "admin.settings.ai.general.note.outro",+ "on both containers and a model provider key. Whatever the AI reads is sent to the provider you pick - an Ollama you host keeps every page in-house.",+ )}+ </Text>+ {AI_ENGINE_DOCS_URL && (+ <Button+ as="a"+ size="sm"+ variant="primary"+ href={AI_ENGINE_DOCS_URL}+ target="_blank"+ rel="noopener noreferrer"+ // Desktop opens links in the system browser; on web this is a no-op.+ onClick={(event) =>+ handleExternalLinkClick(AI_ENGINE_DOCS_URL, event)+ }+ rightSection={<Icon name="external-link" size="0.8rem" />}+ style={{ flexShrink: 0 }}+ >+ {t("admin.settings.ai.general.note.docs", "Set-up guide")}+ </Button>+ )}+ </Group>+ </Alert>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiConnectionCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiConnectionCard.tsxindex dac4ebbc43..895a3d9d7c 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiConnectionCard.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiConnectionCard.tsx@@ -1,25 +1,118 @@-import { useState } from "react";-import { Icon } from "@app/ui/Icon";+import { useState, type ReactNode } from "react";+import { Icon, type IconName } from "@app/ui/Icon";import { InfoTooltip } from "@app/ui/InfoTooltip";import { useTranslation } from "react-i18next";import {TextInput,NumberInput,- Switch,+ Radio,Stack,Paper,Text,Group,- Alert,- Code,} from "@mantine/core";import { alert } from "@app/components/toast";import PendingBadge from "@app/components/shared/config/PendingBadge";import apiClient from "@app/services/apiClient";import { Button } from "@app/ui/Button";+import { StatusBadge } from "@app/ui/StatusBadge";+import { Switch, Anchor } from "@mantine/core";+import { useAuth } from "@app/auth/context";+import { HAS_PORTAL } from "@app/routes/hasPortal";+import { useAccountLinked } from "@app/components/shared/config/configSections/ai/useAiEngineStatus";import type { AiCardProps } from "@app/components/shared/config/configSections/ai/aiCardProps";+import "@app/components/shared/config/configSections/ai/AiModeOption.css";-/** Whether the engine is on and how to reach it. Restart-required, all of it. */+/** The three places AI could run. Only two of them exist. */+type AiMode = "off" | "self" | "cloud";++interface ModeOptionProps {+ mode: AiMode;+ selected: AiMode;+ title: string;+ description: string;+ onSelect: (mode: AiMode) => void;+ disabled?: boolean;+ badge?: ReactNode;+ icon?: IconName;+ /** Shown under the description even when the option cannot be selected. */+ footer?: ReactNode;+ children?: ReactNode;+}++/**+ * One row of the mode chooser. A real radio, so the group is arrow-navigable and screen readers+ * announce it as a choice rather than three unrelated switches.+ */+function ModeOption({+ mode,+ selected,+ title,+ description,+ onSelect,+ disabled = false,+ badge,+ icon,+ footer,+ children,+}: ModeOptionProps) {+ const active = selected === mode;+ return (+ <Paper+ withBorder+ p="md"+ radius="md"+ className={[+ "ai-mode-option",+ active ? "ai-mode-option--selected" : "",+ disabled ? "ai-mode-option--disabled" : "",+ ]+ .filter(Boolean)+ .join(" ")}+ // Clicking anywhere on the card picks the mode; the radio stays the real control, so+ // keyboard and screen readers are unaffected.+ onClick={disabled ? undefined : () => onSelect(mode)}+ >+ <Group gap="sm" align="flex-start" wrap="nowrap">+ <Radio+ value={mode}+ checked={active}+ disabled={disabled}+ onChange={() => onSelect(mode)}+ aria-label={title}+ mt={2}+ />+ <div style={{ flexGrow: 1, minWidth: 0 }}>+ <Group gap="xs" align="center" wrap="nowrap">+ {icon && <Icon name={icon} size="1rem" />}+ <Text fw={600} size="sm">+ {title}+ </Text>+ {badge}+ </Group>+ <Text size="sm" c="dimmed" mt={2}>+ {description}+ </Text>+ {footer ? <div style={{ marginTop: "0.5rem" }}>{footer}</div> : null}+ {active && children ? (+ <div className="ai-mode-option__body">{children}</div>+ ) : null}+ </div>+ </Group>+ </Paper>+ );+}++/**+ * Where AI runs, and - for a self-hosted engine - how to reach it.+ *+ * Was a bare "Enable AI" switch above four always-visible fields, which gave the URL and timeouts+ * equal billing with the decision that makes them relevant. As a mode choice the engine fields sit+ * under the option that owns them, and Stirling Cloud stays visible but disabled until the server+ * is linked.+ *+ * Every key here is restart-required.+ */export function AiConnectionCard({settings,setSettings,@@ -28,6 +121,32 @@ export function AiConnectionCard({const { t } = useTranslation();const [testingConnection, setTestingConnection] = useState(false);const enabled = settings.enabled || false;+ const linked = useAccountLinked();+ const { isAdmin, user, portalAccess } = useAuth();+ const isOwner = isAdmin && user?.orgOwner === true;+ // Mirrors useSettingsNav, which lists the account-link page only for the owner in portal builds.+ const canOpenAccountLink = HAS_PORTAL && portalAccess && isOwner;+ const mode: AiMode = !enabled+ ? "off"+ : settings.mode === "CLOUD"+ ? "cloud"+ : "self";++ const selectMode = (next: AiMode) => {+ if (next === "cloud" && !linked) return;+ setSettings({+ ...settings,+ enabled: next !== "off",+ // Leave the stored mode alone when switching off, so turning AI back on returns the admin+ // to the engine they had rather than silently moving their traffic.+ mode:+ next === "off"+ ? settings.mode+ : next === "cloud"+ ? "CLOUD"+ : "SELF_HOSTED",+ });+ };const handleTestConnection = async () => {setTestingConnection(true);@@ -66,174 +185,267 @@ export function AiConnectionCard({};return (- <>- <Paper withBorder p="md" radius="md">- <Stack gap="md">- <Group justify="space-between" align="flex-start" wrap="nowrap">- <div>- <Text fw={500} size="sm">- {t("admin.settings.ai.general.enabled.label", "Enable AI")}{" "}- <InfoTooltip- label={t(- "admin.settings.ai.general.enabled.description",- "Master switch. When off, no AI tools, agents, or engine calls are available.",- )}- />- </Text>- </div>- <Group gap="xs">- <Switch- checked={enabled}- onChange={(e) =>- setSettings({ ...settings, enabled: e.target.checked })- }- aria-label={t(- "admin.settings.ai.general.enabled.label",- "Enable AI",- )}- />- <PendingBadge show={isFieldPending("enabled")} />- </Group>- </Group>+ <Radio.Group+ value={mode}+ onChange={(value) => selectMode(value as AiMode)}+ aria-label={t("admin.settings.ai.general.mode.label", "Where AI runs")}+ >+ <Stack gap="sm">+ <ModeOption+ mode="off"+ selected={mode}+ onSelect={selectMode}+ title={t("admin.settings.ai.general.mode.off.title", "Off")}+ description={t(+ "admin.settings.ai.general.mode.off.description",+ "No AI tools anywhere in the app, and nothing leaves this server.",+ )}+ />- <TextInput- label={- <Group gap="xs">- <span>- {t("admin.settings.ai.general.url.label", "AI engine URL")}- </span>- <PendingBadge show={isFieldPending("url")} />- <InfoTooltip- label={t(- "admin.settings.ai.general.url.description",- "Internal URL of the Python AI engine, e.g. http://stirling-pdf-engine:5001.",- )}- />- </Group>- }- value={settings.url || ""}- onChange={(e) => setSettings({ ...settings, url: e.target.value })}- placeholder="http://stirling-pdf-engine:5001"- disabled={!enabled}- />+ <ModeOption+ mode="self"+ selected={mode}+ onSelect={selectMode}+ title={t(+ "admin.settings.ai.general.mode.self.title",+ "Run your own engine",+ )}+ description={t(+ "admin.settings.ai.general.mode.self.description",+ "A container you host, pointed at a model provider of your choosing. Your key, your bill, your data path.",+ )}+ badge={<PendingBadge show={isFieldPending("enabled")} />}+ >+ <Stack gap="sm">+ <TextInput+ label={+ <Group gap="xs">+ <span>+ {t("admin.settings.ai.general.url.label", "AI engine URL")}+ </span>+ <PendingBadge show={isFieldPending("url")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.url.description",+ "Internal URL of the Python AI engine, e.g. http://stirling-pdf-engine:5001.",+ )}+ />+ </Group>+ }+ value={settings.url || ""}+ onChange={(e) =>+ setSettings({ ...settings, url: e.target.value })+ }+ placeholder="http://stirling-pdf-engine:5001"+ />- <Group justify="flex-end">- <Button- variant="secondary"- size="sm"- loading={testingConnection}- onClick={handleTestConnection}+ <Group+ gap="sm"+ grow+ align="flex-start"+ style={{ alignItems: "flex-start" }}>- {t("admin.settings.ai.general.test.button", "Test connection")}- </Button>- </Group>+ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.general.timeoutSeconds.label",+ "Request timeout (seconds)",+ )}+ </span>+ <PendingBadge show={isFieldPending("timeoutSeconds")} />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.timeoutSeconds.description",+ "Timeout for standard AI requests to the engine.",+ )}+ />+ </Group>+ }+ value={settings.timeoutSeconds ?? 0}+ onChange={(value) =>+ setSettings({ ...settings, timeoutSeconds: Number(value) })+ }+ min={1}+ />- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.general.timeoutSeconds.label",- "Request timeout (seconds)",- )}- </span>- <PendingBadge show={isFieldPending("timeoutSeconds")} />- <InfoTooltip- label={t(- "admin.settings.ai.general.timeoutSeconds.description",- "Timeout for standard AI requests to the engine.",- )}- />- </Group>- }- value={settings.timeoutSeconds ?? 0}- onChange={(value) =>- setSettings({ ...settings, timeoutSeconds: Number(value) })- }- min={1}- disabled={!enabled}- />+ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.general.longRunningTimeoutSeconds.label",+ "Long-running timeout (seconds)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("longRunningTimeoutSeconds")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.longRunningTimeoutSeconds.description",+ "Timeout for heavier agent operations such as document generation.",+ )}+ />+ </Group>+ }+ value={settings.longRunningTimeoutSeconds ?? 0}+ onChange={(value) =>+ setSettings({+ ...settings,+ longRunningTimeoutSeconds: Number(value),+ })+ }+ min={1}+ />- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.general.longRunningTimeoutSeconds.label",- "Long-running timeout (seconds)",- )}- </span>- <PendingBadge- show={isFieldPending("longRunningTimeoutSeconds")}- />- <InfoTooltip- label={t(- "admin.settings.ai.general.longRunningTimeoutSeconds.description",- "Timeout for heavier agent operations such as document generation.",- )}- />- </Group>- }- value={settings.longRunningTimeoutSeconds ?? 0}- onChange={(value) =>- setSettings({- ...settings,- longRunningTimeoutSeconds: Number(value),- })- }- min={1}- disabled={!enabled}- />+ <NumberInput+ label={+ <Group gap="xs">+ <span>+ {t(+ "admin.settings.ai.general.streamTimeoutSeconds.label",+ "Stream timeout (seconds)",+ )}+ </span>+ <PendingBadge+ show={isFieldPending("streamTimeoutSeconds")}+ />+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.streamTimeoutSeconds.description",+ "Timeout for streamed (token-by-token) chat responses.",+ )}+ />+ </Group>+ }+ value={settings.streamTimeoutSeconds ?? 0}+ onChange={(value) =>+ setSettings({+ ...settings,+ streamTimeoutSeconds: Number(value),+ })+ }+ min={1}+ />+ </Group>- <NumberInput- label={- <Group gap="xs">- <span>- {t(- "admin.settings.ai.general.streamTimeoutSeconds.label",- "Stream timeout (seconds)",- )}- </span>- <PendingBadge show={isFieldPending("streamTimeoutSeconds")} />- <InfoTooltip- label={t(- "admin.settings.ai.general.streamTimeoutSeconds.description",- "Timeout for streamed (token-by-token) chat responses.",- )}- />- </Group>- }- value={settings.streamTimeoutSeconds ?? 0}- onChange={(value) =>- setSettings({- ...settings,- streamTimeoutSeconds: Number(value),- })- }- min={1}- disabled={!enabled}- />- </Stack>- </Paper>+ <Group justify="space-between" align="center">+ <Text size="xs" c="dimmed">+ {t(+ "admin.settings.ai.general.restartNote",+ "Changing the URL or any timeout takes effect after a restart.",+ )}+ </Text>+ <Button+ variant="secondary"+ size="sm"+ loading={testingConnection}+ onClick={handleTestConnection}+ >+ {t("admin.settings.ai.general.test.button", "Test connection")}+ </Button>+ </Group>+ </Stack>+ </ModeOption>- <Alert- variant="light"- color="blue"- title={t("admin.settings.ai.general.note.title", "About the AI engine")}- icon={<Icon name="info" size="1rem" />}- >- <Text size="xs">- {t(- "admin.settings.ai.general.note.body",- "The AI engine runs as a separate service. Its shared secret",- )}{" "}- <Code>STIRLING_ENGINE_SHARED_SECRET</Code>{" "}- {t(- "admin.settings.ai.general.note.body2",- "is set via a container environment variable. Provider API keys can be entered on these pages or supplied as engine environment variables; keys entered here are pushed to the engine when saved.",+ <ModeOption+ mode="cloud"+ selected={mode}+ onSelect={selectMode}+ disabled={linked !== true}+ icon="cloud"+ title={t(+ "admin.settings.ai.general.mode.cloud.title",+ "Use Stirling Cloud AI",)}- </Text>- </Alert>- </>+ description={t(+ "admin.settings.ai.general.mode.cloud.description",+ "No container, no provider key, no model choice - the work runs on Stirling Cloud and is billed to the account this server is linked to.",+ )}+ badge={+ linked === false ? (+ <StatusBadge tone="neutral" size="sm" showDot={false}>+ {t(+ "admin.settings.ai.general.mode.cloud.notLinked",+ "Link an account first",+ )}+ </StatusBadge>+ ) : null+ }+ footer={+ linked !== false ? null : canOpenAccountLink ? (+ <Anchor+ href="/settings/account-link"+ size="sm"+ c="var(--c-accent-text)"+ // Stop the card's own click handler swallowing the link.+ onClick={(event) => event.stopPropagation()}+ >+ {t(+ "admin.settings.ai.general.mode.cloud.linkCta",+ "Connect this server to a Stirling account",+ )}{" "}+ ›+ </Anchor>+ ) : !isOwner ? (+ <Text size="sm" c="dimmed">+ {t(+ "admin.settings.ai.general.mode.cloud.ownerOnly",+ "Only the organization owner can link this server to a Stirling account.",+ )}+ </Text>+ ) : null+ }+ >+ <Stack gap="sm">+ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <div style={{ flexGrow: 1, minWidth: 0 }}>+ <Group gap={4} wrap="nowrap">+ <Text fw={500} size="sm">+ {t(+ "admin.settings.ai.general.cloud.indexing.label",+ "Let Stirling Cloud keep indexed documents",+ )}+ </Text>+ <InfoTooltip+ label={t(+ "admin.settings.ai.general.cloud.indexing.description",+ "Every AI tool sends the page text it needs to answer. This decides whether Stirling Cloud may also keep that text, indexed, so later questions can search across the document.",+ )}+ />+ </Group>+ <Text size="sm" c="dimmed" mt={2}>+ {t(+ "admin.settings.ai.general.cloud.indexing.help",+ "Off means document questions are unavailable. It does not stop text being sent - only stored.",+ )}+ </Text>+ </div>+ <Switch+ checked={settings.cloudDocumentIndexing ?? false}+ onChange={(e) =>+ setSettings({+ ...settings,+ cloudDocumentIndexing: e.target.checked,+ })+ }+ aria-label={t(+ "admin.settings.ai.general.cloud.indexing.label",+ "Let Stirling Cloud keep indexed documents",+ )}+ />+ </Group>+ <Text size="xs" c="dimmed">+ {t(+ "admin.settings.ai.general.cloud.note",+ "Models and provider keys are managed by Stirling Cloud, so those settings do not apply in this mode.",+ )}+ </Text>+ </Stack>+ </ModeOption>+ </Stack>+ </Radio.Group>);}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiModeOption.css b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiModeOption.cssnew file mode 100644index 0000000000..db2a530819--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiModeOption.css@@ -0,0 +1,41 @@+/* The mode chooser reads as three cards, so the whole card has to behave like the control it is:+ hoverable, focusable, and obviously the selected one. A bare border colour change was not enough+ to tell at a glance which mode a server was in. */++.ai-mode-option {+ cursor: pointer;+ transition:+ border-color 0.12s ease,+ background-color 0.12s ease,+ box-shadow 0.12s ease;+}++.ai-mode-option:hover:not(.ai-mode-option--disabled) {+ border-color: var(--c-border-strong);+ background: var(--c-surface-raised);+}++.ai-mode-option--selected,+.ai-mode-option--selected:hover {+ border-color: var(--c-accent-text);+ background: var(--c-surface-raised);+ box-shadow: 0 0 0 1px var(--c-accent-text);+}++/* The radio is the focus target; lift the ring onto the card so keyboard position is visible. */+.ai-mode-option:focus-within {+ box-shadow: 0 0 0 2px+ color-mix(in srgb, var(--c-accent-text) 45%, transparent);+}++.ai-mode-option--disabled {+ cursor: default;+ background: var(--c-surface);+}++/* Fields belonging to the selected mode, set apart from the choice itself. */+.ai-mode-option__body {+ margin-top: 0.75rem;+ padding-top: 0.75rem;+ border-top: 1px solid var(--c-border);+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiStatusCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiStatusCard.tsxnew file mode 100644index 0000000000..8f3087fe71--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/AiStatusCard.tsx@@ -0,0 +1,299 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Paper, Stack, Group, Text, Loader } from "@mantine/core";+import { StatusBadge, type StatusTone } from "@app/ui/StatusBadge";+import { Button } from "@app/ui/Button";+import { Icon } from "@app/ui/Icon";+import type { AiEngineSettingsData } from "@app/components/shared/config/configSections/aiEngineSettings";+import {+ formatAge,+ healthOf,+ useAiEngineStatus,+ type AiEngineHealth,+} from "@app/components/shared/config/configSections/ai/useAiEngineStatus";++interface AiStatusCardProps {+ settings: AiEngineSettingsData;+}++const TONE: Record<AiEngineHealth, StatusTone> = {+ loading: "neutral",+ off: "neutral",+ down: "danger",+ degraded: "warning",+ ok: "success",+};++/** One labelled value in the strip under the headline. */+function Fact({+ label,+ value,+ title,+}: {+ label: string;+ value: React.ReactNode;+ title?: string;+}) {+ return (+ <div style={{ minWidth: 0 }}>+ <Text+ size="xs"+ fw={600}+ tt="uppercase"+ c="dimmed"+ style={{ letterSpacing: "0.04em" }}+ >+ {label}+ </Text>+ <Text size="sm" truncate title={title}>+ {value}+ </Text>+ </div>+ );+}++/**+ * Whether the engine is actually working, at the top of the page.+ *+ * Deliberately does not key off the engine's own /health alone: that route is exempt from the+ * shared-secret check and never contacts the model provider, so it stays green while every real+ * request is refused. The backend probes a secret-gated route too, and a rejection paints amber+ * rather than green - the whole point of the card.+ */+export function AiStatusCard({ settings }: AiStatusCardProps) {+ const { t } = useTranslation();+ const enabled = settings.enabled ?? false;+ const cloud = settings.mode === "CLOUD";+ const { status, loading, checkedAt, refresh } = useAiEngineStatus(enabled);+ const [now, setNow] = useState(() => Date.now());++ // Re-render on a slow tick so "14s ago" does not silently go stale while the page is open.+ useEffect(() => {+ const timer = window.setInterval(() => setNow(Date.now()), 10_000);+ return () => window.clearInterval(timer);+ }, []);++ const health = healthOf(status, loading);+ const age = formatAge(checkedAt, now, t);++ const HEADLINE: Record<AiEngineHealth, string> = {+ loading: t("admin.settings.ai.status.checking", "Checking the engine…"),+ off: t("admin.settings.ai.status.off.title", "AI is switched off"),+ down: cloud+ ? t(+ "admin.settings.ai.status.cloud.down.title",+ "Stirling Cloud unreachable",+ )+ : t("admin.settings.ai.status.down.title", "Engine unreachable"),+ degraded: cloud+ ? t(+ "admin.settings.ai.status.cloud.degraded.title",+ "Stirling Cloud is refusing this server",+ )+ : t(+ "admin.settings.ai.status.degraded.title",+ "Engine is up, but refusing this server",+ ),+ ok: cloud+ ? t(+ "admin.settings.ai.status.cloud.ok.title",+ "Running on Stirling Cloud",+ )+ : t("admin.settings.ai.status.ok.title", "Engine running"),+ };++ const DETAIL: Record<AiEngineHealth, string> = {+ loading: "",+ off: t(+ "admin.settings.ai.status.off.body",+ "Choose how AI runs below, then save and restart.",+ ),+ down: cloud+ ? t(+ "admin.settings.ai.status.cloud.down.body",+ "This server could not reach Stirling Cloud. Check the account link and that this server can reach the internet.",+ )+ : t(+ "admin.settings.ai.status.down.body",+ "Check the URL, that the engine container is running, and that you restarted after enabling AI.",+ ),+ degraded: cloud+ ? t(+ "admin.settings.ai.status.cloud.degraded.body",+ "Stirling Cloud answered but refused this server. The account link may have been revoked.",+ )+ : t(+ "admin.settings.ai.status.degraded.body",+ "It answered the health check but rejected a real request. The two sides are using different shared secrets.",+ ),+ ok: cloud+ ? t(+ "admin.settings.ai.status.cloud.ok.body",+ "Stirling Cloud accepted this server. Nothing to run or patch here.",+ )+ : t(+ "admin.settings.ai.status.ok.body",+ "Health check and an authenticated request both succeeded.",+ ),+ };++ const featuresOn = Object.values(settings.features ?? {}).filter(+ Boolean,+ ).length;+ const featuresTotal = 6;++ const authLabel =+ status?.authenticated === true+ ? t("admin.settings.ai.status.secret.yes", "Accepted")+ : status?.authenticated === false+ ? t("admin.settings.ai.status.secret.no", "Rejected")+ : t("admin.settings.ai.status.secret.unknown", "Unknown");++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <Group+ gap="md"+ wrap="nowrap"+ align="flex-start"+ justify="space-between"+ >+ {/* Headline above detail, not beside it: the degraded headline is long enough to+ wrap, and beside the button it squeezed both onto two ragged lines. */}+ <Stack gap={6} style={{ minWidth: 0 }}>+ {loading && !status ? (+ <Loader size="xs" />+ ) : (+ <StatusBadge tone={TONE[health]} size="sm">+ {HEADLINE[health]}+ </StatusBadge>+ )}+ {DETAIL[health] && (+ <Text size="sm" c="dimmed">+ {DETAIL[health]}+ </Text>+ )}+ </Stack>+ <Group gap="sm" wrap="nowrap" style={{ flexShrink: 0 }}>+ {age && (+ <Text size="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>+ {t("admin.settings.ai.status.checked", "checked")} {age}+ </Text>+ )}+ <Button+ variant="secondary"+ size="sm"+ loading={loading}+ onClick={() => void refresh()}+ disabled={!enabled}+ >+ {t("admin.settings.ai.status.recheck", "Check again")}+ </Button>+ </Group>+ </Group>++ {status?.error && health !== "ok" && (+ <Group gap="xs" wrap="nowrap" align="flex-start">+ <Icon+ name="circle-alert"+ size="1rem"+ style={{ flexShrink: 0, marginTop: "0.1rem" }}+ />+ <Text size="xs" c="dimmed">+ {status.error}+ </Text>+ </Group>+ )}++ {enabled && (+ <div+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(auto-fit, minmax(11rem, 1fr))",+ gap: "1rem",+ borderTop: "1px solid var(--c-border)",+ paddingTop: "0.75rem",+ }}+ >+ <Fact+ label={+ cloud+ ? t("admin.settings.ai.status.runningOn", "Running on")+ : t("admin.settings.ai.status.url", "Engine URL")+ }+ value={+ cloud+ ? t("admin.settings.ai.status.cloud.name", "Stirling Cloud")+ : settings.url || "—"+ }+ title={cloud ? undefined : settings.url || undefined}+ />+ <Fact+ label={+ cloud+ ? t("admin.settings.ai.status.linkLabel", "Account link")+ : t("admin.settings.ai.status.secretLabel", "Shared secret")+ }+ value={authLabel}+ />+ {cloud && (+ <Fact+ label={t(+ "admin.settings.ai.status.cloud.hostLabel",+ "Stirling.com",+ )}+ value={+ status?.cloudUp == null+ ? "—"+ : status.cloudUp+ ? t("admin.settings.ai.status.cloud.hostUp", "Up")+ : t("admin.settings.ai.status.cloud.hostDown", "Down")+ }+ />+ )}+ {cloud && (+ <Fact+ label={t(+ "admin.settings.ai.status.cloud.sharingLabel",+ "AI sharing",+ )}+ value={+ status?.cloudSharingEnabled == null+ ? "—"+ : status.cloudSharingEnabled+ ? t("admin.settings.ai.status.cloud.sharingOn", "Enabled")+ : t(+ "admin.settings.ai.status.cloud.sharingOff",+ "Disabled",+ )+ }+ />+ )}+ <Fact+ label={t("admin.settings.ai.status.smartModel", "Smart model")}+ value={status?.smartModel || "—"}+ />+ <Fact+ label={t("admin.settings.ai.status.fastModel", "Fast model")}+ value={status?.fastModel || "—"}+ />+ <Fact+ label={t("admin.settings.ai.status.capabilities", "Capabilities")}+ value={t(+ "admin.settings.ai.status.capabilitiesValue",+ "{{on}} of {{total}} on",+ { on: featuresOn, total: featuresTotal },+ )}+ />+ {status?.latencyMs != null && (+ <Fact+ label={t("admin.settings.ai.status.latency", "Response time")}+ value={`${status.latencyMs} ms`}+ />+ )}+ </div>+ )}+ </Stack>+ </Paper>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/ai/useAiEngineStatus.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/useAiEngineStatus.tsnew file mode 100644index 0000000000..0ee9712a91--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/ai/useAiEngineStatus.ts@@ -0,0 +1,125 @@+import { useCallback, useEffect, useRef, useState } from "react";+import apiClient from "@app/services/apiClient";++/** Shape of GET /api/v1/ai/status. */+export interface AiEngineStatusData {+ enabled: boolean;+ reachable: boolean;+ latencyMs?: number | null;+ /** Null when the probe could not answer, which is not the same as a refusal. */+ authenticated?: boolean | null;+ smartModel?: string | null;+ fastModel?: string | null;+ error?: string | null;+ /** Cloud mode only: did the Stirling Cloud host answer its public status endpoint. */+ cloudUp?: boolean | null;+ /** Cloud mode only: does that deployment lend its AI to linked servers. */+ cloudSharingEnabled?: boolean | null;+}++/** What the card paints. `degraded` is reachable-but-refusing, the case /health cannot see. */+export type AiEngineHealth = "loading" | "off" | "down" | "degraded" | "ok";++export function healthOf(+ status: AiEngineStatusData | null,+ loading: boolean,+): AiEngineHealth {+ if (loading && !status) return "loading";+ if (!status || !status.enabled) return "off";+ if (!status.reachable) return "down";+ // Only an explicit refusal is degraded; an unanswered probe must not paint a warning.+ if (status.authenticated === false) return "degraded";+ return "ok";+}++/**+ * Fetches the status once on open and again on demand, never on a timer; skipped while AI is off.+ * Tracks when it last answered so the card can say how stale it is.+ */+export function useAiEngineStatus(enabled: boolean) {+ const [status, setStatus] = useState<AiEngineStatusData | null>(null);+ const [loading, setLoading] = useState(false);+ const [checkedAt, setCheckedAt] = useState<number | null>(null);+ // Guards against a slow earlier request resolving after a newer one and winning.+ const requestId = useRef(0);++ const refresh = useCallback(async () => {+ if (!enabled) {+ setStatus(null);+ setCheckedAt(null);+ return;+ }+ const id = ++requestId.current;+ setLoading(true);+ try {+ const response =+ await apiClient.get<AiEngineStatusData>("/api/v1/ai/status");+ if (id !== requestId.current) return;+ setStatus(response.data);+ } catch (_error) {+ if (id !== requestId.current) return;+ // A failed probe is itself a status: the backend could not be asked.+ setStatus({ enabled: true, reachable: false });+ } finally {+ if (id === requestId.current) {+ setLoading(false);+ setCheckedAt(Date.now());+ }+ }+ }, [enabled]);++ useEffect(() => {+ void refresh();+ }, [refresh]);++ return { status, loading, checkedAt, refresh };+}++/** Coarse "14s ago" for the status line; exact enough for a value that refreshes on demand. */+export function formatAge(+ checkedAt: number | null,+ now: number,+ t: (key: string, fallback: string, opts?: Record<string, unknown>) => string,+): string | null {+ if (checkedAt == null) return null;+ const seconds = Math.max(0, Math.round((now - checkedAt) / 1000));+ if (seconds < 5) return t("admin.settings.ai.status.justNow", "just now");+ if (seconds < 60)+ return t("admin.settings.ai.status.secondsAgo", "{{count}}s ago", {+ count: seconds,+ });+ const minutes = Math.round(seconds / 60);+ return t("admin.settings.ai.status.minutesAgo", "{{count}}m ago", {+ count: minutes,+ });+}++/**+ * Whether this server is linked to a Stirling account, which is what makes cloud AI selectable.+ * Its own hook rather than part of the status call: link state is a property of the server, not of+ * the engine, and the AI page is not the only thing that would want it.+ */+export function useAccountLinked() {+ const [linked, setLinked] = useState<boolean | null>(null);++ useEffect(() => {+ let live = true;+ // /linked, not /status: status is owner-only, and any admin can open this page.+ apiClient+ .get<{ linked?: boolean }>("/api/v1/account-link/linked", {+ suppressErrorToast: true,+ })+ .then((response) => {+ if (live) setLinked(response.data?.linked ?? false);+ })+ // A build without account linking answers 404 here; that is "not linked", not an error.+ .catch(() => {+ if (live) setLinked(false);+ });+ return () => {+ live = false;+ };+ }, []);++ return linked;+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/aiEngineSettings.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/aiEngineSettings.tsindex 197f521d8b..9f8ae22ef3 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/aiEngineSettings.ts+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/aiEngineSettings.ts@@ -42,8 +42,17 @@ export interface AiEngineFeatures {classify?: boolean;}+/** Where the reasoning runs; mirrors ApplicationProperties.AiEngine.AiEngineMode. */+export type AiEngineMode = "SELF_HOSTED" | "CLOUD";+export interface AiEngineSettingsData {enabled?: boolean;+ mode?: AiEngineMode;+ /**+ * Cloud mode only. Whether Stirling Cloud may keep a document's text indexed for later+ * questions. Retention, not transmission: every AI tool sends page text either way.+ */+ cloudDocumentIndexing?: boolean;url?: string;/*** Whether the processor forwards settings to the engine; SaaS pins it false, so a save