@aglyn/plugins-ai 1.0.0-beta.293 → 1.0.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.
Files changed (64) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-job-links.d.ts +17 -3
  3. package/src/lib/components/ai-job-links.js +32 -5
  4. package/src/lib/components/ai-job-links.js.map +1 -1
  5. package/src/lib/components/ai-job-requests.d.ts +9 -0
  6. package/src/lib/components/ai-job-requests.js +34 -0
  7. package/src/lib/components/ai-job-requests.js.map +1 -1
  8. package/src/lib/components/ai-site-build-page.component.js +28 -2
  9. package/src/lib/components/ai-site-build-page.component.js.map +1 -1
  10. package/src/lib/components/assist-edit-canvas.d.ts +12 -6
  11. package/src/lib/components/assist-edit-canvas.js +86 -36
  12. package/src/lib/components/assist-edit-canvas.js.map +1 -1
  13. package/src/lib/components/assist-edit-card.component.js +9 -8
  14. package/src/lib/components/assist-edit-card.component.js.map +1 -1
  15. package/src/lib/components/assist-jobs-drawer.component.d.ts +7 -1
  16. package/src/lib/components/assist-jobs-drawer.component.js +20 -6
  17. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  18. package/src/lib/components/assist-page-change-card.component.d.ts +44 -0
  19. package/src/lib/components/assist-page-change-card.component.js +166 -0
  20. package/src/lib/components/assist-page-change-card.component.js.map +1 -0
  21. package/src/lib/components/assist-panel.component.d.ts +105 -1
  22. package/src/lib/components/assist-panel.component.js +242 -36
  23. package/src/lib/components/assist-panel.component.js.map +1 -1
  24. package/src/lib/jobs/ai-job-edit-step.d.ts +82 -16
  25. package/src/lib/jobs/ai-job-edit-step.js +209 -62
  26. package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
  27. package/src/lib/jobs/ai-job-navigation-step.js +4 -2
  28. package/src/lib/jobs/ai-job-navigation-step.js.map +1 -1
  29. package/src/lib/model/ai-edit-job.d.ts +33 -16
  30. package/src/lib/model/ai-edit-job.js +50 -34
  31. package/src/lib/model/ai-edit-job.js.map +1 -1
  32. package/src/lib/model/ai-job-activity.d.ts +6 -11
  33. package/src/lib/model/ai-job-activity.js +8 -15
  34. package/src/lib/model/ai-job-activity.js.map +1 -1
  35. package/src/lib/model/ai-job-notice.js +3 -1
  36. package/src/lib/model/ai-job-notice.js.map +1 -1
  37. package/src/lib/model/ai-jobs.types.d.ts +6 -0
  38. package/src/lib/model/ai-jobs.types.js.map +1 -1
  39. package/src/lib/model/ai-site-inventory.d.ts +6 -0
  40. package/src/lib/model/ai-site-inventory.js.map +1 -1
  41. package/src/lib/model/assist-edit.d.ts +19 -1
  42. package/src/lib/model/assist-edit.js +7 -0
  43. package/src/lib/model/assist-edit.js.map +1 -1
  44. package/src/lib/model/assist-page-change.d.ts +100 -0
  45. package/src/lib/model/assist-page-change.js +107 -0
  46. package/src/lib/model/assist-page-change.js.map +1 -0
  47. package/src/lib/runtime/ai-eval.js +3 -1
  48. package/src/lib/runtime/ai-eval.js.map +1 -1
  49. package/src/lib/runtime/ai-node-tree.d.ts +5 -0
  50. package/src/lib/runtime/ai-node-tree.js +18 -3
  51. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  52. package/src/lib/runtime/site-inventory.d.ts +8 -1
  53. package/src/lib/runtime/site-inventory.js +18 -0
  54. package/src/lib/runtime/site-inventory.js.map +1 -1
  55. package/src/lib/server/assist-build.js +2 -0
  56. package/src/lib/server/assist-build.js.map +1 -1
  57. package/src/lib/server/assist-chat.js +56 -3
  58. package/src/lib/server/assist-chat.js.map +1 -1
  59. package/src/lib/server/assist-edit.d.ts +61 -4
  60. package/src/lib/server/assist-edit.js +248 -38
  61. package/src/lib/server/assist-edit.js.map +1 -1
  62. package/src/lib/server/assist-page-change.d.ts +62 -0
  63. package/src/lib/server/assist-page-change.js +140 -0
  64. package/src/lib/server/assist-page-change.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/assist-jobs-drawer.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkEntitlement } from '@aglyn/aglyn'\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport { formatBytes } from '@aglyn/aglyn/app-utils/measure-node-map'\nimport {\n AI_JOB_TERMINAL_STATUSES,\n type AiJobOutput,\n type AiJobSummary,\n} from '../model/ai-jobs.types'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { mdiChevronDown, mdiChevronUp } from '@aglyn/shared-data-mdi'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { AppLink, HelpTip, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n Box,\n Button,\n Chip,\n CircularProgress,\n Collapse,\n IconButton,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport {\n AI_JOB_PHASE_LABELS,\n aiJobActivityCounts,\n aiJobPhase,\n aiJobsHeaderChips,\n type AiJobActivityState,\n type AiJobPhase,\n} from '../model/ai-job-activity'\nimport type { AiInsightSurface } from '../model/ai-insight'\nimport { AiJobInputForm } from './ai-job-input-form.component'\nimport { resumeAiJobRequest, type AiJobResumeOptions } from './ai-job-requests'\nimport { useAiJobCancel } from './ai-job-cancel.component'\nimport { aiBuildCanRetry, aiBuildItemRows, aiBuildRetryCreditRange, aiSitePartialCopy } from '../model/ai-build-progress'\nimport { aiCreditRangeText, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { AiCreditsPromptNotice } from './ai-credits-prompt.component'\nimport { publishAiJob, type AiJobsOpenRequest } from './ai-jobs-store'\nimport { AiPageBriefDialog } from './ai-page-brief-dialog.component'\nimport { AiInsightDialog } from './ai-insight-dialog.component'\nimport { AiJobPlan } from './ai-job-plan.component'\nimport { aiCreditsBillingHref, aiJobOutputHref, aiJobPrimaryLink, aiSiteBuildHref } from './ai-job-links'\nimport { aiJobRefundCopy } from '../model/ai-job-failure-copy'\nimport {\n AI_SITE_REMOVED_ROW_COPY,\n AI_SITE_START_AGAIN_LABEL,\n aiCreateSiteHref,\n stashAiSiteStartAnswers,\n} from '../model/ai-site-start-handoff'\nimport { readEventFrames } from './ai-job-events'\n\n/** Try again, with what it is likely to cost (AGL-3722). */\nfunction aiBuildRetryLabel(job: AiJobSummary): string {\n const range = aiBuildRetryCreditRange(job)\n return range ? `Try again what failed · ${aiCreditRangeText(range)}` : 'Try again what failed'\n}\n\n// Where an output opens, and the stream reader, live beside the dialogs that\n// share them (AGL-3593); this module has always exported them.\nexport { aiJobOutputHref, aiJobPrimaryLink, readEventFrames }\n\n/**\n * The AI jobs drawer inside the Assist panel (AGL-2904): the workspace's\n * running and recent generation jobs, each step's progress, an \"open\n * draft\" link per output, and cancel.\n *\n * Reads through the routes, never Firestore directly, so the same\n * membership, flag and entitlement rungs answer every read; progress comes\n * from the events route's server-sent stream, re-opened when the server\n * says `reconnect`. Everything loads on EXPAND rather than on mount: the\n * panel opens on every console page, and a list nobody asked for is a read\n * on every page view.\n *\n * It opens EXPANDED while any of the workspace's jobs is moving or waiting\n * for the person (AGL-3593) — the shared list the top-bar indicator reads\n * says so — because a plan waiting behind a collapsed row is a site that\n * never gets built. An \"Open AI jobs\" anywhere in the console expands it,\n * scrolls to the job it names and highlights it for a moment.\n *\n * Hidden — not disabled — unless the flag shows it AND the plan carries\n * `aiGenerative`: a released-off feature does not exist, and a plan without\n * it is sold the add-on on the Billing page, not here.\n */\n\n/** Jobs the drawer lists; the route caps higher, the drawer is a glance. */\nconst LIST_LIMIT = 10\n\n/** How much of a brief a row shows. */\nconst BRIEF_PREVIEW_CHARS = 90\n\n/**\n * A row's chip says where the job stands in the words every AI surface uses\n * (AGL-3593): a plan waiting to be confirmed is \"Plan ready\", never \"Running\"\n * and never the machine's `needs_review`.\n */\nconst PHASE_COLOR: Record<AiJobPhase, 'default' | 'primary' | 'success' | 'error' | 'warning'> = {\n queued: 'default',\n planning: 'primary',\n 'plan-ready': 'warning',\n building: 'primary',\n attention: 'warning',\n done: 'success',\n failed: 'error',\n canceled: 'default',\n}\n\n/** The header's count chips, colored as the rows they count. */\nconst STATE_COLOR: Record<AiJobActivityState, 'primary' | 'warning'> = {\n 'needs-you': 'warning',\n attention: 'warning',\n running: 'primary',\n}\n\n/** What each item state reads as in a row (AGL-3616). */\nconst ITEM_STATE_LABELS = {\n done: 'built',\n active: 'building',\n waiting: 'waiting',\n failed: 'failed',\n skipped: 'not built',\n} as const\n\n/** How long a job AI jobs was opened on stays highlighted. */\nconst HIGHLIGHT_MS = 2_500\n\n/**\n * Where a guided start that ended unbuilt is tried again (AGL-3596): its\n * \"Building your site\" page, opened on its own answers (`?retry=1`). Only for\n * a job of the site the console is on, whose subdomain the address names;\n * `null` otherwise.\n */\nexport function aiJobRestartHref(\n job: Pick<AiJobSummary, 'id' | 'kind' | 'status' | 'hostId' | 'siteInputs'>,\n input: { orgSlug: string; hostId?: string | null; pathname: string },\n): string | null {\n if (job.kind !== 'site' || (job.status !== 'failed' && job.status !== 'canceled')) return null\n if (!job.siteInputs || !job.hostId || job.hostId !== input.hostId) return null\n const subdomain = /^\\/[^/]+\\/hosts\\/([^/?#]+)/.exec(input.pathname)?.[1] ?? null\n const href = aiSiteBuildHref(input.orgSlug, subdomain, job.id)\n return href ? `${href}?retry=1` : null\n}\n\n/** What a job cost the person: what it spent, less what we refunded. */\nfunction netCredits(job: Pick<AiJobSummary, 'creditsSpent' | 'refundedCredits'>): number {\n return Math.max(0, (job.creditsSpent ?? 0) - (job.refundedCredits ?? 0))\n}\n\n/**\n * The navigation entry a page job proposes for the page it built (AGL-2907),\n * or `null`. The job writes no menu: the member adds the entry once the page\n * is live.\n */\nexport function aiJobNavigationProposal(output: AiJobOutput): string | null {\n if (output.resource !== 'screen') return null\n const navigation = output.proposal?.['navigation']\n if (!navigation || typeof navigation !== 'object') return null\n const label = (navigation as Record<string, unknown>)['label']\n return typeof label === 'string' && label.trim() ? label.trim() : null\n}\n\n\nexport interface AssistJobsDrawerProps {\n /** The org the panel is scoped to — `undefined` where the page named none. */\n orgId: string | undefined\n org: Partial<AglynOrgBilling> | undefined\n orgReady: boolean\n orgSlug: string\n user: Parameters<typeof authorizedFetch>[0]\n /** The `release_ai_generative` verdict, staff bypass applied (the shell's). */\n visible: boolean\n /**\n * The viewer is staff (AGL-3078): a job that stopped for a broken rule shows\n * them where the refused answer broke it. Who may read a job is unchanged.\n */\n isStaff?: boolean\n /** The site the console page is on, when it is on one: a page is described for a site. */\n hostId?: string | null\n /**\n * The page's insight surface (AGL-2915) — a site's Analytics, Data or CRM\n * Reports page, or the workspace's Data page — with the site's subdomain;\n * `null` elsewhere, where no question about the figures is offered.\n */\n insight?: { surface: Exclude<AiInsightSurface, 'digest'>; host: string | null } | null\n /**\n * The workspace's jobs that are not yet settled, from the shared store the\n * top-bar indicator reads (AGL-3593). The header counts them, and the\n * drawer opens expanded while there is any. Absent, the drawer counts what\n * it loaded itself.\n */\n inFlight?: readonly AiJobSummary[]\n /**\n * The latest request to open AI jobs (AGL-3593): a new `seq` expands the\n * drawer, and a named job is scrolled to and highlighted.\n */\n focus?: AiJobsOpenRequest | null\n}\n\nexport function AssistJobsDrawer({\n orgId,\n org,\n orgReady,\n orgSlug,\n user,\n visible,\n isStaff = false,\n hostId,\n insight,\n inFlight,\n focus,\n}: AssistJobsDrawerProps): JSX.Element | null {\n const entitled = orgReady && checkEntitlement(org as never, 'aiGenerative')\n const [expanded, setExpanded] = useState(false)\n /**\n * The person opened or closed the list themselves: from then on the\n * expanded-by-default rule leaves their choice alone until the workspace\n * changes.\n */\n const toggledRef = useRef(false)\n /** The job AI jobs was opened on, highlighted for a moment once it is listed. */\n const [highlight, setHighlight] = useState<string | null>(null)\n const listRef = useRef<HTMLDivElement | null>(null)\n const [jobs, setJobs] = useState<AiJobSummary[]>([])\n const [loading, setLoading] = useState(false)\n const [notice, setNotice] = useState<string | null>(null)\n /** Whether the page brief dialog is open (AGL-2907). */\n const [describing, setDescribing] = useState(false)\n /**\n * The insight dialog (AGL-2915): `'ask'` for a new question, a job id for an\n * answer a job already wrote, `null` when closed.\n */\n const [insightOpen, setInsightOpen] = useState<string | null>(null)\n /** Job ids whose terminal event has been tracked, so a re-read does not count twice. */\n const trackedRef = useRef(new Set<string>())\n /** The job whose stream is open, so a re-render does not open a second. */\n const watchingRef = useRef<string | null>(null)\n\n const patchJob = useCallback((next: AiJobSummary) => {\n // Every counting surface moves with the row (AGL-3593).\n publishAiJob(next)\n setJobs((prior) => {\n const index = prior.findIndex((job) => job.id === next.id)\n if (index === -1) return [next, ...prior].slice(0, LIST_LIMIT)\n const copy = [...prior]\n copy[index] = next\n return copy\n })\n if (\n AI_JOB_TERMINAL_STATUSES.includes(next.status) &&\n !trackedRef.current.has(next.id)\n ) {\n trackedRef.current.add(next.id)\n if (next.status === 'done') {\n trackEvent('ai_job_completed', { kind: next.kind, credits: next.creditsSpent })\n } else if (next.status === 'failed') {\n trackEvent('ai_job_failed', { kind: next.kind })\n }\n }\n }, [])\n\n const load = useCallback(async () => {\n if (!orgId) return\n setLoading(true)\n setNotice(null)\n try {\n const response = await authorizedFetch(\n user,\n `/api/ai/jobs?orgId=${encodeURIComponent(orgId)}&limit=${LIST_LIMIT}`,\n )\n if (!response.ok) {\n const payload = await response.json().catch(() => null)\n setNotice(String(payload?.error ?? 'The AI jobs could not be loaded — try again.'))\n return\n }\n const payload = (await response.json()) as { jobs: AiJobSummary[] }\n // Every job that arrives already terminal is one the drawer did not\n // watch finish, so its outcome is not this session's to count.\n for (const job of payload.jobs) {\n if (AI_JOB_TERMINAL_STATUSES.includes(job.status)) trackedRef.current.add(job.id)\n // A job the indicator still counts that has settled since leaves it.\n publishAiJob(job)\n }\n setJobs(payload.jobs)\n } catch {\n setNotice('The AI jobs could not be loaded — try again.')\n } finally {\n setLoading(false)\n }\n }, [orgId, user])\n\n useEffect(() => {\n if (expanded) void load()\n }, [expanded, load])\n\n // Reset when the panel's org changes: a list from one workspace must not\n // show under another's key while the new one loads.\n useEffect(() => {\n setJobs([])\n setExpanded(false)\n toggledRef.current = false\n watchingRef.current = null\n }, [orgId])\n\n // Expanded by default while anything is moving or waiting (AGL-3593): a\n // plan waiting to be confirmed behind a collapsed row is a site that never\n // gets built. Otherwise collapsed, which reads nothing until asked.\n const anyInFlight = (inFlight?.length ?? 0) > 0\n useEffect(() => {\n if (anyInFlight && !toggledRef.current) setExpanded(true)\n }, [anyInFlight])\n\n // A request to open AI jobs (AGL-3593): expand, read the list again so a\n // job created a moment ago is in it, and highlight the job named.\n const focusSeq = focus?.seq ?? 0\n const focusJobId = focus?.jobId ?? null\n const expandedRef = useRef(expanded)\n expandedRef.current = expanded\n useEffect(() => {\n if (!focusSeq) return\n toggledRef.current = true\n setHighlight(focusJobId)\n // An open list does not re-run the expand effect's read, so it reads here.\n if (expandedRef.current) void load()\n else setExpanded(true)\n // Only a new request runs this; `load` and the job are read as they stand.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [focusSeq])\n\n // Scroll to the highlighted job once it is listed, then let it fade.\n const highlightListed = highlight !== null && jobs.some((job) => job.id === highlight)\n useEffect(() => {\n if (!highlight || !highlightListed) return undefined\n const row = Array.from(\n listRef.current?.querySelectorAll<HTMLElement>('[data-ai-job-id]') ?? [],\n ).find((element) => element.dataset['aiJobId'] === highlight)\n row?.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' })\n const timer = setTimeout(() => setHighlight(null), HIGHLIGHT_MS)\n return () => clearTimeout(timer)\n }, [highlight, highlightListed])\n\n // Watch the most recent job that is still moving. One stream at a time:\n // the route re-reads a document every two seconds per open stream, and a\n // drawer with three running jobs does not need three of them.\n const watched = jobs.find((job) => !AI_JOB_TERMINAL_STATUSES.includes(job.status))\n const watchedId = watched?.id ?? null\n useEffect(() => {\n if (!expanded || !orgId || !watchedId || watchingRef.current === watchedId) return\n watchingRef.current = watchedId\n const controller = new AbortController()\n const watch = async () => {\n // The server closes a stream at its deadline with `reconnect`; the\n // loop here re-opens it until the job settles or the drawer unmounts.\n let again = true\n while (again && !controller.signal.aborted) {\n again = false\n try {\n const response = await authorizedFetch(\n user,\n `/api/ai/jobs/${encodeURIComponent(watchedId)}/events?orgId=${encodeURIComponent(orgId)}`,\n { signal: controller.signal },\n )\n if (!response.ok || !response.body) return\n await readEventFrames(response.body, (event) => {\n if (event['type'] === 'state') patchJob(event['job'] as AiJobSummary)\n else if (event['type'] === 'reconnect') again = true\n else if (event['type'] === 'gone') {\n setJobs((prior) => prior.filter((job) => job.id !== watchedId))\n }\n })\n } catch {\n // The stream ended without a terminal state — a network blip or\n // the drawer closing. The next expand reloads the list.\n return\n }\n }\n }\n void watch().finally(() => {\n if (watchingRef.current === watchedId) watchingRef.current = null\n })\n return () => {\n controller.abort()\n if (watchingRef.current === watchedId) watchingRef.current = null\n }\n }, [expanded, orgId, watchedId, user, patchJob])\n\n // The same door the dialog that started the job cancels through (AGL-3593),\n // behind the one confirm every Cancel shows (AGL-3616).\n const canceling = useAiJobCancel({ user, orgId, onJob: patchJob })\n\n /** The job whose resume is in flight, so its button cannot send twice. */\n const [resuming, setResuming] = useState<string | null>(null)\n // A Free Try again past what is left (AGL-3722): its prompt, by job, until chosen.\n const [retryPrompt, setRetryPrompt] = useState<{ jobId: string; prompt: AiCreditsPrompt } | null>(null)\n\n // Confirms a plan, or tries again a step whose answer broke a building\n // rule (AGL-2935). The door runs the next step inline and answers with the\n // job, so the row moves on without waiting for the stream.\n const resume = useCallback(\n async (job: AiJobSummary, options?: AiJobResumeOptions) => {\n if (!orgId) return\n setResuming(job.id)\n setNotice(null)\n setRetryPrompt(null)\n // The same door the dialog that started the job confirms through (AGL-3593).\n const { job: next, error, credits } = await resumeAiJobRequest(user, orgId, job, options)\n if (next) patchJob(next)\n // A Free job past what is left asks with its choices (AGL-3722): a\n // retry here, a plan on its own card from the job the door answered with.\n if (credits && options?.retry) setRetryPrompt({ jobId: job.id, prompt: credits })\n else if (error && !(credits && job.status === 'needs_review')) setNotice(error)\n setResuming(null)\n },\n [orgId, user, patchJob],\n )\n\n if (!visible || !orgId || !entitled) return null\n\n // Counted by state, never as one \"running\" figure (AGL-3593): a plan waiting\n // to be confirmed needs the person, and a stopped job is not moving.\n const chips = aiJobsHeaderChips(aiJobActivityCounts(inFlight ?? jobs))\n\n return (\n <Box sx={{ mb: 2, borderBottom: 1, borderColor: 'divider', pb: 1 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"subtitle2\" sx={{ flexGrow: 1 }}>\n AI jobs\n {chips.map((chip) => (\n <Chip\n key={chip.state}\n size=\"small\"\n color={STATE_COLOR[chip.state]}\n label={chip.label}\n sx={{ ml: 1 }}\n />\n ))}\n </Typography>\n <HelpTip\n {...pluginDocsHelp('aiJobs', {\n anchor: '#ai-jobs-in-assist',\n excerpt:\n 'Every AI job in this workspace, newest first: where it stands, the credits it used, and its plan to confirm, cancel or try again.',\n })}\n />\n {/* A question about the page's figures (AGL-2915). */}\n {insight && (\n <Button size=\"small\" onClick={() => setInsightOpen('ask')}>\n Ask about your numbers\n </Button>\n )}\n {/* A page from a brief (AGL-2907), on a site's own routes. */}\n {hostId && (\n <Button size=\"small\" onClick={() => setDescribing(true)}>\n Describe a page\n </Button>\n )}\n <IconButton\n size=\"small\"\n aria-label={expanded ? 'Hide AI jobs' : 'Show AI jobs'}\n aria-expanded={expanded}\n onClick={() => {\n toggledRef.current = true\n setExpanded((prior) => !prior)\n }}\n >\n <MdiIcon\n path={expanded ? mdiChevronUp.path : mdiChevronDown.path}\n sx={{ fontSize: 18 }}\n />\n </IconButton>\n </Stack>\n <Collapse in={expanded} unmountOnExit>\n {notice && (\n <Typography variant=\"caption\" color=\"error\" component=\"div\" sx={{ mt: 0.5 }}>\n {notice}\n </Typography>\n )}\n {loading && !jobs.length && (\n <CircularProgress size={16} sx={{ mt: 1 }} aria-label=\"Loading AI jobs\" />\n )}\n {!loading && !jobs.length && !notice && (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\" sx={{ mt: 0.5 }}>\n No AI jobs yet.\n </Typography>\n )}\n {canceling.dialog}\n <Stack ref={listRef} spacing={1} sx={{ mt: 1 }} role=\"list\" aria-label=\"AI jobs\">\n {jobs.map((job) => {\n const restartHref = (row: AiJobSummary) =>\n aiJobRestartHref(row, {\n orgSlug,\n hostId,\n pathname: typeof window === 'undefined' ? '' : window.location.pathname,\n })\n const stepsDone = job.steps.filter((step) => step.status === 'done').length\n const current = job.steps.find((step) => step.status === 'running')\n const terminal = AI_JOB_TERMINAL_STATUSES.includes(job.status)\n const phase = aiJobPhase(job)\n const primary = aiJobPrimaryLink(job, orgSlug)\n const highlighted = highlight === job.id\n return (\n <Box\n key={job.id}\n role=\"listitem\"\n data-ai-job-id={job.id}\n aria-current={highlighted ? 'true' : undefined}\n sx={{\n borderRadius: 1,\n bgcolor: highlighted ? 'action.selected' : 'action.hover',\n outline: 2,\n outlineColor: highlighted ? 'primary.main' : 'transparent',\n transition: (theme) =>\n theme.transitions.create(['background-color', 'outline-color'], {\n duration: theme.transitions.duration.standard,\n }),\n px: 1.5,\n py: 1,\n }}\n >\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Chip size=\"small\" variant=\"outlined\" label={job.kind} />\n <Chip size=\"small\" color={PHASE_COLOR[phase]} label={AI_JOB_PHASE_LABELS[phase]} />\n <Typography variant=\"caption\" color=\"text.secondary\" sx={{ flexGrow: 1 }}>\n {stepsDone}/{job.steps.length} steps\n {current ? ` — ${current.name}` : ''}\n {/* Net of what a failure on our side gave back (AGL-3594). */}\n {netCredits(job) > 0 ? ` · ${netCredits(job)} credits` : ''}\n </Typography>\n {!terminal && (\n <Button\n size=\"small\"\n disabled={Boolean(job.cancelRequested) || canceling.busyJobId === job.id}\n onClick={() => canceling.ask(job)}\n >\n {job.cancelRequested ? 'Stopping…' : 'Cancel'}\n </Button>\n )}\n </Stack>\n <Typography variant=\"body2\" sx={{ mt: 0.5, wordBreak: 'break-word' }}>\n {job.brief.length > BRIEF_PREVIEW_CHARS\n ? `${job.brief.slice(0, BRIEF_PREVIEW_CHARS)}…`\n : job.brief}\n </Typography>\n {job.error && (\n <Typography variant=\"caption\" color={job.status === 'failed' ? 'error' : 'warning.main'} component=\"div\">\n {job.error}\n </Typography>\n )}\n {/* What became of its credits, from the job's recorded give-back (AGL-3596). */}\n {aiJobRefundCopy(job) && (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {aiJobRefundCopy(job)}\n </Typography>\n )}\n {/* A site that built part of itself says what, and that the rest was on us (AGL-3616). */}\n {aiSitePartialCopy(job) && (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {aiSitePartialCopy(job)}\n </Typography>\n )}\n {/* A build, item by item: where each stands, and what became of its credits (AGL-3616). */}\n {job.items?.length ? (\n <Box component=\"ul\" aria-label=\"Items\" sx={{ m: 0, mt: 0.5, pl: 2 }}>\n {aiBuildItemRows(job).map((row) => (\n <Typography key={row.slot} component=\"li\" variant=\"caption\" data-item-state={row.state}>\n {`${row.label} — ${ITEM_STATE_LABELS[row.state]}`}\n {row.detail ? `. ${row.detail}` : ''}\n </Typography>\n ))}\n </Box>\n ) : null}\n {aiBuildCanRetry(job) ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={resuming === job.id}\n onClick={() => void resume(job, { retry: 'failed-items' })}\n sx={{ mt: 0.5 }}\n >\n {aiBuildRetryLabel(job)}\n </Button>\n ) : null}\n {retryPrompt?.jobId === job.id ? (\n <AiCreditsPromptNotice\n prompt={retryPrompt.prompt}\n noun=\"build\"\n orgSlug={orgSlug}\n busy={resuming === job.id}\n onBuildWhatFits={() => void resume(job, { retry: 'failed-items', creditsConfirmed: true })}\n />\n ) : null}\n {/* Waiting for an ID only the person has (AGL-3978): asked here, answered onto the plan. */}\n {job.status === 'needs_input' && job.input ? (\n <AiJobInputForm job={{ ...job, input: job.input }} orgId={orgId} user={user} onJob={patchJob} />\n ) : /* Paused by the meter (AGL-3722): Resume carries on from where it stopped. */\n job.status === 'needs_input' ? (\n <Stack direction=\"row\" spacing={1} sx={{ mt: 0.5 }}>\n <Button size=\"small\" variant=\"contained\" disabled={resuming === job.id} onClick={() => void resume(job)}>\n {'Resume'}\n </Button>\n <Button size=\"small\" component={AppLink} href={aiCreditsBillingHref(orgSlug)}>\n {'Upgrade'}\n </Button>\n </Stack>\n ) : null}\n {job.siteRemoved ? (\n // Its empty site was removed (AGL-3936): Create site, with the same answers.\n <>\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {AI_SITE_REMOVED_ROW_COPY}\n </Typography>\n {aiCreateSiteHref(orgSlug) && job.siteInputs ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n component={AppLink}\n href={aiCreateSiteHref(orgSlug) as string}\n onClick={() => stashAiSiteStartAnswers(job.siteInputs)}\n sx={{ mt: 0.5 }}\n >\n {AI_SITE_START_AGAIN_LABEL}\n </Button>\n ) : null}\n </>\n ) : restartHref(job) ? (\n <Button size=\"small\" variant=\"contained\" component={AppLink} href={restartHref(job) as string} sx={{ mt: 0.5 }}>\n {'Try again'}\n </Button>\n ) : null}\n {/* What a finished job built, first (AGL-3593). */}\n {primary ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n component={AppLink}\n href={primary.href}\n sx={{ mt: 0.5 }}\n >\n {primary.label}\n </Button>\n ) : null}\n {job.outputs.map((output, index) => {\n const href = aiJobOutputHref(output, orgSlug)\n const navigation = aiJobNavigationProposal(output)\n return (\n <Box key={`${output.resource}:${output.id}:${index}`} sx={{ mt: 0.5 }}>\n {output.resource === 'insight' ? (\n <Button size=\"small\" onClick={() => setInsightOpen(output.id)}>\n View answer\n </Button>\n ) : href ? (\n <AppLink componentVariant=\"naked\" href={href}>\n Open draft — {output.label}\n </AppLink>\n ) : output.text ? (\n <Typography\n variant=\"body2\"\n component=\"pre\"\n sx={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit', m: 0 }}\n >\n {output.text}\n </Typography>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {output.label}\n </Typography>\n )}\n {output.load ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n About {formatBytes(output.load.totalBytes)} on a first visit\n </Typography>\n ) : null}\n {output.note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {output.note}\n </Typography>\n ) : null}\n {navigation ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n Add “{navigation}” to your navigation once the page is live.\n </Typography>\n ) : null}\n </Box>\n )\n })}\n <AiJobPlan\n job={job}\n onResume={(target, options) => void resume(target, options)}\n busy={resuming === job.id}\n staff={isStaff}\n user={user}\n orgSlug={orgSlug}\n />\n </Box>\n )\n })}\n </Stack>\n </Collapse>\n {/*\n The brief dialog (AGL-2907). It starts a job and closes; the list\n below it is the only place the job is watched, so an open list reads\n the new job back as soon as the dialog hands it over.\n */}\n {insightOpen !== null && (\n <AiInsightDialog\n open\n onClose={() => {\n setInsightOpen(null)\n if (expanded) void load()\n }}\n orgId={orgId}\n orgSlug={orgSlug}\n hostId={insight?.host ? (hostId ?? null) : null}\n host={insight?.host ?? null}\n surface={insight?.surface ?? 'analytics'}\n user={user}\n uid={(user as { uid?: string } | null | undefined)?.uid ?? null}\n jobId={insightOpen === 'ask' ? null : insightOpen}\n />\n )}\n {hostId && (\n <AiPageBriefDialog\n open={describing}\n onClose={() => {\n setDescribing(false)\n if (expanded) void load()\n }}\n orgId={orgId}\n hostId={hostId}\n user={user}\n orgSlug={orgSlug}\n isStaff={isStaff}\n />\n )}\n </Box>\n )\n}\n\nexport default AssistJobsDrawer\n"],"names":["checkEntitlement","trackEvent","formatBytes","AI_JOB_TERMINAL_STATUSES","mdiChevronDown","mdiChevronUp","pluginDocsHelp","AppLink","HelpTip","MdiIcon","authorizedFetch","Box","Button","Chip","CircularProgress","Collapse","IconButton","Stack","Typography","useCallback","useEffect","useRef","useState","AI_JOB_PHASE_LABELS","aiJobActivityCounts","aiJobPhase","aiJobsHeaderChips","AiJobInputForm","resumeAiJobRequest","useAiJobCancel","aiBuildCanRetry","aiBuildItemRows","aiBuildRetryCreditRange","aiSitePartialCopy","aiCreditRangeText","AiCreditsPromptNotice","publishAiJob","AiPageBriefDialog","AiInsightDialog","AiJobPlan","aiCreditsBillingHref","aiJobOutputHref","aiJobPrimaryLink","aiSiteBuildHref","aiJobRefundCopy","AI_SITE_REMOVED_ROW_COPY","AI_SITE_START_AGAIN_LABEL","aiCreateSiteHref","stashAiSiteStartAnswers","readEventFrames","aiBuildRetryLabel","job","range","LIST_LIMIT","BRIEF_PREVIEW_CHARS","PHASE_COLOR","queued","planning","building","attention","done","failed","canceled","STATE_COLOR","running","ITEM_STATE_LABELS","active","waiting","skipped","HIGHLIGHT_MS","aiJobRestartHref","input","kind","status","siteInputs","hostId","subdomain","exec","pathname","href","orgSlug","id","netCredits","Math","max","creditsSpent","refundedCredits","aiJobNavigationProposal","output","resource","navigation","proposal","label","trim","AssistJobsDrawer","orgId","org","orgReady","user","visible","isStaff","insight","inFlight","focus","entitled","expanded","setExpanded","toggledRef","highlight","setHighlight","listRef","jobs","setJobs","loading","setLoading","notice","setNotice","describing","setDescribing","insightOpen","setInsightOpen","trackedRef","Set","watchingRef","patchJob","next","prior","index","findIndex","slice","copy","includes","current","has","add","credits","load","response","encodeURIComponent","ok","payload","json","catch","String","error","anyInFlight","length","focusSeq","seq","focusJobId","jobId","expandedRef","highlightListed","some","row","undefined","Array","from","querySelectorAll","find","element","dataset","scrollIntoView","block","behavior","timer","setTimeout","clearTimeout","watched","watchedId","controller","AbortController","watch","again","signal","aborted","body","event","filter","finally","abort","canceling","onJob","resuming","setResuming","retryPrompt","setRetryPrompt","resume","options","retry","prompt","chips","sx","mb","borderBottom","borderColor","pb","direction","spacing","alignItems","variant","flexGrow","map","chip","size","color","state","ml","anchor","excerpt","onClick","aria-label","aria-expanded","path","fontSize","in","unmountOnExit","component","mt","dialog","ref","role","restartHref","window","location","stepsDone","steps","step","terminal","phase","primary","highlighted","data-ai-job-id","aria-current","borderRadius","bgcolor","outline","outlineColor","transition","theme","transitions","create","duration","standard","px","py","name","disabled","Boolean","cancelRequested","busyJobId","ask","wordBreak","brief","items","m","pl","data-item-state","detail","slot","noun","busy","onBuildWhatFits","creditsConfirmed","siteRemoved","outputs","componentVariant","text","whiteSpace","fontFamily","totalBytes","note","onResume","target","staff","open","onClose","host","surface","uid"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,eAAc;AAC/C,SAASC,UAAU,QAAQ,0CAAyC;AACpE,SAASC,WAAW,QAAQ,0CAAyC;AACrE,SACEC,wBAAwB,QAGnB,4BAAwB;AAE/B,SAASC,cAAc,EAAEC,YAAY,QAAQ,yBAAwB;AACrE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,OAAO,EAAEC,OAAO,EAAEC,OAAO,QAAQ,uBAAsB;AAChE,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,gBAAgB,EAChBC,QAAQ,EACRC,UAAU,EACVC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAChE,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,UAAU,EACVC,iBAAiB,QAGZ,8BAA0B;AAEjC,SAASC,cAAc,QAAQ,mCAA+B;AAC9D,SAASC,kBAAkB,QAAiC,uBAAmB;AAC/E,SA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I;gBACJC,SAAS;oBACP5J,eAAe;oBACf,IAAIf,UAAU,KAAK+B;gBACrB;gBACAzC,OAAOA;gBACPf,SAASA;gBACTL,QAAQ0B,CAAAA,2BAAAA,QAASgL,IAAI,IAAI1M,iBAAAA,SAAU,OAAQ;gBAC3C0M,IAAI,WAAEhL,2BAAAA,QAASgL,IAAI,oBAAI;gBACvBC,OAAO,WAAEjL,2BAAAA,QAASiL,OAAO,oBAAI;gBAC7BpL,MAAMA;gBACNqL,GAAG,WAAGrL,wBAAD,AAACA,KAA8CqL,GAAG,oBAAI;gBAC3DjI,OAAO/B,gBAAgB,QAAQ,OAAOA;;YAGzC5C,wBACC,KAACtC;gBACC8O,MAAM9J;gBACN+J,SAAS;oBACP9J,cAAc;oBACd,IAAIb,UAAU,KAAK+B;gBACrB;gBACAzC,OAAOA;gBACPpB,QAAQA;gBACRuB,MAAMA;gBACNlB,SAASA;gBACToB,SAASA;;;;AAKnB;AAEA,eAAeN,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/assist-jobs-drawer.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkEntitlement } from '@aglyn/aglyn'\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport { formatBytes } from '@aglyn/aglyn/app-utils/measure-node-map'\nimport {\n AI_JOB_TERMINAL_STATUSES,\n type AiJobOutput,\n type AiJobSummary,\n} from '../model/ai-jobs.types'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { mdiChevronDown, mdiChevronUp } from '@aglyn/shared-data-mdi'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { AppLink, HelpTip, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n Box,\n Button,\n Chip,\n CircularProgress,\n Collapse,\n IconButton,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport {\n AI_JOB_PHASE_LABELS,\n aiJobActivityCounts,\n aiJobPhase,\n aiJobsHeaderChips,\n type AiJobActivityState,\n type AiJobPhase,\n} from '../model/ai-job-activity'\nimport type { AiInsightSurface } from '../model/ai-insight'\nimport { AiJobInputForm } from './ai-job-input-form.component'\nimport { resumeAiJobRequest, type AiJobResumeOptions } from './ai-job-requests'\nimport { useAiJobCancel } from './ai-job-cancel.component'\nimport { aiBuildCanRetry, aiBuildItemRows, aiBuildRetryCreditRange, aiSitePartialCopy } from '../model/ai-build-progress'\nimport { aiCreditRangeText, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { AiCreditsPromptNotice } from './ai-credits-prompt.component'\nimport { publishAiJob, type AiJobsOpenRequest } from './ai-jobs-store'\nimport { AiPageBriefDialog } from './ai-page-brief-dialog.component'\nimport { AiInsightDialog } from './ai-insight-dialog.component'\nimport { AiJobPlan } from './ai-job-plan.component'\nimport { aiCreditsBillingHref, aiJobOutputHref, aiJobPrimaryLink, aiSiteBuildHref } from './ai-job-links'\nimport { aiJobRefundCopy } from '../model/ai-job-failure-copy'\nimport {\n AI_SITE_REMOVED_ROW_COPY,\n AI_SITE_START_AGAIN_LABEL,\n aiCreateSiteHref,\n stashAiSiteStartAnswers,\n} from '../model/ai-site-start-handoff'\nimport { readEventFrames } from './ai-job-events'\n\n/** Try again, with what it is likely to cost (AGL-3722). */\nfunction aiBuildRetryLabel(job: AiJobSummary): string {\n const range = aiBuildRetryCreditRange(job)\n return range ? `Try again what failed · ${aiCreditRangeText(range)}` : 'Try again what failed'\n}\n\n// Where an output opens, and the stream reader, live beside the dialogs that\n// share them (AGL-3593); this module has always exported them.\nexport { aiJobOutputHref, aiJobPrimaryLink, readEventFrames }\n\n/**\n * The AI jobs drawer inside the Assist panel (AGL-2904): the workspace's\n * running and recent generation jobs, each step's progress, an \"open\n * draft\" link per output, and cancel.\n *\n * Reads through the routes, never Firestore directly, so the same\n * membership, flag and entitlement rungs answer every read; progress comes\n * from the events route's server-sent stream, re-opened when the server\n * says `reconnect`. Everything loads on EXPAND rather than on mount: the\n * panel opens on every console page, and a list nobody asked for is a read\n * on every page view.\n *\n * It opens EXPANDED while any of the workspace's jobs is moving or waiting\n * for the person (AGL-3593) — the shared list the top-bar indicator reads\n * says so — because a plan waiting behind a collapsed row is a site that\n * never gets built. An \"Open AI jobs\" anywhere in the console expands it,\n * scrolls to the job it names and highlights it for a moment.\n *\n * Hidden — not disabled — unless the flag shows it AND the plan carries\n * `aiGenerative`: a released-off feature does not exist, and a plan without\n * it is sold the add-on on the Billing page, not here.\n */\n\n/** Jobs the drawer lists; the route caps higher, the drawer is a glance. */\nconst LIST_LIMIT = 10\n\n/** How much of a brief a row shows. */\nconst BRIEF_PREVIEW_CHARS = 90\n\n/**\n * A row's chip says where the job stands in the words every AI surface uses\n * (AGL-3593): a plan waiting to be confirmed is \"Plan ready\", never \"Running\"\n * and never the machine's `needs_review`.\n */\nconst PHASE_COLOR: Record<AiJobPhase, 'default' | 'primary' | 'success' | 'error' | 'warning'> = {\n queued: 'default',\n planning: 'primary',\n 'plan-ready': 'warning',\n building: 'primary',\n attention: 'warning',\n done: 'success',\n failed: 'error',\n canceled: 'default',\n}\n\n/** The header's count chips, colored as the rows they count. */\nconst STATE_COLOR: Record<AiJobActivityState, 'primary' | 'warning'> = {\n 'needs-you': 'warning',\n attention: 'warning',\n running: 'primary',\n}\n\n/** What each item state reads as in a row (AGL-3616). */\nconst ITEM_STATE_LABELS = {\n done: 'built',\n active: 'building',\n waiting: 'waiting',\n failed: 'failed',\n skipped: 'not built',\n} as const\n\n/** How long a job AI jobs was opened on stays highlighted. */\nconst HIGHLIGHT_MS = 2_500\n\n/**\n * Where a guided start that ended unbuilt is tried again (AGL-3596): its\n * \"Building your site\" page, opened on its own answers (`?retry=1`). Only for\n * a job of the site the console is on, whose subdomain the address names;\n * `null` otherwise.\n */\nexport function aiJobRestartHref(\n job: Pick<AiJobSummary, 'id' | 'kind' | 'status' | 'hostId' | 'siteInputs'>,\n input: { orgSlug: string; hostId?: string | null; pathname: string },\n): string | null {\n if (job.kind !== 'site' || (job.status !== 'failed' && job.status !== 'canceled')) return null\n if (!job.siteInputs || !job.hostId || job.hostId !== input.hostId) return null\n const subdomain = /^\\/[^/]+\\/hosts\\/([^/?#]+)/.exec(input.pathname)?.[1] ?? null\n const href = aiSiteBuildHref(input.orgSlug, subdomain, job.id)\n return href ? `${href}?retry=1` : null\n}\n\n/** What a job cost the person: what it spent, less what we refunded. */\nfunction netCredits(job: Pick<AiJobSummary, 'creditsSpent' | 'refundedCredits'>): number {\n return Math.max(0, (job.creditsSpent ?? 0) - (job.refundedCredits ?? 0))\n}\n\n/**\n * The navigation entry a page job proposes for the page it built (AGL-2907),\n * or `null`. The job writes no menu: the member adds the entry once the page\n * is live.\n */\nexport function aiJobNavigationProposal(output: AiJobOutput): string | null {\n if (output.resource !== 'screen') return null\n const navigation = output.proposal?.['navigation']\n if (!navigation || typeof navigation !== 'object') return null\n const label = (navigation as Record<string, unknown>)['label']\n return typeof label === 'string' && label.trim() ? label.trim() : null\n}\n\n\nexport interface AssistJobsDrawerProps {\n /** The org the panel is scoped to — `undefined` where the page named none. */\n orgId: string | undefined\n org: Partial<AglynOrgBilling> | undefined\n orgReady: boolean\n orgSlug: string\n user: Parameters<typeof authorizedFetch>[0]\n /** The `release_ai_generative` verdict, staff bypass applied (the shell's). */\n visible: boolean\n /**\n * The viewer is staff (AGL-3078): a job that stopped for a broken rule shows\n * them where the refused answer broke it. Who may read a job is unchanged.\n */\n isStaff?: boolean\n /** The site the console page is on, when it is on one: a page is described for a site. */\n hostId?: string | null\n /**\n * The page's insight surface (AGL-2915) — a site's Analytics, Data or CRM\n * Reports page, or the workspace's Data page — with the site's subdomain;\n * `null` elsewhere, where no question about the figures is offered.\n */\n insight?: { surface: Exclude<AiInsightSurface, 'digest'>; host: string | null } | null\n /**\n * The workspace's jobs that are not yet settled, from the shared store the\n * top-bar indicator reads (AGL-3593). The header counts them, and the\n * drawer opens expanded while there is any. Absent, the drawer counts what\n * it loaded itself.\n */\n inFlight?: readonly AiJobSummary[]\n /**\n * The latest request to open AI jobs (AGL-3593): a new `seq` expands the\n * drawer, and a named job is scrolled to and highlighted.\n */\n focus?: AiJobsOpenRequest | null\n /**\n * The AI jobs page of the site the console page is on (AGL-4116). With\n * one, the list never opens inside the chat: the row counts the jobs and\n * links to the page, where each has room to be read.\n */\n pageHref?: string | null\n}\n\nexport function AssistJobsDrawer({\n orgId,\n org,\n orgReady,\n orgSlug,\n user,\n visible,\n isStaff = false,\n hostId,\n insight,\n inFlight,\n focus,\n pageHref = null,\n}: AssistJobsDrawerProps): JSX.Element | null {\n const entitled = orgReady && checkEntitlement(org as never, 'aiGenerative')\n const [expanded, setExpanded] = useState(false)\n /**\n * The person opened or closed the list themselves: from then on the\n * expanded-by-default rule leaves their choice alone until the workspace\n * changes.\n */\n const toggledRef = useRef(false)\n /** The job AI jobs was opened on, highlighted for a moment once it is listed. */\n const [highlight, setHighlight] = useState<string | null>(null)\n const listRef = useRef<HTMLDivElement | null>(null)\n const [jobs, setJobs] = useState<AiJobSummary[]>([])\n const [loading, setLoading] = useState(false)\n const [notice, setNotice] = useState<string | null>(null)\n /** Whether the page brief dialog is open (AGL-2907). */\n const [describing, setDescribing] = useState(false)\n /**\n * The insight dialog (AGL-2915): `'ask'` for a new question, a job id for an\n * answer a job already wrote, `null` when closed.\n */\n const [insightOpen, setInsightOpen] = useState<string | null>(null)\n /** Job ids whose terminal event has been tracked, so a re-read does not count twice. */\n const trackedRef = useRef(new Set<string>())\n /** The job whose stream is open, so a re-render does not open a second. */\n const watchingRef = useRef<string | null>(null)\n\n const patchJob = useCallback((next: AiJobSummary) => {\n // Every counting surface moves with the row (AGL-3593).\n publishAiJob(next)\n setJobs((prior) => {\n const index = prior.findIndex((job) => job.id === next.id)\n if (index === -1) return [next, ...prior].slice(0, LIST_LIMIT)\n const copy = [...prior]\n copy[index] = next\n return copy\n })\n if (\n AI_JOB_TERMINAL_STATUSES.includes(next.status) &&\n !trackedRef.current.has(next.id)\n ) {\n trackedRef.current.add(next.id)\n if (next.status === 'done') {\n trackEvent('ai_job_completed', { kind: next.kind, credits: next.creditsSpent })\n } else if (next.status === 'failed') {\n trackEvent('ai_job_failed', { kind: next.kind })\n }\n }\n }, [])\n\n const load = useCallback(async () => {\n if (!orgId) return\n setLoading(true)\n setNotice(null)\n try {\n const response = await authorizedFetch(\n user,\n `/api/ai/jobs?orgId=${encodeURIComponent(orgId)}&limit=${LIST_LIMIT}`,\n )\n if (!response.ok) {\n const payload = await response.json().catch(() => null)\n setNotice(String(payload?.error ?? 'The AI jobs could not be loaded — try again.'))\n return\n }\n const payload = (await response.json()) as { jobs: AiJobSummary[] }\n // Every job that arrives already terminal is one the drawer did not\n // watch finish, so its outcome is not this session's to count.\n for (const job of payload.jobs) {\n if (AI_JOB_TERMINAL_STATUSES.includes(job.status)) trackedRef.current.add(job.id)\n // A job the indicator still counts that has settled since leaves it.\n publishAiJob(job)\n }\n setJobs(payload.jobs)\n } catch {\n setNotice('The AI jobs could not be loaded — try again.')\n } finally {\n setLoading(false)\n }\n }, [orgId, user])\n\n useEffect(() => {\n if (expanded) void load()\n }, [expanded, load])\n\n // Reset when the panel's org changes: a list from one workspace must not\n // show under another's key while the new one loads.\n useEffect(() => {\n setJobs([])\n setExpanded(false)\n toggledRef.current = false\n watchingRef.current = null\n }, [orgId])\n\n // Expanded by default while anything is moving or waiting (AGL-3593): a\n // plan waiting to be confirmed behind a collapsed row is a site that never\n // gets built. Otherwise collapsed, which reads nothing until asked.\n // A site's jobs are read on its AI jobs page instead (AGL-4116).\n const anyInFlight = (inFlight?.length ?? 0) > 0\n useEffect(() => {\n if (anyInFlight && !toggledRef.current && !pageHref) setExpanded(true)\n }, [anyInFlight, pageHref])\n useEffect(() => {\n if (pageHref) setExpanded(false)\n }, [pageHref])\n\n // A request to open AI jobs (AGL-3593): expand, read the list again so a\n // job created a moment ago is in it, and highlight the job named.\n const focusSeq = focus?.seq ?? 0\n const focusJobId = focus?.jobId ?? null\n const expandedRef = useRef(expanded)\n expandedRef.current = expanded\n useEffect(() => {\n if (!focusSeq || pageHref) return\n toggledRef.current = true\n setHighlight(focusJobId)\n // An open list does not re-run the expand effect's read, so it reads here.\n if (expandedRef.current) void load()\n else setExpanded(true)\n // Only a new request runs this; `load` and the job are read as they stand.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [focusSeq])\n\n // Scroll to the highlighted job once it is listed, then let it fade.\n const highlightListed = highlight !== null && jobs.some((job) => job.id === highlight)\n useEffect(() => {\n if (!highlight || !highlightListed) return undefined\n const row = Array.from(\n listRef.current?.querySelectorAll<HTMLElement>('[data-ai-job-id]') ?? [],\n ).find((element) => element.dataset['aiJobId'] === highlight)\n row?.scrollIntoView?.({ block: 'nearest', behavior: 'smooth' })\n const timer = setTimeout(() => setHighlight(null), HIGHLIGHT_MS)\n return () => clearTimeout(timer)\n }, [highlight, highlightListed])\n\n // Watch the most recent job that is still moving. One stream at a time:\n // the route re-reads a document every two seconds per open stream, and a\n // drawer with three running jobs does not need three of them.\n const watched = jobs.find((job) => !AI_JOB_TERMINAL_STATUSES.includes(job.status))\n const watchedId = watched?.id ?? null\n useEffect(() => {\n if (!expanded || !orgId || !watchedId || watchingRef.current === watchedId) return\n watchingRef.current = watchedId\n const controller = new AbortController()\n const watch = async () => {\n // The server closes a stream at its deadline with `reconnect`; the\n // loop here re-opens it until the job settles or the drawer unmounts.\n let again = true\n while (again && !controller.signal.aborted) {\n again = false\n try {\n const response = await authorizedFetch(\n user,\n `/api/ai/jobs/${encodeURIComponent(watchedId)}/events?orgId=${encodeURIComponent(orgId)}`,\n { signal: controller.signal },\n )\n if (!response.ok || !response.body) return\n await readEventFrames(response.body, (event) => {\n if (event['type'] === 'state') patchJob(event['job'] as AiJobSummary)\n else if (event['type'] === 'reconnect') again = true\n else if (event['type'] === 'gone') {\n setJobs((prior) => prior.filter((job) => job.id !== watchedId))\n }\n })\n } catch {\n // The stream ended without a terminal state — a network blip or\n // the drawer closing. The next expand reloads the list.\n return\n }\n }\n }\n void watch().finally(() => {\n if (watchingRef.current === watchedId) watchingRef.current = null\n })\n return () => {\n controller.abort()\n if (watchingRef.current === watchedId) watchingRef.current = null\n }\n }, [expanded, orgId, watchedId, user, patchJob])\n\n // The same door the dialog that started the job cancels through (AGL-3593),\n // behind the one confirm every Cancel shows (AGL-3616).\n const canceling = useAiJobCancel({ user, orgId, onJob: patchJob })\n\n /** The job whose resume is in flight, so its button cannot send twice. */\n const [resuming, setResuming] = useState<string | null>(null)\n // A Free Try again past what is left (AGL-3722): its prompt, by job, until chosen.\n const [retryPrompt, setRetryPrompt] = useState<{ jobId: string; prompt: AiCreditsPrompt } | null>(null)\n\n // Confirms a plan, or tries again a step whose answer broke a building\n // rule (AGL-2935). The door runs the next step inline and answers with the\n // job, so the row moves on without waiting for the stream.\n const resume = useCallback(\n async (job: AiJobSummary, options?: AiJobResumeOptions) => {\n if (!orgId) return\n setResuming(job.id)\n setNotice(null)\n setRetryPrompt(null)\n // The same door the dialog that started the job confirms through (AGL-3593).\n const { job: next, error, credits } = await resumeAiJobRequest(user, orgId, job, options)\n if (next) patchJob(next)\n // A Free job past what is left asks with its choices (AGL-3722): a\n // retry here, a plan on its own card from the job the door answered with.\n if (credits && options?.retry) setRetryPrompt({ jobId: job.id, prompt: credits })\n else if (error && !(credits && job.status === 'needs_review')) setNotice(error)\n setResuming(null)\n },\n [orgId, user, patchJob],\n )\n\n if (!visible || !orgId || !entitled) return null\n\n // Counted by state, never as one \"running\" figure (AGL-3593): a plan waiting\n // to be confirmed needs the person, and a stopped job is not moving.\n // A row that links to a site's page counts that site's jobs (AGL-4116).\n const counted = inFlight ?? jobs\n const chips = aiJobsHeaderChips(\n aiJobActivityCounts(pageHref && hostId ? counted.filter((job) => job.hostId === hostId) : counted),\n )\n\n return (\n <Box sx={{ mb: 2, borderBottom: 1, borderColor: 'divider', pb: 1 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"subtitle2\" sx={{ flexGrow: 1 }}>\n AI jobs\n {chips.map((chip) => (\n <Chip\n key={chip.state}\n size=\"small\"\n color={STATE_COLOR[chip.state]}\n label={chip.label}\n sx={{ ml: 1 }}\n />\n ))}\n </Typography>\n <HelpTip\n {...pluginDocsHelp('aiJobs', {\n anchor: '#ai-jobs-in-assist',\n excerpt:\n 'Every AI job in this workspace, newest first: where it stands, the credits it used, and its plan to confirm, cancel or try again.',\n })}\n />\n {/* A question about the page's figures (AGL-2915). */}\n {insight && (\n <Button size=\"small\" onClick={() => setInsightOpen('ask')}>\n Ask about your numbers\n </Button>\n )}\n {/* A page from a brief (AGL-2907), on a site's own routes. */}\n {hostId && (\n <Button size=\"small\" onClick={() => setDescribing(true)}>\n Describe a page\n </Button>\n )}\n {pageHref ? (\n <Button size=\"small\" component={AppLink} href={pageHref}>\n {'View all'}\n </Button>\n ) : (\n <IconButton\n size=\"small\"\n aria-label={expanded ? 'Hide AI jobs' : 'Show AI jobs'}\n aria-expanded={expanded}\n onClick={() => {\n toggledRef.current = true\n setExpanded((prior) => !prior)\n }}\n >\n <MdiIcon\n path={expanded ? mdiChevronUp.path : mdiChevronDown.path}\n sx={{ fontSize: 18 }}\n />\n </IconButton>\n )}\n </Stack>\n <Collapse in={expanded} unmountOnExit>\n {notice && (\n <Typography variant=\"caption\" color=\"error\" component=\"div\" sx={{ mt: 0.5 }}>\n {notice}\n </Typography>\n )}\n {loading && !jobs.length && (\n <CircularProgress size={16} sx={{ mt: 1 }} aria-label=\"Loading AI jobs\" />\n )}\n {!loading && !jobs.length && !notice && (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\" sx={{ mt: 0.5 }}>\n No AI jobs yet.\n </Typography>\n )}\n {canceling.dialog}\n <Stack ref={listRef} spacing={1} sx={{ mt: 1 }} role=\"list\" aria-label=\"AI jobs\">\n {jobs.map((job) => {\n const restartHref = (row: AiJobSummary) =>\n aiJobRestartHref(row, {\n orgSlug,\n hostId,\n pathname: typeof window === 'undefined' ? '' : window.location.pathname,\n })\n const stepsDone = job.steps.filter((step) => step.status === 'done').length\n const current = job.steps.find((step) => step.status === 'running')\n const terminal = AI_JOB_TERMINAL_STATUSES.includes(job.status)\n const phase = aiJobPhase(job)\n const primary = aiJobPrimaryLink(job, orgSlug)\n const highlighted = highlight === job.id\n return (\n <Box\n key={job.id}\n role=\"listitem\"\n data-ai-job-id={job.id}\n aria-current={highlighted ? 'true' : undefined}\n sx={{\n borderRadius: 1,\n bgcolor: highlighted ? 'action.selected' : 'action.hover',\n outline: 2,\n outlineColor: highlighted ? 'primary.main' : 'transparent',\n transition: (theme) =>\n theme.transitions.create(['background-color', 'outline-color'], {\n duration: theme.transitions.duration.standard,\n }),\n px: 1.5,\n py: 1,\n }}\n >\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Chip size=\"small\" variant=\"outlined\" label={job.kind} />\n <Chip size=\"small\" color={PHASE_COLOR[phase]} label={AI_JOB_PHASE_LABELS[phase]} />\n <Typography variant=\"caption\" color=\"text.secondary\" sx={{ flexGrow: 1 }}>\n {stepsDone}/{job.steps.length} steps\n {current ? ` — ${current.name}` : ''}\n {/* Net of what a failure on our side gave back (AGL-3594). */}\n {netCredits(job) > 0 ? ` · ${netCredits(job)} credits` : ''}\n </Typography>\n {!terminal && (\n <Button\n size=\"small\"\n disabled={Boolean(job.cancelRequested) || canceling.busyJobId === job.id}\n onClick={() => canceling.ask(job)}\n >\n {job.cancelRequested ? 'Stopping…' : 'Cancel'}\n </Button>\n )}\n </Stack>\n <Typography variant=\"body2\" sx={{ mt: 0.5, wordBreak: 'break-word' }}>\n {job.brief.length > BRIEF_PREVIEW_CHARS\n ? `${job.brief.slice(0, BRIEF_PREVIEW_CHARS)}…`\n : job.brief}\n </Typography>\n {job.error && (\n <Typography variant=\"caption\" color={job.status === 'failed' ? 'error' : 'warning.main'} component=\"div\">\n {job.error}\n </Typography>\n )}\n {/* What became of its credits, from the job's recorded give-back (AGL-3596). */}\n {aiJobRefundCopy(job) && (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {aiJobRefundCopy(job)}\n </Typography>\n )}\n {/* A site that built part of itself says what, and that the rest was on us (AGL-3616). */}\n {aiSitePartialCopy(job) && (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {aiSitePartialCopy(job)}\n </Typography>\n )}\n {/* A build, item by item: where each stands, and what became of its credits (AGL-3616). */}\n {job.items?.length ? (\n <Box component=\"ul\" aria-label=\"Items\" sx={{ m: 0, mt: 0.5, pl: 2 }}>\n {aiBuildItemRows(job).map((row) => (\n <Typography key={row.slot} component=\"li\" variant=\"caption\" data-item-state={row.state}>\n {`${row.label} — ${ITEM_STATE_LABELS[row.state]}`}\n {row.detail ? `. ${row.detail}` : ''}\n </Typography>\n ))}\n </Box>\n ) : null}\n {aiBuildCanRetry(job) ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={resuming === job.id}\n onClick={() => void resume(job, { retry: 'failed-items' })}\n sx={{ mt: 0.5 }}\n >\n {aiBuildRetryLabel(job)}\n </Button>\n ) : null}\n {retryPrompt?.jobId === job.id ? (\n <AiCreditsPromptNotice\n prompt={retryPrompt.prompt}\n noun=\"build\"\n orgSlug={orgSlug}\n busy={resuming === job.id}\n onBuildWhatFits={() => void resume(job, { retry: 'failed-items', creditsConfirmed: true })}\n />\n ) : null}\n {/* Waiting for an ID only the person has (AGL-3978): asked here, answered onto the plan. */}\n {job.status === 'needs_input' && job.input ? (\n <AiJobInputForm job={{ ...job, input: job.input }} orgId={orgId} user={user} onJob={patchJob} />\n ) : /* Paused by the meter (AGL-3722): Resume carries on from where it stopped. */\n job.status === 'needs_input' ? (\n <Stack direction=\"row\" spacing={1} sx={{ mt: 0.5 }}>\n <Button size=\"small\" variant=\"contained\" disabled={resuming === job.id} onClick={() => void resume(job)}>\n {'Resume'}\n </Button>\n <Button size=\"small\" component={AppLink} href={aiCreditsBillingHref(orgSlug)}>\n {'Upgrade'}\n </Button>\n </Stack>\n ) : null}\n {job.siteRemoved ? (\n // Its empty site was removed (AGL-3936): Create site, with the same answers.\n <>\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {AI_SITE_REMOVED_ROW_COPY}\n </Typography>\n {aiCreateSiteHref(orgSlug) && job.siteInputs ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n component={AppLink}\n href={aiCreateSiteHref(orgSlug) as string}\n onClick={() => stashAiSiteStartAnswers(job.siteInputs)}\n sx={{ mt: 0.5 }}\n >\n {AI_SITE_START_AGAIN_LABEL}\n </Button>\n ) : null}\n </>\n ) : restartHref(job) ? (\n <Button size=\"small\" variant=\"contained\" component={AppLink} href={restartHref(job) as string} sx={{ mt: 0.5 }}>\n {'Try again'}\n </Button>\n ) : null}\n {/* What a finished job built, first (AGL-3593). */}\n {primary ? (\n <Button\n size=\"small\"\n variant=\"contained\"\n component={AppLink}\n href={primary.href}\n sx={{ mt: 0.5 }}\n >\n {primary.label}\n </Button>\n ) : null}\n {job.outputs.map((output, index) => {\n const href = aiJobOutputHref(output, orgSlug)\n const navigation = aiJobNavigationProposal(output)\n return (\n <Box key={`${output.resource}:${output.id}:${index}`} sx={{ mt: 0.5 }}>\n {output.resource === 'insight' ? (\n <Button size=\"small\" onClick={() => setInsightOpen(output.id)}>\n View answer\n </Button>\n ) : href ? (\n <AppLink componentVariant=\"naked\" href={href}>\n Open draft — {output.label}\n </AppLink>\n ) : output.text ? (\n <Typography\n variant=\"body2\"\n component=\"pre\"\n sx={{ whiteSpace: 'pre-wrap', fontFamily: 'inherit', m: 0 }}\n >\n {output.text}\n </Typography>\n ) : (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {output.label}\n </Typography>\n )}\n {output.load ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n About {formatBytes(output.load.totalBytes)} on a first visit\n </Typography>\n ) : null}\n {output.note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n {output.note}\n </Typography>\n ) : null}\n {navigation ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"div\">\n Add “{navigation}” to your navigation once the page is live.\n </Typography>\n ) : null}\n </Box>\n )\n })}\n <AiJobPlan\n job={job}\n onResume={(target, options) => void resume(target, options)}\n busy={resuming === job.id}\n staff={isStaff}\n user={user}\n orgSlug={orgSlug}\n />\n </Box>\n )\n })}\n </Stack>\n </Collapse>\n {/*\n The brief dialog (AGL-2907). It starts a job and closes; the list\n below it is the only place the job is watched, so an open list reads\n the new job back as soon as the dialog hands it over.\n */}\n {insightOpen !== null && (\n <AiInsightDialog\n open\n onClose={() => {\n setInsightOpen(null)\n if (expanded) void load()\n }}\n orgId={orgId}\n orgSlug={orgSlug}\n hostId={insight?.host ? (hostId ?? null) : null}\n host={insight?.host ?? null}\n surface={insight?.surface ?? 'analytics'}\n user={user}\n uid={(user as { uid?: string } | null | undefined)?.uid ?? null}\n jobId={insightOpen === 'ask' ? null : insightOpen}\n />\n )}\n {hostId && (\n <AiPageBriefDialog\n open={describing}\n onClose={() => {\n setDescribing(false)\n if (expanded) void load()\n }}\n orgId={orgId}\n hostId={hostId}\n user={user}\n orgSlug={orgSlug}\n isStaff={isStaff}\n />\n )}\n </Box>\n )\n}\n\nexport default AssistJobsDrawer\n"],"names":["checkEntitlement","trackEvent","formatBytes","AI_JOB_TERMINAL_STATUSES","mdiChevronDown","mdiChevronUp","pluginDocsHelp","AppLink","HelpTip","MdiIcon","authorizedFetch","Box","Button","Chip","CircularProgress","Collapse","IconButton","Stack","Typography","useCallback","useEffect","useRef","useState","AI_JOB_PHASE_LABELS","aiJobActivityCounts","aiJobPhase","aiJobsHeaderChips","AiJobInputForm","resumeAiJobRequest","useAiJobCancel","aiBuildCanRetry","aiBuildItemRows","aiBuildRetryCreditRange","aiSitePartialCopy","aiCreditRangeText","AiCreditsPromptNotice","publishAiJob","AiPageBriefDialog","AiInsightDialog","AiJobPlan","aiCreditsBillingHref","aiJobOutputHref","aiJobPrimaryLink","aiSiteBuildHref","aiJobRefundCopy","AI_SITE_REMOVED_ROW_COPY","AI_SITE_START_AGAIN_LABEL","aiCreateSiteHref","stashAiSiteStartAnswers","readEventFrames","aiBuildRetryLabel","job","range","LIST_LIMIT","BRIEF_PREVIEW_CHARS","PHASE_COLOR","queued","planning","building","attention","done","failed","canceled","STATE_COLOR","running","ITEM_STATE_LABELS","active","waiting","skipped","HIGHLIGHT_MS","aiJobRestartHref","input","kind","status","siteInputs","hostId","subdomain","exec","pathname","href","orgSlug","id","netCredits","Math","max","creditsSpent","refundedCredits","aiJobNavigationProposal","output","resource","navigation","proposal","label","trim","AssistJobsDrawer","orgId","org","orgReady","user","visible","isStaff","insight","inFlight","focus","pageHref","entitled","expanded","setExpanded","toggledRef","highlight","setHighlight","listRef","jobs","setJobs","loading","setLoading","notice","setNotice","describing","setDescribing","insightOpen","setInsightOpen","trackedRef","Set","watchingRef","patchJob","next","prior","index","findIndex","slice","copy","includes","current","has","add","credits","load","response","encodeURIComponent","ok","payload","json","catch","String","error","anyInFlight","length","focusSeq","seq","focusJobId","jobId","expandedRef","highlightListed","some","row","undefined","Array","from","querySelectorAll","find","element","dataset","scrollIntoView","block","behavior","timer","setTimeout","clearTimeout","watched","watchedId","controller","AbortController","watch","again","signal","aborted","body","event","filter","finally","abort","canceling","onJob","resuming","setResuming","retryPrompt","setRetryPrompt","resume","options","retry","prompt","counted","chips","sx","mb","borderBottom","borderColor","pb","direction","spacing","alignItems","variant","flexGrow","map","chip","size","color","state","ml","anchor","excerpt","onClick","component","aria-label","aria-expanded","path","fontSize","in","unmountOnExit","mt","dialog","ref","role","restartHref","window","location","stepsDone","steps","step","terminal","phase","primary","highlighted","data-ai-job-id","aria-current","borderRadius","bgcolor","outline","outlineColor","transition","theme","transitions","create","duration","standard","px","py","name","disabled","Boolean","cancelRequested","busyJobId","ask","wordBreak","brief","items","m","pl","data-item-state","detail","slot","noun","busy","onBuildWhatFits","creditsConfirmed","siteRemoved","outputs","componentVariant","text","whiteSpace","fontFamily","totalBytes","note","onResume","target","staff","open","onClose","host","surface","uid"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,eAAc;AAC/C,SAASC,UAAU,QAAQ,0CAAyC;AACpE,SAASC,WAAW,QAAQ,0CAAyC;AACrE,SACEC,wBAAwB,QAGnB,4BAAwB;AAE/B,SAASC,cAAc,EAAEC,YAAY,QAAQ,yBAAwB;AACrE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,OAAO,EAAEC,OAAO,EAAEC,OAAO,QAAQ,uBAAsB;AAChE,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SACEC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,gBAAgB,EAChBC,QAAQ,EACRC,UAAU,EACVC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAChE,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,UAAU,EACVC,iBAAiB,QAGZ,8BAA0B;AAEjC,SAASC,cAAc,QAAQ,mCAA+B;AAC9D,SAASC,kBAAkB,QAAiC,uBAAmB;AAC/E,SAASC,cAAc,QAAQ,+BAA2B;AAC1D,SAASC,eAAe,EAAEC,eAAe,EAAEC,uBAAuB,EAAEC,iBAAiB,QAAQ,gCAA4B;AACzH,SAASC,iBAAiB,QAA8B,iCAA6B;AACrF,SAASC,qBAA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QtF;wCACnD0E,MAAM/E,aAAarI,IAAI8B,EAAE;wCACzBmM,OAAOhL;wCACPF,MAAMA;wCACNlB,SAASA;;;+BA7LN7B,IAAI8B,EAAE;wBAiMjB;;;;YAQHuC,gBAAgB,sBACf,KAAClF;gBACC+O,IAAI;gBACJC,SAAS;oBACP7J,eAAe;oBACf,IAAIf,UAAU,KAAK+B;gBACrB;gBACA1C,OAAOA;gBACPf,SAASA;gBACTL,QAAQ0B,CAAAA,2BAAAA,QAASkL,IAAI,IAAI5M,iBAAAA,SAAU,OAAQ;gBAC3C4M,IAAI,WAAElL,2BAAAA,QAASkL,IAAI,oBAAI;gBACvBC,OAAO,WAAEnL,2BAAAA,QAASmL,OAAO,oBAAI;gBAC7BtL,MAAMA;gBACNuL,GAAG,WAAGvL,wBAAD,AAACA,KAA8CuL,GAAG,oBAAI;gBAC3DlI,OAAO/B,gBAAgB,QAAQ,OAAOA;;YAGzC7C,wBACC,KAACtC;gBACCgP,MAAM/J;gBACNgK,SAAS;oBACP/J,cAAc;oBACd,IAAIb,UAAU,KAAK+B;gBACrB;gBACA1C,OAAOA;gBACPpB,QAAQA;gBACRuB,MAAMA;gBACNlB,SAASA;gBACToB,SAASA;;;;AAKnB;AAEA,eAAeN,iBAAgB"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { MaybeTokenSource } from '@aglyn/shared-util-http/authorized-token';
18
+ import { type AiJobSummary } from '../model/ai-jobs.types';
19
+ import { type AssistPageChangeProposal } from '../model/assist-page-change';
20
+ /**
21
+ * A change to a page the site already has, asked in the chat (AGL-4116):
22
+ * the edit job making it, then the page's draft it wrote, opened in the
23
+ * Besigner on that draft, where the person checks it and publishes it. No
24
+ * plan, no AI jobs page. On every plan: a new version is made only when one
25
+ * was asked for, and the job's note says which it was.
26
+ */
27
+ export interface AssistPageChangeCardProps {
28
+ proposal: AssistPageChangeProposal;
29
+ /** The edit job, as last seen; `null` while it is being created. */
30
+ job: AiJobSummary | null;
31
+ /** Why the job could not be started, when it could not. */
32
+ notice: string | null;
33
+ orgId: string;
34
+ orgSlug: string;
35
+ user: MaybeTokenSource;
36
+ /** The job as it moved, for the thread to keep. */
37
+ onJob: (job: AiJobSummary) => void;
38
+ /** Starts the same change again, after it failed. */
39
+ onRetry: () => void;
40
+ busy?: boolean;
41
+ }
42
+ export declare function assistPageChangeMakingCopy(pageName: string): string;
43
+ export declare function assistPageChangeReadyCopy(pageName: string): string;
44
+ export declare function AssistPageChangeCard({ proposal, job, notice, orgId, orgSlug, user, onJob, onRetry, busy, }: AssistPageChangeCardProps): JSX.Element;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ 'use client';
17
+ import { _ as _extends } from "@swc/helpers/_/_extends";
18
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
19
+ import { pluginDocsHelp } from "@aglyn/aglyn/app-utils/docs-help";
20
+ import { AppLink, HelpTip } from "@aglyn/shared-ui-jsx";
21
+ import { Button, CircularProgress, Paper, Stack, Typography } from "@mui/material";
22
+ import { useEffect, useRef } from "react";
23
+ import { AI_JOB_TERMINAL_STATUSES } from "../model/ai-jobs.types.js";
24
+ import { assistPageChangeOutput } from "../model/assist-page-change.js";
25
+ import { followAiJobEvents } from "./ai-job-events.js";
26
+ import { aiJobOutputHref } from "./ai-job-links.js";
27
+ const ASSIST_PAGE_CHANGE_HELP = pluginDocsHelp('aiAssistBuilds', {
28
+ anchor: '#change-a-page',
29
+ excerpt: 'The change is saved into the page’s draft. Open it in the Besigner to check it, then publish it; until then visitors see the page as it is.'
30
+ });
31
+ export function assistPageChangeMakingCopy(pageName) {
32
+ return `Making the change as a draft of ${pageName}…`;
33
+ }
34
+ export function assistPageChangeReadyCopy(pageName) {
35
+ return `Your draft of ${pageName} is ready. Open it in the Besigner to check it. Visitors see the page as it is until you publish.`;
36
+ }
37
+ export function AssistPageChangeCard({ proposal, job, notice, orgId, orgSlug, user, onJob, onRetry, busy = false }) {
38
+ var _ref, _ref1, _ref2, _ref3;
39
+ var _job_review;
40
+ const userRef = useRef(user);
41
+ userRef.current = user;
42
+ const onJobRef = useRef(onJob);
43
+ onJobRef.current = onJob;
44
+ // Follow the job until it settles; one waiting on the person has nothing
45
+ // more to say on the stream.
46
+ const following = Boolean(job && !AI_JOB_TERMINAL_STATUSES.includes(job.status) && job.status !== 'needs_review' && job.status !== 'needs_input');
47
+ const jobId = (_ref = job == null ? void 0 : job.id) != null ? _ref : null;
48
+ useEffect(()=>{
49
+ if (!following || !jobId) return;
50
+ const controller = new AbortController();
51
+ void followAiJobEvents(()=>userRef.current, orgId, jobId, controller.signal, (next)=>onJobRef.current(next));
52
+ return ()=>controller.abort();
53
+ }, [
54
+ following,
55
+ jobId,
56
+ orgId
57
+ ]);
58
+ const output = assistPageChangeOutput(job);
59
+ const href = output ? aiJobOutputHref(output, orgSlug) : null;
60
+ const stopped = Boolean(job && (job.status === 'failed' || job.status === 'canceled'));
61
+ const waiting = Boolean(job && (job.status === 'needs_review' || job.status === 'needs_input'));
62
+ return /*#__PURE__*/ _jsxs(Paper, {
63
+ variant: "outlined",
64
+ sx: {
65
+ mt: 1,
66
+ p: 1.5
67
+ },
68
+ "aria-label": "Page change",
69
+ children: [
70
+ /*#__PURE__*/ _jsxs(Stack, {
71
+ direction: "row",
72
+ spacing: 0.5,
73
+ sx: {
74
+ alignItems: 'center'
75
+ },
76
+ children: [
77
+ /*#__PURE__*/ _jsx(Typography, {
78
+ variant: "subtitle2",
79
+ children: proposal.summary
80
+ }),
81
+ /*#__PURE__*/ _jsx(HelpTip, _extends({}, ASSIST_PAGE_CHANGE_HELP))
82
+ ]
83
+ }),
84
+ !job && !notice || following ? /*#__PURE__*/ _jsxs(Stack, {
85
+ direction: "row",
86
+ spacing: 1,
87
+ sx: {
88
+ mt: 0.5,
89
+ alignItems: 'center'
90
+ },
91
+ children: [
92
+ /*#__PURE__*/ _jsx(CircularProgress, {
93
+ size: 14
94
+ }),
95
+ /*#__PURE__*/ _jsx(Typography, {
96
+ variant: "body2",
97
+ color: "text.secondary",
98
+ children: assistPageChangeMakingCopy(proposal.pageName)
99
+ })
100
+ ]
101
+ }) : null,
102
+ notice && /*#__PURE__*/ _jsx(Typography, {
103
+ variant: "body2",
104
+ color: "error",
105
+ sx: {
106
+ mt: 0.5
107
+ },
108
+ role: "alert",
109
+ children: notice
110
+ }),
111
+ output && /*#__PURE__*/ _jsxs(_Fragment, {
112
+ children: [
113
+ /*#__PURE__*/ _jsx(Typography, {
114
+ variant: "body2",
115
+ sx: {
116
+ mt: 0.5
117
+ },
118
+ children: output.note || assistPageChangeReadyCopy(proposal.pageName)
119
+ }),
120
+ href && /*#__PURE__*/ _jsx(Button, {
121
+ size: "small",
122
+ variant: "contained",
123
+ component: AppLink,
124
+ href: href,
125
+ sx: {
126
+ mt: 1
127
+ },
128
+ children: 'Open in the Besigner'
129
+ })
130
+ ]
131
+ }),
132
+ waiting && /*#__PURE__*/ _jsx(Typography, {
133
+ variant: "body2",
134
+ sx: {
135
+ mt: 0.5
136
+ },
137
+ role: "alert",
138
+ children: (_ref1 = (_ref2 = job == null ? void 0 : (_job_review = job.review) == null ? void 0 : _job_review.message) != null ? _ref2 : job == null ? void 0 : job.error) != null ? _ref1 : 'The change is waiting on you.'
139
+ }),
140
+ stopped && /*#__PURE__*/ _jsxs(_Fragment, {
141
+ children: [
142
+ /*#__PURE__*/ _jsx(Typography, {
143
+ variant: "body2",
144
+ color: "error",
145
+ sx: {
146
+ mt: 0.5
147
+ },
148
+ role: "alert",
149
+ children: (_ref3 = job == null ? void 0 : job.error) != null ? _ref3 : 'The change could not be made.'
150
+ }),
151
+ /*#__PURE__*/ _jsx(Button, {
152
+ size: "small",
153
+ sx: {
154
+ mt: 1
155
+ },
156
+ disabled: busy,
157
+ onClick: onRetry,
158
+ children: 'Try again'
159
+ })
160
+ ]
161
+ })
162
+ ]
163
+ });
164
+ }
165
+
166
+ //# sourceMappingURL=assist-page-change-card.component.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/assist-page-change-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use client'\n\nimport type { MaybeTokenSource } from '@aglyn/shared-util-http/authorized-token'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { AppLink, HelpTip } from '@aglyn/shared-ui-jsx'\nimport { Button, CircularProgress, Paper, Stack, Typography } from '@mui/material'\nimport { useEffect, useRef } from 'react'\nimport { AI_JOB_TERMINAL_STATUSES, type AiJobSummary } from '../model/ai-jobs.types'\nimport { assistPageChangeOutput, type AssistPageChangeProposal } from '../model/assist-page-change'\nimport { followAiJobEvents } from './ai-job-events'\nimport { aiJobOutputHref } from './ai-job-links'\n\n/**\n * A change to a page the site already has, asked in the chat (AGL-4116):\n * the edit job making it, then the page's draft it wrote, opened in the\n * Besigner on that draft, where the person checks it and publishes it. No\n * plan, no AI jobs page. On every plan: a new version is made only when one\n * was asked for, and the job's note says which it was.\n */\n\nexport interface AssistPageChangeCardProps {\n proposal: AssistPageChangeProposal\n /** The edit job, as last seen; `null` while it is being created. */\n job: AiJobSummary | null\n /** Why the job could not be started, when it could not. */\n notice: string | null\n orgId: string\n orgSlug: string\n user: MaybeTokenSource\n /** The job as it moved, for the thread to keep. */\n onJob: (job: AiJobSummary) => void\n /** Starts the same change again, after it failed. */\n onRetry: () => void\n busy?: boolean\n}\n\nconst ASSIST_PAGE_CHANGE_HELP = pluginDocsHelp('aiAssistBuilds', {\n anchor: '#change-a-page',\n excerpt:\n 'The change is saved into the page’s draft. Open it in the Besigner to check it, then publish it; until then visitors see the page as it is.',\n})\n\nexport function assistPageChangeMakingCopy(pageName: string): string {\n return `Making the change as a draft of ${pageName}…`\n}\n\nexport function assistPageChangeReadyCopy(pageName: string): string {\n return `Your draft of ${pageName} is ready. Open it in the Besigner to check it. Visitors see the page as it is until you publish.`\n}\n\nexport function AssistPageChangeCard({\n proposal,\n job,\n notice,\n orgId,\n orgSlug,\n user,\n onJob,\n onRetry,\n busy = false,\n}: AssistPageChangeCardProps): JSX.Element {\n const userRef = useRef(user)\n userRef.current = user\n const onJobRef = useRef(onJob)\n onJobRef.current = onJob\n\n // Follow the job until it settles; one waiting on the person has nothing\n // more to say on the stream.\n const following = Boolean(\n job && !AI_JOB_TERMINAL_STATUSES.includes(job.status) && job.status !== 'needs_review' && job.status !== 'needs_input',\n )\n const jobId = job?.id ?? null\n useEffect(() => {\n if (!following || !jobId) return\n const controller = new AbortController()\n void followAiJobEvents(() => userRef.current, orgId, jobId, controller.signal, (next) => onJobRef.current(next))\n return () => controller.abort()\n }, [following, jobId, orgId])\n\n const output = assistPageChangeOutput(job)\n const href = output ? aiJobOutputHref(output, orgSlug) : null\n const stopped = Boolean(job && (job.status === 'failed' || job.status === 'canceled'))\n const waiting = Boolean(job && (job.status === 'needs_review' || job.status === 'needs_input'))\n\n return (\n <Paper variant=\"outlined\" sx={{ mt: 1, p: 1.5 }} aria-label=\"Page change\">\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'center' }}>\n <Typography variant=\"subtitle2\">{proposal.summary}</Typography>\n <HelpTip {...ASSIST_PAGE_CHANGE_HELP} />\n </Stack>\n {(!job && !notice) || following ? (\n <Stack direction=\"row\" spacing={1} sx={{ mt: 0.5, alignItems: 'center' }}>\n <CircularProgress size={14} />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {assistPageChangeMakingCopy(proposal.pageName)}\n </Typography>\n </Stack>\n ) : null}\n {notice && (\n <Typography variant=\"body2\" color=\"error\" sx={{ mt: 0.5 }} role=\"alert\">\n {notice}\n </Typography>\n )}\n {output && (\n <>\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {/* The job's own note says where the change went — the draft or a\n new version — and what it left out. */}\n {output.note || assistPageChangeReadyCopy(proposal.pageName)}\n </Typography>\n {href && (\n <Button size=\"small\" variant=\"contained\" component={AppLink} href={href} sx={{ mt: 1 }}>\n {'Open in the Besigner'}\n </Button>\n )}\n </>\n )}\n {waiting && (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }} role=\"alert\">\n {job?.review?.message ?? job?.error ?? 'The change is waiting on you.'}\n </Typography>\n )}\n {stopped && (\n <>\n <Typography variant=\"body2\" color=\"error\" sx={{ mt: 0.5 }} role=\"alert\">\n {job?.error ?? 'The change could not be made.'}\n </Typography>\n <Button size=\"small\" sx={{ mt: 1 }} disabled={busy} onClick={onRetry}>\n {'Try again'}\n </Button>\n </>\n )}\n </Paper>\n )\n}\n"],"names":["pluginDocsHelp","AppLink","HelpTip","Button","CircularProgress","Paper","Stack","Typography","useEffect","useRef","AI_JOB_TERMINAL_STATUSES","assistPageChangeOutput","followAiJobEvents","aiJobOutputHref","ASSIST_PAGE_CHANGE_HELP","anchor","excerpt","assistPageChangeMakingCopy","pageName","assistPageChangeReadyCopy","AssistPageChangeCard","proposal","job","notice","orgId","orgSlug","user","onJob","onRetry","busy","userRef","current","onJobRef","following","Boolean","includes","status","jobId","id","controller","AbortController","signal","next","abort","output","href","stopped","waiting","variant","sx","mt","p","aria-label","direction","spacing","alignItems","summary","size","color","role","note","component","review","message","error","disabled","onClick"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAGA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,OAAO,EAAEC,OAAO,QAAQ,uBAAsB;AACvD,SAASC,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAClF,SAASC,SAAS,EAAEC,MAAM,QAAQ,QAAO;AACzC,SAASC,wBAAwB,QAA2B,4BAAwB;AACpF,SAASC,sBAAsB,QAAuC,iCAA6B;AACnG,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,eAAe,QAAQ,oBAAgB;AA0BhD,MAAMC,0BAA0Bd,eAAe,kBAAkB;IAC/De,QAAQ;IACRC,SACE;AACJ;AAEA,OAAO,SAASC,2BAA2BC,QAAgB;IACzD,OAAO,CAAC,gCAAgC,EAAEA,SAAS,CAAC,CAAC;AACvD;AAEA,OAAO,SAASC,0BAA0BD,QAAgB;IACxD,OAAO,CAAC,cAAc,EAAEA,SAAS,iGAAiG,CAAC;AACrI;AAEA,OAAO,SAASE,qBAAqB,EACnCC,QAAQ,EACRC,GAAG,EACHC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,IAAI,EACJC,KAAK,EACLC,OAAO,EACPC,OAAO,KAAK,EACc;cA2DjBP;QAAAA;IA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IAAI;oBAAEC,IAAI;oBAAKK,YAAY;gBAAS;;kCACrE,KAACnD;wBAAiBqD,MAAM;;kCACxB,KAAClD;wBAAWyC,SAAQ;wBAAQU,OAAM;kCAC/BzC,2BAA2BI,SAASH,QAAQ;;;iBAG/C;YACHK,wBACC,KAAChB;gBAAWyC,SAAQ;gBAAQU,OAAM;gBAAQT,IAAI;oBAAEC,IAAI;gBAAI;gBAAGS,MAAK;0BAC7DpC;;YAGJqB,wBACC;;kCACE,KAACrC;wBAAWyC,SAAQ;wBAAQC,IAAI;4BAAEC,IAAI;wBAAI;kCAGvCN,OAAOgB,IAAI,IAAIzC,0BAA0BE,SAASH,QAAQ;;oBAE5D2B,sBACC,KAAC1C;wBAAOsD,MAAK;wBAAQT,SAAQ;wBAAYa,WAAW5D;wBAAS4C,MAAMA;wBAAMI,IAAI;4BAAEC,IAAI;wBAAE;kCAClF;;;;YAKRH,yBACC,KAACxC;gBAAWyC,SAAQ;gBAAQC,IAAI;oBAAEC,IAAI;gBAAI;gBAAGS,MAAK;2BAC/CrC,iBAAAA,wBAAAA,cAAAA,IAAKwC,MAAM,qBAAXxC,YAAayC,OAAO,oBAAIzC,uBAAAA,IAAK0C,KAAK,YAAlC1C,QAAsC;;YAG1CwB,yBACC;;kCACE,KAACvC;wBAAWyC,SAAQ;wBAAQU,OAAM;wBAAQT,IAAI;4BAAEC,IAAI;wBAAI;wBAAGS,MAAK;2CAC7DrC,uBAAAA,IAAK0C,KAAK,oBAAI;;kCAEjB,KAAC7D;wBAAOsD,MAAK;wBAAQR,IAAI;4BAAEC,IAAI;wBAAE;wBAAGe,UAAUpC;wBAAMqC,SAAStC;kCAC1D;;;;;;AAMb"}
@@ -1,6 +1,9 @@
1
1
  import { type AglynOrgBilling } from '@aglyn/aglyn';
2
- import { type AssistBuildDraftLink } from '../model/assist-follow-up';
2
+ import { type AssistEditProposal } from '../model/assist-edit';
3
+ import { type AssistBuildProposal } from '../model/assist-build';
4
+ import { type AssistBuildDraft, type AssistBuildDraftLink } from '../model/assist-follow-up';
3
5
  import type { AiJobSummary } from '../model/ai-jobs.types';
6
+ import { type AssistPageChangeProposal } from '../model/assist-page-change';
4
7
  /**
5
8
  * Aglyn Assist (AGL-1860, phase 1 — answer + guide): the floating chat
6
9
  * helper mounted on every authenticated console page. Docs-grounded answers
@@ -34,6 +37,82 @@ interface AssistDocLink {
34
37
  title: string;
35
38
  url: string;
36
39
  }
40
+ /**
41
+ * A level-2 proposal, exactly as the server resolved it (AGL-1988).
42
+ *
43
+ * Every field here is inert. There is no method, no endpoint and no body,
44
+ * because the server type has none: the assistant proposes, the user
45
+ * confirms, and confirming NAVIGATES. The destination form's own submit
46
+ * button stays the only thing that writes.
47
+ */
48
+ interface AssistProposal {
49
+ id: string;
50
+ label: string;
51
+ outcome: string;
52
+ href: string;
53
+ values: Array<{
54
+ name: string;
55
+ value: string;
56
+ }>;
57
+ prefill: boolean;
58
+ /** The draft an open-draft proposal names (AGL-3616), as the server held it. */
59
+ draft?: AssistBuildDraft;
60
+ /**
61
+ * The request a confirmed open-draft proposal asks again once the draft's
62
+ * canvas is open; `href` is then that draft's own Besigner, from the
63
+ * panel's own record of its build.
64
+ */
65
+ followUp?: string;
66
+ }
67
+ interface AssistMessage {
68
+ role: 'user' | 'assistant';
69
+ text: string;
70
+ exchangeId?: string | null;
71
+ feedback?: 'up' | 'down';
72
+ docs?: AssistDocLink[];
73
+ proposal?: AssistProposal | null;
74
+ /** Set once the user acts on or waves away the card, so it does not linger. */
75
+ proposalResolved?: boolean;
76
+ /**
77
+ * A level-3 edit proposal, exactly as the server validated it (AGL-2906):
78
+ * operations for the open canvas, applied only when the author presses
79
+ * Apply, and never by a request.
80
+ */
81
+ edit?: AssistEditProposal | null;
82
+ /** What became of the edit card: applied, waved away, or refused with a reason. */
83
+ editOutcome?: {
84
+ kind: 'applied';
85
+ } | {
86
+ kind: 'dismissed';
87
+ } | {
88
+ kind: 'failed';
89
+ message: string;
90
+ };
91
+ /**
92
+ * A build proposed from this turn (AGL-3616): the panel starts its one
93
+ * `build` job when the turn ends, and the card shows that job's plan to
94
+ * confirm, then where it stands.
95
+ */
96
+ build?: AssistBuildProposal | null;
97
+ /** The job the build started, as last seen. */
98
+ buildJob?: AiJobSummary | null;
99
+ /** Why the build could not be planned or confirmed. */
100
+ buildNotice?: string | null;
101
+ /**
102
+ * A later turn's plan replaced this one before it was confirmed (AGL-4116):
103
+ * its job was canceled, and the card gives way to one line.
104
+ */
105
+ buildReplaced?: boolean;
106
+ /**
107
+ * A change to a page the site already has (AGL-4116): the panel starts its
108
+ * `edit` job when the turn ends, and the card links the draft it makes.
109
+ */
110
+ pageChange?: AssistPageChangeProposal | null;
111
+ /** The edit job the change started, as last seen. */
112
+ pageChangeJob?: AiJobSummary | null;
113
+ /** Why the change could not be started. */
114
+ pageChangeNotice?: string | null;
115
+ }
37
116
  /**
38
117
  * The drafts this thread's builds made that open in the Besigner, newest
39
118
  * build first (AGL-3616): what a follow-up such as "make the about page
@@ -42,6 +121,31 @@ interface AssistDocLink {
42
121
  export declare function assistThreadDraftLinks(messages: ReadonlyArray<{
43
122
  buildJob?: AiJobSummary | null;
44
123
  }>, orgSlug: string): AssistBuildDraftLink[];
124
+ /**
125
+ * The builds in a thread whose plan is still waiting on the person
126
+ * (AGL-4116): queued, being planned, or planned and not yet confirmed. A new
127
+ * plan in the same thread replaces them, so a conversation that keeps
128
+ * changing a plan holds one plan, not one per message.
129
+ */
130
+ export declare function assistUnconfirmedBuilds(messages: ReadonlyArray<Pick<AssistMessage, 'build' | 'buildJob' | 'buildReplaced'>>): Array<{
131
+ index: number;
132
+ jobId: string;
133
+ }>;
134
+ /** What a plan a later one replaced says in its card's place (AGL-4116). */
135
+ export declare const ASSIST_BUILD_REPLACED_COPY = "Replaced by the updated plan below. Nothing from this one was built.";
136
+ /**
137
+ * The thread a question belongs to: one per site, and one for the
138
+ * workspace's own pages (AGL-4116). A workspace-wide thread carried one
139
+ * site's request into a build on another site, because the history that
140
+ * rides each question is the thread's last turns.
141
+ */
142
+ export declare function assistThreadKey(orgId: string, hostId: string | null | undefined): string;
143
+ /**
144
+ * The AI jobs page of the site a console page is on (AGL-4116), or `null`
145
+ * off a site: `/{orgSlug}/hosts/{site}/ai-jobs`, the site named as the
146
+ * address names it.
147
+ */
148
+ export declare function assistSiteAiJobsHref(pathname: string | null | undefined, orgSlug: string | null | undefined, hostId: string | null | undefined): string | null;
45
149
  /**
46
150
  * Minimal renderer for assistant text: markdown links and bare URLs become
47
151
  * links (internal root-relative paths ride AppLink, external open in a new