@qfei-design/make-ai-assistant 0.2.11 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PUBLIC_API.md +5 -4
- package/README.md +6 -7
- package/dist/make-app.cjs +1 -1
- package/dist/make-app.d.ts +1 -1
- package/dist/make-app.mjs +418 -416
- package/dist/react/conversation-controls.d.ts +1 -1
- package/dist/react/use-attachments.d.ts +1 -0
- package/dist/react/use-conversation-manager.d.ts +2 -2
- package/dist/react.cjs +4 -4
- package/dist/react.mjs +1716 -1627
- package/dist/styles.css +368 -177
- package/docs/make-app-integration.md +5 -5
- package/examples/make-app/README.md +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { RefObject } from "react";
|
|
2
2
|
import type { AssistantMessage, AssistantTransport, MakeAssistantHostContext } from "../core/index.js";
|
|
3
3
|
import { type ConversationManager } from "./use-conversation-manager.js";
|
|
4
4
|
export declare function ConversationControls({ id, manager, onDismiss, onNewConversation, triggerRef, }: {
|
|
@@ -9,6 +9,7 @@ export interface AttachmentDraft {
|
|
|
9
9
|
status: "queued" | "uploading" | "completing" | "ready" | "paused" | "failed";
|
|
10
10
|
progress: number;
|
|
11
11
|
error?: string;
|
|
12
|
+
previewUrl?: string;
|
|
12
13
|
upload?: AssistantUpload;
|
|
13
14
|
}
|
|
14
15
|
export declare function useAttachments(context: MakeAssistantHostContext, transport: AssistantTransport, manager: ConversationManager): {
|
|
@@ -26,8 +26,8 @@ export declare function useConversationManager(context: MakeAssistantHostContext
|
|
|
26
26
|
update: (patch: {
|
|
27
27
|
title?: string;
|
|
28
28
|
pinned?: boolean;
|
|
29
|
-
}, target?: AssistantChat | undefined) => Promise<
|
|
30
|
-
remove: (target?: AssistantChat | undefined) => Promise<
|
|
29
|
+
}, target?: AssistantChat | undefined) => Promise<boolean>;
|
|
30
|
+
remove: (target?: AssistantChat | undefined) => Promise<boolean>;
|
|
31
31
|
feedback: (message: AssistantMessage, rating: AssistantFeedbackWrite["rating"], reason?: string, comment?: string) => Promise<boolean | undefined>;
|
|
32
32
|
moreHistory: () => Promise<void>;
|
|
33
33
|
setError: Dispatch<SetStateAction<string | undefined>>;
|
package/dist/react.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),r=require("react"),Ce=require("./index.cjs"),x=require("./conversation-Cvh-IVRV.cjs"),Dt=t=>t?.trim()||void 0,fe=(t,s)=>Dt(t)??s,mt=t=>{const s=Dt(t?.primary);if(s)return{"--make-ai-theme-primary":s,"--make-ai-theme-primary-hover":fe(t?.primaryHover,"color-mix(in srgb, var(--make-ai-theme-primary) 84%, #15233d)"),"--make-ai-theme-on-primary":fe(t?.onPrimary,"#fcfcff"),"--make-ai-theme-bg":fe(t?.background,"color-mix(in srgb, var(--make-ai-theme-primary) 2%, #fcfcff)"),"--make-ai-theme-surface":fe(t?.surface,"color-mix(in srgb, var(--make-ai-theme-primary) 4%, var(--make-ai-theme-bg))"),"--make-ai-theme-surface-strong":fe(t?.surfaceStrong,"color-mix(in srgb, var(--make-ai-theme-primary) 8%, var(--make-ai-theme-bg))"),"--make-ai-theme-text":fe(t?.text,"color-mix(in srgb, var(--make-ai-theme-primary) 12%, #252631)"),"--make-ai-theme-text-secondary":fe(t?.textSecondary,"color-mix(in srgb, var(--make-ai-theme-text) 74%, var(--make-ai-theme-primary))"),"--make-ai-theme-border":fe(t?.border,"color-mix(in srgb, var(--make-ai-theme-primary) 14%, var(--make-ai-theme-bg))"),"--make-ai-theme-overlay":fe(t?.overlay,"color-mix(in srgb, var(--make-ai-theme-text) 88%, var(--make-ai-theme-primary))"),"--make-ai-theme-on-overlay":fe(t?.onOverlay,"#fcfcff")}},Tt=(t,s)=>!s||!r.isValidElement(t)||typeof t.type!="string"?t:r.cloneElement(t,{style:{...t.props.style,...s}});function Ot({artifact:t,context:s,fallback:a,onAction:o,onActionError:n,registry:c,theme:d}){const g=mt(d),p=Ce.resolveArtifactTemplate(c,t,s);if(!p){const E=a?a(t):e.jsxs("section",{className:"make-ai-artifact make-ai-artifact--unsupported",role:"status",children:[e.jsx("strong",{children:"暂不支持展示此结果"}),e.jsxs("span",{children:["结果类型:",t.kind]})]});return Tt(E,g)}const f={context:s,onAction:o,onActionError:n,theme:d,themeStyle:g},j=p.template.render(t,s,f);return Tt(j,g)}const Re=(t,s,a)=>{if(t==null||t==="")return"—";if(typeof t=="boolean")return t?"是":"否";if(typeof t!="number")return`${t}${s?.unit??""}`;const o=s?.precision,n={maximumFractionDigits:o??2,minimumFractionDigits:o};s?.style==="currency"&&s.currency?(n.style="currency",n.currency=s.currency):s?.style==="percent"&&(n.style="percent");try{const c=s?.style==="percent"?t/100:t;return`${new Intl.NumberFormat(a,n).format(c)}${s?.unit??""}`}catch{return`${t}${s?.unit??""}`}},Ft=t=>{let s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const o of t)s=Math.min(s,o),a=Math.max(a,o);return Number.isFinite(s)&&Number.isFinite(a)?{min:s,max:a}:{min:0,max:0}},Pt=(t,s,a)=>{if(!a.onAction)return;const o=c=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:t.id,artifactId:s.artifact.id,errorType:c instanceof Error?c.name:typeof c,intent:t.intent})},n=c=>{if(a.onActionError){try{Promise.resolve(a.onActionError(c,t,s)).catch(o)}catch(d){o(d)}return}console.error("[make-ai-assistant] host action failed",{actionId:t.id,artifactId:s.artifact.id,errorType:c instanceof Error?c.name:typeof c,intent:t.intent})};try{Promise.resolve(a.onAction(t,s)).catch(n)}catch(c){n(c)}},Fe=(t,s)=>t.actions?.length&&s.onAction?e.jsx("div",{className:"make-ai-artifact__actions",children:t.actions.map(a=>e.jsxs("button",{className:`make-ai-artifact__action make-ai-artifact__action--${a.appearance??"link"}`,type:"button",onClick:()=>Pt(a,{artifact:t,context:s.context},s),children:[a.label,e.jsx("span",{"aria-hidden":"true",children:"→"})]},a.id))}):null,Pe=(t,s,a="",o)=>e.jsxs("section",{"aria-label":t.title??`${t.kind} result`,className:`make-ai-artifact ${a}`.trim(),"data-artifact-density":t.presentation?.density,"data-artifact-kind":t.kind,style:o,children:[t.title?e.jsx("h4",{className:"make-ai-artifact__title",children:t.title}):null,t.summary?e.jsx("p",{className:"make-ai-artifact__summary",children:t.summary}):null,s]}),ls=({artifact:t,renderContext:s})=>{const a=t.data.delta,o=a?Re(a.value,a.format==="percent"?{style:"percent"}:void 0,s.context.locale):void 0;return Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__metric-value",children:Re(t.data.value,t.data.format,s.context.locale)}),a?e.jsxs("div",{className:`make-ai-artifact__delta make-ai-artifact__delta--${a.direction??"flat"}`,children:[e.jsx("span",{"aria-hidden":"true",children:a.direction==="up"?"↗":a.direction==="down"?"↘":"→"}),e.jsx("span",{children:o}),a.label?e.jsx("span",{children:a.label}):null]}):null,t.data.context?e.jsx("p",{className:"make-ai-artifact__context",children:t.data.context}):null,Fe(t,s)]}),"make-ai-artifact--metric",s.themeStyle)},ds=({artifact:t,renderContext:s})=>Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__comparison",children:t.data.items.map(a=>e.jsxs("div",{className:"make-ai-artifact__comparison-item",children:[e.jsx("span",{children:a.label}),e.jsx("strong",{children:Re(a.value,a.format,s.context.locale)}),a.hint?e.jsx("small",{children:a.hint}):null]},a.id))}),Fe(t,s)]}),"make-ai-artifact--comparison",s.themeStyle),us=({artifact:t,renderContext:s})=>{const a=t.data.series.flatMap(d=>d.points.map(g=>g.y)),{max:o,min:n}=Ft(a),c=o-n||1;return Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__trend",children:t.data.series.map(d=>e.jsxs("div",{className:"make-ai-artifact__trend-series",children:[e.jsx("div",{className:"make-ai-artifact__trend-label",children:d.label}),e.jsx("div",{className:"make-ai-artifact__trend-bars",children:d.points.map((g,p)=>{const f=18+(g.y-n)/c*70;return e.jsxs("div",{className:"make-ai-artifact__trend-point",children:[e.jsx("span",{"aria-label":`${g.x}: ${Re(g.y,d.format,s.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${f}%`},title:`${g.x}: ${Re(g.y,d.format,s.context.locale)}`}),e.jsx("small",{children:g.x})]},`${g.x}-${p}`)})})]},d.id))}),Fe(t,s)]}),"make-ai-artifact--trend",s.themeStyle)},ms=({artifact:t,renderContext:s})=>{const{max:a}=Ft(t.data.items.map(n=>Math.abs(n.value))),o=Math.max(a,1);return Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("ol",{className:"make-ai-artifact__ranking",children:t.data.items.map((n,c)=>e.jsxs("li",{children:[e.jsx("span",{className:"make-ai-artifact__rank",children:c+1}),e.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[e.jsx("span",{children:n.label}),n.description?e.jsx("small",{children:n.description}):null]}),e.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.abs(n.value)/o*100}%`}})}),e.jsx("strong",{children:Re(n.value,n.format,s.context.locale)})]},n.id))}),Fe(t,s)]}),"make-ai-artifact--ranking",s.themeStyle)},hs=(t,s)=>s.action??{id:`open-${s.id}`,label:s.title??s.id,intent:"open-record",target:{entityKey:t.data.entity.key,recordId:s.id}},fs=({artifact:t,renderContext:s})=>Pe(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__record-list",children:t.data.records.length===0?e.jsx("p",{className:"make-ai-artifact__empty",children:"没有符合条件的记录"}):t.data.records.map(a=>{const o=hs(t,a),n=e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a.title??a.id}),e.jsx("span",{className:"make-ai-artifact__record-values",children:t.data.columns.map(c=>e.jsxs("span",{children:[e.jsx("small",{children:c.label}),Re(a.values[c.key],c.format,s.context.locale)]},c.key))}),s.onAction?e.jsx("span",{"aria-hidden":"true",children:"›"}):null]});return s.onAction?e.jsx("button",{className:"make-ai-artifact__record",type:"button",onClick:()=>Pt(o,{artifact:t,context:s.context},s),children:n},a.id):e.jsx("div",{className:"make-ai-artifact__record",children:n},a.id)})}),t.data.total!==void 0?e.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",t.data.total," 条"]}):null,Fe(t,s)]}),"make-ai-artifact--record-list",s.themeStyle),ps=({artifact:t,renderContext:s})=>Pe(t,e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`make-ai-artifact__notice make-ai-artifact__notice--${t.data.tone}`,children:[e.jsx("span",{"aria-hidden":"true",children:t.data.tone==="success"?"✓":t.data.tone==="warning"?"!":t.data.tone==="danger"?"×":"i"}),e.jsx("p",{children:t.data.body})]}),Fe(t,s)]}),"make-ai-artifact--notice",s.themeStyle),De=(t,s,a)=>({id:t,kinds:[s],priority:0,render:a}),vs=[De("platform.metric.default","metric",(t,s,a)=>e.jsx(ls,{artifact:t,renderContext:a})),De("platform.comparison.default","comparison",(t,s,a)=>e.jsx(ds,{artifact:t,renderContext:a})),De("platform.trend.default","trend",(t,s,a)=>e.jsx(us,{artifact:t,renderContext:a})),De("platform.ranking.default","ranking",(t,s,a)=>e.jsx(ms,{artifact:t,renderContext:a})),De("platform.record-list.default","record-list",(t,s,a)=>e.jsx(fs,{artifact:t,renderContext:a})),De("platform.notice.default","notice",(t,s,a)=>e.jsx(ps,{artifact:t,renderContext:a}))],Bt=Ce.createArtifactTemplateRegistry(vs).templates,zt=(t=Bt)=>Ce.createArtifactTemplateRegistry(t),Oe=()=>globalThis.crypto.randomUUID(),ht=t=>{const s=t,a=s?.status??s?.response?.status;return a===409?"数据已变化或对话仍在运行,请刷新后重试":a===401||s?.code==="AI_AUTH_REQUIRED"||s?.code==="AI_AUTH_EXPIRED"?"登录已失效,请重新登录":a===403?"当前账号无权访问该对话":a===404?"对话或回答已不可见,请刷新列表":s?.message?.startsWith("输入内容过长")?s.message:"操作未完成,请重试或刷新对话"};function gs(t,s){const a=s.features?.conversationManagement===!0,o=a?s.scopeKey?.(t)??t.app.id:"",n=r.useRef(o);n.current=o;const c=r.useRef(o),[d,g]=r.useState(x.createAssistantConversationState),p=r.useRef(d),f=i=>{const h=typeof i=="function"?i(p.current):i;p.current=h,g(h)},[j,E]=r.useState([]),[B,H]=r.useState(),y=r.useRef(void 0),[V,Q]=r.useState(""),[W,v]=r.useState(-1),[u,l]=r.useState(!1),[T,N]=r.useState(!1),[ae,R]=r.useState(a),[G,K]=r.useState(!1),[L,q]=r.useState(),[ne,re]=r.useState([]),[de,ye]=r.useState([]),be=r.useRef(new Set),X=r.useRef(new Map),k=r.useRef(0),b=r.useRef(0),P=r.useRef(0),Y=r.useRef(void 0),ee=r.useRef(void 0),Se=r.useRef(new Map),C=(i,h=o)=>b.current===i&&n.current===h,te=()=>{const i=new AbortController;return be.current.add(i),i},ie=i=>be.current.delete(i),ue=i=>{y.current=i,H(i)},je=()=>{for(const i of X.current.values())i.abort();X.current.clear()},J=i=>{i instanceof Error&&i.name==="AbortError"||(console.warn("[make-ai-assistant] conversation operation failed",{errorType:i instanceof Error?i.name:typeof i}),q(ht(i)))},ve=async i=>{if(!a||!s.listConversations)return;const h=b.current,_=++P.current,A=te();try{const w=await s.listConversations(t,{cursor:i},{signal:A.signal});if(!C(h)||A.signal.aborted||_!==P.current)return;E(S=>[...new Map([...i?S:[],...w.chats].map(I=>[I.chatId,I])).values()]),Q(w.nextCursor)}catch(w){C(h)&&!A.signal.aborted&&J(w)}finally{ie(A),C(h)&&R(!1)}},_e=async(i,h,_)=>{const A=b.current,w=k.current;let S;try{for await(const I of i){if(!C(A)||h.signal.aborted||w!==k.current||y.current?.chatId!==_)return;const z=x.parseAssistantEvent(I);if(z.type==="response.accepted"||z.type==="response.state"){S=z.responseId;const F=X.current.get(S);if(F&&F!==h){z.type==="response.accepted"&&f(O=>x.reduceAssistantEvent(O,z)),h.abort();return}X.current.set(S,h)}f(F=>x.reduceAssistantEvent(F,z)),z.type==="response.terminal"&&(re(F=>F.filter(O=>O!==z.responseId)),ve())}}catch(I){C(A)&&!h.signal.aborted&&w===k.current&&(J(I),S||f(z=>({...z,status:Object.values(z.responses??{}).some(F=>!x.isResponseTerminal(F.status))?"streaming":"error"})))}finally{S&&X.current.get(S)===h&&X.current.delete(S),ie(h)}},Xe=async(i,h,_,A)=>{if(!s.getResponse||!s.watchResponse)return;const w=new Set(i.filter(I=>I.role==="assistant"&&I.persistent).map(I=>I.responseId)),S=[...new Map(i.filter(I=>I.role==="user"&&I.responseId&&!w.has(I.responseId)).map(I=>[I.responseId,I.cursor??-1])).entries()].slice(-20);for(const[I,z]of S){if(!C(A)||_!==k.current)return;if(X.current.has(I))continue;const F=te();try{const O=await s.getResponse(t,{chatId:h,responseId:I},{signal:F.signal});if(!C(A)||F.signal.aborted||_!==k.current||X.current.has(I))continue;f(he=>x.reduceAssistantEvent(he,x.isResponseTerminal(O.status)?{type:"response.snapshot",snapshot:O}:{type:"response.state",chatId:h,responseId:I,status:O.status})),O.status==="failed"||O.status==="cancelled"?f(he=>x.reduceAssistantEvent(he,{type:"response.terminal",chatId:h,responseId:I,status:O.status})):(X.current.set(I,F),_e(s.watchResponse(t,{chatId:h,responseId:I,historyCursor:z},{signal:F.signal}),F,h))}catch(O){C(A)&&!F.signal.aborted&&J(O)}finally{X.current.get(I)!==F&&ie(F)}}},oe=async i=>{const h=++k.current,_=b.current,A=te();je(),q(void 0),R(!0),re([]),ee.current=void 0,ue(i),f({messages:[],status:"idle",threadId:i.chatId}),v(-1),l(!1),N(!1);try{const[w,S]=await Promise.all([s.getConversation(t,{chatId:i.chatId},{signal:A.signal}),s.loadConversation(t,{threadId:i.chatId,cursor:-1,signal:A.signal})]);if(!C(_)||A.signal.aborted||h!==k.current)return;if(w.chatId!==i.chatId||S.threadId!==i.chatId)throw new Error("Conversation mismatch");ue(w),f(x.createAssistantConversationState(S)),v(S.nextCursor??-1),l(S.hasMore??!1),Xe(S.messages,i.chatId,h,_)}catch(w){C(_)&&!A.signal.aborted&&h===k.current&&J(w)}finally{ie(A),C(_)&&h===k.current&&R(!1)}},me=async()=>{if(y.current)return y.current;if(Y.current??={requestId:Oe()},Y.current.promise)return Y.current.promise;const i=b.current,h=k.current,_=te(),A=Y.current;return K(!0),A.promise=s.createConversation(t,{requestId:A.requestId},{signal:_.signal}).then(w=>{if(!C(i)||_.signal.aborted||h!==k.current)throw Object.assign(new Error("Stale create"),{name:"AbortError"});return Y.current=void 0,ue(w),f({messages:[],status:"idle",threadId:w.chatId}),ve(),w}).finally(()=>{ie(_),A.promise=void 0,C(i)&&K(!1)}),A.promise},Ye=async()=>{if(!(G||Y.current?.promise)){k.current+=1,je(),ue(void 0),q(void 0),ee.current=void 0,f(x.createAssistantConversationState()),l(!1),v(-1);try{await me()}catch(i){J(i)}}},ke=async i=>{const h=te();ee.current=i,q(void 0),p.current.messages.some(_=>_.id===i.message.id)||f(_=>x.appendUserMessage(_,i.message)),await _e(s.run(i,{signal:h.signal}),h,i.threadId)},Ze=async(i,h)=>{if(!(!i.trim()&&!h?.length))try{const _=await me(),A={id:Oe(),content:i,...h?{parts:h}:{}};await ke({threadId:_.chatId,message:A,context:t,capabilities:{artifactSchemaVersions:[],artifactKinds:[],templates:[]}})}catch(_){J(_)}},Ie=async()=>{const i=ee.current;if(!i||i.threadId!==y.current?.chatId){y.current&&await oe(y.current);return}const h=p.current.messages.find(_=>_.id===i.message.id);if(h?.responseId&&s.watchResponse){const _=h.responseId;if(X.current.has(_))return;const A=te();X.current.set(_,A),q(void 0),await _e(s.watchResponse(t,{chatId:i.threadId,responseId:_,historyCursor:h.cursor},{signal:A.signal}),A,i.threadId)}else await ke(i)},Ae=async(i=p.current.activeRunId)=>{const h=y.current;if(!h||!i||!s.cancelResponse||ne.includes(i))return;const _=b.current,A=k.current,w=te();re(S=>[...S,i]),q(void 0);try{const S=await s.cancelResponse(t,{chatId:h.chatId,responseId:i},{signal:w.signal});if(!C(_)||A!==k.current)return;if(x.isResponseTerminal(S.status))f(I=>x.reduceAssistantEvent(I,{type:"response.snapshot",snapshot:S})),re(I=>I.filter(z=>z!==i));else if(!X.current.has(i)&&s.watchResponse){const I=te();X.current.set(i,I),_e(s.watchResponse(t,{chatId:h.chatId,responseId:i},{signal:I.signal}),I,h.chatId)}}catch(S){C(_)&&A===k.current&&(J(S),re(I=>I.filter(z=>z!==i)))}finally{ie(w)}},we=async(i,h=y.current)=>{if(!h||G)return;const _=b.current,A=te();K(!0),q(void 0);try{const w=await s.updateConversation(t,{chatId:h.chatId,expectedRevision:h.revision,...i},{signal:A.signal});if(!C(_))return;y.current?.chatId===w.chatId&&ue(w),await ve()}catch(w){if(C(_)){J(w);try{const S=await s.getConversation(t,{chatId:h.chatId},{signal:A.signal});C(_)&&y.current?.chatId===h.chatId&&ue(S)}catch{}ve()}}finally{ie(A),C(_)&&K(!1)}},Ge=async(i=y.current)=>{if(!i||G)return;const h=b.current,_=te();K(!0),q(void 0);try{if(await s.deleteConversation(t,{chatId:i.chatId,expectedRevision:i.revision},{signal:_.signal}),!C(h))return;y.current?.chatId===i.chatId&&(k.current+=1,je(),ue(void 0),f(x.createAssistantConversationState())),await ve()}catch(A){C(h)&&J(A)}finally{ie(_),C(h)&&K(!1)}},Ee=async(i,h,_="",A="")=>{const w=y.current;if(!w||!i.persistent||!s.setFeedback||de.includes(i.id))return;const S={chatId:w.chatId,messageId:i.id,rating:h,..._?{reason:_}:{},...A?{comment:A}:{}},I=Se.current.get(i.id),{requestId:z,...F}=I??{requestId:""},O=I&&JSON.stringify(F)===JSON.stringify(S)?I:{...S,requestId:Oe()};Se.current.set(i.id,O);const he=b.current,Be=k.current,ze=te();ye(ce=>[...ce,i.id]),q(void 0);try{const ce=await s.setFeedback(t,O,{signal:ze.signal});return!C(he)||Be!==k.current||Se.current.get(i.id)!==O?void 0:(f(Ne=>({...Ne,messages:Ne.messages.map(ge=>ge.id===i.id&&ce.revision>=(ge.feedback?.revision??0)?{...ge,feedback:ce}:ge)})),Se.current.delete(i.id),!0)}catch(ce){return C(he)&&Be===k.current&&J(ce),!1}finally{ie(ze),C(he)&&ye(ce=>ce.filter(Ne=>Ne!==i.id))}},Je=async()=>{if(!y.current||!u||ae)return;const i=b.current,h=k.current,_=y.current,A=te();R(!0);try{const w=await s.loadConversation(t,{threadId:_.chatId,cursor:W,signal:A.signal});if(!C(i)||h!==k.current)return;const S=x.createAssistantConversationState(w),I=[...new Map([...p.current.messages,...S.messages].map(O=>[O.id,O])).values()];let z=0;const F=[];for(const O of I.slice(-200).reverse()){if(z+=[...O.content].length,z>1e6)break;F.unshift(O)}F.length<I.length&&N(!0),f(O=>({...O,messages:F})),v(w.nextCursor??W),l(w.hasMore??!1),Xe(w.messages,_.chatId,h,i)}catch(w){C(i)&&J(w)}finally{ie(A),C(i)&&R(!1)}};r.useEffect(()=>(b.current+=1,c.current=o,Y.current=void 0,ee.current=void 0,Se.current.clear(),ue(void 0),E([]),Q(""),f(x.createAssistantConversationState()),q(void 0),R(a),K(!1),re([]),ye([]),a&&ve(),()=>{b.current+=1,k.current+=1;for(const i of be.current)i.abort();be.current.clear(),X.current.clear()}),[a,o,s]);const Te=c.current===o;return{enabled:a,state:Te?d:x.createAssistantConversationState(),setState:f,chats:Te?j:[],chat:Te?B:void 0,listCursor:V,historyMore:u,historyTruncated:T,loading:!Te||ae,busy:G,error:Te?L:void 0,cancelling:ne,feedbackBusy:de,refresh:ve,select:oe,create:Ye,ensureChat:me,send:Ze,retry:Ie,stop:Ae,update:we,remove:Ge,feedback:Ee,moreHistory:Je,setError:q}}const xs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M5 5.5h14v10H9l-4 3v-13Z"}),e.jsx("path",{d:"M8 9h8M8 12h6"})]}),ys=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})});function bs({id:t,manager:s,onDismiss:a,onNewConversation:o,triggerRef:n}){const[c,d]=r.useState(""),[g,p]=r.useState(!1),f=r.useRef(null);return r.useEffect(()=>{d(s.chat?.title??""),p(!1)},[s.chat?.chatId,s.chat?.title]),r.useEffect(()=>{const j=E=>{const B=E.target;B instanceof Node&&(f.current?.contains(B)||n.current?.contains(B)||a())};return document.addEventListener("pointerdown",j),()=>{document.removeEventListener("pointerdown",j)}},[a,n]),e.jsxs("div",{"aria-label":"任务列表",className:"make-ai-assistant__conversation-controls",id:t,ref:f,role:"dialog",children:[e.jsxs("div",{className:"make-ai-assistant__conversation-heading",children:[e.jsx("span",{children:"最近对话"}),e.jsx("button",{"aria-label":"刷新任务列表",className:"make-ai-assistant__conversation-refresh",disabled:s.busy,type:"button",onClick:()=>{s.refresh()},children:"刷新"})]}),e.jsxs("nav",{"aria-label":"对话列表",className:"make-ai-assistant__conversation-list",children:[s.chats.map(j=>e.jsxs("div",{className:"make-ai-assistant__conversation-row",children:[e.jsxs("button",{type:"button","aria-pressed":s.chat?.chatId===j.chatId,onClick:()=>{a(),s.select(j)},children:[e.jsx(xs,{}),e.jsx("span",{children:j.title||"未命名对话"})]}),e.jsx("button",{type:"button",disabled:s.busy,"aria-label":`${j.pinned?"取消置顶":"置顶"} ${j.title}`,onClick:()=>{s.update({pinned:!j.pinned},j)},children:j.pinned?"★":"☆"})]},j.chatId)),!s.loading&&!s.chats.length?e.jsx("p",{children:"暂无对话,发送消息即可新建"}):null,s.listCursor?e.jsx("button",{className:"make-ai-assistant__conversation-more",type:"button",onClick:()=>{s.refresh(s.listCursor)},children:"更多对话"}):null]}),s.chat?e.jsxs("details",{className:"make-ai-assistant__conversation-management",children:[e.jsx("summary",{children:"管理当前对话"}),e.jsxs("div",{className:"make-ai-assistant__conversation-actions",children:[e.jsx("input",{"aria-label":"对话标题",maxLength:255,value:c,onChange:j=>d(j.currentTarget.value)}),e.jsx("button",{type:"button",disabled:s.busy||!c.trim(),onClick:()=>{s.update({title:c})},children:"保存标题"}),e.jsx("button",{type:"button",disabled:s.busy,onClick:()=>p(!0),children:"删除对话"}),g?e.jsxs("div",{role:"group","aria-label":"确认删除对话",children:[e.jsxs("span",{children:["删除“",s.chat.title,"”?"]}),e.jsx("button",{type:"button",disabled:s.busy,onClick:()=>{p(!1),s.remove()},children:"确认删除"}),e.jsx("button",{type:"button",onClick:()=>p(!1),children:"保留"})]}):null,s.historyMore?e.jsx("button",{type:"button",disabled:s.loading,onClick:()=>{s.moreHistory()},children:"继续加载历史"}):null,s.historyTruncated||s.state.historyTruncated?e.jsx("p",{children:"当前展示有界消息窗口,可重新选择对话从头读取。"}):null]})]}):null,s.error?e.jsxs("div",{className:"make-ai-assistant__conversation-error",role:"alert",children:[e.jsx("span",{children:s.error}),e.jsx("button",{type:"button",onClick:()=>{s.retry()},children:"恢复对话"})]}):null,o?e.jsxs("button",{className:"make-ai-assistant__conversation-new",type:"button",onClick:o,children:[e.jsx(ys,{}),e.jsx("span",{children:"新建对话"})]}):null]})}function js({message:t,manager:s}){const[a,o]=r.useState(!1),[n,c]=r.useState(""),[d,g]=r.useState(""),p=s.feedbackBusy.includes(t.id);if(!t.persistent||t.role!=="assistant"||t.intermediate)return null;const f=t.feedback?.rating??"none";return e.jsxs("div",{className:"make-ai-assistant__feedback","aria-label":"回答反馈",children:[e.jsx("button",{type:"button","aria-label":"点赞","aria-pressed":f==="like",disabled:p,onClick:()=>{s.feedback(t,f==="like"?"none":"like")},children:"赞"}),e.jsx("button",{type:"button","aria-label":"点踩","aria-pressed":f==="dislike",disabled:p,onClick:()=>{if(f==="dislike"){s.feedback(t,"none");return}c(t.feedback?.reason??""),g(t.feedback?.comment??""),o(!0)},children:"踩"}),f==="dislike"?e.jsx("button",{type:"button",disabled:p,onClick:()=>{c(t.feedback?.reason??""),g(t.feedback?.comment??""),o(!0)},children:"修改反馈"}):null,a?e.jsxs("form",{onSubmit:j=>{j.preventDefault(),s.feedback(t,"dislike",n,d).then(E=>{E&&o(!1)})},children:[e.jsx("input",{"aria-label":"反馈原因",maxLength:128,value:n,onChange:j=>c(j.currentTarget.value),placeholder:"原因(可选)"}),e.jsx("textarea",{"aria-label":"反馈说明",maxLength:4e3,value:d,onChange:j=>g(j.currentTarget.value),placeholder:"补充说明(可选)"}),e.jsx("button",{type:"submit",disabled:p,children:"提交反馈"}),e.jsx("button",{type:"button",onClick:()=>o(!1),children:"取消"})]}):null]})}const Mt=new Set(["image/png","image/jpeg","image/webp","image/gif","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg"]);function _s({part:t,context:s,transport:a,chatId:o}){const[n,c]=r.useState(),[d,g]=r.useState(),[p,f]=r.useState(!1),j=r.useRef([]),E=r.useRef(void 0);r.useEffect(()=>()=>{E.current?.abort(),j.current.forEach(H=>URL.revokeObjectURL(H))},[]);const B=async H=>{if(!a.readContent||p)return;const y=new AbortController;E.current=y,f(!0),g(void 0);try{const V=await a.readContent(s,{chatId:o,contentRef:t.media.contentRef},{signal:y.signal});if(y.signal.aborted)return;const Q=new Blob([new Uint8Array(V).buffer],{type:H&&Mt.has(t.media.contentType)?t.media.contentType:"application/octet-stream"}),W=URL.createObjectURL(Q);if(j.current.push(W),H)c(W);else{const v=document.createElement("a");v.href=W,v.download=t.name??"attachment",v.click()}}catch(V){y.signal.aborted||g(ht(V))}finally{y.signal.aborted||f(!1)}};return e.jsxs("div",{className:"make-ai-assistant__attachment",children:[e.jsxs("span",{children:[t.name??"附件"," · ",t.media.sizeBytes," 字节"]}),e.jsx("button",{type:"button",disabled:p,onClick:()=>{B(!1)},children:"下载附件"}),Mt.has(t.media.contentType)?e.jsx("button",{type:"button",disabled:p,onClick:()=>{B(!0)},children:"预览附件"}):null,d?e.jsx("span",{role:"alert",children:d}):null,n&&t.kind==="image"?e.jsx("img",{src:n,alt:t.name??"附件图片"}):null,n&&t.kind==="audio"?e.jsx("audio",{src:n,controls:!0}):null,n&&t.kind==="video"?e.jsx("video",{src:n,controls:!0}):null]})}function ks({message:t,context:s,transport:a,chatId:o}){return e.jsx(e.Fragment,{children:t.parts?.map((n,c)=>n.kind==="text"?null:e.jsx(_s,{part:n,context:s,transport:a,chatId:o},n.id??`${t.id}:${c}`))})}const Is=(t,s)=>new Promise((a,o)=>{const n=new FileReader,c=()=>s.removeEventListener("abort",d),d=()=>{n.abort(),c(),o(Object.assign(new Error("Read aborted"),{name:"AbortError"}))};if(s.aborted){d();return}s.addEventListener("abort",d,{once:!0}),n.onload=()=>{c(),a(new Uint8Array(n.result))},n.onerror=()=>{c(),o(new Error("无法读取文件"))},n.readAsArrayBuffer(t)});function As(t,s,a){const[o,n]=r.useState([]),c=r.useRef(new Map),d=r.useRef(Promise.resolve()),g=s.scopeKey?.(t)??t.app.id,p=r.useRef(g);p.current=g;const f=r.useRef(void 0),j=a.enabled&&s.features?.attachments===!0,E=(u,l)=>{!c.current.has(u.draft.id)||u.scope!==p.current||(u.draft={...u.draft,...l},n([...c.current.values()].map(T=>T.draft)))},B=()=>{for(const u of c.current.values())u.controller.abort();c.current.clear(),n([]),f.current=void 0,d.current=Promise.resolve()};r.useEffect(()=>(B(),B),[g,s]),r.useEffect(()=>{f.current&&a.chat?.chatId!==f.current&&B()},[a.chat?.chatId]);const H=async u=>{const l=u.controller.signal,T=()=>{if(l.aborted||u.scope!==p.current||!c.current.has(u.draft.id))throw Object.assign(new Error("Upload aborted"),{name:"AbortError"})};try{if(T(),u.file.size>64<<20)throw new Error("文件不能超过 64 MiB");const N=await a.ensureChat();T(),f.current=N.chatId;const ae=u.file.type.split(";")[0].trim().toLowerCase()||"application/octet-stream";E(u,{status:"uploading",error:void 0});let R=u.draft.upload?await s.getUpload(t,{chatId:N.chatId,uploadId:u.draft.upload.id},{signal:l}):await s.startUpload(t,{chatId:N.chatId,fileId:u.draft.fileId,name:u.file.name,contentType:ae,sizeBytes:u.file.size},{signal:l});if(T(),E(u,{upload:R}),R.name!==u.file.name||R.contentType!==ae||R.sizeBytes!==u.file.size)throw new Error("上传文件身份不一致");if(R.status!=="ready"){R=await s.getUpload(t,{chatId:N.chatId,uploadId:R.id},{signal:l}),T();const G=new Set(R.completedParts),K=Math.ceil(u.file.size/R.partSize);for(let L=0;L<K;L+=1){if(T(),!G.has(L)){const q=await Is(u.file.slice(L*R.partSize,Math.min(u.file.size,(L+1)*R.partSize)),l);T(),await s.uploadPart(t,{chatId:N.chatId,uploadId:R.id,part:L,bytes:q},{signal:l}),T(),G.add(L)}E(u,{progress:G.size/Math.max(K,1)})}E(u,{status:"completing"}),R=await s.completeUpload(t,{chatId:N.chatId,uploadId:R.id},{signal:l}),T()}if(R.status!=="ready"||!R.content)throw new Error("上传尚未完成");E(u,{status:"ready",progress:1,upload:R})}catch(N){E(u,{status:l.aborted?"paused":"failed",error:l.aborted?void 0:ht(N)})}},y=u=>{if(j){if(u.length+c.current.size>32){a.setError("每条消息最多包含 32 个附件或文本片段");return}for(const l of u){const T={id:Oe(),fileId:Oe(),name:l.name,size:l.size,status:"queued",progress:0},N={draft:T,file:l,controller:new AbortController,scope:g};c.current.set(T.id,N),d.current=d.current.then(()=>H(N))}n([...c.current.values()].map(l=>l.draft))}},V=u=>{const l=c.current.get(u);!l||!["paused","failed"].includes(l.draft.status)||(l.controller=new AbortController,E(l,{status:"queued"}),d.current=d.current.then(()=>H(l)))},Q=u=>{c.current.get(u)?.controller.abort(),c.current.delete(u),n([...c.current.values()].map(T=>T.draft))},W=u=>c.current.get(u)?.controller.abort(),v=o.flatMap(u=>{const l=u.upload;if(u.status!=="ready"||!l?.content)return[];const T=l.contentType.startsWith("image/")&&l.contentType!=="image/svg+xml"?"image":l.contentType.startsWith("audio/")?"audio":l.contentType.startsWith("video/")?"video":"file";return[{id:u.id,kind:T,name:l.name,media:{contentRef:l.content.contentRef,contentType:l.contentType,sizeBytes:l.content.sizeBytes,digestSha256:l.content.digestSha256}}]});return{enabled:j,drafts:o,parts:v,pending:o.some(u=>u.status!=="ready"),add:y,retry:V,remove:Q,pause:W,clear:B}}function ws({attachments:t,onOpenChange:s,open:a,triggerRef:o}){const n=r.useRef(null),c=r.useRef(null),d=r.useRef(null);r.useEffect(()=>{if(!a)return;const p=f=>{const j=f.target;j instanceof Node&&!n.current?.contains(j)&&s(!1)};return document.addEventListener("pointerdown",p),()=>{document.removeEventListener("pointerdown",p)}},[s,a]);const g=p=>{t.add(Array.from(p.files??[])),p.value="",s(!1)};return e.jsxs("div",{className:"make-ai-assistant__attachment-composer",ref:n,children:[e.jsx("button",{"aria-expanded":a,"aria-haspopup":"menu","aria-label":"添加附件",className:"make-ai-assistant__attachment-trigger",ref:o,title:"添加附件",type:"button",onClick:()=>s(!a),children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})}),a?e.jsxs("div",{"aria-label":"附件选项",className:"make-ai-assistant__attachment-menu",role:"menu",children:[e.jsxs("button",{role:"menuitem",type:"button",onClick:()=>c.current?.click(),children:[e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("rect",{height:"15",rx:"2",width:"18",x:"3",y:"4.5"}),e.jsx("circle",{cx:"8.5",cy:"9",r:"1.5"}),e.jsx("path",{d:"m5.5 17 4.2-4.2 2.8 2.7 2.2-2.1 3.8 3.6"})]}),e.jsx("span",{children:"上传图片"})]}),e.jsxs("button",{role:"menuitem",type:"button",onClick:()=>d.current?.click(),children:[e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M7 3.5h7l4 4V20H7z"}),e.jsx("path",{d:"M14 3.5v4h4M10 12h5M10 15h5"})]}),e.jsx("span",{children:"上传文件"})]})]}):null,e.jsx("input",{accept:"image/*","aria-label":"上传图片",hidden:!0,multiple:!0,ref:c,type:"file",onChange:p=>g(p.currentTarget)}),e.jsx("input",{"aria-label":"上传文件",hidden:!0,multiple:!0,ref:d,type:"file",onChange:p=>g(p.currentTarget)})]})}function Ts({attachments:t}){return t.drafts.length?e.jsx("div",{className:"make-ai-assistant__attachment-drafts","aria-label":"待发送附件",children:e.jsx("ul",{children:t.drafts.map(s=>e.jsxs("li",{children:[e.jsxs("span",{children:[s.name," ·"," ",s.status==="ready"?"已上传":s.status==="completing"?"校验中":s.status==="paused"?"已暂停":s.status==="failed"?"上传失败":`${Math.round(s.progress*100)}%`]}),s.error?e.jsx("span",{role:"alert",children:s.error}):null,s.status==="failed"||s.status==="paused"?e.jsx("button",{type:"button",onClick:()=>t.retry(s.id),children:"重试上传"}):null,s.status==="uploading"?e.jsx("button",{type:"button",onClick:()=>t.pause(s.id),children:"暂停上传"}):null,e.jsx("button",{type:"button",onClick:()=>t.remove(s.id),children:"移除附件"})]},s.id))})}):null}const Ms=t=>`${t}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,Rs="Make",Cs=["总结当前页面数据","找出需要关注的记录","列出我有权限查看的数据对象"],Ut=(t,s)=>s??`${t?.trim()||Rs} AI 助手`,Ss=t=>t??Cs,Es=/^只读分析\s*[·•]\s*/u,Ns=(t,s)=>t?.trim().replace(Es,"").trim()||`当前对象:${s??"未命名应用"}`,Ls=480,Ht=1024,$s=.72,Rt=16,pe=16,We=8,lt=(t,s,a)=>Math.min(Math.max(t,Math.min(s,a)),a),Ds=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0,Os=(t,s,a)=>{const o=Math.min(Ht,a*$s);return Math.max(t,Math.min(s??o,a))},Ct=(t,s,a)=>Math.min(Math.max(t,s),Math.max(s,a)),Fs=(t,s,a,o)=>{const n=Math.min(Math.max(s.width,1),Math.max(1,o-pe*2)),c=Math.min(Math.max(s.height,1),Math.max(1,a-pe*2)),d=t.left+t.width/2,g=t.top+t.height/2,f=[{left:t.right+We,placement:"right",top:g-c/2},{left:t.left-We-n,placement:"left",top:g-c/2},{left:d-n/2,placement:"bottom",top:t.bottom+We},{left:d-n/2,placement:"top",top:t.top-We-c}].find(({left:j,top:E})=>j>=pe&&E>=pe&&j+n<=o-pe&&E+c<=a-pe);return f||{left:Ct(d-n/2,pe,o-pe-n),placement:"bottom",top:Ct(t.bottom+We,pe,a-pe-c)}},Ps=t=>typeof t=="number"?Number.isFinite(t)?`${t}px`:void 0:t?.trim()||void 0;class Z extends Error{}const rt=(t,s)=>{if(!(typeof t!="object"||t===null))return t[s]},Bs=t=>{const s=rt(t,"status");return typeof s=="number"?s:rt(rt(t,"response"),"status")},zs=t=>{const s=rt(t,"code"),a=Bs(t),o=t instanceof Error?t.message:"",n=[s,o].filter(p=>typeof p=="string").join(" ").toLowerCase(),d=globalThis.navigator?.onLine===!1||/network|fetch|timeout|offline|connection|网络|连接|超时/.test(n),g=typeof a=="number"&&a>=500||/server|service|服务器|服务异常/.test(n);return d?{actionLabel:"重新连接",description:"请检查网络后再试。",kind:"network",label:"网络连接",title:"网络连接不可用"}:g?{actionLabel:"重新加载",description:"服务暂时未能响应,请稍后重试。",kind:"service",label:"服务异常",title:"服务暂时不可用"}:{actionLabel:"重新加载",description:"请稍后重试;若问题持续出现,请联系管理员。",kind:"unknown",label:"加载异常",title:"暂时无法加载对话"}},St=t=>{try{const s=t?.return?.();if(!s)return;Promise.resolve(s).catch(a=>{console.error("[make-ai-assistant] transport iterator close failed",{errorType:a instanceof Error?a.name:typeof a})})}catch(s){console.error("[make-ai-assistant] transport iterator close failed",{errorType:s instanceof Error?s.name:typeof s})}},Us=async t=>{if(globalThis.navigator?.clipboard?.writeText){await globalThis.navigator.clipboard.writeText(t);return}if(typeof document>"u"||!document.body)throw new Error("Clipboard API is unavailable");const s=document.createElement("textarea");s.value=t,s.setAttribute("readonly",""),s.style.position="fixed",s.style.inset="0 auto auto 0",s.style.opacity="0",document.body.append(s),s.select();const a=document.execCommand("copy");if(s.remove(),!a)throw new Error("Clipboard copy failed")},Kt=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 2.8c.5 4.4 2.8 6.8 7.2 7.2-4.4.5-6.8 2.8-7.2 7.2-.5-4.4-2.8-6.8-7.2-7.2 4.4-.5 6.8-2.8 7.2-7.2Z"}),e.jsx("path",{d:"M18.3 16.1c.2 1.8 1.2 2.8 3 3-1.8.2-2.8 1.2-3 3-.2-1.8-1.2-2.8-3-3 1.8-.2 2.8-1.2 3-3Z"})]}),Hs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),Ks=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M8 8h10v12H8z"}),e.jsx("path",{d:"M6 16H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),Vs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),e.jsx("path",{d:"M4 4v4h4"}),e.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),e.jsx("path",{d:"M20 20v-4h-4"})]}),Ws=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("circle",{cx:"12",cy:"12",r:"8"}),e.jsx("path",{d:"M9.8 9.4a2.35 2.35 0 1 1 3.93 1.73c-.96.86-1.73 1.42-1.73 2.87"}),e.jsx("path",{d:"M12 17h.01"})]}),qs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 4v11"}),e.jsx("path",{d:"m7 10 5 5 5-5"}),e.jsx("path",{d:"M5 20h14"})]}),Xs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),Ys=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M10 6h9M10 12h9M10 18h9"}),e.jsx("path",{d:"M5 6h.01M5 12h.01M5 18h.01"})]}),Zs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m7 10 5 5 5-5"})}),Et=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"m4 4 17 8-17 8 3-8-3-8Z"}),e.jsx("path",{d:"M7 12h14"})]}),Vt=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),e.jsx("path",{d:"M4 4v4h4"}),e.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),e.jsx("path",{d:"M20 20v-4h-4"})]}),Gs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("circle",{cx:"12",cy:"12",r:"8"}),e.jsx("path",{d:"M12 8v4.5"}),e.jsx("path",{d:"M12 16h.01"})]}),it=({className:t=""})=>e.jsx("span",{className:`make-ai-assistant__avatar ${t}`.trim(),"aria-hidden":"true",children:e.jsx(Kt,{})}),Js=({src:t})=>t?e.jsx("span",{className:"make-ai-assistant__user-avatar","aria-hidden":"true",children:e.jsx("img",{alt:"",src:t})}):null,Qs=({userAvatarUrl:t,userName:s})=>{const a=s?.trim();return!a&&!t?null:e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[a?e.jsx("span",{className:"make-ai-assistant__message-sender",children:a}):null,e.jsx(Js,{src:t})]})},dt=t=>{const s=t.trim();if(!(!s.startsWith("|")||!s.endsWith("|")))return s.slice(1,-1).split("|").map(a=>a.trim())},ea=t=>t.length>0&&t.every(s=>/^:?-{3,}:?$/.test(s)),ta=(t,s)=>{const a=dt(t[s]??""),o=dt(t[s+1]??"");if(!a||!o||a.length!==o.length||!ea(o))return;const n=[];let c=s+2;for(;c<t.length;){const d=dt(t[c]??"");if(!d||d.length!==a.length)break;n.push(d),c+=1}return{headers:a,lastIndex:c-1,rows:n}},sa=t=>{const s=[],a=[],o=[],n=[],c=t.replace(/\r\n?/g,`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),Ie=require("./index.cjs"),b=require("./conversation-Cvh-IVRV.cjs"),Xt=require("react-dom"),Ct=t=>t?.trim()||void 0,ge=(t,s)=>Ct(t)??s,dt=t=>{const s=Ct(t?.primary);if(s)return{"--make-ai-theme-primary":s,"--make-ai-theme-primary-hover":ge(t?.primaryHover,"color-mix(in srgb, var(--make-ai-theme-primary) 84%, #15233d)"),"--make-ai-theme-on-primary":ge(t?.onPrimary,"#fcfcff"),"--make-ai-theme-bg":ge(t?.background,"color-mix(in srgb, var(--make-ai-theme-primary) 2%, #fcfcff)"),"--make-ai-theme-surface":ge(t?.surface,"color-mix(in srgb, var(--make-ai-theme-primary) 4%, var(--make-ai-theme-bg))"),"--make-ai-theme-surface-strong":ge(t?.surfaceStrong,"color-mix(in srgb, var(--make-ai-theme-primary) 8%, var(--make-ai-theme-bg))"),"--make-ai-theme-text":ge(t?.text,"color-mix(in srgb, var(--make-ai-theme-primary) 12%, #252631)"),"--make-ai-theme-text-secondary":ge(t?.textSecondary,"color-mix(in srgb, var(--make-ai-theme-text) 74%, var(--make-ai-theme-primary))"),"--make-ai-theme-border":ge(t?.border,"color-mix(in srgb, var(--make-ai-theme-primary) 14%, var(--make-ai-theme-bg))"),"--make-ai-theme-overlay":ge(t?.overlay,"color-mix(in srgb, var(--make-ai-theme-text) 88%, var(--make-ai-theme-primary))"),"--make-ai-theme-on-overlay":ge(t?.onOverlay,"#fcfcff")}},_t=(t,s)=>!s||!c.isValidElement(t)||typeof t.type!="string"?t:c.cloneElement(t,{style:{...t.props.style,...s}});function Et({artifact:t,context:s,fallback:a,onAction:i,onActionError:o,registry:l,theme:d}){const h=dt(d),y=Ie.resolveArtifactTemplate(l,t,s);if(!y){const S=a?a(t):e.jsxs("section",{className:"make-ai-artifact make-ai-artifact--unsupported",role:"status",children:[e.jsx("strong",{children:"暂不支持展示此结果"}),e.jsxs("span",{children:["结果类型:",t.kind]})]});return _t(S,h)}const p={context:s,onAction:i,onActionError:o,theme:d,themeStyle:h},C=y.template.render(t,s,p);return _t(C,h)}const ke=(t,s,a)=>{if(t==null||t==="")return"—";if(typeof t=="boolean")return t?"是":"否";if(typeof t!="number")return`${t}${s?.unit??""}`;const i=s?.precision,o={maximumFractionDigits:i??2,minimumFractionDigits:i};s?.style==="currency"&&s.currency?(o.style="currency",o.currency=s.currency):s?.style==="percent"&&(o.style="percent");try{const l=s?.style==="percent"?t/100:t;return`${new Intl.NumberFormat(a,o).format(l)}${s?.unit??""}`}catch{return`${t}${s?.unit??""}`}},Lt=t=>{let s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const i of t)s=Math.min(s,i),a=Math.max(a,i);return Number.isFinite(s)&&Number.isFinite(a)?{min:s,max:a}:{min:0,max:0}},$t=(t,s,a)=>{if(!a.onAction)return;const i=l=>{console.error("[make-ai-assistant] host action error handler failed",{actionId:t.id,artifactId:s.artifact.id,errorType:l instanceof Error?l.name:typeof l,intent:t.intent})},o=l=>{if(a.onActionError){try{Promise.resolve(a.onActionError(l,t,s)).catch(i)}catch(d){i(d)}return}console.error("[make-ai-assistant] host action failed",{actionId:t.id,artifactId:s.artifact.id,errorType:l instanceof Error?l.name:typeof l,intent:t.intent})};try{Promise.resolve(a.onAction(t,s)).catch(o)}catch(l){o(l)}},$e=(t,s)=>t.actions?.length&&s.onAction?e.jsx("div",{className:"make-ai-artifact__actions",children:t.actions.map(a=>e.jsxs("button",{className:`make-ai-artifact__action make-ai-artifact__action--${a.appearance??"link"}`,type:"button",onClick:()=>$t(a,{artifact:t,context:s.context},s),children:[a.label,e.jsx("span",{"aria-hidden":"true",children:"→"})]},a.id))}):null,De=(t,s,a="",i)=>e.jsxs("section",{"aria-label":t.title??`${t.kind} result`,className:`make-ai-artifact ${a}`.trim(),"data-artifact-density":t.presentation?.density,"data-artifact-kind":t.kind,style:i,children:[t.title?e.jsx("h4",{className:"make-ai-artifact__title",children:t.title}):null,t.summary?e.jsx("p",{className:"make-ai-artifact__summary",children:t.summary}):null,s]}),Gt=({artifact:t,renderContext:s})=>{const a=t.data.delta,i=a?ke(a.value,a.format==="percent"?{style:"percent"}:void 0,s.context.locale):void 0;return De(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__metric-value",children:ke(t.data.value,t.data.format,s.context.locale)}),a?e.jsxs("div",{className:`make-ai-artifact__delta make-ai-artifact__delta--${a.direction??"flat"}`,children:[e.jsx("span",{"aria-hidden":"true",children:a.direction==="up"?"↗":a.direction==="down"?"↘":"→"}),e.jsx("span",{children:i}),a.label?e.jsx("span",{children:a.label}):null]}):null,t.data.context?e.jsx("p",{className:"make-ai-artifact__context",children:t.data.context}):null,$e(t,s)]}),"make-ai-artifact--metric",s.themeStyle)},Yt=({artifact:t,renderContext:s})=>De(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__comparison",children:t.data.items.map(a=>e.jsxs("div",{className:"make-ai-artifact__comparison-item",children:[e.jsx("span",{children:a.label}),e.jsx("strong",{children:ke(a.value,a.format,s.context.locale)}),a.hint?e.jsx("small",{children:a.hint}):null]},a.id))}),$e(t,s)]}),"make-ai-artifact--comparison",s.themeStyle),Jt=({artifact:t,renderContext:s})=>{const a=t.data.series.flatMap(d=>d.points.map(h=>h.y)),{max:i,min:o}=Lt(a),l=i-o||1;return De(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__trend",children:t.data.series.map(d=>e.jsxs("div",{className:"make-ai-artifact__trend-series",children:[e.jsx("div",{className:"make-ai-artifact__trend-label",children:d.label}),e.jsx("div",{className:"make-ai-artifact__trend-bars",children:d.points.map((h,y)=>{const p=18+(h.y-o)/l*70;return e.jsxs("div",{className:"make-ai-artifact__trend-point",children:[e.jsx("span",{"aria-label":`${h.x}: ${ke(h.y,d.format,s.context.locale)}`,className:"make-ai-artifact__trend-bar",role:"img",style:{height:`${p}%`},title:`${h.x}: ${ke(h.y,d.format,s.context.locale)}`}),e.jsx("small",{children:h.x})]},`${h.x}-${y}`)})})]},d.id))}),$e(t,s)]}),"make-ai-artifact--trend",s.themeStyle)},Qt=({artifact:t,renderContext:s})=>{const{max:a}=Lt(t.data.items.map(o=>Math.abs(o.value))),i=Math.max(a,1);return De(t,e.jsxs(e.Fragment,{children:[e.jsx("ol",{className:"make-ai-artifact__ranking",children:t.data.items.map((o,l)=>e.jsxs("li",{children:[e.jsx("span",{className:"make-ai-artifact__rank",children:l+1}),e.jsxs("span",{className:"make-ai-artifact__ranking-label",children:[e.jsx("span",{children:o.label}),o.description?e.jsx("small",{children:o.description}):null]}),e.jsx("span",{className:"make-ai-artifact__ranking-track","aria-hidden":"true",children:e.jsx("span",{style:{width:`${Math.abs(o.value)/i*100}%`}})}),e.jsx("strong",{children:ke(o.value,o.format,s.context.locale)})]},o.id))}),$e(t,s)]}),"make-ai-artifact--ranking",s.themeStyle)},es=(t,s)=>s.action??{id:`open-${s.id}`,label:s.title??s.id,intent:"open-record",target:{entityKey:t.data.entity.key,recordId:s.id}},ts=({artifact:t,renderContext:s})=>De(t,e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"make-ai-artifact__record-list",children:t.data.records.length===0?e.jsx("p",{className:"make-ai-artifact__empty",children:"没有符合条件的记录"}):t.data.records.map(a=>{const i=es(t,a),o=e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:a.title??a.id}),e.jsx("span",{className:"make-ai-artifact__record-values",children:t.data.columns.map(l=>e.jsxs("span",{children:[e.jsx("small",{children:l.label}),ke(a.values[l.key],l.format,s.context.locale)]},l.key))}),s.onAction?e.jsx("span",{"aria-hidden":"true",children:"›"}):null]});return s.onAction?e.jsx("button",{className:"make-ai-artifact__record",type:"button",onClick:()=>$t(i,{artifact:t,context:s.context},s),children:o},a.id):e.jsx("div",{className:"make-ai-artifact__record",children:o},a.id)})}),t.data.total!==void 0?e.jsxs("p",{className:"make-ai-artifact__record-total",children:["共 ",t.data.total," 条"]}):null,$e(t,s)]}),"make-ai-artifact--record-list",s.themeStyle),ss=({artifact:t,renderContext:s})=>De(t,e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`make-ai-artifact__notice make-ai-artifact__notice--${t.data.tone}`,children:[e.jsx("span",{"aria-hidden":"true",children:t.data.tone==="success"?"✓":t.data.tone==="warning"?"!":t.data.tone==="danger"?"×":"i"}),e.jsx("p",{children:t.data.body})]}),$e(t,s)]}),"make-ai-artifact--notice",s.themeStyle),Ee=(t,s,a)=>({id:t,kinds:[s],priority:0,render:a}),as=[Ee("platform.metric.default","metric",(t,s,a)=>e.jsx(Gt,{artifact:t,renderContext:a})),Ee("platform.comparison.default","comparison",(t,s,a)=>e.jsx(Yt,{artifact:t,renderContext:a})),Ee("platform.trend.default","trend",(t,s,a)=>e.jsx(Jt,{artifact:t,renderContext:a})),Ee("platform.ranking.default","ranking",(t,s,a)=>e.jsx(Qt,{artifact:t,renderContext:a})),Ee("platform.record-list.default","record-list",(t,s,a)=>e.jsx(ts,{artifact:t,renderContext:a})),Ee("platform.notice.default","notice",(t,s,a)=>e.jsx(ss,{artifact:t,renderContext:a}))],Dt=Ie.createArtifactTemplateRegistry(as).templates,Ot=(t=Dt)=>Ie.createArtifactTemplateRegistry(t),Le=()=>globalThis.crypto.randomUUID(),ut=t=>{const s=t,a=s?.status??s?.response?.status;return a===409?"数据已变化或对话仍在运行,请刷新后重试":a===401||s?.code==="AI_AUTH_REQUIRED"||s?.code==="AI_AUTH_EXPIRED"?"登录已失效,请重新登录":a===403?"当前账号无权访问该对话":a===404?"对话或回答已不可见,请刷新列表":s?.message?.startsWith("输入内容过长")?s.message:"操作未完成,请重试或刷新对话"};function ns(t,s){const a=s.features?.conversationManagement===!0,i=a?s.scopeKey?.(t)??t.app.id:"",o=c.useRef(i);o.current=i;const l=c.useRef(i),[d,h]=c.useState(b.createAssistantConversationState),y=c.useRef(d),p=r=>{const u=typeof r=="function"?r(y.current):r;y.current=u,h(u)},[C,S]=c.useState([]),[R,V]=c.useState(),A=c.useRef(void 0),[D,g]=c.useState(""),[N,F]=c.useState(-1),[f,n]=c.useState(!1),[v,_]=c.useState(!1),[K,I]=c.useState(a),[X,G]=c.useState(!1),[U,J]=c.useState(),[me,re]=c.useState([]),[O,ae]=c.useState([]),ie=c.useRef(new Set),q=c.useRef(new Map),$=c.useRef(0),w=c.useRef(0),P=c.useRef(0),te=c.useRef(void 0),he=c.useRef(void 0),we=c.useRef(new Map),E=(r,u=i)=>w.current===r&&o.current===u,Q=()=>{const r=new AbortController;return ie.current.add(r),r},oe=r=>ie.current.delete(r),ce=r=>{A.current=r,V(r)},at=r=>{S(u=>u.map(x=>x.chatId===r.chatId?r:x))},fe=r=>{S(u=>u.filter(x=>x.chatId!==r))},xe=()=>{P.current+=1},pe=()=>{for(const r of q.current.values())r.abort();q.current.clear()},ee=r=>{r instanceof Error&&r.name==="AbortError"||(console.warn("[make-ai-assistant] conversation operation failed",{errorType:r instanceof Error?r.name:typeof r}),J(ut(r)))},_e=async r=>{if(!a||!s.listConversations)return;const u=w.current,x=++P.current,k=Q();try{const M=await s.listConversations(t,{cursor:r},{signal:k.signal});if(!E(u)||k.signal.aborted||x!==P.current)return;S(L=>[...new Map([...r?L:[],...M.chats].map(j=>[j.chatId,j])).values()]),g(M.nextCursor)}catch(M){E(u)&&!k.signal.aborted&&x===P.current&&ee(M)}finally{oe(k),E(u)&&x===P.current&&I(!1)}},ve=async(r,u,x)=>{const k=w.current,M=$.current;let L;try{for await(const j of r){if(!E(k)||u.signal.aborted||M!==$.current||A.current?.chatId!==x)return;const H=b.parseAssistantEvent(j);if(H.type==="response.accepted"||H.type==="response.state"){L=H.responseId;const B=q.current.get(L);if(B&&B!==u){H.type==="response.accepted"&&p(z=>b.reduceAssistantEvent(z,H)),u.abort();return}q.current.set(L,u)}p(B=>b.reduceAssistantEvent(B,H)),H.type==="response.terminal"&&(re(B=>B.filter(z=>z!==H.responseId)),_e())}}catch(j){E(k)&&!u.signal.aborted&&M===$.current&&(ee(j),L||p(H=>({...H,status:Object.values(H.responses??{}).some(B=>!b.isResponseTerminal(B.status))?"streaming":"error"})))}finally{L&&q.current.get(L)===u&&q.current.delete(L),oe(u)}},Oe=async(r,u,x,k)=>{if(!s.getResponse||!s.watchResponse)return;const M=new Set(r.filter(j=>j.role==="assistant"&&j.persistent).map(j=>j.responseId)),L=[...new Map(r.filter(j=>j.role==="user"&&j.responseId&&!M.has(j.responseId)).map(j=>[j.responseId,j.cursor??-1])).entries()].slice(-20);for(const[j,H]of L){if(!E(k)||x!==$.current)return;if(q.current.has(j))continue;const B=Q();try{const z=await s.getResponse(t,{chatId:u,responseId:j},{signal:B.signal});if(!E(k)||B.signal.aborted||x!==$.current||q.current.has(j))continue;p(ye=>b.reduceAssistantEvent(ye,b.isResponseTerminal(z.status)?{type:"response.snapshot",snapshot:z}:{type:"response.state",chatId:u,responseId:j,status:z.status})),z.status==="failed"||z.status==="cancelled"?p(ye=>b.reduceAssistantEvent(ye,{type:"response.terminal",chatId:u,responseId:j,status:z.status})):(q.current.set(j,B),ve(s.watchResponse(t,{chatId:u,responseId:j,historyCursor:H},{signal:B.signal}),B,u))}catch(z){E(k)&&!B.signal.aborted&&ee(z)}finally{q.current.get(j)!==B&&oe(B)}}},Fe=async r=>{const u=++$.current,x=w.current,k=Q();pe(),J(void 0),I(!0),re([]),he.current=void 0,ce(r),p({messages:[],status:"idle",threadId:r.chatId}),F(-1),n(!1),_(!1);try{const[M,L]=await Promise.all([s.getConversation(t,{chatId:r.chatId},{signal:k.signal}),s.loadConversation(t,{threadId:r.chatId,cursor:-1,signal:k.signal})]);if(!E(x)||k.signal.aborted||u!==$.current)return;if(M.chatId!==r.chatId||L.threadId!==r.chatId)throw new Error("Conversation mismatch");ce(M),p(b.createAssistantConversationState(L)),F(L.nextCursor??-1),n(L.hasMore??!1),Oe(L.messages,r.chatId,u,x)}catch(M){E(x)&&!k.signal.aborted&&u===$.current&&ee(M)}finally{oe(k),E(x)&&u===$.current&&I(!1)}},Ae=async()=>{if(A.current)return A.current;if(te.current??={requestId:Le()},te.current.promise)return te.current.promise;const r=w.current,u=$.current,x=Q(),k=te.current;return G(!0),k.promise=s.createConversation(t,{requestId:k.requestId},{signal:x.signal}).then(M=>{if(!E(r)||x.signal.aborted||u!==$.current)throw Object.assign(new Error("Stale create"),{name:"AbortError"});return te.current=void 0,ce(M),p({messages:[],status:"idle",threadId:M.chatId}),_e(),M}).finally(()=>{oe(x),k.promise=void 0,E(r)&&G(!1)}),k.promise},We=async()=>{if(!(X||te.current?.promise)){$.current+=1,pe(),ce(void 0),J(void 0),he.current=void 0,p(b.createAssistantConversationState()),n(!1),F(-1);try{await Ae()}catch(r){ee(r)}}},le=async r=>{const u=Q();he.current=r,J(void 0),y.current.messages.some(x=>x.id===r.message.id)||p(x=>b.appendUserMessage(x,r.message)),await ve(s.run(r,{signal:u.signal}),u,r.threadId)},Ve=async(r,u)=>{if(!(!r.trim()&&!u?.length))try{const x=await Ae(),k={id:Le(),content:r,...u?{parts:u}:{}};await le({threadId:x.chatId,message:k,context:t,capabilities:{artifactSchemaVersions:[],artifactKinds:[],templates:[]}})}catch(x){ee(x)}},qe=async()=>{const r=he.current;if(!r||r.threadId!==A.current?.chatId){A.current&&await Fe(A.current);return}const u=y.current.messages.find(x=>x.id===r.message.id);if(u?.responseId&&s.watchResponse){const x=u.responseId;if(q.current.has(x))return;const k=Q();q.current.set(x,k),J(void 0),await ve(s.watchResponse(t,{chatId:r.threadId,responseId:x,historyCursor:u.cursor},{signal:k.signal}),k,r.threadId)}else await le(r)},He=async(r=y.current.activeRunId)=>{const u=A.current;if(!u||!r||!s.cancelResponse||me.includes(r))return;const x=w.current,k=$.current,M=Q();re(L=>[...L,r]),J(void 0);try{const L=await s.cancelResponse(t,{chatId:u.chatId,responseId:r},{signal:M.signal});if(!E(x)||k!==$.current)return;if(b.isResponseTerminal(L.status))p(j=>b.reduceAssistantEvent(j,{type:"response.snapshot",snapshot:L})),re(j=>j.filter(H=>H!==r));else if(!q.current.has(r)&&s.watchResponse){const j=Q();q.current.set(r,j),ve(s.watchResponse(t,{chatId:u.chatId,responseId:r},{signal:j.signal}),j,u.chatId)}}catch(L){E(x)&&k===$.current&&(ee(L),re(j=>j.filter(H=>H!==r)))}finally{oe(M)}},Ze=async(r,u=A.current)=>{if(!u||X)return!1;const x=w.current,k=Q();G(!0),J(void 0);try{const M=await s.updateConversation(t,{chatId:u.chatId,expectedRevision:u.revision,...r},{signal:k.signal});return E(x)?(xe(),at(M),A.current?.chatId===M.chatId&&ce(M),!0):!1}catch(M){if(E(x)){ee(M);try{const L=await s.getConversation(t,{chatId:u.chatId},{signal:k.signal});E(x)&&A.current?.chatId===u.chatId&&ce(L)}catch{}_e()}return!1}finally{oe(k),E(x)&&G(!1)}},Xe=async(r=A.current)=>{if(!r||X)return!1;const u=w.current,x=Q();G(!0),J(void 0);try{return await s.deleteConversation(t,{chatId:r.chatId,expectedRevision:r.revision},{signal:x.signal}),E(u)?(xe(),fe(r.chatId),A.current?.chatId===r.chatId&&($.current+=1,pe(),ce(void 0),p(b.createAssistantConversationState())),!0):!1}catch(k){return E(u)&&ee(k),!1}finally{oe(x),E(u)&&G(!1)}},Ne=async(r,u,x="",k="")=>{const M=A.current;if(!M||!r.persistent||!s.setFeedback||O.includes(r.id))return;const L={chatId:M.chatId,messageId:r.id,rating:u,...x?{reason:x}:{},...k?{comment:k}:{}},j=we.current.get(r.id),{requestId:H,...B}=j??{requestId:""},z=j&&JSON.stringify(B)===JSON.stringify(L)?j:{...L,requestId:Le()};we.current.set(r.id,z);const ye=w.current,Re=$.current,Ge=Q();ae(de=>[...de,r.id]),J(void 0);try{const de=await s.setFeedback(t,z,{signal:Ge.signal});return!E(ye)||Re!==$.current||we.current.get(r.id)!==z?void 0:(p(Te=>({...Te,messages:Te.messages.map(m=>m.id===r.id&&de.revision>=(m.feedback?.revision??0)?{...m,feedback:de}:m)})),we.current.delete(r.id),!0)}catch(de){return E(ye)&&Re===$.current&&ee(de),!1}finally{oe(Ge),E(ye)&&ae(de=>de.filter(Te=>Te!==r.id))}},nt=async()=>{if(!A.current||!f||K)return;const r=w.current,u=$.current,x=A.current,k=Q();I(!0);try{const M=await s.loadConversation(t,{threadId:x.chatId,cursor:N,signal:k.signal});if(!E(r)||u!==$.current)return;const L=b.createAssistantConversationState(M),j=[...new Map([...y.current.messages,...L.messages].map(z=>[z.id,z])).values()];let H=0;const B=[];for(const z of j.slice(-200).reverse()){if(H+=[...z.content].length,H>1e6)break;B.unshift(z)}B.length<j.length&&_(!0),p(z=>({...z,messages:B})),F(M.nextCursor??N),n(M.hasMore??!1),Oe(M.messages,x.chatId,u,r)}catch(M){E(r)&&ee(M)}finally{oe(k),E(r)&&I(!1)}};c.useEffect(()=>(w.current+=1,l.current=i,te.current=void 0,he.current=void 0,we.current.clear(),ce(void 0),S([]),g(""),p(b.createAssistantConversationState()),J(void 0),I(a),G(!1),re([]),ae([]),a&&_e(),()=>{w.current+=1,$.current+=1;for(const r of ie.current)r.abort();ie.current.clear(),q.current.clear()}),[a,i,s]);const Me=l.current===i;return{enabled:a,state:Me?d:b.createAssistantConversationState(),setState:p,chats:Me?C:[],chat:Me?R:void 0,listCursor:D,historyMore:f,historyTruncated:v,loading:!Me||K,busy:X,error:Me?U:void 0,cancelling:me,feedbackBusy:O,refresh:_e,select:Fe,create:We,ensureChat:Ae,send:Ve,retry:qe,stop:He,update:Ze,remove:Xe,feedback:Ne,moreHistory:nt,setError:J}}const rs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M5 5.5h14v10H9l-4 3v-13Z"}),e.jsx("path",{d:"M8 9h8M8 12h6"})]}),is=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),os=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"m4.5 16.8-.7 3.7 3.7-.7L18 9.3l-3-3L4.5 16.8Z"}),e.jsx("path",{d:"m13.8 7.5 3 3"})]}),cs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M5.5 7.5h13M9.5 7.5V5.7h5v1.8M8 10.5v6M12 10.5v6M16 10.5v6M7 7.5l.7 12h8.6l.7-12"})}),jt=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m5 12.5 4.5 4.5L19 7.5"})}),kt=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),ls=({anchor:t,label:s,onDismiss:a})=>{const[i,o]=c.useState();if(c.useLayoutEffect(()=>{const d=()=>{if(!t.isConnected){a();return}const h=t.getBoundingClientRect(),y=h.top>=48?"above":"below";o({left:h.left+h.width/2,placement:y,top:y==="above"?h.top-8:h.bottom+8})};return d(),window.addEventListener("resize",d),document.addEventListener("scroll",d,!0),()=>{window.removeEventListener("resize",d),document.removeEventListener("scroll",d,!0)}},[t,a]),!i||typeof document>"u")return null;const l=t.closest(".make-ai-assistant")??document.body;return Xt.createPortal(e.jsx("span",{className:"make-ai-assistant__conversation-tooltip","data-placement":i.placement,role:"tooltip",style:{left:i.left,top:i.top},children:s}),l)},ds=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M7.5 10.5v9H4.8a1.8 1.8 0 0 1-1.8-1.8v-5.4a1.8 1.8 0 0 1 1.8-1.8h2.7Z"}),e.jsx("path",{d:"M7.5 19.5h8.1a2.4 2.4 0 0 0 2.3-1.8l1.4-5.4a1.5 1.5 0 0 0-1.5-1.8h-4.1l.7-3.4A2.4 2.4 0 0 0 12 4.2L7.5 10.5Z"})]}),us=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M7.5 13.5v-9H4.8A1.8 1.8 0 0 0 3 6.3v5.4a1.8 1.8 0 0 0 1.8 1.8h2.7Z"}),e.jsx("path",{d:"M7.5 4.5h8.1a2.4 2.4 0 0 1 2.3 1.8l1.4 5.4a1.5 1.5 0 0 1-1.5 1.8h-4.1l.7 3.4A2.4 2.4 0 0 1 12 19.8l-4.5-6.3Z"})]});function ms({id:t,manager:s,onDismiss:a,onNewConversation:i,triggerRef:o}){const[l,d]=c.useState(),[h,y]=c.useState(""),[p,C]=c.useState(),[S,R]=c.useState(),V=c.useRef(null),A=(n,v)=>{R(_=>_?.anchor===v&&_.label===n?_:{anchor:v,label:n})},D=n=>{R(v=>v?.anchor===n?void 0:v)},g=n=>({"data-tooltip":n,onBlur:v=>D(v.currentTarget),onFocus:v=>A(n,v.currentTarget),onPointerEnter:v=>A(n,v.currentTarget),onPointerLeave:v=>D(v.currentTarget)}),N=()=>{d(void 0),y("")},F=async n=>{const v=h.trim();v&&await s.update({title:v},n)&&N()},f=async n=>{await s.remove(n)&&C(void 0)};return c.useEffect(()=>{const n=v=>{const _=v.target;_ instanceof Node&&(V.current?.contains(_)||o.current?.contains(_)||a())};return document.addEventListener("pointerdown",n),()=>{document.removeEventListener("pointerdown",n)}},[a,o]),e.jsxs("div",{"aria-label":"任务列表",className:"make-ai-assistant__conversation-controls",id:t,ref:V,role:"dialog",children:[e.jsxs("div",{className:"make-ai-assistant__conversation-heading",children:[e.jsx("span",{children:"最近对话"}),e.jsx("button",{"aria-label":"刷新任务列表",className:"make-ai-assistant__conversation-refresh",disabled:s.busy,type:"button",onClick:()=>{s.refresh()},children:"刷新"})]}),e.jsxs("nav",{"aria-label":"对话列表",className:"make-ai-assistant__conversation-list",children:[s.chats.map(n=>{const v=l===n.chatId,_=p===n.chatId,K=n.title||"未命名对话";return e.jsxs("div",{className:"make-ai-assistant__conversation-row","data-editing":v||_||void 0,children:[_?e.jsxs("div",{"aria-label":"确认删除对话",className:"make-ai-assistant__conversation-delete-confirmation",role:"group",children:[e.jsxs("span",{children:["删除“",K,"”?"]}),e.jsx("button",{"aria-label":`确认删除:${K}`,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-row-action--danger",disabled:s.busy,type:"button",...g("确认删除"),onClick:()=>{f(n)},children:e.jsx(jt,{})}),e.jsx("button",{"aria-label":`取消删除:${K}`,className:"make-ai-assistant__conversation-row-action",disabled:s.busy,type:"button",...g("取消"),onClick:()=>C(void 0),children:e.jsx(kt,{})})]}):v?e.jsx("input",{"aria-label":"对话标题",autoFocus:!0,className:"make-ai-assistant__conversation-row-title-input",disabled:s.busy,maxLength:255,value:h,onChange:I=>y(I.currentTarget.value),onKeyDown:I=>{I.nativeEvent.isComposing||(I.key==="Escape"&&(I.preventDefault(),N()),I.key==="Enter"&&(I.preventDefault(),F(n)))}}):e.jsxs("button",{"aria-pressed":s.chat?.chatId===n.chatId,className:"make-ai-assistant__conversation-row-select",type:"button",onClick:()=>{a(),s.select(n)},children:[e.jsx(rs,{}),e.jsx("span",{children:K})]}),v?e.jsxs("div",{"aria-label":"修改标题操作",className:"make-ai-assistant__conversation-row-actions",role:"group",children:[e.jsx("button",{"aria-label":"确认修改标题",className:"make-ai-assistant__conversation-row-action",disabled:s.busy||!h.trim(),type:"button",...g("保存标题"),onClick:()=>{F(n)},children:e.jsx(jt,{})}),e.jsx("button",{"aria-label":"取消修改标题",className:"make-ai-assistant__conversation-row-action",disabled:s.busy,type:"button",...g("取消"),onClick:N,children:e.jsx(kt,{})})]}):_?null:e.jsxs("div",{className:"make-ai-assistant__conversation-row-actions",children:[e.jsx("button",{"aria-label":`${n.pinned?"取消置顶":"置顶"} ${K}`,className:"make-ai-assistant__conversation-row-pin",disabled:s.busy,type:"button",onClick:()=>{s.update({pinned:!n.pinned},n)},children:n.pinned?"★":"☆"}),e.jsx("button",{"aria-label":`修改标题:${K}`,className:"make-ai-assistant__conversation-row-action",disabled:s.busy,type:"button",...g("修改标题"),onClick:()=>{C(void 0),d(n.chatId),y(n.title)},children:e.jsx(os,{})}),e.jsx("button",{"aria-label":`删除:${K}`,className:"make-ai-assistant__conversation-row-action make-ai-assistant__conversation-row-action--danger",disabled:s.busy,type:"button",...g("删除"),onClick:()=>{N(),C(n.chatId)},children:e.jsx(cs,{})})]})]},n.chatId)}),!s.loading&&!s.chats.length?e.jsx("p",{children:"暂无对话,发送消息即可新建"}):null,s.listCursor?e.jsx("button",{className:"make-ai-assistant__conversation-more",type:"button",onClick:()=>{s.refresh(s.listCursor)},children:"更多对话"}):null]}),s.chat&&(s.historyMore||s.historyTruncated||s.state.historyTruncated)?e.jsxs("div",{className:"make-ai-assistant__conversation-history-actions",children:[s.historyMore?e.jsx("button",{type:"button",disabled:s.loading,onClick:()=>{s.moreHistory()},children:"继续加载历史"}):null,s.historyTruncated||s.state.historyTruncated?e.jsx("p",{children:"当前展示有界消息窗口,可重新选择对话从头读取。"}):null]}):null,s.error?e.jsxs("div",{className:"make-ai-assistant__conversation-error",role:"alert",children:[e.jsx("span",{children:s.error}),e.jsx("button",{type:"button",onClick:()=>{s.retry()},children:"恢复对话"})]}):null,i?e.jsxs("button",{className:"make-ai-assistant__conversation-new",type:"button",onClick:i,children:[e.jsx(is,{}),e.jsx("span",{children:"新建对话"})]}):null,S?e.jsx(ls,{anchor:S.anchor,label:S.label,onDismiss:()=>R(void 0)}):null]})}function hs({message:t,manager:s}){const[a,i]=c.useState(!1),[o,l]=c.useState(""),[d,h]=c.useState(""),y=s.feedbackBusy.includes(t.id);if(!t.persistent||t.role!=="assistant"||t.intermediate)return null;const p=t.feedback?.rating??"none";return e.jsxs("div",{"aria-label":"回答反馈",className:"make-ai-assistant__feedback",role:"group",children:[e.jsx("button",{type:"button","aria-label":"喜欢","aria-pressed":p==="like",className:"make-ai-assistant__reply-action make-ai-assistant__reply-feedback-action","data-tooltip":"喜欢",disabled:y,onClick:()=>{s.feedback(t,p==="like"?"none":"like")},children:e.jsx(ds,{})}),e.jsx("button",{type:"button","aria-label":"不喜欢","aria-pressed":p==="dislike",className:"make-ai-assistant__reply-action make-ai-assistant__reply-feedback-action","data-tooltip":"不喜欢",disabled:y,onClick:()=>{if(p==="dislike"){s.feedback(t,"none");return}l(t.feedback?.reason??""),h(t.feedback?.comment??""),i(!0)},children:e.jsx(us,{})}),p==="dislike"?e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"button",disabled:y,onClick:()=>{l(t.feedback?.reason??""),h(t.feedback?.comment??""),i(!0)},children:"修改反馈"}):null,a?e.jsxs("form",{onSubmit:C=>{C.preventDefault(),s.feedback(t,"dislike",o,d).then(S=>{S&&i(!1)})},children:[e.jsx("input",{"aria-label":"反馈原因",maxLength:128,value:o,onChange:C=>l(C.currentTarget.value),placeholder:"原因(可选)"}),e.jsx("textarea",{"aria-label":"反馈说明",maxLength:4e3,value:d,onChange:C=>h(C.currentTarget.value),placeholder:"补充说明(可选)"}),e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"submit",disabled:y,children:"提交反馈"}),e.jsx("button",{className:"make-ai-assistant__feedback-text-action",type:"button",onClick:()=>i(!1),children:"取消"})]}):null]})}const It=new Set(["image/png","image/jpeg","image/webp","image/gif","audio/mpeg","audio/wav","audio/ogg","audio/webm","video/mp4","video/webm","video/ogg"]);function fs({part:t,context:s,transport:a,chatId:i}){const[o,l]=c.useState(),[d,h]=c.useState(),[y,p]=c.useState(!1),C=c.useRef([]),S=c.useRef(void 0);c.useEffect(()=>()=>{S.current?.abort(),C.current.forEach(V=>URL.revokeObjectURL(V))},[]);const R=async V=>{if(!a.readContent||y)return;const A=new AbortController;S.current=A,p(!0),h(void 0);try{const D=await a.readContent(s,{chatId:i,contentRef:t.media.contentRef},{signal:A.signal});if(A.signal.aborted)return;const g=new Blob([new Uint8Array(D).buffer],{type:V&&It.has(t.media.contentType)?t.media.contentType:"application/octet-stream"}),N=URL.createObjectURL(g);if(C.current.push(N),V)l(N);else{const F=document.createElement("a");F.href=N,F.download=t.name??"attachment",F.click()}}catch(D){A.signal.aborted||h(ut(D))}finally{A.signal.aborted||p(!1)}};return e.jsxs("div",{className:"make-ai-assistant__attachment",children:[e.jsxs("span",{children:[t.name??"附件"," · ",t.media.sizeBytes," 字节"]}),a.readContent?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:y,onClick:()=>{R(!1)},children:"下载附件"}),It.has(t.media.contentType)?e.jsx("button",{type:"button",disabled:y,onClick:()=>{R(!0)},children:"预览附件"}):null]}):null,d?e.jsx("span",{role:"alert",children:d}):null,o&&t.kind==="image"?e.jsx("img",{src:o,alt:t.name??"附件图片"}):null,o&&t.kind==="audio"?e.jsx("audio",{src:o,controls:!0}):null,o&&t.kind==="video"?e.jsx("video",{src:o,controls:!0}):null]})}function ps({message:t,context:s,transport:a,chatId:i}){return e.jsx(e.Fragment,{children:t.parts?.map((o,l)=>o.kind==="text"?null:e.jsx(fs,{part:o,context:s,transport:a,chatId:i},o.id??`${t.id}:${l}`))})}const Ft=t=>t.type.split(";")[0].trim().toLowerCase()||"application/octet-stream",vs=t=>t.startsWith("image/")&&t!=="image/svg+xml"?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file",gs=t=>{const s=Ft(t);if(!(!s.startsWith("image/")||s==="image/svg+xml"||typeof URL>"u"||typeof URL.createObjectURL!="function"))return URL.createObjectURL(t)},wt=t=>{t&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(t)},xs=(t,s)=>new Promise((a,i)=>{const o=new FileReader,l=()=>s.removeEventListener("abort",d),d=()=>{o.abort(),l(),i(Object.assign(new Error("Read aborted"),{name:"AbortError"}))};if(s.aborted){d();return}s.addEventListener("abort",d,{once:!0}),o.onload=()=>{l(),a(new Uint8Array(o.result))},o.onerror=()=>{l(),i(new Error("无法读取文件"))},o.readAsArrayBuffer(t)});function ys(t,s,a){const[i,o]=c.useState([]),l=c.useRef(new Map),d=c.useRef(Promise.resolve()),h=s.scopeKey?.(t)??t.app.id,y=c.useRef(h);y.current=h;const p=c.useRef(void 0),C=a.enabled&&s.features?.attachments===!0,S=(f,n)=>{!l.current.has(f.draft.id)||f.scope!==y.current||(f.draft={...f.draft,...n},o([...l.current.values()].map(v=>v.draft)))},R=()=>{for(const f of l.current.values())f.controller.abort(),wt(f.draft.previewUrl);l.current.clear(),o([]),p.current=void 0,d.current=Promise.resolve()};c.useEffect(()=>(R(),R),[h,s]),c.useEffect(()=>{p.current&&a.chat?.chatId!==p.current&&R()},[a.chat?.chatId]);const V=async f=>{const n=f.controller.signal,v=()=>{if(n.aborted||f.scope!==y.current||!l.current.has(f.draft.id))throw Object.assign(new Error("Upload aborted"),{name:"AbortError"})};try{if(v(),f.file.size>64<<20)throw new Error("文件不能超过 64 MiB");const _=await a.ensureChat();v(),p.current=_.chatId;const K=Ft(f.file);S(f,{status:"uploading",error:void 0});let I=f.draft.upload?await s.getUpload(t,{chatId:_.chatId,uploadId:f.draft.upload.id},{signal:n}):await s.startUpload(t,{chatId:_.chatId,fileId:f.draft.fileId,name:f.file.name,contentType:K,sizeBytes:f.file.size},{signal:n});if(v(),S(f,{upload:I}),I.name!==f.file.name||I.contentType!==K||I.sizeBytes!==f.file.size)throw new Error("上传文件身份不一致");if(I.status!=="ready"){I=await s.getUpload(t,{chatId:_.chatId,uploadId:I.id},{signal:n}),v();const X=new Set(I.completedParts),G=Math.ceil(f.file.size/I.partSize);for(let U=0;U<G;U+=1){if(v(),!X.has(U)){const J=await xs(f.file.slice(U*I.partSize,Math.min(f.file.size,(U+1)*I.partSize)),n);v(),await s.uploadPart(t,{chatId:_.chatId,uploadId:I.id,part:U,bytes:J},{signal:n}),v(),X.add(U)}S(f,{progress:X.size/Math.max(G,1)})}S(f,{status:"completing"}),I=await s.completeUpload(t,{chatId:_.chatId,uploadId:I.id},{signal:n}),v()}if(I.status!=="ready"||!I.content)throw new Error("上传尚未完成");S(f,{status:"ready",progress:1,upload:I})}catch(_){S(f,{status:n.aborted?"paused":"failed",error:n.aborted?void 0:ut(_)})}},A=f=>{if(C){if(f.length+l.current.size>32){a.setError("每条消息最多包含 32 个附件或文本片段");return}for(const n of f){const v={id:Le(),fileId:Le(),name:n.name,size:n.size,status:"queued",progress:0,previewUrl:gs(n)},_={draft:v,file:n,controller:new AbortController,scope:h};l.current.set(v.id,_),d.current=d.current.then(()=>V(_))}o([...l.current.values()].map(n=>n.draft))}},D=f=>{const n=l.current.get(f);!n||!["paused","failed"].includes(n.draft.status)||(n.controller=new AbortController,S(n,{status:"queued"}),d.current=d.current.then(()=>V(n)))},g=f=>{const n=l.current.get(f);n?.controller.abort(),wt(n?.draft.previewUrl),l.current.delete(f),o([...l.current.values()].map(v=>v.draft))},N=f=>l.current.get(f)?.controller.abort(),F=i.flatMap(f=>{const n=f.upload;if(f.status!=="ready"||!n?.content)return[];const v=vs(n.contentType);return[{id:f.id,kind:v,name:n.name,media:{contentRef:n.content.contentRef,contentType:n.contentType,sizeBytes:n.content.sizeBytes,digestSha256:n.content.digestSha256}}]});return{enabled:C,drafts:i,parts:F,pending:i.some(f=>f.status!=="ready"),add:A,retry:D,remove:g,pause:N,clear:R}}function bs({attachments:t,onOpenChange:s,open:a,triggerRef:i}){const o=c.useRef(null),l=c.useRef(null);c.useEffect(()=>{if(!a)return;const h=y=>{const p=y.target;p instanceof Node&&!o.current?.contains(p)&&s(!1)};return document.addEventListener("pointerdown",h),()=>{document.removeEventListener("pointerdown",h)}},[s,a]);const d=h=>{t.add(Array.from(h.files??[])),h.value="",s(!1)};return e.jsxs("div",{className:"make-ai-assistant__attachment-composer",ref:o,children:[e.jsx("button",{"aria-expanded":a,"aria-haspopup":"menu","aria-label":"添加附件",className:"make-ai-assistant__attachment-trigger",ref:i,title:"添加附件",type:"button",onClick:()=>s(!a),children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})}),a?e.jsx("div",{"aria-label":"附件选项",className:"make-ai-assistant__attachment-menu",role:"menu",children:e.jsxs("button",{role:"menuitem",type:"button",onClick:()=>l.current?.click(),children:[e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 15V4M7.5 8.5 12 4l4.5 4.5"}),e.jsx("path",{d:"M5 14v5h14v-5"})]}),e.jsx("span",{children:"上传文件或图片"})]})}):null,e.jsx("input",{"aria-label":"上传文件或图片",hidden:!0,multiple:!0,ref:l,type:"file",onChange:h=>d(h.currentTarget)})]})}function _s({attachments:t}){return t.drafts.length?e.jsx("div",{className:"make-ai-assistant__attachment-drafts","aria-label":"待发送附件",children:e.jsx("ul",{children:t.drafts.map(s=>e.jsxs("li",{"data-status":s.status,children:[s.previewUrl?e.jsx("img",{alt:"",className:"make-ai-assistant__attachment-draft-preview",src:s.previewUrl}):e.jsx("span",{"aria-hidden":"true",className:"make-ai-assistant__attachment-draft-file",children:e.jsxs("svg",{viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M6 3h8l4 4v14H6z"}),e.jsx("path",{d:"M14 3v5h5M9 13h6M9 16h6"})]})}),e.jsxs("span",{className:"make-ai-assistant__attachment-draft-details",children:[e.jsx("span",{className:"make-ai-assistant__attachment-draft-name",title:s.name,children:s.name}),e.jsx("span",{className:"make-ai-assistant__attachment-draft-status",children:s.status==="ready"?"已上传":s.status==="completing"?"校验中":s.status==="paused"?"已暂停":s.status==="failed"?"上传失败":`${Math.round(s.progress*100)}%`})]}),s.error?e.jsx("span",{role:"alert",children:s.error}):null,s.status==="failed"||s.status==="paused"?e.jsx("button",{type:"button",onClick:()=>t.retry(s.id),children:"重试上传"}):null,s.status==="uploading"?e.jsx("button",{type:"button",onClick:()=>t.pause(s.id),children:"暂停上传"}):null,e.jsx("button",{"aria-label":`移除附件 ${s.name}`,className:"make-ai-assistant__attachment-draft-remove",type:"button",onClick:()=>t.remove(s.id),children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m7 7 10 10M17 7 7 17"})})})]},s.id))})}):null}const js=t=>`${t}-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,ks="Make",Is=["总结当前页面数据","找出需要关注的记录","列出我有权限查看的数据对象"],Ut=(t,s)=>s??`${t?.trim()||ks} AI 助手`,ws=t=>t??Is,As=480,Pt=1024,Ms=.72,At=16,ot=(t,s,a)=>Math.min(Math.max(t,Math.min(s,a)),a),Rs=t=>typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0,Ns=(t,s,a)=>{const i=Math.min(Pt,a*Ms);return Math.max(t,Math.min(s??i,a))},Ts=t=>typeof t=="number"?Number.isFinite(t)?`${t}px`:void 0:t?.trim()||void 0;class Y extends Error{}const tt=(t,s)=>{if(!(typeof t!="object"||t===null))return t[s]},Ss=t=>{const s=tt(t,"status");return typeof s=="number"?s:tt(tt(t,"response"),"status")},Cs=t=>{const s=tt(t,"code"),a=Ss(t),i=t instanceof Error?t.message:"",o=[s,i].filter(y=>typeof y=="string").join(" ").toLowerCase(),d=globalThis.navigator?.onLine===!1||/network|fetch|timeout|offline|connection|网络|连接|超时/.test(o),h=typeof a=="number"&&a>=500||/server|service|服务器|服务异常/.test(o);return d?{actionLabel:"重新连接",description:"请检查网络后再试。",kind:"network",label:"网络连接",title:"网络连接不可用"}:h?{actionLabel:"重新加载",description:"服务暂时未能响应,请稍后重试。",kind:"service",label:"服务异常",title:"服务暂时不可用"}:{actionLabel:"重新加载",description:"请稍后重试;若问题持续出现,请联系管理员。",kind:"unknown",label:"加载异常",title:"暂时无法加载对话"}},Mt=t=>{try{const s=t?.return?.();if(!s)return;Promise.resolve(s).catch(a=>{console.error("[make-ai-assistant] transport iterator close failed",{errorType:a instanceof Error?a.name:typeof a})})}catch(s){console.error("[make-ai-assistant] transport iterator close failed",{errorType:s instanceof Error?s.name:typeof s})}},Es=async t=>{if(globalThis.navigator?.clipboard?.writeText){await globalThis.navigator.clipboard.writeText(t);return}if(typeof document>"u"||!document.body)throw new Error("Clipboard API is unavailable");const s=document.createElement("textarea");s.value=t,s.setAttribute("readonly",""),s.style.position="fixed",s.style.inset="0 auto auto 0",s.style.opacity="0",document.body.append(s),s.select();const a=document.execCommand("copy");if(s.remove(),!a)throw new Error("Clipboard copy failed")},Bt=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 2.8c.5 4.4 2.8 6.8 7.2 7.2-4.4.5-6.8 2.8-7.2 7.2-.5-4.4-2.8-6.8-7.2-7.2 4.4-.5 6.8-2.8 7.2-7.2Z"}),e.jsx("path",{d:"M18.3 16.1c.2 1.8 1.2 2.8 3 3-1.8.2-2.8 1.2-3 3-.2-1.8-1.2-2.8-3-3 1.8-.2 2.8-1.2 3-3Z"})]}),Ls=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m6 6 12 12M18 6 6 18"})}),$s=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M8 8h10v12H8z"}),e.jsx("path",{d:"M6 16H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),Ds=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),e.jsx("path",{d:"M4 4v4h4"}),e.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),e.jsx("path",{d:"M20 20v-4h-4"})]}),Os=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M12 4v11"}),e.jsx("path",{d:"m7 10 5 5 5-5"}),e.jsx("path",{d:"M5 20h14"})]}),Fs=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"M12 5v14M5 12h14"})}),Us=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M10 6h9M10 12h9M10 18h9"}),e.jsx("path",{d:"M5 6h.01M5 12h.01M5 18h.01"})]}),Ps=()=>e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:e.jsx("path",{d:"m7 10 5 5 5-5"})}),Rt=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"m4 4 17 8-17 8 3-8-3-8Z"}),e.jsx("path",{d:"M7 12h14"})]}),zt=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M20 11a8 8 0 0 0-14.7-4.4L4 8"}),e.jsx("path",{d:"M4 4v4h4"}),e.jsx("path",{d:"M4 13a8 8 0 0 0 14.7 4.4L20 16"}),e.jsx("path",{d:"M20 20v-4h-4"})]}),Bs=()=>e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[e.jsx("circle",{cx:"12",cy:"12",r:"8"}),e.jsx("path",{d:"M12 8v4.5"}),e.jsx("path",{d:"M12 16h.01"})]}),st=({className:t=""})=>e.jsx("span",{className:`make-ai-assistant__avatar ${t}`.trim(),"aria-hidden":"true",children:e.jsx(Bt,{})}),zs=({src:t})=>t?e.jsx("span",{className:"make-ai-assistant__user-avatar","aria-hidden":"true",children:e.jsx("img",{alt:"",src:t})}):null,Ks=({userAvatarUrl:t,userName:s})=>{const a=s?.trim();return!a&&!t?null:e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[a?e.jsx("span",{className:"make-ai-assistant__message-sender",children:a}):null,e.jsx(zs,{src:t})]})},ct=t=>{const s=t.trim();if(!(!s.startsWith("|")||!s.endsWith("|")))return s.slice(1,-1).split("|").map(a=>a.trim())},Ws=t=>t.length>0&&t.every(s=>/^:?-{3,}:?$/.test(s)),Vs=(t,s)=>{const a=ct(t[s]??""),i=ct(t[s+1]??"");if(!a||!i||a.length!==i.length||!Ws(i))return;const o=[];let l=s+2;for(;l<t.length;){const d=ct(t[l]??"");if(!d||d.length!==a.length)break;o.push(d),l+=1}return{headers:a,lastIndex:l-1,rows:o}},qs=t=>{const s=[],a=[],i=[],o=[],l=t.replace(/\r\n?/g,`
|
|
2
2
|
`).split(`
|
|
3
|
-
`),d=()=>{const
|
|
4
|
-
`).trim();a.length=0,
|
|
5
|
-
`).trim();n.length=0,f&&s.push({type:"pre",text:f})};for(let f=0;f<c.length;f+=1){const j=c[f]??"",E=j.trim();if(!E){d(),g(),p();continue}const B=ta(c,f);if(B){d(),g(),p(),s.push({headers:B.headers,rows:B.rows,type:"table"}),f=B.lastIndex;continue}const H=/^(#{1,6})\s+(.+)$/.exec(E);if(H){d(),g(),p();const V=(H[2]??"").replace(/\s+#+\s*$/,"").trim();V&&s.push({type:"heading",level:H[1]?.length,text:V});continue}if(/^\s*\|.+\|\s*$/.test(j)){d(),g(),n.push(j.trim());continue}const y=/^\s*[-*]\s+(.+)$/.exec(j);if(y){d(),p(),o.push(y[1]?.trim()??"");continue}g(),p(),a.push(E)}return d(),g(),p(),s},qe=t=>{const s=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g;let o=0;for(const n of t.matchAll(a)){const c=n[0],d=n.index??0;d>o&&s.push(t.slice(o,d)),c.startsWith("**")?s.push(e.jsx("strong",{children:c.slice(2,-2)},`${d}-strong`)):s.push(e.jsx("code",{children:c.slice(1,-1)},`${d}-code`)),o=d+c.length}return o<t.length&&s.push(t.slice(o)),s},Nt=({content:t})=>{const s=sa(t);return s.length?e.jsx("div",{className:"make-ai-assistant__bubble make-ai-assistant__assistant-text",children:s.map((a,o)=>{if(a.type==="heading"){const n=a.level<=2?"h3":"h4";return e.jsx(n,{className:`make-ai-assistant__markdown-heading make-ai-assistant__markdown-heading--${a.level}`,children:qe(a.text)},`${o}-heading`)}return a.type==="paragraph"?e.jsx("p",{children:qe(a.text)},`${o}-paragraph`):a.type==="pre"?e.jsx("pre",{children:e.jsx("code",{children:a.text})},`${o}-pre`):a.type==="table"?e.jsx("div",{"aria-label":"表格内容,可横向滚动",className:"make-ai-assistant__markdown-table-scroll",role:"region",tabIndex:0,children:e.jsxs("table",{className:"make-ai-assistant__markdown-table",children:[e.jsx("thead",{children:e.jsx("tr",{children:a.headers.map((n,c)=>e.jsx("th",{scope:"col",children:qe(n)},`${c}-${n}`))})}),e.jsx("tbody",{children:a.rows.map((n,c)=>e.jsx("tr",{children:n.map((d,g)=>e.jsx("td",{children:qe(d)},`${g}-${d}`))},`${c}-${n.join("|")}`))})]})},`${o}-table`):e.jsx("ul",{children:a.items.map((n,c)=>e.jsx("li",{children:qe(n)},`${c}-${n}`))},`${o}-list`)})}):null},Wt=({assistantName:t})=>e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[e.jsx(it,{className:"make-ai-assistant__avatar--message"}),e.jsx("span",{className:"make-ai-assistant__message-sender",children:t})]}),qt=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="assistant"&&a.status==="streaming")return a.id}},aa=t=>{for(let s=t.messages.length-1;s>=0;s-=1)if(t.messages[s].role==="user")return s;return-1},Xt=t=>{const s=aa(t);if(!(s<0))for(let a=t.messages.length-1;a>s;a-=1){const o=t.messages[a];if(o.role==="assistant")return o.id}},na=t=>{if(t.status==="idle")for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="assistant"&&a.status==="complete")return a.id}},ra=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="user")return a}},ia=(t,s)=>{const a=t.messages.findIndex(o=>o.id===s&&o.role==="user");return{...t,error:void 0,progress:void 0,status:"streaming",messages:a<0?t.messages:t.messages.slice(0,a+1)}},oa=t=>t.scrollHeight-t.scrollTop-t.clientHeight<=48,Lt=(t="smooth")=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":t,ut=(t,s)=>{typeof t.scrollTo=="function"?t.scrollTo({top:t.scrollHeight,behavior:s}):t.scrollTop=t.scrollHeight},Yt=({error:t,onRetry:s})=>e.jsxs("div",{className:"make-ai-assistant__message-status make-ai-assistant__message-status--error","data-error-presentation":"request-failed",role:"alert",children:[e.jsxs("div",{className:"make-ai-assistant__message-status-header",children:[e.jsx("span",{className:"make-ai-assistant__message-status-icon","aria-hidden":"true",children:e.jsx(Gs,{})}),e.jsx("strong",{children:"请求未完成"})]}),e.jsx("span",{className:"make-ai-assistant__message-status-message",children:t.message}),t.retryable&&s?e.jsxs("button",{className:"make-ai-assistant__retry",type:"button",onClick:s,children:[e.jsx(Vt,{}),"重新发送"]}):null]}),ca=({error:t,onRetry:s})=>{const a=zs(t);return e.jsxs("section",{"aria-live":"assertive",className:"make-ai-assistant__load-failure","data-load-failure-kind":a.kind,role:"alert",children:[e.jsx("span",{className:"make-ai-assistant__load-failure-icon","aria-hidden":"true",children:e.jsxs("svg",{viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M5 12a7 7 0 0 1 13.4-2.8A4.5 4.5 0 0 1 18 18H7.5A4.5 4.5 0 0 1 5 12Z"}),e.jsx("path",{d:"m9.2 14.8 5.6-5.6M9.2 9.2l5.6 5.6"})]})}),e.jsxs("div",{className:"make-ai-assistant__load-failure-copy",children:[e.jsx("span",{className:"make-ai-assistant__load-failure-label",children:a.label}),e.jsx("h3",{children:a.title}),e.jsx("p",{children:a.description})]}),e.jsxs("button",{className:"make-ai-assistant__retry make-ai-assistant__retry--primary",type:"button",onClick:s,children:[e.jsx(Vt,{}),a.actionLabel]})]})},Zt=({active:t,steps:s})=>{if(!t||!s?.length)return null;const a=s[s.length-1]??"处理中";return e.jsxs("details",{className:"make-ai-assistant__process",open:!0,children:[e.jsxs("summary",{children:[e.jsxs("span",{className:"make-ai-assistant__progress",role:"status",children:[e.jsx("span",{"aria-hidden":"true"}),e.jsx("span",{children:a})]}),e.jsxs("span",{className:"make-ai-assistant__process-count",children:[s.length," 步"]})]}),e.jsx("ol",{children:s.map((o,n)=>e.jsxs("li",{"data-step-active":n===s.length-1?!0:void 0,children:[e.jsx("span",{"aria-hidden":"true"}),e.jsx("span",{children:o})]},`${n}-${o}`))})]})},la=({copyFeedback:t,onCopy:s,onRegenerate:a})=>!s&&!a?null:e.jsxs("div",{className:"make-ai-assistant__reply-actions","aria-label":"回复操作",children:[s?e.jsx("button",{"aria-label":"复制回答",className:"make-ai-assistant__reply-action make-ai-assistant__reply-copy","data-tooltip":"复制",type:"button",onClick:s,children:e.jsx(Ks,{})}):null,a?e.jsx("button",{"aria-label":"重新生成",className:"make-ai-assistant__reply-action make-ai-assistant__reply-regenerate","data-tooltip":"重新生成",type:"button",onClick:a,children:e.jsx(Vs,{})}):null,t?e.jsx("span",{className:"make-ai-assistant__reply-feedback","data-copy-status":t.status,role:"status",children:t.message}):null]}),$t=({assistantName:t,error:s,onRetry:a,progress:o})=>{const n=s?"error":"progress";return s?.message??o?.message?e.jsx("article",{"aria-label":`${t}的${n==="error"?"错误消息":"状态消息"}`,className:`make-ai-assistant__message make-ai-assistant__message--assistant make-ai-assistant__message--${n}`,"data-message-role":"assistant","data-message-state":n,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[e.jsx(Wt,{assistantName:t}),e.jsx("div",{className:"make-ai-assistant__message-stack",children:s?e.jsx(Yt,{error:s,onRetry:a}):e.jsx(Zt,{active:!0,steps:o?.steps})})]})}):null},da=(t,s,a,o,n,c,d,g,p,f,j,E,B,H,y,V)=>{const Q=Xt(t),W=qt(t),v=na(t);let u;return t.messages.map(l=>{if(l.intermediate)return e.jsxs("details",{className:"make-ai-assistant__process",children:[e.jsx("summary",{children:"处理过程"}),e.jsx(Nt,{content:l.content})]},l.id);const T=l.role==="assistant",N=u;T||(u=l);const ae=l.id===W,R=l.id===Q?t.error:void 0,G=l.error??R,K=!T&&!!(p?.trim()||f),L=T?d:p?.trim()||"用户",q=T&&l.status==="complete"&&!G&&(l.content.trim()||l.id===v);return e.jsx("article",{"aria-label":`${L}的消息`,className:`make-ai-assistant__message make-ai-assistant__message--${l.role}`,"data-message-role":l.role,"data-message-state":G?"error":void 0,"data-message-status":l.status,"data-message-has-identity":T||K?!0:void 0,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[T?e.jsx(Wt,{assistantName:d}):K?e.jsx(Qs,{userAvatarUrl:f,userName:p}):null,e.jsxs("div",{className:"make-ai-assistant__message-stack",children:[T&&l.responseId&&t.responses?.[l.responseId]?.status==="cancelled"?e.jsx("p",{className:"make-ai-assistant__response-status",role:"status",children:"已停止生成"}):null,l.content?T?e.jsx(Nt,{content:l.content}):e.jsx("div",{className:"make-ai-assistant__bubble",children:l.content}):l.status==="streaming"?e.jsxs("div",{className:"make-ai-assistant__typing","aria-label":`${d}正在思考`,children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):null,T?e.jsx(Zt,{active:ae&&t.status==="streaming",steps:l.progressSteps}):null,G?e.jsx(Yt,{error:G,onRetry:R?g:void 0}):null,l.artifacts.map(ne=>e.jsx(Ot,{artifact:ne,context:s,onAction:n,onActionError:c,registry:a,theme:o},ne.id)),y&&V&&t.threadId?e.jsx(ks,{message:l,context:s,transport:V,chatId:t.threadId}):null,y&&V?.features?.feedback?e.jsx(js,{message:l,manager:y}):null,q?e.jsx(la,{copyFeedback:j?.messageId===l.id?{message:j.message,status:j.status}:void 0,onCopy:l.content.trim()?()=>B(l.id,l.content):void 0,onRegenerate:E&&l.id===v&&N?()=>H({userMessage:N,assistantMessage:l}):void 0}):null]})]})},`${t.threadId??"local"}:${l.id}`)})};function Gt({assistantName:t="AI 助手",brandName:s,context:a,onAction:o,onActionError:n,onClose:c,onNewConversation:d,headerHeight:g,privacyNotice:p,registry:f,subtitle:j,suggestions:E,title:B,theme:H,transport:y,userAvatarUrl:V,userName:Q,visible:W}){const v=gs(a,y),u=As(a,y,v),l=Ut(s,B),T=p?.trim(),N=Ns(j,a.app.name),ae=Ps(g),R=mt(H),G=R||ae?{...R,...ae?{"--make-ai-internal-header-height":ae}:{}}:void 0,[K,L]=r.useState(""),[q,ne]=r.useState(!1),[re,de]=r.useState(!1),ye=v.enabled?y.scopeKey?.(a)??a.app.id:"";r.useLayoutEffect(()=>{v.enabled&&L("")},[ye,v.enabled]);const[be,X]=r.useState(x.createAssistantConversationState),k=v.enabled?v.state:be,b=v.enabled?v.setState:X,P=r.useRef(k);P.current=k;const[Y,ee]=r.useState(void 0),[Se,C]=r.useState(void 0),[te,ie]=r.useState(0),[ue,je]=r.useState(()=>y.loadConversation?"loading":"ready"),J=v.enabled?v.loading&&!k.messages.length?"loading":"ready":ue,[ve,_e]=r.useState(void 0),[Xe,oe]=r.useState(!1),[me,Ye]=r.useState(!1),[ke,Ze]=r.useState(void 0),Ie=r.useRef(void 0),Ae=r.useRef(void 0),we=r.useRef(0),Ge=r.useRef(null),Ee=r.useRef(null),Je=r.useRef(null),Te=r.useRef(null),i=r.useRef(null),h=r.useRef(null),_=r.useRef(null),A=r.useRef(null),w=r.useRef(!0),S=r.useRef(a.app.id),I=r.useRef(W),z=r.useId(),F=r.useId(),O=r.useMemo(()=>f??zt(),[f]),he=r.useMemo(()=>Ss(E),[E]),Be=()=>{const m=h.current,$=_.current;if(!m||!$||typeof window>"u")return;const D=Fs(m.getBoundingClientRect(),$.getBoundingClientRect(),window.innerHeight,window.innerWidth);Ze(U=>U?.left===D.left&&U.top===D.top&&U.placement===D.placement?U:D)},ze=()=>Ye(!0),ce=()=>Ye(!1),Ne=ke?{left:`${ke.left}px`,top:`${ke.top}px`}:void 0;r.useLayoutEffect(()=>{if(!me||!T){Ze(void 0);return}Be()},[me,T]),r.useEffect(()=>{if(!me||!T)return;const m=()=>Be();return window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),()=>{window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0)}},[me,T]);const ge=m=>{const $=Ie.current,D=Ae.current?.iterator;return!$&&!D?!1:(we.current+=1,Ie.current=void 0,Ae.current=void 0,console.info("[make-ai-assistant] local run cancellation requested",{reason:m}),$?.abort(),St(D),!0)};r.useEffect(()=>()=>{ge("unmount")},[]),r.useEffect(()=>{if(v.enabled)return;const m=y.loadConversation,$=S.current!==a.app.id;if(S.current=a.app.id,ge("reinitialize"),$&&(L(""),w.current=!0),ee(void 0),C(void 0),oe(!1),b(x.createAssistantConversationState()),!m){_e(void 0),je("ready");return}const D=new AbortController;return _e(void 0),je("loading"),console.info("[make-ai-assistant] conversation load start",{appId:a.app.id}),m.call(y,a,{signal:D.signal}).then(U=>{D.signal.aborted||(b(x.createAssistantConversationState(U)),je("ready"),console.info("[make-ai-assistant] conversation load success",{appId:a.app.id,messageCount:U.messages.length}))}).catch(U=>{D.signal.aborted||(console.error("[make-ai-assistant] conversation load failed",{appId:a.app.id,errorType:U instanceof Error?U.name:typeof U}),_e(U),je("error"))}),()=>D.abort()},[a.app.id,te,y,v.enabled]),r.useEffect(()=>{const m=Ee.current;if(!m||!w.current)return;oe(!1);const $=requestAnimationFrame(()=>{if(!w.current)return;const D=k.status==="streaming"||globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";ut(m,D)});return()=>cancelAnimationFrame($)},[k.messages,k.progress,k.status]),r.useEffect(()=>{W||(ne(!1),de(!1))},[W]),r.useEffect(()=>{const m=W&&!I.current;if(I.current=W,!m)return;const $=requestAnimationFrame(()=>{const D=Ee.current;if(D&&w.current){oe(!1);const Ue=P.current.status==="streaming"?"auto":Lt();ut(D,Ue)}else D&&oe(P.current.messages.length>0);const U=Je.current;(U&&!U.disabled?U:A.current??Ge.current?.querySelector("button:not(:disabled)"))?.focus()});return()=>cancelAnimationFrame($)},[W]);const Jt=()=>{const m=Ee.current;if(!m)return;const $=oa(m);w.current=$,oe(!$&&P.current.messages.length>0)},Qt=()=>{const m=Ee.current;if(!m)return;w.current=!0,oe(!1);const $=Lt();ut(m,$)},ft=async(m,$)=>{const D=m.trim(),U=P.current,xe=$?.regenerateFrom,Ue=y.regenerate;if(!D||J!=="ready"||U.status==="streaming"||Ie.current||xe&&!Ue)return;if(x.countCodePointsUpTo(D,x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){ee(`输入内容过长,请控制在 ${x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const tt={id:xe?.userMessage.id??Ms("user"),content:D},st=xe?ia(U,xe.userMessage.id):x.appendUserMessage(U,tt),at=new AbortController,Le=we.current+1;we.current=Le,Ie.current=at,ee(void 0),C(void 0),oe(!w.current&&U.messages.length>0),xe||L(""),b(st);try{let Me=!1,se,xt=0,yt=0,bt=0,ot=0,He=0;const Ke=new Map,jt=new Set,_t=new Set([...st.messages.map(nt=>nt.id),tt.id]),Ve=new Set,kt=Ce.createArtifactCapabilities(O),It={signal:at.signal};let ct;if(xe){if(!Ue)throw new Z("当前 AI 助手不支持重新生成");ct=Ue({threadId:st.threadId,message:tt,assistantMessage:{id:xe.assistantMessage.id,content:xe.assistantMessage.content},context:a,capabilities:kt},It)}else ct=y.run({threadId:st.threadId,message:tt,context:a,capabilities:kt},It);const At=ct[Symbol.asyncIterator]();for(Ae.current={iterator:At,requestVersion:Le};;){const nt=await At.next();if(we.current!==Le||nt.done)break;let M;try{M=x.parseAssistantEvent(nt.value)}catch(le){throw new Z(le instanceof Error?le.message:"Invalid assistant event")}if(M.type==="message.start"){if(se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(se??=M.runId,yt+=1,yt>x.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new Z("AI 助手单次响应消息数量超过限制");if(_t.has(M.messageId))throw new Z("AI 助手响应包含重复的 message id");_t.add(M.messageId),Ve.add(M.messageId),Ke.set(M.messageId,0)}if(M.type==="message.delta"){if(!Ve.has(M.messageId))throw new Z("AI 助手响应事件顺序无效");const le=Ke.get(M.messageId)??0,$e=x.countCodePointsUpTo(M.delta,x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-He);if(He+$e>x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Z("AI 助手响应文本超过大小限制");He+=$e,Ke.set(M.messageId,le+$e)}if(M.type==="message.replace"){if(!Ve.has(M.messageId))throw new Z("AI 助手响应事件顺序无效");const le=Ke.get(M.messageId)??0,$e=x.countCodePointsUpTo(M.content,x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters),wt=He-le+$e;if(wt>x.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Z("AI 助手响应文本超过大小限制");He=wt,Ke.set(M.messageId,$e)}if(M.type==="run.progress"){if(se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(se??=M.runId,bt+=1,bt>x.MAKE_AI_CONVERSATION_LIMITS.progressStepsPerRun)throw new Z("AI 助手处理过程数量超过限制");const le=x.countCodePointsUpTo(M.message,x.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun-ot);if(ot+le>x.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun)throw new Z("AI 助手处理过程文本超过大小限制");ot+=le}if(M.type==="artifact"){if(!Ve.has(M.messageId))throw new Z("AI 助手响应事件顺序无效");if(xt+=1,xt>x.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new Z("AI 助手单次响应 Artifact 数量超过限制");if(jt.has(M.artifact.id))throw new Z("AI 助手响应包含重复的 Artifact id");jt.add(M.artifact.id)}if(M.type==="message.complete"&&!Ve.delete(M.messageId))throw new Z("AI 助手响应事件顺序无效");if(M.type==="run.complete"&&se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(M.type==="run.cancelled"&&M.runId!==void 0&&se!==void 0&&se!==M.runId)throw new Z("AI 助手响应 run id 不一致");if(b(le=>x.reduceAssistantEvent(le,M)),M.type==="error"||M.type==="run.cancelled"||M.type==="run.complete"){Me=!0;break}}if(!Me)throw new Z("AI 助手流式响应在终止事件前结束")}catch(Me){if(we.current!==Le)return;if(at.signal.aborted){b(se=>x.reduceAssistantEvent(se,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:Me instanceof Error?Me.name:typeof Me}),b(se=>x.reduceAssistantEvent(se,{type:"error",code:"TRANSPORT_ERROR",message:Me instanceof Z?Me.message:"连接失败,请重试",retryable:!0}))}finally{we.current===Le&&Ie.current===at&&(Ie.current=void 0),Ae.current?.requestVersion===Le&&(St(Ae.current.iterator),Ae.current=void 0)}},Qe=m=>{if(v.enabled){if(u.pending)return ee("请等待附件上传完成,或移除失败的附件"),Promise.resolve();if(u.parts.some(U=>!y.features?.modelInputKinds?.includes(U.kind)))return ee("当前模型尚未开放此类附件理解,已上传原件可保留或移除"),Promise.resolve();const $=m.trim(),D=u.parts.length?[...$?[{id:Oe(),kind:"text",text:$}]:[],...u.parts]:void 0;return L(""),u.clear(),v.send($,D)}return ft(m)},es=m=>ft(m.userMessage.content,{regenerateFrom:m}),ts=async(m,$)=>{try{await Us($),C({messageId:m,message:"已复制",status:"success"})}catch(D){console.error("[make-ai-assistant] copy answer failed",{errorType:D instanceof Error?D.name:typeof D}),C({messageId:m,message:"复制失败",status:"error"})}},ss=m=>{m.preventDefault(),Qe(K)},as=m=>{m.key==="Enter"&&!m.shiftKey&&!m.nativeEvent.isComposing&&(m.preventDefault(),Qe(K))},ns=()=>{if(v.enabled){v.stop();return}ge("stop")&&b(m=>x.reduceAssistantEvent(m,{type:"run.cancelled"}))},pt=()=>{if(de(!1),v.enabled){L(""),v.create(),d?.();return}ge("new-conversation"),L(""),ee(void 0),C(void 0),oe(!1),w.current=!0,b(x.createAssistantConversationState()),d?.()},vt=v.enabled&&v.cancelling.length?"停止中":y.features?.remoteCancellation===!1?"停止接收":"停止生成",rs=qt(k),is=Xt(k),et=ra(k),os=typeof y.regenerate=="function"&&y.features?.regeneration!==!1,gt=()=>{if(v.enabled){v.retry();return}et&&Qe(et.content)},cs=m=>{if(m.key==="Escape"&&!(!q&&!re)){if(m.preventDefault(),m.stopPropagation(),q){ne(!1),Te.current?.focus();return}de(!1),i.current?.focus()}};return e.jsxs("section",{className:`make-ai-assistant make-ai-assistant__panel${v.enabled?" make-ai-assistant__panel--managed":""}`,ref:Ge,style:G,onKeyDown:cs,onDragOver:m=>{u.enabled&&m.dataTransfer.types.includes("Files")&&m.preventDefault()},onDrop:m=>{u.enabled&&m.dataTransfer.files.length&&(m.preventDefault(),u.add(Array.from(m.dataTransfer.files)))},children:[e.jsxs("header",{className:"make-ai-assistant__header",children:[e.jsx("div",{className:"make-ai-assistant__header-leading",children:v.enabled?e.jsxs("button",{"aria-controls":F,"aria-expanded":re,"aria-haspopup":"dialog","aria-label":"任务列表",className:"make-ai-assistant__task-list-trigger",ref:i,type:"button",onClick:()=>de(m=>!m),children:[e.jsx(Ys,{}),e.jsx("span",{children:"任务列表"}),e.jsx(Zs,{})]}):null}),e.jsxs("div",{className:"make-ai-assistant__header-center",children:[e.jsx(it,{}),e.jsxs("div",{className:"make-ai-assistant__header-content",children:[e.jsxs("div",{className:"make-ai-assistant__header-title-row",children:[e.jsx("h2",{className:"make-ai-assistant__header-title",title:l,children:l}),v.enabled?e.jsx("span",{className:"make-ai-assistant__current-conversation",children:v.chat?.title||"新对话"}):null,e.jsx("span",{className:"make-ai-assistant__read-only-tag",children:"只读"})]}),e.jsxs("div",{className:"make-ai-assistant__header-context",children:[e.jsx("p",{title:N,children:N}),T?e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-describedby":z,"aria-label":`使用提示:${T}`,className:"make-ai-assistant__header-context-help","data-tooltip":T,ref:h,role:"note",tabIndex:0,onBlur:ce,onFocus:ze,onPointerEnter:ze,onPointerLeave:ce,children:e.jsx(Ws,{})}),e.jsx("span",{"aria-hidden":!me,className:"make-ai-assistant__header-context-tooltip","data-placement":ke?.placement,"data-positioned":ke?!0:void 0,"data-visible":me||void 0,id:z,ref:_,role:"tooltip",style:Ne,children:T})]}):null]})]})]}),e.jsxs("div",{className:"make-ai-assistant__header-actions",children:[y.features?.newConversation!==!1?e.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:pt,children:e.jsx(Xs,{})}):null,c?e.jsx("button",{"aria-label":`关闭 ${l}`,className:"make-ai-assistant__icon-button",type:"button",onClick:c,children:e.jsx(Hs,{})}):null]})]}),v.enabled&&re?e.jsx(bs,{id:F,manager:v,triggerRef:i,onDismiss:()=>de(!1),onNewConversation:y.features?.newConversation!==!1?pt:void 0}):null,e.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite","aria-relevant":"additions text",ref:Ee,role:"log",onScroll:Jt,children:[J==="loading"?e.jsxs("div",{className:"make-ai-assistant__empty",role:"status",children:[e.jsx(it,{}),e.jsx("h3",{children:"正在恢复对话"}),e.jsx("p",{children:"正在读取当前 App 的历史消息…"})]}):J==="error"?e.jsx("div",{className:"make-ai-assistant__empty",children:e.jsx(ca,{error:ve,onRetry:()=>ie(m=>m+1)})}):k.messages.length===0?e.jsxs("div",{className:"make-ai-assistant__empty",children:[e.jsx(it,{}),e.jsx("h3",{children:"有什么可以帮你?"}),e.jsx("p",{children:"我会结合当前 App、页面位置和宿主允许的上下文回答,并把过程与结果分开展示。"})]}):da(k,a,O,H,o,n,t,et?gt:void 0,Q,V,Se,os,(m,$)=>{ts(m,$)},m=>{es(m)},v.enabled?v:void 0,y),k.progress&&!rs?e.jsx($t,{assistantName:t,progress:k.progress}):null,k.error&&!is?e.jsx($t,{assistantName:t,error:k.error,onRetry:et?gt:void 0}):null]}),Xe?e.jsx("button",{"aria-label":"回到最新消息",className:"make-ai-assistant__back-to-latest",type:"button",onClick:Qt,children:e.jsx(qs,{})}):null,e.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[u.enabled?e.jsx(Ts,{attachments:u}):null,J==="ready"&&he.length>0&&k.messages.length===0?e.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:he.map((m,$)=>e.jsx("button",{type:"button",onClick:()=>{Qe(m)},children:m},`${$}-${m}`))}):null,e.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:ss,children:[e.jsx("textarea",{"aria-label":`向 ${t} 提问`,"aria-describedby":Y?"make-ai-composer-error":void 0,"aria-invalid":Y?!0:void 0,autoFocus:!0,disabled:J!=="ready"||!v.enabled&&k.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,ref:Je,rows:2,value:K,onChange:m=>{L(m.currentTarget.value),ee(void 0)},onKeyDown:as,onPaste:m=>{u.enabled&&m.clipboardData.files.length&&(m.preventDefault(),u.add(Array.from(m.clipboardData.files)))}}),u.enabled?e.jsx(ws,{attachments:u,open:q,triggerRef:Te,onOpenChange:ne}):null,e.jsxs("div",{className:"make-ai-assistant__composer-actions",children:[k.status==="streaming"?e.jsx("button",{"aria-label":vt,className:"make-ai-assistant__send make-ai-assistant__send--stop","data-tooltip":vt,ref:A,disabled:v.enabled&&v.cancelling.includes(k.activeRunId??""),type:"button",onClick:ns,children:e.jsx("span",{"aria-hidden":"true"})}):e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:J!=="ready"||u.pending||!K.trim()&&!u.parts.length,type:"submit",children:e.jsx(Et,{})}),v.enabled&&k.status==="streaming"?e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:v.busy||u.pending||!K.trim()&&!u.parts.length,type:"submit",children:e.jsx(Et,{})}):null]})]}),Y?e.jsx("p",{id:"make-ai-composer-error",role:"alert",children:Y}):null,e.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function ua(t){return e.jsx(Gt,{...t,visible:!0})}function ma({defaultOpen:t=!1,hideLauncher:s=!1,launcher:a,launcherPosition:o="bottom-right",maxDrawerWidth:n,onOpenChange:c,open:d,...g}){const p=Ut(g.brandName,g.title),[f,j]=r.useState(t),[E,B]=r.useState(()=>t||d===!0),H=r.useRef(null),y=r.useRef(null),V=r.useRef(void 0),[Q,W]=r.useState(),[v,u]=r.useState(Ls),[l,T]=r.useState(!1),N=d??f,ae=mt(g.theme),R=Ds(n),G=()=>Os(v,R,typeof window>"u"?Ht:window.innerWidth),K=G(),L=Q===void 0?void 0:lt(Q,v,K),q=L===void 0&&R===void 0?void 0:{...L===void 0?{}:{"--make-ai-internal-drawer-width":`${L}px`},...R===void 0?{}:{"--make-ai-internal-drawer-max-width":`max(var(--make-ai-internal-drawer-min-width), ${R}px)`}};r.useLayoutEffect(()=>{L!==void 0&&L!==Q&&W(L)},[L,Q]);const ne=()=>{if(L!==void 0)return L;const b=y.current?.getBoundingClientRect().width;return b&&Number.isFinite(b)&&b>0?b:v},re=b=>{if(b.button!==0)return;const P=ne(),Y=Q===void 0?P:v;u(Y),V.current={minimumWidth:Y,pointerId:b.pointerId,startWidth:P,startX:b.clientX},T(!0),typeof b.currentTarget.setPointerCapture=="function"&&b.currentTarget.setPointerCapture(b.pointerId),b.preventDefault()},de=b=>{const P=V.current;if(!P||P.pointerId!==b.pointerId)return;const Y=lt(P.startWidth+P.startX-b.clientX,P.minimumWidth,G());W(Y)},ye=b=>{const P=V.current;!P||P.pointerId!==b.pointerId||(V.current=void 0,T(!1))},be=b=>{const P=b.key==="ArrowLeft"?Rt:b.key==="ArrowRight"?-Rt:void 0;if(P===void 0)return;b.preventDefault();const Y=ne(),ee=Q===void 0?Y:v;u(ee),W(lt(Y+P,ee,G()))},X=b=>{d===void 0&&j(b),c?.(b),b||requestAnimationFrame(()=>H.current?.focus())},k=()=>X(!N);return r.useEffect(()=>{N&&B(!0)},[N]),r.useEffect(()=>{if(!N)return;const b=P=>{P.key==="Escape"&&(X(!1),requestAnimationFrame(()=>H.current?.focus()))};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[c,N]),e.jsxs("div",{className:"make-ai-assistant","data-open":N||void 0,style:ae,children:[!s&&(!N||a)?a?a({open:N,toggle:k}):e.jsxs("button",{"aria-label":N?`关闭 ${p}`:`打开 ${p}`,"aria-expanded":N,className:"make-ai-assistant__launcher","data-launcher-position":o,ref:H,type:"button",onClick:k,children:[e.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),e.jsx(Kt,{})]}):null,E?e.jsxs("aside",{"aria-label":p,"aria-modal":"false",className:"make-ai-assistant__drawer","data-resizing":l||void 0,hidden:!N,ref:y,role:"dialog",style:q,children:[e.jsx("div",{"aria-label":"调整对话框宽度","aria-orientation":"vertical","aria-valuemax":K,"aria-valuemin":v,"aria-valuenow":L??v,className:"make-ai-assistant__drawer-resize-handle",role:"separator",tabIndex:0,onKeyDown:be,onPointerCancel:ye,onPointerDown:re,onPointerMove:de,onPointerUp:ye}),e.jsx(Gt,{...g,onClose:()=>X(!1),visible:N})]}):null]})}exports.createArtifactCapabilities=Ce.createArtifactCapabilities;exports.createArtifactTemplateRegistry=Ce.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=Ce.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=Ce.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=x.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=x.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=x.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=x.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=x.appendUserMessage;exports.createAssistantConversationState=x.createAssistantConversationState;exports.parseArtifact=x.parseArtifact;exports.parseAssistantEvent=x.parseAssistantEvent;exports.reduceAssistantEvent=x.reduceAssistantEvent;exports.validateArtifact=x.validateArtifact;exports.ArtifactRenderer=Ot;exports.AssistantPanel=ua;exports.MakeAiAssistant=ma;exports.createPlatformArtifactRegistry=zt;exports.formatArtifactValue=Re;exports.platformArtifactTemplates=Bt;
|
|
3
|
+
`),d=()=>{const p=a.join(`
|
|
4
|
+
`).trim();a.length=0,p&&s.push({type:"paragraph",text:p})},h=()=>{i.length&&s.push({type:"list",items:i.splice(0)})},y=()=>{const p=o.join(`
|
|
5
|
+
`).trim();o.length=0,p&&s.push({type:"pre",text:p})};for(let p=0;p<l.length;p+=1){const C=l[p]??"",S=C.trim();if(!S){d(),h(),y();continue}const R=Vs(l,p);if(R){d(),h(),y(),s.push({headers:R.headers,rows:R.rows,type:"table"}),p=R.lastIndex;continue}const V=/^(#{1,6})\s+(.+)$/.exec(S);if(V){d(),h(),y();const D=(V[2]??"").replace(/\s+#+\s*$/,"").trim();D&&s.push({type:"heading",level:V[1]?.length,text:D});continue}if(/^\s*\|.+\|\s*$/.test(C)){d(),h(),o.push(C.trim());continue}const A=/^\s*[-*]\s+(.+)$/.exec(C);if(A){d(),y(),i.push(A[1]?.trim()??"");continue}h(),y(),a.push(S)}return d(),h(),y(),s},Ke=t=>{const s=[],a=/(\*\*[^*]+\*\*|`[^`]+`)/g;let i=0;for(const o of t.matchAll(a)){const l=o[0],d=o.index??0;d>i&&s.push(t.slice(i,d)),l.startsWith("**")?s.push(e.jsx("strong",{children:l.slice(2,-2)},`${d}-strong`)):s.push(e.jsx("code",{children:l.slice(1,-1)},`${d}-code`)),i=d+l.length}return i<t.length&&s.push(t.slice(i)),s},Nt=({content:t})=>{const s=qs(t);return s.length?e.jsx("div",{className:"make-ai-assistant__bubble make-ai-assistant__assistant-text",children:s.map((a,i)=>{if(a.type==="heading"){const o=a.level<=2?"h3":"h4";return e.jsx(o,{className:`make-ai-assistant__markdown-heading make-ai-assistant__markdown-heading--${a.level}`,children:Ke(a.text)},`${i}-heading`)}return a.type==="paragraph"?e.jsx("p",{children:Ke(a.text)},`${i}-paragraph`):a.type==="pre"?e.jsx("pre",{children:e.jsx("code",{children:a.text})},`${i}-pre`):a.type==="table"?e.jsx("div",{"aria-label":"表格内容,可横向滚动",className:"make-ai-assistant__markdown-table-scroll",role:"region",tabIndex:0,children:e.jsxs("table",{className:"make-ai-assistant__markdown-table",children:[e.jsx("thead",{children:e.jsx("tr",{children:a.headers.map((o,l)=>e.jsx("th",{scope:"col",children:Ke(o)},`${l}-${o}`))})}),e.jsx("tbody",{children:a.rows.map((o,l)=>e.jsx("tr",{children:o.map((d,h)=>e.jsx("td",{children:Ke(d)},`${h}-${d}`))},`${l}-${o.join("|")}`))})]})},`${i}-table`):e.jsx("ul",{children:a.items.map((o,l)=>e.jsx("li",{children:Ke(o)},`${l}-${o}`))},`${i}-list`)})}):null},Kt=({assistantName:t})=>e.jsxs("div",{className:"make-ai-assistant__message-identity",children:[e.jsx(st,{className:"make-ai-assistant__avatar--message"}),e.jsx("span",{className:"make-ai-assistant__message-sender",children:t})]}),Wt=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="assistant"&&a.status==="streaming")return a.id}},Hs=t=>{for(let s=t.messages.length-1;s>=0;s-=1)if(t.messages[s].role==="user")return s;return-1},Vt=t=>{const s=Hs(t);if(!(s<0))for(let a=t.messages.length-1;a>s;a-=1){const i=t.messages[a];if(i.role==="assistant")return i.id}},Zs=t=>{if(t.status==="idle")for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="assistant"&&a.status==="complete")return a.id}},Xs=t=>{for(let s=t.messages.length-1;s>=0;s-=1){const a=t.messages[s];if(a.role==="user")return a}},Gs=(t,s)=>{const a=t.messages.findIndex(i=>i.id===s&&i.role==="user");return{...t,error:void 0,progress:void 0,status:"streaming",messages:a<0?t.messages:t.messages.slice(0,a+1)}},Ys=t=>t.scrollHeight-t.scrollTop-t.clientHeight<=48,Tt=(t="smooth")=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":t,lt=(t,s)=>{typeof t.scrollTo=="function"?t.scrollTo({top:t.scrollHeight,behavior:s}):t.scrollTop=t.scrollHeight},qt=({error:t,onRetry:s})=>e.jsxs("div",{className:"make-ai-assistant__message-status make-ai-assistant__message-status--error","data-error-presentation":"request-failed",role:"alert",children:[e.jsxs("div",{className:"make-ai-assistant__message-status-header",children:[e.jsx("span",{className:"make-ai-assistant__message-status-icon","aria-hidden":"true",children:e.jsx(Bs,{})}),e.jsx("strong",{children:"请求未完成"})]}),e.jsx("span",{className:"make-ai-assistant__message-status-message",children:t.message}),t.retryable&&s?e.jsxs("button",{className:"make-ai-assistant__retry",type:"button",onClick:s,children:[e.jsx(zt,{}),"重新发送"]}):null]}),Js=({error:t,onRetry:s})=>{const a=Cs(t);return e.jsxs("section",{"aria-live":"assertive",className:"make-ai-assistant__load-failure","data-load-failure-kind":a.kind,role:"alert",children:[e.jsx("span",{className:"make-ai-assistant__load-failure-icon","aria-hidden":"true",children:e.jsxs("svg",{viewBox:"0 0 24 24",children:[e.jsx("path",{d:"M5 12a7 7 0 0 1 13.4-2.8A4.5 4.5 0 0 1 18 18H7.5A4.5 4.5 0 0 1 5 12Z"}),e.jsx("path",{d:"m9.2 14.8 5.6-5.6M9.2 9.2l5.6 5.6"})]})}),e.jsxs("div",{className:"make-ai-assistant__load-failure-copy",children:[e.jsx("span",{className:"make-ai-assistant__load-failure-label",children:a.label}),e.jsx("h3",{children:a.title}),e.jsx("p",{children:a.description})]}),e.jsxs("button",{className:"make-ai-assistant__retry make-ai-assistant__retry--primary",type:"button",onClick:s,children:[e.jsx(zt,{}),a.actionLabel]})]})},Ht=({active:t,steps:s})=>{const[a,i]=c.useState(!1);if(!t||!s?.length)return null;const o=s[s.length-1]??"处理中";return e.jsxs("details",{className:"make-ai-assistant__process",open:a,onToggle:l=>i(l.currentTarget.open),children:[e.jsxs("summary",{"aria-label":`查看处理过程,共 ${s.length} 步`,children:[e.jsxs("span",{className:"make-ai-assistant__process-summary",children:[e.jsx("span",{className:"make-ai-assistant__process-indicator","aria-hidden":"true"}),e.jsxs("span",{className:"make-ai-assistant__process-copy",children:[e.jsx("span",{className:"make-ai-assistant__process-title",children:"处理过程"}),e.jsx("span",{className:"make-ai-assistant__progress make-ai-assistant__process-latest",role:"status",children:o})]})]}),e.jsxs("span",{className:"make-ai-assistant__process-count",children:[s.length," 步"]})]}),e.jsx("ol",{children:s.map((l,d)=>e.jsxs("li",{"data-step-active":d===s.length-1?!0:void 0,children:[e.jsx("span",{"aria-hidden":"true"}),e.jsx("span",{children:l})]},`${d}-${l}`))})]})},Qs=({copyFeedback:t,feedback:s,onCopy:a,onRegenerate:i})=>!s&&!a&&!i?null:e.jsxs("div",{className:"make-ai-assistant__reply-actions","aria-label":"回复操作",children:[a?e.jsx("button",{"aria-label":"复制回答",className:"make-ai-assistant__reply-action make-ai-assistant__reply-copy","data-tooltip":"复制",type:"button",onClick:a,children:e.jsx($s,{})}):null,s,i?e.jsx("button",{"aria-label":"重新生成",className:"make-ai-assistant__reply-action make-ai-assistant__reply-regenerate","data-tooltip":"重新生成",type:"button",onClick:i,children:e.jsx(Ds,{})}):null,t?e.jsx("span",{className:"make-ai-assistant__reply-feedback","data-copy-status":t.status,role:"status",children:t.message}):null]}),St=({assistantName:t,error:s,onRetry:a,progress:i})=>{const o=s?"error":"progress";return s?.message??i?.message?e.jsx("article",{"aria-label":`${t}的${o==="error"?"错误消息":"状态消息"}`,className:`make-ai-assistant__message make-ai-assistant__message--assistant make-ai-assistant__message--${o}`,"data-message-role":"assistant","data-message-state":o,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[e.jsx(Kt,{assistantName:t}),e.jsx("div",{className:"make-ai-assistant__message-stack",children:s?e.jsx(qt,{error:s,onRetry:a}):e.jsx(Ht,{active:!0,steps:i?.steps})})]})}):null},ea=(t,s,a,i,o,l,d,h,y,p,C,S,R,V,A,D)=>{const g=Vt(t),N=Wt(t),F=Zs(t);let f;return t.messages.map(n=>{if(n.intermediate)return e.jsxs("details",{className:"make-ai-assistant__process",children:[e.jsx("summary",{children:"处理过程"}),e.jsx(Nt,{content:n.content})]},n.id);const v=n.role==="assistant",_=f;v||(f=n);const K=n.id===N,I=n.id===g?t.error:void 0,X=n.error??I,G=!v&&!!(y?.trim()||p),U=v?d:y?.trim()||"用户",J=v&&n.status==="complete"&&!X&&(n.content.trim()||n.id===F),me=!!(A&&D?.features?.feedback&&v&&n.persistent),re=J||me;return e.jsx("article",{"aria-label":`${U}的消息`,className:`make-ai-assistant__message make-ai-assistant__message--${n.role}`,"data-message-role":n.role,"data-message-state":X?"error":void 0,"data-message-status":n.status,"data-message-has-identity":v||G?!0:void 0,children:e.jsxs("div",{className:"make-ai-assistant__message-turn",children:[v?e.jsx(Kt,{assistantName:d}):G?e.jsx(Ks,{userAvatarUrl:p,userName:y}):null,e.jsxs("div",{className:"make-ai-assistant__message-stack",children:[v&&n.responseId&&t.responses?.[n.responseId]?.status==="cancelled"?e.jsx("p",{className:"make-ai-assistant__response-status",role:"status",children:"已停止生成"}):null,n.content?v?e.jsx(Nt,{content:n.content}):e.jsx("div",{className:"make-ai-assistant__bubble",children:n.content}):n.status==="streaming"?e.jsxs("div",{className:"make-ai-assistant__typing","aria-label":`${d}正在思考`,children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}):null,v?e.jsx(Ht,{active:K&&t.status==="streaming",steps:n.progressSteps}):null,X?e.jsx(qt,{error:X,onRetry:I?h:void 0}):null,n.artifacts.map(O=>e.jsx(Et,{artifact:O,context:s,onAction:o,onActionError:l,registry:a,theme:i},O.id)),A&&D&&t.threadId?e.jsx(ps,{message:n,context:s,transport:D,chatId:t.threadId}):null,re?e.jsx(Qs,{copyFeedback:C?.messageId===n.id?{message:C.message,status:C.status}:void 0,onCopy:n.content.trim()?()=>R(n.id,n.content):void 0,feedback:A&&me?e.jsx(hs,{message:n,manager:A}):void 0,onRegenerate:S&&n.id===F&&_?()=>V({userMessage:_,assistantMessage:n}):void 0}):null]})]})},`${t.threadId??"local"}:${n.id}`)})};function Zt({assistantName:t="AI 助手",brandName:s,context:a,onAction:i,onActionError:o,onClose:l,onNewConversation:d,headerHeight:h,registry:y,suggestions:p,title:C,theme:S,transport:R,userAvatarUrl:V,userName:A,visible:D}){const g=ns(a,R),N=ys(a,R,g),F=Ut(s,C),f=Ts(h),n=dt(S),v=n||f?{...n,...f?{"--make-ai-internal-header-height":f}:{}}:void 0,[_,K]=c.useState(""),[I,X]=c.useState(!1),[G,U]=c.useState(!1),J=g.enabled?R.scopeKey?.(a)??a.app.id:"";c.useLayoutEffect(()=>{g.enabled&&K("")},[J,g.enabled]);const[me,re]=c.useState(b.createAssistantConversationState),O=g.enabled?g.state:me,ae=g.enabled?g.setState:re,ie=c.useRef(O);ie.current=O;const[q,$]=c.useState(void 0),[w,P]=c.useState(void 0),[te,he]=c.useState(0),[we,E]=c.useState(()=>R.loadConversation?"loading":"ready"),Q=g.enabled?g.loading&&!O.messages.length?"loading":"ready":we,[oe,ce]=c.useState(void 0),[at,fe]=c.useState(!1),xe=c.useRef(void 0),pe=c.useRef(void 0),ee=c.useRef(0),_e=c.useRef(null),ve=c.useRef(null),Oe=c.useRef(null),Fe=c.useRef(null),Ae=c.useRef(null),We=c.useRef(null),le=c.useRef(!0),Ve=c.useRef(a.app.id),qe=c.useRef(D),He=c.useId(),Ze=c.useMemo(()=>y??Ot(),[y]),Xe=c.useMemo(()=>ws(p),[p]),Ne=m=>{const W=xe.current,Z=pe.current?.iterator;return!W&&!Z?!1:(ee.current+=1,xe.current=void 0,pe.current=void 0,console.info("[make-ai-assistant] local run cancellation requested",{reason:m}),W?.abort(),Mt(Z),!0)};c.useEffect(()=>()=>{Ne("unmount")},[]),c.useEffect(()=>{if(g.enabled)return;const m=R.loadConversation,W=Ve.current!==a.app.id;if(Ve.current=a.app.id,Ne("reinitialize"),W&&(K(""),le.current=!0),$(void 0),P(void 0),fe(!1),ae(b.createAssistantConversationState()),!m){ce(void 0),E("ready");return}const Z=new AbortController;return ce(void 0),E("loading"),console.info("[make-ai-assistant] conversation load start",{appId:a.app.id}),m.call(R,a,{signal:Z.signal}).then(se=>{Z.signal.aborted||(ae(b.createAssistantConversationState(se)),E("ready"),console.info("[make-ai-assistant] conversation load success",{appId:a.app.id,messageCount:se.messages.length}))}).catch(se=>{Z.signal.aborted||(console.error("[make-ai-assistant] conversation load failed",{appId:a.app.id,errorType:se instanceof Error?se.name:typeof se}),ce(se),E("error"))}),()=>Z.abort()},[a.app.id,te,R,g.enabled]),c.useEffect(()=>{const m=ve.current;if(!m||!le.current)return;fe(!1);const W=requestAnimationFrame(()=>{if(!le.current)return;const Z=O.status==="streaming"||globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches?"auto":"smooth";lt(m,Z)});return()=>cancelAnimationFrame(W)},[O.messages,O.progress,O.status]),c.useEffect(()=>{D||(X(!1),U(!1))},[D]),c.useEffect(()=>{const m=D&&!qe.current;if(qe.current=D,!m)return;const W=requestAnimationFrame(()=>{const Z=ve.current;if(Z&&le.current){fe(!1);const Ue=ie.current.status==="streaming"?"auto":Tt();lt(Z,Ue)}else Z&&fe(ie.current.messages.length>0);const se=Oe.current;(se&&!se.disabled?se:We.current??_e.current?.querySelector("button:not(:disabled)"))?.focus()});return()=>cancelAnimationFrame(W)},[D]);const nt=()=>{const m=ve.current;if(!m)return;const W=Ys(m);le.current=W,fe(!W&&ie.current.messages.length>0)},Me=()=>{const m=ve.current;if(!m)return;le.current=!0,fe(!1);const W=Tt();lt(m,W)},r=async(m,W)=>{const Z=m.trim(),se=ie.current,be=W?.regenerateFrom,Ue=R.regenerate;if(!Z||Q!=="ready"||se.status==="streaming"||xe.current||be&&!Ue)return;if(b.countCodePointsUpTo(Z,b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)>b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters){$(`输入内容过长,请控制在 ${b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters} 个字符以内`);return}const Ye={id:be?.userMessage.id??js("user"),content:Z},Je=be?Gs(se,be.userMessage.id):b.appendUserMessage(se,Ye),Qe=new AbortController,Se=ee.current+1;ee.current=Se,xe.current=Qe,$(void 0),P(void 0),fe(!le.current&&se.messages.length>0),be||K(""),ae(Je);try{let je=!1,ne,mt=0,ht=0,ft=0,rt=0,Pe=0;const Be=new Map,pt=new Set,vt=new Set([...Je.messages.map(et=>et.id),Ye.id]),ze=new Set,gt=Ie.createArtifactCapabilities(Ze),xt={signal:Qe.signal};let it;if(be){if(!Ue)throw new Y("当前 AI 助手不支持重新生成");it=Ue({threadId:Je.threadId,message:Ye,assistantMessage:{id:be.assistantMessage.id,content:be.assistantMessage.content},context:a,capabilities:gt},xt)}else it=R.run({threadId:Je.threadId,message:Ye,context:a,capabilities:gt},xt);const yt=it[Symbol.asyncIterator]();for(pe.current={iterator:yt,requestVersion:Se};;){const et=await yt.next();if(ee.current!==Se||et.done)break;let T;try{T=b.parseAssistantEvent(et.value)}catch(ue){throw new Y(ue instanceof Error?ue.message:"Invalid assistant event")}if(T.type==="message.start"){if(ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(ne??=T.runId,ht+=1,ht>b.MAKE_AI_CONVERSATION_LIMITS.assistantMessagesPerRun)throw new Y("AI 助手单次响应消息数量超过限制");if(vt.has(T.messageId))throw new Y("AI 助手响应包含重复的 message id");vt.add(T.messageId),ze.add(T.messageId),Be.set(T.messageId,0)}if(T.type==="message.delta"){if(!ze.has(T.messageId))throw new Y("AI 助手响应事件顺序无效");const ue=Be.get(T.messageId)??0,Ce=b.countCodePointsUpTo(T.delta,b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters-Pe);if(Pe+Ce>b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Y("AI 助手响应文本超过大小限制");Pe+=Ce,Be.set(T.messageId,ue+Ce)}if(T.type==="message.replace"){if(!ze.has(T.messageId))throw new Y("AI 助手响应事件顺序无效");const ue=Be.get(T.messageId)??0,Ce=b.countCodePointsUpTo(T.content,b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters),bt=Pe-ue+Ce;if(bt>b.MAKE_AI_CONVERSATION_LIMITS.messageCharacters)throw new Y("AI 助手响应文本超过大小限制");Pe=bt,Be.set(T.messageId,Ce)}if(T.type==="run.progress"){if(ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(ne??=T.runId,ft+=1,ft>b.MAKE_AI_CONVERSATION_LIMITS.progressStepsPerRun)throw new Y("AI 助手处理过程数量超过限制");const ue=b.countCodePointsUpTo(T.message,b.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun-rt);if(rt+ue>b.MAKE_AI_CONVERSATION_LIMITS.progressCharactersPerRun)throw new Y("AI 助手处理过程文本超过大小限制");rt+=ue}if(T.type==="artifact"){if(!ze.has(T.messageId))throw new Y("AI 助手响应事件顺序无效");if(mt+=1,mt>b.MAKE_AI_CONVERSATION_LIMITS.artifactsPerRun)throw new Y("AI 助手单次响应 Artifact 数量超过限制");if(pt.has(T.artifact.id))throw new Y("AI 助手响应包含重复的 Artifact id");pt.add(T.artifact.id)}if(T.type==="message.complete"&&!ze.delete(T.messageId))throw new Y("AI 助手响应事件顺序无效");if(T.type==="run.complete"&&ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(T.type==="run.cancelled"&&T.runId!==void 0&&ne!==void 0&&ne!==T.runId)throw new Y("AI 助手响应 run id 不一致");if(ae(ue=>b.reduceAssistantEvent(ue,T)),T.type==="error"||T.type==="run.cancelled"||T.type==="run.complete"){je=!0;break}}if(!je)throw new Y("AI 助手流式响应在终止事件前结束")}catch(je){if(ee.current!==Se)return;if(Qe.signal.aborted){ae(ne=>b.reduceAssistantEvent(ne,{type:"run.cancelled"}));return}console.error("[make-ai-assistant] assistant run failed",{appId:a.app.id,errorType:je instanceof Error?je.name:typeof je}),ae(ne=>b.reduceAssistantEvent(ne,{type:"error",code:"TRANSPORT_ERROR",message:je instanceof Y?je.message:"连接失败,请重试",retryable:!0}))}finally{ee.current===Se&&xe.current===Qe&&(xe.current=void 0),pe.current?.requestVersion===Se&&(Mt(pe.current.iterator),pe.current=void 0)}},u=m=>{if(g.enabled){if(N.pending)return $("请等待附件上传完成,或移除失败的附件"),Promise.resolve();const W=m.trim(),Z=N.parts.length?[...W?[{id:Le(),kind:"text",text:W}]:[],...N.parts]:void 0;return K(""),N.clear(),g.send(W,Z)}return r(m)},x=m=>r(m.userMessage.content,{regenerateFrom:m}),k=async(m,W)=>{try{await Es(W),P({messageId:m,message:"已复制",status:"success"})}catch(Z){console.error("[make-ai-assistant] copy answer failed",{errorType:Z instanceof Error?Z.name:typeof Z}),P({messageId:m,message:"复制失败",status:"error"})}},M=m=>{m.preventDefault(),u(_)},L=m=>{m.key==="Enter"&&!m.shiftKey&&!m.nativeEvent.isComposing&&(m.preventDefault(),u(_))},j=()=>{if(g.enabled){g.stop();return}Ne("stop")&&ae(m=>b.reduceAssistantEvent(m,{type:"run.cancelled"}))},H=()=>{if(U(!1),g.enabled){K(""),g.create(),d?.();return}Ne("new-conversation"),K(""),$(void 0),P(void 0),fe(!1),le.current=!0,ae(b.createAssistantConversationState()),d?.()},B=g.enabled&&g.cancelling.length?"停止中":R.features?.remoteCancellation===!1?"停止接收":"停止生成",z=Wt(O),ye=Vt(O),Re=Xs(O),Ge=typeof R.regenerate=="function"&&R.features?.regeneration!==!1,de=()=>{if(g.enabled){g.retry();return}Re&&u(Re.content)},Te=m=>{if(m.key==="Escape"&&!(!I&&!G)){if(m.preventDefault(),m.stopPropagation(),I){X(!1),Fe.current?.focus();return}U(!1),Ae.current?.focus()}};return e.jsxs("section",{className:`make-ai-assistant make-ai-assistant__panel${g.enabled?" make-ai-assistant__panel--managed":""}`,ref:_e,style:v,onKeyDown:Te,onDragOver:m=>{N.enabled&&m.dataTransfer.types.includes("Files")&&m.preventDefault()},onDrop:m=>{N.enabled&&m.dataTransfer.files.length&&(m.preventDefault(),N.add(Array.from(m.dataTransfer.files)))},children:[e.jsxs("header",{className:"make-ai-assistant__header",children:[e.jsx("div",{className:"make-ai-assistant__header-leading",children:g.enabled?e.jsxs("button",{"aria-controls":He,"aria-expanded":G,"aria-haspopup":"dialog","aria-label":"任务列表",className:"make-ai-assistant__task-list-trigger",ref:Ae,type:"button",onClick:()=>U(m=>!m),children:[e.jsx(Us,{}),e.jsx("span",{children:"任务列表"}),e.jsx(Ps,{})]}):null}),e.jsxs("div",{className:"make-ai-assistant__header-center",children:[e.jsx(st,{}),e.jsx("h2",{className:"make-ai-assistant__header-title",title:F,children:F})]}),e.jsxs("div",{className:"make-ai-assistant__header-actions",children:[R.features?.newConversation!==!1?e.jsx("button",{"aria-label":"新建对话",className:"make-ai-assistant__icon-button",type:"button",onClick:H,children:e.jsx(Fs,{})}):null,l?e.jsx("button",{"aria-label":`关闭 ${F}`,className:"make-ai-assistant__icon-button",type:"button",onClick:l,children:e.jsx(Ls,{})}):null]})]}),g.enabled&&G?e.jsx(ms,{id:He,manager:g,triggerRef:Ae,onDismiss:()=>U(!1),onNewConversation:R.features?.newConversation!==!1?H:void 0}):null,e.jsxs("div",{className:"make-ai-assistant__body","aria-live":"polite","aria-relevant":"additions text",ref:ve,role:"log",onScroll:nt,children:[Q==="loading"?e.jsxs("div",{className:"make-ai-assistant__empty",role:"status",children:[e.jsx(st,{}),e.jsx("h3",{children:"正在恢复对话"}),e.jsx("p",{children:"正在读取当前 App 的历史消息…"})]}):Q==="error"?e.jsx("div",{className:"make-ai-assistant__empty",children:e.jsx(Js,{error:oe,onRetry:()=>he(m=>m+1)})}):O.messages.length===0?e.jsxs("div",{className:"make-ai-assistant__empty",children:[e.jsx(st,{}),e.jsx("h3",{children:"有什么可以帮你?"}),e.jsx("p",{children:"我会结合当前 App、页面位置和宿主允许的上下文回答,并把过程与结果分开展示。"})]}):ea(O,a,Ze,S,i,o,t,Re?de:void 0,A,V,w,Ge,(m,W)=>{k(m,W)},m=>{x(m)},g.enabled?g:void 0,R),O.progress&&!z?e.jsx(St,{assistantName:t,progress:O.progress}):null,O.error&&!ye?e.jsx(St,{assistantName:t,error:O.error,onRetry:Re?de:void 0}):null]}),at?e.jsx("button",{"aria-label":"回到最新消息",className:"make-ai-assistant__back-to-latest",type:"button",onClick:Me,children:e.jsx(Os,{})}):null,e.jsxs("footer",{className:"make-ai-assistant__composer-region",children:[N.enabled?e.jsx(_s,{attachments:N}):null,Q==="ready"&&Xe.length>0&&O.messages.length===0?e.jsx("div",{className:"make-ai-assistant__suggestions","aria-label":"推荐问题",children:Xe.map((m,W)=>e.jsx("button",{type:"button",onClick:()=>{u(m)},children:m},`${W}-${m}`))}):null,e.jsxs("form",{className:"make-ai-assistant__composer",onSubmit:M,children:[e.jsx("textarea",{"aria-label":`向 ${t} 提问`,"aria-describedby":q?"make-ai-composer-error":void 0,"aria-invalid":q?!0:void 0,autoFocus:!0,disabled:Q!=="ready"||!g.enabled&&O.status==="streaming",placeholder:`询问当前 ${a.app.name??"App"} 中的数据…`,ref:Oe,rows:2,value:_,onChange:m=>{K(m.currentTarget.value),$(void 0)},onKeyDown:L,onPaste:m=>{N.enabled&&m.clipboardData.files.length&&(m.preventDefault(),N.add(Array.from(m.clipboardData.files)))}}),N.enabled?e.jsx(bs,{attachments:N,open:I,triggerRef:Fe,onOpenChange:X}):null,e.jsxs("div",{className:"make-ai-assistant__composer-actions",children:[O.status==="streaming"?e.jsx("button",{"aria-label":B,className:"make-ai-assistant__send make-ai-assistant__send--stop","data-tooltip":B,ref:We,disabled:g.enabled&&g.cancelling.includes(O.activeRunId??""),type:"button",onClick:j,children:e.jsx("span",{"aria-hidden":"true"})}):e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:Q!=="ready"||N.pending||!_.trim()&&!N.parts.length,type:"submit",children:e.jsx(Rt,{})}),g.enabled&&O.status==="streaming"?e.jsx("button",{"aria-label":"发送",className:"make-ai-assistant__send",disabled:g.busy||N.pending||!_.trim()&&!N.parts.length,type:"submit",children:e.jsx(Rt,{})}):null]})]}),q?e.jsx("p",{id:"make-ai-composer-error",role:"alert",children:q}):null,e.jsx("p",{children:"AI 生成的结果可能存在偏差,重要数据请核对明细。"})]})]})}function ta(t){return e.jsx(Zt,{...t,visible:!0})}function sa({defaultOpen:t=!1,hideLauncher:s=!1,launcher:a,launcherPosition:i="bottom-right",maxDrawerWidth:o,onOpenChange:l,open:d,...h}){const y=Ut(h.brandName,h.title),[p,C]=c.useState(t),[S,R]=c.useState(()=>t||d===!0),V=c.useRef(null),A=c.useRef(null),D=c.useRef(void 0),[g,N]=c.useState(),[F,f]=c.useState(As),[n,v]=c.useState(!1),_=d??p,K=dt(h.theme),I=Rs(o),X=()=>Ns(F,I,typeof window>"u"?Pt:window.innerWidth),G=X(),U=g===void 0?void 0:ot(g,F,G),J=U===void 0&&I===void 0?void 0:{...U===void 0?{}:{"--make-ai-internal-drawer-width":`${U}px`},...I===void 0?{}:{"--make-ai-internal-drawer-max-width":`max(var(--make-ai-internal-drawer-min-width), ${I}px)`}};c.useLayoutEffect(()=>{U!==void 0&&U!==g&&N(U)},[U,g]);const me=()=>{if(U!==void 0)return U;const w=A.current?.getBoundingClientRect().width;return w&&Number.isFinite(w)&&w>0?w:F},re=w=>{if(w.button!==0)return;const P=me(),te=g===void 0?P:F;f(te),D.current={minimumWidth:te,pointerId:w.pointerId,startWidth:P,startX:w.clientX},v(!0),typeof w.currentTarget.setPointerCapture=="function"&&w.currentTarget.setPointerCapture(w.pointerId),w.preventDefault()},O=w=>{const P=D.current;if(!P||P.pointerId!==w.pointerId)return;const te=ot(P.startWidth+P.startX-w.clientX,P.minimumWidth,X());N(te)},ae=w=>{const P=D.current;!P||P.pointerId!==w.pointerId||(D.current=void 0,v(!1))},ie=w=>{const P=w.key==="ArrowLeft"?At:w.key==="ArrowRight"?-At:void 0;if(P===void 0)return;w.preventDefault();const te=me(),he=g===void 0?te:F;f(he),N(ot(te+P,he,X()))},q=w=>{d===void 0&&C(w),l?.(w),w||requestAnimationFrame(()=>V.current?.focus())},$=()=>q(!_);return c.useEffect(()=>{_&&R(!0)},[_]),c.useEffect(()=>{if(!_)return;const w=P=>{P.key==="Escape"&&(q(!1),requestAnimationFrame(()=>V.current?.focus()))};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[l,_]),e.jsxs("div",{className:"make-ai-assistant","data-open":_||void 0,style:K,children:[!s&&(!_||a)?a?a({open:_,toggle:$}):e.jsxs("button",{"aria-label":_?`关闭 ${y}`:`打开 ${y}`,"aria-expanded":_,className:"make-ai-assistant__launcher","data-launcher-position":i,ref:V,type:"button",onClick:$,children:[e.jsx("span",{className:"make-ai-assistant__launcher-orbit","aria-hidden":"true"}),e.jsx(Bt,{})]}):null,S?e.jsxs("aside",{"aria-label":y,"aria-modal":"false",className:"make-ai-assistant__drawer","data-resizing":n||void 0,hidden:!_,ref:A,role:"dialog",style:J,children:[e.jsx("div",{"aria-label":"调整对话框宽度","aria-orientation":"vertical","aria-valuemax":G,"aria-valuemin":F,"aria-valuenow":U??F,className:"make-ai-assistant__drawer-resize-handle",role:"separator",tabIndex:0,onKeyDown:ie,onPointerCancel:ae,onPointerDown:re,onPointerMove:O,onPointerUp:ae}),e.jsx(Zt,{...h,onClose:()=>q(!1),visible:_})]}):null]})}exports.createArtifactCapabilities=Ie.createArtifactCapabilities;exports.createArtifactTemplateRegistry=Ie.createArtifactTemplateRegistry;exports.extendArtifactTemplateRegistry=Ie.extendArtifactTemplateRegistry;exports.resolveArtifactTemplate=Ie.resolveArtifactTemplate;exports.MAKE_AI_ARTIFACT_KINDS=b.MAKE_AI_ARTIFACT_KINDS;exports.MAKE_AI_ARTIFACT_LIMITS=b.MAKE_AI_ARTIFACT_LIMITS;exports.MAKE_AI_ARTIFACT_SCHEMA_VERSION=b.MAKE_AI_ARTIFACT_SCHEMA_VERSION;exports.MAKE_AI_CONVERSATION_LIMITS=b.MAKE_AI_CONVERSATION_LIMITS;exports.appendUserMessage=b.appendUserMessage;exports.createAssistantConversationState=b.createAssistantConversationState;exports.parseArtifact=b.parseArtifact;exports.parseAssistantEvent=b.parseAssistantEvent;exports.reduceAssistantEvent=b.reduceAssistantEvent;exports.validateArtifact=b.validateArtifact;exports.ArtifactRenderer=Et;exports.AssistantPanel=ta;exports.MakeAiAssistant=sa;exports.createPlatformArtifactRegistry=Ot;exports.formatArtifactValue=ke;exports.platformArtifactTemplates=Dt;
|