@scalio-cloud/ui 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -573,6 +573,41 @@ list. Test IDs: `agents-panel`, `agents-code-create`, `agents-code-value`, `agen
573
573
  `agent-role-<id>-<role>`, `agent-worker-state-<id>-<worker>`, `agent-worker-restart|stop|start-<id>-<worker>`,
574
574
  `agent-block-<id>`, `agent-remove-<id>`, `agents-tasks`.
575
575
 
576
+ ## KI-Bausteine: Einstellungen → KI-Assistent, Knopf, Vorschlag, Assistent (React)
577
+
578
+ Since 0.57.0 (scalio-docs ADR 0111, `concepts/ki-alle-apps.md`) every app shows AI the same way. Server side:
579
+ scalio-platform 0.34.0 `ai` (`public_settings`, `merge_settings` with `features`, `feature_level`, `Usage.summary`).
580
+ KI is optional: the blocks hide when AI is off, and nothing the AI proposes runs without a click.
581
+
582
+ ```jsx
583
+ import { AiSettingsPanel, AiButton, AiSuggestion, AiBadge, AiPanel, aiApi } from "@scalio-cloud/ui/react";
584
+
585
+ const ai = aiApi(api); // GET /ai/usage, POST /ai/usage/reset (aiApi(api, {usage, reset}) for other paths)
586
+ <AiSettingsPanel value={settings.ai} status={aiStatus} client={ai} canReset={isAdmin} lang={lang} demo={demoMode}
587
+ features={[{ key: "drift.explain", label: "Drift erklären", max: 1 }]}
588
+ onSave={(patch) => api.put("/settings", { ai: patch })} notify={toast} />
589
+ <AiButton available={aiStatus.available && level >= 1} kind="explain" busy={busy} onClick={explain} />
590
+ <AiSuggestion suggestion={{ title, text, reason, risk, source }} onAccept={run} onEdit={edit} onReject={drop} />
591
+ <AiPanel open={open} context="Benutzer Anna Muster" onAsk={(q, history) => askBackend(q, history)} onClose={close} />
592
+ ```
593
+
594
+ `AiSettingsPanel` holds provider, key (never shown, empty keeps it), models «schnell»/«stark» (empty = default,
595
+ former defaults count as empty), base URL for OpenAI-compatible or local models, the daily limit per person, one level
596
+ per feature (`features`: `key`, `label`, `hint`, `max` = the app's highest level; Aus, Erklären, Entwurf, Aktion nach
597
+ Klick, Selbständig), the privacy note and the usage. `status.managed` (Scalio KI) hides provider and key;
598
+ `status.licensed === false` locks the form. `onSave` gets the body for `merge_settings`. `AiBadge` marks text the AI
599
+ wrote. `AiSuggestion` never runs anything: the app's `onAccept` runs its normal action with the person's rights and
600
+ an audit entry. Test IDs: `ai-settings`, `ai-enable-switch`, `ai-status-badge`, `ai-provider-select`, `ai-model-fast`,
601
+ `ai-model-strong`, `ai-key`, `ai-daily-limit`, `ai-feature-<key>-level`, `ai-save-button`, `ai-usage-*`, `ai-button`,
602
+ `ai-suggestion-accept|edit|reject`, `ai-panel-input`, `ai-panel-send`, `ai-panel-close`.
603
+
604
+ Since 0.58.0 (ADR 0111 K2/K7, scalio-platform 0.35.0): provider `scalio` = «Scalio KI» (no key, no models; calls go
605
+ through Scalio Compass and use the organisation's credits). `status.scalio === false` (instance not connected to
606
+ Compass) hides it in the list. With `client.credits()` (`GET /ai/credits` → `{used, limit, state, month}`) the panel
607
+ shows `AiCredits` (bar, warning from 80 %, note at 100 %). `AiHelp` is «Frag Scalio»: an `AiPanel` with the help title
608
+ whose `onAsk` returns `{text, sources: [{title, source, url}]}`; `AiPanel` shows such sources too. Test IDs
609
+ `ai-scalio`, `ai-credits`, `ai-credits-text`, `ai-credits-note`, `ai-help`, `ai-help-sources-<n>`.
610
+
576
611
  ## Benachrichtigungen: E-Mail-Versand und E-Mail-Vorlagen (React)
577
612
 
578
613
  Since 0.29.0 (ADR 0069 W5) every app sends mail the same way. The server side is scalio-platform 0.8.0 `mail`
package/nav.css CHANGED
@@ -885,3 +885,37 @@ ul.scalio-notice { flex-direction: column; gap: 0.25rem; padding-left: 2rem; lis
885
885
  /* Main action of a page (react/actions.js MainAction): in the sidebar as .scalio-nav-cta; on phones in place. */
886
886
  .scalio-nav-cta:disabled { opacity: 0.6; cursor: default; }
887
887
  .scalio-main-action-inline { display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem; margin-top: 0; text-decoration: none; }
888
+
889
+ /* KI-Bausteine (ADR 0111): button, badge, suggestion card, side panel «Assistent», feature levels. */
890
+ .scalio-switch { width: 2.25rem; height: 1.25rem; accent-color: hsl(var(--primary)); cursor: pointer; }
891
+ .scalio-ai-btn .scalio-icon { color: hsl(var(--primary)); }
892
+ .scalio-ai-badge { display: inline-flex; align-items: center; gap: 0.25rem; color: hsl(var(--primary)); border-color: hsl(var(--primary) / 0.35); background: hsl(var(--primary) / 0.08); }
893
+ .scalio-ai-badge .scalio-icon { width: 0.75rem; height: 0.75rem; }
894
+ .dark .scalio-ai-badge, .dark .scalio-ai-btn .scalio-icon { color: #8ba6f7; }
895
+ .scalio-ai-suggestion { display: flex; flex-direction: column; gap: 0.5rem; padding: 0.875rem 1rem; border: 1px solid hsl(var(--primary) / 0.3); border-left-width: 3px; border-radius: var(--radius, 4px); background: hsl(var(--card)); }
896
+ .scalio-ai-suggestion-head { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
897
+ .scalio-ai-suggestion-text { white-space: pre-wrap; font-size: 0.875rem; }
898
+ .scalio-ai-suggestion-actions { display: flex; flex-wrap: wrap; gap: 0.5rem; }
899
+ .scalio-ai-feature { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 0.5rem 0; }
900
+ .scalio-ai-feature + .scalio-ai-feature { border-top: 1px solid hsl(var(--border)); }
901
+ .scalio-ai-feature-text { display: flex; flex-direction: column; gap: 0.125rem; min-width: 0; }
902
+ .scalio-ai-feature select { width: auto; min-width: 11rem; }
903
+ .scalio-ai-usage { display: grid; grid-template-columns: max-content 1fr; gap: 0.25rem 1rem; font-size: 0.875rem; margin: 0; }
904
+ .scalio-ai-usage dd { margin: 0; font-family: 'JetBrains Mono', monospace; }
905
+ .scalio-ai-credits { display: flex; align-items: center; gap: 0.75rem; font-size: 0.875rem; }
906
+ .scalio-ai-credits-bar { flex: 1; max-width: 16rem; height: 0.5rem; border-radius: 999px; background: hsl(var(--border)); overflow: hidden; }
907
+ .scalio-ai-credits-bar span { display: block; height: 100%; background: hsl(var(--primary)); }
908
+ .scalio-ai-credits-bar span.is-warn { background: #d97706; }
909
+ .scalio-ai-credits-bar span.is-stop { background: hsl(var(--destructive)); }
910
+ .scalio-ai-sources { margin-top: 0.375rem; font-size: 0.75rem; color: hsl(var(--muted-foreground)); display: flex; flex-wrap: wrap; gap: 0.25rem 0.5rem; }
911
+ .scalio-ai-source { padding: 0 0.375rem; border: 1px solid hsl(var(--border)); border-radius: 999px; }
912
+ .scalio-ai-panel { position: fixed; top: var(--scalio-header-height, 60px); right: 0; bottom: 0; z-index: 50; width: min(420px, 100vw); display: flex; flex-direction: column; gap: 0.75rem; padding: 1rem; background: hsl(var(--card)); border-left: 1px solid hsl(var(--border)); box-shadow: -8px 0 24px rgb(0 0 0 / 0.08); }
913
+ .scalio-ai-panel-head { display: flex; align-items: center; gap: 0.5rem; }
914
+ .scalio-ai-panel-head .scalio-btn { margin-left: auto; }
915
+ .scalio-ai-panel-turns { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 0.75rem; }
916
+ .scalio-ai-turn { display: flex; flex-direction: column; gap: 0.25rem; font-size: 0.875rem; }
917
+ .scalio-ai-turn.is-user { align-self: flex-end; max-width: 85%; padding: 0.5rem 0.75rem; border-radius: var(--radius, 4px); background: hsl(var(--muted)); }
918
+ .scalio-ai-turn.is-error .scalio-ai-turn-text { color: hsl(var(--destructive)); }
919
+ .scalio-ai-turn-text { white-space: pre-wrap; }
920
+ .scalio-ai-panel-form { display: flex; gap: 0.5rem; align-items: flex-end; }
921
+ .scalio-ai-panel-form textarea { flex: 1; resize: vertical; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalio-cloud/ui",
3
- "version": "0.56.0",
3
+ "version": "0.58.0",
4
4
  "description": "Scalio Control Room design tokens, Tailwind preset, self-hosted fonts, the shared app header, sign-in layout, sidebar and page blocks",
5
5
  "license": "SEE LICENSE IN README.md",
6
6
  "private": false,
package/react/ai.js ADDED
@@ -0,0 +1,463 @@
1
+ "use strict";
2
+ // KI-Bausteine for every app (scalio-docs ADR 0111, BL-332). Backend: scalio_platform.ai (settings dict `ai`,
3
+ // `public_settings`, `merge_settings`, `feature_level`, `Usage.summary`).
4
+ // - AiSettingsPanel: one settings page for AI (provider, key, models fast/strong, daily limit, features with level, usage)
5
+ // - AiButton: «Mit KI erklären» / «Entwurf mit KI», only when AI is available
6
+ // - AiBadge: marks text the AI wrote
7
+ // - AiSuggestion: a proposal with reason and source; «Übernehmen», «Bearbeiten», «Verwerfen» (never runs by itself)
8
+ // - AiPanel: side panel «Assistent» with the context of the open page
9
+ const React = require("react");
10
+ const h = React.createElement;
11
+ const Icons = require("./icons");
12
+ const { SettingsSection, SettingsField: Field, SettingsRow } = require("./settings");
13
+ const { askConfirm } = require("./dialog");
14
+
15
+ const PROVIDERS = ["scalio", "openai", "anthropic", "gemini", "ollama"];
16
+ const KEY_PROVIDERS = ["openai", "anthropic", "gemini"];
17
+ const PROVIDER_NAMES = { scalio: "Scalio KI (Guthaben)", openai: "OpenAI", anthropic: "Anthropic (Claude)", gemini: "Google (Gemini)", ollama: "Ollama / lokal" };
18
+ // Defaults of scalio_platform.ai (ADR 0104); the backend sends the current ones as `defaults`.
19
+ const DEFAULT_MODELS = {
20
+ openai: { fast: "gpt-6-luna", strong: "gpt-6-astra" },
21
+ anthropic: { fast: "claude-haiku-5-5", strong: "claude-sonnet-5-5" },
22
+ gemini: { fast: "gemini-3.5-flash-lite", strong: "gemini-4-argon" },
23
+ ollama: { fast: "llama3", strong: "llama3" },
24
+ scalio: { fast: "claude-haiku-5-5", strong: "claude-sonnet-5-5" },
25
+ };
26
+ const FORMER_DEFAULTS = ["gpt-4o-mini", "claude-3-5-haiku-latest", "gemini-3.1-flash-lite", "gemini-2.0-flash", "gemini-1.5-flash"];
27
+ const LEVELS = [0, 1, 2, 3, 4];
28
+
29
+ const LABELS = {
30
+ de: {
31
+ title: "KI-Assistent",
32
+ hint: "KI ist eine Option: Sie erklärt, fasst zusammen und schlägt vor. Was etwas ändert, bestätigen Sie immer selbst.",
33
+ enable: "KI einschalten",
34
+ enableHint: "Aus: alle KI-Funktionen sind ausgeblendet.",
35
+ statusOff: "Aus",
36
+ statusReady: "Bereit",
37
+ statusSetup: "Einrichtung nötig",
38
+ notLicensed: "Der KI-Assistent ist in Ihrer Lizenz nicht enthalten.",
39
+ managed: "Scalio KI: Die Instanz nutzt das KI-Guthaben Ihrer Organisation, kein eigener Schlüssel nötig.",
40
+ provider: "Anbieter",
41
+ modelFast: "Schnelles Modell",
42
+ modelFastHint: "Für Zusammenfassungen, Erklärungen, Zuordnungen. Leer = Standard:",
43
+ modelStrong: "Starkes Modell",
44
+ modelStrongHint: "Für Pläne und Hilfe. Leer = Standard:",
45
+ key: "API-Schlüssel",
46
+ keyStored: "Ein Schlüssel ist gespeichert. Leer lassen, um ihn zu behalten.",
47
+ openaiBase: "Basis-URL (optional)",
48
+ openaiBaseHint: "Für einen OpenAI-kompatiblen Endpunkt, z. B. Azure OpenAI im eigenen Tenant.",
49
+ ollamaBase: "Basis-URL des lokalen Modells",
50
+ ollamaHint: "Ollama oder ein OpenAI-kompatibler Server in Ihrem Netz. Daten verlassen Ihr Netz nicht.",
51
+ limit: "Tageslimit pro Person (Tokens)",
52
+ limitHint: "0 = kein Limit. Zählt pro Person und Tag (UTC).",
53
+ features: "Funktionen",
54
+ featuresHint: "Pro Funktion die höchste Stufe. Höher als die Stufe der App geht nicht.",
55
+ level: ["Aus", "Erklären", "Entwurf", "Aktion nach Klick", "Selbständig"],
56
+ privacy: "Datenschutz: Kennwörter, Schlüssel und Tokens werden vor jedem Aufruf entfernt. Ein Aufruf enthält nur Daten eines Tenants. Fragen und Antworten werden nicht gespeichert, nur die Anzahl Tokens.",
57
+ save: "Speichern",
58
+ saved: "Gespeichert.",
59
+ usage: "Nutzung",
60
+ usageNone: "Noch keine KI-Aufrufe.",
61
+ usageCalls: "Aufrufe",
62
+ usageTokens: "Tokens gesamt",
63
+ usageMine: "Meine Tokens heute",
64
+ usageToday: "Heute pro Person",
65
+ usageReset: "Zähler zurücksetzen",
66
+ usageResetConfirm: "Alle KI-Zähler auf null setzen?",
67
+ demo: "Im Demo-Modus werden Einstellungen nicht gespeichert.",
68
+ explain: "Mit KI erklären",
69
+ draft: "Entwurf mit KI",
70
+ working: "KI arbeitet …",
71
+ badge: "KI",
72
+ badgeTitle: "Von der KI geschrieben. Bitte prüfen.",
73
+ accept: "Übernehmen",
74
+ edit: "Bearbeiten",
75
+ reject: "Verwerfen",
76
+ reason: "Begründung",
77
+ source: "Quelle",
78
+ risk: { low: "Risiko gering", medium: "Risiko mittel", high: "Risiko hoch" },
79
+ panelTitle: "Assistent",
80
+ panelContext: "Bezieht sich auf: {context}",
81
+ panelPlaceholder: "Frage stellen …",
82
+ panelSend: "Senden",
83
+ panelClose: "Schliessen",
84
+ panelEmpty: "Fragen Sie zur offenen Seite. Die Antworten sind Vorschläge, prüfen Sie sie.",
85
+ scalioHint: "Scalio KI: kein eigener Schlüssel nötig. Die Aufrufe laufen über Scalio Compass und verbrauchen das KI-Guthaben Ihrer Organisation (schnell 1, stark 5). Inhalte werden nicht gespeichert.",
86
+ scalioUnavailable: "Scalio KI braucht die Verbindung zu Scalio Compass (Einstellungen → Support).",
87
+ credits: "KI-Guthaben diesen Monat",
88
+ creditsNone: "Ihre Organisation hat noch kein Paket «Scalio KI». Pakete gibt es in Scalio Compass.",
89
+ creditsWarn: "Über 80 % des Guthabens sind verbraucht.",
90
+ creditsStop: "Das Guthaben ist aufgebraucht. Die KI ist bis zum Monatsende aus; alles andere läuft weiter.",
91
+ helpTitle: "Frag Scalio",
92
+ helpEmpty: "Fragen Sie zur Bedienung. Die Antwort kommt aus dem Handbuch dieser Version.",
93
+ helpSources: "Quellen",
94
+ },
95
+ en: {
96
+ title: "AI assistant",
97
+ hint: "AI is optional: it explains, summarises and suggests. Anything that changes something you always confirm yourself.",
98
+ enable: "Turn on AI",
99
+ enableHint: "Off: all AI features are hidden.",
100
+ statusOff: "Off",
101
+ statusReady: "Ready",
102
+ statusSetup: "Setup needed",
103
+ notLicensed: "The AI assistant is not part of your license.",
104
+ managed: "Scalio AI: this instance uses your organisation's AI credits, no own key needed.",
105
+ provider: "Provider",
106
+ modelFast: "Fast model",
107
+ modelFastHint: "For summaries, explanations, mapping. Empty = default:",
108
+ modelStrong: "Strong model",
109
+ modelStrongHint: "For plans and help. Empty = default:",
110
+ key: "API key",
111
+ keyStored: "A key is stored. Leave empty to keep it.",
112
+ openaiBase: "Base URL (optional)",
113
+ openaiBaseHint: "For an OpenAI-compatible endpoint, e.g. Azure OpenAI in your own tenant.",
114
+ ollamaBase: "Base URL of the local model",
115
+ ollamaHint: "Ollama or an OpenAI-compatible server in your network. Data does not leave your network.",
116
+ limit: "Daily limit per person (tokens)",
117
+ limitHint: "0 = no limit. Counted per person and day (UTC).",
118
+ features: "Features",
119
+ featuresHint: "The highest level per feature. It cannot go above the level the app allows.",
120
+ level: ["Off", "Explain", "Draft", "Action after a click", "On its own"],
121
+ privacy: "Privacy: passwords, keys and tokens are removed before every call. A call holds the data of one tenant only. Questions and answers are not stored, only the token count.",
122
+ save: "Save",
123
+ saved: "Saved.",
124
+ usage: "Usage",
125
+ usageNone: "No AI calls yet.",
126
+ usageCalls: "Calls",
127
+ usageTokens: "Tokens in total",
128
+ usageMine: "My tokens today",
129
+ usageToday: "Today per person",
130
+ usageReset: "Reset counters",
131
+ usageResetConfirm: "Set all AI counters to zero?",
132
+ demo: "Settings are not saved in demo mode.",
133
+ explain: "Explain with AI",
134
+ draft: "Draft with AI",
135
+ working: "AI is working …",
136
+ badge: "AI",
137
+ badgeTitle: "Written by the AI. Please check.",
138
+ accept: "Apply",
139
+ edit: "Edit",
140
+ reject: "Discard",
141
+ reason: "Reason",
142
+ source: "Source",
143
+ risk: { low: "Low risk", medium: "Medium risk", high: "High risk" },
144
+ panelTitle: "Assistant",
145
+ panelContext: "About: {context}",
146
+ panelPlaceholder: "Ask a question …",
147
+ panelSend: "Send",
148
+ panelClose: "Close",
149
+ panelEmpty: "Ask about the open page. The answers are suggestions, please check them.",
150
+ scalioHint: "Scalio AI: no own key needed. The calls go through Scalio Compass and use your organisation's AI credits (fast 1, strong 5). Content is not stored.",
151
+ scalioUnavailable: "Scalio AI needs the connection to Scalio Compass (Settings → Support).",
152
+ credits: "AI credits this month",
153
+ creditsNone: "Your organisation has no «Scalio AI» package yet. Packages are in Scalio Compass.",
154
+ creditsWarn: "More than 80 % of the credits are used.",
155
+ creditsStop: "The credits are used up. AI is off until the end of the month; everything else keeps working.",
156
+ helpTitle: "Ask Scalio",
157
+ helpEmpty: "Ask how to use the app. The answer comes from the manual of this version.",
158
+ helpSources: "Sources",
159
+ },
160
+ };
161
+
162
+ function labels(lang, overrides) {
163
+ return Object.assign({}, LABELS[lang === "en" ? "en" : "de"], overrides || {});
164
+ }
165
+
166
+ function fill(text, vars) {
167
+ return Object.keys(vars || {}).reduce((s, k) => s.split(`{${k}}`).join(vars[k] == null ? "" : vars[k]), text);
168
+ }
169
+
170
+ function errorText(err) {
171
+ const d = err && err.response && err.response.data && err.response.data.detail;
172
+ if (typeof d === "string") return d;
173
+ return (err && err.message) || String(err);
174
+ }
175
+
176
+ function chosen(models) {
177
+ const out = {};
178
+ Object.keys(models || {}).forEach((k) => { if (models[k] && !FORMER_DEFAULTS.includes(models[k])) out[k] = models[k]; });
179
+ return out;
180
+ }
181
+
182
+ // The stored `ai` dict as the backend's public_settings sends it -> form state.
183
+ function aiForm(ai) {
184
+ ai = ai || {};
185
+ const blank = { openai: "", anthropic: "", gemini: "", ollama: "", scalio: "" };
186
+ return {
187
+ enabled: !!ai.enabled,
188
+ activeProvider: PROVIDERS.includes(ai.activeProvider) ? ai.activeProvider : "openai",
189
+ models: Object.assign({}, blank, chosen(ai.models)),
190
+ strongModels: Object.assign({}, blank, chosen(ai.strongModels)),
191
+ keys: { openai: "", anthropic: "", gemini: "" },
192
+ keysSet: ai.keysSet || {},
193
+ openaiBaseUrl: ai.openaiBaseUrl || "",
194
+ ollamaBaseUrl: ai.ollamaBaseUrl || "",
195
+ dailyTokenLimitPerUser: Number(ai.dailyTokenLimitPerUser) || 0,
196
+ features: Object.assign({}, ai.features || {}),
197
+ };
198
+ }
199
+
200
+ // Form state -> body for merge_settings: only typed keys go out (empty keeps the stored key).
201
+ function aiPatch(form) {
202
+ const keys = {};
203
+ KEY_PROVIDERS.forEach((p) => { const v = String(form.keys[p] || "").trim(); if (v && !v.includes("•")) keys[p] = v; });
204
+ return {
205
+ enabled: !!form.enabled, activeProvider: form.activeProvider,
206
+ models: Object.assign({}, form.models), strongModels: Object.assign({}, form.strongModels),
207
+ keys, openaiBaseUrl: form.openaiBaseUrl || "", ollamaBaseUrl: form.ollamaBaseUrl || "",
208
+ dailyTokenLimitPerUser: Math.max(0, Math.floor(Number(form.dailyTokenLimitPerUser) || 0)),
209
+ features: Object.assign({}, form.features),
210
+ };
211
+ }
212
+
213
+ function configured(form, managed) {
214
+ if (managed || form.activeProvider === "scalio") return true;
215
+ if (form.activeProvider === "ollama") return !!form.ollamaBaseUrl;
216
+ return !!(form.keysSet[form.activeProvider] || String(form.keys[form.activeProvider] || "").trim());
217
+ }
218
+
219
+ // api: axios instance with the app's base URL. Paths are Nexus' and can be changed.
220
+ function aiApi(api, paths) {
221
+ const p = Object.assign({ usage: "/ai/usage", reset: "/ai/usage/reset", credits: "/ai/credits" }, paths || {});
222
+ return {
223
+ usage: () => api.get(p.usage).then((r) => r.data),
224
+ credits: () => api.get(p.credits).then((r) => r.data),
225
+ resetUsage: () => api.post(p.reset).then((r) => r.data),
226
+ };
227
+ }
228
+
229
+ // Props: value (public_settings `ai`), status ({licensed, managed, defaults}), onSave(patch) -> Promise,
230
+ // client (aiApi; optional, without it no usage block), features ([{key, label, hint, max}]), canReset,
231
+ // demo, lang, labels, notify(message, tone), formatError(err).
232
+ function AiSettingsPanel(props) {
233
+ const L = labels(props.lang, props.labels);
234
+ const fmtErr = props.formatError || errorText;
235
+ const status = props.status || {};
236
+ const licensed = status.licensed !== false;
237
+ const managed = !!status.managed;
238
+ const [form, setForm] = React.useState(() => aiForm(props.value));
239
+ const [busy, setBusy] = React.useState(false);
240
+ const [error, setError] = React.useState("");
241
+ const [usage, setUsage] = React.useState(null);
242
+ const [credits, setCredits] = React.useState(null);
243
+ React.useEffect(() => { setForm(aiForm(props.value)); }, [props.value]);
244
+ const loadUsage = () => props.client && props.client.usage().then(setUsage).catch(() => {});
245
+ React.useEffect(() => {
246
+ if (form.activeProvider === "scalio" && props.client && props.client.credits) props.client.credits().then(setCredits).catch(() => setCredits(null));
247
+ }, [props.client, form.activeProvider]); // eslint-disable-line react-hooks/exhaustive-deps
248
+ React.useEffect(() => { loadUsage(); }, [props.client]); // eslint-disable-line react-hooks/exhaustive-deps
249
+
250
+ const p = form.activeProvider;
251
+ const hints = (Object.assign({}, DEFAULT_MODELS, status.defaults || {}))[p] || {};
252
+ const set = (patch) => setForm((f) => Object.assign({}, f, patch));
253
+ const setIn = (field, key, v) => setForm((f) => Object.assign({}, f, { [field]: Object.assign({}, f[field], { [key]: v }) }));
254
+ const ready = configured(form, managed);
255
+ const badge = !form.enabled ? ["is-neutral", L.statusOff] : ready ? ["is-ok", L.statusReady] : ["is-warn", L.statusSetup];
256
+
257
+ const save = async (e) => {
258
+ if (e) e.preventDefault();
259
+ if (props.demo) { if (props.notify) props.notify(L.demo, "info"); return; }
260
+ setBusy(true);
261
+ setError("");
262
+ try {
263
+ await props.onSave(aiPatch(form));
264
+ if (props.notify) props.notify(L.saved, "ok");
265
+ } catch (err) {
266
+ const t = fmtErr(err);
267
+ setError(t);
268
+ if (props.notify) props.notify(t, "error");
269
+ }
270
+ setBusy(false);
271
+ };
272
+ const reset = async () => {
273
+ if (!(await askConfirm({ title: L.usageReset, text: L.usageResetConfirm, confirmLabel: L.usageReset, lang: props.lang }))) return;
274
+ try { await props.client.resetUsage(); await loadUsage(); } catch (err) { if (props.notify) props.notify(fmtErr(err), "error"); }
275
+ };
276
+
277
+ const off = !licensed || busy;
278
+ const input = (id, value, onChange, extra) => h("input", Object.assign({ id, className: "scalio-input", value, disabled: off,
279
+ "data-testid": id, onChange: (e) => onChange(e.target.value) }, extra || {}));
280
+ const rows = [];
281
+ if (!licensed) rows.push(h("div", { key: "lic", className: "scalio-notice is-warn", "data-testid": "ai-not-licensed" }, L.notLicensed));
282
+ rows.push(h(SettingsRow, { key: "on", title: L.enable, hint: L.enableHint, testId: "ai-enable-row" },
283
+ h("span", { className: `scalio-badge ${badge[0]}`, "data-testid": "ai-status-badge" }, badge[1]),
284
+ h("input", { type: "checkbox", role: "switch", className: "scalio-switch", checked: form.enabled, disabled: off,
285
+ "aria-label": L.enable, "data-testid": "ai-enable-switch", onChange: (e) => set({ enabled: e.target.checked }) })));
286
+ if (managed) {
287
+ rows.push(h("div", { key: "managed", className: "scalio-notice is-info", "data-testid": "ai-managed" }, L.managed));
288
+ } else {
289
+ rows.push(h(Field, { key: "prov", id: "ai-provider", label: L.provider },
290
+ h("select", { id: "ai-provider", className: "scalio-input", value: p, disabled: off, "data-testid": "ai-provider-select",
291
+ onChange: (e) => set({ activeProvider: e.target.value }) },
292
+ PROVIDERS.filter((x) => x !== "scalio" || status.scalio !== false || p === "scalio")
293
+ .map((x) => h("option", { key: x, value: x }, PROVIDER_NAMES[x])))));
294
+ }
295
+ if (!managed && p === "scalio") {
296
+ rows.push(h("div", { key: "scalio", className: `scalio-notice ${status.scalio === false ? "is-warn" : "is-info"}`, "data-testid": "ai-scalio" },
297
+ status.scalio === false ? L.scalioUnavailable : L.scalioHint));
298
+ if (credits) rows.push(h(AiCredits, { key: "credits", credits, L }));
299
+ } else if (!managed) {
300
+ rows.push(h(Field, { key: "fast", id: "ai-model-fast", label: L.modelFast, hint: `${L.modelFastHint} ${hints.fast || "–"}` },
301
+ input("ai-model-fast", form.models[p] || "", (v) => setIn("models", p, v), { placeholder: hints.fast })));
302
+ rows.push(h(Field, { key: "strong", id: "ai-model-strong", label: L.modelStrong, hint: `${L.modelStrongHint} ${hints.strong || "–"}` },
303
+ input("ai-model-strong", form.strongModels[p] || "", (v) => setIn("strongModels", p, v), { placeholder: hints.strong })));
304
+ if (KEY_PROVIDERS.includes(p)) {
305
+ rows.push(h(Field, { key: "key", id: "ai-key", label: `${L.key} · ${PROVIDER_NAMES[p]}`, hint: form.keysSet[p] ? L.keyStored : null },
306
+ input("ai-key", form.keys[p] || "", (v) => setIn("keys", p, v), { type: "password", autoComplete: "off",
307
+ placeholder: form.keysSet[p] ? "••••••••" : "sk-…" })));
308
+ }
309
+ if (p === "openai") rows.push(h(Field, { key: "obase", id: "ai-openai-base", label: L.openaiBase, hint: L.openaiBaseHint },
310
+ input("ai-openai-base", form.openaiBaseUrl, (v) => set({ openaiBaseUrl: v }), { placeholder: "https://api.openai.com/v1" })));
311
+ if (p === "ollama") rows.push(h(Field, { key: "lbase", id: "ai-ollama-base", label: L.ollamaBase, hint: L.ollamaHint },
312
+ input("ai-ollama-base", form.ollamaBaseUrl, (v) => set({ ollamaBaseUrl: v }), { placeholder: "http://localhost:11434" })));
313
+ }
314
+ rows.push(h(Field, { key: "limit", id: "ai-daily-limit", label: L.limit, hint: L.limitHint },
315
+ input("ai-daily-limit", String(form.dailyTokenLimitPerUser), (v) => set({ dailyTokenLimitPerUser: v === "" ? 0 : Number(v) }),
316
+ { type: "number", min: 0, step: 1000 })));
317
+ const feats = props.features || [];
318
+ if (feats.length) {
319
+ rows.push(h(Field, { key: "feats", label: L.features, hint: L.featuresHint, testId: "ai-features" },
320
+ feats.map((f) => {
321
+ const max = Math.max(0, Math.min(4, f.max == null ? 4 : f.max));
322
+ const cur = form.features[f.key] == null ? max : Math.min(max, Number(form.features[f.key]));
323
+ return h("div", { key: f.key, className: "scalio-ai-feature", "data-testid": `ai-feature-${f.key}` },
324
+ h("div", { className: "scalio-ai-feature-text" }, h("strong", null, f.label), f.hint ? h("span", { className: "scalio-settings-help" }, f.hint) : null),
325
+ h("select", { className: "scalio-input", value: String(cur), disabled: off, "aria-label": f.label,
326
+ "data-testid": `ai-feature-${f.key}-level`, onChange: (e) => setIn("features", f.key, Number(e.target.value)) },
327
+ LEVELS.filter((l) => l <= max).map((l) => h("option", { key: l, value: String(l) }, L.level[l]))));
328
+ })));
329
+ }
330
+ rows.push(h("p", { key: "privacy", className: "scalio-settings-help", "data-testid": "ai-privacy" }, L.privacy));
331
+ if (error) rows.push(h("div", { key: "err", className: "scalio-notice is-error", role: "alert", "data-testid": "ai-error" }, error));
332
+ rows.push(h("div", { key: "save", className: "scalio-settings-section-footer" },
333
+ h("button", { type: "submit", className: "scalio-btn is-primary", disabled: off, "data-testid": "ai-save-button" }, L.save)));
334
+ if (props.client) rows.push(h(AiUsage, { key: "usage", usage, L, canReset: props.canReset, onReset: reset }));
335
+ return h(SettingsSection, { id: "ai", title: L.title, description: L.hint, testId: "ai-settings" },
336
+ h("form", { onSubmit: save, "data-testid": "ai-settings-form" }, rows));
337
+ }
338
+
339
+ function AiCredits({ credits, L }) {
340
+ const fmt = (n) => Number(n || 0).toLocaleString("de-CH");
341
+ const limit = Number(credits.limit) || 0;
342
+ const pct = limit ? Math.min(100, Math.round((100 * (Number(credits.used) || 0)) / limit)) : 100;
343
+ const note = !limit ? L.creditsNone : credits.state === "stop" ? L.creditsStop : credits.state === "warn" ? L.creditsWarn : null;
344
+ return h(Field, { label: L.credits, testId: "ai-credits" },
345
+ limit ? h("div", { className: "scalio-ai-credits" },
346
+ h("div", { className: "scalio-ai-credits-bar", role: "progressbar", "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": pct },
347
+ h("span", { className: `is-${credits.state || "ok"}`, style: { width: `${pct}%` } })),
348
+ h("span", { "data-testid": "ai-credits-text" }, `${fmt(credits.used)} / ${fmt(limit)}`)) : null,
349
+ note ? h("p", { className: `scalio-settings-help${credits.state === "stop" || !limit ? " is-warn" : ""}`, "data-testid": "ai-credits-note" }, note) : null);
350
+ }
351
+
352
+ function AiUsage({ usage, L, canReset, onReset }) {
353
+ const fmt = (n) => Number(n || 0).toLocaleString("de-CH");
354
+ const body = !usage || !usage.total
355
+ ? h("p", { className: "scalio-settings-text", "data-testid": "ai-usage-empty" }, L.usageNone)
356
+ : h("dl", { className: "scalio-ai-usage" },
357
+ h("dt", null, L.usageCalls), h("dd", { "data-testid": "ai-usage-total" }, fmt(usage.total)),
358
+ usage.totalTokens ? [h("dt", { key: "t" }, L.usageTokens), h("dd", { key: "tv", "data-testid": "ai-usage-tokens" }, fmt(usage.totalTokens))] : null,
359
+ usage.dailyLimit ? [h("dt", { key: "m" }, L.usageMine), h("dd", { key: "mv", "data-testid": "ai-usage-mine" }, `${fmt(usage.myTokensToday)} / ${fmt(usage.dailyLimit)}`)] : null,
360
+ (usage.usersToday || []).length ? [h("dt", { key: "u" }, L.usageToday), h("dd", { key: "uv", "data-testid": "ai-usage-users" },
361
+ usage.usersToday.map((r) => h("div", { key: r.user }, `${r.user}: ${fmt(r.tokens)}`)))] : null);
362
+ return h(Field, { label: L.usage, testId: "ai-usage" }, body,
363
+ canReset && usage && usage.total ? h("button", { type: "button", className: "scalio-btn is-ghost", "data-testid": "ai-usage-reset", onClick: onReset }, L.usageReset) : null);
364
+ }
365
+
366
+ // Props: available (status.available and the feature's level >= 1), kind ("explain" | "draft"), onClick, busy, label, lang, labels, testId.
367
+ function AiButton(props) {
368
+ if (!props.available) return null;
369
+ const L = labels(props.lang, props.labels);
370
+ const text = props.busy ? L.working : (props.label || (props.kind === "draft" ? L.draft : L.explain));
371
+ return h("button", { type: "button", className: "scalio-btn scalio-ai-btn", disabled: !!props.busy || !!props.disabled,
372
+ "aria-busy": props.busy ? "true" : "false", "data-testid": props.testId || "ai-button", onClick: props.onClick },
373
+ props.busy ? h("span", { className: "scalio-spinner", "aria-hidden": "true" }) : h(Icons.Sparkles, { className: "scalio-icon" }), text);
374
+ }
375
+
376
+ function AiBadge(props) {
377
+ const L = labels(props.lang, props.labels);
378
+ return h("span", { className: "scalio-badge scalio-ai-badge", title: L.badgeTitle, "data-testid": props.testId || "ai-badge" },
379
+ h(Icons.Sparkles, { className: "scalio-icon" }), L.badge);
380
+ }
381
+
382
+ // Props: suggestion ({title, text, reason, risk, source}), onAccept, onEdit, onReject (each optional), busy, lang, labels, testId.
383
+ // The app runs its normal action in onAccept, with the person's rights and an audit entry (ADR 0111 K3).
384
+ function AiSuggestion(props) {
385
+ const L = labels(props.lang, props.labels);
386
+ const s = props.suggestion || {};
387
+ const risk = ["low", "medium", "high"].includes(s.risk) ? s.risk : null;
388
+ const tid = props.testId || "ai-suggestion";
389
+ const btn = (key, cls, label, fn) => fn ? h("button", { key, type: "button", className: `scalio-btn ${cls}`, disabled: !!props.busy,
390
+ "data-testid": `${tid}-${key}`, onClick: fn }, label) : null;
391
+ return h("div", { className: "scalio-ai-suggestion", role: "group", "aria-label": s.title || L.badge, "data-testid": tid },
392
+ h("div", { className: "scalio-ai-suggestion-head" }, h(AiBadge, { lang: props.lang, labels: props.labels, testId: `${tid}-badge` }),
393
+ s.title ? h("strong", null, s.title) : null,
394
+ risk ? h("span", { className: `scalio-badge ${risk === "high" ? "is-error" : risk === "medium" ? "is-warn" : "is-ok"}`, "data-testid": `${tid}-risk` }, L.risk[risk]) : null),
395
+ s.text ? h("div", { className: "scalio-ai-suggestion-text", "data-testid": `${tid}-text` }, s.text) : null,
396
+ s.reason ? h("div", { className: "scalio-settings-help" }, `${L.reason}: ${s.reason}`) : null,
397
+ s.source ? h("div", { className: "scalio-settings-help", "data-testid": `${tid}-source` }, `${L.source}: ${s.source}`) : null,
398
+ h("div", { className: "scalio-ai-suggestion-actions" },
399
+ btn("accept", "is-primary", L.accept, props.onAccept), btn("edit", "", L.edit, props.onEdit), btn("reject", "is-ghost", L.reject, props.onReject)));
400
+ }
401
+
402
+ // Props: open, onClose, context (name of the open page or object), onAsk(question, history) -> Promise<string>,
403
+ // lang, labels, testId. History is kept while the panel lives; nothing is stored.
404
+ function AiPanel(props) {
405
+ const L = labels(props.lang, props.labels);
406
+ const [turns, setTurns] = React.useState([]);
407
+ const [q, setQ] = React.useState("");
408
+ const [busy, setBusy] = React.useState(false);
409
+ const field = React.useRef(null);
410
+ React.useEffect(() => { if (props.open && field.current) field.current.focus(); }, [props.open]);
411
+ if (!props.open) return null;
412
+ const tid = props.testId || "ai-panel";
413
+ const ask = async (e) => {
414
+ if (e) e.preventDefault();
415
+ const question = q.trim();
416
+ if (!question || busy) return;
417
+ const history = turns.map((t) => ({ role: t.role, content: t.content }));
418
+ setTurns((t) => t.concat([{ role: "user", content: question }]));
419
+ setQ("");
420
+ setBusy(true);
421
+ let answer;
422
+ try {
423
+ const out = await props.onAsk(question, history);
424
+ answer = out && typeof out === "object"
425
+ ? { role: "assistant", content: String(out.text || ""), sources: Array.isArray(out.sources) ? out.sources : [] }
426
+ : { role: "assistant", content: String(out) };
427
+ }
428
+ catch (err) { answer = { role: "assistant", content: errorText(err), error: true }; }
429
+ setTurns((t) => t.concat([answer]));
430
+ setBusy(false);
431
+ };
432
+ const title = props.title || L.panelTitle;
433
+ return h("aside", { className: "scalio-ai-panel", role: "complementary", "aria-label": title, "data-testid": tid,
434
+ onKeyDown: (e) => { if (e.key === "Escape" && props.onClose) props.onClose(); } },
435
+ h("div", { className: "scalio-ai-panel-head" },
436
+ h(Icons.Sparkles, { className: "scalio-icon" }), h("strong", null, title),
437
+ props.onClose ? h("button", { type: "button", className: "scalio-btn is-ghost", "aria-label": L.panelClose, "data-testid": `${tid}-close`, onClick: props.onClose },
438
+ h(Icons.X, { className: "scalio-icon" })) : null),
439
+ props.context ? h("div", { className: "scalio-settings-help", "data-testid": `${tid}-context` }, fill(L.panelContext, { context: props.context })) : null,
440
+ h("div", { className: "scalio-ai-panel-turns", "aria-live": "polite", "data-testid": `${tid}-turns` },
441
+ turns.length ? turns.map((t, i) => h("div", { key: i, className: `scalio-ai-turn is-${t.role}${t.error ? " is-error" : ""}` },
442
+ t.role === "assistant" && !t.error ? h(AiBadge, { lang: props.lang, labels: props.labels, testId: `${tid}-badge-${i}` }) : null,
443
+ h("div", { className: "scalio-ai-turn-text" }, t.content),
444
+ t.sources && t.sources.length ? h("div", { className: "scalio-ai-sources", "data-testid": `${tid}-sources-${i}` },
445
+ h("span", null, `${L.helpSources}: `),
446
+ t.sources.map((src, j) => h("span", { key: j, className: "scalio-ai-source" }, src.url
447
+ ? h("a", { href: src.url, target: "_blank", rel: "noreferrer" }, src.title || src.source) : (src.title || src.source)))) : null))
448
+ : h("p", { className: "scalio-settings-help" }, props.emptyText || L.panelEmpty),
449
+ busy ? h("div", { className: "scalio-ai-turn is-assistant", "data-testid": `${tid}-busy` }, h("span", { className: "scalio-spinner", "aria-hidden": "true" }), L.working) : null),
450
+ h("form", { className: "scalio-ai-panel-form", onSubmit: ask },
451
+ h("textarea", { ref: field, className: "scalio-input", rows: 2, value: q, placeholder: L.panelPlaceholder, "aria-label": L.panelPlaceholder,
452
+ "data-testid": `${tid}-input`, onChange: (e) => setQ(e.target.value),
453
+ onKeyDown: (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(); } } }),
454
+ h("button", { type: "submit", className: "scalio-btn is-primary", disabled: busy || !q.trim(), "data-testid": `${tid}-send` }, L.panelSend)));
455
+ }
456
+
457
+ // «Frag Scalio» (ADR 0111 K7): AiPanel with the help title; onAsk returns {text, sources: [{title, source, url}]}.
458
+ function AiHelp(props) {
459
+ const L = labels(props.lang, props.labels);
460
+ return h(AiPanel, Object.assign({ testId: "ai-help", title: L.helpTitle, emptyText: L.helpEmpty }, props));
461
+ }
462
+
463
+ module.exports = { AiSettingsPanel, AiHelp, AiCredits, AiButton, AiBadge, AiSuggestion, AiPanel, aiApi, aiForm, aiPatch, AI_LABELS: LABELS, AI_LEVELS: LEVELS };
package/react/icons.js CHANGED
@@ -134,8 +134,12 @@ const Globe = icon([
134
134
  const Clock = icon([["circle", { cx: 12, cy: 12, r: 10 }], ["path", { d: "M12 6v6l4 2" }]]);
135
135
  const Upload = icon([["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }], ["path", { d: "m17 8-5-5-5 5" }], ["path", { d: "M12 3v12" }]]);
136
136
  const RotateCcw = icon([["path", { d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" }], ["path", { d: "M3 3v5h5" }]]);
137
+ const Sparkles = icon([
138
+ ["path", { d: "M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z" }],
139
+ ["path", { d: "M20 3v4M22 5h-4M4 17v2M5 18H3" }],
140
+ ]);
137
141
  const Download = icon([["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }], ["path", { d: "m7 10 5 5 5-5" }], ["path", { d: "M12 15V3" }]]);
138
142
 
139
143
  module.exports = { Sun, Moon, Monitor, LifeBuoy, BookOpen, LogOut, Menu, Check, X, Search, ChevronDown, Fingerprint, FileStack, ShieldCheck, Hammer, Activity,
140
144
  Smartphone, KeyRound, Trash, Copy, Puzzle, Plus, Pencil, Link2, Alert, History, CornerDownLeft,
141
- Users, Settings, ScrollText, Info, RadioTower, Globe, Clock, Download, Upload, RotateCcw };
145
+ Users, Settings, ScrollText, Info, RadioTower, Globe, Clock, Download, Upload, RotateCcw, Sparkles };
package/react/index.js CHANGED
@@ -378,6 +378,6 @@ module.exports = {
378
378
  TEST_IDS,
379
379
  initials,
380
380
  };
381
- Object.assign(module.exports, Nav, Blocks, require("./settings"), require("./support"), require("./beacon"), require("./security"), require("./license"), require("./palette"), require("./unify"), require("./profile"), require("./actions"), require("./selftest"), require("./users"), require("./customers"), require("./roles"), require("./wizard"), require("./maintenance"), require("./backup"), require("./audit"), require("./mail"), require("./saas_updates"), require("./pages"), require("./tenant"), require("./fields"), require("./dialog"), require("./keyboard"), require("./agents"));
381
+ Object.assign(module.exports, Nav, Blocks, require("./settings"), require("./support"), require("./beacon"), require("./security"), require("./license"), require("./palette"), require("./unify"), require("./profile"), require("./actions"), require("./selftest"), require("./users"), require("./customers"), require("./roles"), require("./wizard"), require("./maintenance"), require("./backup"), require("./audit"), require("./mail"), require("./saas_updates"), require("./pages"), require("./tenant"), require("./fields"), require("./dialog"), require("./keyboard"), require("./agents"), require("./ai"));
382
382
  // After the exports above: auth.js uses LanguageToggle and ThemeToggle from this module.
383
383
  Object.assign(module.exports, require("./auth"), require("./session"), require("./setup"), require("./clientErrors"));