domma-cms 1.70.0 → 1.71.1

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/admin/js/lib/sidebar-frequent.js +1 -1
  3. package/admin/js/templates/docs/usage-tools.html +1 -1
  4. package/docs/DommaFeatures.md +46 -12
  5. package/package.json +1 -1
  6. package/plugins/feedback/CHANGELOG.md +5 -0
  7. package/plugins/feedback/CLAUDE.md +26 -0
  8. package/plugins/feedback/admin/css/index.css +11 -0
  9. package/plugins/feedback/admin/lib/ai.js +41 -0
  10. package/plugins/feedback/admin/lib/kit.js +3 -1
  11. package/plugins/feedback/admin/views/feedback.js +1 -1
  12. package/plugins/feedback/admin/views/inbox.js +58 -2
  13. package/plugins/feedback/docs/guide.md +2 -0
  14. package/plugins/feedback/lib/ai-text.js +217 -0
  15. package/plugins/feedback/lib/receiver.js +10 -0
  16. package/plugins/feedback/lib/themes.js +75 -0
  17. package/plugins/feedback/plugin.js +39 -2
  18. package/plugins/feedback/plugin.json +2 -2
  19. package/plugins/feedback/tests/ai.test.js +248 -0
  20. package/plugins/free-tier.lock.json +31 -21
  21. package/plugins/support/CHANGELOG.md +5 -0
  22. package/plugins/support/CLAUDE.md +33 -0
  23. package/plugins/support/admin/css/index.css +14 -0
  24. package/plugins/support/admin/lib/ai.js +68 -0
  25. package/plugins/support/admin/lib/kit.js +5 -1
  26. package/plugins/support/admin/views/inbox.js +121 -4
  27. package/plugins/support/admin/views/support.js +1 -1
  28. package/plugins/support/docs/guide.md +5 -0
  29. package/plugins/support/lib/ai-text.js +217 -0
  30. package/plugins/support/lib/assist.js +74 -0
  31. package/plugins/support/lib/receiver.js +2 -1
  32. package/plugins/support/plugin.js +73 -3
  33. package/plugins/support/plugin.json +2 -2
  34. package/plugins/support/tests/ai.test.js +245 -0
  35. package/server/services/sidebarFrequent.js +1 -1
  36. package/server/services/wpImport/redirects.js +7 -2
