@aglyn/plugins-ai 1.27.0 → 1.29.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 (48) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-credits-prompt.component.js +4 -1
  3. package/src/lib/components/ai-credits-prompt.component.js.map +1 -1
  4. package/src/lib/components/ai-site-import-job.component.js +5 -2
  5. package/src/lib/components/ai-site-import-job.component.js.map +1 -1
  6. package/src/lib/components/ai-site-start-card.component.js +6 -3
  7. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  8. package/src/lib/components/assist-build-card.component.js +4 -1
  9. package/src/lib/components/assist-build-card.component.js.map +1 -1
  10. package/src/lib/components/assist-edit-canvas.d.ts +12 -0
  11. package/src/lib/components/assist-edit-canvas.js +38 -7
  12. package/src/lib/components/assist-edit-canvas.js.map +1 -1
  13. package/src/lib/components/assist-jobs-drawer.component.js +4 -1
  14. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  15. package/src/lib/components/assist-panel.component.js +5 -2
  16. package/src/lib/components/assist-panel.component.js.map +1 -1
  17. package/src/lib/declarations.server.js +17 -0
  18. package/src/lib/declarations.server.js.map +1 -1
  19. package/src/lib/jobs/ai-job-drafts.d.ts +5 -11
  20. package/src/lib/jobs/ai-job-drafts.js +8 -25
  21. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  22. package/src/lib/jobs/ai-job-edit-step.d.ts +95 -5
  23. package/src/lib/jobs/ai-job-edit-step.js +88 -17
  24. package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
  25. package/src/lib/model/ai-edit-job.d.ts +27 -0
  26. package/src/lib/model/ai-edit-job.js +45 -23
  27. package/src/lib/model/ai-edit-job.js.map +1 -1
  28. package/src/lib/model/ai-layout-menus.d.ts +10 -0
  29. package/src/lib/model/ai-layout-menus.js +23 -2
  30. package/src/lib/model/ai-layout-menus.js.map +1 -1
  31. package/src/lib/model/assist-edit.d.ts +2 -0
  32. package/src/lib/model/assist-edit.js.map +1 -1
  33. package/src/lib/runtime/ai-node-tree.d.ts +25 -1
  34. package/src/lib/runtime/ai-node-tree.js +39 -14
  35. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  36. package/src/lib/runtime/ai-palette.generated.js +84 -2
  37. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  38. package/src/lib/server/ai-page-content.d.ts +83 -0
  39. package/src/lib/server/ai-page-content.js +765 -0
  40. package/src/lib/server/ai-page-content.js.map +1 -0
  41. package/src/lib/server/ai-usage.js +7 -1
  42. package/src/lib/server/ai-usage.js.map +1 -1
  43. package/src/lib/server/assist-edit.d.ts +136 -1
  44. package/src/lib/server/assist-edit.js +124 -47
  45. package/src/lib/server/assist-edit.js.map +1 -1
  46. package/src/lib/usage/ai-usage-wire.d.ts +15 -0
  47. package/src/lib/usage/ai-usage-wire.js +21 -0
  48. package/src/lib/usage/ai-usage-wire.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/assist-build-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 { HelpTip } from '@aglyn/shared-ui-jsx'\nimport { Alert, Box, Button, CircularProgress, Paper, Stack, Typography } from '@mui/material'\nimport { useEffect, useRef, useState } from 'react'\nimport { aiBuildCanRetry, aiBuildItemRows, aiBuildOutcomeLine, aiBuildRetryCreditRange } from '../model/ai-build-progress'\nimport { aiCreditRangeText, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { AiCreditsPromptNotice } from './ai-credits-prompt.component'\nimport { aiCreditsBillingHref, aiStoreFinishHostId, aiStoreFinishLinks } from './ai-job-links'\nimport { AiStoreFinishCard } from './ai-store-finish-card.component'\nimport { AI_JOB_TERMINAL_STATUSES, type AiJobSummary } from '../model/ai-jobs.types'\nimport type { AssistBuildProposal } from '../model/assist-build'\nimport { followAiJobEvents } from './ai-job-events'\nimport { AiJobInputForm } from './ai-job-input-form.component'\nimport { AiJobPlan } from './ai-job-plan.component'\nimport { resumeAiJobRequest, type AiJobResumeOptions } from './ai-job-requests'\nimport { openAiJobs } from './ai-jobs-store'\n\n/**\n * The one card a build proposed in the chat becomes (AGL-3616): while its\n * job plans, a line saying so; then the job's own plan card, with its one\n * price and Confirm — the same `AiJobPlan` the AI jobs drawer shows, so\n * confirming here and there is one door; then where the build stands, item\n * by item, with AI jobs a click away. The job itself is started by the\n * panel, once, when the turn that proposed it ends; this card only follows\n * it, so re-rendering a stored thread never starts a second build.\n */\nexport interface AssistBuildCardProps {\n proposal: AssistBuildProposal\n /** The job the proposal started, as last seen; `null` while it is being created. */\n job: AiJobSummary | null\n /** Why the job could not be created or confirmed, when it could not. */\n notice: string | null\n orgId: string\n user: MaybeTokenSource\n staff?: boolean\n /** The job as it moved, for the thread to keep. */\n onJob: (job: AiJobSummary) => void\n onNotice: (notice: string | null) => void\n /** The workspace's path slug, for Upgrade on a Free build past what is left or paused (AGL-3722). */\n orgSlug?: string | null\n}\n\n/** The card's own section of the Assist builds guide (AGL-3660). */\nconst ASSIST_BUILD_HELP = pluginDocsHelp('aiAssistBuilds', {\n anchor: '#the-plan-card',\n excerpt:\n 'What one request will build, item by item, with its estimate. Nothing is built until you choose Confirm plan, and what it makes is a draft.',\n})\n\nconst ITEM_STATES = { done: 'built', active: 'building', waiting: 'waiting', failed: 'failed', skipped: 'not built' } as const\n\nexport function AssistBuildCard({\n proposal,\n job,\n notice,\n orgId,\n user,\n staff = false,\n onJob,\n onNotice,\n orgSlug,\n}: AssistBuildCardProps): JSX.Element {\n const [busy, setBusy] = useState(false)\n // A Free Try again past what is left (AGL-3722): its prompt, until chosen.\n const [retryPrompt, setRetryPrompt] = useState<AiCreditsPrompt | null>(null)\n const userRef = useRef(user)\n userRef.current = user\n const onJobRef = useRef(onJob)\n onJobRef.current = onJob\n\n // Follow a job that is still planning or building; a plan waiting for its\n // confirmation and a settled job need nothing more from the stream.\n // A build the meter paused (AGL-3722) waits for Resume, not the stream.\n const paused = job?.status === 'needs_input'\n const following = Boolean(\n job && !AI_JOB_TERMINAL_STATUSES.includes(job.status) && job.status !== 'needs_review' && !paused,\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 resume = async (target: AiJobSummary, options?: AiJobResumeOptions) => {\n setBusy(true)\n onNotice(null)\n setRetryPrompt(null)\n const decision = await resumeAiJobRequest(user, orgId, target, options)\n if (decision.job) onJob(decision.job)\n // A Free Try again past what is left asks with its choices; a plan's\n // card draws its own from the job the door answered with.\n if (decision.credits && options?.retry) setRetryPrompt(decision.credits)\n else if (decision.error && !(decision.credits && target.status === 'needs_review')) onNotice(decision.error)\n setBusy(false)\n }\n const retryRange = job && aiBuildCanRetry(job) ? aiBuildRetryCreditRange(job) : null\n\n const settled = job ? AI_JOB_TERMINAL_STATUSES.includes(job.status) : false\n const outcome = job ? aiBuildOutcomeLine(job) : null\n // A build that made the site a store (AGL-3676) ends with what is left before it sells.\n const storeFinish = job && orgSlug ? aiStoreFinishLinks(job, orgSlug) : null\n return (\n <Paper variant=\"outlined\" sx={{ mt: 1, p: 1.5 }} aria-label=\"Build plan\">\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'center' }}>\n <Typography variant=\"subtitle2\">{proposal.summary}</Typography>\n <HelpTip {...ASSIST_BUILD_HELP} />\n </Stack>\n {!job && !notice && (\n <Stack direction=\"row\" spacing={1} sx={{ mt: 0.5, alignItems: 'center' }}>\n <CircularProgress size={14} />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Planning what to build on this site…'}\n </Typography>\n </Stack>\n )}\n {notice && (\n <Typography variant=\"body2\" color=\"error\" sx={{ mt: 0.5 }} role=\"alert\">\n {notice}\n </Typography>\n )}\n {job && job.status === 'needs_review' && (\n <AiJobPlan\n job={job}\n busy={busy}\n staff={staff}\n user={user}\n orgSlug={orgSlug}\n onResume={(target, options) => void resume(target, options)}\n />\n )}\n {job && 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 {job.plan?.status === 'confirmed'\n ? 'Building each part in turn. What it makes is an unpublished draft unless you chose to publish.'\n : 'Planning what to build on this site…'}\n </Typography>\n </Stack>\n )}\n {job && (job.items?.length ?? 0) > 0 && job.status !== 'needs_review' && (\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_STATES[row.state]}`}\n {row.detail ? `. ${row.detail}` : ''}\n </Typography>\n ))}\n </Box>\n )}\n {job && paused && job.input ? (\n // A plan that needs an ID only the person has (AGL-3978): asked here,\n // and answered back onto the plan card.\n <AiJobInputForm job={{ ...job, input: job.input }} orgId={orgId} user={user} onJob={onJob} />\n ) : job && paused && (\n // Out of credits mid-build (AGL-3722): paused, never failed. What is\n // built is kept, and Resume carries on from the next item.\n <Alert\n severity=\"warning\"\n sx={{ mt: 0.5 }}\n action={\n <Stack direction=\"row\" spacing={1}>\n {orgSlug ? (\n <Button color=\"inherit\" size=\"small\" href={aiCreditsBillingHref(orgSlug)}>\n {'Upgrade'}\n </Button>\n ) : null}\n <Button color=\"inherit\" size=\"small\" disabled={busy} onClick={() => void resume(job)}>\n {'Resume'}\n </Button>\n </Stack>\n }\n >\n {`Paused. ${job.error ?? 'Your AI credits ran out.'} What is built so far is kept, and Resume carries on from the next item once you upgrade or your credits renew.`}\n </Alert>\n )}\n {job && retryPrompt && (\n <AiCreditsPromptNotice\n prompt={retryPrompt}\n noun=\"build\"\n orgSlug={orgSlug}\n busy={busy}\n onBuildWhatFits={() => void resume(job, { retry: 'failed-items', creditsConfirmed: true })}\n />\n )}\n {settled && (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {outcome ?? job?.error ?? ''}\n </Typography>\n )}\n {storeFinish && (\n <Box sx={{ mt: 1 }}>\n <AiStoreFinishCard steps={storeFinish} hostId={job ? aiStoreFinishHostId(job) : null} />\n </Box>\n )}\n {job && (\n <Stack direction=\"row\" spacing={1} sx={{ mt: 1 }}>\n {job && aiBuildCanRetry(job) && (\n <Button size=\"small\" variant=\"contained\" disabled={busy} onClick={() => void resume(job, { retry: 'failed-items' })}>\n {retryRange ? `Try again what failed · ${aiCreditRangeText(retryRange)}` : 'Try again what failed'}\n </Button>\n )}\n <Button size=\"small\" onClick={() => openAiJobs({ jobId: job.id })}>\n {'Open in AI jobs'}\n </Button>\n </Stack>\n )}\n </Paper>\n )\n}\n"],"names":["pluginDocsHelp","HelpTip","Alert","Box","Button","CircularProgress","Paper","Stack","Typography","useEffect","useRef","useState","aiBuildCanRetry","aiBuildItemRows","aiBuildOutcomeLine","aiBuildRetryCreditRange","aiCreditRangeText","AiCreditsPromptNotice","aiCreditsBillingHref","aiStoreFinishHostId","aiStoreFinishLinks","AiStoreFinishCard","AI_JOB_TERMINAL_STATUSES","followAiJobEvents","AiJobInputForm","AiJobPlan","resumeAiJobRequest","openAiJobs","ASSIST_BUILD_HELP","anchor","excerpt","ITEM_STATES","done","active","waiting","failed","skipped","AssistBuildCard","proposal","job","notice","orgId","user","staff","onJob","onNotice","orgSlug","outcome","busy","setBusy","retryPrompt","setRetryPrompt","userRef","current","onJobRef","paused","status","following","Boolean","includes","jobId","id","controller","AbortController","signal","next","abort","resume","target","options","decision","credits","retry","error","retryRange","settled","storeFinish","variant","sx","mt","p","aria-label","direction","spacing","alignItems","summary","size","color","role","onResume","plan","items","length","component","m","pl","map","row","data-item-state","state","label","detail","slot","input","severity","action","href","disabled","onClick","prompt","noun","onBuildWhatFits","creditsConfirmed","steps","hostId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAGA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,SAASC,KAAK,EAAEC,GAAG,EAAEC,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AAC9F,SAASC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AACnD,SAASC,eAAe,EAAEC,eAAe,EAAEC,kBAAkB,EAAEC,uBAAuB,QAAQ,gCAA4B;AAC1H,SAASC,iBAAiB,QAA8B,iCAA6B;AACrF,SAASC,qBAAqB,QAAQ,mCAA+B;AACrE,SAASC,oBAAoB,EAAEC,mBAAmB,EAAEC,kBAAkB,QAAQ,oBAAgB;AAC9F,SAASC,iBAAiB,QAAQ,sCAAkC;AACpE,SAASC,wBAAwB,QAA2B,4BAAwB;AAEpF,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,cAAc,QAAQ,mCAA+B;AAC9D,SAASC,SAAS,QAAQ,6BAAyB;AACnD,SAASC,kBAAkB,QAAiC,uBAAmB;AAC/E,SAASC,UAAU,QAAQ,qBAAiB;AA2B5C,kEAAkE,GAClE,MAAMC,oBAAoB5B,eAAe,kBAAkB;IACzD6B,QAAQ;IACRC,SACE;AACJ;AAEA,MAAMC,cAAc;IAAEC,MAAM;IAASC,QAAQ;IAAYC,SAAS;IAAWC,QAAQ;IAA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qBAAqB4B;sCAC7D;6BAED;sCACJ,KAAC1C;4BAAOmF,OAAM;4BAAUD,MAAK;4BAAQqB,UAAU3D;4BAAM4D,SAAS,IAAM,KAAKzC,OAAO5B;sCAC7E;;;;0BAKN,CAAC,QAAQ,GAAEA,aAAAA,IAAIkC,KAAK,YAATlC,aAAa,2BAA2B,+GAA+G,CAAC;;YAGvKA,OAAOW,6BACN,KAACjC;gBACC4F,QAAQ3D;gBACR4D,MAAK;gBACLhE,SAASA;gBACTE,MAAMA;gBACN+D,iBAAiB,IAAM,KAAK5C,OAAO5B,KAAK;wBAAEiC,OAAO;wBAAgBwC,kBAAkB;oBAAK;;YAG3FrC,yBACC,KAACnE;gBAAWqE,SAAQ;gBAAQC,IAAI;oBAAEC,IAAI;gBAAI;2BACvChC,QAAAA,kBAAAA,UAAWR,uBAAAA,IAAKkC,KAAK,YAArB1B,QAAyB;;YAG7B6B,6BACC,KAACzE;gBAAI2E,IAAI;oBAAEC,IAAI;gBAAE;0BACf,cAAA,KAAC1D;oBAAkB4F,OAAOrC;oBAAasC,QAAQ3E,MAAMpB,oBAAoBoB,OAAO;;;YAGnFA,qBACC,MAAChC;gBAAM2E,WAAU;gBAAMC,SAAS;gBAAGL,IAAI;oBAAEC,IAAI;gBAAE;;oBAC5CxC,OAAO3B,gBAAgB2B,sBACtB,KAACnC;wBAAOkF,MAAK;wBAAQT,SAAQ;wBAAY8B,UAAU3D;wBAAM4D,SAAS,IAAM,KAAKzC,OAAO5B,KAAK;gCAAEiC,OAAO;4BAAe;kCAC9GE,aAAa,CAAC,wBAAwB,EAAE1D,kBAAkB0D,aAAa,GAAG;;kCAG/E,KAACtE;wBAAOkF,MAAK;wBAAQsB,SAAS,IAAMjF,WAAW;gCAAEiC,OAAOrB,IAAIsB,EAAE;4BAAC;kCAC5D;;;;;;AAMb"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/assist-build-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 { HelpTip } from '@aglyn/shared-ui-jsx'\nimport { useBuyingHidden } from '@aglyn/shared-ui-jsx/contexts/buying-hidden.context'\nimport { Alert, Box, Button, CircularProgress, Paper, Stack, Typography } from '@mui/material'\nimport { useEffect, useRef, useState } from 'react'\nimport { aiBuildCanRetry, aiBuildItemRows, aiBuildOutcomeLine, aiBuildRetryCreditRange } from '../model/ai-build-progress'\nimport { aiCreditRangeText, type AiCreditsPrompt } from '../model/ai-credit-estimate'\nimport { AiCreditsPromptNotice } from './ai-credits-prompt.component'\nimport { aiCreditsBillingHref, aiStoreFinishHostId, aiStoreFinishLinks } from './ai-job-links'\nimport { AiStoreFinishCard } from './ai-store-finish-card.component'\nimport { AI_JOB_TERMINAL_STATUSES, type AiJobSummary } from '../model/ai-jobs.types'\nimport type { AssistBuildProposal } from '../model/assist-build'\nimport { followAiJobEvents } from './ai-job-events'\nimport { AiJobInputForm } from './ai-job-input-form.component'\nimport { AiJobPlan } from './ai-job-plan.component'\nimport { resumeAiJobRequest, type AiJobResumeOptions } from './ai-job-requests'\nimport { openAiJobs } from './ai-jobs-store'\n\n/**\n * The one card a build proposed in the chat becomes (AGL-3616): while its\n * job plans, a line saying so; then the job's own plan card, with its one\n * price and Confirm — the same `AiJobPlan` the AI jobs drawer shows, so\n * confirming here and there is one door; then where the build stands, item\n * by item, with AI jobs a click away. The job itself is started by the\n * panel, once, when the turn that proposed it ends; this card only follows\n * it, so re-rendering a stored thread never starts a second build.\n */\nexport interface AssistBuildCardProps {\n proposal: AssistBuildProposal\n /** The job the proposal started, as last seen; `null` while it is being created. */\n job: AiJobSummary | null\n /** Why the job could not be created or confirmed, when it could not. */\n notice: string | null\n orgId: string\n user: MaybeTokenSource\n staff?: boolean\n /** The job as it moved, for the thread to keep. */\n onJob: (job: AiJobSummary) => void\n onNotice: (notice: string | null) => void\n /** The workspace's path slug, for Upgrade on a Free build past what is left or paused (AGL-3722). */\n orgSlug?: string | null\n}\n\n/** The card's own section of the Assist builds guide (AGL-3660). */\nconst ASSIST_BUILD_HELP = pluginDocsHelp('aiAssistBuilds', {\n anchor: '#the-plan-card',\n excerpt:\n 'What one request will build, item by item, with its estimate. Nothing is built until you choose Confirm plan, and what it makes is a draft.',\n})\n\nconst ITEM_STATES = { done: 'built', active: 'building', waiting: 'waiting', failed: 'failed', skipped: 'not built' } as const\n\nexport function AssistBuildCard({\n proposal,\n job,\n notice,\n orgId,\n user,\n staff = false,\n onJob,\n onNotice,\n orgSlug,\n}: AssistBuildCardProps): JSX.Element {\n const [busy, setBusy] = useState(false)\n // An app build for store review leaves out every way to buy more.\n const buyingHidden = useBuyingHidden()\n // A Free Try again past what is left (AGL-3722): its prompt, until chosen.\n const [retryPrompt, setRetryPrompt] = useState<AiCreditsPrompt | null>(null)\n const userRef = useRef(user)\n userRef.current = user\n const onJobRef = useRef(onJob)\n onJobRef.current = onJob\n\n // Follow a job that is still planning or building; a plan waiting for its\n // confirmation and a settled job need nothing more from the stream.\n // A build the meter paused (AGL-3722) waits for Resume, not the stream.\n const paused = job?.status === 'needs_input'\n const following = Boolean(\n job && !AI_JOB_TERMINAL_STATUSES.includes(job.status) && job.status !== 'needs_review' && !paused,\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 resume = async (target: AiJobSummary, options?: AiJobResumeOptions) => {\n setBusy(true)\n onNotice(null)\n setRetryPrompt(null)\n const decision = await resumeAiJobRequest(user, orgId, target, options)\n if (decision.job) onJob(decision.job)\n // A Free Try again past what is left asks with its choices; a plan's\n // card draws its own from the job the door answered with.\n if (decision.credits && options?.retry) setRetryPrompt(decision.credits)\n else if (decision.error && !(decision.credits && target.status === 'needs_review')) onNotice(decision.error)\n setBusy(false)\n }\n const retryRange = job && aiBuildCanRetry(job) ? aiBuildRetryCreditRange(job) : null\n\n const settled = job ? AI_JOB_TERMINAL_STATUSES.includes(job.status) : false\n const outcome = job ? aiBuildOutcomeLine(job) : null\n // A build that made the site a store (AGL-3676) ends with what is left before it sells.\n const storeFinish = job && orgSlug ? aiStoreFinishLinks(job, orgSlug) : null\n return (\n <Paper variant=\"outlined\" sx={{ mt: 1, p: 1.5 }} aria-label=\"Build plan\">\n <Stack direction=\"row\" spacing={0.5} sx={{ alignItems: 'center' }}>\n <Typography variant=\"subtitle2\">{proposal.summary}</Typography>\n <HelpTip {...ASSIST_BUILD_HELP} />\n </Stack>\n {!job && !notice && (\n <Stack direction=\"row\" spacing={1} sx={{ mt: 0.5, alignItems: 'center' }}>\n <CircularProgress size={14} />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Planning what to build on this site…'}\n </Typography>\n </Stack>\n )}\n {notice && (\n <Typography variant=\"body2\" color=\"error\" sx={{ mt: 0.5 }} role=\"alert\">\n {notice}\n </Typography>\n )}\n {job && job.status === 'needs_review' && (\n <AiJobPlan\n job={job}\n busy={busy}\n staff={staff}\n user={user}\n orgSlug={orgSlug}\n onResume={(target, options) => void resume(target, options)}\n />\n )}\n {job && 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 {job.plan?.status === 'confirmed'\n ? 'Building each part in turn. What it makes is an unpublished draft unless you chose to publish.'\n : 'Planning what to build on this site…'}\n </Typography>\n </Stack>\n )}\n {job && (job.items?.length ?? 0) > 0 && job.status !== 'needs_review' && (\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_STATES[row.state]}`}\n {row.detail ? `. ${row.detail}` : ''}\n </Typography>\n ))}\n </Box>\n )}\n {job && paused && job.input ? (\n // A plan that needs an ID only the person has (AGL-3978): asked here,\n // and answered back onto the plan card.\n <AiJobInputForm job={{ ...job, input: job.input }} orgId={orgId} user={user} onJob={onJob} />\n ) : job && paused && (\n // Out of credits mid-build (AGL-3722): paused, never failed. What is\n // built is kept, and Resume carries on from the next item.\n <Alert\n severity=\"warning\"\n sx={{ mt: 0.5 }}\n action={\n <Stack direction=\"row\" spacing={1}>\n {orgSlug && !buyingHidden ? (\n <Button color=\"inherit\" size=\"small\" href={aiCreditsBillingHref(orgSlug)}>\n {'Upgrade'}\n </Button>\n ) : null}\n <Button color=\"inherit\" size=\"small\" disabled={busy} onClick={() => void resume(job)}>\n {'Resume'}\n </Button>\n </Stack>\n }\n >\n {`Paused. ${job.error ?? 'Your AI credits ran out.'} What is built so far is kept, and Resume carries on from the next item once you upgrade or your credits renew.`}\n </Alert>\n )}\n {job && retryPrompt && (\n <AiCreditsPromptNotice\n prompt={retryPrompt}\n noun=\"build\"\n orgSlug={orgSlug}\n busy={busy}\n onBuildWhatFits={() => void resume(job, { retry: 'failed-items', creditsConfirmed: true })}\n />\n )}\n {settled && (\n <Typography variant=\"body2\" sx={{ mt: 0.5 }}>\n {outcome ?? job?.error ?? ''}\n </Typography>\n )}\n {storeFinish && (\n <Box sx={{ mt: 1 }}>\n <AiStoreFinishCard steps={storeFinish} hostId={job ? aiStoreFinishHostId(job) : null} />\n </Box>\n )}\n {job && (\n <Stack direction=\"row\" spacing={1} sx={{ mt: 1 }}>\n {job && aiBuildCanRetry(job) && (\n <Button size=\"small\" variant=\"contained\" disabled={busy} onClick={() => void resume(job, { retry: 'failed-items' })}>\n {retryRange ? `Try again what failed · ${aiCreditRangeText(retryRange)}` : 'Try again what failed'}\n </Button>\n )}\n <Button size=\"small\" onClick={() => openAiJobs({ jobId: job.id })}>\n {'Open in AI jobs'}\n </Button>\n </Stack>\n )}\n </Paper>\n )\n}\n"],"names":["pluginDocsHelp","HelpTip","useBuyingHidden","Alert","Box","Button","CircularProgress","Paper","Stack","Typography","useEffect","useRef","useState","aiBuildCanRetry","aiBuildItemRows","aiBuildOutcomeLine","aiBuildRetryCreditRange","aiCreditRangeText","AiCreditsPromptNotice","aiCreditsBillingHref","aiStoreFinishHostId","aiStoreFinishLinks","AiStoreFinishCard","AI_JOB_TERMINAL_STATUSES","followAiJobEvents","AiJobInputForm","AiJobPlan","resumeAiJobRequest","openAiJobs","ASSIST_BUILD_HELP","anchor","excerpt","ITEM_STATES","done","active","waiting","failed","skipped","AssistBuildCard","proposal","job","notice","orgId","user","staff","onJob","onNotice","orgSlug","outcome","busy","setBusy","buyingHidden","retryPrompt","setRetryPrompt","userRef","current","onJobRef","paused","status","following","Boolean","includes","jobId","id","controller","AbortController","signal","next","abort","resume","target","options","decision","credits","retry","error","retryRange","settled","storeFinish","variant","sx","mt","p","aria-label","direction","spacing","alignItems","summary","size","color","role","onResume","plan","items","length","component","m","pl","map","row","data-item-state","state","label","detail","slot","input","severity","action","href","disabled","onClick","prompt","noun","onBuildWhatFits","creditsConfirmed","steps","hostId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAGA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,OAAO,QAAQ,uBAAsB;AAC9C,SAASC,eAAe,QAAQ,sDAAqD;AACrF,SAASC,KAAK,EAAEC,GAAG,EAAEC,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAA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AAA,kBAAAA,UAAWR,uBAAAA,IAAKmC,KAAK,YAArB3B,QAAyB;;YAG7B8B,6BACC,KAAC1E;gBAAI4E,IAAI;oBAAEC,IAAI;gBAAE;0BACf,cAAA,KAAC3D;oBAAkB6F,OAAOrC;oBAAasC,QAAQ5E,MAAMpB,oBAAoBoB,OAAO;;;YAGnFA,qBACC,MAAChC;gBAAM4E,WAAU;gBAAMC,SAAS;gBAAGL,IAAI;oBAAEC,IAAI;gBAAE;;oBAC5CzC,OAAO3B,gBAAgB2B,sBACtB,KAACnC;wBAAOmF,MAAK;wBAAQT,SAAQ;wBAAY8B,UAAU5D;wBAAM6D,SAAS,IAAM,KAAKzC,OAAO7B,KAAK;gCAAEkC,OAAO;4BAAe;kCAC9GE,aAAa,CAAC,wBAAwB,EAAE3D,kBAAkB2D,aAAa,GAAG;;kCAG/E,KAACvE;wBAAOmF,MAAK;wBAAQsB,SAAS,IAAMlF,WAAW;gCAAEkC,OAAOtB,IAAIuB,EAAE;4BAAC;kCAC5D;;;;;;AAMb"}
@@ -119,12 +119,24 @@ export type AssistEditCheck = {
119
119
  reason: AssistEditRefusal;
120
120
  message: string;
121
121
  };
122
+ /** The elements one insert added, as the canvas named them. */
123
+ export interface AssistEditInserted {
124
+ /** The insert's position among the proposal's ops. */
125
+ op: number;
126
+ /** Every element it added, depth first in the order they read, its root first. */
127
+ ids: string[];
128
+ }
122
129
  export type AssistEditApplyResult = {
123
130
  ok: true;
124
131
  /** Applied ops, counted by kind for the activity row. */
125
132
  opCounts: Record<string, number>;
126
133
  /** Editor fields staged, as the editor keys them. */
127
134
  staged: string[];
135
+ /**
136
+ * The ids the canvas gave the elements each insert added (AGL-4235),
137
+ * so a caller can name them in a later change. Absent with no insert.
138
+ */
139
+ inserted?: AssistEditInserted[];
128
140
  } | {
129
141
  ok: false;
130
142
  reason: AssistEditRefusal;
@@ -509,6 +509,8 @@ const STALE = {
509
509
  sx: _extends({}, node.sx)
510
510
  } : {}, node.hidden ? {
511
511
  hidden: true
512
+ } : {}, node.name ? {
513
+ name: node.name
512
514
  } : {}, {
513
515
  nodes: node.nodes.filter((child)=>op.nodes[child] && !visited.has(child)).map((child)=>build(child))
514
516
  });
@@ -520,7 +522,24 @@ function live(canvas, id) {
520
522
  if (!node) throw new Error(`element ${id} is no longer on the canvas`);
521
523
  return node;
522
524
  }
523
- function applyOne(canvas, op) {
525
+ /** A subtree's ids, depth first in child order, its root first. */ function subtreeInOrder(canvas, rootId) {
526
+ const ids = [];
527
+ const stack = [
528
+ rootId
529
+ ];
530
+ while(stack.length){
531
+ var _ref;
532
+ var _canvas_getNode;
533
+ const id = stack.pop();
534
+ if (ids.includes(id) || !canvas.getNode(id)) continue;
535
+ ids.push(id);
536
+ stack.push(...[
537
+ ...(_ref = (_canvas_getNode = canvas.getNode(id)) == null ? void 0 : _canvas_getNode.nodes) != null ? _ref : []
538
+ ].reverse());
539
+ }
540
+ return ids;
541
+ }
542
+ /** Applies one op; an insert answers the ids of the elements it added. */ function applyOne(canvas, op) {
524
543
  switch(op.op){
525
544
  case 'updateProps':
526
545
  {
@@ -569,9 +588,11 @@ function applyOne(canvas, op) {
569
588
  return;
570
589
  }
571
590
  case 'insertSubtree':
572
- var _op_index1;
573
- canvas.addNodeFromNested(nestSubtree(op), live(canvas, op.parentId), (_op_index1 = op.index) != null ? _op_index1 : NaN);
574
- return;
591
+ {
592
+ var _op_index1;
593
+ const added = canvas.addNodeFromNested(nestSubtree(op), live(canvas, op.parentId), (_op_index1 = op.index) != null ? _op_index1 : NaN);
594
+ return (added == null ? void 0 : added.$id) ? subtreeInOrder(canvas, added.$id) : [];
595
+ }
575
596
  case 'setSeo':
576
597
  case 'saveAsComponent':
577
598
  // Both are applied outside the canvas batch: search fields are staged
@@ -647,10 +668,18 @@ function applyOne(canvas, op) {
647
668
  if (check.ok === false) return check;
648
669
  const open = session;
649
670
  const canvasOps = proposal.ops.filter((op)=>op.op !== 'setSeo' && op.op !== 'saveAsComponent');
671
+ const inserted = [];
650
672
  if (canvasOps.length) {
651
673
  try {
652
674
  canvas.batch(()=>{
653
- for (const op of canvasOps)applyOne(canvas, op);
675
+ proposal.ops.forEach((op, position)=>{
676
+ if (op.op === 'setSeo' || op.op === 'saveAsComponent') return;
677
+ const ids = applyOne(canvas, op);
678
+ if (ids) inserted.push({
679
+ op: position,
680
+ ids
681
+ });
682
+ });
654
683
  });
655
684
  } catch (error) {
656
685
  console.error('assist edit refused by the canvas', error);
@@ -670,11 +699,13 @@ function applyOne(canvas, op) {
670
699
  }
671
700
  staged.push(...stageEditorSessionFields(open, values).staged);
672
701
  }
673
- return {
702
+ return _extends({
674
703
  ok: true,
675
704
  opCounts: assistEditOpCounts(proposal.ops),
676
705
  staged
677
- };
706
+ }, inserted.length ? {
707
+ inserted
708
+ } : {});
678
709
  }
679
710
  /**
680
711
  * Lands a proposal that saves the selection as a reusable component
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/assist-edit-canvas.ts"],"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 {\n screenSeoStageKey,\n type ScreenSeoTextField,\n} from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport {\n NODE_HIDE_IF_PROP,\n replaceSubtreeWithInstance,\n reusableComponentDefinitionFrom,\n} from '@aglyn/aglyn/app-utils/compose-reusable-components'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport {\n NODE_MAX_INTERACTIONS,\n upsertNodeInteraction,\n type NodeInteraction,\n} from '@aglyn/aglyn/app-utils/node-interactions'\nimport type {\n ReusableComponentProp,\n ReusableComponentPropValue,\n} from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport {\n stageEditorSessionFields,\n type EditorSession,\n} from '@aglyn/aglyn/plugin-manager/editor-sessions'\nimport {\n ASSIST_EDIT_CONTEXT_MAX_NODES,\n ASSIST_EDIT_CONTEXT_MAX_PROPS,\n ASSIST_EDIT_OUTLINE_TEXT_CHARS,\n ASSIST_EDIT_SELECTED_TEXT_CHARS,\n ASSIST_EDIT_WHOLE_MAX_NODES,\n assistEditOpCounts,\n type AssistEditCanvasContext,\n type AssistEditCanvasNode,\n type AssistEditInsertOp,\n type AssistEditInteractionSummary,\n type AssistEditOp,\n type AssistEditProposal,\n type AssistEditComponentProp,\n type AssistEditSaveAsComponentOp,\n} from '../model/assist-edit'\n\n/**\n * The edit rung's client half (AGL-2906): what the panel tells the server\n * about the open canvas, and how a confirmed proposal lands on it.\n *\n * Applying goes through the canvas's own guarded mutators — the same ones\n * the besigner's panels and the marketing appliers use — inside ONE\n * `batch`, so the whole proposal is one undo step and a guard that refuses\n * part-way leaves nothing behind. Every change is an unsaved edit on the\n * version the editor has open; saving it stays the author's act, with the\n * editor's own control. On a version the live site serves, that save writes\n * the page's draft and never the version, so a change lands there too and\n * reaches visitors only when the author publishes (AGL-4116).\n */\n\n/** A node as the canvas holds it — the fields this module reads. */\nexport interface AssistEditCanvasNodeLike {\n $id?: string\n componentId?: string\n parentId?: string | null\n nodes?: string[]\n name?: string\n props?: unknown\n sx?: unknown\n /** The element's own interactions (AGL-3603), as the canvas holds them. */\n interactions?: unknown\n}\n\n/**\n * The slice of the besigner canvas the edit rung reads and drives. Every\n * member is one `CanvasManager` already has, so the panel hands over the\n * canvas itself and a spec hands over a real one.\n */\nexport interface AssistEditCanvas {\n getNode(id: string): AssistEditCanvasNodeLike | undefined\n batch<T>(mutate: () => T): T\n updateNodeProps(node: any, props: any): void\n updateNodeFields(node: any, patch: any): void\n reparentNode(node: any, parent: any, index?: number): unknown\n deleteNode(node: any): unknown\n addNodeFromNested(nested: any, parent: any, index?: number): unknown\n nodeAcceptsChildren(node: any): boolean\n /** The whole document, which a component save reads its definition out of. */\n toJSON(): { nodes: Record<string, unknown> }\n /** The document after a save: the promoted subtree swapped for an instance. */\n applyNodes(nodes: any): unknown\n}\n\nconst UNDESCRIBED_PROP = /^(html|sx|style|className|dangerouslySetInnerHTML|on[A-Z].*)$/\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * An observable's own keys as a plain object. A canvas node's `props` and\n * `sx` are observable proxies, and a spread of one is how a merge silently\n * copies nothing.\n */\nfunction plain(value: unknown): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n if (!value || typeof value !== 'object') return out\n for (const key in value as Record<string, unknown>) {\n out[key] = (value as Record<string, unknown>)[key]\n }\n return out\n}\n\nfunction describeProps(\n raw: unknown,\n textChars: number,\n): Record<string, string | number | boolean> | undefined {\n const props: Record<string, string | number | boolean> = {}\n let kept = 0\n for (const [name, value] of Object.entries(plain(raw))) {\n if (kept >= ASSIST_EDIT_CONTEXT_MAX_PROPS) break\n if (UNDESCRIBED_PROP.test(name)) continue\n if (typeof value === 'string') {\n if (!value.trim()) continue\n props[name] = value.slice(0, textChars)\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n props[name] = value\n } else if (typeof value === 'boolean') {\n props[name] = value\n } else {\n continue\n }\n kept += 1\n }\n return kept ? props : undefined\n}\n\nfunction describeSx(raw: unknown): Record<string, unknown> | undefined {\n const sx: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(plain(raw))) {\n if (typeof value === 'string' || typeof value === 'number') sx[key] = value\n else if (isRecord(value)) sx[key] = plain(value)\n }\n return Object.keys(sx).length ? sx : undefined\n}\n\n/**\n * The selection's ancestors below the document root, top-level section first\n * and the selection last; null when its parents do not lead to the root,\n * which is not a chain the server can check.\n */\nfunction chainToRoot(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n selected: AssistEditCanvasNodeLike,\n): string[] | null {\n const chain: string[] = []\n const walked = new Set<string>()\n let current: AssistEditCanvasNodeLike | undefined = selected\n while (current?.$id && current.$id !== CANVAS_ROOT_ELEMENT_ID && !walked.has(current.$id)) {\n walked.add(current.$id)\n chain.unshift(current.$id)\n current = current.parentId ? canvas.getNode(current.parentId) : undefined\n }\n return current?.$id === CANVAS_ROOT_ELEMENT_ID ? chain : null\n}\n\n/** Elements one shape is taken over at most; a larger subtree is never called alike. */\nconst SHAPE_LIMIT = 200\n\n/**\n * How an element is built: its component and, in order, its children's —\n * what two cards of one row have in common whatever their text. Null past\n * `SHAPE_LIMIT` elements, or for a subtree that loops back on itself.\n */\nfunction shapeOf(canvas: Pick<AssistEditCanvas, 'getNode'>, rootId: string): string | null {\n let budget = SHAPE_LIMIT\n const walked = new Set<string>()\n const walk = (id: string): string | null => {\n const node = canvas.getNode(id)\n if (!node || walked.has(id) || --budget < 0) return null\n walked.add(id)\n const parts: string[] = []\n for (const child of node.nodes ?? []) {\n const part = walk(child)\n if (part === null) return null\n parts.push(part)\n }\n return `${String(node.componentId ?? '')}(${parts.join(',')})`\n }\n return walk(rootId)\n}\n\n/** Elements reachable from the document root through child lists, the root included. */\nfunction countElements(canvas: Pick<AssistEditCanvas, 'getNode'>): number {\n let count = 0\n const reached = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n const pending = [CANVAS_ROOT_ELEMENT_ID]\n while (pending.length) {\n const node = canvas.getNode(pending.pop() as string)\n if (!node) continue\n count += 1\n for (const child of node.nodes ?? []) {\n if (reached.has(child)) continue\n reached.add(child)\n pending.push(child)\n }\n }\n return count\n}\n\n/**\n * The canvas outline a question carries on the edit rung, in two tiers, until\n * the cap.\n *\n * Described in full, settings and all: the document root, the selection's\n * ancestors and the selection, the document's top-level sections, everything\n * inside the selection — what an edit to it changes — and its siblings.\n *\n * Described briefly, by place alone (`brief`): what surrounds that, so the\n * model knows it exists and asks for it rather than calling it missing —\n *\n * 1. what the selection's siblings hold, level by level (the icons beside a\n * selected link, in the card they share);\n * 2. the siblings of each ancestor below the top-level section, nearest\n * first (the other cards of the row, then what sits beside the row).\n *\n * An element built the same way as the selection, or as the ancestor it sits\n * beside, is marked `like` it and its contents are left out: one card\n * described, and every other card of the row says it holds the same.\n *\n * With nothing selected, it is the root, the top-level sections and one level\n * inside each: enough for a change to the page as a whole, and the prompt asks\n * for a selection before anything more specific.\n *\n * With `whole`, it is the whole document instead (AGL-4116), up to\n * `ASSIST_EDIT_WHOLE_MAX_NODES`: every element, in the order it reads on the\n * page, with its settings and its styles. That is what the chat in the\n * Besigner sends, so \"change the Get in touch button\" finds the button with\n * nothing selected. A document past the cap falls back to the two tiers.\n *\n * An element is only ever described after its parent, so every ancestor chain\n * the server checks is whole. `total` counts the document, and each element's\n * `childCount` stays its real one, so the server can tell the model what the\n * outline leaves out. The server holds this to its own limits before it quotes\n * a byte of it; null when the canvas has no document root loaded.\n */\nexport function describeAssistEditCanvas(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n selectedId: string | null,\n options: { whole?: boolean } = {},\n): AssistEditCanvasContext | null {\n const root = canvas.getNode(CANVAS_ROOT_ELEMENT_ID)\n if (!root) return null\n const whole = options.whole ? describeWholeCanvas(canvas, selectedId) : null\n if (whole) return whole\n const order: string[] = []\n const seen = new Set<string>()\n const brief = new Set<string>()\n const like = new Map<string, string>()\n const full = (): boolean => order.length >= ASSIST_EDIT_CONTEXT_MAX_NODES\n const add = (id: string | undefined | null, briefly = false): void => {\n if (!id || seen.has(id) || full()) return\n if (!canvas.getNode(id)) return\n seen.add(id)\n order.push(id)\n if (briefly) brief.add(id)\n }\n const childrenOf = (id: string): string[] => canvas.getNode(id)?.nodes ?? []\n const shapes = new Map<string, string | null>()\n const shape = (id: string): string | null => {\n if (!shapes.has(id)) shapes.set(id, shapeOf(canvas, id))\n return shapes.get(id) ?? null\n }\n // Alike only when there are contents to leave out.\n const alike = (id: string, model: string): boolean =>\n childrenOf(id).length > 0 && shape(id) !== null && shape(id) === shape(model)\n\n add(CANVAS_ROOT_ELEMENT_ID)\n const selected =\n selectedId && selectedId !== CANVAS_ROOT_ELEMENT_ID ? canvas.getNode(selectedId) : undefined\n const chain = selected?.$id ? chainToRoot(canvas, selected) : null\n chain?.forEach((id) => add(id))\n if (selected?.$id && chain && seen.has(selected.$id)) {\n for (const id of root.nodes ?? []) add(id)\n const inside = new Set<string>([selected.$id])\n const queue = [...childrenOf(selected.$id)]\n while (queue.length && !full()) {\n const id = queue.shift() as string\n if (inside.has(id)) continue\n inside.add(id)\n add(id)\n queue.push(...childrenOf(id))\n }\n const siblings = selected.parentId\n ? childrenOf(selected.parentId).filter((id) => id !== selected.$id)\n : []\n const held: string[] = []\n for (const id of siblings) {\n add(id)\n // A sibling the cap left out takes its contents with it.\n if (!seen.has(id)) continue\n if (alike(id, selected.$id)) like.set(id, selected.$id)\n else held.push(...childrenOf(id))\n }\n const reached = new Set<string>([...inside, ...siblings, ...held])\n for (let level = held; level.length && !full(); ) {\n const deeper: string[] = []\n for (const id of level) {\n add(id, true)\n for (const child of childrenOf(id)) {\n if (reached.has(child)) continue\n reached.add(child)\n deeper.push(child)\n }\n }\n level = deeper\n }\n // Parent first; the top-level section's own siblings are the sections above.\n for (const ancestor of chain.slice(1, -1).reverse()) {\n const parentId = canvas.getNode(ancestor)?.parentId\n for (const id of parentId ? childrenOf(parentId) : []) {\n if (id === ancestor || seen.has(id)) continue\n add(id, true)\n if (seen.has(id) && alike(id, ancestor)) like.set(id, ancestor)\n }\n }\n } else {\n for (const id of root.nodes ?? []) add(id)\n for (const section of root.nodes ?? []) {\n for (const id of childrenOf(section)) add(id)\n }\n }\n\n const nodes = order.map((id) => {\n const isSelected = id === selected?.$id\n return outlineElement(canvas, id, {\n selected: isSelected,\n brief: brief.has(id),\n like: like.get(id),\n textChars: isSelected ? ASSIST_EDIT_SELECTED_TEXT_CHARS : ASSIST_EDIT_OUTLINE_TEXT_CHARS,\n styles: isSelected,\n })\n })\n return {\n selectedId: selected?.$id && seen.has(selected.$id) ? selected.$id : null,\n total: countElements(canvas),\n nodes,\n }\n}\n\n/** One element as an outline carries it, at the tier it was described in. */\nfunction outlineElement(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n id: string,\n tier: { selected: boolean; brief?: boolean; like?: string; textChars: number; styles: boolean },\n): AssistEditCanvasNode {\n const node = canvas.getNode(id) as AssistEditCanvasNodeLike\n const parentId = id === CANVAS_ROOT_ELEMENT_ID ? null : (node.parentId ?? null)\n const parent = parentId ? canvas.getNode(parentId) : undefined\n const props = tier.brief ? undefined : describeProps(node.props, tier.textChars)\n const sx = tier.styles ? describeSx(node.sx) : undefined\n return {\n id,\n componentId: String(node.componentId ?? ''),\n parentId,\n index: Math.max(0, parent?.nodes?.indexOf(id) ?? 0),\n childCount: node.nodes?.length ?? 0,\n ...(node.name ? { name: String(node.name) } : {}),\n ...(props ? { props } : {}),\n ...(sx ? { sx } : {}),\n ...(tier.brief ? { brief: true } : {}),\n ...(tier.like ? { like: tier.like } : {}),\n ...(tier.selected ? summarizeInteractions(node.interactions) : {}),\n }\n}\n\n/**\n * The whole document as the chat in the Besigner sends it (AGL-4116): every\n * element depth first, children in their stored order, so the outline reads\n * as the page does and each element follows its parent. Null past the cap.\n */\nfunction describeWholeCanvas(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n selectedId: string | null,\n): AssistEditCanvasContext | null {\n const total = countElements(canvas)\n if (total > ASSIST_EDIT_WHOLE_MAX_NODES) return null\n const selected = selectedId !== CANVAS_ROOT_ELEMENT_ID ? selectedId : null\n const nodes: AssistEditCanvasNode[] = []\n const seen = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n const pending = [CANVAS_ROOT_ELEMENT_ID]\n while (pending.length) {\n const id = pending.pop() as string\n const node = canvas.getNode(id)\n if (!node) continue\n nodes.push(\n outlineElement(canvas, id, {\n selected: id === selected,\n textChars: ASSIST_EDIT_SELECTED_TEXT_CHARS,\n styles: true,\n }),\n )\n const children = node.nodes ?? []\n for (let index = children.length - 1; index >= 0; index -= 1) {\n if (seen.has(children[index])) continue\n seen.add(children[index])\n pending.push(children[index])\n }\n }\n return {\n selectedId: selected && nodes.some((node) => node.id === selected) ? selected : null,\n total,\n nodes,\n whole: true,\n }\n}\n\n/**\n * The selected element's interactions as the outline carries them\n * (AGL-3603): name, event and the kinds of its steps — never a selector.\n */\nfunction summarizeInteractions(raw: unknown): { interactions?: AssistEditInteractionSummary[] } {\n if (!Array.isArray(raw) || !raw.length) return {}\n const interactions = raw\n .filter(isRecord)\n .slice(0, NODE_MAX_INTERACTIONS)\n .map((entry) => ({\n name: String(entry['name'] ?? ''),\n event: String(isRecord(entry['trigger']) ? (entry['trigger']['event'] ?? '') : ''),\n steps: (Array.isArray(entry['steps']) ? entry['steps'] : [])\n .filter(isRecord)\n .map((step) => String(step['type'] ?? '')),\n enabled: entry['enabled'] !== false,\n }))\n .filter((entry) => entry.event)\n return interactions.length ? { interactions } : {}\n}\n\n/** Why a proposal cannot land on the open editor as it stands. */\nexport type AssistEditRefusal =\n /** No editor is open. */\n | 'no-editor'\n /** The editor open is not the document the proposal was made for. */\n | 'other-document'\n /** An element the proposal names has gone or changed since. */\n | 'stale'\n /** The canvas's own guards refused part of the change. */\n | 'refused'\n\nexport type AssistEditCheck =\n | { ok: true }\n | { ok: false; reason: AssistEditRefusal; message: string }\n\nexport type AssistEditApplyResult =\n | {\n ok: true\n /** Applied ops, counted by kind for the activity row. */\n opCounts: Record<string, number>\n /** Editor fields staged, as the editor keys them. */\n staged: string[]\n }\n | { ok: false; reason: AssistEditRefusal; message: string }\n\n/** Ids of the subtree at `rootId`, the root included, through child lists only. */\nfunction subtreeIds(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n rootId: string,\n): Set<string> {\n const found = new Set<string>([rootId])\n const queue = [...(canvas.getNode(rootId)?.nodes ?? [])]\n while (queue.length) {\n const id = queue.shift() as string\n if (found.has(id) || !canvas.getNode(id)) continue\n found.add(id)\n queue.push(...(canvas.getNode(id)?.nodes ?? []))\n }\n return found\n}\n\nconst STALE: AssistEditCheck = {\n ok: false,\n reason: 'stale',\n message: 'The canvas has changed since this was proposed, so nothing was applied. Ask again.',\n}\n\n/**\n * Whether the proposal can land on the open editor as it stands — checked in\n * full before anything is touched, so a refusal never leaves half an edit.\n */\nexport function checkAssistEdit(\n canvas: Pick<AssistEditCanvas, 'getNode' | 'nodeAcceptsChildren'>,\n proposal: AssistEditProposal,\n session: EditorSession | undefined,\n): AssistEditCheck {\n if (!session) {\n return {\n ok: false,\n reason: 'no-editor',\n message: 'Open the editor this change was proposed for to apply it.',\n }\n }\n if (\n session.documentKind !== proposal.target.kind ||\n session.documentId !== proposal.target.documentId\n ) {\n return {\n ok: false,\n reason: 'other-document',\n message: 'This change was proposed for a different document than the one open.',\n }\n }\n // The version the live site shows takes the change too (AGL-4116): it lands\n // as unsaved edits on the canvas, exactly as the author's own would, and the\n // Besigner's Save on that version writes the page's draft, never the version\n // visitors see. Publishing stays its own deliberate step.\n for (const op of proposal.ops) {\n switch (op.op) {\n case 'setSeo': {\n for (const field of Object.keys(op.fields) as ScreenSeoTextField[]) {\n if (typeof session.fields?.[screenSeoStageKey(field)] !== 'function') {\n return {\n ok: false,\n reason: 'other-document',\n message: 'This editor has no search fields to fill in.',\n }\n }\n }\n break\n }\n case 'insertSubtree': {\n const parent = canvas.getNode(op.parentId)\n if (!parent || parent.componentId !== op.parentComponentId) return STALE\n if (!canvas.nodeAcceptsChildren(parent)) return STALE\n break\n }\n case 'move': {\n const node = canvas.getNode(op.nodeId)\n const parent = canvas.getNode(op.parentId)\n if (!node || node.componentId !== op.componentId) return STALE\n if (!parent || parent.componentId !== op.parentComponentId) return STALE\n break\n }\n case 'saveAsComponent': {\n const node = canvas.getNode(op.nodeId)\n if (!node || node.componentId !== op.componentId) return STALE\n // The document itself is not a section of itself: promoting the root\n // would leave a document holding one instance of its own contents.\n if (op.nodeId === CANVAS_ROOT_ELEMENT_ID) return STALE\n const inside = subtreeIds(canvas, op.nodeId)\n for (const binding of op.bindings) {\n const bound = canvas.getNode(binding.nodeId)\n if (!bound || bound.componentId !== binding.componentId) return STALE\n // A closed world: a token outside the promoted subtree would bind a\n // property of the new component to an element it does not contain.\n if (!inside.has(binding.nodeId)) return STALE\n }\n break\n }\n case 'addInteraction': {\n const node = canvas.getNode(op.nodeId)\n if (!node || node.componentId !== op.componentId) return STALE\n if (Array.isArray(node.interactions) && node.interactions.length >= NODE_MAX_INTERACTIONS) {\n return {\n ok: false,\n reason: 'refused',\n message: `That element already does ${NODE_MAX_INTERACTIONS} things, the most one can. Remove one in Interactions first.`,\n }\n }\n // Every element a step acts on is still there, as it was.\n for (const target of op.targets) {\n const live = canvas.getNode(target.nodeId)\n if (!live || live.componentId !== target.componentId) return STALE\n }\n break\n }\n default: {\n const node = canvas.getNode(op.nodeId)\n if (!node || node.componentId !== op.componentId) return STALE\n }\n }\n }\n return { ok: true }\n}\n\n/**\n * Styles merged one key at a time. A responsive patch over a plain value\n * keeps that value as the base breakpoint, so \"more padding on wide screens\"\n * does not quietly remove the padding everywhere else.\n */\nfunction mergeSx(\n current: Record<string, unknown>,\n patch: Record<string, unknown>,\n): Record<string, unknown> {\n const out = { ...current }\n for (const [key, value] of Object.entries(patch)) {\n const existing = out[key]\n if (isRecord(value) && isRecord(existing)) {\n out[key] = { ...plain(existing), ...value }\n } else if (isRecord(value) && (typeof existing === 'string' || typeof existing === 'number')) {\n out[key] = { xs: existing, ...value }\n } else {\n out[key] = value\n }\n }\n return out\n}\n\n/** A validated flat subtree as the nested shape `addNodeFromNested` takes. */\nfunction nestSubtree(op: AssistEditInsertOp): Record<string, unknown> {\n const visited = new Set<string>()\n const build = (id: string): Record<string, unknown> => {\n visited.add(id)\n const node = op.nodes[id]\n return {\n componentId: node.componentId,\n ...(node.pluginId ? { pluginId: node.pluginId } : {}),\n props: { ...node.props },\n ...(node.sx ? { sx: { ...node.sx } } : {}),\n ...(node.hidden ? { hidden: true } : {}),\n nodes: node.nodes\n .filter((child) => op.nodes[child] && !visited.has(child))\n .map((child) => build(child)),\n }\n }\n return build(op.rootId)\n}\n\nfunction live(canvas: AssistEditCanvas, id: string): AssistEditCanvasNodeLike {\n const node = canvas.getNode(id)\n if (!node) throw new Error(`element ${id} is no longer on the canvas`)\n return node\n}\n\nfunction applyOne(canvas: AssistEditCanvas, op: AssistEditOp): void {\n switch (op.op) {\n case 'updateProps': {\n const node = live(canvas, op.nodeId)\n // Spread the props the element has: `updateNodeProps` REPLACES the bag,\n // and a patch of one setting would otherwise strip every other one.\n const next: Record<string, unknown> = { ...plain(node.props), ...op.props }\n // Rich text renders `html` over `children`; proposed text replaces it.\n if ('children' in op.props) delete next['html']\n canvas.updateNodeProps(node, next)\n return\n }\n case 'updateSx': {\n const node = live(canvas, op.nodeId)\n canvas.updateNodeFields(node, { sx: mergeSx(plain(node.sx), op.sx) })\n return\n }\n case 'move':\n canvas.reparentNode(live(canvas, op.nodeId), live(canvas, op.parentId), op.index ?? NaN)\n return\n case 'remove':\n canvas.deleteNode(live(canvas, op.nodeId))\n return\n case 'rename':\n canvas.updateNodeFields(live(canvas, op.nodeId), { name: op.name })\n return\n case 'addInteraction': {\n // Added beside what the element does already, never in place of it:\n // an id the element already uses is re-minted, so nothing is replaced.\n const node = live(canvas, op.nodeId)\n const current = (Array.isArray(node.interactions) ? node.interactions : []) as NodeInteraction[]\n let id = op.interaction.id\n while (current.some((entry) => entry.id === id)) id = `${op.interaction.id}${current.length}x`\n canvas.updateNodeFields(node, {\n interactions: upsertNodeInteraction(current, { ...op.interaction, id }),\n })\n return\n }\n case 'insertSubtree':\n canvas.addNodeFromNested(nestSubtree(op), live(canvas, op.parentId), op.index ?? NaN)\n return\n case 'setSeo':\n case 'saveAsComponent':\n // Both are applied outside the canvas batch: search fields are staged\n // into the editor's own form, and a component save mints a document\n // first and then swaps the subtree for an instance of it.\n return\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Save the selection as a reusable component (AGL-2908)\n * ------------------------------------------------------------------ */\n\n/** What the apply needs from the console to create the component. */\nexport interface AssistEditComponentWriter {\n /**\n * Creates the component through `POST /api/hosts/resources`, where the\n * plan's entitlement and the route's field allow-list are enforced, and\n * answers its id. The plugin never writes Firestore from the browser.\n */\n createComponent(input: {\n name: string\n rootId: string\n nodes: Record<string, unknown>\n props: ReusableComponentProp[]\n }): Promise<string>\n}\n\n/**\n * The value a bound field holds on the live canvas right now, which becomes\n * the property's default.\n *\n * `hideIf` is the exception: the part is on the page, so the property that\n * hides it starts at no. Every other field answers with what the author can\n * see, which is what makes the instance render exactly what was there.\n */\nfunction currentValue(\n node: AssistEditCanvasNodeLike,\n field: string,\n): ReusableComponentPropValue | undefined {\n if (field === NODE_HIDE_IF_PROP) return false\n const value = plain(node.props)[field]\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value\n }\n return undefined\n}\n\n/**\n * Whether a default the canvas gave is one the property's own control\n * offers. A Choice whose current value is not among its answers is a\n * selection that has changed since the proposal was made, and applying it\n * would declare a property no page could ever set back.\n */\nfunction defaultFitsProp(prop: AssistEditComponentProp, value: unknown): boolean {\n if (!prop.options?.length) return true\n return prop.options.some((option) => option.value === value)\n}\n\n/**\n * The definition the new component holds: the promoted subtree, with each\n * bound field replaced by its property's token.\n *\n * The defaults are read off the SAME fields a moment before they are\n * replaced, so the instance that takes the subtree's place renders what the\n * author was looking at. Returns null when a default no longer fits its\n * property, which is the stale case.\n */\nfunction componentDefinition(\n canvas: AssistEditCanvas,\n op: AssistEditSaveAsComponentOp,\n): { nodes: Record<string, unknown>; props: ReusableComponentProp[] } | null {\n const nodes = reusableComponentDefinitionFrom(\n canvas.toJSON().nodes as never,\n op.nodeId,\n ) as unknown as Record<string, Record<string, unknown>>\n const defaults = new Map<string, ReusableComponentPropValue | undefined>()\n for (const binding of op.bindings) {\n const live = canvas.getNode(binding.nodeId)\n const stored = nodes[binding.nodeId]\n if (!live || !stored) return null\n if (!defaults.has(binding.prop)) defaults.set(binding.prop, currentValue(live, binding.field))\n stored['props'] = { ...plain(stored['props']), [binding.field]: `{{prop.${binding.prop}}}` }\n }\n const props: ReusableComponentProp[] = []\n for (const declared of op.props) {\n const value = defaults.get(declared.name)\n if (!defaultFitsProp(declared, value)) return null\n props.push({ ...declared, ...(value === undefined ? {} : { defaultValue: value }) })\n }\n return { nodes, props }\n}\n\n/**\n * Lands a confirmed proposal on the open editor: the canvas ops as ONE batch\n * — one undo step, all or nothing — then any search fields staged into the\n * editor's own form. Nothing is saved.\n */\nexport function applyAssistEdit(\n canvas: AssistEditCanvas,\n proposal: AssistEditProposal,\n session: EditorSession | undefined,\n): AssistEditApplyResult {\n const check = checkAssistEdit(canvas, proposal, session)\n if (check.ok === false) return check\n const open = session as EditorSession\n const canvasOps = proposal.ops.filter((op) => op.op !== 'setSeo' && op.op !== 'saveAsComponent')\n if (canvasOps.length) {\n try {\n canvas.batch(() => {\n for (const op of canvasOps) applyOne(canvas, op)\n })\n } catch (error) {\n console.error('assist edit refused by the canvas', error)\n return {\n ok: false,\n reason: 'refused',\n message: 'The editor refused part of this change, so none of it was applied.',\n }\n }\n }\n const staged: string[] = []\n for (const op of proposal.ops) {\n if (op.op !== 'setSeo') continue\n const values: Record<string, string> = {}\n for (const [field, value] of Object.entries(op.fields)) {\n values[screenSeoStageKey(field as ScreenSeoTextField)] = String(value)\n }\n staged.push(...stageEditorSessionFields(open, values).staged)\n }\n return { ok: true, opCounts: assistEditOpCounts(proposal.ops), staged }\n}\n\n/**\n * Lands a proposal that saves the selection as a reusable component\n * (AGL-2908) — AGL-2866's recipe, in place, with no clipboard.\n *\n * The order is the manual action's order, and it matters:\n *\n * 1. the definition is read off the live subtree, each bound field replaced\n * by its token and its current value kept as that property's default;\n * 2. the component is created through the host resources route, where the\n * server enforces the plan's entitlement and its own allow-list — so a\n * refusal happens before the open document is touched at all;\n * 3. the subtree is swapped for an instance of what was just created, inside\n * ONE `batch` with the rest of the proposal's canvas ops: one undo step.\n *\n * The only document created is the component, exactly as Save as reusable\n * component creates one. The page change is an unsaved edit on the version\n * the editor has open, which the check has already refused to be a live one.\n * Nothing is published and nothing is saved.\n */\nexport async function applyAssistEditSavingComponent(\n canvas: AssistEditCanvas,\n proposal: AssistEditProposal,\n session: EditorSession | undefined,\n writer: AssistEditComponentWriter,\n): Promise<AssistEditApplyResult> {\n const save = proposal.ops.find(\n (op): op is AssistEditSaveAsComponentOp => op.op === 'saveAsComponent',\n )\n if (!save) return applyAssistEdit(canvas, proposal, session)\n const check = checkAssistEdit(canvas, proposal, session)\n if (check.ok === false) return check\n\n const definition = componentDefinition(canvas, save)\n if (!definition) return STALE as AssistEditApplyResult\n\n let componentId: string\n try {\n componentId = await writer.createComponent({\n name: save.name,\n rootId: save.nodeId,\n nodes: definition.nodes,\n props: definition.props,\n })\n } catch (error) {\n console.error('assist edit could not create the component', error)\n return {\n ok: false,\n reason: 'refused',\n message:\n error instanceof Error && error.message\n ? error.message\n : 'The component could not be saved, so nothing on this page was changed.',\n }\n }\n\n const canvasOps = proposal.ops.filter((op) => op.op !== 'setSeo' && op.op !== 'saveAsComponent')\n try {\n canvas.batch(() => {\n for (const op of canvasOps) applyOne(canvas, op)\n canvas.applyNodes(\n replaceSubtreeWithInstance(\n canvas.toJSON().nodes as never,\n save.nodeId,\n componentId,\n save.name,\n ),\n )\n })\n } catch (error) {\n console.error('assist edit refused by the canvas', error)\n return {\n ok: false,\n reason: 'refused',\n message:\n 'The component was saved, but the editor refused to swap this element for it. ' +\n 'Insert it from Your components instead.',\n }\n }\n return { ok: true, opCounts: assistEditOpCounts(proposal.ops), staged: [] }\n}\n"],"names":["screenSeoStageKey","NODE_HIDE_IF_PROP","replaceSubtreeWithInstance","reusableComponentDefinitionFrom","CANVAS_ROOT_ELEMENT_ID","NODE_MAX_INTERACTIONS","upsertNodeInteraction","stageEditorSessionFields","ASSIST_EDIT_CONTEXT_MAX_NODES","ASSIST_EDIT_CONTEXT_MAX_PROPS","ASSIST_EDIT_OUTLINE_TEXT_CHARS","ASSIST_EDIT_SELECTED_TEXT_CHARS","ASSIST_EDIT_WHOLE_MAX_NODES","assistEditOpCounts","UNDESCRIBED_PROP","isRecord","value","Array","isArray","plain","out","key","describeProps","raw","textChars","props","kept","name","Object","entries","test","trim","slice","Number","isFinite","undefined","describeSx","sx","keys","length","chainToRoot","canvas","selected","chain","walked","Set","current","$id","has","add","unshift","parentId","getNode","SHAPE_LIMIT","shapeOf","rootId","budget","walk","id","node","parts","child","nodes","part","push","String","componentId","join","countElements","count","reached","pending","pop","describeAssistEditCanvas","selectedId","options","root","whole","describeWholeCanvas","order","seen","brief","like","Map","full","briefly","childrenOf","shapes","shape","set","get","alike","model","forEach","inside","queue","shift","siblings","filter","held","level","deeper","ancestor","reverse","section","map","isSelected","outlineElement","styles","total","tier","parent","index","Math","max","indexOf","childCount","summarizeInteractions","interactions","children","some","entry","event","steps","step","enabled","subtreeIds","found","STALE","ok","reason","message","checkAssistEdit","proposal","session","documentKind","target","kind","documentId","op","ops","field","fields","parentComponentId","nodeAcceptsChildren","nodeId","binding","bindings","bound","targets","live","mergeSx","patch","existing","xs","nestSubtree","visited","build","pluginId","hidden","Error","applyOne","next","updateNodeProps","updateNodeFields","reparentNode","NaN","deleteNode","interaction","addNodeFromNested","currentValue","defaultFitsProp","prop","option","componentDefinition","toJSON","defaults","stored","declared","defaultValue","applyAssistEdit","check","open","canvasOps","batch","error","console","staged","values","opCounts","applyAssistEditSavingComponent","writer","save","find","definition","createComponent","applyNodes"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,QAEZ,2CAA0C;AACjD,SACEC,iBAAiB,EACjBC,0BAA0B,EAC1BC,+BAA+B,QAC1B,qDAAoD;AAC3D,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,qBAAqB,EACrBC,qBAAqB,QAEhB,2CAA0C;AAKjD,SACEC,wBAAwB,QAEnB,8CAA6C;AACpD,SACEC,6BAA6B,EAC7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,EAAE,KAAK;IAC9E,IAAI;QACFlG,OAAO+I,KAAK,CAAC;YACX,KAAK,MAAM7C,MAAM4C,UAAWtB,SAASxH,QAAQkG;YAC7ClG,OAAO2J,UAAU,CACflM,2BACEuC,OAAOsI,MAAM,GAAGjH,KAAK,EACrBkI,KAAK/C,MAAM,EACX/E,aACA8H,KAAKrK,IAAI;QAGf;IACF,EAAE,OAAO8J,OAAO;QACdC,QAAQD,KAAK,CAAC,qCAAqCA;QACnD,OAAO;YACLxD,IAAI;YACJC,QAAQ;YACRC,SACE,kFACA;QACJ;IACF;IACA,OAAO;QAAEF,IAAI;QAAM4D,UAAUhL,mBAAmBwH,SAASO,GAAG;QAAG+C,QAAQ,EAAE;IAAC;AAC5E"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/assist-edit-canvas.ts"],"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 {\n screenSeoStageKey,\n type ScreenSeoTextField,\n} from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport {\n NODE_HIDE_IF_PROP,\n replaceSubtreeWithInstance,\n reusableComponentDefinitionFrom,\n} from '@aglyn/aglyn/app-utils/compose-reusable-components'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport {\n NODE_MAX_INTERACTIONS,\n upsertNodeInteraction,\n type NodeInteraction,\n} from '@aglyn/aglyn/app-utils/node-interactions'\nimport type {\n ReusableComponentProp,\n ReusableComponentPropValue,\n} from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport {\n stageEditorSessionFields,\n type EditorSession,\n} from '@aglyn/aglyn/plugin-manager/editor-sessions'\nimport {\n ASSIST_EDIT_CONTEXT_MAX_NODES,\n ASSIST_EDIT_CONTEXT_MAX_PROPS,\n ASSIST_EDIT_OUTLINE_TEXT_CHARS,\n ASSIST_EDIT_SELECTED_TEXT_CHARS,\n ASSIST_EDIT_WHOLE_MAX_NODES,\n assistEditOpCounts,\n type AssistEditCanvasContext,\n type AssistEditCanvasNode,\n type AssistEditInsertOp,\n type AssistEditInteractionSummary,\n type AssistEditOp,\n type AssistEditProposal,\n type AssistEditComponentProp,\n type AssistEditSaveAsComponentOp,\n} from '../model/assist-edit'\n\n/**\n * The edit rung's client half (AGL-2906): what the panel tells the server\n * about the open canvas, and how a confirmed proposal lands on it.\n *\n * Applying goes through the canvas's own guarded mutators — the same ones\n * the besigner's panels and the marketing appliers use — inside ONE\n * `batch`, so the whole proposal is one undo step and a guard that refuses\n * part-way leaves nothing behind. Every change is an unsaved edit on the\n * version the editor has open; saving it stays the author's act, with the\n * editor's own control. On a version the live site serves, that save writes\n * the page's draft and never the version, so a change lands there too and\n * reaches visitors only when the author publishes (AGL-4116).\n */\n\n/** A node as the canvas holds it — the fields this module reads. */\nexport interface AssistEditCanvasNodeLike {\n $id?: string\n componentId?: string\n parentId?: string | null\n nodes?: string[]\n name?: string\n props?: unknown\n sx?: unknown\n /** The element's own interactions (AGL-3603), as the canvas holds them. */\n interactions?: unknown\n}\n\n/**\n * The slice of the besigner canvas the edit rung reads and drives. Every\n * member is one `CanvasManager` already has, so the panel hands over the\n * canvas itself and a spec hands over a real one.\n */\nexport interface AssistEditCanvas {\n getNode(id: string): AssistEditCanvasNodeLike | undefined\n batch<T>(mutate: () => T): T\n updateNodeProps(node: any, props: any): void\n updateNodeFields(node: any, patch: any): void\n reparentNode(node: any, parent: any, index?: number): unknown\n deleteNode(node: any): unknown\n addNodeFromNested(nested: any, parent: any, index?: number): unknown\n nodeAcceptsChildren(node: any): boolean\n /** The whole document, which a component save reads its definition out of. */\n toJSON(): { nodes: Record<string, unknown> }\n /** The document after a save: the promoted subtree swapped for an instance. */\n applyNodes(nodes: any): unknown\n}\n\nconst UNDESCRIBED_PROP = /^(html|sx|style|className|dangerouslySetInnerHTML|on[A-Z].*)$/\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * An observable's own keys as a plain object. A canvas node's `props` and\n * `sx` are observable proxies, and a spread of one is how a merge silently\n * copies nothing.\n */\nfunction plain(value: unknown): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n if (!value || typeof value !== 'object') return out\n for (const key in value as Record<string, unknown>) {\n out[key] = (value as Record<string, unknown>)[key]\n }\n return out\n}\n\nfunction describeProps(\n raw: unknown,\n textChars: number,\n): Record<string, string | number | boolean> | undefined {\n const props: Record<string, string | number | boolean> = {}\n let kept = 0\n for (const [name, value] of Object.entries(plain(raw))) {\n if (kept >= ASSIST_EDIT_CONTEXT_MAX_PROPS) break\n if (UNDESCRIBED_PROP.test(name)) continue\n if (typeof value === 'string') {\n if (!value.trim()) continue\n props[name] = value.slice(0, textChars)\n } else if (typeof value === 'number' && Number.isFinite(value)) {\n props[name] = value\n } else if (typeof value === 'boolean') {\n props[name] = value\n } else {\n continue\n }\n kept += 1\n }\n return kept ? props : undefined\n}\n\nfunction describeSx(raw: unknown): Record<string, unknown> | undefined {\n const sx: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(plain(raw))) {\n if (typeof value === 'string' || typeof value === 'number') sx[key] = value\n else if (isRecord(value)) sx[key] = plain(value)\n }\n return Object.keys(sx).length ? sx : undefined\n}\n\n/**\n * The selection's ancestors below the document root, top-level section first\n * and the selection last; null when its parents do not lead to the root,\n * which is not a chain the server can check.\n */\nfunction chainToRoot(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n selected: AssistEditCanvasNodeLike,\n): string[] | null {\n const chain: string[] = []\n const walked = new Set<string>()\n let current: AssistEditCanvasNodeLike | undefined = selected\n while (current?.$id && current.$id !== CANVAS_ROOT_ELEMENT_ID && !walked.has(current.$id)) {\n walked.add(current.$id)\n chain.unshift(current.$id)\n current = current.parentId ? canvas.getNode(current.parentId) : undefined\n }\n return current?.$id === CANVAS_ROOT_ELEMENT_ID ? chain : null\n}\n\n/** Elements one shape is taken over at most; a larger subtree is never called alike. */\nconst SHAPE_LIMIT = 200\n\n/**\n * How an element is built: its component and, in order, its children's —\n * what two cards of one row have in common whatever their text. Null past\n * `SHAPE_LIMIT` elements, or for a subtree that loops back on itself.\n */\nfunction shapeOf(canvas: Pick<AssistEditCanvas, 'getNode'>, rootId: string): string | null {\n let budget = SHAPE_LIMIT\n const walked = new Set<string>()\n const walk = (id: string): string | null => {\n const node = canvas.getNode(id)\n if (!node || walked.has(id) || --budget < 0) return null\n walked.add(id)\n const parts: string[] = []\n for (const child of node.nodes ?? []) {\n const part = walk(child)\n if (part === null) return null\n parts.push(part)\n }\n return `${String(node.componentId ?? '')}(${parts.join(',')})`\n }\n return walk(rootId)\n}\n\n/** Elements reachable from the document root through child lists, the root included. */\nfunction countElements(canvas: Pick<AssistEditCanvas, 'getNode'>): number {\n let count = 0\n const reached = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n const pending = [CANVAS_ROOT_ELEMENT_ID]\n while (pending.length) {\n const node = canvas.getNode(pending.pop() as string)\n if (!node) continue\n count += 1\n for (const child of node.nodes ?? []) {\n if (reached.has(child)) continue\n reached.add(child)\n pending.push(child)\n }\n }\n return count\n}\n\n/**\n * The canvas outline a question carries on the edit rung, in two tiers, until\n * the cap.\n *\n * Described in full, settings and all: the document root, the selection's\n * ancestors and the selection, the document's top-level sections, everything\n * inside the selection — what an edit to it changes — and its siblings.\n *\n * Described briefly, by place alone (`brief`): what surrounds that, so the\n * model knows it exists and asks for it rather than calling it missing —\n *\n * 1. what the selection's siblings hold, level by level (the icons beside a\n * selected link, in the card they share);\n * 2. the siblings of each ancestor below the top-level section, nearest\n * first (the other cards of the row, then what sits beside the row).\n *\n * An element built the same way as the selection, or as the ancestor it sits\n * beside, is marked `like` it and its contents are left out: one card\n * described, and every other card of the row says it holds the same.\n *\n * With nothing selected, it is the root, the top-level sections and one level\n * inside each: enough for a change to the page as a whole, and the prompt asks\n * for a selection before anything more specific.\n *\n * With `whole`, it is the whole document instead (AGL-4116), up to\n * `ASSIST_EDIT_WHOLE_MAX_NODES`: every element, in the order it reads on the\n * page, with its settings and its styles. That is what the chat in the\n * Besigner sends, so \"change the Get in touch button\" finds the button with\n * nothing selected. A document past the cap falls back to the two tiers.\n *\n * An element is only ever described after its parent, so every ancestor chain\n * the server checks is whole. `total` counts the document, and each element's\n * `childCount` stays its real one, so the server can tell the model what the\n * outline leaves out. The server holds this to its own limits before it quotes\n * a byte of it; null when the canvas has no document root loaded.\n */\nexport function describeAssistEditCanvas(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n selectedId: string | null,\n options: { whole?: boolean } = {},\n): AssistEditCanvasContext | null {\n const root = canvas.getNode(CANVAS_ROOT_ELEMENT_ID)\n if (!root) return null\n const whole = options.whole ? describeWholeCanvas(canvas, selectedId) : null\n if (whole) return whole\n const order: string[] = []\n const seen = new Set<string>()\n const brief = new Set<string>()\n const like = new Map<string, string>()\n const full = (): boolean => order.length >= ASSIST_EDIT_CONTEXT_MAX_NODES\n const add = (id: string | undefined | null, briefly = false): void => {\n if (!id || seen.has(id) || full()) return\n if (!canvas.getNode(id)) return\n seen.add(id)\n order.push(id)\n if (briefly) brief.add(id)\n }\n const childrenOf = (id: string): string[] => canvas.getNode(id)?.nodes ?? []\n const shapes = new Map<string, string | null>()\n const shape = (id: string): string | null => {\n if (!shapes.has(id)) shapes.set(id, shapeOf(canvas, id))\n return shapes.get(id) ?? null\n }\n // Alike only when there are contents to leave out.\n const alike = (id: string, model: string): boolean =>\n childrenOf(id).length > 0 && shape(id) !== null && shape(id) === shape(model)\n\n add(CANVAS_ROOT_ELEMENT_ID)\n const selected =\n selectedId && selectedId !== CANVAS_ROOT_ELEMENT_ID ? canvas.getNode(selectedId) : undefined\n const chain = selected?.$id ? chainToRoot(canvas, selected) : null\n chain?.forEach((id) => add(id))\n if (selected?.$id && chain && seen.has(selected.$id)) {\n for (const id of root.nodes ?? []) add(id)\n const inside = new Set<string>([selected.$id])\n const queue = [...childrenOf(selected.$id)]\n while (queue.length && !full()) {\n const id = queue.shift() as string\n if (inside.has(id)) continue\n inside.add(id)\n add(id)\n queue.push(...childrenOf(id))\n }\n const siblings = selected.parentId\n ? childrenOf(selected.parentId).filter((id) => id !== selected.$id)\n : []\n const held: string[] = []\n for (const id of siblings) {\n add(id)\n // A sibling the cap left out takes its contents with it.\n if (!seen.has(id)) continue\n if (alike(id, selected.$id)) like.set(id, selected.$id)\n else held.push(...childrenOf(id))\n }\n const reached = new Set<string>([...inside, ...siblings, ...held])\n for (let level = held; level.length && !full(); ) {\n const deeper: string[] = []\n for (const id of level) {\n add(id, true)\n for (const child of childrenOf(id)) {\n if (reached.has(child)) continue\n reached.add(child)\n deeper.push(child)\n }\n }\n level = deeper\n }\n // Parent first; the top-level section's own siblings are the sections above.\n for (const ancestor of chain.slice(1, -1).reverse()) {\n const parentId = canvas.getNode(ancestor)?.parentId\n for (const id of parentId ? childrenOf(parentId) : []) {\n if (id === ancestor || seen.has(id)) continue\n add(id, true)\n if (seen.has(id) && alike(id, ancestor)) like.set(id, ancestor)\n }\n }\n } else {\n for (const id of root.nodes ?? []) add(id)\n for (const section of root.nodes ?? []) {\n for (const id of childrenOf(section)) add(id)\n }\n }\n\n const nodes = order.map((id) => {\n const isSelected = id === selected?.$id\n return outlineElement(canvas, id, {\n selected: isSelected,\n brief: brief.has(id),\n like: like.get(id),\n textChars: isSelected ? ASSIST_EDIT_SELECTED_TEXT_CHARS : ASSIST_EDIT_OUTLINE_TEXT_CHARS,\n styles: isSelected,\n })\n })\n return {\n selectedId: selected?.$id && seen.has(selected.$id) ? selected.$id : null,\n total: countElements(canvas),\n nodes,\n }\n}\n\n/** One element as an outline carries it, at the tier it was described in. */\nfunction outlineElement(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n id: string,\n tier: { selected: boolean; brief?: boolean; like?: string; textChars: number; styles: boolean },\n): AssistEditCanvasNode {\n const node = canvas.getNode(id) as AssistEditCanvasNodeLike\n const parentId = id === CANVAS_ROOT_ELEMENT_ID ? null : (node.parentId ?? null)\n const parent = parentId ? canvas.getNode(parentId) : undefined\n const props = tier.brief ? undefined : describeProps(node.props, tier.textChars)\n const sx = tier.styles ? describeSx(node.sx) : undefined\n return {\n id,\n componentId: String(node.componentId ?? ''),\n parentId,\n index: Math.max(0, parent?.nodes?.indexOf(id) ?? 0),\n childCount: node.nodes?.length ?? 0,\n ...(node.name ? { name: String(node.name) } : {}),\n ...(props ? { props } : {}),\n ...(sx ? { sx } : {}),\n ...(tier.brief ? { brief: true } : {}),\n ...(tier.like ? { like: tier.like } : {}),\n ...(tier.selected ? summarizeInteractions(node.interactions) : {}),\n }\n}\n\n/**\n * The whole document as the chat in the Besigner sends it (AGL-4116): every\n * element depth first, children in their stored order, so the outline reads\n * as the page does and each element follows its parent. Null past the cap.\n */\nfunction describeWholeCanvas(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n selectedId: string | null,\n): AssistEditCanvasContext | null {\n const total = countElements(canvas)\n if (total > ASSIST_EDIT_WHOLE_MAX_NODES) return null\n const selected = selectedId !== CANVAS_ROOT_ELEMENT_ID ? selectedId : null\n const nodes: AssistEditCanvasNode[] = []\n const seen = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n const pending = [CANVAS_ROOT_ELEMENT_ID]\n while (pending.length) {\n const id = pending.pop() as string\n const node = canvas.getNode(id)\n if (!node) continue\n nodes.push(\n outlineElement(canvas, id, {\n selected: id === selected,\n textChars: ASSIST_EDIT_SELECTED_TEXT_CHARS,\n styles: true,\n }),\n )\n const children = node.nodes ?? []\n for (let index = children.length - 1; index >= 0; index -= 1) {\n if (seen.has(children[index])) continue\n seen.add(children[index])\n pending.push(children[index])\n }\n }\n return {\n selectedId: selected && nodes.some((node) => node.id === selected) ? selected : null,\n total,\n nodes,\n whole: true,\n }\n}\n\n/**\n * The selected element's interactions as the outline carries them\n * (AGL-3603): name, event and the kinds of its steps — never a selector.\n */\nfunction summarizeInteractions(raw: unknown): { interactions?: AssistEditInteractionSummary[] } {\n if (!Array.isArray(raw) || !raw.length) return {}\n const interactions = raw\n .filter(isRecord)\n .slice(0, NODE_MAX_INTERACTIONS)\n .map((entry) => ({\n name: String(entry['name'] ?? ''),\n event: String(isRecord(entry['trigger']) ? (entry['trigger']['event'] ?? '') : ''),\n steps: (Array.isArray(entry['steps']) ? entry['steps'] : [])\n .filter(isRecord)\n .map((step) => String(step['type'] ?? '')),\n enabled: entry['enabled'] !== false,\n }))\n .filter((entry) => entry.event)\n return interactions.length ? { interactions } : {}\n}\n\n/** Why a proposal cannot land on the open editor as it stands. */\nexport type AssistEditRefusal =\n /** No editor is open. */\n | 'no-editor'\n /** The editor open is not the document the proposal was made for. */\n | 'other-document'\n /** An element the proposal names has gone or changed since. */\n | 'stale'\n /** The canvas's own guards refused part of the change. */\n | 'refused'\n\nexport type AssistEditCheck =\n | { ok: true }\n | { ok: false; reason: AssistEditRefusal; message: string }\n\n/** The elements one insert added, as the canvas named them. */\nexport interface AssistEditInserted {\n /** The insert's position among the proposal's ops. */\n op: number\n /** Every element it added, depth first in the order they read, its root first. */\n ids: string[]\n}\n\nexport type AssistEditApplyResult =\n | {\n ok: true\n /** Applied ops, counted by kind for the activity row. */\n opCounts: Record<string, number>\n /** Editor fields staged, as the editor keys them. */\n staged: string[]\n /**\n * The ids the canvas gave the elements each insert added (AGL-4235),\n * so a caller can name them in a later change. Absent with no insert.\n */\n inserted?: AssistEditInserted[]\n }\n | { ok: false; reason: AssistEditRefusal; message: string }\n\n/** Ids of the subtree at `rootId`, the root included, through child lists only. */\nfunction subtreeIds(\n canvas: Pick<AssistEditCanvas, 'getNode'>,\n rootId: string,\n): Set<string> {\n const found = new Set<string>([rootId])\n const queue = [...(canvas.getNode(rootId)?.nodes ?? [])]\n while (queue.length) {\n const id = queue.shift() as string\n if (found.has(id) || !canvas.getNode(id)) continue\n found.add(id)\n queue.push(...(canvas.getNode(id)?.nodes ?? []))\n }\n return found\n}\n\nconst STALE: AssistEditCheck = {\n ok: false,\n reason: 'stale',\n message: 'The canvas has changed since this was proposed, so nothing was applied. Ask again.',\n}\n\n/**\n * Whether the proposal can land on the open editor as it stands — checked in\n * full before anything is touched, so a refusal never leaves half an edit.\n */\nexport function checkAssistEdit(\n canvas: Pick<AssistEditCanvas, 'getNode' | 'nodeAcceptsChildren'>,\n proposal: AssistEditProposal,\n session: EditorSession | undefined,\n): AssistEditCheck {\n if (!session) {\n return {\n ok: false,\n reason: 'no-editor',\n message: 'Open the editor this change was proposed for to apply it.',\n }\n }\n if (\n session.documentKind !== proposal.target.kind ||\n session.documentId !== proposal.target.documentId\n ) {\n return {\n ok: false,\n reason: 'other-document',\n message: 'This change was proposed for a different document than the one open.',\n }\n }\n // The version the live site shows takes the change too (AGL-4116): it lands\n // as unsaved edits on the canvas, exactly as the author's own would, and the\n // Besigner's Save on that version writes the page's draft, never the version\n // visitors see. Publishing stays its own deliberate step.\n for (const op of proposal.ops) {\n switch (op.op) {\n case 'setSeo': {\n for (const field of Object.keys(op.fields) as ScreenSeoTextField[]) {\n if (typeof session.fields?.[screenSeoStageKey(field)] !== 'function') {\n return {\n ok: false,\n reason: 'other-document',\n message: 'This editor has no search fields to fill in.',\n }\n }\n }\n break\n }\n case 'insertSubtree': {\n const parent = canvas.getNode(op.parentId)\n if (!parent || parent.componentId !== op.parentComponentId) return STALE\n if (!canvas.nodeAcceptsChildren(parent)) return STALE\n break\n }\n case 'move': {\n const node = canvas.getNode(op.nodeId)\n const parent = canvas.getNode(op.parentId)\n if (!node || node.componentId !== op.componentId) return STALE\n if (!parent || parent.componentId !== op.parentComponentId) return STALE\n break\n }\n case 'saveAsComponent': {\n const node = canvas.getNode(op.nodeId)\n if (!node || node.componentId !== op.componentId) return STALE\n // The document itself is not a section of itself: promoting the root\n // would leave a document holding one instance of its own contents.\n if (op.nodeId === CANVAS_ROOT_ELEMENT_ID) return STALE\n const inside = subtreeIds(canvas, op.nodeId)\n for (const binding of op.bindings) {\n const bound = canvas.getNode(binding.nodeId)\n if (!bound || bound.componentId !== binding.componentId) return STALE\n // A closed world: a token outside the promoted subtree would bind a\n // property of the new component to an element it does not contain.\n if (!inside.has(binding.nodeId)) return STALE\n }\n break\n }\n case 'addInteraction': {\n const node = canvas.getNode(op.nodeId)\n if (!node || node.componentId !== op.componentId) return STALE\n if (Array.isArray(node.interactions) && node.interactions.length >= NODE_MAX_INTERACTIONS) {\n return {\n ok: false,\n reason: 'refused',\n message: `That element already does ${NODE_MAX_INTERACTIONS} things, the most one can. Remove one in Interactions first.`,\n }\n }\n // Every element a step acts on is still there, as it was.\n for (const target of op.targets) {\n const live = canvas.getNode(target.nodeId)\n if (!live || live.componentId !== target.componentId) return STALE\n }\n break\n }\n default: {\n const node = canvas.getNode(op.nodeId)\n if (!node || node.componentId !== op.componentId) return STALE\n }\n }\n }\n return { ok: true }\n}\n\n/**\n * Styles merged one key at a time. A responsive patch over a plain value\n * keeps that value as the base breakpoint, so \"more padding on wide screens\"\n * does not quietly remove the padding everywhere else.\n */\nfunction mergeSx(\n current: Record<string, unknown>,\n patch: Record<string, unknown>,\n): Record<string, unknown> {\n const out = { ...current }\n for (const [key, value] of Object.entries(patch)) {\n const existing = out[key]\n if (isRecord(value) && isRecord(existing)) {\n out[key] = { ...plain(existing), ...value }\n } else if (isRecord(value) && (typeof existing === 'string' || typeof existing === 'number')) {\n out[key] = { xs: existing, ...value }\n } else {\n out[key] = value\n }\n }\n return out\n}\n\n/** A validated flat subtree as the nested shape `addNodeFromNested` takes. */\nfunction nestSubtree(op: AssistEditInsertOp): Record<string, unknown> {\n const visited = new Set<string>()\n const build = (id: string): Record<string, unknown> => {\n visited.add(id)\n const node = op.nodes[id]\n return {\n componentId: node.componentId,\n ...(node.pluginId ? { pluginId: node.pluginId } : {}),\n props: { ...node.props },\n ...(node.sx ? { sx: { ...node.sx } } : {}),\n ...(node.hidden ? { hidden: true } : {}),\n ...(node.name ? { name: node.name } : {}),\n nodes: node.nodes\n .filter((child) => op.nodes[child] && !visited.has(child))\n .map((child) => build(child)),\n }\n }\n return build(op.rootId)\n}\n\nfunction live(canvas: AssistEditCanvas, id: string): AssistEditCanvasNodeLike {\n const node = canvas.getNode(id)\n if (!node) throw new Error(`element ${id} is no longer on the canvas`)\n return node\n}\n\n/** A subtree's ids, depth first in child order, its root first. */\nfunction subtreeInOrder(canvas: Pick<AssistEditCanvas, 'getNode'>, rootId: string): string[] {\n const ids: string[] = []\n const stack = [rootId]\n while (stack.length) {\n const id = stack.pop() as string\n if (ids.includes(id) || !canvas.getNode(id)) continue\n ids.push(id)\n stack.push(...[...(canvas.getNode(id)?.nodes ?? [])].reverse())\n }\n return ids\n}\n\n/** Applies one op; an insert answers the ids of the elements it added. */\nfunction applyOne(canvas: AssistEditCanvas, op: AssistEditOp): string[] | void {\n switch (op.op) {\n case 'updateProps': {\n const node = live(canvas, op.nodeId)\n // Spread the props the element has: `updateNodeProps` REPLACES the bag,\n // and a patch of one setting would otherwise strip every other one.\n const next: Record<string, unknown> = { ...plain(node.props), ...op.props }\n // Rich text renders `html` over `children`; proposed text replaces it.\n if ('children' in op.props) delete next['html']\n canvas.updateNodeProps(node, next)\n return\n }\n case 'updateSx': {\n const node = live(canvas, op.nodeId)\n canvas.updateNodeFields(node, { sx: mergeSx(plain(node.sx), op.sx) })\n return\n }\n case 'move':\n canvas.reparentNode(live(canvas, op.nodeId), live(canvas, op.parentId), op.index ?? NaN)\n return\n case 'remove':\n canvas.deleteNode(live(canvas, op.nodeId))\n return\n case 'rename':\n canvas.updateNodeFields(live(canvas, op.nodeId), { name: op.name })\n return\n case 'addInteraction': {\n // Added beside what the element does already, never in place of it:\n // an id the element already uses is re-minted, so nothing is replaced.\n const node = live(canvas, op.nodeId)\n const current = (Array.isArray(node.interactions) ? node.interactions : []) as NodeInteraction[]\n let id = op.interaction.id\n while (current.some((entry) => entry.id === id)) id = `${op.interaction.id}${current.length}x`\n canvas.updateNodeFields(node, {\n interactions: upsertNodeInteraction(current, { ...op.interaction, id }),\n })\n return\n }\n case 'insertSubtree': {\n const added = canvas.addNodeFromNested(nestSubtree(op), live(canvas, op.parentId), op.index ?? NaN) as\n | AssistEditCanvasNodeLike\n | undefined\n return added?.$id ? subtreeInOrder(canvas, added.$id) : []\n }\n case 'setSeo':\n case 'saveAsComponent':\n // Both are applied outside the canvas batch: search fields are staged\n // into the editor's own form, and a component save mints a document\n // first and then swaps the subtree for an instance of it.\n return\n }\n}\n\n/* ------------------------------------------------------------------ *\n * Save the selection as a reusable component (AGL-2908)\n * ------------------------------------------------------------------ */\n\n/** What the apply needs from the console to create the component. */\nexport interface AssistEditComponentWriter {\n /**\n * Creates the component through `POST /api/hosts/resources`, where the\n * plan's entitlement and the route's field allow-list are enforced, and\n * answers its id. The plugin never writes Firestore from the browser.\n */\n createComponent(input: {\n name: string\n rootId: string\n nodes: Record<string, unknown>\n props: ReusableComponentProp[]\n }): Promise<string>\n}\n\n/**\n * The value a bound field holds on the live canvas right now, which becomes\n * the property's default.\n *\n * `hideIf` is the exception: the part is on the page, so the property that\n * hides it starts at no. Every other field answers with what the author can\n * see, which is what makes the instance render exactly what was there.\n */\nfunction currentValue(\n node: AssistEditCanvasNodeLike,\n field: string,\n): ReusableComponentPropValue | undefined {\n if (field === NODE_HIDE_IF_PROP) return false\n const value = plain(node.props)[field]\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return value\n }\n return undefined\n}\n\n/**\n * Whether a default the canvas gave is one the property's own control\n * offers. A Choice whose current value is not among its answers is a\n * selection that has changed since the proposal was made, and applying it\n * would declare a property no page could ever set back.\n */\nfunction defaultFitsProp(prop: AssistEditComponentProp, value: unknown): boolean {\n if (!prop.options?.length) return true\n return prop.options.some((option) => option.value === value)\n}\n\n/**\n * The definition the new component holds: the promoted subtree, with each\n * bound field replaced by its property's token.\n *\n * The defaults are read off the SAME fields a moment before they are\n * replaced, so the instance that takes the subtree's place renders what the\n * author was looking at. Returns null when a default no longer fits its\n * property, which is the stale case.\n */\nfunction componentDefinition(\n canvas: AssistEditCanvas,\n op: AssistEditSaveAsComponentOp,\n): { nodes: Record<string, unknown>; props: ReusableComponentProp[] } | null {\n const nodes = reusableComponentDefinitionFrom(\n canvas.toJSON().nodes as never,\n op.nodeId,\n ) as unknown as Record<string, Record<string, unknown>>\n const defaults = new Map<string, ReusableComponentPropValue | undefined>()\n for (const binding of op.bindings) {\n const live = canvas.getNode(binding.nodeId)\n const stored = nodes[binding.nodeId]\n if (!live || !stored) return null\n if (!defaults.has(binding.prop)) defaults.set(binding.prop, currentValue(live, binding.field))\n stored['props'] = { ...plain(stored['props']), [binding.field]: `{{prop.${binding.prop}}}` }\n }\n const props: ReusableComponentProp[] = []\n for (const declared of op.props) {\n const value = defaults.get(declared.name)\n if (!defaultFitsProp(declared, value)) return null\n props.push({ ...declared, ...(value === undefined ? {} : { defaultValue: value }) })\n }\n return { nodes, props }\n}\n\n/**\n * Lands a confirmed proposal on the open editor: the canvas ops as ONE batch\n * — one undo step, all or nothing — then any search fields staged into the\n * editor's own form. Nothing is saved.\n */\nexport function applyAssistEdit(\n canvas: AssistEditCanvas,\n proposal: AssistEditProposal,\n session: EditorSession | undefined,\n): AssistEditApplyResult {\n const check = checkAssistEdit(canvas, proposal, session)\n if (check.ok === false) return check\n const open = session as EditorSession\n const canvasOps = proposal.ops.filter((op) => op.op !== 'setSeo' && op.op !== 'saveAsComponent')\n const inserted: AssistEditInserted[] = []\n if (canvasOps.length) {\n try {\n canvas.batch(() => {\n proposal.ops.forEach((op, position) => {\n if (op.op === 'setSeo' || op.op === 'saveAsComponent') return\n const ids = applyOne(canvas, op)\n if (ids) inserted.push({ op: position, ids })\n })\n })\n } catch (error) {\n console.error('assist edit refused by the canvas', error)\n return {\n ok: false,\n reason: 'refused',\n message: 'The editor refused part of this change, so none of it was applied.',\n }\n }\n }\n const staged: string[] = []\n for (const op of proposal.ops) {\n if (op.op !== 'setSeo') continue\n const values: Record<string, string> = {}\n for (const [field, value] of Object.entries(op.fields)) {\n values[screenSeoStageKey(field as ScreenSeoTextField)] = String(value)\n }\n staged.push(...stageEditorSessionFields(open, values).staged)\n }\n return { ok: true, opCounts: assistEditOpCounts(proposal.ops), staged, ...(inserted.length ? { inserted } : {}) }\n}\n\n/**\n * Lands a proposal that saves the selection as a reusable component\n * (AGL-2908) — AGL-2866's recipe, in place, with no clipboard.\n *\n * The order is the manual action's order, and it matters:\n *\n * 1. the definition is read off the live subtree, each bound field replaced\n * by its token and its current value kept as that property's default;\n * 2. the component is created through the host resources route, where the\n * server enforces the plan's entitlement and its own allow-list — so a\n * refusal happens before the open document is touched at all;\n * 3. the subtree is swapped for an instance of what was just created, inside\n * ONE `batch` with the rest of the proposal's canvas ops: one undo step.\n *\n * The only document created is the component, exactly as Save as reusable\n * component creates one. The page change is an unsaved edit on the version\n * the editor has open, which the check has already refused to be a live one.\n * Nothing is published and nothing is saved.\n */\nexport async function applyAssistEditSavingComponent(\n canvas: AssistEditCanvas,\n proposal: AssistEditProposal,\n session: EditorSession | undefined,\n writer: AssistEditComponentWriter,\n): Promise<AssistEditApplyResult> {\n const save = proposal.ops.find(\n (op): op is AssistEditSaveAsComponentOp => op.op === 'saveAsComponent',\n )\n if (!save) return applyAssistEdit(canvas, proposal, session)\n const check = checkAssistEdit(canvas, proposal, session)\n if (check.ok === false) return check\n\n const definition = componentDefinition(canvas, save)\n if (!definition) return STALE as AssistEditApplyResult\n\n let componentId: string\n try {\n componentId = await writer.createComponent({\n name: save.name,\n rootId: save.nodeId,\n nodes: definition.nodes,\n props: definition.props,\n })\n } catch (error) {\n console.error('assist edit could not create the component', error)\n return {\n ok: false,\n reason: 'refused',\n message:\n error instanceof Error && error.message\n ? error.message\n : 'The component could not be saved, so nothing on this page was changed.',\n }\n }\n\n const canvasOps = proposal.ops.filter((op) => op.op !== 'setSeo' && op.op !== 'saveAsComponent')\n try {\n canvas.batch(() => {\n for (const op of canvasOps) applyOne(canvas, op)\n canvas.applyNodes(\n replaceSubtreeWithInstance(\n canvas.toJSON().nodes as never,\n save.nodeId,\n componentId,\n save.name,\n ),\n )\n })\n } catch (error) {\n console.error('assist edit refused by the canvas', error)\n return {\n ok: false,\n reason: 'refused',\n message:\n 'The component was saved, but the editor refused to swap this element for it. ' +\n 'Insert it from Your components instead.',\n }\n }\n return { ok: true, opCounts: assistEditOpCounts(proposal.ops), staged: [] }\n}\n"],"names":["screenSeoStageKey","NODE_HIDE_IF_PROP","replaceSubtreeWithInstance","reusableComponentDefinitionFrom","CANVAS_ROOT_ELEMENT_ID","NODE_MAX_INTERACTIONS","upsertNodeInteraction","stageEditorSessionFields","ASSIST_EDIT_CONTEXT_MAX_NODES","ASSIST_EDIT_CONTEXT_MAX_PROPS","ASSIST_EDIT_OUTLINE_TEXT_CHARS","ASSIST_EDIT_SELECTED_TEXT_CHARS","ASSIST_EDIT_WHOLE_MAX_NODES","assistEditOpCounts","UNDESCRIBED_PROP","isRecord","value","Array","isArray","plain","out","key","describeProps","raw","textChars","props","kept","name","Object","entries","test","trim","slice","Number","isFinite","undefined","describeSx","sx","keys","length","chainToRoot","canvas","selected","chain","walked","Set","current","$id","has","add","unshift","parentId","getNode","SHAPE_LIMIT","shapeOf","rootId","budget","walk","id","node","parts","child","nodes","part","push","String","componentId","join","countElements","count","reached","pending","pop","describeAssistEditCanvas","selectedId","options","root","whole","describeWholeCanvas","order","seen","brief","like","Map","full","briefly","childrenOf","shapes","shape","set","get","alike","model","forEach","inside","queue","shift","siblings","filter","held","level","deeper","ancestor","reverse","section","map","isSelected","outlineElement","styles","total","tier","parent","index","Math","max","indexOf","childCount","summarizeInteractions","interactions","children","some","entry","event","steps","step","enabled","subtreeIds","found","STALE","ok","reason","message","checkAssistEdit","proposal","session","documentKind","target","kind","documentId","op","ops","field","fields","parentComponentId","nodeAcceptsChildren","nodeId","binding","bindings","bound","targets","live","mergeSx","patch","existing","xs","nestSubtree","visited","build","pluginId","hidden","Error","subtreeInOrder","ids","stack","includes","applyOne","next","updateNodeProps","updateNodeFields","reparentNode","NaN","deleteNode","interaction","added","addNodeFromNested","currentValue","defaultFitsProp","prop","option","componentDefinition","toJSON","defaults","stored","declared","defaultValue","applyAssistEdit","check","open","canvasOps","inserted","batch","position","error","console","staged","values","opCounts","applyAssistEditSavingComponent","writer","save","find","definition","createComponent","applyNodes"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,QAEZ,2CAA0C;AACjD,SACEC,iBAAiB,EACjBC,0BAA0B,EAC1BC,+BAA+B,QAC1B,qDAAoD;AAC3D,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,qBAAqB,EACrBC,qBAAqB,QAEhB,2CAA0C;AAKjD,SACEC,wBAAwB,QAEnB,8CAA6C;AACpD,SACEC,6BAA6B,EAC7BC,6BAA6B,EAC7BC,8BAA8B,EAC9BC,+BAA+B,EAC/BC,2BAA2B,EAC3BC,kBAAkB,QASb,0BAAsB;AAiD7B,MAAMC,mBAAmB;AAEzB,MAAMC,WAAW,CAACC,QAChB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF;AAEhE;;;;CAIC,GACD,SAASG,MAAMH,KAAc;IAC3B,MAAMI,MAA+B,CAAC;IACtC,IAAI,CAACJ,SAAS,OAAOA,UAAU,UAAU,OAAOI;IAChD,IAAK,MAAMC,OAAOL,MAAkC;QAClDI,GAAG,CAACC,IAAI,GAAG,AAACL,KAAiC,CAACK,IAAI;IACpD;IACA,OAAOD;AACT;AAEA,SAASE,cACPC,GAAY,EACZC,SAAiB;IAEjB,MAAMC,QAAmD,CAAC;IAC1D,IAAIC,OAAO;IACX,KAAK,MAAM,CAACC,MAAMX,MAAM,IAAIY,OAAOC,OAAO,C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AAQgJ,KAAKtD,MAAM;YACnBnF,OAAO2I,WAAW3I,KAAK;YACvBrC,OAAOgL,WAAWhL,KAAK;QACzB;IACF,EAAE,OAAOuK,OAAO;QACdC,QAAQD,KAAK,CAAC,8CAA8CA;QAC5D,OAAO;YACL/D,IAAI;YACJC,QAAQ;YACRC,SACE6D,iBAAiBhC,SAASgC,MAAM7D,OAAO,GACnC6D,MAAM7D,OAAO,GACb;QACR;IACF;IAEA,MAAMyD,YAAYvD,SAASO,GAAG,CAAC1C,MAAM,CAAC,CAACyC,KAAOA,GAAGA,EAAE,KAAK,YAAYA,GAAGA,EAAE,KAAK;IAC9E,IAAI;QACFlG,OAAOqJ,KAAK,CAAC;YACX,KAAK,MAAMnD,MAAMiD,UAAWvB,SAAS5H,QAAQkG;YAC7ClG,OAAOkK,UAAU,CACfzM,2BACEuC,OAAO2I,MAAM,GAAGtH,KAAK,EACrByI,KAAKtD,MAAM,EACX/E,aACAqI,KAAK5K,IAAI;QAGf;IACF,EAAE,OAAOqK,OAAO;QACdC,QAAQD,KAAK,CAAC,qCAAqCA;QACnD,OAAO;YACL/D,IAAI;YACJC,QAAQ;YACRC,SACE,kFACA;QACJ;IACF;IACA,OAAO;QAAEF,IAAI;QAAMmE,UAAUvL,mBAAmBwH,SAASO,GAAG;QAAGsD,QAAQ,EAAE;IAAC;AAC5E"}
@@ -22,6 +22,7 @@ import { AI_JOB_TERMINAL_STATUSES } from "../model/ai-jobs.types.js";
22
22
  import { mdiChevronDown, mdiChevronUp } from "@aglyn/shared-data-mdi";
23
23
  import { pluginDocsHelp } from "@aglyn/aglyn/app-utils/docs-help";
24
24
  import { AppLink, HelpTip, MdiIcon } from "@aglyn/shared-ui-jsx";
25
+ import { useBuyingHidden } from "@aglyn/shared-ui-jsx/contexts/buying-hidden.context";
25
26
  import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
26
27
  import { Box, Button, Chip, CircularProgress, Collapse, IconButton, Stack, Typography } from "@mui/material";
27
28
  import { useCallback, useEffect, useRef, useState } from "react";
@@ -130,6 +131,8 @@ export { aiJobOutputHref, aiJobPrimaryLink, readEventFrames };
130
131
  export function AssistJobsDrawer({ orgId, org, orgReady, orgSlug, user, visible, isStaff = false, hostId, insight, inFlight, focus, pageHref = null }) {
131
132
  var _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6;
132
133
  const entitled = orgReady && checkEntitlement(org, 'aiGenerative');
134
+ // An app build for store review leaves out every way to buy more.
135
+ const buyingHidden = useBuyingHidden();
133
136
  const [expanded, setExpanded] = useState(false);
134
137
  /**
135
138
  * The person opened or closed the list themselves: from then on the
@@ -627,7 +630,7 @@ export function AssistJobsDrawer({ orgId, org, orgReady, orgSlug, user, visible,
627
630
  onClick: ()=>void resume(job),
628
631
  children: 'Resume'
629
632
  }),
630
- /*#__PURE__*/ _jsx(Button, {
633
+ buyingHidden ? null : /*#__PURE__*/ _jsx(Button, {
631
634
  size: "small",
632
635
  component: AppLink,
633
636
  href: aiCreditsBillingHref(orgSlug),