@prenta/admin 2.8.0 → 2.9.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 (81) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/AdminRoot.d.ts.map +1 -1
  3. package/dist/AdminRoot.js +6 -6
  4. package/dist/AdminRoot.js.map +1 -1
  5. package/dist/__tests__/components/batch-ai-actions.test.js +4 -0
  6. package/dist/__tests__/components/batch-ai-actions.test.js.map +1 -1
  7. package/dist/__tests__/lib/batch-wizard.test.js +85 -1
  8. package/dist/__tests__/lib/batch-wizard.test.js.map +1 -1
  9. package/dist/__tests__/lib/jobs-service.test.js +19 -1
  10. package/dist/__tests__/lib/jobs-service.test.js.map +1 -1
  11. package/dist/__tests__/views/run-with-ai.render.test.d.ts +2 -0
  12. package/dist/__tests__/views/run-with-ai.render.test.d.ts.map +1 -0
  13. package/dist/__tests__/views/run-with-ai.render.test.js +711 -0
  14. package/dist/__tests__/views/run-with-ai.render.test.js.map +1 -0
  15. package/dist/components/BatchAiActions.d.ts +8 -1
  16. package/dist/components/BatchAiActions.d.ts.map +1 -1
  17. package/dist/components/BatchAiActions.js +3 -2
  18. package/dist/components/BatchAiActions.js.map +1 -1
  19. package/dist/lib/batch-wizard.d.ts +34 -0
  20. package/dist/lib/batch-wizard.d.ts.map +1 -1
  21. package/dist/lib/batch-wizard.js +97 -0
  22. package/dist/lib/batch-wizard.js.map +1 -1
  23. package/dist/lib/jobs-service.d.ts +28 -0
  24. package/dist/lib/jobs-service.d.ts.map +1 -1
  25. package/dist/lib/jobs-service.js +9 -0
  26. package/dist/lib/jobs-service.js.map +1 -1
  27. package/dist/prenta-admin.css +1 -1
  28. package/dist/views/CollectionList.d.ts +3 -1
  29. package/dist/views/CollectionList.d.ts.map +1 -1
  30. package/dist/views/CollectionList.js +5 -2
  31. package/dist/views/CollectionList.js.map +1 -1
  32. package/dist/views/Jobs/DrawerOverview.d.ts +6 -2
  33. package/dist/views/Jobs/DrawerOverview.d.ts.map +1 -1
  34. package/dist/views/Jobs/DrawerOverview.js +6 -3
  35. package/dist/views/Jobs/DrawerOverview.js.map +1 -1
  36. package/dist/views/Jobs/DrawerResults.d.ts +13 -3
  37. package/dist/views/Jobs/DrawerResults.d.ts.map +1 -1
  38. package/dist/views/Jobs/DrawerResults.js +37 -3
  39. package/dist/views/Jobs/DrawerResults.js.map +1 -1
  40. package/dist/views/Jobs/JobDrawer.d.ts +4 -1
  41. package/dist/views/Jobs/JobDrawer.d.ts.map +1 -1
  42. package/dist/views/Jobs/JobDrawer.js +2 -2
  43. package/dist/views/Jobs/JobDrawer.js.map +1 -1
  44. package/dist/views/Jobs/RunWithAi.d.ts +25 -0
  45. package/dist/views/Jobs/RunWithAi.d.ts.map +1 -0
  46. package/dist/views/Jobs/RunWithAi.js +46 -0
  47. package/dist/views/Jobs/RunWithAi.js.map +1 -0
  48. package/dist/views/Jobs.d.ts +3 -1
  49. package/dist/views/Jobs.d.ts.map +1 -1
  50. package/dist/views/Jobs.js +42 -8
  51. package/dist/views/Jobs.js.map +1 -1
  52. package/dist/views/MediaBrowser.d.ts +5 -1
  53. package/dist/views/MediaBrowser.d.ts.map +1 -1
  54. package/dist/views/MediaBrowser.js +6 -2
  55. package/dist/views/MediaBrowser.js.map +1 -1
  56. package/dist/views/Pages/PagesListView.d.ts +5 -1
  57. package/dist/views/Pages/PagesListView.d.ts.map +1 -1
  58. package/dist/views/Pages/PagesListView.js +7 -4
  59. package/dist/views/Pages/PagesListView.js.map +1 -1
  60. package/dist/views/Posts/PostsListView.d.ts +5 -1
  61. package/dist/views/Posts/PostsListView.d.ts.map +1 -1
  62. package/dist/views/Posts/PostsListView.js +7 -4
  63. package/dist/views/Posts/PostsListView.js.map +1 -1
  64. package/package.json +3 -3
  65. package/src/AdminRoot.tsx +20 -4
  66. package/src/__tests__/components/batch-ai-actions.test.tsx +10 -0
  67. package/src/__tests__/lib/batch-wizard.test.ts +129 -0
  68. package/src/__tests__/lib/jobs-service.test.ts +20 -0
  69. package/src/__tests__/views/run-with-ai.render.test.tsx +832 -0
  70. package/src/components/BatchAiActions.tsx +15 -2
  71. package/src/lib/batch-wizard.ts +128 -0
  72. package/src/lib/jobs-service.ts +35 -0
  73. package/src/views/CollectionList.tsx +20 -1
  74. package/src/views/Jobs/DrawerOverview.tsx +16 -3
  75. package/src/views/Jobs/DrawerResults.tsx +71 -2
  76. package/src/views/Jobs/JobDrawer.tsx +5 -1
  77. package/src/views/Jobs/RunWithAi.tsx +89 -0
  78. package/src/views/Jobs.tsx +58 -10
  79. package/src/views/MediaBrowser.tsx +20 -1
  80. package/src/views/Pages/PagesListView.tsx +28 -3
  81. package/src/views/Posts/PostsListView.tsx +26 -3