@@ -0,0 +1,217 @@
1
+ /**
2
+ * AI Assist on the Manager - the receiver side only. The Domma team's inbox asks Claude for summaries and
3
+ * suggestions through the Manager's own AI Assist service, reached in this process:
4
+ * globalThis[Symbol.for('domma.ai-text')] = {version: 1, tasks: [...], run(body) -> Promise<{status, body}>}
5
+ * (site-manager/services/aiTextRoutes.js). There is no fleet route here: the receiver IS the Manager, and a
6
+ * customer site never offers these features.
7
+ *
8
+ * What is sent is text only, cleaned by `scrubText()`: no names, email addresses, phone numbers, ids or files.
9
+ * A suggestion is never sent or saved by itself: the person sees it and keeps, edits or drops it.
10
+ *
11
+ * Feedback and Support each carry their own copy of this file (either can be installed alone).
12
+ *
13
+ * @module lib/ai-text
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ let aiAssistLookup = null;
19
+ try {
20
+ ({isAiAssist: aiAssistLookup} = await import('../../../server/services/aiAssist.js'));
21
+ } catch { /* an engine before AI Assist: no AI features */ }
22
+
23
+ /** Whether this server has AI Assist (the Tool is on and licensed). Tests set their own. */
24
+ export function aiAssistOn() {
25
+ try { return typeof aiAssistLookup === 'function' && aiAssistLookup() === true; } catch { return false; }
26
+ }
27
+ export function useAiAssistLookup(fn) { aiAssistLookup = fn; }
28
+
29
+ const LOCAL = Symbol.for('domma.ai-text');
30
+ const registry = () => {
31
+ const r = globalThis[LOCAL];
32
+ return r && typeof r === 'object' && typeof r.run === 'function' ? r : null;
33
+ };
34
+
35
+ /** Whether a task can be asked for here: AI Assist on, and the Manager's service in this process. */
36
+ export function aiTextAvailable(task) {
37
+ if (!aiAssistOn()) return false;
38
+ const r = registry();
39
+ if (!r) return false;
40
+ return !task || !Array.isArray(r.tasks) || r.tasks.includes(task);
41
+ }
42
+
43
+ /**
44
+ * Ask the Manager's AI Assist service. Never throws: {status, body} as it answered, or a 403/503 of its own.
45
+ * @param {object} body {task, ...} as aiTextRoutes.js takes it
46
+ */
47
+ export async function requestAiText(body) {
48
+ if (!aiAssistOn()) return {status: 403, body: {error: 'This comes with AI Assist, in the Pro plan.'}};
49
+ const r = registry();
50
+ if (!r) return {status: 503, body: {error: 'AI Assist is not available on this server.'}};
51
+ try {
52
+ const out = await r.run(body);
53
+ if (!out || !Number.isInteger(out.status)) return {status: 503, body: {error: 'AI Assist did not answer. Try again shortly.'}};
54
+ return {status: out.status, body: out.body && typeof out.body === 'object' ? out.body : {}};
55
+ } catch {
56
+ return {status: 503, body: {error: 'AI Assist is not available just now. Try again shortly.'}};
57
+ }
58
+ }
59
+
60
+ /**
61
+ * The answer an admin route gives when the service did not produce a result: its status and error text
62
+ * passed through, a decline as 422. Null when there is a result to use.
63
+ */
64
+ export function aiFailure({status, body}, declined = 'Claude would not do that one.') {
65
+ if (status === 200 && !body?.declined) return null;
66
+ return {status: status === 200 ? 422 : status,
67
+ body: {error: body?.declined ? declined : body?.error || 'AI Assist did not answer.', used: body?.used, limit: body?.limit}};
68
+ }
69
+
70
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
71
+ /** Whole words (not inside another word), longest first, any case. */
72
+ const wordsOf = (list) => {
73
+ const alts = [...new Set(list.map(w => w.toLowerCase()))].filter(w => w.length >= 2).sort((a, b) => b.length - a.length).map(escapeRe);
74
+ return alts.length ? new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alts.join('|')})(?![\\p{L}\\p{N}_])`, 'giu') : null;
75
+ };
76
+
77
+ /**
78
+ * Names that stand in for a missing one, and words a mailbox is often called: never treated as anyone's name
79
+ * (taking "site", "admin" or "support" out of every message would lose its sense, and protect no one).
80
+ */
81
+ const NOT_NAMES = new Set(['a', 'an', 'the', 'site', 'admin', 'administrator', 'an admin', 'a site admin', 'domma', 'domma support', 'support',
82
+ 'team', 'customer', 'manager', 'user', 'info', 'hello', 'contact', 'sales', 'office', 'mail', 'email', 'enquiries', 'help', 'noreply',
83
+ 'no-reply', 'webmaster', 'accounts', 'billing']);
84
+
85
+ /** The parts of the names and of the email addresses' local parts (john.smith@ -> john, smith). */
86
+ export function nameParts({names = [], emails = []} = {}) {
87
+ const out = new Set();
88
+ const add = (w) => { const v = String(w || '').trim().replace(/^[^\p{L}]+|[^\p{L}]+$/gu, ''); if (v.length >= 2 && !NOT_NAMES.has(v.toLowerCase())) out.add(v); };
89
+ for (const n of names || []) {
90
+ const full = String(n || '').trim();
91
+ if (!full || NOT_NAMES.has(full.toLowerCase())) continue;
92
+ add(full);
93
+ for (const w of full.split(/\s+/)) add(w);
94
+ }
95
+ for (const e of emails || []) {
96
+ const local = String(e || '').split('@')[0] || '';
97
+ if (!String(e || '').includes('@')) continue;
98
+ for (const w of local.split(/[._+\-\d]+/)) if (/^\p{L}+$/u.test(w)) add(w);
99
+ }
100
+ return [...out];
101
+ }
102
+
103
+ const GREETING_LINE = /^\s*(?:hi|hello|hey|dear|good (?:morning|afternoon|evening)|morning|afternoon)\b(?:[ \t]+[\p{L}'-]+){0,3}[ \t]*[,!.]?[ \t]*$/iu;
104
+ const GREETING_START = /^\s*(?:hi|hello|hey|dear|good (?:morning|afternoon|evening))\b[^,\n]{0,40},[ \t]*/iu;
105
+ const WORDS = "[\\p{L}'.-]+(?:[ \\t]+[\\p{L}'.-]+){0,2}";
106
+ /** "Thanks," / "Kind regards" / "Cheers, Jo" / "Thanks Darryl": a line of its own. Bare "Best" needs its comma or the line to end. */
107
+ const SIGN_OFF = new RegExp(`^\\s*(?:(?:many thanks|thanks(?: again| so much| very much)?|thank you(?: so much| very much| again)?|kind regards|warm regards|best regards|best wishes|all the best|regards)[ \\t]*(?:[,.!][ \\t]*(?:${WORDS})?|[ \\t]+${WORDS})?|(?:best|cheers)[ \\t]*(?:[,.!][ \\t]*(?:${WORDS})?)?)[ \\t]*[,.!]?[ \\t]*$`, 'iu');
108
+
109
+ /**
110
+ * Text fit to send. Taken out: a greeting at the start ("Hi Ann,"), a sign-off and the short lines under it
111
+ * ("Thanks,\nAnn Jones\nAcme Ltd"), earlier messages quoted in an email (lines starting ">", "On ... wrote:" and
112
+ * what follows), a signature after "-- ", email addresses and phone numbers; then the people and sites known to be
113
+ * in it: `names` and the local parts of `emails` (whole names or any part, any case, as whole words) become [name],
114
+ * `sites` (names and domains, any case; a link on a domain too) become [site]. Spaces tidied. `letter: false` (a title
115
+ * or subject) keeps the first line and any "Thanks" as they are.
116
+ */
117
+ export function scrubText(raw, max = 2000, {names = [], emails = [], sites = [], letter = true} = {}) {
118
+ const people = wordsOf(nameParts({names, emails}));
119
+ const siteList = (sites || []).map(n => String(n || '').trim().toLowerCase()).filter(Boolean);
120
+ const hosts = siteList.filter(s => /^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/.test(s));
121
+ const links = hosts.length
122
+ ? new RegExp(`(?:https?://)?(?:[a-z0-9-]+\\.)*(?:${hosts.map(escapeRe).join('|')})(?::\\d+)?(?:[/?#](?:[^\\s<>"']*[^\\s<>"'.,;:!?)\\]])?)?(?![\\w.-]*[a-z0-9])`, 'gi') : null;
123
+ const places = wordsOf(siteList.filter(s => !hosts.includes(s)));
124
+ const lines = String(raw ?? '').replace(/\r\n?/g, '\n').replace(/ /g, ' ').split('\n');
125
+ const kept = [];
126
+ let started = false;
127
+ for (let i = 0; i < lines.length; i++) {
128
+ let line = lines[i];
129
+ if (/^--\s?$/.test(line)) break;
130
+ if (/^\s*On\b.{0,200}\bwrote:\s*$/i.test(line)) break;
131
+ if (/^\s*>/.test(line)) continue;
132
+ if (letter && !started && line.trim()) {
133
+ started = true;
134
+ if (GREETING_LINE.test(line)) continue;
135
+ line = line.replace(GREETING_START, '');
136
+ }
137
+ if (letter && SIGN_OFF.test(line)) {
138
+ // The name, role and company lines under it: short ones only, at most three.
139
+ let j = i + 1;
140
+ while (j < lines.length && j <= i + 3 && lines[j].trim() && lines[j].trim().length <= 40) j++;
141
+ i = j - 1;
142
+ continue;
143
+ }
144
+ kept.push(line);
145
+ }
146
+ let out = kept.join('\n')
147
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]+/g, ' ')
148
+ // Bounded parts, so a long run without spaces costs little.
149
+ .replace(/(?:mailto:)?[^\s@<>()"',;:]{1,64}@[^\s@<>()"',;:]{1,253}\.[A-Za-z]{2,24}/g, '[email]')
150
+ // A run of digits, spaces, brackets and hyphens holding 9 to 15 digits is a phone number. Dates and
151
+ // versions (2026-11-16, 1.58.0) have fewer digits, or dots.
152
+ .replace(/(?<![\w.])\+?\(?\d[\d \t()-]{6,24}\d(?!\w|\.\d)/g, (m) => {
153
+ const digits = m.replace(/\D/g, '').length;
154
+ return digits >= 9 && digits <= 15 ? '[phone]' : m;
155
+ });
156
+ if (links) out = out.replace(links, '[site]');
157
+ if (places) out = out.replace(places, '[site]');
158
+ if (people) out = out.replace(people, '[name]');
159
+ return out
160
+ .replace(/[ \t]+/g, ' ')
161
+ .replace(/\n{3,}/g, '\n\n')
162
+ .trim()
163
+ .slice(0, max);
164
+ }
165
+
166
+ const text = (v, max) => String(v ?? '').slice(0, max);
167
+ const whole = (v) => Math.max(0, Math.floor(Number(v) || 0));
168
+
169
+ /** A kept themes result, cleaned (it is shown again later). */
170
+ export function cleanThemes(raw) {
171
+ const r = raw && typeof raw === 'object' ? raw : {};
172
+ return {
173
+ at: text(r.at, 40),
174
+ filter: text(r.filter, 300),
175
+ answers: whole(r.answers),
176
+ summary: text(r.summary, 1500),
177
+ themes: (Array.isArray(r.themes) ? r.themes : []).slice(0, 8).map(t => ({
178
+ title: text(t?.title, 120), detail: text(t?.detail, 600), count: whole(t?.count),
179
+ quotes: (Array.isArray(t?.quotes) ? t.quotes : []).slice(0, 3).map(q => text(q, 300))
180
+ }))
181
+ };
182
+ }
183
+
184
+ /** A kept summary of one conversation, cleaned. */
185
+ export function cleanSummary(raw) {
186
+ const r = raw && typeof raw === 'object' ? raw : {};
187
+ return {
188
+ at: text(r.at, 40),
189
+ messages: whole(r.messages),
190
+ summary: text(r.summary, 1500),
191
+ points: (Array.isArray(r.points) ? r.points : []).slice(0, 5).map(p => text(p, 300)).filter(Boolean)
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Results kept on the Manager, one file: {<key>: value}. Read on each use; written whole, through a temporary
197
+ * file, private (0600). Nothing here is sent anywhere.
198
+ */
199
+ export function createKept(file) {
200
+ const read = () => {
201
+ try {
202
+ const v = JSON.parse(fs.readFileSync(file, 'utf8'));
203
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
204
+ } catch { return {}; }
205
+ };
206
+ const write = (all) => {
207
+ fs.mkdirSync(path.dirname(file), {recursive: true, mode: 0o700});
208
+ const tmp = `${file}.${process.pid}.tmp`;
209
+ fs.writeFileSync(tmp, JSON.stringify(all, null, 2), {mode: 0o600});
210
+ fs.renameSync(tmp, file);
211
+ };
212
+ return {
213
+ get: (key) => read()[key] ?? null,
214
+ set(key, value) { const all = read(); all[key] = value; write(all); return value; },
215
+ remove(key) { const all = read(); if (key in all) { delete all[key]; write(all); } }
216
+ };
217
+ }
@@ -52,6 +52,16 @@ export function siteNames() {
52
52
  } catch { return {}; }
53
53
  }
54
54
 
55
+ /** slug -> every domain the site answers on (primary, fallback, the rest), from Site Manager's registry. */
56
+ export function siteHosts() {
57
+ try {
58
+ const j = JSON.parse(fs.readFileSync(path.join(SITE_MANAGER, 'data', 'sites.json'), 'utf8'));
59
+ const list = Array.isArray(j) ? j : (j.sites || Object.values(j));
60
+ return Object.fromEntries(list.filter(s => s?.slug).map(s => [s.slug,
61
+ [...new Set([s.primaryDomain, s.fallbackDomain, ...(Array.isArray(s.domains) ? s.domains : [])].filter(d => typeof d === 'string' && d))]]));
62
+ } catch { return {}; }
63
+ }
64
+
55
65
  /** Make the collection when it is missing. Every boot: a plugin switched on by copy never runs onEnable. */
56
66
  export async function ensureCollection() {
57
67
  if (await getCollection(COLLECTION)) return false;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Feedback inbox - "Summarise" (AI Assist, the Manager only). PURE: which reports the inbox shows for a filter
3
+ * (the same rules as admin/views/inbox.js), what of them is sent, and how the filter is described to Claude.
4
+ *
5
+ * What is sent of a report: its title and its description as plain text, through scrubText() - never the
6
+ * site, who sent it, their email, where it happened, the CMS version or its files.
7
+ *
8
+ * @module feedback/lib/themes
9
+ */
10
+ import {richTextToPlain} from '../../../server/services/richText.js';
11
+ import {STATUS_KEYS, TYPE_KEYS, statusLabel, typeLabel} from './shape.js';
12
+ import {scrubText} from './ai-text.js';
13
+
14
+ /** The Manager's caps for a themes task (aiTextRoutes.js LIMITS): answers, characters per answer. */
15
+ export const THEMES_MAX = {answers: 1000, answer: 2000};
16
+ export const THEMES_SURVEY = 'Feedback from Domma sites';
17
+
18
+ const plain = (v) => richTextToPlain(String(v || '')).replace(/\u00a0/g, ' ');
19
+
20
+ /** The inbox's filter, from the browser, cleaned: {status: open|all|<status>, type, site, q}. */
21
+ export function cleanFilter(raw = {}) {
22
+ const b = raw && typeof raw === 'object' ? raw : {};
23
+ const status = ['open', 'all', ...STATUS_KEYS].includes(b.status) ? b.status : 'open';
24
+ return {
25
+ status,
26
+ type: TYPE_KEYS.includes(b.type) ? b.type : '',
27
+ site: typeof b.site === 'string' ? b.site.slice(0, 100) : '',
28
+ q: typeof b.q === 'string' ? b.q.trim().slice(0, 200) : ''
29
+ };
30
+ }
31
+
32
+ const statusMatch = (f, s) => (f === 'all' ? true : f === 'open' ? !['done', 'declined'].includes(s) : s === f);
33
+
34
+ /**
35
+ * The reports the inbox shows for a filter, newest first.
36
+ * @param {Array<{id, data, meta}>} entries
37
+ * @param {object} filter cleanFilter()
38
+ * @param {object} names site slug -> name (the search looks in it, as the inbox's does)
39
+ */
40
+ export function reportsInView(entries = [], filter = cleanFilter(), names = {}) {
41
+ const q = filter.q.toLowerCase();
42
+ return entries
43
+ .filter(e => statusMatch(filter.status, e.data?.status))
44
+ .filter(e => !filter.site || e.data?.site === filter.site)
45
+ .filter(e => !filter.type || e.data?.type === filter.type)
46
+ .filter(e => !q || [e.data?.title, plain(e.data?.description), e.data?.userName, names[e.data?.site] || e.data?.site, e.data?.issueKey]
47
+ .join(' ').toLowerCase().includes(q))
48
+ .sort((a, b) => String(b.meta?.createdAt || '').localeCompare(String(a.meta?.createdAt || '')));
49
+ }
50
+
51
+ /** What is sent of each report: "Title. Description", cleaned (the sender's name and email, the site's name and domains too). Blanks dropped; at most THEMES_MAX.answers. */
52
+ export function themesAnswers(entries = [], siteNames = {}, siteHosts = {}) {
53
+ return entries
54
+ .map(e => {
55
+ // The sender (name, and the parts of their email address) and their site (name, domains, links on them).
56
+ const hosts = Array.isArray(siteHosts[e.data?.site]) ? siteHosts[e.data.site] : [];
57
+ const names = {names: [e.data?.userName], emails: [e.data?.userEmail], sites: [siteNames[e.data?.site], ...hosts]};
58
+ const title = scrubText(e.data?.title, 200, {...names, letter: false});
59
+ const body = scrubText(plain(e.data?.description), THEMES_MAX.answer, names);
60
+ return scrubText([title && !/[.!?]$/.test(title) ? `${title}.` : title, body].filter(Boolean).join(' '), THEMES_MAX.answer);
61
+ })
62
+ .filter(Boolean)
63
+ .slice(0, THEMES_MAX.answers);
64
+ }
65
+
66
+ /** The filter in a few words, for Claude and for the card: never a site's name, nor the search's words. */
67
+ export function filterText(filter = cleanFilter()) {
68
+ const what = filter.status === 'all' ? 'Every report'
69
+ : filter.status === 'open' ? 'Open reports (not done or not planned)'
70
+ : `Reports marked ${statusLabel(filter.status)}`;
71
+ return [what,
72
+ filter.type && `${typeLabel(filter.type)} only`,
73
+ filter.site && 'from one site',
74
+ filter.q && 'matching a search'].filter(Boolean).join(', ');
75
+ }
@@ -25,6 +25,9 @@
25
25
  * GET /reports/:id/attachments/:att a report's file
26
26
  * GET /waypoint is Waypoint Pro here, and its projects
27
27
  * POST /reports/:id/promote make a Waypoint issue from a report
28
+ * POST /themes "Summarise": the reports in the inbox's current view, grouped into
29
+ * themes by Claude through AI Assist (the Manager's own service, in
30
+ * this process; only when AI Assist is on). The latest is kept.
28
31
  *
29
32
  * Nothing the browser sends says who sent a report or which site it came from:
30
33
  * the user is the session's, the site is the one the fleet token names.
@@ -39,6 +42,8 @@ import {
39
42
  } from './lib/shape.js';
40
43
  import {createStore, readUpload, sendFile} from './lib/attachments.js';
41
44
  import {createOutbox, flush, managerApi, managerOf, mergeReports, newRef} from './lib/sender.js';
45
+ import {aiFailure, aiTextAvailable, cleanThemes, createKept, requestAiText} from './lib/ai-text.js';
46
+ import {THEMES_MAX, THEMES_SURVEY, cleanFilter, filterText, reportsInView, themesAnswers} from './lib/themes.js';
42
47
  import {getEffectiveLevel} from '../../server/services/userRoles.js';
43
48
  import {getPluginSettings, getPluginStates, savePluginState} from '../../server/services/plugins.js';
44
49
 
@@ -247,6 +252,7 @@ async function receiverRoutes(fastify, {can, authenticate, requirePermission, ho
247
252
  const rx = receiverMod;
248
253
  const slugOf = options.slugFromToken || rx.slugFromToken;
249
254
  const siteNames = options.siteNames || rx.siteNames;
255
+ const siteHosts = options.siteHosts || rx.siteHosts;
250
256
  // The manager's own reports are filed as `_manager` - a slug no site can have (theirs start [a-z0-9]).
251
257
  const names = () => ({...siteNames(), [rx.MANAGER_SITE]: rx.MANAGER_NAME});
252
258
  // Its own feedback: the level-0 role only, on top of the `feedback` send permission.
@@ -256,6 +262,8 @@ async function receiverRoutes(fastify, {can, authenticate, requirePermission, ho
256
262
  const own = {preHandler: [authenticate, requirePermission('feedback', 'send'), topOnly]};
257
263
  const dataDir = options.dataDir || path.join(HERE, 'data');
258
264
  const ownSeen = createOutbox(dataDir, 'own.json');
265
+ // The latest "Summarise" result (AI Assist), shown again until the next one.
266
+ const kept = createKept(path.join(dataDir, 'ai.json'));
259
267
  // The per-site brakes take their limits at each call (the cog changes them live).
260
268
  const reportThrottle = createThrottle();
261
269
  const fileThrottle = createThrottle();
@@ -332,7 +340,9 @@ async function receiverRoutes(fastify, {can, authenticate, requirePermission, ho
332
340
 
333
341
  // ---- The inbox ----
334
342
 
335
- fastify.get('/mode', can('manage'), async (request) => ({mode: 'receiver', waypoint: Boolean(waypoint()), canSend: isTopLevel(request.user)}));
343
+ // `ai`: whether "Summarise" is offered (AI Assist on, and the Manager's AI Assist service here).
344
+ fastify.get('/mode', can('manage'), async (request) => ({mode: 'receiver', waypoint: Boolean(waypoint()), canSend: isTopLevel(request.user),
345
+ ai: aiTextAvailable('themes')}));
336
346
 
337
347
  fastify.get('/count', can('manage'), async (request) => {
338
348
  const all = await rx.allReports();
@@ -415,8 +425,33 @@ async function receiverRoutes(fastify, {can, authenticate, requirePermission, ho
415
425
 
416
426
  fastify.get('/reports', can('manage'), async () => {
417
427
  const n = names();
428
+ const last = kept.get('themes');
418
429
  return {sites: n, reports: (await rx.allReports()).map(e => ({id: e.id, ...e.data, siteName: n[e.data.site] || e.data.site,
419
- createdAt: e.meta?.createdAt, updatedAt: e.meta?.updatedAt}))};
430
+ createdAt: e.meta?.createdAt, updatedAt: e.meta?.updatedAt})), themes: last ? cleanThemes(last) : null};
431
+ });
432
+
433
+ /**
434
+ * "Summarise" (AI Assist): the reports the inbox shows for {status, type, site, q} - its filter as it
435
+ * stands - grouped into themes by Claude. Only their titles and descriptions go, cleaned (lib/themes.js):
436
+ * no site names, people's names, emails or files. The result is kept (data/ai.json) until the next.
437
+ */
438
+ fastify.post('/themes', can('manage'), async (request, reply) => {
439
+ if (!aiTextAvailable('themes')) return reply.code(403).send({error: 'Summaries come with AI Assist, in the Pro plan.'});
440
+ const filter = cleanFilter(request.body || {});
441
+ const n = names();
442
+ const shown = reportsInView(await rx.allReports(), filter, n);
443
+ const answers = themesAnswers(shown, n, siteHosts());
444
+ if (answers.length < 2) return reply.code(400).send({error: 'There need to be at least two reports to summarise.'});
445
+ const question = filterText(filter);
446
+ const res = await requestAiText({task: 'themes', kind: 'feedback', survey: THEMES_SURVEY, question, answers});
447
+ const failed = aiFailure(res, 'Claude would not summarise these reports.');
448
+ if (failed) return reply.code(failed.status).send(failed.body);
449
+ const result = cleanThemes({at: new Date().toISOString(), filter: question, answers: res.body.answers ?? answers.length,
450
+ summary: res.body.summary, themes: res.body.themes});
451
+ // Which reports it read (never shown): deleting one of them drops the summary, which may quote it.
452
+ try { kept.set('themes', {...result, ids: shown.slice(0, THEMES_MAX.answers).map(e => e.id)}); }
453
+ catch (err) { fastify.log.warn(`[feedback] summary not kept: ${err.message}`); }
454
+ return {...result, used: res.body.used, limit: res.body.limit};
420
455
  });
421
456
 
422
457
  fastify.get('/reports/:id', can('manage'), async (request, reply) => {
@@ -459,6 +494,8 @@ async function receiverRoutes(fastify, {can, authenticate, requirePermission, ho
459
494
  if (!e) return reply.code(404).send({error: 'No such report.'});
460
495
  await rx.removeReport(e.id);
461
496
  files.removeAll(e.id);
497
+ // A kept summary that read this report may quote it: it goes too.
498
+ try { if ((kept.get('themes')?.ids || []).includes(e.id)) kept.remove('themes'); } catch { /* tidying only */ }
462
499
  return {ok: true};
463
500
  });
464
501
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "feedback",
3
3
  "displayName": "Feedback",
4
- "version": "1.3.0",
4
+ "version": "1.4.0",
5
5
  "minCmsVersion": "1.67.2",
6
6
  "tier": "free",
7
7
  "description": "Tell Domma what is broken, missing or good - straight from your admin - and see what became of it: seen, planned, in progress, done, with Domma's reply.",
@@ -41,7 +41,7 @@
41
41
  ],
42
42
  "views": {
43
43
  "plugin-feedback": {
44
- "entry": "feedback/admin/views/feedback.js?v=1.3.0",
44
+ "entry": "feedback/admin/views/feedback.js?v=1.4.0",
45
45
  "exportName": "feedbackView"
46
46
  }
47
47
  }