@@ -13,17 +13,30 @@ const LABELS: Record<BatchOperation, string> = {
13
13
  summarize: 'Summaries',
14
14
  }
15
15
 
16
+ const ALL_OPERATIONS = Object.keys(LABELS) as BatchOperation[]
17
+
16
18
  interface BatchAiActionsProps {
17
19
  documents: Array<{ collection: string; id: string }>
18
20
  onQueued?: () => void
19
21
  buttonClassName?: string
22
+ /**
23
+ * The buttons to show, all three by default. Posts and Pages keep only
24
+ * Alt text beside "Run with AI…", whose wizard writes meta descriptions and
25
+ * excerpts but not the alt text of images inside a document (P-21).
26
+ */
27
+ operations?: readonly BatchOperation[]
20
28
  }
21
29
 
22
30
  /**
23
31
  * Queues a list-view AI batch after a confirm that names the daily cap.
24
32
  * The server writes field drafts and does not publish.
25
33
  */
26
- export function BatchAiActions({ documents, onQueued, buttonClassName }: BatchAiActionsProps) {
34
+ export function BatchAiActions({
35
+ documents,
36
+ onQueued,
37
+ buttonClassName,
38
+ operations = ALL_OPERATIONS,
39
+ }: BatchAiActionsProps) {
27
40
  const [operation, setOperation] = useState<BatchOperation | null>(null)
28
41
  const [busy, setBusy] = useState(false)
29
42
  const buttonClass =
@@ -51,7 +64,7 @@ export function BatchAiActions({ documents, onQueued, buttonClassName }: BatchAi
51
64
 
52
65
  return (
53
66
  <>
54
- {(Object.keys(LABELS) as BatchOperation[]).map((key) => (
67
+ {operations.map((key) => (
55
68
  <button
56
69
  key={key}
57
70
  type="button"
@@ -11,6 +11,7 @@ import type {
11
11
  BatchAiTextField,
12
12
  } from '@prenta/core'
13
13
  import { JOB_OPS } from './job-view.js'
14
+ import type { SeoBatchTarget } from './jobs-service.js'
14
15
 
15
16
  export type BatchOperation = BatchAiPayload['operation']
16
17
  export type BatchOp = (typeof JOB_OPS)[number]
@@ -35,6 +36,67 @@ export interface BatchSelection {
35
36
  documentIds: string[]
36
37
  }
37
38
 
39
+ /**
40
+ * What a list's "Run with AI…" sends (P-21): the picked documents, or why
41
+ * they can't run as one batch.
42
+ */
43
+ export type ListPick =
44
+ | { selection: BatchSelection; reason: null }
45
+ | { selection: null; reason: string }
46
+
47
+ /**
48
+ * The most picked documents one batch takes. The wizard's estimate sends them
49
+ * in its query string, and a request line much past 16 KB is refused; 400 ids
50
+ * is about 11 KB. Pages' grouped and tree views can select every page, so a
51
+ * pick isn't always page-sized. Fix with AI caps its batches the same way
52
+ * (cms-core `issue-batch-targets.ts`).
53
+ */
54
+ const PICK_MAX = 400
55
+
56
+ function tooMany(count: number, noun: string): ListPick | null {
57
+ if (count <= PICK_MAX) return null
58
+ return {
59
+ selection: null,
60
+ reason: `Run with AI takes at most ${PICK_MAX} ${noun} at a time. Pick fewer.`,
61
+ }
62
+ }
63
+
64
+ /** Posts and pages picked in a list. A batch runs on one collection. */
65
+ export function pickedDocuments(
66
+ picked: ReadonlyArray<{ collection: string; id: string }>,
67
+ ): ListPick {
68
+ const sources = new Set(picked.map((doc) => doc.collection))
69
+ const [source] = sources
70
+ if (sources.size > 1 || !source) {
71
+ return {
72
+ selection: null,
73
+ reason: 'Run with AI works on one post type at a time. Pick posts of a single type.',
74
+ }
75
+ }
76
+ return (
77
+ tooMany(picked.length, 'documents') ?? {
78
+ selection: { source, documentIds: picked.map((doc) => doc.id) },
79
+ reason: null,
80
+ }
81
+ )
82
+ }
83
+
84
+ /** Files picked in the media library. Only images get alt text; the rest are left out. */
85
+ export function pickedImages(imageIds: ReadonlyArray<string>): ListPick {
86
+ if (imageIds.length === 0) {
87
+ return {
88
+ selection: null,
89
+ reason: 'Run with AI writes alt text for images. Pick at least one image.',
90
+ }
91
+ }
92
+ return (
93
+ tooMany(imageIds.length, 'images') ?? {
94
+ selection: { source: MEDIA_SOURCE.id, documentIds: [...imageIds] },
95
+ reason: null,
96
+ }
97
+ )
98
+ }
99
+
38
100
  /** A custom instruction needs more than 8 characters, and at most 2,000. */
39
101
  const INSTRUCTION_MIN = 9
40
102
  export const INSTRUCTION_MAX = 2000
@@ -178,6 +240,72 @@ export function estimateTiles(estimate: BatchAiEstimate): { minutes: string; tok
178
240
  }
179
241
  }
180
242
 
243
+ /**
244
+ * The scan result category "Fix with AI" offers (jobs-drawer.jsx shows one
245
+ * box): the first, so the largest, with documents a batch can fix. Types SEO
246
+ * autopilot fixes on its own are skipped.
247
+ */
248
+ export function fixWithAiPick(
249
+ categories: ReadonlyArray<{ key: string }>,
250
+ targets: ReadonlyArray<SeoBatchTarget>,
251
+ ): SeoBatchTarget | null {
252
+ for (const category of categories) {
253
+ const target = targets.find((t) => t.type === category.key)
254
+ if (target && !target.autopilot && target.sources.length > 0) return target
255
+ }
256
+ return null
257
+ }
258
+
259
+ function plural(n: number, one: string, many = `${one}s`): string {
260
+ return `${n.toLocaleString('en-US')} ${n === 1 ? one : many}`
261
+ }
262
+
263
+ /** "Start a batch job for the 5 missing meta descriptions", per issue type. */
264
+ function fixLead(type: string, n: number): string {
265
+ const are = n === 1 ? 'is' : 'are'
266
+ if (type === 'meta-description-length') {
267
+ return `Start a batch job to shorten the ${plural(n, 'meta description')} that ${are} too long`
268
+ }
269
+ if (type === 'meta-title-length') {
270
+ return `Start a batch job to shorten the ${plural(n, 'SEO title')} that ${are} too long`
271
+ }
272
+ return `Start a batch job for the ${plural(n, 'missing meta description')}`
273
+ }
274
+
275
+ /**
276
+ * The "Fix with AI" box's text. The kit's is "Start a batch job for the 5
277
+ * missing meta descriptions. You’ll review each one before it’s applied.";
278
+ * this adds the content types when there are several (a batch runs on one),
279
+ * the 400 a batch takes at most, and the documents already waiting.
280
+ */
281
+ export function fixWithAiText(target: SeoBatchTarget, labelOf: (source: string) => string): string {
282
+ const total = target.sources.reduce((sum, s) => sum + s.total, 0)
283
+ const parts: string[] = []
284
+ if (target.sources.length > 1) {
285
+ const each = target.sources.map(
286
+ (s) => `${s.total.toLocaleString('en-US')} in ${labelOf(s.source)}`,
287
+ )
288
+ parts.push(
289
+ `${fixLead(target.type, total)}: ${each.slice(0, -1).join(', ')} and ${each[each.length - 1]}. A batch runs on one content type, so there’s one to set up for each.`,
290
+ )
291
+ } else {
292
+ parts.push(`${fixLead(target.type, total)}.`)
293
+ }
294
+ const capped = target.sources.find((s) => s.total > s.documentIds.length)
295
+ if (capped) {
296
+ parts.push(
297
+ `A batch takes ${capped.documentIds.length.toLocaleString('en-US')} at most, so it starts with the most recently found.`,
298
+ )
299
+ }
300
+ if (target.waiting > 0) {
301
+ parts.push(
302
+ `${plural(target.waiting, 'other')} already ${target.waiting === 1 ? 'has' : 'have'} a suggestion waiting.`,
303
+ )
304
+ }
305
+ parts.push('You’ll review each one before it’s applied.')
306
+ return parts.join(' ')
307
+ }
308
+
181
309
  /** The line under the tiles. The limit sentence is left out when Settings → AI sets none. */
182
310
  export function estimateNote(estimate: BatchAiEstimate): string {
183
311
  const pace = 'One document per slice, about one a minute.'
@@ -195,6 +195,41 @@ export function createBatchAiJob(request: BatchAiRequest): Promise<JobsOutcome<J
195
195
  return call('/jobs/batch-ai', { method: 'POST', body: JSON.stringify(request) })
196
196
  }
197
197
 
198
+ /** One collection's share of an SEO issue type's documents (cms-core `issue-batch-targets.ts`). */
199
+ interface SeoBatchSource {
200
+ /** A collection key: the batch's `source`. */
201
+ source: string
202
+ /** At most 400, the most recently found first. */
203
+ documentIds: string[]
204
+ /** Every document in this collection, before the cap. */
205
+ total: number
206
+ }
207
+
208
+ /** What "Fix with AI" can start for one SEO issue type. */
209
+ export interface SeoBatchTarget {
210
+ /** The issue type, as a scan result category's `key`. */
211
+ type: string
212
+ operation: 'meta' | 'titles'
213
+ /** SEO autopilot fixes this type on its own, so there are no sources. */
214
+ autopilot: boolean
215
+ /** The largest first. */
216
+ sources: SeoBatchSource[]
217
+ /** Documents left out because a suggestion for them is already waiting. */
218
+ waiting: number
219
+ }
220
+
221
+ /**
222
+ * `GET /seo/issues/batch-targets`: for each SEO issue type a batch can fix,
223
+ * the open issues' documents by collection, without those SEO autopilot or
224
+ * another suggestion already covers (CONFLICTS.md §4, P-21).
225
+ */
226
+ export async function listSeoBatchTargets(
227
+ signal?: AbortSignal,
228
+ ): Promise<JobsOutcome<SeoBatchTarget[]>> {
229
+ const res = await call<{ targets?: SeoBatchTarget[] }>('/seo/issues/batch-targets', { signal })
230
+ return res.ok ? { ok: true, value: res.value.targets ?? [] } : res
231
+ }
232
+
198
233
  function jobPath(id: string): string {
199
234
  return `/jobs/${encodeURIComponent(id)}`
200
235
  }
@@ -14,6 +14,7 @@ import { useState, useMemo, useCallback, useEffect, useRef } from 'react'
14
14
  import { toast } from 'sonner'
15
15
  import { BatchAiActions } from '../components/BatchAiActions.js'
16
16
  import { cmsApi } from '../lib/api.js'
17
+ import { pickedDocuments } from '../lib/batch-wizard.js'
17
18
  import { useApiData } from '../lib/useApiData.js'
18
19
  import { useVirtualWindow, VirtualTablePadding } from '../components/virtual-window.js'
19
20
  import { editPathForDoc, newPathForCollection } from '../lib/collection-routes.js'
@@ -28,11 +29,14 @@ import {
28
29
  import { TIER_MEDIA, useMediaQuery } from '../lib/tiers.js'
29
30
  import { CardListControls, type CardSortOption } from '../components/ui/CardListControls.js'
30
31
  import { EntryDetailPane } from '../components/collections/EntryDetailPane.js'
32
+ import { RunWithAi } from './Jobs/RunWithAi.js'
31
33
 
32
34
  export interface CollectionListProps {
33
35
  collectionSlug: string
34
36
  config: any
35
37
  onNavigate: (path: string) => void
38
+ /** The signed-in user's role: "Run with AI…" shows to the roles that may queue jobs. */
39
+ role?: string | null
36
40
  }
37
41
 
38
42
  type SortField = 'title' | 'status' | 'updatedAt'
@@ -200,7 +204,7 @@ function formatDate(d: string | undefined): string {
200
204
  })
201
205
  }
202
206
 
203
- export function CollectionList({ collectionSlug, config, onNavigate }: CollectionListProps) {
207
+ export function CollectionList({ collectionSlug, config, onNavigate, role }: CollectionListProps) {
204
208
  const labels = useMemo(() => resolveLabel(config, collectionSlug), [config, collectionSlug])
205
209
  const facets = useMemo(() => facetFieldsFor(config, collectionSlug), [config, collectionSlug])
206
210
  // Post-type and Pages collections open in dedicated editors — never the
@@ -210,6 +214,7 @@ export function CollectionList({ collectionSlug, config, onNavigate }: Collectio
210
214
  () => resolveCollection(config, collectionSlug),
211
215
  [config, collectionSlug],
212
216
  )
217
+ const runsBatchAi = collectionDef?.type === 'page' || collectionDef?.type === 'post'
213
218
  const editPath = useCallback(
214
219
  (id: string | number) => editPathForDoc(collectionDef, collectionSlug, String(id)),
215
220
  [collectionDef, collectionSlug],
@@ -515,10 +520,24 @@ export function CollectionList({ collectionSlug, config, onNavigate }: Collectio
515
520
  >
516
521
  Unpublish
517
522
  </button>
523
+ {/* The batch wizard runs on page and post collections (P-21). Like
524
+ Posts and Pages, they keep only Alt text of the old buttons. */}
525
+ {runsBatchAi ? (
526
+ <RunWithAi
527
+ pick={pickedDocuments(
528
+ [...selected].map((id) => ({ collection: collectionSlug, id })),
529
+ )}
530
+ role={role}
531
+ config={config}
532
+ onNavigate={onNavigate}
533
+ className="rounded-lg px-3 py-1.5 text-sm"
534
+ />
535
+ ) : null}
518
536
  <BatchAiActions
519
537
  documents={[...selected].map((id) => ({ collection: collectionSlug, id }))}
520
538
  onQueued={() => setSelected(new Set())}
521
539
  buttonClassName="rounded-lg px-3 py-1.5 text-sm"
540
+ operations={runsBatchAi ? ['alt-text'] : undefined}
522
541
  />
523
542
  <button
524
543
  onClick={() => bulkAction('delete')}
@@ -16,10 +16,23 @@ export function DrawerSection({ children }: { children: ReactNode }) {
16
16
  )
17
17
  }
18
18
 
19
- /** `.jd-ai`: an AI note ("What happened", "AI summary") on the accent tint. */
20
- export function AiNote({ label, children }: { label: string; children: ReactNode }) {
19
+ /**
20
+ * `.jd-ai`: an AI note ("What happened", "AI summary") on the accent tint, or
21
+ * on `--bg` (`plain`) for the results' "Fix with AI".
22
+ */
23
+ export function AiNote({
24
+ label,
25
+ plain,
26
+ children,
27
+ }: {
28
+ label: string
29
+ plain?: boolean
30
+ children: ReactNode
31
+ }) {
21
32
  return (
22
- <div className="rounded-10 bg-acc-l text-body text-txt flex gap-2.5 px-3.5 py-3 leading-[1.55]">
33
+ <div
34
+ className={`rounded-10 text-body text-txt flex gap-2.5 px-3.5 py-3 leading-[1.55] ${plain ? 'bg-bg' : 'bg-acc-l'}`}
35
+ >
23
36
  <span className="text-acc mt-0.5 flex shrink-0">
24
37
  <JobIcons.spark size={15} />
25
38
  </span>
@@ -1,9 +1,18 @@
1
1
  'use client'
2
2
 
3
- import type { MouseEvent, ReactNode } from 'react'
3
+ import { useEffect, useState, type MouseEvent, type ReactNode } from 'react'
4
4
  import type { ScanResults } from '@prenta/core'
5
+ import { Button } from '../../components/ui/Button.js'
5
6
  import { useAdminLinks } from '../../components/ui/admin-links.js'
7
+ import {
8
+ fixWithAiPick,
9
+ fixWithAiText,
10
+ type BatchOperation,
11
+ type BatchSelection,
12
+ type BatchSource,
13
+ } from '../../lib/batch-wizard.js'
6
14
  import { formatCreated } from '../../lib/job-view.js'
15
+ import { listSeoBatchTargets, type SeoBatchTarget } from '../../lib/jobs-service.js'
7
16
  import { AiNote, DrawerSection } from './DrawerOverview.js'
8
17
  import { JobIcons } from './icons.js'
9
18
 
@@ -30,6 +39,61 @@ function plainClick(event: MouseEvent) {
30
39
  return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey
31
40
  }
32
41
 
42
+ export interface FixWithAiProps {
43
+ /** The config's page and post collections, to name a batch's content type. */
44
+ sources: BatchSource[]
45
+ /** Open the wizard with an issue's documents, at step 1 on its operation. */
46
+ onFix: (selection: BatchSelection, operation: BatchOperation) => void
47
+ }
48
+
49
+ /**
50
+ * jobs-drawer.jsx's "Fix with AI" box, after the digest line: a batch job for
51
+ * the largest kind of open issue a batch can fix, with its documents picked.
52
+ * The documents come from `GET /seo/issues/batch-targets` each time Results
53
+ * opens, so the box follows what's still open (the scan's counts are frozen),
54
+ * and leaves out what SEO autopilot or another suggestion already covers.
55
+ * Nothing shows while they load, or when nothing is left to fix.
56
+ */
57
+ function FixWithAi({
58
+ categories,
59
+ sources,
60
+ onFix,
61
+ }: FixWithAiProps & { categories: ScanResults['categories'] }) {
62
+ const [targets, setTargets] = useState<SeoBatchTarget[] | null>(null)
63
+ useEffect(() => {
64
+ const controller = new AbortController()
65
+ void listSeoBatchTargets(controller.signal).then((res) => {
66
+ if (!controller.signal.aborted && res.ok) setTargets(res.value)
67
+ })
68
+ return () => controller.abort()
69
+ }, [])
70
+ const target = targets ? fixWithAiPick(categories, targets) : null
71
+ if (!target) return null
72
+ const labelOf = (id: string) => sources.find((s) => s.id === id)?.label ?? id
73
+ const several = target.sources.length > 1
74
+ return (
75
+ <AiNote label="Fix with AI" plain>
76
+ <span data-fix-with-ai="">{fixWithAiText(target, labelOf)}</span>
77
+ <div className="mt-2 flex flex-wrap gap-2">
78
+ {target.sources.map((s) => (
79
+ <Button
80
+ key={s.source}
81
+ size="sm"
82
+ aria-haspopup="dialog"
83
+ onClick={(event) => {
84
+ // Safari doesn't focus a clicked button; the wizard returns focus here.
85
+ event.currentTarget.focus()
86
+ onFix({ source: s.source, documentIds: s.documentIds }, target.operation)
87
+ }}
88
+ >
89
+ {several ? `Set up batch job for ${labelOf(s.source)}` : 'Set up batch job'}
90
+ </Button>
91
+ ))}
92
+ </div>
93
+ </AiNote>
94
+ )
95
+ }
96
+
33
97
  export interface DrawerResultsProps {
34
98
  type: string
35
99
  results: ScanResults | undefined
@@ -41,12 +105,15 @@ export interface DrawerResultsProps {
41
105
  scanned: number
42
106
  now: number
43
107
  onNavigate: (path: string) => void
108
+ /** An SEO scan's "Fix with AI", for roles that may queue jobs. */
109
+ fixWithAi?: FixWithAiProps
44
110
  }
45
111
 
46
112
  /**
47
113
  * jobs-drawer.jsx Results, for SEO scans and content health checks: three
48
114
  * key numbers, the AI summary, the open issues by kind (each linking to the
49
- * screen that fixes it) and whether the SEO digest went out.
115
+ * screen that fixes it), whether the SEO digest went out and, for an SEO
116
+ * scan, "Fix with AI".
50
117
  */
51
118
  export function DrawerResults({
52
119
  type,
@@ -57,6 +124,7 @@ export function DrawerResults({
57
124
  scanned,
58
125
  now,
59
126
  onNavigate,
127
+ fixWithAi,
60
128
  }: DrawerResultsProps) {
61
129
  const links = useAdminLinks()
62
130
  if (!results) {
@@ -150,6 +218,7 @@ export function DrawerResults({
150
218
  </span>
151
219
  </p>
152
220
  ) : null}
221
+ {seo && fixWithAi ? <FixWithAi categories={results.categories} {...fixWithAi} /> : null}
153
222
  </>
154
223
  )
155
224
  }
@@ -27,7 +27,7 @@ import { Pill, TypeTile } from './atoms.js'
27
27
  import { BusyButton } from './BusyButton.js'
28
28
  import { DrawerActivity } from './DrawerActivity.js'
29
29
  import { DrawerOverview } from './DrawerOverview.js'
30
- import { DrawerResults } from './DrawerResults.js'
30
+ import { DrawerResults, type FixWithAiProps } from './DrawerResults.js'
31
31
  import { DrawerReview, type ReviewItemState } from './DrawerReview.js'
32
32
  import { focusJobDrawer, focusJobRow, useReturnFocus } from './focus.js'
33
33
  import { JobIcons } from './icons.js'
@@ -105,6 +105,8 @@ export interface JobDrawerProps {
105
105
  /** Read the list again: a decision changes the job's review counts. */
106
106
  onReload: () => void
107
107
  onNavigate: (path: string) => void
108
+ /** An SEO scan's "Fix with AI" (P-21), for roles that may queue jobs. */
109
+ fixWithAi?: FixWithAiProps
108
110
  }
109
111
 
110
112
  function without<T>(record: Record<string, T>, key: string): Record<string, T> {
@@ -149,6 +151,7 @@ export function JobDrawer({
149
151
  onClose,
150
152
  onReload,
151
153
  onNavigate,
154
+ fixWithAi,
152
155
  }: JobDrawerProps) {
153
156
  const batch = job.type === 'batch-ai'
154
157
  const counts = job.review ?? NO_COUNTS
@@ -543,6 +546,7 @@ export function JobDrawer({
543
546
  scanned={row.total}
544
547
  now={now}
545
548
  onNavigate={onNavigate}
549
+ fixWithAi={fixWithAi}
546
550
  />
547
551
  ) : null}
548
552
  {shown === 'activity' ? (
@@ -0,0 +1,89 @@
1
+ 'use client'
2
+
3
+ import { useId, useState } from 'react'
4
+ import { toast } from 'sonner'
5
+ import type { Job } from '@prenta/core'
6
+ import { MEDIA_SOURCE, type ListPick } from '../../lib/batch-wizard.js'
7
+ import { canActOnJobs, jobTotal } from '../../lib/job-view.js'
8
+ import { JobIcons } from './icons.js'
9
+ import { NewBatchJob } from './NewBatchJob.js'
10
+
11
+ export interface RunWithAiProps {
12
+ /** The picked documents, or why they can't run as one batch. */
13
+ pick: ListPick
14
+ /** The signed-in user's role: the roles that may queue jobs see the button. */
15
+ role?: string | null
16
+ /** The CMS config, for the wizard's content labels. */
17
+ config?: unknown
18
+ onNavigate: (path: string) => void
19
+ /** The bulk bar's own button style. */
20
+ className?: string
21
+ }
22
+
23
+ /** The toast after queuing: what was queued, and a way to the job in Jobs. */
24
+ function queuedToast(job: Job, onNavigate: (path: string) => void): void {
25
+ toast(`“${job.title}” queued · ${jobTotal(job)} documents`, {
26
+ action: {
27
+ label: 'View job',
28
+ onClick: () => onNavigate(`/jobs?job=${encodeURIComponent(job.id)}`),
29
+ },
30
+ })
31
+ }
32
+
33
+ /**
34
+ * A list's "Run with AI…" (TRACKING P-21): opens the New batch AI job wizard
35
+ * at step 1 with the picked documents, so step 2 shows "{n} selected". Picked
36
+ * images start on alt text. Only roles that may queue jobs see it, as for
37
+ * Jobs' New batch AI job (`canActOnJobs`).
38
+ *
39
+ * After queuing, the list keeps its selection, so another change can run on
40
+ * the same documents, and focus returns here. The toast links to the job.
41
+ * When the pick can't run as one batch (posts of two types, no images), the
42
+ * button stays focusable and says why.
43
+ */
44
+ export function RunWithAi({ pick, role = null, config, onNavigate, className }: RunWithAiProps) {
45
+ const [open, setOpen] = useState(false)
46
+ const reasonId = useId()
47
+ if (!canActOnJobs({ role, userId: null })) return null
48
+ const { selection, reason } = pick
49
+ return (
50
+ <>
51
+ <button
52
+ type="button"
53
+ data-run-with-ai=""
54
+ aria-haspopup="dialog"
55
+ aria-disabled={reason ? true : undefined}
56
+ aria-describedby={reason ? reasonId : undefined}
57
+ title={reason ?? undefined}
58
+ onClick={(event) => {
59
+ // Safari doesn't focus a clicked button, and the wizard returns
60
+ // focus to whatever had it when it opened.
61
+ event.currentTarget.focus()
62
+ if (selection) setOpen(true)
63
+ }}
64
+ className={`inline-flex items-center gap-1.5 aria-disabled:cursor-not-allowed aria-disabled:opacity-50 ${className ?? ''}`}
65
+ >
66
+ <JobIcons.spark size={13} />
67
+ Run with AI…
68
+ </button>
69
+ {reason ? (
70
+ <span id={reasonId} hidden>
71
+ {reason}
72
+ </span>
73
+ ) : null}
74
+ {open && selection ? (
75
+ <NewBatchJob
76
+ role={role}
77
+ config={config}
78
+ selection={selection}
79
+ operation={selection.source === MEDIA_SOURCE.id ? 'alt' : undefined}
80
+ onClose={() => setOpen(false)}
81
+ onQueued={(job) => {
82
+ setOpen(false)
83
+ queuedToast(job, onNavigate)
84
+ }}
85
+ />
86
+ ) : null}
87
+ </>
88
+ )
89
+ }