dsh-gpt-image-playground 0.2.2 → 0.2.3
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/README.md +1 -1
- package/THIRD-PARTY-NOTICES.md +5 -2
- package/package.json +2 -2
- package/vendor-app/announcements.json +1 -1
- package/vendor-app/assets/App-BNIPBgoM.js +197 -0
- package/vendor-app/assets/{index-yY_cAGHl.js → index-B7YZ4edk.js} +1 -1
- package/vendor-app/assets/{index-CbdCkTIj.js → index-BBj85vBi.js} +1 -1
- package/vendor-app/assets/{index-DsvpNQKY.js → index-eWsk1PG_.js} +1 -1
- package/vendor-app/assets/index-keImJbNS.css +1 -0
- package/vendor-app/assets/{mermaid-GHXKKRXX-ZwJVxNkk.js → mermaid-GHXKKRXX-Dxz-gSLM.js} +3 -3
- package/vendor-app/index.html +2 -2
- package/vendor-app/sw.js +1 -1
- package/vendor-app/assets/App-q7a4rxqa.js +0 -197
- package/vendor-app/assets/index-TVJv2SDW.css +0 -1
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./harmonyos-sans-sc-78ty70VX.css","./maple-mono-nf-cn-CkIt5zzM.css","./index-BBj85vBi.js","./index-DNpwxtJ4.js","./index-B7YZ4edk.js","./index-keImJbNS.css","./index-eWsk1PG_.js","./index-DNljbSyS.js","./index-BEECAir2.js","./index-BugPYPDb.js","./index-CtXnX3Xp.js","./mermaid-GHXKKRXX-Dxz-gSLM.js","./index-CsiGg4nI.js","./index-PLZKjL94.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Mv=Object.defineProperty;var Ev=(e,t,r)=>t in e?Mv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ze=(e,t,r)=>Ev(e,typeof t!="symbol"?t+"":t,r);import{R as pl,i as De,_ as aa,d as Rv,a as Bh,b as oa,t as _v,c as Dv,e as Dr,F as Lc,f as of,h as Uh,p as Lv,k as Jg,l as Ov,m as Bv,n as Nt,o as Uv,q as lf,r as p,s as Fv,u as Fh,v as $v,j as s,T as cf,w as _o,x as zv,y as df,z as $h,A as Wv,B as Hv,C as Yv,D as Vv,E as Kv,G as Xv,H as qv,I as Jv,J as Gg,K as Gv,L as Zv,M as Qv}from"./index-B7YZ4edk.js";const Zg=e=>{let t;const r=new Set,n=(u,f)=>{const d=typeof u=="function"?u(t):u;if(!Object.is(d,t)){const g=t;t=f??(typeof d!="object"||d===null)?d:Object.assign({},t,d),r.forEach(m=>m(t,g))}},a=()=>t,l={setState:n,getState:a,getInitialState:()=>c,subscribe:u=>(r.add(u),()=>r.delete(u))},c=t=e(n,a,l);return l},ew=(e=>e?Zg(e):Zg),tw=e=>e;function rw(e,t=tw){const r=pl.useSyncExternalStore(e.subscribe,pl.useCallback(()=>t(e.getState()),[e,t]),pl.useCallback(()=>t(e.getInitialState()),[e,t]));return pl.useDebugValue(r),r}const Qg=e=>{const t=ew(e),r=n=>rw(t,n);return Object.assign(r,t),r},Mi=(e=>e?Qg(e):Qg);function zh(e,t){let r;try{r=e()}catch{return}return{getItem:a=>{var o;const i=c=>c===null?null:JSON.parse(c,void 0),l=(o=r.getItem(a))!=null?o:null;return l instanceof Promise?l.then(i):i(l)},setItem:(a,o)=>r.setItem(a,JSON.stringify(o,void 0)),removeItem:a=>r.removeItem(a)}}const xu=e=>t=>{try{const r=e(t);return r instanceof Promise?r:{then(n){return xu(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return xu(n)(r)}}}},nw=(e,t)=>(r,n,a)=>{let o={storage:zh(()=>window.localStorage),partialize:h=>h,version:0,merge:(h,y)=>({...y,...h}),...t},i=!1,l=0;const c=new Set,u=new Set;let f=o.storage;if(!f)return e((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),r(...h)},n,a);const d=()=>{const h=o.partialize({...n()});return f.setItem(o.name,{state:h,version:o.version})},g=a.setState;a.setState=(h,y)=>(g(h,y),d());const m=e((...h)=>(r(...h),d()),n,a);a.getInitialState=()=>m;let x;const b=()=>{var h,y;if(!f)return;const v=++l;i=!1,c.forEach(S=>{var k;return S((k=n())!=null?k:m)});const I=((y=o.onRehydrateStorage)==null?void 0:y.call(o,(h=n())!=null?h:m))||void 0;return xu(f.getItem.bind(f))(o.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==o.version){if(o.migrate){const k=o.migrate(S.state,S.version);return k instanceof Promise?k.then(j=>[!0,j]):[!0,k]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var k;if(v!==l)return;const[j,A]=S;if(x=o.merge(A,(k=n())!=null?k:m),r(x,!0),j)return d()}).then(()=>{v===l&&(I==null||I(n(),void 0),x=n(),i=!0,u.forEach(S=>S(x)))}).catch(S=>{v===l&&(I==null||I(void 0,S))})};return a.persist={setOptions:h=>{o={...o,...h},h.storage&&(f=h.storage)},clearStorage:()=>{f==null||f.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>b(),hasHydrated:()=>i,onHydrate:h=>(c.add(h),()=>{c.delete(h)}),onFinishHydration:h=>(u.add(h),()=>{u.delete(h)})},o.skipHydration||b(),x||m},sw=nw,Wh=["none","minimal","low","medium","high","xhigh","max"],aw=["task-selection","favorite-collection-selection","image-context-menu-all","task-detail-all","task-detail-partial","agent-round-all"],Hh=["task-selection","favorite-collection-selection"],kr=1,Jn=15,yr=16,Qr={size:"auto",quality:"auto",output_format:"png",output_compression:null,moderation:"auto",n:1,transparent_output:!1};function Xl(e){return e==="$params.background"?!0:Array.isArray(e)?e.some(Xl):!e||typeof e!="object"?!1:Object.values(e).some(Xl)}function em(e){return Xl(e.body)||Xl(e.query)}function Ei(e){return em(e.submit)?!e.editSubmit||em(e.editSubmit):!1}function mr(e){return String.prototype.trim.call(e??"")}const ow="/api-proxy";function Tn(e){const t=e.trim();if(!t)return"";const r=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//.test(t)?t:`https://${t}`;try{const n=new URL(r);if(t.endsWith("/"))return`${n.origin}${n.pathname.replace(/\/+$/,"/")}`;const a=n.pathname.split("/").filter(Boolean),o=a.indexOf("v1"),i=o>=0?a.slice(0,o+1):a.length?[...a,"v1"]:[],l=i.length?`/${i.join("/")}`:"";return`${n.origin}${l}`}catch{return t.replace(/\/+$/,"")}}function ps(e,t,r,n=!1){const a=e.trim(),o=t.replace(/^\/+/,"");if(n)return`${(r==null?void 0:r.prefix)??ow}/${o}`;const i=Tn(a);if(a.endsWith("/"))return`${i.replace(/\/+$/,"")}/${o}`;const l=i.endsWith("/v1")?o:["v1",o].join("/");return i?`${i}/${l}`:`/${l}`}function iw(e,t){return null}function sn(){return iw()}function Oc(e=sn()){return De?!1:mr(void 0)==="true"||!!(e!=null&&e.enabled)}function uf(e=sn()){return mr(void 0)==="true"&&Oc(e)}function ha(e,t=sn()){return Oc(t)&&(e||uf(t))}function Yr(e,t=kr){const r=t??kr,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?Math.min(3,Math.max(0,Math.trunc(n))):r}function ia(e,t){return typeof e=="string"&&Wh.includes(e)?e:t}function lw(e){const t=e.trim();if(!t)return{baseUrl:""};try{const r=new URL(t),n=t.search(/[?#]/),a=n>=0?t.slice(0,n):t,o={baseUrl:Tn(a)},i=r.searchParams.get("apiUrl"),l=r.searchParams.get("apiKey"),c=r.searchParams.get("apiMode"),u=r.searchParams.get("model"),f=r.searchParams.get("imageGenerationModel"),d=r.searchParams.get("reasoningEffort"),g=r.searchParams.get("profileName"),m=r.searchParams.get("codexCli"),x=r.searchParams.get("streamImages"),b=r.searchParams.get("streamPartialImages"),h=r.searchParams.get("transparentBackgroundMethod");return i!==null&&(o.baseUrl=Tn(i.trim())),l!==null&&(o.apiKey=l.trim()),(c==="images"||c==="responses")&&(o.apiMode=c),u!==null&&u.trim()&&(o.model=u.trim()),f!==null&&(o.imageGenerationModel=f.trim()),d!==null&&(o.reasoningEffort=ia(d)),g!=null&&g.trim()&&(o.name=g.trim()),m!==null&&(o.codexCli=m.trim().toLowerCase()==="true"),x!==null&&(o.streamImages=x.trim().toLowerCase()==="true"),b!==null&&(o.streamPartialImages=Yr(b)),(h==="api"||h==="local")&&(o.transparentBackgroundMethod=h),o}catch{return{baseUrl:Tn(t)}}}const ql="embedded-config:";function cw(e){const t=e.trim();if(!t)return!1;if(t.startsWith(ql))return!0;try{const r=new URL(t);return r.searchParams.has("settings")||r.pathname.toLowerCase().endsWith(".json")}catch{return!1}}const ir="gpt-image-2.5-sunburst";function Ri(e){var t;return e.provider==="openai"&&e.apiMode==="responses"?((t=e.imageGenerationModel)==null?void 0:t.trim())??"":e.model}function ff(e){return e.trim().toLowerCase().includes("gpt-image-2.5")}const Jl=10;function Yh(e){return e.split(/\r?\n[ \t]*\r?\n[ \t]*\r?\n/).map(t=>t.trim()).filter(Boolean)}function Vh(e){return typeof e!="number"||!Number.isFinite(e)?Jl:Math.max(1,Math.round(e))}async function dw(e,t,r,n=()=>!1){let a=0;const o=Array.from({length:Math.min(t,e.length)},async()=>{for(;a<e.length&&!n();){const i=a;a+=1,await r(e[i],i)}});await Promise.all(o)}const uw=["default","builtin","system","custom"],fw=mr("").toLowerCase()==="local"?"local":"cdn",gf={ui:{family:"HarmonyOS Sans SC",fallback:"'Noto Sans SC', 'PingFang SC', 'Microsoft YaHei', sans-serif",cssVar:"--font-ui-sans",cdnCss:"https://cdn.jsdelivr.net/npm/@lobehub/webfont-harmony-sans-sc@1.0.0/css/index.css",deployValue:mr(""),loadLocal:()=>aa(()=>Promise.resolve({}),__vite__mapDeps([0]),import.meta.url)},mono:{family:"Maple Mono NF CN",fallback:"'Cascadia Code', 'SF Mono', Menlo, Consolas, monospace",cssVar:"--font-mono",cdnCss:"https://fontsapi.zeoseven.com/442/main/result.css",deployValue:mr(""),loadLocal:()=>aa(()=>Promise.resolve({}),__vite__mapDeps([1]),import.meta.url)}};function tm(e){return uw.includes(e)?e:"default"}function gw(e){const t=e.trim(),r=t.toLowerCase();return!t||r==="builtin"?{source:"builtin"}:r==="system"?{source:"system"}:{source:"custom",name:t}}function Kh(e,t,r){return e==="default"?gw(r):e!=="custom"?{source:e}:t.trim()?{source:"custom",name:t.trim()}:{source:"system"}}function Gl(e,t,r){return Kh(t,r,gf[e].deployValue)}function mw(e){return`"${e.replace(/["\\]/g,"\\$&")}"`}function bu(e,t){const r=gf[e];return t.source==="system"?r.fallback:`${mw(t.source==="custom"?t.name:r.family)}, ${r.fallback}`}function rm(e,t,r=fw){const n=gf[e],a=`cdn-font-${e}`,o=document.getElementById(a),i=t.source==="builtin"&&r==="cdn";if(i||o==null||o.remove(),i&&!o){const l=document.createElement("link");l.id=a,l.rel="stylesheet",l.href=n.cdnCss,document.head.appendChild(l)}t.source==="builtin"&&r==="local"&&n.loadLocal().catch(l=>console.error("本地字体加载失败:",l)),document.documentElement.style.setProperty(n.cssVar,bu(e,t))}function nm(e){return e.source==="custom"?e.name:e.source==="builtin"?"内置字体":"系统字体"}const mf="Ctrl+Shift+H",hw={ctrl:"Ctrl",control:"Ctrl",alt:"Alt",option:"Alt",shift:"Shift",meta:"Meta",cmd:"Meta",command:"Meta",win:"Meta"},pw=new Set(["Control","Alt","AltGraph","Shift","Meta","OS","Dead","Unidentified","Process"]),xw=/^F([1-9]|1[0-2])$/;function bw(e,t=""){var a,o;if(e===" ")return"Space";if(e.length!==1)return e;const r=e.toUpperCase();return/^[A-Z0-9]$/.test(r)?r:((a=/^Key([A-Z])$/.exec(t))==null?void 0:a[1])??((o=/^Digit([0-9])$/.exec(t))==null?void 0:o[1])??r}function hf(e){var n;if(!e.key||pw.has(e.key)||(n=e.getModifierState)!=null&&n.call(e,"AltGraph"))return null;const t=bw(e.key,e.code);return!e.ctrlKey&&!e.altKey&&!e.metaKey&&!xw.test(t)?null:[...[e.ctrlKey&&"Ctrl",e.altKey&&"Alt",e.shiftKey&&"Shift",e.metaKey&&"Meta"].filter(Boolean),t].join("+")}function Xh(e){var o;const t=e.trim(),r=t.endsWith("++")?[...t.slice(0,-2).split("+"),"+"]:t.split("+"),n=(o=r.pop())==null?void 0:o.trim();if(!n)return null;const a=new Set;for(const i of r){const l=hw[i.trim().toLowerCase()];if(!l)return null;a.add(l)}return{key:n.length===1?n:n.toLowerCase()==="space"?" ":n.replace(/^f(\d+)$/i,"F$1"),ctrlKey:a.has("Ctrl"),altKey:a.has("Alt"),shiftKey:a.has("Shift"),metaKey:a.has("Meta")}}function yw(e){if(!e.trim())return"";const t=Xh(e);return t?hf(t):null}function vw(e,t){return typeof e!="string"?t:yw(e)??t}function ww(e,t){const r=Xh(e);return r?[r.ctrlKey&&"Ctrl",r.altKey&&(t?"⌥":"Alt"),r.shiftKey&&"Shift",r.metaKey&&(t?"⌘":"Win"),r.key===" "?"Space":r.key].filter(Boolean).join(" + "):e}const kw="https://api.openai.com/v1",yu=mr("embedded-config:ewogICJjdXN0b21Qcm92aWRlcnMiOiBbCiAgICB7CiAgICAgICJpZCI6ICJjdXN0b20tYXBpbWFydCIsCiAgICAgICJuYW1lIjogIkFQSU1hcnQiLAogICAgICAic3VibWl0IjogewogICAgICAgICJwYXRoIjogImltYWdlcy9nZW5lcmF0aW9ucyIsCiAgICAgICAgIm1ldGhvZCI6ICJQT1NUIiwKICAgICAgICAiY29udGVudFR5cGUiOiAianNvbiIsCiAgICAgICAgImJvZHkiOiB7CiAgICAgICAgICAibW9kZWwiOiAiJHByb2ZpbGUubW9kZWwiLAogICAgICAgICAgInByb21wdCI6ICIkcHJvbXB0IiwKICAgICAgICAgICJzaXplIjogIiRwYXJhbXMuc2l6ZSIsCiAgICAgICAgICAicXVhbGl0eSI6ICIkcGFyYW1zLnF1YWxpdHkiLAogICAgICAgICAgIm91dHB1dF9mb3JtYXQiOiAiJHBhcmFtcy5vdXRwdXRfZm9ybWF0IiwKICAgICAgICAgICJvdXRwdXRfY29tcHJlc3Npb24iOiAiJHBhcmFtcy5vdXRwdXRfY29tcHJlc3Npb24iLAogICAgICAgICAgIm1vZGVyYXRpb24iOiAiJHBhcmFtcy5tb2RlcmF0aW9uIiwKICAgICAgICAgICJuIjogIiRwYXJhbXMubiIsCiAgICAgICAgICAiYmFja2dyb3VuZCI6ICIkcGFyYW1zLmJhY2tncm91bmQiLAogICAgICAgICAgImltYWdlX3VybHMiOiAiJGlucHV0SW1hZ2VzLmRhdGFVcmxzIiwKICAgICAgICAgICJtYXNrX3VybCI6ICIkbWFzay5kYXRhVXJsIgogICAgICAgIH0sCiAgICAgICAgInRhc2tJZFBhdGgiOiAiZGF0YS4wLnRhc2tfaWQiCiAgICAgIH0sCiAgICAgICJwb2xsIjogewogICAgICAgICJwYXRoIjogInRhc2tzL3t0YXNrX2lkfSIsCiAgICAgICAgIm1ldGhvZCI6ICJHRVQiLAogICAgICAgICJpbnRlcnZhbFNlY29uZHMiOiA1LAogICAgICAgICJzdGF0dXNQYXRoIjogImRhdGEuc3RhdHVzIiwKICAgICAgICAic3VjY2Vzc1ZhbHVlcyI6IFsiY29tcGxldGVkIl0sCiAgICAgICAgImZhaWx1cmVWYWx1ZXMiOiBbImZhaWxlZCJdLAogICAgICAgICJlcnJvclBhdGgiOiAiZGF0YS5lcnJvci5tZXNzYWdlIiwKICAgICAgICAicmVzdWx0IjogewogICAgICAgICAgImltYWdlVXJsUGF0aHMiOiBbImRhdGEucmVzdWx0LmltYWdlcy4qLnVybC4qIl0sCiAgICAgICAgICAiYjY0SnNvblBhdGhzIjogW10KICAgICAgICB9CiAgICAgIH0KICAgIH0KICBdLAogICJwcm9maWxlcyI6IFsKICAgIHsKICAgICAgImlkIjogImdwdF9pbWFnZV9wbGF5Z3JvdW5kLWRlZmF1bHQtb3BlbmFpIiwKICAgICAgIm5hbWUiOiAi6buY6K6kIiwKICAgICAgInByb3ZpZGVyIjogIm9wZW5haSIsCiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vYXBpLm9wZW5haS5jb20vdjEiLAogICAgICAibW9kZWwiOiAiZ3B0LWltYWdlLTIuNS1zdW5idXJzdCIsCiAgICAgICJhcGlNb2RlIjogImltYWdlcyIsCiAgICAgICJpc0RlZmF1bHQiOiB0cnVlCiAgICB9LAogICAgewogICAgICAiaWQiOiAiYXBpbWFydCIsCiAgICAgICJuYW1lIjogIkFQSU1hcnQiLAogICAgICAiZGVzY3JpcHRpb24iOiAiW0FQSU1hcnRdKGh0dHBzOi8vZ28uYXBpbWFydC5haS9naC1ncHRfaW1hZ2VfcGxheWdyb3VuZCkg5piv5LiT5rOoIEFJIOWbvueJhy/op4bpopHnlJ/miJDnmoTkvY7ku7cgQVBJIOW5s+WPsO+8jEdQVC1JbWFnZS0yIOS9juiHsyAkMC4wMDYv5byg77yMMSDnvo7lhYPlj6/lh7rlm74gMTYwKyDlvKDjgILlm77niYfjgIHop4bpopHkuIDlpZflvILmraUgQVBJIOmAmuWQg++8jOaPkOS6pOS7u+WKoeaLvyBJROOAgeWbnuiwg+WPlue7k+aenO+8jOi3keaJueS4h+W8oOS4jei2heaXtuOAgeaNouaooeWei+S4jeaUueS7o+eggeOAguaMiemHj+S7mOi0ueOAgeaXoOaciOi0ue+8jOmAmui/h1vmraTms6jlhozpk77mjqVdKGh0dHBzOi8vZ28uYXBpbWFydC5haS9naC1ncHRfaW1hZ2VfcGxheWdyb3VuZCnms6jlhozljbPlj6/lvIDnlKjjgIIiLAogICAgICAicHJvdmlkZXIiOiAiY3VzdG9tLWFwaW1hcnQiLAogICAgICAiYmFzZVVybCI6ICJodHRwczovL2FwaS5hcGltYXJ0LmFpL3YxIiwKICAgICAgIm1vZGVsIjogImdwdC1pbWFnZS0yIiwKICAgICAgImFwaU1vZGUiOiAiaW1hZ2VzIgogICAgfSwKICAgIHsKICAgICAgImlkIjogIm1veXV1LWFpIiwKICAgICAgIm5hbWUiOiAi5pG46bG8IEFJIiwKICAgICAgImRlc2NyaXB0aW9uIjogIlvmkbjpsbwgQUldKGh0dHBzOi8vbW95dXUuY2MvcmVnaXN0ZXI/YWZmPXo5NXIp77yM6K6pIEFJIEFQSSDmjqXlhaXmm7TnroDljZXjgILmmI7noIHmoIfku7fvvIzlhYXlgLwgMTox77yM5pSv5oyBIEdQVOOAgUNsYXVkZeOAgUdlbWluaSDnrYnkuLvmtYHmqKHlnovvvIzph43mlrDlrprkuYnjgIzkvr/lrpwgwrcg56iz5a6aIMK3IOmrmOmAn+OAjSIsCiAgICAgICJwcm92aWRlciI6ICJvcGVuYWkiLAogICAgICAiYmFzZVVybCI6ICJodHRwczovL2xvbmcubW95dXUuY2MvdjEiLAogICAgICAibW9kZWwiOiAiZ3B0LWltYWdlLTIiLAogICAgICAiYXBpTW9kZSI6ICJpbWFnZXMiCiAgICB9LAogICAgewogICAgICAiaWQiOiAianVjb2RleCIsCiAgICAgICJuYW1lIjogIkp1Q29kZXgiLAogICAgICAiZGVzY3JpcHRpb24iOiAiW0p1Q29kZXhdKGh0dHBzOi8vanVjb2RleC5jb20vcmVnaXN0ZXI/YWZmPTNKRFcpIOS4uuS8geS4mue6p+eUqOaIt+aJk+mAoOeahOmrmOWPr+eUqOOAgeS9juW7tui/n+OAgeaegeiHtOaAp+S7t+avlOeahOS4rei9rOerme+8jOaPkOS+myBDb2RleOOAgUNsYXVkZSBDb2Rl44CBR3JvayDnrYnkuLvmtYHlpKfmqKHlnovkuK3ovazmnI3liqHvvIzmlrDnlKjmiLfms6jlhozpgIEgMyDlhYPvvIhRUSDpgq7nrrHvvInvvIzmsLjkuYXmib/or7ogMCDmsLQgMCDmm7/jgIHmqKHlnosgMTAwJSDkv53nnJ/jgIJb55Sf5Zu+5bel5L2c5Y+wXShodHRwczovL2ltYWdlLmp1Y29kZXguY29tKSIsCiAgICAgICJwcm92aWRlciI6ICJvcGVuYWkiLAogICAgICAiYmFzZVVybCI6ICJodHRwczovL2FwaS5zei1saW5rLmNvbS92MSIsCiAgICAgICJtb2RlbCI6ICJncHQtaW1hZ2UtMi41LXN1bmJ1cnN0IiwKICAgICAgImFwaU1vZGUiOiAiaW1hZ2VzIgogICAgfSwKICAgIHsKICAgICAgImlkIjogIm1hcnVjb2RlIiwKICAgICAgIm5hbWUiOiAiTWFydUNvZGUiLAogICAgICAiZGVzY3JpcHRpb24iOiAiW01hcnVDb2RlXShodHRwczovL2FwaS5tdXRla2kuc2l0ZS9yZWdpc3Rlcj9hZmY9Q29va1NsZWVwJnByb21vPUNvb2tTbGVlcCkg5piv5LiA5a625YG25bCU5YGa5YGa5oWI5ZaE55qE5bCP56C056uZIEFQSe+8jOiHquiQpeWPt+axoO+8jOS4u+imgeaPkOS+myBPcGVuQUnjgIFBbnRocm9waWPjgIFHUFQgSW1hZ2Ug562J5Li75rWB5qih5Z6L77yM5pSv5oyBIFdlYnNvY2tldCDljY/orq7vvIzmmI7noIHmoIfku7coT0FJIDAuM3gsIEHDtyAxLjd4Ke+8jOmAj+aYjuaxh+eOhygxOjEp77yMW+aWsOeUqOaIt+azqOWGjOmAgSAxIOWIgF0oaHR0cHM6Ly9hcGkubXV0ZWtpLnNpdGUvcmVnaXN0ZXI/YWZmPUNvb2tTbGVlcCZwcm9tbz1Db29rU2xlZXAp44CCW+eUn+WbvuW3peS9nOWPsPCflrzvuI9dKGh0dHBzOi8vaW1hZ2VzLTIubXV0ZWtpLnNpdGUpIiwKICAgICAgInByb3ZpZGVyIjogIm9wZW5haSIsCiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vYXBpLm11dGVraS5zaXRlIiwKICAgICAgIm1vZGVsIjogImdwdC1pbWFnZS0yLjUtc3VuYnVyc3QiLAogICAgICAiYXBpTW9kZSI6ICJpbWFnZXMiLAogICAgICAidHJhbnNwYXJlbnRCYWNrZ3JvdW5kTWV0aG9kIjogImxvY2FsIgogICAgfSwKICAgIHsKICAgICAgImlkIjogInN1Ymx5eCIsCiAgICAgICJuYW1lIjogIlN1Ymx5eCIsCiAgICAgICJkZXNjcmlwdGlvbiI6ICJbU3VibHl4XShodHRwczovL2FwaS5zdWJseXgub3JnL3JlZ2lzdGVyP2FmZj1VNjJQQVpFUkNIRUEpIOaYr+S4gOWutueos+WumumrmOaViOeahCBBSSBBUEkg6IGa5ZCI572R5YWz77yM5pSv5oyBIE9wZW5BSeOAgUNsYXVkZeOAgUdyb2vjgIFDb2RleOOAgWdwdC1pbWFnZS0yIOetieS4u+a1geaooeWei++8jOWFvOWuuSBPcGVuQUkgU0RL44CBQ2xhdWRlIENvZGXjgIFDb2RleOOAgUNoZXJyeSBTdHVkaW8g562J5bi455So5bel5YW344CC6YCa6L+HW+mTvuaOpeazqOWGjF0oaHR0cHM6Ly9hcGkuc3VibHl4Lm9yZy9yZWdpc3Rlcj9hZmY9VTYyUEFaRVJDSEVBKeW5tuS9v+eUqOS8mOaDoOeggSBgSU1HMmDvvIzlj6/pop3lpJbpooblj5YgMTAg5YiA6aKd5bqm44CCW+eUn+WbvuW3peS9nOWPsF0oaHR0cHM6Ly9pbWcyLmljZWRpdC5haSkiLAogICAgICAicHJvdmlkZXIiOiAic2IyYXBpLWFzeW5jIiwKICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly9hcGkuc3VibHl4Lm9yZy92MSIsCiAgICAgICJtb2RlbCI6ICJncHQtaW1hZ2UyLjUtZmxhcmUiLAogICAgICAiYXBpTW9kZSI6ICJpbWFnZXMiCiAgICB9CiAgXQp9Cg=="),pa=mr(void 0)==="true",Iw=mr(void 0)==="true",ze=cw(yu)?null:lw(yu||(Iw&&pa?"":kw)),Qs=(ze==null?void 0:ze.baseUrl)??"",Wa="gpt-6.1-sol",Gn="https://fal.run",_i="openai/gpt-image-2",pf="default-openai",Di=600,ao=new Set(["openai","sb2api-async","fal"]),La={generationPath:"images/generations",editPath:"images/edits",taskPath:"images/tasks/{task_id}"},Li={model:"$profile.model",prompt:"$prompt",size:"$params.size",quality:"$params.quality",output_format:"$params.output_format",moderation:"$params.moderation",output_compression:"$params.output_compression",n:"$params.n",background:"$params.background"},Bc=Li,la={imageUrlPaths:["data.*.url"],b64JsonPaths:["data.*.b64_json"]},xf=[{field:"image[]",source:"inputImages",array:!0},{field:"mask",source:"mask"}],qh={id:"sb2api-async",name:"sub2api(异步)",template:"http-image",submit:{path:"images/generations/async",method:"POST",contentType:"json",body:Li,taskIdPath:"task_id"},editSubmit:{path:"images/edits/async",method:"POST",contentType:"multipart",body:Bc,files:xf,taskIdPath:"task_id"},poll:{path:"images/tasks/{task_id}",method:"GET",intervalSeconds:3,statusPath:"status",successValues:["completed"],failureValues:["failed"],errorPath:"error.message",result:{imageUrlPaths:["result.data.*.url"],b64JsonPaths:["result.data.*.b64_json"]}}};function bf(e,t){return e==="openai"&&t==="responses"}function Zl(e,t=Jn){const r=t??Jn,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?Math.min(50,Math.max(1,Math.trunc(n))):r}function Cw(){return!!yu||pa}function Uc(e){const t=Wt(e)?e:{},n=(Array.isArray(t.profiles)?t.profiles.filter(Wt):[]).find(a=>a.isDefault===!0&&typeof a.id=="string");return n&&typeof n.id=="string"?n.id:null}function jw(e){return e==="sketch"||e==="mask"?e:"ask"}function Sw(e,t){return e==="overwriteAll"?t?e:"overwriteFailed":e==="overwriteFailed"?e:"new"}function Nw(e){if(!Array.isArray(e))return[...Hh];const t=new Set(aw);return e.filter(r=>typeof r=="string"&&t.has(r))}function Aw(e,t){if(!Array.isArray(e))return;const r=["openai","sb2api-async","fal",...t.map(o=>o.id)],n=new Set(r),a=e.map(String).filter((o,i,l)=>n.has(o)&&l.indexOf(o)===i);return[...a,...r.filter(o=>!a.includes(o))]}function Pw(e){return e==="native"||e==="hybrid"?e:"off"}function Oa(e){return e.provider==="openai"&&e.apiMode==="responses"}function Tw(e){return e==="http-image"}function Jh(e,t){return(typeof e=="string"&&e.trim()?e:t).trim().replace(/^\/+/,"").replace(/^v1\//,"")}function Ql(e){if(!e||typeof e!="object")return;const t=Object.entries(e).filter(r=>typeof r[0]=="string"&&["string","number","boolean"].includes(typeof r[1])).map(([r,n])=>[r,String(n)]);return t.length?Object.fromEntries(t):void 0}function Ha(e,t){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&!!r.trim()).map(r=>r.trim()):t}function Wt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Gh(e,t="POST"){return e==="GET"||e==="POST"?e:t}function Mw(e,t="json"){return e==="multipart"?"multipart":t}function Ew(e,t){return Wt(e)?e:t}function Rw(e,t=[]){if(!Array.isArray(e))return t;const r=e.map(n=>!Wt(n)||typeof n.field!="string"||!n.field.trim()||n.source!=="inputImages"&&n.source!=="mask"?null:{field:n.field.trim(),source:n.source,array:!!n.array}).filter(n=>!!n);return r.length?r:t}function Zh(e,t=la){const r=Wt(e)?e:{},n=Ha(r.imageUrlPaths,t.imageUrlPaths??[]),a=Ha(r.b64JsonPaths,t.b64JsonPaths??[]);return{imageUrlPaths:n,b64JsonPaths:a}}function sm(e,t){const r=Wt(e)?e:{},n=Mw(r.contentType,t.contentType??"json");return{path:Jh(r.path,t.path),method:Gh(r.method,t.method??"POST"),contentType:n,query:Ql(r.query)??t.query,body:Ew(r.body,t.body??(n==="multipart"?Bc:Li)),files:n==="multipart"?Rw(r.files,t.files):void 0,taskIdPath:typeof r.taskIdPath=="string"&&r.taskIdPath.trim()?r.taskIdPath.trim():t.taskIdPath,result:Zh(r.result,t.result??la)}}function _w(e,t){if(!Wt(e)&&!t)return;const r=Wt(e)?e:{},n=Jh(r.path,La.taskPath),a=typeof r.statusPath=="string"&&r.statusPath.trim()?r.statusPath.trim():t==null?void 0:t.statusPath;if(a)return{path:n,method:Gh(r.method,"GET"),query:Ql(r.query)??(t==null?void 0:t.query),intervalSeconds:typeof r.intervalSeconds=="number"&&Number.isFinite(r.intervalSeconds)?Math.max(1,r.intervalSeconds):(t==null?void 0:t.intervalSeconds)??5,statusPath:a,successValues:Ha(r.successValues,["SUCCESS","succeeded","completed","COMPLETED"]),failureValues:Ha(r.failureValues,["FAILURE","failed","error","FAILED","cancelled"]),errorPath:typeof r.errorPath=="string"&&r.errorPath.trim()?r.errorPath.trim():t==null?void 0:t.errorPath,result:Zh(r.result,la)}}function Dw(e){if(e.template!=="openai-compatible"&&e.template!=="openai-compatible-async")return null;const t=e.template==="openai-compatible-async",r=typeof e.taskResultPath=="string"&&e.taskResultPath.trim()?e.taskResultPath.trim():"data.data";return{id:e.id,name:e.name,template:"http-image",submit:{path:e.generationPath??La.generationPath,method:"POST",contentType:"json",query:t?Ql(e.submitQuery)??{async:"true"}:void 0,body:Li,taskIdPath:t?e.taskIdPath??"data":void 0,result:la},editSubmit:{path:e.editPath??La.editPath,method:"POST",contentType:"multipart",query:t?Ql(e.submitQuery)??{async:"true"}:void 0,body:Bc,files:xf,taskIdPath:t?e.taskIdPath??"data":void 0,result:la},poll:t?{path:e.taskPath??La.taskPath,method:"GET",statusPath:e.taskStatusPath??"data.status",successValues:Ha(e.taskSuccessValues,["SUCCESS","succeeded","completed","COMPLETED"]),failureValues:Ha(e.taskFailureValues,["FAILURE","failed","error","FAILED"]),errorPath:"data.fail_reason",intervalSeconds:typeof e.pollIntervalSeconds=="number"?e.pollIntervalSeconds:5,result:{imageUrlPaths:[`${r}.data.*.url`],b64JsonPaths:[`${r}.data.*.b64_json`]}}:void 0}}function Lw(e,t){const r=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"custom";let n=`custom-${r}`,a=2;for(;t.has(n)||ao.has(n);)n=`custom-${r}-${a}`,a+=1;return t.add(n),n}function Oi(e,t=new Set){if(!e||typeof e!="object")return null;const r=e,n=Dw(r)??r,a=n.template==null?"http-image":Tw(n.template)?n.template:null;if(!a||!Wt(n.submit))return null;const o=typeof n.name=="string"&&n.name.trim()?n.name.trim():"自定义服务商",i=typeof n.id=="string"&&n.id.trim()&&!ao.has(n.id.trim())&&!t.has(n.id.trim())?n.id.trim():Lw(o,t);return t.add(i),{id:i,name:o,template:a,submit:sm(n.submit,{path:La.generationPath,method:"POST",contentType:"json",body:Li,result:la}),editSubmit:Wt(n.editSubmit)?sm(n.editSubmit,{path:La.editPath,method:"POST",contentType:"multipart",body:Bc,files:xf,result:la}):void 0,poll:_w(n.poll)}}function Qh(e){const t=new Set;return(Array.isArray(e)?e:[]).map(n=>Oi(n,t)).filter(n=>!!n)}function In(e={}){const t=e.apiMode??(ze==null?void 0:ze.apiMode)??"images",r=e.streamImages??(ze==null?void 0:ze.streamImages)??bf("openai",t);return{id:pf,name:(ze==null?void 0:ze.name)??"默认",provider:"openai",baseUrl:Qs,apiKey:(ze==null?void 0:ze.apiKey)??"",model:(ze==null?void 0:ze.model)??(t==="responses"?Wa:ir),imageGenerationModel:(ze==null?void 0:ze.imageGenerationModel)??ir,timeout:Di,reasoningEffort:ze==null?void 0:ze.reasoningEffort,codexCli:(ze==null?void 0:ze.codexCli)??!1,apiProxy:pa,streamPartialImages:(ze==null?void 0:ze.streamPartialImages)??kr,transparentBackgroundMethod:(ze==null?void 0:ze.transparentBackgroundMethod)??"api",...e,apiMode:t,streamImages:r}}function ep(e={}){return{id:`fal-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,name:"新配置",provider:"fal",baseUrl:Gn,apiKey:"",model:_i,imageGenerationModel:ir,timeout:Di,apiMode:"images",codexCli:!1,apiProxy:!1,streamImages:!1,streamPartialImages:kr,transparentBackgroundMethod:"api",...e}}function ec(e,t,r){const n={...e.providerDrafts,[e.provider]:{baseUrl:e.baseUrl,model:e.model,imageGenerationModel:e.imageGenerationModel,apiMode:e.apiMode,reasoningEffort:e.reasoningEffort,codexCli:e.codexCli,apiProxy:e.apiProxy,responseFormatB64Json:e.responseFormatB64Json,streamImages:e.streamImages,streamPartialImages:e.streamPartialImages,transparentBackgroundMethod:e.transparentBackgroundMethod}},a=n[t];if(t==="fal")return{...e,provider:t,baseUrl:(a==null?void 0:a.baseUrl)??Gn,model:(a==null?void 0:a.model)??_i,imageGenerationModel:(a==null?void 0:a.imageGenerationModel)??e.imageGenerationModel,apiMode:"images",reasoningEffort:a==null?void 0:a.reasoningEffort,codexCli:!1,apiProxy:!1,responseFormatB64Json:a==null?void 0:a.responseFormatB64Json,streamImages:!1,streamPartialImages:(a==null?void 0:a.streamPartialImages)??kr,transparentBackgroundMethod:(a==null?void 0:a.transparentBackgroundMethod)??"api",providerDrafts:n};if(r){const c=e.provider==="fal",u=Ei(r);return{...e,provider:r.id,baseUrl:(a==null?void 0:a.baseUrl)??(c?Qs:e.baseUrl||Qs),model:(a==null?void 0:a.model)??(c?ir:e.model||ir),imageGenerationModel:(a==null?void 0:a.imageGenerationModel)??e.imageGenerationModel,apiMode:"images",reasoningEffort:a==null?void 0:a.reasoningEffort,codexCli:(a==null?void 0:a.codexCli)??!1,apiProxy:!1,responseFormatB64Json:a==null?void 0:a.responseFormatB64Json,streamImages:!1,streamPartialImages:(a==null?void 0:a.streamPartialImages)??kr,transparentBackgroundMethod:u?(a==null?void 0:a.transparentBackgroundMethod)??"api":"local",providerDrafts:n}}const o=(a==null?void 0:a.apiMode)??e.apiMode,i=(a==null?void 0:a.streamImages)??(e.provider==="openai"?e.streamImages:bf(t,o)),l=(a==null?void 0:a.streamPartialImages)??(e.provider==="openai"?e.streamPartialImages:kr);return{...e,provider:t,baseUrl:(a==null?void 0:a.baseUrl)??Qs,model:(a==null?void 0:a.model)??ir,imageGenerationModel:(a==null?void 0:a.imageGenerationModel)??e.imageGenerationModel,apiMode:o,reasoningEffort:(a==null?void 0:a.reasoningEffort)??e.reasoningEffort,codexCli:(a==null?void 0:a.codexCli)??e.codexCli,apiProxy:(a==null?void 0:a.apiProxy)??pa,responseFormatB64Json:a==null?void 0:a.responseFormatB64Json,streamImages:i,streamPartialImages:l,transparentBackgroundMethod:(a==null?void 0:a.transparentBackgroundMethod)??"api",providerDrafts:n}}function Ow(e,t,r,n){if(!Wt(e))return;const a=r.has(t)&&!n.has(t),i=t==="fal"?ep():In({transparentBackgroundMethod:a?"local":"api"}),l=typeof e.baseUrl=="string"?e.baseUrl:void 0,c=typeof e.model=="string"&&wf(e.model)||void 0,u=typeof e.imageGenerationModel=="string"?e.imageGenerationModel.trim():"",f=e.apiMode==="responses"?"responses":e.apiMode==="images"?"images":void 0;if(ao.has(t)||r.has(t))return{baseUrl:t==="fal"?(l==null?void 0:l.trim().replace(/\/+$/,""))||Gn:l,model:c,imageGenerationModel:u,apiMode:f,reasoningEffort:ia(e.reasoningEffort),codexCli:typeof e.codexCli=="boolean"?e.codexCli:i.codexCli,apiProxy:typeof e.apiProxy=="boolean"?e.apiProxy:i.apiProxy,responseFormatB64Json:e.responseFormatB64Json===!0?!0:void 0,streamImages:typeof e.streamImages=="boolean"?e.streamImages:i.streamImages,streamPartialImages:Yr(e.streamPartialImages,i.streamPartialImages),transparentBackgroundMethod:!a&&(e.transparentBackgroundMethod==="api"||e.transparentBackgroundMethod==="local")?e.transparentBackgroundMethod:i.transparentBackgroundMethod}}function Bw(e,t,r){if(!Wt(e))return;const n=Object.entries(e).map(([a,o])=>[a,Ow(o,a,t,r)]).filter(a=>!!a[1]);return n.length?Object.fromEntries(n):void 0}function tc(e,t,r=new Set,n=new Set){const a=e&&typeof e=="object"?e:{},o=typeof a.provider=="string"?a.provider:"",i=ao.has(o)||r.has(o)?o:"openai",l=i==="openai"&&a.apiMode==="responses"?"responses":"images",c=r.has(i)?{transparentBackgroundMethod:"local",...t}:t,u=i==="fal"?ep(c):In({...c,apiMode:l}),f=typeof a.baseUrl=="string"?a.baseUrl:u.baseUrl,d=i==="openai"?typeof a.streamImages=="boolean"?a.streamImages:u.streamImages:!1,g=r.has(i)&&!n.has(i);return{...u,id:typeof a.id=="string"&&a.id.trim()?a.id:u.id,isDefault:typeof a.isDefault=="boolean"?a.isDefault:void 0,name:typeof a.name=="string"&&a.name.trim()?a.name:u.name,description:typeof a.description=="string"&&a.description.trim()?a.description:void 0,provider:i,baseUrl:i==="fal"?f.trim().replace(/\/+$/,""):f,apiKey:typeof a.apiKey=="string"?a.apiKey:u.apiKey,model:typeof a.model=="string"&&wf(a.model)||u.model,selectedModel:typeof a.selectedModel=="string"&&a.selectedModel.trim()?a.selectedModel.trim():void 0,imageGenerationModel:typeof a.imageGenerationModel=="string"?a.imageGenerationModel.trim():"",timeout:typeof a.timeout=="number"&&Number.isFinite(a.timeout)?a.timeout:u.timeout,apiMode:l,reasoningEffort:ia(a.reasoningEffort,u.reasoningEffort),codexCli:!!a.codexCli,apiProxy:i==="sb2api-async"?!1:typeof a.apiProxy=="boolean"?a.apiProxy:u.apiProxy,responseFormatB64Json:a.responseFormatB64Json===!0?!0:void 0,streamImages:d,streamPartialImages:Yr(a.streamPartialImages,u.streamPartialImages),transparentBackgroundMethod:!g&&(a.transparentBackgroundMethod==="api"||a.transparentBackgroundMethod==="local")?a.transparentBackgroundMethod:u.transparentBackgroundMethod,providerDrafts:Bw(a.providerDrafts,r,n)}}function Uw(e){if(!Wt(e))return;const t=typeof e.baseUrl=="string"?e.baseUrl.trim():"";if(t&&(t.startsWith("[")||t.includes("](")))throw new Error("JSON 包含 Markdown 链接,请粘贴纯文本");if(typeof e.apiMode=="string"&&e.apiMode!=="images"&&e.apiMode!=="responses")throw new Error("apiMode 格式无效,应为 images 或 responses")}function vu(e){if(!Array.isArray(e))return;const t=new Set;for(const r of e){if(!Wt(r))throw new Error("部署文件中的服务商配置必须是对象");const n=typeof r.name=="string"?r.name.trim():"",a=n?`「${n}」`:"",o=typeof r.id=="string"?r.id.trim():"";if(!o)throw new Error(`部署服务商${a}缺少 id`);if(ao.has(o))throw new Error(`部署服务商${a}的 id「${o}」与内置服务商冲突`);if(t.has(o))throw new Error(`部署服务商${a}的 id「${o}」重复`);if(!Oi(r))throw new Error(`部署服务商${a}的 Manifest 无效`);t.add(o)}}function tp(e,t,r=new Set,n=!1){const a=Array.isArray(e)?e.flatMap(i=>{if(Uw(i),!Wt(i))throw new Error("API 配置必须是对象");if(typeof i.provider!="string"||!ao.has(i.provider)&&!t.has(i.provider)){const l=typeof i.name=="string"?i.name.trim():"",c=typeof i.id=="string"?i.id.trim():"",u=l||c?`「${l||c}」`:"";throw new Error(`API 配置${u}引用了不存在的自定义服务商`)}return[i]}):[],o=new Set;if(n&&a.length>1&&a.filter(l=>l.isDefault===!0).length!==1)throw new Error("部署文件包含多个 API 配置时,必须且只能有一项设置 isDefault: true");for(const i of a){const l=typeof i.id=="string"?i.id.trim():"";if(l){if(o.has(l)){const c=typeof i.name=="string"?i.name.trim():"",u=c?`「${c}」`:"";throw new Error(`API 配置${u}的 id「${l}」重复`)}o.add(l);continue}}return a.map(i=>{const l=typeof i.id=="string"?i.id.trim():"",c=r.has(i.provider)?{transparentBackgroundMethod:"api"}:void 0;if(l)return{source:i,profile:tc({...i,id:l},c,t,r)};const u=i.provider,f=n?zw(u,i,o):rp(u,o);return{source:i,profile:tc({...i,id:f},c,t,r)}})}function Me(e){const t=e&&typeof e=="object"?e:{},r=Qh(t.customProviders),n=new Set(r.map(h=>h.id)),a=new Set(r.filter(Ei).map(h=>h.id)),o=t.apiMode==="responses"?"responses":"images",i=tc({baseUrl:typeof t.baseUrl=="string"?t.baseUrl:Qs,apiKey:typeof t.apiKey=="string"?t.apiKey:"",model:t.model,imageGenerationModel:t.imageGenerationModel,timeout:typeof t.timeout=="number"&&Number.isFinite(t.timeout)?t.timeout:Di,apiMode:o,codexCli:!!t.codexCli,apiProxy:typeof t.apiProxy=="boolean"?t.apiProxy:pa,responseFormatB64Json:t.responseFormatB64Json===!0?!0:void 0,streamImages:typeof t.streamImages=="boolean"?t.streamImages:void 0,streamPartialImages:Yr(t.streamPartialImages)}),l=Array.isArray(t.profiles)&&t.profiles.length?t.profiles.map(h=>{const y=Wt(h)&&typeof h.provider=="string"?h.provider:"",v=a.has(y)?{transparentBackgroundMethod:"api"}:void 0;return tc(h,v,n,a)}):[i],c=Uc({profiles:l}),u=l.map(h=>({...h,isDefault:h.id===c?!0:void 0})),f=typeof t.activeProfileId=="string"&&u.some(h=>h.id===t.activeProfileId)?t.activeProfileId:u[0].id,d=u.find(h=>h.id===f)??u[0],g=Pw(t.agentApiConfigMode),m=u.find(Oa),x=typeof t.agentTextProfileId=="string"&&u.some(h=>h.id===t.agentTextProfileId&&Oa(h))?t.agentTextProfileId:Oa(d)?d.id:(m==null?void 0:m.id)??null,b=typeof t.agentImageProfileId=="string"&&u.some(h=>h.id===t.agentImageProfileId)?t.agentImageProfileId:d.id;return{baseUrl:d.baseUrl,apiKey:d.apiKey,model:d.model,timeout:d.timeout,apiMode:d.apiMode,codexCli:d.codexCli,apiProxy:d.apiProxy,streamImages:d.streamImages,streamPartialImages:d.streamPartialImages,customProviders:r,providerOrder:Aw(t.providerOrder,r),clearInputAfterSubmit:typeof t.clearInputAfterSubmit=="boolean"?t.clearInputAfterSubmit:!1,persistInputOnRestart:typeof t.persistInputOnRestart=="boolean"?t.persistInputOnRestart:!0,reuseTaskApiProfileTemporarily:typeof t.reuseTaskApiProfileTemporarily=="boolean"?t.reuseTaskApiProfileTemporarily:!1,alwaysShowRetryButton:typeof t.alwaysShowRetryButton=="boolean"?t.alwaysShowRetryButton:!1,saveTasksToActiveFavoriteCollection:typeof t.saveTasksToActiveFavoriteCollection=="boolean"?t.saveTasksToActiveFavoriteCollection:!0,retryMode:Sw(t.retryMode,t.alwaysShowRetryButton===!0),allowPromptRewrite:typeof t.allowPromptRewrite=="boolean"?t.allowPromptRewrite:!1,taskCompletionNotification:typeof t.taskCompletionNotification=="boolean"?t.taskCompletionNotification:!1,autoCheckUpdate:typeof t.autoCheckUpdate=="boolean"?t.autoCheckUpdate:!0,writeLogFile:typeof t.writeLogFile=="boolean"?t.writeLogFile:!0,enterSubmit:typeof t.enterSubmit=="boolean"?t.enterSubmit:!1,privacyModeShortcut:vw(t.privacyModeShortcut,mf),colorMode:t.colorMode==="light"||t.colorMode==="dark"?t.colorMode:"system",uiFont:tm(t.uiFont),uiFontName:typeof t.uiFontName=="string"?t.uiFontName.trim():"",monoFont:tm(t.monoFont),monoFontName:typeof t.monoFontName=="string"?t.monoFontName.trim():"",showBatchPrompt:typeof t.showBatchPrompt=="boolean"?t.showBatchPrompt:!1,batchPromptEnabled:typeof t.batchPromptEnabled=="boolean"?t.batchPromptEnabled:!1,batchPromptMode:t.batchPromptMode==="concurrent"?"concurrent":"queue",batchPromptConcurrencyLimited:typeof t.batchPromptConcurrencyLimited=="boolean"?t.batchPromptConcurrencyLimited:!0,batchPromptConcurrency:Vh(t.batchPromptConcurrency),referenceImageEditAction:jw(t.referenceImageEditAction),zipDownloadRoutes:Nw(t.zipDownloadRoutes),saveLocationMode:t.saveLocationMode==="default"?"default":"ask",agentScrollToBottomAfterSubmit:typeof t.agentScrollToBottomAfterSubmit=="boolean"?t.agentScrollToBottomAfterSubmit:!0,agentMaxToolRounds:Zl(t.agentMaxToolRounds),agentWebSearch:typeof t.agentWebSearch=="boolean"?t.agentWebSearch:!1,agentMathFormattingPrompt:typeof t.agentMathFormattingPrompt=="boolean"?t.agentMathFormattingPrompt:!0,agentApiConfigMode:g,agentTextProfileId:x,agentImageProfileId:b,profiles:u,activeProfileId:f}}function Bi(e){const t=Me(e);if(t.agentApiConfigMode==="off")return zt(t);const r=t.profiles.find(n=>n.id===t.agentTextProfileId);return r?oo(r):null}function Ui(e){const t=Me(e);if(t.agentApiConfigMode!=="hybrid")return Bi(t);const r=t.profiles.find(n=>n.id===t.agentImageProfileId);return r?oo(r):null}function Rn(e,t){return t==="sb2api-async"?qh:Me(e).customProviders.find(n=>n.id===t)??null}function Ys(e,t){var r;return t==="fal"?"fal.ai":t==="openai"?"OpenAI":t==="sb2api-async"?qh.name:((r=Rn(e,t))==null?void 0:r.name)??t}function ei(e,t){return t==="openai"||!!Rn(e,t)}function yf(e,t){if(e!==void 0){if(!Wt(e)||e.apiConfigMode!==void 0&&e.apiConfigMode!=="off"&&e.apiConfigMode!=="native"&&e.apiConfigMode!=="hybrid"||e.textProfileId!==void 0&&!t.some(r=>r.id===e.textProfileId&&Oa(r))||e.imageProfileId!==void 0&&!t.some(r=>r.id===e.imageProfileId)){console.warn("忽略无效的 Agent 预置配置:请检查模式及引用的配置 ID(文本配置必须使用 Responses API)");return}return{...e.apiConfigMode!==void 0?{apiConfigMode:e.apiConfigMode}:{},...e.textProfileId!==void 0?{textProfileId:e.textProfileId}:{},...e.imageProfileId!==void 0?{imageProfileId:e.imageProfileId}:{}}}}function wu(e){return{...(e==null?void 0:e.apiConfigMode)!==void 0?{agentApiConfigMode:e.apiConfigMode}:{},...(e==null?void 0:e.textProfileId)!==void 0?{agentTextProfileId:e.textProfileId}:{},...(e==null?void 0:e.imageProfileId)!==void 0?{agentImageProfileId:e.imageProfileId}:{}}}function am(e){const t=e.find(r=>{var n;return(r.submit.taskIdPath||((n=r.editSubmit)==null?void 0:n.taskIdPath))&&!r.poll});if(t)throw new Error(`自定义服务商「${t.name}」配置了 taskIdPath,但缺少 poll`)}function Fw(e){const t=e.trim(),r=t.match(/^```[^\r\n]*\r?\n([\s\S]*?)\r?\n```$/);return r?r[1].trim():t}function vf(e,t=[],r={}){let n;try{n=JSON.parse(Fw(e))}catch{throw new Error("JSON 格式无效")}if(!n||typeof n!="object")throw new Error("JSON 根节点必须是对象");const a=n;if(Array.isArray(a.profiles)||Array.isArray(a.customProviders)){r.deploymentConfig&&vu(a.customProviders);const l=Qh(a.customProviders);if(!r.deploymentConfig&&Array.isArray(a.customProviders)&&a.customProviders.length>0&&!l.length)throw new Error("customProviders 数组中没有有效的服务商配置");am(l);const c=new Set(l.map(m=>m.id)),u=new Set(l.filter(Ei).map(m=>m.id)),f=tp(a.profiles,c,u,r.deploymentConfig),d=f.map(m=>m.profile);if(!r.deploymentConfig)return{customProviders:l,profiles:d};const g=yf(a.agent,d);return{customProviders:l,profiles:d,...g?{agent:g}:{},...f.length?{presetProfileFields:Object.fromEntries(f.map(m=>[m.profile.id,Object.keys(m.source)]))}:{}}}r.deploymentConfig&&vu([n]);const o=new Set(t.map(l=>l.id)),i=Oi(n,o);if(i)return am([i]),{customProviders:[i],profiles:[]};throw new Error("无法识别该 JSON。请粘贴自定义服务商配置。")}function ca(e){return Array.from(new Set(e.split(/[,,]/).map(t=>t.trim()).filter(Boolean)))}function wf(e){return ca(e).join(", ")}function oo(e,t){const r=ca(e.model),n=[t,e.selectedModel].find(a=>a&&r.includes(a))??r[0]??e.model;return{...e,model:n}}function zt(e){const t=e&&typeof e=="object"?e:{},r=Me(e),n=r.profiles.find(o=>o.id===r.activeProfileId)??r.profiles[0]??In(),a=n.provider==="openai"&&(t.apiMode==="images"||t.apiMode==="responses")?t.apiMode:n.apiMode;return oo({...n,baseUrl:typeof t.baseUrl=="string"?t.baseUrl:n.baseUrl,apiKey:typeof t.apiKey=="string"?t.apiKey:n.apiKey,model:typeof t.model=="string"&&t.model.trim()?t.model:n.model,timeout:typeof t.timeout=="number"&&Number.isFinite(t.timeout)?t.timeout:n.timeout,apiMode:a,codexCli:typeof t.codexCli=="boolean"?t.codexCli:n.codexCli,apiProxy:typeof t.apiProxy=="boolean"?t.apiProxy:n.apiProxy,streamImages:n.provider==="openai"&&typeof t.streamImages=="boolean"?t.streamImages:n.streamImages,streamPartialImages:Yr(t.streamPartialImages,n.streamPartialImages)})}function ti(e){return e.name.trim()?e.provider!=="fal"&&!e.baseUrl.trim()&&!ha(e.apiProxy)?"缺少 API URL":e.apiKey.trim()?e.model.trim()?null:"缺少模型 ID":"缺少 API Key":"缺少名称"}function $w(e){return e.id===pf&&e.name==="默认"&&e.provider==="openai"&&e.baseUrl===Qs&&e.apiKey===""&&e.model===ir&&e.imageGenerationModel===ir&&e.timeout===Di&&e.apiMode==="images"&&e.reasoningEffort===void 0&&e.codexCli===!1&&e.apiProxy===pa&&e.streamImages===!1&&e.streamPartialImages===kr&&e.transparentBackgroundMethod==="api"}function ku(e){return e.customProviders.length===0&&e.profiles.length===1&&e.activeProfileId===pf&&$w(e.profiles[0])}function rp(e,t){let r=`${e}-imported-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;for(;t.has(r);)r=`${e}-imported-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;return t.add(r),r}function zw(e,t,r){const n=JSON.stringify(t);let a=2166136261;for(let c=0;c<n.length;c+=1)a^=n.charCodeAt(c),a=Math.imul(a,16777619);const o=`${e}-preset-${(a>>>0).toString(36)}`;let i=o,l=2;for(;r.has(i);)i=`${o}-${l}`,l+=1;return r.add(i),i}function om(e){var t;return JSON.stringify([e.provider,e.baseUrl.trim().toLowerCase(),e.apiKey.trim(),e.model.trim(),(t=e.imageGenerationModel)==null?void 0:t.trim(),e.apiMode,e.reasoningEffort])}function im(e){var t;return JSON.stringify([e.provider,e.baseUrl.trim().toLowerCase(),e.model.trim(),(t=e.imageGenerationModel)==null?void 0:t.trim(),e.apiMode,e.reasoningEffort])}function lm(e){return JSON.stringify([e.name,e.template??"http-image",e.submit,e.editSubmit??null,e.poll??null])}function Ww(e,t){const r=[...e],n=new Map,a=new Set(r.map(o=>o.id));for(const o of t){const i=r.findIndex(c=>c.id===o.id);if(i>=0){r[i]=o,n.set(o.id,o.id);continue}const l=Oi(o,a);l&&(n.set(o.id,l.id),r.push(l))}return{providers:r,providerIdMap:n}}function np(e,t,r=[]){var d;const n=Me(e),a=r.find(g=>g.id===t.provider),o=a?((d=n.customProviders.find(g=>lm(g)===lm(a)))==null?void 0:d.id)??t.provider:t.provider,i={...t,provider:o},l=n.profiles.find(g=>g.id===i.id);if(l)return l;const c=om(i),u=n.profiles.find(g=>om(g)===c);if(u)return u;if(i.apiKey.trim())return null;const f=im(i);return n.profiles.find(g=>im(g)===f)??null}function kf(e,t,r={}){const n=Me(e),a=Me(t),o=Me({...a,customProviders:a.customProviders,profiles:a.profiles.map(f=>({...f,isDefault:void 0}))});if(r.preserveInternalIds){if(ku(n))return o;const f=[...n.customProviders];for(const g of o.customProviders){const m=f.findIndex(x=>x.id===g.id);m>=0?f[m]=g:f.push(g)}const d=[...n.profiles];for(const g of o.profiles){const m=d.findIndex(x=>x.id===g.id);m>=0?d[m]=g:d.push(g)}return Me({...n,customProviders:f,profiles:d,activeProfileId:n.activeProfileId})}if(ku(n))return o;const{providers:i,providerIdMap:l}=Ww(n.customProviders,o.customProviders),c=[...n.profiles],u=Wt(t)&&Array.isArray(t.profiles);for(const f of o.profiles){const d=l.has(f.provider)?{...f,provider:l.get(f.provider)??f.provider}:f,g=u?d:{...d,id:rp(d.provider,new Set(c.map(x=>x.id)))},m=c.findIndex(x=>x.id===g.id);if(m>=0){c[m]=g;continue}c.push(g)}return Me({...n,customProviders:i,profiles:c,activeProfileId:n.activeProfileId})}const sp=["name","description","provider","baseUrl","model","imageGenerationModel","timeout","apiMode","reasoningEffort","codexCli","apiProxy","responseFormatB64Json","streamImages","streamPartialImages","transparentBackgroundMethod","providerDrafts"];function cm(e,t,r){return!Wt(e)||!Array.isArray(e[t])?new Set(Object.keys(r)):new Set(e[t].filter(n=>typeof n=="string"))}function dm(e,t,r){if(e.provider!==t.provider)return t;const n={};for(const a of sp)r.has(a)&&Object.assign(n,{[a]:t[a]});return{...e,...n,id:t.id,isDefault:t.isDefault}}function Hw(e,t,r={}){var K,te,P,B,$,Q;const n=Wt(t)?t:{};vu(n.customProviders);const a=Me(t),o=Me(e),i=new Set(a.customProviders.map(L=>L.id)),l=new Set(a.customProviders.filter(Ei).map(L=>L.id)),c=tp(n.profiles,i,l,!0).map(L=>({profile:L.profile,source:L.source,isDefault:L.source.isDefault===!0})),u=new Set(r.dismissedPresetProfileIds??[]),f=new Set(r.dismissedPresetProviderIds??[]),d=c.filter(L=>!u.has(L.profile.id)),g=d.map(L=>L.profile),m=new Set(c.map(L=>L.profile.id)),x=c.length===1?c[0].profile.id:((K=c.find(L=>L.isDefault))==null?void 0:K.profile.id)??null,b=g.length>0&&ku(o),h=new Map(o.customProviders.map(L=>[L.id,L])),y=new Map(((te=r.previousPresetConfig)==null?void 0:te.profiles.map(L=>[L.id,L]))??[]),v=new Map(((P=r.previousPresetConfig)==null?void 0:P.customProviders.map(L=>[L.id,L]))??[]),I=a.customProviders.filter(L=>!f.has(L.id)).map(L=>{const G=h.get(L.id),se=v.get(L.id);return!G||r.lockPresetParams?L:!se||JSON.stringify(L)===JSON.stringify(se)?G:L}),S=new Set(a.customProviders.map(L=>L.id)),k=new Set(r.usedPresetProfileIds??[]),j=new Set(o.customProviders.filter(L=>{const G=v.get(L.id);return G&&JSON.stringify(L)!==JSON.stringify(G)}).map(L=>L.id)),A=new Set(o.profiles.filter(L=>{const G=y.get(L.id);return!G||m.has(L.id)||k.has(L.id)||j.has(L.provider)?!1:JSON.stringify({...L,isDefault:void 0})===JSON.stringify({...G,isDefault:void 0})}).map(L=>L.id)),N=new Map(o.profiles.map(L=>[L.id,L])),C=d.map(L=>{const G=b?void 0:N.get(L.profile.id),se={...L.profile,isDefault:L.profile.id===x?!0:void 0},Y=y.get(L.profile.id),le=cm(n.presetProfileFields,L.profile.id,L.source),ie=Y?dm(Y,se,le):se;if(!G)return ie;if(r.lockPresetParams)return{...ie,apiKey:G.apiKey};if(!Y)return{...G,baseUrl:ie.baseUrl,isDefault:ie.isDefault};const D={};for(const ue of sp)JSON.stringify(ie[ue])!==JSON.stringify(Y[ue])&&Object.assign(D,{[ue]:ie[ue]});return{...G,...D,isDefault:ie.isDefault}}),T=new Map(C.map(L=>[L.id,L])),R=b?C:[...o.profiles.filter(L=>!A.has(L.id)).map(L=>T.get(L.id)??(L.isDefault?{...L,isDefault:void 0}:L)),...C.filter(L=>!N.has(L.id))],U=o.customProviders.filter(L=>!S.has(L.id)).filter(L=>{const G=v.get(L.id);return!(G&&JSON.stringify(L)===JSON.stringify(G))||R.some(Y=>Y.provider===L.id)}),W=[...I,...U],F=[...a.customProviders];for(const L of((B=r.previousPresetConfig)==null?void 0:B.customProviders)??[])!S.has(L.id)&&W.some(G=>G.id===L.id)&&F.push(L);const _=c.map(L=>{const G={...L.profile,isDefault:L.profile.id===x?!0:void 0},se=y.get(L.profile.id);if(!se)return G;const Y=cm(n.presetProfileFields,L.profile.id,L.source);return dm(se,G,Y)});for(const L of(($=r.previousPresetConfig)==null?void 0:$.profiles)??[])!m.has(L.id)&&R.some(G=>G.id===L.id)&&_.push(L);const O=yf(n.agent,c.map(L=>L.profile)),J=wu((Q=r.previousPresetConfig)==null?void 0:Q.agent),H=Object.fromEntries(Object.entries(wu(O)).filter(([L,G])=>r.lockPresetParams||G!==J[L]));return{settings:Me({...o,...H,customProviders:W,profiles:R,activeProfileId:b?x??C[0].id:o.activeProfileId}),presetConfig:{customProviders:F,profiles:_,...O?{agent:O}:{}}}}const sr=Me({profiles:[In()],baseUrl:Qs,apiKey:(ze==null?void 0:ze.apiKey)??"",model:(ze==null?void 0:ze.model)??((ze==null?void 0:ze.apiMode)==="responses"?Wa:ir),timeout:Di,apiMode:(ze==null?void 0:ze.apiMode)??"images",codexCli:(ze==null?void 0:ze.codexCli)??!1,apiProxy:pa,streamImages:(ze==null?void 0:ze.streamImages)??bf("openai",(ze==null?void 0:ze.apiMode)??"images"),streamPartialImages:(ze==null?void 0:ze.streamPartialImages)??kr,customProviders:[],clearInputAfterSubmit:!1,persistInputOnRestart:!0,reuseTaskApiProfileTemporarily:!1,alwaysShowRetryButton:!1,saveTasksToActiveFavoriteCollection:!0,retryMode:"new",allowPromptRewrite:!1,taskCompletionNotification:!1,autoCheckUpdate:!0,writeLogFile:!0,enterSubmit:!1,privacyModeShortcut:mf,showBatchPrompt:!1,batchPromptEnabled:!1,batchPromptMode:"queue",batchPromptConcurrencyLimited:!0,batchPromptConcurrency:Jl,referenceImageEditAction:"ask",zipDownloadRoutes:Hh,saveLocationMode:"ask",agentScrollToBottomAfterSubmit:!0,agentMaxToolRounds:Jn,agentWebSearch:!1,agentMathFormattingPrompt:!0,agentApiConfigMode:"off",agentTextProfileId:null,agentImageProfileId:null}),Yw=mr(""),ap=(Yw||mr(void 0))==="true",Vw=mr("")==="true",Kw=mr("")==="true";let Kt=[],da=[],op,Pr,Vs=null;function um(e){var t;Kt=(e==null?void 0:e.profiles.map(r=>({...r})))??[],da=(e==null?void 0:e.customProviders.map(r=>({...r})))??[],op=e==null?void 0:e.presetProfileFields,Pr=e!=null&&e.agent?{...e.agent}:void 0,Vs=Kt.length===1?Kt[0].id:((t=Kt.find(r=>r.isDefault===!0))==null?void 0:t.id)??null}function Bn(){return new Set(Kt.map(e=>e.id))}function Xw(e){var t;return(t=Kt.find(r=>r.id===e))==null?void 0:t.description}function If(){return new Set(da.map(e=>e.id))}function ri(){return Kt.length===0&&da.length===0?null:{customProviders:da.map(e=>({...e})),profiles:Kt.map(e=>({...e})),presetProfileFields:op,...Pr?{agent:{...Pr}}:{}}}function Fc(){return Vs}function qw(){const e=Kt.find(t=>t.id===Vs);return!e||e.provider==="fal"?"":e.baseUrl}function Cf(e){return Kt.some(t=>t.id===e)}function $c(e){return da.some(t=>t.id===e)}function Cn(){return ap&&Kt.length>0}function io(){return Vw&&Kt.length>0}function Fi(){return(Kw||ap)&&Kt.length>0}function zc(e){return io()&&Cf(e)}function xl(e){return io()&&(Pr==null?void 0:Pr[e])!==void 0}function _l(e){return io()&&$c(e)}function ni(e,t){return $c(e)?Fi()?!0:t.some(r=>r.provider===e&&zc(r.id)):!1}function fm(e,t={}){var x,b,h;const r=Cn(),n=io();if(Kt.length===0)return e;const a=new Set(t.dismissedPresetProviderIds??[]),o=Bn(),i=new Map(Kt.map(y=>[y.id,y])),l=new Map(da.map(y=>[y.id,y])),c=e.profiles.map(y=>{const v=i.get(y.id);return v?{...n?v:y,apiKey:y.apiKey,selectedModel:y.selectedModel,provider:n||r?v.provider:y.provider,isDefault:y.id===Vs?!0:void 0}:y.isDefault?{...y,isDefault:void 0}:y});if(Fi())for(const y of Kt)c.some(v=>v.id===y.id)||c.push({...y,isDefault:y.id===Vs?!0:void 0});const u=e.customProviders.filter(y=>!a.has(y.id)).map(y=>{const v=l.get(y.id);return v&&n?v:y});for(const y of da)a.has(y.id)||u.some(v=>v.id===y.id)||u.push(y);const f=r&&!o.has(e.activeProfileId)?Vs??((x=Kt[0])==null?void 0:x.id)??e.activeProfileId:e.activeProfileId,d=r&&(!e.agentTextProfileId||!o.has(e.agentTextProfileId))?((b=Kt.find(y=>y.provider==="openai"&&y.apiMode==="responses"))==null?void 0:b.id)??null:e.agentTextProfileId,g=r&&(!e.agentImageProfileId||!o.has(e.agentImageProfileId))?Vs??((h=Kt[0])==null?void 0:h.id)??null:e.agentImageProfileId,m=n&&Pr?Me({...e,profiles:c,...wu(Pr)}):null;return{...e,...m?{agentApiConfigMode:m.agentApiConfigMode}:{},customProviders:u,profiles:c,activeProfileId:f,agentTextProfileId:m&&(Pr==null?void 0:Pr.textProfileId)!==void 0?m.agentTextProfileId:d,agentImageProfileId:m&&(Pr==null?void 0:Pr.imageProfileId)!==void 0?m.agentImageProfileId:g}}const Iu=new EventTarget,Cu="dismiss-tooltips";function xr(){Iu.dispatchEvent(new Event(Cu))}function ip(e){return Iu.addEventListener(Cu,e),()=>Iu.removeEventListener(Cu,e)}const Wc="",si="",Hc="",lp=/\u2063@图(\d+)\u2064/g,Yc=/\u2063@图(\d+) 评论\u2065([^\u2064]*)\u2064/g,cp=/\u2063(@图(\d+)(?: 评论)?|@(?:第)?\d+轮图\d+)(?:\u2065[^\u2064]*)?\u2064/g;function zo(e){return`@图${e+1}`}function dp(e){return Vc(zo(e))}function Vc(e){return`${Wc}${e}${si}`}function gr(e){return e.replace(/\u2065[^\u2064]*/g,"").replace(/[\u2063\u2064]/g,"")}function ms(e,t){let r=0;for(let n=0;n<e.length;n++){if(e[n]===Hc){for(;n+1<e.length&&e[n+1]!==si;)n++;continue}if(e[n]!==si){if(r>=t)return n;e[n]!==Wc&&r++}}return e.length}function Jw(e,t){for(const r of e.matchAll(cp)){if(r.index==null)continue;const n=gr(e.slice(0,r.index)).length,a=n+r[1].length;if(t>n&&t<=a)return!0}return!1}function gm(e,t,r){if(r.length===0)return null;const n=e.slice(0,t),a=n.lastIndexOf("@");if(a<0)return null;const o=n.slice(a+1);return/\s/.test(o)?null:{start:a,query:o}}function Gw(e,t){const r=e.trim().toLowerCase();if(!r)return!0;const n=String(t+1),a=`图${n}`;return n.includes(r)||a.toLowerCase().includes(r)}function mm(e,t,r,n){return up(e,t,r,zo(n))}function up(e,t,r,n){const a=ms(e,t),o=ms(e,r),i=Vc(n);return{prompt:`${e.slice(0,a)}${i}${e.slice(o)}`,cursor:t+n.length}}function jf(e,t,r,n={}){const a=o=>{const i=t[Number(o)-1];if(!i)return null;const l=n[i.id]??i.id;return r.findIndex(c=>c.id===l)};return e.replace(Yc,(o,i,l)=>{const c=a(i);return c==null?o:c>=0?`${Wc}@图${c+1} 评论${Hc}${l}${si}`:""}).replace(lp,(o,i)=>{const l=a(i);return l==null?o:l>=0?dp(l):"@已移除图片"})}function fp(e,t){const r=[];let n=0;for(const a of e.matchAll(cp)){const o=a[1],i=a[2]?Number(a[2])-1:null;a.index!=null&&(i!=null&&!t[i]||(a.index>n&&r.push({type:"text",text:gr(e.slice(n,a.index))}),r.push(i==null?{type:"mention",text:o,mentionText:Vc(o)}:{type:"mention",text:o,imageIndex:i,...a[0].includes(Hc)?{mentionText:a[0]}:{}}),n=a.index+a[0].length))}return n<e.length&&r.push({type:"text",text:gr(e.slice(n))}),r.length>0?r:[{type:"text",text:gr(e)}]}function $i(e,t,r){return Qw(e).replace(lp,(n,a)=>{const o=Number(a)-1;return t!=null&&(o<0||o>=t)?gr(n):r?r(o):`[image ${a}]`})}function gp(e){try{const t=JSON.parse(decodeURIComponent(e));return Array.isArray(t)?t.flatMap(r=>{if(!r||typeof r!="object")return[];const n=r;return typeof n.x!="number"||typeof n.y!="number"||typeof n.text!="string"?[]:[{x:Math.min(1,Math.max(0,n.x)),y:Math.min(1,Math.max(0,n.y)),text:n.text}]}):[]}catch{return[]}}function hm(e,t){const r=t.map(n=>({x:Math.round(n.x*1e4)/1e4,y:Math.round(n.y*1e4)/1e4,text:n.text.replace(/[\u2063-\u2065]/g,"")}));return`${Wc}@图${e+1} 评论${Hc}${encodeURIComponent(JSON.stringify(r))}${si}`}function Ya(e,t){for(const r of e.matchAll(Yc))if(Number(r[1])-1===t)return gp(r[2]);return[]}function Zw(e,t,r,n,a=n){let o=!1;const i=e.replace(Yc,(f,d)=>Number(d)-1!==t||o?f:(o=!0,r.length?hm(t,r):""));if(o||!r.length)return{prompt:i,cursor:null};const l=ms(e,n),c=ms(e,a),u=hm(t,r);return{prompt:`${e.slice(0,l)}${u}${e.slice(c)}`,cursor:gr(e.slice(0,l)+u).length}}function Qw(e){const t=(i,l)=>{const c=(l?/\n*$/:/^\n*/).exec(i)[0].length;return`
|
|
3
|
+
`.repeat(Math.max(0,2-c))};let r="",n=0,a=!1;const o=i=>{const l=a?i.replace(/^[ \t]+/,""):i;l&&(a&&(r+=t(l,!1)),a=!1,r+=l)};for(const i of e.matchAll(Yc)){o(e.slice(n,i.index)),n=i.index+i[0].length;const l=gp(i[2]);if(!l.length)continue;const c=f=>`${Math.round(f*100)}%`,u=l.map((f,d)=>`${d+1}. (X=${c(f.x)}, Y=${c(f.y)}) ${f.text}`);r=r.replace(/[ \t]+$/,""),r&&(r+=t(r,!0)),r+=`${dp(Number(i[1])-1)} notes:
|
|
4
|
+
${u.join(`
|
|
5
|
+
`)}`,a=!0}return o(e.slice(n)),r}function ai(e,t){return gr($i(e,t))}const ek="gpt-image-playground",tk=4,xs="tasks",_n="images",bn="thumbnails",Zn="agentConversations",ju="thumbnailVersion";let Os=null,Su=!1;const Nu=new Set;function bl(e){if(Su!==e){Su=e;for(const t of Nu)t()}}function rk(){return Su}function nk(e){return Nu.add(e),()=>{Nu.delete(e)}}function xa(){return Os||(Os=new Promise((e,t)=>{const r=indexedDB.open(ek,tk);r.onupgradeneeded=()=>{bl(!1);const n=r.result;n.objectStoreNames.contains(xs)||n.createObjectStore(xs,{keyPath:"id"}),n.objectStoreNames.contains(_n)||n.createObjectStore(_n,{keyPath:"id"});const a=n.objectStoreNames.contains(bn)?r.transaction.objectStore(bn):n.createObjectStore(bn,{keyPath:"id"});a.indexNames.contains(ju)||a.createIndex(ju,"thumbnailVersion"),n.objectStoreNames.contains(Zn)||n.createObjectStore(Zn,{keyPath:"id"})},r.onsuccess=()=>{bl(!1);const n=r.result;n.onversionchange=()=>{n.close(),Os=null},n.onclose=()=>{Os=null},e(n)},r.onerror=()=>{bl(!1),Os=null,t(r.error)},r.onblocked=()=>{console.warn("数据库升级等待其他标签页关闭旧连接"),bl(!0)}}),Os)}function Cr(e,t,r){return xa().then(n=>new Promise((a,o)=>{const i=n.transaction(e,t),l=i.objectStore(e),c=r(l);if(t==="readonly"){c.onsuccess=()=>a(c.result),c.onerror=()=>o(c.error);return}i.oncomplete=()=>a(c.result),i.onerror=()=>o(i.error??c.error),i.onabort=()=>o(i.error??c.error)}))}const pm="gpt-image-playground:image-blob-migrated",mp="gpt-image-playground:image-blob-disabled";let ua=!0;try{ua=!localStorage.getItem(mp)}catch{}function hp(e,t=!1){if(t)try{localStorage.setItem(mp,"1")}catch{}ua&&(ua=!1,console.warn("当前浏览器无法在 IndexedDB 中可靠地保存 Blob,改为保存 dataUrl 字符串",e))}function Sf(e){const t=Rv(e);if(t.mime===Bh)return;const r=new Blob([t.bytes],{type:t.mime});return r.type===t.mime?r:void 0}function sk(e){const t=ua?Sf(e.dataUrl):void 0;if(!t)return e;const{dataUrl:r,...n}=e;return{...n,blob:t}}function ak(e){const t=ua?Sf(e.thumbnailDataUrl):void 0;if(!t)return e;const{thumbnailDataUrl:r,...n}=e;return{...n,blob:t}}async function Nf(e){if(typeof FileReader>"u")return oa(e);const t=await new Promise((r,n)=>{const a=new FileReader;a.onload=()=>r(String(a.result)),a.onerror=()=>n(a.error),a.readAsDataURL(e)});return t.startsWith(`data:${e.type};base64,`)?t:oa(e)}async function pp(e){if(!(e!=null&&e.blob))return e;const{blob:t,...r}=e;try{return{...r,dataUrl:await Nf(t)}}catch(n){console.warn("读取图片失败",e.id,n);return}}async function ok(e){if(!(e!=null&&e.blob))return e;const{blob:t,...r}=e;try{return{...r,thumbnailDataUrl:await Nf(t)}}catch(n){console.warn("读取缩略图失败",e.id,n);return}}function Kc(e){return Cr(_n,"readonly",t=>t.get(e))}function Xc(e){return Cr(bn,"readonly",t=>t.get(e))}async function ik(e){return(await Cr(bn,"readonly",r=>r.index(ju).getAllKeys(e))).map(String)}async function lk(e,t){const r=await Xc(e);if(!r||r.thumbnailVersion!==t)return;const n=r.blob?URL.createObjectURL(r.blob):r.thumbnailDataUrl;if(n)return{src:n,width:r.width,height:r.height,thumbnailVersion:r.thumbnailVersion}}function xm(e,t){return(e==null?void 0:e.blob)instanceof Blob&&e.blob.size===t.size&&e.thumbnailVersion===t.thumbnailVersion}function ck(e,t,r){return xa().then(n=>new Promise((a,o)=>{const i=n.transaction(e,"readwrite"),l=i.objectStore(e);let c={result:"skipped"};const u=l.get(r);u.onsuccess=()=>{const f=u.result,d=f==null?void 0:f[t];if(!f||typeof d!="string")return;const g=Sf(d);if(!g){c={result:"kept"};return}const{[t]:m,...x}=f;l.put({...x,blob:g}),c={result:"converted",written:{original:d,size:g.size,thumbnailVersion:f.thumbnailVersion}}},i.oncomplete=()=>a(c),i.onerror=()=>o(i.error),i.onabort=()=>o(i.error)}))}async function dk(e,t,r,n){const a=await Cr(e,"readonly",o=>o.get(r));if(!xm(a,n))return!0;try{if(await Nf(a.blob)===n.original)return!0}catch(o){console.warn("读回转换后的图片失败",r,o)}return await xa().then(o=>new Promise((i,l)=>{const c=o.transaction(e,"readwrite"),u=c.objectStore(e),f=u.get(r);f.onsuccess=()=>{const d=f.result;if(!xm(d,n))return;const{blob:g,...m}=d;u.put({...m,[t]:n.original})},c.oncomplete=()=>i(),c.onerror=()=>l(c.error),c.onabort=()=>l(c.error)})),!1}let $d=!1;async function uk(){if($d||!ua)return;try{if(localStorage.getItem(pm))return}catch{}$d=!0;let e=0,t=0;try{for(const[r,n]of[[_n,"dataUrl"],[bn,"thumbnailDataUrl"]]){const a=await Cr(r,"readonly",o=>o.getAllKeys());for(const o of a){if(!ua)return;try{const i=await ck(r,n,o);if(i.result==="kept"&&(t++,console.warn("图片无法无损转换为 Blob,保留原格式",o)),i.result==="converted"){if(!await dk(r,n,o,i.written)){hp(`读回的 Blob 与原图不一致:${String(o)}`,!0);return}e++}}catch(i){console.warn("图片转换为 Blob 失败,保留原格式",o,i);return}await new Promise(i=>setTimeout(i,0))}}try{localStorage.setItem(pm,"1")}catch{}}catch(r){console.warn("图片存储格式迁移中断,下次启动继续",r)}finally{$d=!1,(e||t)&&console.info(`图片存储格式迁移:转换 ${e} 条,保留原格式 ${t} 条`)}}const fk=new Set(["DataCloneError","UnknownError"]);async function xp(e,t,r){try{return await Cr(e,"readwrite",n=>n.put(r))}catch(n){if(r===t||!fk.has((n==null?void 0:n.name)??""))throw n;return hp(n),Cr(e,"readwrite",a=>a.put(t))}}function gk(){return Cr(xs,"readonly",e=>e.getAll())}function mk(e){return Cr(xs,"readwrite",t=>t.put(e))}function hk(e){return Cr(xs,"readwrite",t=>t.delete(e))}function pk(e,t,r){return xa().then(n=>new Promise((a,o)=>{const i=n.transaction([xs,Zn],"readwrite"),l=i.objectStore(xs),c=i.objectStore(Zn);for(const u of e)l.delete(u);for(const u of t)l.put(u);for(const u of r)c.put(u);i.oncomplete=()=>a(void 0),i.onerror=()=>o(i.error),i.onabort=()=>o(i.error)}))}function xk(){return Cr(xs,"readwrite",e=>e.clear())}function bk(){return Cr(Zn,"readonly",e=>e.getAll())}function yk(e){return Cr(Zn,"readwrite",t=>t.put(e))}function vk(){return Cr(Zn,"readwrite",e=>e.clear())}function wk(e){return xa().then(t=>new Promise((r,n)=>{const a=t.transaction(Zn,"readwrite"),o=a.objectStore(Zn);o.clear();for(const i of e)o.put(i);a.oncomplete=()=>r(void 0),a.onerror=()=>n(a.error),a.onabort=()=>n(a.error)}))}function kk(e){return Kc(e).then(pp)}async function Ik(e){const t=await Kc(e);if(!t)return;const{blob:r,dataUrl:n,...a}=t;return a}function Ck(e){return Xc(e).then(ok)}function jk(e){return xp(bn,e,ak(e))}function Sk(){return Cr(_n,"readonly",e=>e.getAllKeys()).then(e=>e.map(String))}function Nk(e){return xp(_n,e,sk(e))}function Ak(e){return xa().then(t=>new Promise((r,n)=>{const a=t.transaction([_n,bn],"readwrite");a.objectStore(_n).delete(e),a.objectStore(bn).delete(e),a.oncomplete=()=>r(void 0),a.onerror=()=>n(a.error)}))}function Pk(){return xa().then(e=>new Promise((t,r)=>{const n=e.transaction([_n,bn],"readwrite");n.objectStore(_n).clear(),n.objectStore(bn).clear(),n.oncomplete=()=>t(void 0),n.onerror=()=>r(n.error)}))}const Tk=Object.freeze(Object.defineProperty({__proto__:null,clearAgentConversations:vk,clearImages:Pk,clearTasks:xk,commitTaskDeletion:pk,deleteImage:Ak,deleteTask:hk,getAllAgentConversations:bk,getAllImageIds:Sk,getAllTasks:gk,getImage:kk,getImageMeta:Ik,getStoredImageThumbnail:Ck,putAgentConversation:yk,putImage:Nk,putImageThumbnail:jk,putTask:mk,replaceAgentConversations:wk},Symbol.toStringTag,{value:"Module"})),Mk=720,Ek=.9,Yn=2,Dn=Yn,Rk=De?_v:Tk,{getAllTasks:Af,putTask:bp,deleteTask:_k,commitTaskDeletion:Dk,clearTasks:Lk,getAllAgentConversations:Ok,putAgentConversation:Bk,clearAgentConversations:Uk,replaceAgentConversations:Fk,getImage:qn,getImageMeta:yp,getStoredImageThumbnail:Pf,putImageThumbnail:Va,getAllImageIds:vp,putImage:ea,deleteImage:wp,clearImages:$k}=Rk;async function kp(e){const t=await Pf(e);if((t==null?void 0:t.thumbnailVersion)===Yn){const i=await yp(e);if(i&&(!i.width||!i.height)&&t.width&&t.height){const l=await qn(e);l&&await ea({...l,width:t.width,height:t.height})}return t}const r=await qn(e);if(!r)return;const n=r;if(n.thumbnailDataUrl&&n.thumbnailVersion===Yn){const i={id:e,thumbnailDataUrl:n.thumbnailDataUrl,width:n.width,height:n.height,thumbnailVersion:Yn};return await Va(i),(!r.width||!r.height)&&i.width&&i.height&&await ea({...r,width:i.width,height:i.height}),i}const a=await Au(r.dataUrl);if(!a.thumbnailDataUrl)return;const o={id:e,thumbnailDataUrl:a.thumbnailDataUrl,width:a.width,height:a.height,thumbnailVersion:Yn};return await Va(o),a.width&&a.height&&(r.width!==a.width||r.height!==a.height)&&await ea({...r,width:a.width,height:a.height}),o}async function zk(e){var n;if(!((n=globalThis.crypto)!=null&&n.subtle))return Wk(e);const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}function Wk(e){let t=2166136261,r=16777619;for(let n=0;n<e.length;n++){const a=e.charCodeAt(n);t^=a,t=Math.imul(t,16777619),r^=a,r=Math.imul(r,668265261)}return`fallback-${(t>>>0).toString(16).padStart(8,"0")}${(r>>>0).toString(16).padStart(8,"0")}`}async function Qn(e,t="upload"){return(await oi(e,t)).id}async function oi(e,t="upload"){var a;const r=await zk(e),n=await qn(r);if(!n){const o=await Au(e);return await ea({id:r,dataUrl:e,createdAt:Date.now(),source:t,width:o.width,height:o.height}),o.thumbnailDataUrl&&await Va({id:r,thumbnailDataUrl:o.thumbnailDataUrl,width:o.width,height:o.height,thumbnailVersion:Yn}),{id:r,width:o.width,height:o.height}}if(((a=await Pf(r))==null?void 0:a.thumbnailVersion)!==Yn){const o=await Au(n.dataUrl),i=o.width??n.width,l=o.height??n.height;return o.width&&o.height&&(n.width!==o.width||n.height!==o.height)&&await ea({...n,width:o.width,height:o.height}),o.thumbnailDataUrl&&await Va({id:r,thumbnailDataUrl:o.thumbnailDataUrl,width:o.width,height:o.height,thumbnailVersion:Yn}),{id:r,width:i,height:l}}return{id:r,width:n.width,height:n.height}}function Hk(e){return new Promise((t,r)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>r(new Error("图片加载失败")),n.src=e})}async function Yk(e){const t=await Hk(e),r=t.naturalWidth,n=t.naturalHeight;if(r<=0||n<=0)throw new Error("图片尺寸无效");const a=Math.min(1,Mk/Math.max(r,n)),o=document.createElement("canvas");o.width=Math.max(1,Math.round(r*a)),o.height=Math.max(1,Math.round(n*a));const i=o.getContext("2d");if(!i)throw new Error("当前浏览器不支持 Canvas");return i.drawImage(t,0,0,o.width,o.height),{thumbnailDataUrl:o.toDataURL("image/webp",Ek),width:r,height:n,thumbnailVersion:Yn}}async function Au(e){try{return await Yk(e)}catch{return{}}}var Bs={},ja={},zd={},wo={},bm;function Ip(){return bm||(bm=1,(function(e){var t=wo&&wo.__awaiter||function(o,i,l,c){function u(f){return f instanceof l?f:new l(function(d){d(f)})}return new(l||(l=Promise))(function(f,d){function g(b){try{x(c.next(b))}catch(h){d(h)}}function m(b){try{x(c.throw(b))}catch(h){d(h)}}function x(b){b.done?f(b.value):u(b.value).then(g,m)}x((c=c.apply(o,i||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.TARGET_URL_HEADER=void 0,e.withMiddleware=r,e.withProxy=a;function r(...o){const i=l=>typeof l=="function";return l=>t(this,void 0,void 0,function*(){let c=Object.assign({},l);for(const u of o.filter(i))c=yield u(c);return c})}e.TARGET_URL_HEADER="x-fal-target-url";function n(o){const i={isBrowser:typeof window<"u"&&typeof window.document<"u"};return typeof o=="function"?o(i):o==="always"?!0:i.isBrowser}function a(o){return i=>i.headers&&e.TARGET_URL_HEADER in i.headers||!n(o.when)?Promise.resolve(i):Promise.resolve(Object.assign(Object.assign({},i),{url:o.targetUrl,headers:Object.assign(Object.assign({},i.headers||{}),{[e.TARGET_URL_HEADER]:i.url})}))}})(wo)),wo}var dn={},Wd={},ym;function Tf(){return ym||(ym=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.RUNNER_HINT_HEADER=e.QUEUE_PRIORITY_HEADER=e.REQUEST_TIMEOUT_TYPE_HEADER=e.REQUEST_TIMEOUT_HEADER=e.MIN_REQUEST_TIMEOUT_SECONDS=void 0,e.validateTimeoutHeader=t,e.buildTimeoutHeaders=r,e.MIN_REQUEST_TIMEOUT_SECONDS=1,e.REQUEST_TIMEOUT_HEADER="x-fal-request-timeout",e.REQUEST_TIMEOUT_TYPE_HEADER="x-fal-request-timeout-type",e.QUEUE_PRIORITY_HEADER="x-fal-queue-priority",e.RUNNER_HINT_HEADER="x-fal-runner-hint";function t(n){if(typeof n!="number"||isNaN(n))throw new Error(`Timeout must be a number, got ${n}`);if(n<=e.MIN_REQUEST_TIMEOUT_SECONDS)throw new Error(`Timeout must be greater than ${e.MIN_REQUEST_TIMEOUT_SECONDS} seconds`);return n.toString()}function r(n){return n===void 0?{}:{[e.REQUEST_TIMEOUT_HEADER]:t(n)}}})(Wd)),Wd}var vm;function ba(){if(vm)return dn;vm=1;var e=dn&&dn.__awaiter||function(l,c,u,f){function d(g){return g instanceof u?g:new u(function(m){m(g)})}return new(u||(u=Promise))(function(g,m){function x(y){try{h(f.next(y))}catch(v){m(v)}}function b(y){try{h(f.throw(y))}catch(v){m(v)}}function h(y){y.done?g(y.value):d(y.value).then(x,b)}h((f=f.apply(l,c||[])).next())})};Object.defineProperty(dn,"__esModule",{value:!0}),dn.ValidationError=dn.ApiError=void 0,dn.defaultResponseHandler=o,dn.resultResponseHandler=i;const t=Tf(),r="x-fal-request-id";class n extends Error{constructor({message:c,status:u,body:f,requestId:d,timeoutType:g}){super(c),this.name="ApiError",this.status=u,this.body=f,this.requestId=d||"",this.timeoutType=g}get isUserTimeout(){return this.status===504&&this.timeoutType==="user"}}dn.ApiError=n;class a extends n{constructor(c){super(c),this.name="ValidationError"}get fieldErrors(){return typeof this.body.detail=="string"?[{loc:["body"],msg:this.body.detail,type:"value_error"}]:this.body.detail||[]}getFieldErrors(c){return this.fieldErrors.filter(u=>u.loc[u.loc.length-1]===c)}}dn.ValidationError=a;function o(l){return e(this,void 0,void 0,function*(){var c;const{status:u,statusText:f}=l,d=(c=l.headers.get("Content-Type"))!==null&&c!==void 0?c:"",g=l.headers.get(r)||void 0,m=l.headers.get(t.REQUEST_TIMEOUT_TYPE_HEADER)||void 0;if(!l.ok){if(d.includes("application/json")){const x=yield l.json(),b=u===422?a:n;throw new b({message:x.message||f,status:u,body:x,requestId:g,timeoutType:m})}throw new n({message:`HTTP ${u}: ${f}`,status:u,requestId:g,timeoutType:m})}return d.includes("application/json")?l.json():d.includes("text/html")?l.text():d.includes("application/octet-stream")?l.arrayBuffer():l.text()})}function i(l){return e(this,void 0,void 0,function*(){return{data:yield o(l),requestId:l.headers.get(r)||""}})}return dn}var ko={},Ur={},wm;function js(){if(wm)return Ur;wm=1;var e=Ur&&Ur.__awaiter||function(d,g,m,x){function b(h){return h instanceof m?h:new m(function(y){y(h)})}return new(m||(m=Promise))(function(h,y){function v(k){try{S(x.next(k))}catch(j){y(j)}}function I(k){try{S(x.throw(k))}catch(j){y(j)}}function S(k){k.done?h(k.value):b(k.value).then(v,I)}S((x=x.apply(d,g||[])).next())})};Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.ensureEndpointIdFormat=t,Ur.parseEndpointId=n,Ur.resolveEndpointPath=a,Ur.isValidUrl=o,Ur.throttle=i,Ur.isReact=c,Ur.isPlainObject=u,Ur.sleep=f;function t(d){if(d.split("/").length>1)return d;const[,m,x]=/^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(d)||[];if(m&&x)return`${m}/${x}`;throw new Error(`Invalid app id: ${d}. Must be in the format <appOwner>/<appId>`)}const r=["workflows","comfy"];function n(d){const m=t(d).split("/");return r.includes(m[0])?{owner:m[1],alias:m[2],path:m.slice(3).join("/")||void 0,namespace:m[0]}:{owner:m[0],alias:m[1],path:m.slice(2).join("/")||void 0}}function a(d,g,m){if(g)return`/${g.replace(/^\/+/,"")}`;if(!d.endsWith(m))return m}function o(d){try{const{host:g}=new URL(d);return/(fal\.(ai|run))$/.test(g)}catch{return!1}}function i(d,g,m=!1){let x,b;return(...h)=>{!b&&m?(d(...h),b=Date.now()):(x&&clearTimeout(x),x=setTimeout(()=>{Date.now()-b>=g&&(d(...h),b=Date.now())},g-(Date.now()-b)))}}let l;function c(){if(l===void 0){const d=new Error().stack;l=!!d&&(d.includes("node_modules/react-dom/")||d.includes("node_modules/next/"))}return l}function u(d){return!!d&&Object.getPrototypeOf(d)===Object.prototype}function f(d){return e(this,void 0,void 0,function*(){return new Promise(g=>setTimeout(g,d))})}return Ur}var km;function qc(){return km||(km=1,(function(e){var t=ko&&ko.__awaiter||function(l,c,u,f){function d(g){return g instanceof u?g:new u(function(m){m(g)})}return new(u||(u=Promise))(function(g,m){function x(y){try{h(f.next(y))}catch(v){m(v)}}function b(y){try{h(f.throw(y))}catch(v){m(v)}}function h(y){y.done?g(y.value):d(y.value).then(x,b)}h((f=f.apply(l,c||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_RETRY_OPTIONS=e.DEFAULT_RETRYABLE_STATUS_CODES=void 0,e.isRetryableError=a,e.calculateBackoffDelay=o,e.executeWithRetry=i;const r=ba(),n=js();e.DEFAULT_RETRYABLE_STATUS_CODES=[429,502,503,504],e.DEFAULT_RETRY_OPTIONS={maxRetries:3,baseDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:e.DEFAULT_RETRYABLE_STATUS_CODES,enableJitter:!0};function a(l,c){return!(l instanceof r.ApiError)||l.isUserTimeout?!1:c.includes(l.status)}function o(l,c,u,f,d){const g=Math.min(c*Math.pow(f,l),u);if(d){const m=.25*g*(Math.random()*2-1);return Math.max(0,g+m)}return g}function i(l,c,u){return t(this,void 0,void 0,function*(){const f={totalAttempts:0,totalDelay:0};let d;for(let g=0;g<=c.maxRetries;g++){f.totalAttempts++;try{return{result:yield l(),metrics:f}}catch(m){if(d=m,f.lastError=m,g===c.maxRetries||!a(m,c.retryableStatusCodes))throw m;const x=o(g,c.baseDelay,c.maxDelay,c.backoffMultiplier,c.enableJitter);f.totalDelay+=x,u&&u(g+1,m,x),yield(0,n.sleep)(x)}}throw d})}})(ko)),ko}var Io={};const Vk="@fal-ai/client",Kk="1.10.0",Xk={name:Vk,version:Kk};var Im;function Mf(){if(Im)return Io;Im=1,Object.defineProperty(Io,"__esModule",{value:!0}),Io.isBrowser=e,Io.getUserAgent=r;function e(){return typeof window<"u"&&typeof window.document<"u"}let t=null;function r(){if(t!==null)return t;const n=Xk;return t=`${n.name}/${n.version}`,t}return Io}var Cm;function Ef(){return Cm||(Cm=1,(function(e){var t={};Object.defineProperty(e,"__esModule",{value:!0}),e.credentialsFromEnv=void 0,e.resolveDefaultFetch=i,e.createConfig=f,e.getRestApiUrl=d;const r=Ip(),n=ba(),a=qc(),o=Mf();function i(){if(typeof fetch>"u")throw new Error("Your environment does not support fetch. Please provide your own fetch implementation.");return fetch}function l(){return typeof process<"u"&&t&&(typeof t.FAL_KEY<"u"||typeof t.FAL_KEY_ID<"u"&&typeof t.FAL_KEY_SECRET<"u")}const c=()=>{if(l())return typeof t.FAL_KEY<"u"?t.FAL_KEY:t.FAL_KEY_ID?`${t.FAL_KEY_ID}:${t.FAL_KEY_SECRET}`:void 0};e.credentialsFromEnv=c;const u={credentials:e.credentialsFromEnv,suppressLocalCredentialsWarning:!1,requestMiddleware:g=>Promise.resolve(g),responseHandler:n.defaultResponseHandler,retry:a.DEFAULT_RETRY_OPTIONS};function f(g){var m;let x=Object.assign(Object.assign(Object.assign({},u),g),{fetch:(m=g.fetch)!==null&&m!==void 0?m:i(),retry:Object.assign(Object.assign({},a.DEFAULT_RETRY_OPTIONS),g.retry||{})});if(g.proxyUrl){const v=typeof g.proxyUrl=="string"?{url:g.proxyUrl}:g.proxyUrl;x=Object.assign(Object.assign({},x),{requestMiddleware:(0,r.withMiddleware)(x.requestMiddleware,(0,r.withProxy)({targetUrl:v.url,when:v.when}))})}const{credentials:b,suppressLocalCredentialsWarning:h}=x,y=typeof b=="function"?b():b;return(0,o.isBrowser)()&&y&&!h&&console.warn("The fal credentials are exposed in the browser's environment. That's not recommended for production use cases."),x}function d(){return"https://rest.fal.ai"}})(zd)),zd}var $n={},zn={},jm;function zi(){if(jm)return zn;jm=1;var e=zn&&zn.__awaiter||function(c,u,f,d){function g(m){return m instanceof f?m:new f(function(x){x(m)})}return new(f||(f=Promise))(function(m,x){function b(v){try{y(d.next(v))}catch(I){x(I)}}function h(v){try{y(d.throw(v))}catch(I){x(I)}}function y(v){v.done?m(v.value):g(v.value).then(b,h)}y((d=d.apply(c,u||[])).next())})},t=zn&&zn.__rest||function(c,u){var f={};for(var d in c)Object.prototype.hasOwnProperty.call(c,d)&&u.indexOf(d)<0&&(f[d]=c[d]);if(c!=null&&typeof Object.getOwnPropertySymbols=="function")for(var g=0,d=Object.getOwnPropertySymbols(c);g<d.length;g++)u.indexOf(d[g])<0&&Object.prototype.propertyIsEnumerable.call(c,d[g])&&(f[d[g]]=c[d[g]]);return f};Object.defineProperty(zn,"__esModule",{value:!0}),zn.dispatchRequest=i,zn.buildUrl=l;const r=qc(),n=Mf(),a=js(),o=typeof navigator<"u"&&(navigator==null?void 0:navigator.userAgent)==="Cloudflare-Workers";function i(c){return e(this,void 0,void 0,function*(){var u;const{targetUrl:f,input:d,config:g,options:m={}}=c,{credentials:x,requestMiddleware:b,responseHandler:h,fetch:y}=g,v=Object.assign(Object.assign({},g.retry),m.retry||{}),I=()=>e(this,void 0,void 0,function*(){var k,j,A;const N=(0,n.isBrowser)()?{}:{"User-Agent":(0,n.getUserAgent)()},C=typeof x=="function"?x():x,{method:T,url:R,headers:U}=yield b({method:((j=(k=c.method)!==null&&k!==void 0?k:m.method)!==null&&j!==void 0?j:"post").toUpperCase(),url:f,headers:c.headers}),W=C?{Authorization:`Key ${C}`}:{},F=Object.assign(Object.assign(Object.assign(Object.assign({},W),{Accept:"application/json","Content-Type":"application/json"}),N),U??{}),{responseHandler:_,retry:O}=m,J=t(m,["responseHandler","retry"]),H=yield y(R,Object.assign(Object.assign(Object.assign(Object.assign({},J),{method:T,headers:Object.assign(Object.assign({},F),(A=J.headers)!==null&&A!==void 0?A:{})}),!o&&{mode:"cors"}),{signal:m.signal,body:T.toLowerCase()!=="get"&&d?JSON.stringify(d):void 0}));return yield(_??h)(H)});let S;for(let k=0;k<=v.maxRetries;k++)try{return yield I()}catch(j){if(S=j,k===v.maxRetries||!(0,r.isRetryableError)(j,v.retryableStatusCodes)||((u=m.signal)===null||u===void 0?void 0:u.aborted))throw j;const N=(0,r.calculateBackoffDelay)(k,v.baseDelay,v.maxDelay,v.backoffMultiplier,v.enableJitter);yield(0,a.sleep)(N)}throw S})}function l(c,u={}){var f,d;const g=((f=u.method)!==null&&f!==void 0?f:"post").toLowerCase(),m=((d=u.path)!==null&&d!==void 0?d:"").replace(/^\//,"").replace(/\/{2,}/,"/"),x=u.input,b=Object.assign(Object.assign({},u.query||{}),g==="get"?x:{}),h=Object.keys(b).length>0?`?${new URLSearchParams(b).toString()}`:"";if((0,a.isValidUrl)(c))return`${c.endsWith("/")?c:`${c}/`}${m}${h}`;const y=(0,a.ensureEndpointIdFormat)(c);return`${`https://${u.subdomain?`${u.subdomain}.`:""}fal.run/${y}/${m}`.replace(/\/$/,"")}${h}`}return zn}var Co={},Sm;function Cp(){return Sm||(Sm=1,(function(e){var t=Co&&Co.__awaiter||function(b,h,y,v){function I(S){return S instanceof y?S:new y(function(k){k(S)})}return new(y||(y=Promise))(function(S,k){function j(C){try{N(v.next(C))}catch(T){k(T)}}function A(C){try{N(v.throw(C))}catch(T){k(T)}}function N(C){C.done?S(C.value):I(C.value).then(j,A)}N((v=v.apply(b,h||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.OBJECT_LIFECYCYLE_PREFERENCE_HEADER=void 0,e.getExpirationDurationSeconds=i,e.buildObjectLifecycleHeaders=c,e.createStorageClient=x;const r=Ef(),n=zi(),a=js();e.OBJECT_LIFECYCYLE_PREFERENCE_HEADER="x-fal-object-lifecycle-preference";const o={never:void 0,immediate:60,"1h":3600,"1d":86400,"7d":604800,"30d":2592e3,"1y":31536e3};function i(b){const{expiresIn:h}=b;if(h!==void 0)return typeof h=="number"?h:o[h]}function l(b){if(!b)return;const h=i(b),y={};return h!==void 0&&(y.expiration_duration_seconds=h),b.initialAcl!==void 0&&(y.initial_acl=b.initialAcl),Object.keys(y).length>0?y:void 0}function c(b){const h=l(b);return h?{[e.OBJECT_LIFECYCYLE_PREFERENCE_HEADER]:JSON.stringify(h)}:{}}function u(b){var h;const[,y]=b.split("/");return(h=y.split(/[-;]/)[0])!==null&&h!==void 0?h:"bin"}function f(b,h,y,v){return t(this,void 0,void 0,function*(){const I=b.name||`${Date.now()}.${u(y)}`,S={},k=l(v);return k&&(S["X-Fal-Object-Lifecycle"]=JSON.stringify(k)),yield(0,n.dispatchRequest)({method:"POST",targetUrl:`${(0,r.getRestApiUrl)()}/storage/upload/initiate?storage_type=fal-cdn-v3`,input:{content_type:y,file_name:I},config:h,headers:S})})}function d(b,h,y,v){return t(this,void 0,void 0,function*(){const I=b.name||`${Date.now()}.${u(y)}`,S={},k=l(v);return k&&(S["X-Fal-Object-Lifecycle"]=JSON.stringify(k)),yield(0,n.dispatchRequest)({method:"POST",targetUrl:`${(0,r.getRestApiUrl)()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`,input:{content_type:y,file_name:I},config:h,headers:S})})}function g(b,h,y){return t(this,arguments,void 0,function*(v,I,S,k=3){if(k===0)throw new Error("Part upload failed, retries exhausted");const{fetch:j,responseHandler:A}=S;try{const N=yield j(v,{method:"PUT",body:I});return yield A(N)}catch{return yield g(v,I,S,k-1)}})}function m(b,h,y){return t(this,void 0,void 0,function*(){const{fetch:v,responseHandler:I}=h,S=b.type||"application/octet-stream",{upload_url:k,file_url:j}=yield d(b,h,S,y),A=10*1024*1024,N=Math.ceil(b.size/A),C=new URL(k),T=[];for(let W=0;W<N;W++){const F=W*A,_=Math.min(F+A,b.size),O=b.slice(F,_),J=W+1,H=`${C.origin}${C.pathname}/${J}${C.search}`;T.push(yield g(H,O,h))}const R=`${C.origin}${C.pathname}/complete${C.search}`,U=yield v(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:T.map(W=>({partNumber:W.partNumber,etag:W.etag}))})});return yield I(U),j})}function x({config:b}){const h={upload:(y,v)=>t(this,void 0,void 0,function*(){const I=v==null?void 0:v.lifecycle;if(y.size>94371840)return yield m(y,b,I);const S=y.type||"application/octet-stream",{fetch:k,responseHandler:j}=b,{upload_url:A,file_url:N}=yield f(y,b,S,I),C=yield k(A,{method:"PUT",body:y,headers:{"Content-Type":y.type||"application/octet-stream"}});return yield j(C),N}),transformInput:y=>t(this,void 0,void 0,function*(){if(Array.isArray(y))return Promise.all(y.map(v=>h.transformInput(v)));if(y instanceof Blob)return yield h.upload(y);if((0,a.isPlainObject)(y)){const I=Object.entries(y).map(k=>t(this,[k],void 0,function*([j,A]){return[j,yield h.transformInput(A)]})),S=yield Promise.all(I);return Object.fromEntries(S)}return y})};return h}})(Co)),Co}var Jr={},yl={},Nm;function qk(){if(Nm)return yl;Nm=1,Object.defineProperty(yl,"__esModule",{value:!0});function e(n){let a,o,i,l,c,u,f;return d(),{feed:g,reset:d};function d(){a=!0,o="",i=0,l=-1,c=void 0,u=void 0,f=""}function g(x){o=o?o+x:x,a&&r(o)&&(o=o.slice(t.length)),a=!1;const b=o.length;let h=0,y=!1;for(;h<b;){y&&(o[h]===`
|
|
6
|
+
`&&++h,y=!1);let v=-1,I=l,S;for(let k=i;v<0&&k<b;++k)S=o[k],S===":"&&I<0?I=k-h:S==="\r"?(y=!0,v=k-h):S===`
|
|
7
|
+
`&&(v=k-h);if(v<0){i=b-h,l=I;break}else i=0,l=-1;m(o,h,I,v),h+=v+1}h===b?o="":h>0&&(o=o.slice(h))}function m(x,b,h,y){if(y===0){f.length>0&&(n({type:"event",id:c,event:u||void 0,data:f.slice(0,-1)}),f="",c=void 0),u=void 0;return}const v=h<0,I=x.slice(b,b+(v?y:h));let S=0;v?S=y:x[b+h+1]===" "?S=h+2:S=h+1;const k=b+S,j=y-S,A=x.slice(k,k+j).toString();if(I==="data")f+=A?"".concat(A,`
|
|
8
|
+
`):`
|
|
9
|
+
`;else if(I==="event")u=A;else if(I==="id"&&!A.includes("\0"))c=A;else if(I==="retry"){const N=parseInt(A,10);Number.isNaN(N)||n({type:"reconnect-interval",value:N})}}}const t=[239,187,191];function r(n){return t.every((a,o)=>n.charCodeAt(o)===a)}return yl.createParser=e,yl}var jo={},Am;function jp(){return Am||(Am=1,(function(e){var t=jo&&jo.__awaiter||function(i,l,c,u){function f(d){return d instanceof c?d:new c(function(g){g(d)})}return new(c||(c=Promise))(function(d,g){function m(h){try{b(u.next(h))}catch(y){g(y)}}function x(h){try{b(u.throw(h))}catch(y){g(y)}}function b(h){h.done?d(h.value):f(h.value).then(m,x)}b((u=u.apply(i,l||[])).next())})};Object.defineProperty(e,"__esModule",{value:!0}),e.TOKEN_EXPIRATION_SECONDS=void 0,e.getTemporaryAuthToken=o;const r=Ef(),n=zi(),a=js();e.TOKEN_EXPIRATION_SECONDS=120;function o(i,l){return t(this,void 0,void 0,function*(){const c=(0,a.parseEndpointId)(i),u=yield(0,n.dispatchRequest)({method:"POST",targetUrl:`${(0,r.getRestApiUrl)()}/tokens/`,config:l,input:{allowed_apps:[c.alias],token_expiration:e.TOKEN_EXPIRATION_SECONDS}});return typeof u!="string"&&u.detail?u.detail:u})}})(jo)),jo}var Pm;function Sp(){if(Pm)return Jr;Pm=1;var e=Jr&&Jr.__awaiter||function(g,m,x,b){function h(y){return y instanceof x?y:new x(function(v){v(y)})}return new(x||(x=Promise))(function(y,v){function I(j){try{k(b.next(j))}catch(A){v(A)}}function S(j){try{k(b.throw(j))}catch(A){v(A)}}function k(j){j.done?y(j.value):h(j.value).then(I,S)}k((b=b.apply(g,m||[])).next())})},t=Jr&&Jr.__await||function(g){return this instanceof t?(this.v=g,this):new t(g)},r=Jr&&Jr.__asyncGenerator||function(g,m,x){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var b=x.apply(g,m||[]),h,y=[];return h={},I("next"),I("throw"),I("return",v),h[Symbol.asyncIterator]=function(){return this},h;function v(C){return function(T){return Promise.resolve(T).then(C,A)}}function I(C,T){b[C]&&(h[C]=function(R){return new Promise(function(U,W){y.push([C,R,U,W])>1||S(C,R)})},T&&(h[C]=T(h[C])))}function S(C,T){try{k(b[C](T))}catch(R){N(y[0][3],R)}}function k(C){C.value instanceof t?Promise.resolve(C.value.v).then(j,A):N(y[0][2],C)}function j(C){S("next",C)}function A(C){S("throw",C)}function N(C,T){C(T),y.shift(),y.length&&S(y[0][0],y[0][1])}};Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.FalStream=void 0,Jr.createStreamingClient=d;const n=qk(),a=jp(),o=zi(),i=ba(),l=js(),c="text/event-stream",u=15*1e3;class f{constructor(m,x,b){var h;this.listeners=new Map,this.buffer=[],this.currentData=void 0,this.lastEventTimestamp=0,this.streamClosed=!1,this._requestId=null,this.abortController=new AbortController,this.start=()=>e(this,void 0,void 0,function*(){var y,v,I;const{endpointId:S,options:k}=this,{input:j,method:A="post",connectionMode:N="server",tokenProvider:C}=k;try{if(N==="client"){const T=(0,l.ensureEndpointIdFormat)(S),R=(y=(0,l.resolveEndpointPath)(S,void 0,"/stream"))!==null&&y!==void 0?y:"",W=yield(C?()=>C(`${T}${R}`):()=>(console.warn('[fal.stream] Using the default token provider is deprecated. Please provide a `tokenProvider` function when using `connectionMode: "client"`. See https://docs.fal.ai/fal-client/authentication for more information.'),(0,a.getTemporaryAuthToken)(S,this.config)))(),{fetch:F}=this.config,_=new URL(this.url);_.searchParams.set("fal_jwt_token",W);const O=yield F(_.toString(),{method:A.toUpperCase(),headers:{accept:(v=k.accept)!==null&&v!==void 0?v:c,"content-type":"application/json"},body:j&&A!=="get"?JSON.stringify(j):void 0,signal:this.abortController.signal});return this._requestId=O.headers.get("x-fal-request-id"),yield this.handleResponse(O)}return yield(0,o.dispatchRequest)({method:A.toUpperCase(),targetUrl:this.url,input:j,config:this.config,options:{headers:{accept:(I=k.accept)!==null&&I!==void 0?I:c},responseHandler:T=>e(this,void 0,void 0,function*(){return this._requestId=T.headers.get("x-fal-request-id"),yield this.handleResponse(T)}),signal:this.abortController.signal}})}catch(T){this.handleError(T)}}),this.handleResponse=y=>e(this,void 0,void 0,function*(){var v,I;if(!y.ok){try{yield(0,i.defaultResponseHandler)(y)}catch(R){this.emit("error",R)}return}const S=y.body;if(!S){this.emit("error",new i.ApiError({message:"Response body is empty.",status:400,body:void 0,requestId:this._requestId||void 0}));return}if(!((v=y.headers.get("content-type"))!==null&&v!==void 0?v:"").startsWith(c)){const R=S.getReader(),U=()=>{R.read().then(({done:W,value:F})=>{if(W){this.emit("done",this.currentData);return}this.buffer.push(F),this.currentData=F,this.emit("data",F),U()})};U();return}const j=new TextDecoder("utf-8"),A=y.body.getReader(),N=(0,n.createParser)(R=>{if(R.type==="event"){const U=R.data;try{const W=JSON.parse(U);this.buffer.push(W),this.currentData=W,this.emit("data",W),this.emit("message",W)}catch(W){this.emit("error",W)}}}),C=(I=this.options.timeout)!==null&&I!==void 0?I:u,T=()=>e(this,void 0,void 0,function*(){const{value:R,done:U}=yield A.read();this.lastEventTimestamp=Date.now(),N.feed(j.decode(R)),Date.now()-this.lastEventTimestamp>C&&this.emit("error",new i.ApiError({message:`Event stream timed out after ${(C/1e3).toFixed(0)} seconds with no messages.`,status:408,requestId:this._requestId||void 0})),U?this.emit("done",this.currentData):T().catch(this.handleError)});T().catch(this.handleError)}),this.handleError=y=>{var v;if(y.name==="AbortError"||this.signal.aborted)return;const I=y instanceof i.ApiError?y:new i.ApiError({message:(v=y.message)!==null&&v!==void 0?v:"An unknown error occurred",status:500,requestId:this._requestId||void 0});this.emit("error",I)},this.on=(y,v)=>{var I;this.listeners.has(y)||this.listeners.set(y,[]),(I=this.listeners.get(y))===null||I===void 0||I.push(v)},this.emit=(y,v)=>{const I=this.listeners.get(y)||[];for(const S of I)S(v)},this.done=()=>e(this,void 0,void 0,function*(){return this.donePromise}),this.abort=y=>{this.streamClosed||this.abortController.abort(y)},this.endpointId=m,this.config=x,this.url=(h=b.url)!==null&&h!==void 0?h:(0,o.buildUrl)(m,{path:(0,l.resolveEndpointPath)(m,void 0,"/stream"),query:b.queryParams}),this.options=b,this.donePromise=new Promise((y,v)=>{this.streamClosed&&v(new i.ApiError({message:"Streaming connection is already closed.",status:400,body:void 0,requestId:this._requestId||void 0})),this.signal.addEventListener("abort",()=>{var I;y((I=this.currentData)!==null&&I!==void 0?I:{})}),this.on("done",I=>{this.streamClosed=!0,y(I)}),this.on("error",I=>{this.streamClosed=!0,v(I)})}),b.signal&&b.signal.addEventListener("abort",()=>{this.abortController.abort()}),this.start().catch(this.handleError)}[Symbol.asyncIterator](){return r(this,arguments,function*(){let x=!0;const b=()=>x=!1;for(this.on("error",b),this.on("done",b);x||this.buffer.length>0;){const h=this.buffer.shift();h&&(yield yield t(h)),yield t(new Promise(y=>setTimeout(y,16)))}})}get signal(){return this.abortController.signal}get requestId(){return this._requestId}}Jr.FalStream=f;function d({config:g,storage:m}){return{stream(x,b){return e(this,void 0,void 0,function*(){const h=b.input?yield m.transformInput(b.input):void 0;return new f(x,g,Object.assign(Object.assign({},b),{input:h}))})}}}return Jr}var Tm;function Jk(){if(Tm)return $n;Tm=1;var e=$n&&$n.__awaiter||function(m,x,b,h){function y(v){return v instanceof b?v:new b(function(I){I(v)})}return new(b||(b=Promise))(function(v,I){function S(A){try{j(h.next(A))}catch(N){I(N)}}function k(A){try{j(h.throw(A))}catch(N){I(N)}}function j(A){A.done?v(A.value):y(A.value).then(S,k)}j((h=h.apply(m,x||[])).next())})},t=$n&&$n.__rest||function(m,x){var b={};for(var h in m)Object.prototype.hasOwnProperty.call(m,h)&&x.indexOf(h)<0&&(b[h]=m[h]);if(m!=null&&typeof Object.getOwnPropertySymbols=="function")for(var y=0,h=Object.getOwnPropertySymbols(m);y<h.length;y++)x.indexOf(h[y])<0&&Object.prototype.propertyIsEnumerable.call(m,h[y])&&(b[h[y]]=m[h[y]]);return b};Object.defineProperty($n,"__esModule",{value:!0}),$n.createQueueClient=void 0;const r=Tf(),n=zi(),a=ba(),o=qc(),i=Cp(),l=Sp(),c=js(),u=500,f={maxRetries:3,baseDelay:1e3,maxDelay:6e4,retryableStatusCodes:o.DEFAULT_RETRYABLE_STATUS_CODES},d={maxRetries:5,baseDelay:1e3,maxDelay:3e4,retryableStatusCodes:[...o.DEFAULT_RETRYABLE_STATUS_CODES,500]},g=({config:m,storage:x})=>{const b={submit(h,y){return e(this,void 0,void 0,function*(){const{webhookUrl:v,priority:I,hint:S,startTimeout:k,headers:j,storageSettings:A}=y,N=t(y,["webhookUrl","priority","hint","startTimeout","headers","storageSettings"]),C=y.input?yield x.transformInput(y.input):void 0,T=Object.fromEntries(Object.entries(j??{}).map(([R,U])=>[R.toLowerCase(),U]));return(0,n.dispatchRequest)({method:y.method,targetUrl:(0,n.buildUrl)(h,Object.assign(Object.assign({},N),{subdomain:"queue",query:v?{fal_webhook:v}:void 0})),headers:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},T),(0,i.buildObjectLifecycleHeaders)(A)),{[r.QUEUE_PRIORITY_HEADER]:I??"normal"}),S&&{[r.RUNNER_HINT_HEADER]:S}),(0,r.buildTimeoutHeaders)(k)),input:C,config:m,options:{signal:y.abortSignal,retry:f}})})},status(h,y){return e(this,arguments,void 0,function*(v,{requestId:I,logs:S=!1,abortSignal:k}){const j=(0,c.parseEndpointId)(v),A=j.namespace?`${j.namespace}/`:"";return(0,n.dispatchRequest)({method:"get",targetUrl:(0,n.buildUrl)(`${A}${j.owner}/${j.alias}`,{subdomain:"queue",query:{logs:S?"1":"0"},path:`/requests/${I}/status`}),config:m,options:{signal:k,retry:d}})})},streamStatus(h,y){return e(this,arguments,void 0,function*(v,{requestId:I,logs:S=!1,connectionMode:k}){const j=(0,c.parseEndpointId)(v),A=j.namespace?`${j.namespace}/`:"",N={logs:S?"1":"0"},C=(0,n.buildUrl)(`${A}${j.owner}/${j.alias}`,{subdomain:"queue",path:`/requests/${I}/status/stream`,query:N});return new l.FalStream(v,m,{url:C,method:"get",connectionMode:k,queryParams:N})})},subscribeToStatus(h,y){return e(this,void 0,void 0,function*(){const v=y.requestId,I=y.timeout;let S;const k=()=>{};if(y.mode==="streaming"){const j=yield b.streamStatus(h,{requestId:v,logs:y.logs,connectionMode:"connectionMode"in y?y.connectionMode:void 0}),A=[];I&&(S=setTimeout(()=>{throw j.abort(),b.cancel(h,{requestId:v}).catch(k),new Error(`Client timed out waiting for the request to complete after ${I}ms`)},I)),j.on("data",C=>{y.onQueueUpdate&&("logs"in C&&Array.isArray(C.logs)&&C.logs.length>0&&A.push(...C.logs),y.onQueueUpdate("logs"in C?Object.assign(Object.assign({},C),{logs:A}):C))});const N=yield j.done();return S&&clearTimeout(S),N}return new Promise((j,A)=>{var N;let C;const T="pollInterval"in y&&typeof y.pollInterval=="number"&&(N=y.pollInterval)!==null&&N!==void 0?N:u,R=()=>{S&&clearTimeout(S),C&&clearTimeout(C)};I&&(S=setTimeout(()=>{R(),b.cancel(h,{requestId:v}).catch(k),A(new Error(`Client timed out waiting for the request to complete after ${I}ms`))},I));const U=()=>e(this,void 0,void 0,function*(){var W;try{const F=yield b.status(h,{requestId:v,logs:(W=y.logs)!==null&&W!==void 0?W:!1,abortSignal:y.abortSignal});if(y.onQueueUpdate&&y.onQueueUpdate(F),F.status==="COMPLETED"){R(),j(F);return}C=setTimeout(U,T)}catch(F){R(),A(F)}});U().catch(A)})})},result(h,y){return e(this,arguments,void 0,function*(v,{requestId:I,abortSignal:S}){const k=(0,c.parseEndpointId)(v),j=k.namespace?`${k.namespace}/`:"";return(0,n.dispatchRequest)({method:"get",targetUrl:(0,n.buildUrl)(`${j}${k.owner}/${k.alias}`,{subdomain:"queue",path:`/requests/${I}`}),config:Object.assign(Object.assign({},m),{responseHandler:a.resultResponseHandler}),options:{signal:S,retry:f}})})},cancel(h,y){return e(this,arguments,void 0,function*(v,{requestId:I,abortSignal:S}){const k=(0,c.parseEndpointId)(v),j=k.namespace?`${k.namespace}/`:"";yield(0,n.dispatchRequest)({method:"put",targetUrl:(0,n.buildUrl)(`${j}${k.owner}/${k.alias}`,{subdomain:"queue",path:`/requests/${I}/cancel`}),config:m,options:{signal:S}})})}};return b};return $n.createQueueClient=g,$n}var Sa={};function Gk(e){const t=e.length;let r=0,n=0;for(;n<t;){let a=e.charCodeAt(n++);if((a&4294967168)===0){r++;continue}else if((a&4294965248)===0)r+=2;else{if(a>=55296&&a<=56319&&n<t){const o=e.charCodeAt(n);(o&64512)===56320&&(++n,a=((a&1023)<<10)+(o&1023)+65536)}(a&4294901760)===0?r+=3:r+=4}}return r}function Zk(e,t,r){const n=e.length;let a=r,o=0;for(;o<n;){let i=e.charCodeAt(o++);if((i&4294967168)===0){t[a++]=i;continue}else if((i&4294965248)===0)t[a++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&o<n){const l=e.charCodeAt(o);(l&64512)===56320&&(++o,i=((i&1023)<<10)+(l&1023)+65536)}(i&4294901760)===0?(t[a++]=i>>12&15|224,t[a++]=i>>6&63|128):(t[a++]=i>>18&7|240,t[a++]=i>>12&63|128,t[a++]=i>>6&63|128)}t[a++]=i&63|128}}const Qk=new TextEncoder,e1=50;function t1(e,t,r){Qk.encodeInto(e,t.subarray(r))}function r1(e,t,r){e.length>e1?t1(e,t,r):Zk(e,t,r)}const n1=4096;function Np(e,t,r){let n=t;const a=n+r,o=[];let i="";for(;n<a;){const l=e[n++];if((l&128)===0)o.push(l);else if((l&224)===192){const c=e[n++]&63;o.push((l&31)<<6|c)}else if((l&240)===224){const c=e[n++]&63,u=e[n++]&63;o.push((l&31)<<12|c<<6|u)}else if((l&248)===240){const c=e[n++]&63,u=e[n++]&63,f=e[n++]&63;let d=(l&7)<<18|c<<12|u<<6|f;d>65535&&(d-=65536,o.push(d>>>10&1023|55296),d=56320|d&1023),o.push(d)}else o.push(l);o.length>=n1&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const s1=new TextDecoder,a1=200;function o1(e,t,r){const n=e.subarray(t,t+r);return s1.decode(n)}function i1(e,t,r){return r>a1?o1(e,t,r):Np(e,t,r)}class Do{constructor(t,r){Ze(this,"type");Ze(this,"data");this.type=t,this.data=r}}class Tr extends Error{constructor(t){super(t);const r=Object.create(Tr.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Tr.name})}}const So=4294967295;function l1(e,t,r){const n=r/4294967296,a=r;e.setUint32(t,n),e.setUint32(t+4,a)}function Ap(e,t,r){const n=Math.floor(r/4294967296),a=r;e.setUint32(t,n),e.setUint32(t+4,a)}function Pp(e,t){const r=e.getInt32(t),n=e.getUint32(t+4);return r*4294967296+n}function c1(e,t){const r=e.getUint32(t),n=e.getUint32(t+4);return r*4294967296+n}const Tp=-1,d1=4294967296-1,u1=17179869184-1;function Mp({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=u1)if(t===0&&e<=d1){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e),r}else{const r=e/4294967296,n=e&4294967295,a=new Uint8Array(8),o=new DataView(a.buffer);return o.setUint32(0,t<<2|r&3),o.setUint32(4,n),a}else{const r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,t),Ap(n,4,e),r}}function Ep(e){const t=e.getTime(),r=Math.floor(t/1e3),n=(t-r*1e3)*1e6,a=Math.floor(n/1e9);return{sec:r+a,nsec:n-a*1e9}}function Rp(e){if(e instanceof Date){const t=Ep(e);return Mp(t)}else return null}function _p(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const r=t.getUint32(0),n=t.getUint32(4),a=(r&3)*4294967296+n,o=r>>>2;return{sec:a,nsec:o}}case 12:{const r=Pp(t,4),n=t.getUint32(0);return{sec:r,nsec:n}}default:throw new Tr(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}function Dp(e){const t=_p(e);return new Date(t.sec*1e3+t.nsec/1e6)}const f1={type:Tp,encode:Rp,decode:Dp},Dc=class Dc{constructor(){Ze(this,"__brand");Ze(this,"builtInEncoders",[]);Ze(this,"builtInDecoders",[]);Ze(this,"encoders",[]);Ze(this,"decoders",[]);this.register(f1)}register({type:t,encode:r,decode:n}){if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{const a=-1-t;this.builtInEncoders[a]=r,this.builtInDecoders[a]=n}}tryToEncode(t,r){for(let n=0;n<this.builtInEncoders.length;n++){const a=this.builtInEncoders[n];if(a!=null){const o=a(t,r);if(o!=null){const i=-1-n;return new Do(i,o)}}}for(let n=0;n<this.encoders.length;n++){const a=this.encoders[n];if(a!=null){const o=a(t,r);if(o!=null){const i=n;return new Do(i,o)}}}return t instanceof Do?t:null}decode(t,r,n){const a=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return a?a(t,r,n):new Do(r,t)}};Ze(Dc,"defaultCodec",new Dc);let ii=Dc;function g1(e){return e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer}function Pu(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):g1(e)?new Uint8Array(e):Uint8Array.from(e)}const m1=100,h1=2048;class Jc{constructor(t){Ze(this,"extensionCodec");Ze(this,"context");Ze(this,"useBigInt64");Ze(this,"maxDepth");Ze(this,"initialBufferSize");Ze(this,"sortKeys");Ze(this,"forceFloat32");Ze(this,"ignoreUndefined");Ze(this,"forceIntegerToFloat");Ze(this,"pos");Ze(this,"view");Ze(this,"bytes");Ze(this,"entered",!1);this.extensionCodec=(t==null?void 0:t.extensionCodec)??ii.defaultCodec,this.context=t==null?void 0:t.context,this.useBigInt64=(t==null?void 0:t.useBigInt64)??!1,this.maxDepth=(t==null?void 0:t.maxDepth)??m1,this.initialBufferSize=(t==null?void 0:t.initialBufferSize)??h1,this.sortKeys=(t==null?void 0:t.sortKeys)??!1,this.forceFloat32=(t==null?void 0:t.forceFloat32)??!1,this.ignoreUndefined=(t==null?void 0:t.ignoreUndefined)??!1,this.forceIntegerToFloat=(t==null?void 0:t.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Jc({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(t){if(this.entered)return this.clone().encodeSharedRef(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(t){if(this.entered)return this.clone().encode(t);try{return this.entered=!0,this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(t,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(t):this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.useBigInt64&&typeof t=="bigint"?this.encodeBigInt64(t):this.encodeObject(t,r)}ensureBufferSizeToWrite(t){const r=this.pos+t;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(t){const r=new ArrayBuffer(t),n=new Uint8Array(r),a=new DataView(r);n.set(this.bytes),this.view=a,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(t){t===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(t){!this.forceIntegerToFloat&&Number.isSafeInteger(t)?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):this.useBigInt64?this.encodeNumberAsFloat(t):(this.writeU8(211),this.writeI64(t)):this.encodeNumberAsFloat(t)}encodeNumberAsFloat(t){this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))}encodeBigInt64(t){t>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(t)):(this.writeU8(211),this.writeBigInt64(t))}writeStringHeader(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error(`Too long string: ${t} bytes in UTF-8`)}encodeString(t){const n=Gk(t);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),r1(t,this.bytes,this.pos),this.pos+=n}encodeObject(t,r){const n=this.extensionCodec.tryToEncode(t,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(t))this.encodeArray(t,r);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(t)}`)}encodeBinary(t){const r=t.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const n=Pu(t);this.writeU8a(n)}encodeArray(t,r){const n=t.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const a of t)this.doEncode(a,r+1)}countWithoutUndefined(t,r){let n=0;for(const a of r)t[a]!==void 0&&n++;return n}encodeMap(t,r){const n=Object.keys(t);this.sortKeys&&n.sort();const a=this.ignoreUndefined?this.countWithoutUndefined(t,n):n.length;if(a<16)this.writeU8(128+a);else if(a<65536)this.writeU8(222),this.writeU16(a);else if(a<4294967296)this.writeU8(223),this.writeU32(a);else throw new Error(`Too large map object: ${a}`);for(const o of n){const i=t[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,r+1))}}encodeExtension(t){if(typeof t.data=="function"){const n=t.data(this.pos+6),a=n.length;if(a>=4294967296)throw new Error(`Too large extension object: ${a}`);this.writeU8(201),this.writeU32(a),this.writeI8(t.type),this.writeU8a(n);return}const r=t.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(t.type),this.writeU8a(t.data)}writeU8(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++}writeU8a(t){const r=t.length;this.ensureBufferSizeToWrite(r),this.bytes.set(t,this.pos),this.pos+=r}writeI8(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++}writeU16(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2}writeI16(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2}writeU32(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4}writeI32(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4}writeF32(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4}writeF64(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8}writeU64(t){this.ensureBufferSizeToWrite(8),l1(this.view,this.pos,t),this.pos+=8}writeI64(t){this.ensureBufferSizeToWrite(8),Ap(this.view,this.pos,t),this.pos+=8}writeBigUint64(t){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,t),this.pos+=8}writeBigInt64(t){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,t),this.pos+=8}}function p1(e,t){return new Jc(t).encodeSharedRef(e)}function Hd(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const x1=16,b1=16;class y1{constructor(t=x1,r=b1){Ze(this,"hit",0);Ze(this,"miss",0);Ze(this,"caches");Ze(this,"maxKeyLength");Ze(this,"maxLengthPerKey");this.maxKeyLength=t,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(t){return t>0&&t<=this.maxKeyLength}find(t,r,n){const a=this.caches[n-1];e:for(const o of a){const i=o.bytes;for(let l=0;l<n;l++)if(i[l]!==t[r+l])continue e;return o.str}return null}store(t,r){const n=this.caches[t.length-1],a={bytes:t,str:r};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=a:n.push(a)}decode(t,r,n){const a=this.find(t,r,n);if(a!=null)return this.hit++,a;this.miss++;const o=Np(t,r,n),i=Uint8Array.prototype.slice.call(t,r,r+n);return this.store(i,o),o}}const Tu="array",Wo="map_key",Lp="map_value",v1=e=>{if(typeof e=="string"||typeof e=="number")return e;throw new Tr("The type of key must be string or number but "+typeof e)};class w1{constructor(){Ze(this,"stack",[]);Ze(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(t){const r=this.getUninitializedStateFromPool();r.type=Tu,r.position=0,r.size=t,r.array=new Array(t)}pushMapState(t){const r=this.getUninitializedStateFromPool();r.type=Wo,r.readCount=0,r.size=t,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const t={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(t)}return this.stack[this.stackHeadPosition]}release(t){if(this.stack[this.stackHeadPosition]!==t)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(t.type===Tu){const n=t;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(t.type===Wo||t.type===Lp){const n=t;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const No=-1,Rf=new DataView(new ArrayBuffer(0)),k1=new Uint8Array(Rf.buffer);try{Rf.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Mm=new RangeError("Insufficient data"),I1=new y1;class Ss{constructor(t){Ze(this,"extensionCodec");Ze(this,"context");Ze(this,"useBigInt64");Ze(this,"rawStrings");Ze(this,"maxStrLength");Ze(this,"maxBinLength");Ze(this,"maxArrayLength");Ze(this,"maxMapLength");Ze(this,"maxExtLength");Ze(this,"keyDecoder");Ze(this,"mapKeyConverter");Ze(this,"totalPos",0);Ze(this,"pos",0);Ze(this,"view",Rf);Ze(this,"bytes",k1);Ze(this,"headByte",No);Ze(this,"stack",new w1);Ze(this,"entered",!1);this.extensionCodec=(t==null?void 0:t.extensionCodec)??ii.defaultCodec,this.context=t==null?void 0:t.context,this.useBigInt64=(t==null?void 0:t.useBigInt64)??!1,this.rawStrings=(t==null?void 0:t.rawStrings)??!1,this.maxStrLength=(t==null?void 0:t.maxStrLength)??So,this.maxBinLength=(t==null?void 0:t.maxBinLength)??So,this.maxArrayLength=(t==null?void 0:t.maxArrayLength)??So,this.maxMapLength=(t==null?void 0:t.maxMapLength)??So,this.maxExtLength=(t==null?void 0:t.maxExtLength)??So,this.keyDecoder=(t==null?void 0:t.keyDecoder)!==void 0?t.keyDecoder:I1,this.mapKeyConverter=(t==null?void 0:t.mapKeyConverter)??v1}clone(){return new Ss({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=No,this.stack.reset()}setBuffer(t){const r=Pu(t);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(t){if(this.headByte===No&&!this.hasRemaining(1))this.setBuffer(t);else{const r=this.bytes.subarray(this.pos),n=Pu(t),a=new Uint8Array(r.length+n.length);a.set(r),a.set(n,r.length),this.setBuffer(a)}}hasRemaining(t){return this.view.byteLength-this.pos>=t}createExtraByteError(t){const{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.byteLength} byte(s) found at buffer[${t}]`)}decode(t){if(this.entered)return this.clone().decode(t);try{this.entered=!0,this.reinitializeState(),this.setBuffer(t);const r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(t){if(this.entered){yield*this.clone().decodeMulti(t);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(t);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(t){if(this.entered)return this.clone().decodeAsync(t);try{this.entered=!0;let r=!1,n;for await(const l of t){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(l);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:a,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${Hd(a)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(t){return this.decodeMultiAsync(t,!0)}decodeStream(t){return this.decodeMultiAsync(t,!1)}async*decodeMultiAsync(t,r){if(this.entered){yield*this.clone().decodeMultiAsync(t,r);return}try{this.entered=!0;let n=r,a=-1;for await(const o of t){if(r&&a===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),n&&(a=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--a!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const t=this.readHeadByte();let r;if(t>=224)r=t-256;else if(t<192)if(t<128)r=t;else if(t<144){const a=t-128;if(a!==0){this.pushMapState(a),this.complete();continue e}else r={}}else if(t<160){const a=t-144;if(a!==0){this.pushArrayState(a),this.complete();continue e}else r=[]}else{const a=t-160;r=this.decodeString(a,0)}else if(t===192)r=null;else if(t===194)r=!1;else if(t===195)r=!0;else if(t===202)r=this.readF32();else if(t===203)r=this.readF64();else if(t===204)r=this.readU8();else if(t===205)r=this.readU16();else if(t===206)r=this.readU32();else if(t===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(t===208)r=this.readI8();else if(t===209)r=this.readI16();else if(t===210)r=this.readI32();else if(t===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(t===217){const a=this.lookU8();r=this.decodeString(a,1)}else if(t===218){const a=this.lookU16();r=this.decodeString(a,2)}else if(t===219){const a=this.lookU32();r=this.decodeString(a,4)}else if(t===220){const a=this.readU16();if(a!==0){this.pushArrayState(a),this.complete();continue e}else r=[]}else if(t===221){const a=this.readU32();if(a!==0){this.pushArrayState(a),this.complete();continue e}else r=[]}else if(t===222){const a=this.readU16();if(a!==0){this.pushMapState(a),this.complete();continue e}else r={}}else if(t===223){const a=this.readU32();if(a!==0){this.pushMapState(a),this.complete();continue e}else r={}}else if(t===196){const a=this.lookU8();r=this.decodeBinary(a,1)}else if(t===197){const a=this.lookU16();r=this.decodeBinary(a,2)}else if(t===198){const a=this.lookU32();r=this.decodeBinary(a,4)}else if(t===212)r=this.decodeExtension(1,0);else if(t===213)r=this.decodeExtension(2,0);else if(t===214)r=this.decodeExtension(4,0);else if(t===215)r=this.decodeExtension(8,0);else if(t===216)r=this.decodeExtension(16,0);else if(t===199){const a=this.lookU8();r=this.decodeExtension(a,1)}else if(t===200){const a=this.lookU16();r=this.decodeExtension(a,2)}else if(t===201){const a=this.lookU32();r=this.decodeExtension(a,4)}else throw new Tr(`Unrecognized type byte: ${Hd(t)}`);this.complete();const n=this.stack;for(;n.length>0;){const a=n.top();if(a.type===Tu)if(a.array[a.position]=r,a.position++,a.position===a.size)r=a.array,n.release(a);else continue e;else if(a.type===Wo){if(r==="__proto__")throw new Tr("The key __proto__ is not allowed");a.key=this.mapKeyConverter(r),a.type=Lp;continue e}else if(a.map[a.key]=r,a.readCount++,a.readCount===a.size)r=a.map,n.release(a);else{a.key=null,a.type=Wo;continue e}}return r}}readHeadByte(){return this.headByte===No&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=No}readArraySize(){const t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new Tr(`Unrecognized array type byte: ${Hd(t)}`)}}}pushMapState(t){if(t>this.maxMapLength)throw new Tr(`Max length exceeded: map length (${t}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(t)}pushArrayState(t){if(t>this.maxArrayLength)throw new Tr(`Max length exceeded: array length (${t}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(t)}decodeString(t,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(t,r):this.decodeBinary(t,r)}decodeUtf8String(t,r){var o;if(t>this.maxStrLength)throw new Tr(`Max length exceeded: UTF-8 byte length (${t}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+t)throw Mm;const n=this.pos+r;let a;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(t))?a=this.keyDecoder.decode(this.bytes,n,t):a=i1(this.bytes,n,t),this.pos+=r+t,a}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Wo:!1}decodeBinary(t,r){if(t>this.maxBinLength)throw new Tr(`Max length exceeded: bin length (${t}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(t+r))throw Mm;const n=this.pos+r,a=this.bytes.subarray(n,n+t);return this.pos+=r+t,a}decodeExtension(t,r){if(t>this.maxExtLength)throw new Tr(`Max length exceeded: ext length (${t}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+r),a=this.decodeBinary(t,r+1);return this.extensionCodec.decode(a,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const t=this.view.getUint8(this.pos);return this.pos++,t}readI8(){const t=this.view.getInt8(this.pos);return this.pos++,t}readU16(){const t=this.view.getUint16(this.pos);return this.pos+=2,t}readI16(){const t=this.view.getInt16(this.pos);return this.pos+=2,t}readU32(){const t=this.view.getUint32(this.pos);return this.pos+=4,t}readI32(){const t=this.view.getInt32(this.pos);return this.pos+=4,t}readU64(){const t=c1(this.view,this.pos);return this.pos+=8,t}readI64(){const t=Pp(this.view,this.pos);return this.pos+=8,t}readU64AsBigInt(){const t=this.view.getBigUint64(this.pos);return this.pos+=8,t}readI64AsBigInt(){const t=this.view.getBigInt64(this.pos);return this.pos+=8,t}readF32(){const t=this.view.getFloat32(this.pos);return this.pos+=4,t}readF64(){const t=this.view.getFloat64(this.pos);return this.pos+=8,t}}function C1(e,t){return new Ss(t).decode(e)}function j1(e,t){return new Ss(t).decodeMulti(e)}function S1(e){return e[Symbol.asyncIterator]!=null}async function*N1(e){const t=e.getReader();try{for(;;){const{done:r,value:n}=await t.read();if(r)return;yield n}}finally{t.releaseLock()}}function _f(e){return S1(e)?e:N1(e)}async function A1(e,t){const r=_f(e);return new Ss(t).decodeAsync(r)}function P1(e,t){const r=_f(e);return new Ss(t).decodeArrayStream(r)}function T1(e,t){const r=_f(e);return new Ss(t).decodeStream(r)}const M1=Object.freeze(Object.defineProperty({__proto__:null,DecodeError:Tr,Decoder:Ss,EXT_TIMESTAMP:Tp,Encoder:Jc,ExtData:Do,ExtensionCodec:ii,decode:C1,decodeArrayStream:P1,decodeAsync:A1,decodeMulti:j1,decodeMultiStream:T1,decodeTimestampExtension:Dp,decodeTimestampToTimeSpec:_p,encode:p1,encodeDateToTimeSpec:Ep,encodeTimeSpecToTimestamp:Mp,encodeTimestampExtension:Rp},Symbol.toStringTag,{value:"Module"})),E1=Dv(M1);var Fr={},Em;function R1(){if(Em)return Fr;Em=1,Object.defineProperty(Fr,"__esModule",{value:!0});function e(K){return{enumerable:!0,value:K}}function t(K){return{enumerable:!0,writable:!0,value:K}}let r={},n=()=>!0,a=()=>({}),o=K=>K,i=(K,te,P,B)=>K.apply(P,B)&&te.apply(P,B),l=(K,te,P,[B,$])=>te.call(P,K.call(P,B,$),$),c=(K,te)=>Object.freeze(Object.create(K,te));function u(K,te,P){return K.reduce((B,$)=>function(...Q){return P(B,$,this,Q)},te)}function f(K){return c(this,{fn:e(K)})}let d={},g=f.bind(d),m=K=>g((te,P)=>!!~K(te,P)&&te),x={},b=f.bind(x);function h(K,te){return te.filter(P=>K.isPrototypeOf(P))}function y(K,te,...P){let B=u(h(x,P).map(Q=>Q.fn),n,i),$=u(h(d,P).map(Q=>Q.fn),o,l);return c(this,{from:e(K),to:e(te),guards:e(B),reducers:e($)})}let v={},I={},S=y.bind(v),k=y.bind(I,null);function j(K,te,P){return _(te,K,P,this.immediates)||K}function A(K){let te=new Map;for(let P of K)te.has(P.from)||te.set(P.from,[]),te.get(P.from).push(P);return te}let N={enter:o};function C(...K){let te=h(v,K),P=h(I,K),B={final:e(K.length===0),transitions:e(A(te))};return P.length&&(B.immediates=e(P),B.enter=e(j)),c(N,B)}let T={enter(K,te,P){let B=this.fn.call(te,te.context,P);return W.isPrototypeOf(B)?c(R,{machine:e(B),transitions:e(this.transitions)}).enter(K,te,P):(B.then($=>te.send({type:"done",data:$})).catch($=>te.send({type:"error",error:$})),K)}},R={enter(K,te,P){if(te.child=H(this.machine,B=>{te.onChange(B),te.child==B&&B.machine.state.value.final&&(delete te.child,te.send({type:"done",data:B.context}))},te.context,P),te.child.machine.state.value.final){let B=te.child.context;return delete te.child,_(te,K,{type:"done",data:B},this.transitions.get("done"))}return K}};function U(K,...te){let P=e(A(te));return W.isPrototypeOf(K)?c(R,{machine:e(K),transitions:P}):c(T,{fn:e(K),transitions:P})}let W={get state(){return{name:this.current,value:this.states[this.current]}}};function F(K,te,P=a){return typeof K!="string"&&(P=te||a,te=K,K=Object.keys(te)[0]),r._create&&r._create(K,te),c(W,{context:e(P),current:e(K),states:e(te)})}function _(K,te,P,B){let{context:$}=K;for(let{to:Q,guards:L,reducers:G}of B)if(L($,P)){K.context=G.call(K,$,P);let se=te.original||te,Y=c(se,{current:e(Q),original:{value:se}});return r._onEnter&&r._onEnter(te,Q,K.context,$,P),Y.state.value.enter(Y,K,P)}}function O(K,te){let P=te.type||te,{machine:B}=K,{value:$,name:Q}=B.state;return $.transitions.has(P)?_(K,B,te,$.transitions.get(P))||B:(r._send&&r._send(P,Q),B)}let J={send(K){this.machine=O(this,K),this.onChange(this)}};function H(K,te,P,B){let $=Object.create(J,{machine:t(K),context:t(K.context(P,B)),onChange:e(te)});return $.send=$.send.bind($),$.machine=$.machine.state.value.enter($.machine,$,B),$}return Fr.action=m,Fr.createMachine=F,Fr.d=r,Fr.guard=b,Fr.immediate=k,Fr.interpret=H,Fr.invoke=U,Fr.reduce=g,Fr.state=C,Fr.transition=S,Fr}var Rm;function _1(){if(Rm)return Sa;Rm=1;var e=Sa&&Sa.__awaiter||function(O,J,H,K){function te(P){return P instanceof H?P:new H(function(B){B(P)})}return new(H||(H=Promise))(function(P,B){function $(G){try{L(K.next(G))}catch(se){B(se)}}function Q(G){try{L(K.throw(G))}catch(se){B(se)}}function L(G){G.done?P(G.value):te(G.value).then($,Q)}L((K=K.apply(O,J||[])).next())})};Object.defineProperty(Sa,"__esModule",{value:!0}),Sa.createRealtimeClient=_;const t=E1,r=R1(),n=jp(),a=ba(),o=Mf(),i=js(),l=()=>({enqueuedMessage:void 0});function c(O){return O.token!==void 0}function u(O){return!c(O)}function f(O,J){return Object.assign(Object.assign({},O),{enqueuedMessage:J.message})}function d(O){return O.websocket&&O.websocket.readyState===WebSocket.OPEN&&O.websocket.close(),Object.assign(Object.assign({},O),{websocket:void 0})}function g(O,J){return O.websocket&&O.websocket.readyState===WebSocket.OPEN?(J.message instanceof Uint8Array||typeof J.message=="string"?O.websocket.send(J.message):O.websocket.send((0,t.encode)(J.message)),Object.assign(Object.assign({},O),{enqueuedMessage:void 0})):Object.assign(Object.assign({},O),{enqueuedMessage:J.message})}function m(O){return Object.assign(Object.assign({},O),{token:void 0})}function x(O,J){return Object.assign(Object.assign({},O),{token:J.token})}function b(O,J){return Object.assign(Object.assign({},O),{websocket:J.websocket})}const h=(0,r.createMachine)("idle",{idle:(0,r.state)((0,r.transition)("send","connecting",(0,r.reduce)(f)),(0,r.transition)("close","idle",(0,r.reduce)(d))),connecting:(0,r.state)((0,r.transition)("connecting","connecting"),(0,r.transition)("connected","active",(0,r.reduce)(b)),(0,r.transition)("connectionClosed","idle",(0,r.reduce)(d)),(0,r.transition)("send","connecting",(0,r.reduce)(f)),(0,r.transition)("close","idle",(0,r.reduce)(d)),(0,r.immediate)("authRequired",(0,r.guard)(u))),authRequired:(0,r.state)((0,r.transition)("initiateAuth","authInProgress"),(0,r.transition)("send","authRequired",(0,r.reduce)(f)),(0,r.transition)("close","idle",(0,r.reduce)(d))),authInProgress:(0,r.state)((0,r.transition)("authenticated","connecting",(0,r.reduce)(x)),(0,r.transition)("unauthorized","idle",(0,r.reduce)(m),(0,r.reduce)(d)),(0,r.transition)("send","authInProgress",(0,r.reduce)(f)),(0,r.transition)("close","idle",(0,r.reduce)(d))),active:(0,r.state)((0,r.transition)("send","active",(0,r.reduce)(g)),(0,r.transition)("authenticated","active",(0,r.reduce)(x)),(0,r.transition)("unauthorized","idle",(0,r.reduce)(m)),(0,r.transition)("connectionClosed","idle",(0,r.reduce)(m),(0,r.reduce)(d)),(0,r.transition)("close","idle",(0,r.reduce)(m),(0,r.reduce)(d)))},l);function y(O,{token:J,maxBuffering:H,path:K}){var te;if(H!==void 0&&(H<1||H>60))throw new Error("The `maxBuffering` must be between 1 and 60 (inclusive)");const P=new URLSearchParams({fal_jwt_token:J});H!==void 0&&P.set("max_buffering",H.toFixed(0));const B=(0,i.ensureEndpointIdFormat)(O),$=(te=(0,i.resolveEndpointPath)(O,K,"/realtime"))!==null&&te!==void 0?te:"";return`wss://fal.run/${B}${$}?${P.toString()}`}const v=128;function I(O){return O.status==="error"&&O.error==="Unauthorized"}const S={NORMAL_CLOSURE:1e3},k=new Map,j=new Map;function A(O,J,H){if(!k.has(O)){const K=(0,r.interpret)(h,H);k.set(O,{service:K,throttledSend:J>0?(0,i.throttle)(K.send,J,!0):K.send})}return k.get(O)}const N=()=>{},C={send:N,close:N};function T(O){return O.status!=="error"&&O.type!=="x-fal-message"&&!R(O)}function R(O){return O.type==="x-fal-error"}function U(O){return e(this,void 0,void 0,function*(){if(typeof O=="string")return JSON.parse(O);const J=H=>e(this,void 0,void 0,function*(){return H instanceof Uint8Array?H:H instanceof Blob?new Uint8Array(yield H.arrayBuffer()):new Uint8Array(H)});return O instanceof ArrayBuffer||O instanceof Uint8Array?(0,t.decode)(yield J(O)):O instanceof Blob?(0,t.decode)(yield J(O)):O})}function W(O){return O instanceof Uint8Array?O:(0,t.encode)(O)}function F({data:O,decodeMessage:J,onResult:H,onError:K,send:te}){const P=B=>{if(I(B)){te({type:"unauthorized",error:new Error("Unauthorized")});return}if(T(B)){H(B);return}if(R(B)){if(B.error==="TIMEOUT")return;K(new a.ApiError({message:`${B.error}: ${B.reason}`,status:400,body:B}));return}};Promise.resolve(J?J(O):O).then(P).catch(B=>{var $;K(new a.ApiError({message:($=B==null?void 0:B.message)!==null&&$!==void 0?$:"Failed to decode realtime message",status:400}))})}function _({config:O}){return{connect(J,H){const{clientOnly:K=(0,i.isReact)()&&!(0,o.isBrowser)(),connectionKey:te=crypto.randomUUID(),maxBuffering:P,path:B,throttleInterval:$=v,encodeMessage:Q,decodeMessage:L,tokenProvider:G,tokenExpirationSeconds:se}=H;if(K&&!(0,o.isBrowser)())return C;const Y=Q??(Ee=>W(Ee)),le=L??(Ee=>U(Ee));let ie,D,ue,ke=0;j.set(te,{decodeMessage:le,onError:H.onError,onResult:H.onResult});const we=()=>j.get(te),We=A(te,$,({context:Ee,machine:Ge,send:Xe})=>{var ht;const{enqueuedMessage:Pe,token:ne,websocket:ge}=Ee;if(D=Pe,Ge.current==="active"&&Pe&&(ge==null?void 0:ge.readyState)===WebSocket.OPEN&&Xe({type:"send",message:Pe}),Ge.current==="authRequired"&&ne===void 0&&ie!==Ge.current){Xe({type:"initiateAuth"}),ke++;const xe=ke,fe=(0,i.ensureEndpointIdFormat)(J),be=(ht=(0,i.resolveEndpointPath)(J,B,"/realtime"))!==null&&ht!==void 0?ht:"",Z=G?()=>G(`${fe}${be}`):()=>(console.warn("[fal.realtime] Using the default token provider is deprecated. Please provide a `tokenProvider` function to `fal.realtime.connect()`. See https://docs.fal.ai/model-apis/client#client-side-usage-with-token-provider for more information."),(0,n.getTemporaryAuthToken)(J,O)),de=G?se:n.TOKEN_EXPIRATION_SECONDS,he=de!==void 0?()=>{clearTimeout(ue);const pe=Math.round(de*.9*1e3);ue=setTimeout(()=>{xe===ke&&Z().then(Be=>{xe===ke&&(queueMicrotask(()=>{Xe({type:"authenticated",token:Be})}),he())}).catch(()=>{if(xe!==ke)return;const Be=Math.round(de*.05*1e3);ue=setTimeout(()=>{he()},Be)})},pe)}:N;Z().then(pe=>{queueMicrotask(()=>{Xe({type:"authenticated",token:pe})}),he()}).catch(pe=>{queueMicrotask(()=>{Xe({type:"unauthorized",error:pe})})})}if(Ge.current==="connecting"&&ie!==Ge.current&&ne!==void 0){const xe=new WebSocket(y(J,{token:ne,maxBuffering:P,path:B}));xe.onopen=()=>{var fe,be;Xe({type:"connected",websocket:xe});const Z=(be=(fe=We.service.context)===null||fe===void 0?void 0:fe.enqueuedMessage)!==null&&be!==void 0?be:D;Z&&(xe.send(Y(Z)),We.service.context=Object.assign(Object.assign({},We.service.context),{enqueuedMessage:void 0}))},xe.onclose=fe=>{if(fe.code!==S.NORMAL_CLOSURE){const{onError:be=N}=we();be(new a.ApiError({message:`Error closing the connection: ${fe.reason}`,status:fe.code}))}Xe({type:"connectionClosed",code:fe.code})},xe.onerror=fe=>{const{onError:be=N}=we();be(new a.ApiError({message:"Unknown error",status:500}))},xe.onmessage=fe=>{const{decodeMessage:be=le,onResult:Z,onError:de=N}=we();F({data:fe.data,decodeMessage:be,onResult:Z,onError:de,send:Xe})}}ie==="active"&&Ge.current!=="active"&&(clearTimeout(ue),ue=void 0),ie=Ge.current});return{send:Ee=>{We.throttledSend({type:"send",message:Y(Ee)})},close:()=>{We.service.send({type:"close"})}}}}}return Sa}var _m;function Dm(){if(_m)return ja;_m=1;var e=ja&&ja.__awaiter||function(f,d,g,m){function x(b){return b instanceof g?b:new g(function(h){h(b)})}return new(g||(g=Promise))(function(b,h){function y(S){try{I(m.next(S))}catch(k){h(k)}}function v(S){try{I(m.throw(S))}catch(k){h(k)}}function I(S){S.done?b(S.value):x(S.value).then(y,v)}I((m=m.apply(f,d||[])).next())})};Object.defineProperty(ja,"__esModule",{value:!0}),ja.createFalClient=u;const t=Ef(),r=Tf(),n=Jk(),a=_1(),o=zi(),i=ba(),l=Cp(),c=Sp();function u(f={}){const d=(0,t.createConfig)(f),g=(0,l.createStorageClient)({config:d}),m=(0,n.createQueueClient)({config:d,storage:g}),x=(0,c.createStreamingClient)({config:d,storage:g}),b=(0,a.createRealtimeClient)({config:d});return{queue:m,realtime:b,storage:g,streaming:x,stream:x.stream,run(h){return e(this,arguments,void 0,function*(y,v={}){const I=v.input?yield g.transformInput(v.input):void 0;return(0,o.dispatchRequest)({method:v.method,targetUrl:(0,o.buildUrl)(y,v),input:I,headers:Object.assign(Object.assign({},(0,l.buildObjectLifecycleHeaders)(v.storageSettings)),(0,r.buildTimeoutHeaders)(v.startTimeout)),config:Object.assign(Object.assign({},d),{responseHandler:i.resultResponseHandler}),options:{signal:v.abortSignal,retry:{maxRetries:3,baseDelay:500,maxDelay:15e3}}})})},subscribe:(h,y)=>e(this,void 0,void 0,function*(){const{request_id:v}=yield m.submit(h,y);return y.onEnqueue&&y.onEnqueue(v),yield m.subscribeToStatus(h,Object.assign({requestId:v},y)),m.result(h,{requestId:v})})}}return ja}var Ao={},Lm;function D1(){if(Lm)return Ao;Lm=1,Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.isQueueStatus=e,Ao.isCompletedQueueStatus=t;function e(r){return r&&r.status&&r.response_url}function t(r){return e(r)&&r.status==="COMPLETED"}return Ao}var Om;function L1(){return Om||(Om=1,(function(e){var t=Bs&&Bs.__createBinding||(Object.create?(function(u,f,d,g){g===void 0&&(g=d);var m=Object.getOwnPropertyDescriptor(f,d);(!m||("get"in m?!f.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return f[d]}}),Object.defineProperty(u,g,m)}):(function(u,f,d,g){g===void 0&&(g=d),u[g]=f[d]})),r=Bs&&Bs.__exportStar||function(u,f){for(var d in u)d!=="default"&&!Object.prototype.hasOwnProperty.call(f,d)&&t(f,u,d)};Object.defineProperty(e,"__esModule",{value:!0}),e.fal=e.parseEndpointId=e.isRetryableError=e.ValidationError=e.ApiError=e.withProxy=e.withMiddleware=e.createFalClient=void 0;const n=Dm();var a=Dm();Object.defineProperty(e,"createFalClient",{enumerable:!0,get:function(){return a.createFalClient}});var o=Ip();Object.defineProperty(e,"withMiddleware",{enumerable:!0,get:function(){return o.withMiddleware}}),Object.defineProperty(e,"withProxy",{enumerable:!0,get:function(){return o.withProxy}});var i=ba();Object.defineProperty(e,"ApiError",{enumerable:!0,get:function(){return i.ApiError}}),Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return i.ValidationError}});var l=qc();Object.defineProperty(e,"isRetryableError",{enumerable:!0,get:function(){return l.isRetryableError}}),r(D1(),e);var c=js();Object.defineProperty(e,"parseEndpointId",{enumerable:!0,get:function(){return c.parseEndpointId}}),e.fal=(function(){let f=(0,n.createFalClient)();return{config(d){f=(0,n.createFalClient)(d)},get queue(){return f.queue},get realtime(){return f.realtime},get storage(){return f.storage},get streaming(){return f.streaming},run(d,g){return f.run(d,g)},subscribe(d,g){return f.subscribe(d,g)},stream(d,g){return f.stream(d,g)}}})()})(Bs)),Bs}var rc=L1();const ya={png:"image/png",jpeg:"image/jpeg",webp:"image/webp"},O1=50*1024*1024,B1=512*1024*1024,Gc="Treat everything after this line as one complete image-generation prompt, including the resolution instruction. Follow it exactly without rewriting or omitting anything:";function Ir(e){return typeof e=="string"&&/^https?:\/\//i.test(e)}function Ka(e){return typeof e=="string"&&e.startsWith("data:")}function Rr(e,t){return e.startsWith("data:")?e:`data:${t};base64,${e}`}function Zc(e){const t=typeof e=="string"?e:e&&typeof e=="object"?typeof e.b64_json=="string"?e.b64_json:typeof e.base64=="string"?e.base64:typeof e.image=="string"?e.image:typeof e.data=="string"?e.data:"":"";return t.trim()?t:void 0}function Bm(e){return`${(e/1024/1024).toFixed(1)} MiB`}function Xa(e){return e.length}function qa(e){const t=e.indexOf(",");if(t<0)return e.length;const r=e.slice(0,t),n=e.slice(t+1);if(!/;base64/i.test(r))return decodeURIComponent(n).length;const a=n.replace(/\s/g,""),o=a.endsWith("==")?2:a.endsWith("=")?1:0;return Math.max(0,Math.floor(a.length*3/4)-o)}function Op(e,t,r){if(t>r)throw new Error(`${e}过大:${Bm(t)},上限为 ${Bm(r)}`)}function Wi(e){Op("图像输入有效负载总大小",e,B1)}function bs(e,t){Op(e,t,O1)}const Bp=/Tool choice 'required' must be specified with 'tools' parameter\./i,U1="提示:当前使用的 API 可能未正确转发图像生成工具,请尝试更换支持该工具的接口或模型。",Ea=" 可点链接按钮复制结果链接,或尝试开启「返回 Base64 图片数据」避免此问题。",Um="提示:当前使用的 API 可能不支持流式传输,请尝试关闭「流式传输」功能。",Fm="提示:API 返回了无法解析的流式数据格式,请尝试关闭「流式传输」功能。",F1="提示:当前使用的 API 不支持为该模型使用原生透明背景,请将「透明背景实现方式」切换为「本地后处理」。";function $1(e){return e?`${e}
|
|
10
|
+
${Um}`:Um}function Qc(e){return e?`${e}
|
|
11
|
+
${Fm}`:Fm}function Up(e){return/transparent background is not supported for this model\.?/i.test(e)?`${e}
|
|
12
|
+
${F1}`:e}function Fp(e){return Bp.test(e)?`${e}
|
|
13
|
+
${U1}`:e}function lo(e){return new DOMException(`请求超时:超过 ${e} 秒仍未完成,请稍后重试或提高超时时间。`,"AbortError")}function Hi(e,t,r){const n=Up(e);return n!==e?n:Bp.test(e)||!r||t===401||t===403||t===404||t===408||t===429||t>=500?e:$1(e)}async function z1(e,t=8e3){const r=new AbortController,n=setTimeout(()=>r.abort(),t);try{return(await fetch(e,{method:"GET",mode:"no-cors",cache:"no-store",signal:r.signal})).type==="opaque"?"opaque":"reachable"}catch{return"failed"}finally{clearTimeout(n)}}async function ed(e,t,r){if(Ka(e))return e;let n;try{n=await Dr(e,{cache:"no-store",signal:r})}catch(o){throw o instanceof TypeError?De?new Error(`图片链接下载失败(可能因链接过期或网络异常)。${Ea}`):await z1(e)==="opaque"?new Error(`图片已生成,但因服务商未允许跨域,图片链接下载失败。${Ea}`):typeof navigator<"u"&&navigator.onLine===!1?new Error(`图片链接下载失败(网络不可用)。${Ea}`):new Error(`图片链接下载失败(可能因跨域限制、链接过期或网络异常)。${Ea}`):o}if(!n.ok)throw new Error(`图片 URL 下载失败:HTTP ${n.status}`);const a=await n.blob();return oa(a,t)}async function va(e){var n;let t=`HTTP ${e.status}`;const r=e.clone();try{const a=await e.json();(n=a.error)!=null&&n.message?t=a.error.message:typeof a.detail=="string"?t=a.detail:Array.isArray(a.detail)?t=a.detail.map(o=>typeof o=="string"?o:JSON.stringify(o)).join(`
|
|
14
|
+
`):typeof a.error=="string"?t=a.error:a.message&&(t=a.message)}catch{try{t=await r.text()}catch{}}return t}function Yi(e){if(!e||typeof e!="object")return{};const t=e,r={};return typeof t.size=="string"&&(r.size=t.size),(t.quality==="auto"||t.quality==="low"||t.quality==="medium"||t.quality==="high"||t.quality==="xhigh"||t.quality==="max")&&(r.quality=t.quality),(t.output_format==="png"||t.output_format==="jpeg"||t.output_format==="webp")&&(r.output_format=t.output_format),typeof t.output_compression=="number"&&(r.output_compression=t.output_compression),(t.moderation==="auto"||t.moderation==="low")&&(r.moderation=t.moderation),typeof t.n=="number"&&(r.n=t.n),r}function Ln(...e){const t=Object.assign({},...e.filter(r=>r&&Object.keys(r).length));return Object.keys(t).length?t:void 0}const W1={width:1360,height:1024};function H1(e,t){const r=e.trim().replace(/^\/+/,"").replace(/\/+$/,"")||"openai/gpt-image-2";return r.endsWith("/edit")?t?r:r.replace(/\/edit$/,"/text-to-image"):r.endsWith("/text-to-image")?t?r.replace(/\/text-to-image$/,"/edit"):r:r.includes("gpt-image-2.5/")?`${r}/${t?"edit":"text-to-image"}`:t?`${r}/edit`:r}async function Y1(e){const t=e.match(/^(\d+)x(\d+)$/);return t?{width:Number(t[1]),height:Number(t[2])}:W1}function V1(e,t){return ff(t)&&(e==="xhigh"||e==="max")||e==="low"||e==="medium"?e:"high"}function $p(e){const t=e.baseUrl.trim().replace(/\/+$/,"")||Gn,r={credentials:e.apiKey,suppressLocalCredentialsWarning:!0,fetch:Dr};t!==Gn&&(r.proxyUrl=t),rc.fal.config(r)}async function K1(e,t){const r=e.inputImageDataUrls.length>0,n={prompt:e.prompt,image_size:r&&e.params.size==="auto"?"auto":await Y1(e.params.size),quality:V1(e.params.quality,t),num_images:Math.min(4,Math.max(1,e.params.n||1)),output_format:e.params.output_format};return e.nativeTransparentBackground&&(n.background="transparent"),r&&(n.image_urls=e.inputImageDataUrls),e.maskDataUrl&&(n.mask_url=e.maskDataUrl),n}function X1(e,t){if(typeof e=="string")return Ir(e)||Ka(e)?e:Rr(e,t);if(!e||typeof e!="object")return null;const r=e;return Ir(r.url)||Ka(r.url)?r.url:typeof r.b64_json=="string"?Rr(r.b64_json,t):typeof r.base64=="string"?Rr(r.base64,t):typeof r.data=="string"?Rr(r.data,t):null}function q1(e){if(!e||typeof e!="object")return;const t=e,r=typeof t.width=="number"?t.width:null,n=typeof t.height=="number"?t.height:null;if(!(!r||!n||!Number.isFinite(r)||!Number.isFinite(n)))return{size:`${Math.round(r)}x${Math.round(n)}`}}async function J1(e,t,r,n){const a=[];Array.isArray(e.images)&&a.push(...e.images),e.image&&a.push(e.image),e.url&&a.push(e.url);const o=[],i=[];try{for(const l of a){const c=X1(l,t);c&&(Ir(c)&&i.push(c),o.push({image:Ir(c)?await ed(c,t,n):c,actualParams:q1(l),rawImageUrl:Ir(c)?c:void 0}))}}catch(l){throw i.length>0&&l instanceof Error&&(l.rawImageUrls=i),l}if(!o.length){const l=new Error(r?`${r} 没有返回可识别的图片数据,请查看原始响应内容确认实际返回的数据结构。如果当前接口与 fal.ai 格式不兼容,建议创建并使用「自定义服务商」配置。`:"fal.ai 未返回可用图片数据");throw r&&(l.rawResponsePayload=JSON.stringify(e,null,2)),l}return o}async function zp(e,t,r,n){var c;const a=ya[t.output_format]||"image/png",o=await J1(e,a,r,n),i=Ln((c=o[0])==null?void 0:c.actualParams),l=o.map(u=>u.rawImageUrl).filter(u=>!!u);return{images:o.map(u=>u.image),actualParams:i,actualParamsList:o.map(u=>u.actualParams),revisedPrompts:o.map(()=>{}),...l.length?{rawImageUrls:l}:{}}}function Wp(e){const t=e&&typeof e=="object"&&"body"in e?e.body:null;if(!t||typeof t!="object")return null;const r=t.detail;if(typeof r=="string"&&r.trim())return r;if(Array.isArray(r)){const a=r.map(o=>{if(typeof o=="string")return o;if(o&&typeof o=="object"){const i=o;if(typeof i.msg=="string"&&i.msg.trim())return i.msg;if(typeof i.message=="string"&&i.message.trim())return i.message}return null}).filter(o=>!!o);if(a.length)return a.join(`
|
|
15
|
+
`)}const n=t.message;return typeof n=="string"&&n.trim()?n:null}function Hp(e){const t=e.baseUrl.trim().replace(/\/+$/,"");return!t||t===Gn?null:t.replace(/^https?:\/\//,"")}async function G1(e,t,r,n){$p(e),await rc.fal.queue.subscribeToStatus(t,{requestId:r,logs:!0});const a=await rc.fal.queue.result(t,{requestId:r});return zp(a.data,n,Hp(e))}async function Z1(e,t){var r;try{e.maskDataUrl&&(bs("遮罩主图文件",qa(e.inputImageDataUrls[0]??"")),bs("遮罩文件",qa(e.maskDataUrl))),Wi(e.inputImageDataUrls.reduce((c,u)=>c+Xa(u),0)+(e.maskDataUrl?Xa(e.maskDataUrl):0)),$p(t);const n=e.inputImageDataUrls.length>0,a=H1(t.model,n),o=await K1(e,t.model),i=await rc.fal.subscribe(a,{input:o,logs:!0,onEnqueue:c=>{var u;(u=e.onFalRequestEnqueued)==null||u.call(e,{requestId:c,endpoint:a})}}),l=i.data;return(r=e.onFalRequestEnqueued)==null||r.call(e,{requestId:i.requestId,endpoint:a}),zp(l,e.params,Hp(t))}catch(n){const a=Wp(n);throw a?new Error(a):n}}function Q1(e,t){const r=e.find(n=>n.id===t);if(!r)throw new Error("遮罩主图已不存在,请重新选择遮罩区域");return r}function Yp(e,t){return[Q1(e,t),...e.filter(n=>n.id!==t)]}function eI(e){let t=0,r=0;const n=e.data.length/4;for(let a=3;a<e.data.length;a+=4)e.data[a]<255&&t++,e.data[a]===0&&r++;return t===0?"empty":r===n?"full":"partial"}function tI(e){if(e==="empty")throw new Error("请先涂抹需要编辑的区域")}async function On(e){return new Promise((t,r)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>r(new Error("图片加载失败")),n.src=e})}async function Df(e,t="image/png"){const n=await(await fetch(e)).blob();return n.type?n:new Blob([await n.arrayBuffer()],{type:t})}async function Lf(e){const t=await On(e),r=document.createElement("canvas");r.width=t.naturalWidth,r.height=t.naturalHeight;const n=r.getContext("2d");if(!n)throw new Error("当前浏览器不支持 Canvas");return n.drawImage(t,0,0),td(r,"image/png")}async function Vp(e){const t=await Df(e,"image/png");return t.type!=="image/png"?Lf(e):t}async function td(e,t="image/png",r){return new Promise((n,a)=>{e.toBlob(o=>{o?n(o):a(new Error("图片导出失败"))},t,r)})}async function Kp(e,t){const[r,n]=await Promise.all([On(e),On(t)]);if(r.naturalWidth!==n.naturalWidth||r.naturalHeight!==n.naturalHeight)throw new Error("遮罩尺寸与遮罩主图不一致,请重新绘制遮罩");const a=document.createElement("canvas");a.width=r.naturalWidth,a.height=r.naturalHeight;const o=a.getContext("2d",{willReadFrequently:!0});if(!o)throw new Error("当前浏览器不支持 Canvas");o.drawImage(r,0,0);const i=eI(o.getImageData(0,0,a.width,a.height));return tI(i),i}async function rd(e,t){const[r,n]=await Promise.all([On(e),On(t)]);if(r.naturalWidth!==n.naturalWidth||r.naturalHeight!==n.naturalHeight)throw new Error("遮罩尺寸与遮罩主图不一致,请重新绘制遮罩");const a=document.createElement("canvas");a.width=r.naturalWidth,a.height=r.naturalHeight;const o=a.getContext("2d",{willReadFrequently:!0});if(!o)throw new Error("当前浏览器不支持 Canvas");o.drawImage(r,0,0);const i=document.createElement("canvas");i.width=n.naturalWidth,i.height=n.naturalHeight;const l=i.getContext("2d",{willReadFrequently:!0});if(!l)throw new Error("当前浏览器不支持 Canvas");l.drawImage(n,0,0);const c=l.getImageData(0,0,i.width,i.height),u=o.createImageData(a.width,a.height);for(let g=0;g<c.data.length;g+=4){const m=255-c.data[g+3];u.data[g]=59,u.data[g+1]=130,u.data[g+2]=246,u.data[g+3]=Math.round(m*.58)}const f=document.createElement("canvas");f.width=a.width,f.height=a.height;const d=f.getContext("2d");if(!d)throw new Error("当前浏览器不支持 Canvas");return d.putImageData(u,0,0),o.drawImage(f,0,0),a.toDataURL("image/png")}function nd(e){var t;return((t=e.headers.get("Content-Type"))==null?void 0:t.toLowerCase().includes("text/event-stream"))??!1}function rI(e){const t=[];for(const n of e.split(/\r?\n/))!n||n.startsWith(":")||n.startsWith("data:")&&t.push(n.slice(5).replace(/^ /,""));const r=t.join(`
|
|
16
|
+
`).trim();return!r||r==="[DONE]"?null:r}function Qt(...e){const t=e.find(r=>r==null?void 0:r.aborted);if(t)throw t.reason instanceof Error?t.reason:new DOMException("请求已停止","AbortError")}async function sd(e,t,r={}){var f,d;if(!e.body)throw new Error("接口未返回可读取的流式响应");const n=r.signals??[],a=e.body.getReader(),o=new TextDecoder;let i="",l=!1;const c=()=>{a.cancel().catch(()=>{})};Qt(...n);for(const g of n)g==null||g.addEventListener("abort",c,{once:!0});const u=async g=>{var h,y;g.split(/\r?\n/).some(v=>v.startsWith("data:"))&&(l=!0);const m=rI(g);if(!m)return;let x;try{x=JSON.parse(m)}catch{throw new Error(((h=r.formatErrorMessage)==null?void 0:h.call(r,m))??m)}if(!x||typeof x!="object"||Array.isArray(x))return;const b=(y=r.getEventErrorMessage)==null?void 0:y.call(r,x);if(b)throw new Error(b);Qt(...n),await t(x),Qt(...n)};try{for(;;){Qt(...n);const{value:g,done:m}=await a.read();if(Qt(...n),m)break;i+=o.decode(g,{stream:!0});let x=i.search(/\r?\n\r?\n/);for(;x>=0;){const b=i.slice(0,x),h=((f=i.match(/\r?\n\r?\n/))==null?void 0:f[0])??`
|
|
17
|
+
|
|
18
|
+
`;i=i.slice(x+h.length),await u(b),x=i.search(/\r?\n\r?\n/)}}if(i+=o.decode(),Qt(...n),i.trim()&&await u(i),!l){const g="未从流式响应中解析到有效的 data 事件";throw new Error(((d=r.formatErrorMessage)==null?void 0:d.call(r,g))??g)}}finally{for(const g of n)g==null||g.removeEventListener("abort",c)}}const Xp=/^\s*(\d+)\s*[xX×]\s*(\d+)\s*$/,nI=/^\s*(\d+(?:\.\d+)?)\s*[:xX×]\s*(\d+(?:\.\d+)?)\s*$/,br=16,nc=3840,Lo=3,Mu=655360,Eu=8294400,qp=1572864;function $m(e,t){return Math.max(t,Math.round(e/t)*t)}function vl(e,t){return Math.max(t,Math.floor(e/t)*t)}function zm(e,t){return Math.max(t,Math.ceil(e/t)*t)}function Jp(e,t){let r=$m(e,br),n=$m(t,br);const a=i=>{r=vl(r*i,br),n=vl(n*i,br)},o=i=>{r=zm(r*i,br),n=zm(n*i,br)};for(let i=0;i<4;i++){const l=Math.max(r,n);l>nc&&a(nc/l),r/n>Lo?r=vl(n*Lo,br):n/r>Lo&&(n=vl(r*Lo,br));const c=r*n;c>Eu?a(Math.sqrt(Eu/c)):c<Mu&&o(Math.sqrt(Mu/c))}return{width:r,height:n}}function ad(e){const t=e.trim(),r=t.match(Xp);if(!r)return t;const{width:n,height:a}=Jp(Number(r[1]),Number(r[2]));return`${n}x${a}`}function Of(e){const t=e.trim(),r=t.match(Xp);if(!r)return t;const n=Number(r[1]),a=Number(r[2]),o=Jp(n,a);if(o.width*o.height>qp)return Uf("1K",`${o.width}:${o.height}`)??`${o.width}x${o.height}`;const{width:i,height:l}=o;return`${i}x${l}`}function Bf(e,t){if(t==="auto")return e;const r=e.trimStart(),n=`Generate at ${t} resolution.`;return r.startsWith(n)?r:`${n} ${r}`}function sI(e,t,r){if(r==="auto")return e;const n=`Generate at ${r} resolution.`;if(t.trimStart().startsWith(n))return e;const a=e.trimStart();return a.startsWith(n)?a.slice(n.length).trimStart():e}function Gp(e){const t=e.match(nI);if(!t)return null;const r=Number(t[1]),n=Number(t[2]);return!Number.isFinite(r)||!Number.isFinite(n)||r<=0||n<=0?null:{width:r,height:n}}function Zp(e,t){const r=Math.round(e),n=Math.round(t);if(!Number.isFinite(r)||!Number.isFinite(n)||r<=0||n<=0)return"";const a=(x,b)=>b===0?x:a(b,x%b),o=a(r,n),i=r/o,l=n/o,c=`${i}:${l}`,u=[[1,1],[4,3],[3,4],[3,2],[2,3],[16,9],[9,16],[21,9],[9,21]];for(const[x,b]of u)if(i===x&&l===b)return c;const f=r/n;if(Math.abs(f-1)<=.18)return"≈1:1";const g=u.map(([x,b])=>{const h=x/b;return{label:`${x}:${b}`,delta:Math.abs(f-h)/h}}).sort((x,b)=>x.delta-b.delta)[0];if(g&&g.delta<=.01)return`≈${g.label}`;const m=Array.from({length:12},(x,b)=>b+1).flatMap(x=>Array.from({length:12},(b,h)=>h+1).map(b=>{const h=x/b,y=Math.abs(f-h)/h;return{label:`${x}:${b}`,delta:y,score:y+(x+b)*.002}})).filter(x=>x.label!==c).sort((x,b)=>x.score-b.score)[0];return m&&m.delta<=.04?`≈${m.label}`:c}const aI={"1K":qp,"2K":4194304,"4K":Eu},Qp={"1K":{"1:1":"1024x1024","3:2":"1536x1024","2:3":"1024x1536","16:9":"1280x720","9:16":"720x1280","4:3":"1024x768","3:4":"768x1024","21:9":"1280x544"},"2K":{"1:1":"2048x2048","3:2":"2160x1440","2:3":"1440x2160","16:9":"2560x1440","9:16":"1440x2560","4:3":"2048x1536","3:4":"1536x2048","21:9":"2560x1088"},"4K":{"1:1":"2880x2880","3:2":"3456x2304","2:3":"2304x3456","16:9":"3840x2160","9:16":"2160x3840","4:3":"3200x2400","3:4":"2400x3200","21:9":"3840x1600"}};function oI(e,t){if(!Number.isInteger(e)||!Number.isInteger(t))return null;const r=(o,i)=>i===0?o:r(i,o%i),n=r(e,t),a=`${e/n}:${t/n}`;return a in Qp["1K"]?a:null}const iI=.01;function Uf(e,t){const r=Gp(t);if(!r)return null;const{width:n,height:a}=r,o=oI(n,a);if(o)return Qp[e][o];const i=n/a,l=aI[e];let c=0,u=0,f=0;for(let d=br;d<=nc;d+=br){const g=d/i,m=[Math.floor(g/br)*br,Math.ceil(g/br)*br];for(const x of m){if(x<br||x>nc)continue;const b=d*x;if(b>l||b<Mu||Math.max(d/x,x/d)>Lo)continue;const h=d/x;Math.abs(h-i)/i>iI||b>f&&(f=b,c=d,u=x)}}return f===0?null:`${c}x${u}`}function Ru(e){return e.streamPartialImages??kr}function ex(e,t){if(!t||!Object.keys(t).length)return e;const r=new URLSearchParams;for(const[n,a]of Object.entries(t))r.set(n,a);return`${e}${e.includes("?")?"&":"?"}${r.toString()}`}function lI(){return{generationPath:"images/generations",editPath:"images/edits"}}function Ks(e,t){return t?t.split(".").filter(Boolean).reduce((r,n)=>{if(r!=null){if(/^\d+$/.test(n)&&Array.isArray(r))return r[Number(n)];if(typeof r=="object")return r[n]}},e):e}function Wm(e,t){if(!t)return[e];const r=t.split(".").filter(Boolean);let n=[e];for(const a of r){const o=[];for(const i of n)if(i!=null){if(a==="*"){Array.isArray(i)?o.push(...i):typeof i=="object"&&o.push(...Object.values(i));continue}if(/^\d+$/.test(a)&&Array.isArray(i)){o.push(i[Number(a)]);continue}typeof i=="object"&&o.push(i[a])}n=o}return n.flatMap(a=>Array.isArray(a)?a:[a]).filter(a=>a!=null)}function cI(e){return Array.isArray(e)?{data:e}:e&&typeof e=="object"?e:{data:[]}}function od(e){return{Authorization:`Bearer ${e.apiKey}`}}function _u(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function vr(e,t){const r=e[t];return typeof r=="string"&&r.trim()?r:void 0}function dI(e){return e instanceof Error?e.message:String(e)}function Ff(e,t){const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function tx(e){const t=e.error;if(_u(t)){const n=vr(t,"message");if(n)return n}if(typeof t=="string"&&t.trim())return t;const r=vr(e,"type");return r!=null&&r.endsWith(".failed")?vr(e,"message")??"流式请求失败":null}function uI(e,t,r,n,a){const o={type:"image_generation",action:t?"edit":"generate",output_format:e.output_format,moderation:e.moderation},i=Ri(r);return i&&(o.model=i),r.codexCli||(o.size=e.size),r.streamImages&&(o.partial_images=Ru(r)),r.codexCli||(o.quality=e.quality),e.output_format!=="png"&&e.output_compression!=null&&(o.output_compression=e.output_compression),a&&(o.background="transparent"),n&&(o.input_image_mask={image_url:n}),o}function fI(e,t,r){const n=r?e:`${Gc}
|
|
19
|
+
${e}`;return t.length?[{role:"user",content:[{type:"input_text",text:n},...t.map(a=>({type:"input_image",image_url:a}))]}]:n}function Du(e,t){const r=e.output;if(!Array.isArray(r)||!r.length){const a=new Error("接口未返回图片数据");throw a.rawResponsePayload=JSON.stringify(e,null,2),a}const n=[];for(const a of r){if((a==null?void 0:a.type)!=="image_generation_call")continue;const o=Zc(a.result);o&&n.push({image:Rr(o,t),actualParams:Ln(Yi(a)),revisedPrompt:typeof a.revised_prompt=="string"?a.revised_prompt:void 0})}if(!n.length){const a=new Error("接口没有返回可识别的图片数据,请查看原始响应内容确认服务商实际返回的数据结构。如果使用的是中转或兼容接口,建议创建并使用「自定义服务商」配置。");throw a.rawResponsePayload=JSON.stringify(e,null,2),a}return n}async function rx(e,t,r){const n=e.data;if(!Array.isArray(n)||!n.length){const c=new Error("接口没有返回图片数据,请查看原始响应内容确认服务商实际返回的数据结构。如果使用的是中转或兼容接口,建议创建并使用「自定义服务商」配置。");throw c.rawResponsePayload=JSON.stringify(e,null,2),c}const a=[],o=n.map(c=>c.url).filter(Ir),i=[];try{for(const c of n){const u=c.b64_json;if(u){a.push(Rr(u,t)),i.push(typeof c.revised_prompt=="string"?c.revised_prompt:void 0);continue}(Ir(c.url)||Ka(c.url))&&(a.push(await ed(c.url,t,r)),i.push(typeof c.revised_prompt=="string"?c.revised_prompt:void 0))}}catch(c){throw o.length>0&&c instanceof Error&&(c.rawImageUrls=o),c}if(!a.length){const c=new Error("接口没有返回可识别的图片数据,请查看原始响应内容确认服务商实际返回的数据结构。如果使用的是中转或兼容接口,建议创建并使用「自定义服务商」配置。");throw c.rawResponsePayload=JSON.stringify(e,null,2),c}const l=Ln(Yi(e));return{images:a,actualParams:l,actualParamsList:a.map(()=>l),revisedPrompts:i,...o.length?{rawImageUrls:o}:{}}}function gI(e){return{b64_json:vr(e,"b64_json"),url:vr(e,"url"),revised_prompt:vr(e,"revised_prompt"),size:vr(e,"size"),quality:vr(e,"quality"),output_format:vr(e,"output_format"),output_compression:Ff(e,"output_compression"),moderation:vr(e,"moderation")}}async function mI(e,t,r,n){const a=[];let o=null;if(await sd(e,f=>{const d=vr(f,"type"),g=vr(f,"object");if(d==="image_generation.partial_image"||d==="image_edit.partial_image"){const m=vr(f,"b64_json");m&&(r==null||r({image:Rr(m,t),partialImageIndex:Ff(f,"partial_image_index")}));return}if(g==="image.generation.result"||g==="image.edit.result"){o=cI(f);return}(d==="image_generation.completed"||d==="image_edit.completed")&&a.push(gI(f))},{signals:[n],formatErrorMessage:Qc,getEventErrorMessage:tx}),o)return rx(o,t);if(!a.length)throw new Error("流式接口未返回最终图片数据");const i=[],l=a.map(f=>f.url).filter(Ir);try{for(const f of a){if(f.b64_json){i.push(Rr(f.b64_json,t));continue}(Ir(f.url)||Ka(f.url))&&i.push(await ed(f.url,t,n))}}catch(f){throw l.length>0&&f instanceof Error&&(f.rawImageUrls=l),f}if(!i.length)throw new Error("流式接口未返回可用图片数据");const c=a.map(f=>Ln(Yi(f))),u=Ln(c[0],i.length>1?{n:i.length}:void 0);return{images:i,actualParams:u,actualParamsList:c,revisedPrompts:a.map(f=>f.revised_prompt),...l.length?{rawImageUrls:l}:{}}}function hI(e){const t=e.response;if(_u(t))return t;const r=e.item;return _u(r)&&r.type==="image_generation_call"?{output:[r]}:null}async function pI(e,t,r){var c;let n=null;const a=[];await sd(e,u=>{const f=vr(u,"type");if(f==="response.image_generation_call.partial_image"){const g=vr(u,"partial_image_b64");g&&(r==null||r({image:Rr(g,t),partialImageIndex:Ff(u,"partial_image_index")}));return}const d=hI(u);if(d){if(f==="response.output_item.done"&&Array.isArray(d.output)){a.push(...d.output);return}n=d}},{formatErrorMessage:Qc,getEventErrorMessage:tx});const o=n??(a.length?{output:a}:null);if(!o)throw new Error("流式接口未返回最终图片数据");let i;try{i=Du(o,t)}catch(u){const f=a.filter(d=>Zc(d.result));if(f.length===0)throw u;i=Du({output:f},t)}const l=Ln(((c=i[0])==null?void 0:c.actualParams)??{});return{images:i.map(u=>u.image),actualParams:l,actualParamsList:i.map(u=>Ln(u.actualParams??{})),revisedPrompts:i.map(u=>u.revisedPrompt)}}async function xI(e,t,r){if(r){const n=e.params.n>0?e.params.n:1,o=!!(e.inputImageDataUrls.length>0&&r.editSubmit?r.editSubmit:r.submit).taskIdPath;return t.codexCli&&n>1&&!o?PI(e,t,r,n):ox(e,t,r)}return t.apiMode==="responses"?TI(e,t):bI(e,t)}async function bI(e,t){const r=e.params.n>0?e.params.n:1;return(t.codexCli||t.streamImages&&r>1)&&r>1?yI(e,t,r):nx(e,t)}async function yI(e,t,r){const n={...e,params:{...e.params,n:1,...t.codexCli?{quality:"auto"}:{}}},a=await Promise.allSettled(Array.from({length:r}).map((o,i)=>nx({...n,onPartialImage:e.onPartialImage?l=>{var c;return(c=e.onPartialImage)==null?void 0:c.call(e,{...l,requestIndex:i})}:void 0},t)));return $f(a)}async function nx(e,t){var b;const{prompt:r,params:n,inputImageDataUrls:a}=e,o=t.codexCli&&!e.skipCodexCliSizePrompt?Bf(r,n.size):r,i=t.codexCli&&!e.settings.allowPromptRewrite?`${Gc}
|
|
20
|
+
${o}`:o,l=a.length>0,c=ya[n.output_format]||"image/png",u=sn(),f=ha(t.apiProxy,u),d=od(t),g=lI(),m=new AbortController,x=setTimeout(()=>m.abort(lo(t.timeout)),t.timeout*1e3);try{let h;if(l){const y=new FormData;y.append("model",t.model),y.append("prompt",i),t.codexCli||y.append("size",n.size),y.append("output_format",n.output_format),y.append("moderation",n.moderation),e.nativeTransparentBackground&&y.append("background","transparent"),t.codexCli||y.append("quality",n.quality),n.output_format!=="png"&&n.output_compression!=null&&y.append("output_compression",String(n.output_compression)),n.n>1&&y.append("n",String(n.n)),t.responseFormatB64Json&&y.append("response_format","b64_json"),t.streamImages&&(y.append("stream","true"),y.append("partial_images",String(Ru(t))));const v=[];for(let S=0;S<a.length;S++){const k=a[S],j=e.maskDataUrl&&S===0?await Lf(k):await Df(k);v.push(j)}const I=e.maskDataUrl?await Vp(e.maskDataUrl):null;e.maskDataUrl&&(bs("遮罩主图文件",((b=v[0])==null?void 0:b.size)??0),bs("遮罩文件",(I==null?void 0:I.size)??0)),Wi(v.reduce((S,k)=>S+k.size,0)+((I==null?void 0:I.size)??0));for(let S=0;S<v.length;S++){const k=v[S],j=k.type.split("/")[1]||"png";y.append("image[]",k,`input-${S+1}.${j}`)}I&&y.append("mask",I,"mask.png"),h=await Dr(ps(t.baseUrl,g.editPath,u,f),{method:"POST",headers:d,cache:"no-store",body:y,signal:m.signal})}else{const y={model:t.model,prompt:i,output_format:n.output_format,moderation:n.moderation};e.nativeTransparentBackground&&(y.background="transparent"),t.codexCli||(y.size=n.size),t.codexCli||(y.quality=n.quality),n.output_format!=="png"&&n.output_compression!=null&&(y.output_compression=n.output_compression),n.n>1&&(y.n=n.n),t.responseFormatB64Json&&(y.response_format="b64_json"),t.streamImages&&(y.stream=!0,y.partial_images=Ru(t)),h=await Dr(ps(t.baseUrl,g.generationPath,u,f),{method:"POST",headers:{...d,"Content-Type":"application/json"},cache:"no-store",body:JSON.stringify(y),signal:m.signal})}if(!h.ok){const y=await va(h);throw new Error(Hi(y,h.status,t.streamImages))}return t.streamImages&&nd(h)?await mI(h,c,e.onPartialImage,m.signal):await rx(await h.json(),c,m.signal)}finally{clearTimeout(x)}}function vI(e,t){return new Promise((r,n)=>{if(t.aborted){n(new DOMException("Aborted","AbortError"));return}const a=setTimeout(r,e);t.addEventListener("abort",()=>{clearTimeout(a),n(new DOMException("Aborted","AbortError"))},{once:!0})})}function wI(e,t){const r=Ks(e,t.statusPath),n=typeof r=="string"?r:String(r??"");return t.successValues.includes(n)?"success":t.failureValues.includes(n)?"failure":"pending"}function Hm(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"||e instanceof Lc)return!0;const t=e instanceof Error?e.message:String(e);return/abort|network|failed to fetch|fetch failed|load failed|timeout|连接|断开|中断/i.test(t)}function kI(e){return e===408||e===429||e>=500}function II(e,t){return e.replace(/\{task_id\}/g,encodeURIComponent(t)).replace(/\{taskId\}/g,encodeURIComponent(t))}function li(e,t){if(typeof e=="string"&&e.startsWith("$"))return Ks(t,e.slice(1));if(Array.isArray(e))return e.map(r=>li(r,t)).filter(r=>r!=null);if(e&&typeof e=="object"){const r=Object.entries(e).map(([n,a])=>[n,li(a,t)]).filter(([,n])=>n!=null&&(!Array.isArray(n)||n.length>0));return Object.fromEntries(r)}return e}function CI(e,t){var i;const r=t.codexCli&&!e.skipCodexCliSizePrompt?Bf(e.prompt,e.params.size):e.prompt,n=t.codexCli&&!e.settings.allowPromptRewrite?`${Gc}
|
|
21
|
+
${r}`:r,a={...e.params,...t.codexCli?{size:void 0,quality:void 0}:{},...e.nativeTransparentBackground?{background:"transparent"}:{}},o=((i=e.inputImageUrls)==null?void 0:i.filter(Ir))??[];return{profile:t,prompt:n,params:a,inputImages:{dataUrls:e.inputImageDataUrls.length?e.inputImageDataUrls:void 0,base64:e.inputImageDataUrls.length?e.inputImageDataUrls.map(l=>l.replace(/^data:[^;]+;base64,/,"")):void 0,urls:o.length?o:void 0,count:e.inputImageDataUrls.length},mask:{dataUrl:e.maskDataUrl}}}function jI(e,t){if(!e)return;const r=Object.entries(e).map(([n,a])=>[n,li(a,t)]).filter(([,n])=>n!=null&&String(n)!=="").map(([n,a])=>[n,String(a)]);return r.length?Object.fromEntries(r):void 0}async function SI(e,t,r){var u,f,d;const n=new FormData,a=li(e.body??{},r);if(a&&typeof a=="object"&&!Array.isArray(a)){for(const[g,m]of Object.entries(a))if(m!=null)if(Array.isArray(m))for(const x of m)n.append(g,String(x));else n.append(g,String(m))}const o=(u=e.files)==null?void 0:u.some(g=>g.source==="inputImages"),i=(f=e.files)==null?void 0:f.some(g=>g.source==="mask"),l=[];if(o)for(let g=0;g<t.inputImageDataUrls.length;g++){const m=t.inputImageDataUrls[g],x=t.maskDataUrl&&g===0?await Lf(m):await Df(m);l.push(x)}const c=i&&t.maskDataUrl?await Vp(t.maskDataUrl):null;t.maskDataUrl&&(o||i)&&(bs("遮罩主图文件",((d=l[0])==null?void 0:d.size)??0),bs("遮罩文件",(c==null?void 0:c.size)??0)),Wi(l.reduce((g,m)=>g+m.size,0)+((c==null?void 0:c.size)??0));for(const g of e.files??[])if(g.source==="inputImages")for(let m=0;m<l.length;m++){const x=l[m],b=x.type.split("/")[1]||"png";n.append(g.field,x,`input-${m+1}.${b}`)}else g.source==="mask"&&c&&n.append(g.field,c,"mask.png");return n}async function sx(e,t,r,n){const a=[],o=(t.imageUrlPaths??[]).flatMap(l=>Wm(e,l).filter(c=>Ir(c)||Ka(c))),i=o.filter(Ir);try{for(const l of t.b64JsonPaths??[])for(const c of Wm(e,l))typeof c=="string"&&c.trim()&&a.push(Rr(c,r));for(const l of o)a.push(await ed(l,r,n))}catch(l){throw i.length>0&&l instanceof Error&&(l.rawImageUrls=i),l}if(!a.length){const l=new Error("接口没有返回可识别的图片数据,请查看原始响应内容确认接口实际返回的数据结构,并根据 API 文档调整「自定义服务商」配置中的结果提取路径。");throw l.rawResponsePayload=JSON.stringify(e,null,2),l}return{images:a,...i.length?{rawImageUrls:i}:{}}}async function NI(e,t,r,n,a,o){var y,v;const i=od(r),l=CI(t,r),c=JSON.stringify([e.body,e.query]),u=c.includes("$inputImages.urls")&&!c.includes("$inputImages.dataUrls")&&!c.includes("$inputImages.base64")&&!((y=e.files)!=null&&y.some(I=>I.source==="inputImages")),f=l.inputImages.count-(((v=l.inputImages.urls)==null?void 0:v.length)??0);if(u&&f>0)throw new Error(`当前服务商只接受链接参考图,有 ${f} 张参考图不是通过链接添加的。请在输入框的「+ → 添加链接」中添加,或移除这些参考图后重试。`);const d=e.method??"POST",g=e.contentType??"json",m=ex(e.path,jI(e.query,l)),x={...i};let b;if(d!=="GET")if(g==="multipart"){const I=await SI(e,t,l);r.responseFormatB64Json&&I.append("response_format","b64_json"),b=I}else{Wi(t.inputImageDataUrls.reduce((S,k)=>S+Xa(k),0)+(t.maskDataUrl?Xa(t.maskDataUrl):0)),x["Content-Type"]="application/json";const I=li(e.body??{},l);r.responseFormatB64Json&&I&&typeof I=="object"&&!Array.isArray(I)&&(I.response_format="b64_json"),b=JSON.stringify(I)}const h=await Dr(ps(r.baseUrl,m,a,o),{method:d,headers:x,cache:"no-store",body:b,signal:n.signal});if(!h.ok){const I=await va(h);throw new Error(Hi(I,h.status,r.streamImages))}return h.json()}async function ax(e,t,r,n,a){var c;const o=sn(),i=od(e);let l=!0;for(;;){l?l=!1:a?await vI((t.intervalSeconds??5)*1e3,a):await new Promise(g=>setTimeout(g,(t.intervalSeconds??5)*1e3));const u=ex(II(t.path,r),t.query);let f;try{const g=await Dr(ps(e.baseUrl,u,o,!1),{method:t.method??"GET",headers:i,cache:"no-store",signal:a});if(!g.ok){if(kI(g.status)){(c=g.body)==null||c.cancel().catch(()=>{});continue}throw new Error(await va(g))}f=await g.json()}catch(g){if(!(a!=null&&a.aborted)&&Hm(g))continue;throw g}const d=wI(f,t);if(d==="failure"){const g=Ks(f,t.errorPath)||Ks(f,"message")||Ks(f,"data.fail_reason")||Ks(f,"error.message"),m=typeof g=="string"&&g.trim()?g:"异步任务失败";throw new Error(Up(m))}if(d==="success")try{return await sx(f,t.result,n,a)}catch(g){if(!(a!=null&&a.aborted)&&Hm(g))continue;throw g}}}async function AI(e,t,r,n){if(!t.poll)throw new Error("自定义异步任务缺少 poll 配置");const a=ya[n.output_format]||"image/png";return ax(e,t.poll,r,a)}async function ox(e,t,r){var u;const{params:n,inputImageDataUrls:a}=e,o=a.length>0,i=ya[n.output_format]||"image/png",l=new AbortController;let c=setTimeout(()=>l.abort(lo(t.timeout)),t.timeout*1e3);try{const f=sn(),d=ha(t.apiProxy,f),g=o&&r.editSubmit?r.editSubmit:r.submit;if(d&&(g.method??"POST")!=="POST")throw new Error("API 代理暂不支持使用 GET 提交的自定义服务商。请关闭 API 代理,或改用 POST 提交的自定义服务商配置。");if(d&&(g.taskIdPath||r.poll))throw new Error("API 代理暂不支持使用异步任务的自定义服务商。请关闭 API 代理,或改用同步返回图片的自定义服务商配置。");const m=await NI(g,e,t,l,f,d),x=g.taskIdPath?Ks(m,g.taskIdPath):void 0,b=typeof x=="string"?x.trim():String(x??"").trim();if(g.taskIdPath&&!b){const h=new Error("无法从响应中提取异步任务 ID,请查看原始响应内容确认接口实际返回的数据结构,并根据 API 文档调整「自定义服务商」配置中的 taskIdPath。");throw h.rawResponsePayload=JSON.stringify(m,null,2),h}if(!b)return await sx(m,g.result??{},i,l.signal);if(!r.poll)throw new Error("异步接口返回了 task_id,但服务商配置缺少 poll");return(u=e.onCustomTaskEnqueued)==null||u.call(e,{taskId:b}),c&&(clearTimeout(c),c=null),ax(t,r.poll,b,i,l.signal)}finally{c&&clearTimeout(c)}}function $f(e){const t=e.filter(l=>l.status==="fulfilled").map(l=>l.value);if(!t.length)throw e.find(c=>c.status==="rejected").reason;const r=t.flatMap(l=>l.images),n=t.flatMap(l=>{var c;return(c=l.actualParamsList)!=null&&c.length?l.actualParamsList:l.images.map(()=>l.actualParams)}),a=t.flatMap(l=>{var c;return(c=l.revisedPrompts)!=null&&c.length?l.revisedPrompts:l.images.map(()=>{})}),o=t.flatMap(l=>l.rawImageUrls??[]),i=e.flatMap((l,c)=>l.status==="rejected"?[{requestIndex:c,error:dI(l.reason)}]:[]);return{images:r,actualParams:Ln(t[0].actualParams??{},{n:r.length}),actualParamsList:n,revisedPrompts:a,...o.length?{rawImageUrls:o}:{},...i.length?{failedRequests:i}:{}}}async function PI(e,t,r,n){const a=await Promise.allSettled(Array.from({length:n}).map(()=>ox({...e,params:{...e.params,n:1}},t,r)));return $f(a)}async function TI(e,t){const r=e.params.n>0?e.params.n:1;if(r===1)return Ym(e,t);const n=Array.from({length:r}).map((o,i)=>Ym({...e,onPartialImage:e.onPartialImage?l=>{var c;return(c=e.onPartialImage)==null?void 0:c.call(e,{...l,requestIndex:i})}:void 0},t)),a=await Promise.allSettled(n);return $f(a)}async function Ym(e,t){var g;const{prompt:r,params:n,inputImageDataUrls:a}=e,o=t.codexCli&&!e.skipCodexCliSizePrompt?Bf(r,n.size):r,i=ya[n.output_format]||"image/png",l=sn(),c=ha(t.apiProxy,l),u=od(t),f=new AbortController,d=setTimeout(()=>f.abort(lo(t.timeout)),t.timeout*1e3);try{e.maskDataUrl&&(bs("遮罩主图文件",qa(a[0]??"")),bs("遮罩文件",qa(e.maskDataUrl))),Wi(a.reduce((v,I)=>v+Xa(I),0)+(e.maskDataUrl?Xa(e.maskDataUrl):0));const m={model:t.model,input:fI(o,a,e.settings.allowPromptRewrite),tools:[uI(n,a.length>0,t,e.maskDataUrl,e.nativeTransparentBackground)],tool_choice:"required"};t.reasoningEffort&&(m.reasoning={effort:t.reasoningEffort}),t.streamImages&&(m.stream=!0);const x=await Dr(ps(t.baseUrl,"responses",l,c),{method:"POST",headers:{...u,"Content-Type":"application/json"},cache:"no-store",body:JSON.stringify(m),signal:f.signal});if(!x.ok){const v=await va(x);throw new Error(Hi(Fp(v),x.status,t.streamImages))}if(t.streamImages&&nd(x))return await pI(x,i,e.onPartialImage);const b=await x.json(),h=Du(b,i),y=Ln(((g=h[0])==null?void 0:g.actualParams)??{});return{images:h.map(v=>v.image),actualParams:y,actualParamsList:h.map(v=>Ln(v.actualParams??{})),revisedPrompts:h.map(v=>v.revisedPrompt)}}finally{clearTimeout(d)}}async function ix(e){const t=zt(e.settings);return t.provider==="fal"?Z1(e,t):xI(e,t,Rn(e.settings,t.provider))}function co(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function pn(e,t){e[t]!==void 0&&typeof e[t]!="string"&&delete e[t]}function MI(e,t){const r={...e,type:t};return pn(r,"id"),pn(r,"status"),r}function EI(e){if(Array.isArray(e))return e.filter(co).map(t=>{const r={...t};return pn(r,"type"),pn(r,"url"),pn(r,"title"),r.start_index!==void 0&&(typeof r.start_index!="number"||!Number.isFinite(r.start_index))&&delete r.start_index,r.end_index!==void 0&&(typeof r.end_index!="number"||!Number.isFinite(r.end_index))&&delete r.end_index,r})}function RI(e){if(!Array.isArray(e))return null;const t=[];for(const r of e)if(!(!co(r)||typeof r.type!="string"||!r.type.trim())){if(r.type==="output_text"||r.type==="text"){if(typeof r.text!="string")continue;const n=EI(r.annotations),a={...r,type:r.type,text:r.text};n?a.annotations=n:delete a.annotations,t.push(a);continue}if(r.type==="refusal"){if(typeof r.refusal!="string")continue;t.push({...r,type:r.type,refusal:r.refusal});continue}t.push({...r,type:r.type})}return t}function Vm(e){return typeof e=="string"?e:co(e)?{...e}:void 0}function _I(e){if(e===null)return null;if(typeof e=="string")return e;if(!co(e))return;const t={...e};return pn(t,"b64_json"),pn(t,"base64"),pn(t,"image"),pn(t,"data"),t}function DI(e){if(!Array.isArray(e))return null;const t=[];for(const r of e)if(!(!co(r)||typeof r.type!="string"||!r.type.trim())){if(r.type==="input_text"){if(typeof r.text!="string")continue;t.push({...r,type:r.type,text:r.text});continue}if(r.type==="input_image"){const n=typeof r.image_url=="string"&&r.image_url.trim()?r.image_url:void 0,a=typeof r.file_id=="string"&&r.file_id.trim()?r.file_id:void 0;if(!n&&!a)continue;const o={...r,type:r.type};n?o.image_url=n:delete o.image_url,a?o.file_id=a:delete o.file_id,pn(o,"detail"),t.push(o);continue}if(r.type==="input_file"){const n={...r,type:r.type};for(const o of["file_data","file_id","file_url","filename"])pn(n,o);if(!["file_data","file_id","file_url"].some(o=>typeof n[o]=="string"&&!!n[o].trim()))continue;t.push(n);continue}t.push({...r,type:r.type})}return t}function Ns(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){if(!co(r)||typeof r.type!="string"||!r.type.trim())continue;const n=r.type,a=MI(r,n);if(n==="message"){const o=RI(r.content);if(!o)continue;t.push({...a,content:o});continue}if(n==="function_call"){if(typeof r.call_id!="string"||!r.call_id.trim()||typeof r.name!="string"||!r.name.trim()||typeof r.arguments!="string")continue;t.push({...a,call_id:r.call_id,name:r.name,arguments:r.arguments});continue}if(n==="function_call_output"){if(typeof r.call_id!="string"||!r.call_id.trim())continue;const o=typeof r.output=="string"?r.output:DI(r.output);if(o===null)continue;t.push({...a,call_id:r.call_id,output:o});continue}if(n==="image_generation_call"){const o=Vm(r.action),i=_I(r.result),l={...a};o!==void 0?l.action=o:delete l.action,i!==void 0?l.result=i:delete l.result,t.push(l);continue}if(n==="web_search_call"){const o=Vm(r.action),i={...a};o!==void 0?i.action=o:delete i.action,t.push(i);continue}t.push(a)}return t}const Km=["You are an image-generation assistant in a multi-turn gallery app.","","## Progressive Batch Generation","For multi-image requests, use a progressive batching strategy to ensure consistency:"," 1. **Base Reference First:** If the images need to share a consistent style, character, or layout (e.g. PPT slides, storyboards), generate ONE primary image first to establish the visual baseline, then call continue_generation to get another round."," 2. **Batch Remaining Tasks:** Once the base reference is available, list all remaining images to be generated. The app will generate them concurrently for you. In your descriptions, explicitly instruct to reference the base image to maintain consistency.",' 3. **Independent Images:** If the requested images are completely independent (e.g. "3 different cats"), generate them together in ONE response. Do NOT generate them one by one across multiple responses.',"As the turn continues, output a brief progress note before each tool call.","For single-image requests, generate directly without any listing.","","## Generating images","- One image_generation call per distinct image. Never collage.",'- Dependent images (a later image needs to reference an earlier one) → generate the prerequisite first, then call continue_generation. The next round will have the result available as `<ref id="..." />`.',"- Only generate when explicitly requested; otherwise reply with text.","- Preserve the user's original intent faithfully. Never substitute requested subjects for copyright/trademark reasons.","","## Reference tags and generated images in context","NEVER output `<ref>`, `<available_refs>`, `<removed_ref>`, or any XML reference tags in visible assistant text — the system injects them automatically and your raw output will be shown directly to the user.",'- Previously generated images are injected as user messages containing the actual image (input_image) followed by a `<ref id="round-N-image-M" prompt="..." />` tag identifying it.','- Deleted images appear as `<removed_ref id="..." />` without an accompanying image — do not reference them.','- In user messages: `<ref id="..." />` may also point to user-attached/cited images.','- In generate_image_batch tool arguments, include matching `<ref id="..." />` tags inside each image prompt when the prompt refers to a reference image. Do not use separate bare reference ids.','Resolve user mentions ("the first image") to the matching id. Only use existing ids in image_generation prompts and generate_image_batch prompts.'].join(`
|
|
22
|
+
`),LI=["## Math formatting","- When a response contains mathematical formulas, output them using Markdown math delimiters supported by this app.","- Use `$...$` for inline formulas.","- Use block math with opening and closing `$$` on their own lines for display formulas.","- Do not use LaTeX delimiters like `\\(...\\)` or `\\[...\\]` in visible assistant text."].join(`
|
|
23
|
+
`);function OI(e,t){const r=Number.isFinite(e.agentMaxToolRounds)?Math.max(1,Math.trunc(e.agentMaxToolRounds)):Jn,n=e.agentApiConfigMode==="hybrid"?"Use generate_image for single-image requests and generate_image_batch for concurrent multi-image requests. The built-in image_generation tool is not available in this session.":"Use image_generation for single-image requests and generate_image_batch for concurrent multi-image requests.",o=[e.agentApiConfigMode==="hybrid"?Km.replace(/image_generation/g,"generate_image"):Km,"","## Tool policy",`- Current maximum tool-use rounds for this Agent turn: ${r}.`,`- ${n}`,"- Call continue_generation ONLY when you have generated a prerequisite image and need another round to generate dependent images. Do NOT call it when the task is complete.","- When web_search is available, use it only when current external information would improve the answer or the user asks for research/news/facts.","- When the requested task is complete, stop calling tools and provide the final response."];return t&&t!=="auto"&&o.push("",`- Start every image prompt with exactly "Generate at ${t} resolution." followed by a space.`),e.agentMathFormattingPrompt&&o.push("",LI),o.join(`
|
|
24
|
+
`)}const BI=["Generate a concise conversation title from the first user message.","Output exactly one XML element in this form: <title>short title</title>","Do not output markdown, code fences, explanations, attributes, or additional XML elements.","Use the main language of the user message. Chinese titles should be no more than 12 characters. English titles should be no more than 5 words.","Escape XML special characters when necessary."].join(`
|
|
25
|
+
`),Xm=28;function zf(e){return{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json"}}function UI(e,t,r){const n={type:"image_generation",action:"auto",output_format:e.output_format,moderation:e.moderation},a=Ri(t);return a&&(n.model=a),t.codexCli||(n.size=e.size),n.quality=e.quality,e.output_format!=="png"&&e.output_compression!=null&&(n.output_compression=e.output_compression),t.streamImages&&(n.partial_images=t.streamPartialImages??kr),r&&(n.input_image_mask={image_url:r}),n}function FI(){return{type:"function",name:"generate_image",description:["Generate one image through the app image API. Use this for single-image requests or prerequisite/base images that later images must reference.","The prompt must be self-contained and include full visual style descriptions.",'If it refers to an existing image, include the corresponding XML tag, e.g. <ref id="round-1-image-1" />, inside the prompt so the app can attach the reference image automatically.'].join(" "),parameters:{type:"object",properties:{id:{type:"string",description:'Short stable identifier for this image, e.g. "cover", "base_character", "scene_1".'},prompt:{type:"string",description:"Complete image generation prompt with all visual details. Include matching XML ref tags when referring to existing images."}},required:["id","prompt"],additionalProperties:!1},strict:!0}}function $I(e,t,r,n){const a=r.agentApiConfigMode==="hybrid"?[FI()]:[UI(e,t,n)],o=r.agentApiConfigMode==="hybrid"?"For single images or prerequisite/base images, use the generate_image tool instead.":"For single images or prerequisite/base images, use the built-in image_generation tool instead.";return a.push({type:"function",name:"generate_image_batch",description:["Generate multiple images concurrently. Use this ONLY when:","1. There are 2+ remaining images whose prerequisites (base references) are ALL already generated.","2. These images are independent of each other (none references another image in this same batch).",o,"Each image prompt must be self-contained and include full visual style descriptions.",'If an image needs to match a previously generated image, include the corresponding XML tag (e.g. <ref id="round-1-image-1" />) inside that image prompt so the app can attach the reference image automatically.'].join(" "),parameters:{type:"object",properties:{images:{type:"array",description:"Array of images to generate concurrently.",items:{type:"object",properties:{id:{type:"string",description:'Short stable identifier for this image, e.g. "slide_2_problem", "scene_3".'},prompt:{type:"string",description:'Complete image generation prompt with all visual details. If it refers to a previous image, include the matching XML tag, e.g. <ref id="round-1-image-1" />.'}},required:["id","prompt"],additionalProperties:!1}}},required:["images"],additionalProperties:!1},strict:!0}),a.push({type:"function",name:"continue_generation",description:["Request another round to continue generating images.","Call this ONLY when you have just generated a prerequisite/base image and still need to generate dependent images that reference it.","Do NOT call this when the task is already complete."].join(" "),parameters:{type:"object",properties:{reason:{type:"string",description:"Brief explanation of why another round is needed and what will be generated next."}},required:["reason"],additionalProperties:!1},strict:!0}),r.agentWebSearch&&a.push({type:"web_search"}),a}function Vi(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Er(e,t){const r=e[t];return typeof r=="string"&&r?r:void 0}function Dl(e,t){const r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function zI(e){return e.replace(/\\/g,"\\\\").replace(/\]/g,"\\]")}function WI(e,t){const r=(t??[]).filter(o=>o.type==="url_citation"&&typeof o.url=="string"&&o.url.trim()&&typeof o.start_index=="number"&&typeof o.end_index=="number"&&o.start_index>=0&&o.end_index>o.start_index&&o.end_index<=e.length).sort((o,i)=>(o.start_index??0)-(i.start_index??0));if(r.length===0)return e;let n=0,a="";for(const o of r){const i=o.start_index??0,l=o.end_index??i;if(i<n)continue;a+=e.slice(n,i);const c=e.slice(i,l)||o.title||o.url||"source";a+=`[${zI(c)}](${o.url})`,n=l}return a+=e.slice(n),a}function lx(e){const t=e.error;if(Vi(t)){const n=Er(t,"message");if(n)return n}if(typeof t=="string"&&t.trim())return t;const r=Er(e,"type");return r!=null&&r.endsWith(".failed")?Er(e,"message")??"Agent 流式请求失败":null}function qm(e){return typeof e=="string"&&e.trim()?e.trim():Vi(e)?Er(e,"message")??Er(e,"code")??null:null}function HI(e,t){if((t==null?void 0:t.type)!=="image_generation_call"||t.status!=="failed")return null;const r=typeof(t==null?void 0:t.id)=="string"&&t.id||Er(e,"item_id");if(!r)return null;const n=t,a=qm(n==null?void 0:n.error)??qm(e.error)??Er(e,"message")??"内置 image_generation 工具调用失败";return{toolCallId:r,error:a}}function Wf(e){const t=[];for(const r of e.output??[])if(r.type==="message")for(const n of r.content??[])(n.type==="output_text"||n.type==="text")&&typeof n.text=="string"?t.push(WI(n.text,n.annotations)):n.type==="refusal"&&typeof n.refusal=="string"&&t.push(n.refusal);return t.join(`
|
|
26
|
+
`).trim()}function YI(e){return e.replace(/&(?:#(\d+)|#x([\da-fA-F]+)|amp|lt|gt|quot|apos);/g,(t,r,n)=>{if(r)return String.fromCodePoint(Number(r));if(n)return String.fromCodePoint(Number.parseInt(n,16));switch(t){case"&":return"&";case"<":return"<";case">":return">";case""":return'"';case"'":return"'";default:return t}})}function VI(e){const t=e.match(/<title>([\s\S]*?)<\/title>/i),r=t?YI(t[1]).trim():"",n=Array.from(r);return n.length<=Xm?r:`${n.slice(0,Xm-3).join("")}...`}function sc(e,t){const r=[];for(const n of e.output??[]){if(n.type!=="image_generation_call")continue;const a=Zc(n.result);a&&r.push({toolCallId:typeof n.id=="string"?n.id:void 0,action:typeof n.action=="string"?n.action:void 0,dataUrl:Rr(a,t),actualParams:Yi(n),revisedPrompt:typeof n.revised_prompt=="string"?n.revised_prompt:void 0})}return r}function cx(e,t){if(e.type!=="image_generation_call")return null;const r=Zc(e.result);return r?{toolCallId:typeof e.id=="string"?e.id:void 0,action:typeof e.action=="string"?e.action:void 0,dataUrl:Rr(r,t),actualParams:Yi(e),revisedPrompt:typeof e.revised_prompt=="string"?e.revised_prompt:void 0}:null}function id(e){return Vi(e)?{...e,...typeof e.id=="string"?{id:e.id}:{id:void 0},output:Ns(e.output)}:null}function Lu(e){const t=e.response,r=id(t);if(r)return r;const n=e.item,a=Ns([n]);return a.length?{output:a}:null}async function KI(e,t,r,n,a,o,i,l,c,u){let f=null;const d=[];let g="";const m=(y,v)=>{for(let I=0;I<y.length;I+=1){const S=y[I],k=v==null?void 0:v[I];let j=S.id?d.findIndex(A=>A.id===S.id):-1;if(j<0&&!S.id&&typeof k=="number"&&k>=0&&k<d.length){const A=d[k];(A==null?void 0:A.type)===S.type&&(j=k)}if(j<0&&!S.id&&S.type){const A=d.map((N,C)=>N.type===S.type?C:-1).filter(N=>N>=0);A.length===1&&(j=A[0])}j>=0?d[j]=S:d.push(S)}o==null||o([...d])},x=(y,v,I)=>{const S=Er(y,"item_id");if(!S)return;const k=d.findIndex(N=>N.id===S),A={...k>=0?d[k]:{id:S,type:"web_search_call"},id:S,type:"web_search_call",status:v,...I?{action:{type:I}}:{}};k>=0?d[k]=A:d.push(A),o==null||o([...d])};await sd(e,async y=>{var S,k;const v=Er(y,"type");if(v==="response.image_generation_call.partial_image"){const j=Er(y,"item_id"),A=Er(y,"partial_image_b64");j&&A&&await(l==null?void 0:l({toolCallId:j,image:Rr(A,t),partialImageIndex:Dl(y,"partial_image_index"),outputIndex:Dl(y,"output_index")}));return}if(v==="response.web_search_call.searching"){x(y,"in_progress","search");return}if(v==="response.web_search_call.completed"){x(y,"completed");return}if(v==="response.web_search_call.failed"){x(y,"failed");return}if(v==="response.web_search_call.in_progress"){x(y,"in_progress");return}if(v==="response.output_text.delta"){const j=Er(y,"delta");j&&(g+=j,a==null||a(j));return}const I=Lu(y);if(I){if(Array.isArray(I.output)){const j=v==="response.completed"?I.output.map((A,N)=>N):void 0;m(I.output,j)}if(v==="response.output_item.added"){const j=(S=I.output)==null?void 0:S[0];(j==null?void 0:j.type)==="image_generation_call"&&typeof j.id=="string"&&j.id&&await(i==null?void 0:i({toolCallId:j.id,outputIndex:Dl(y,"output_index")}));return}if(v==="response.output_item.done"){const j=(k=I.output)==null?void 0:k[0],A=HI(y,j);if(A){await(u==null?void 0:u(A));return}const N=j?cx(j,t):null;N&&await(c==null?void 0:c(N));return}(v==="response.completed"||Vi(y.response))&&(f=I)}},{signals:[r,n],formatErrorMessage:Qc,getEventErrorMessage:lx}),Qt(r,n);const b=f??(d.length?{output:d}:null);if(!b)throw new Error("Agent 流式接口未返回最终响应数据");const h=Wf(b)||g.trim();return{responseId:b.id,text:h,images:sc(b,t),outputItems:b.output??[],rawResponsePayload:JSON.stringify(b,null,2)}}async function XI(e){const{settings:t,profile:r,imageProfile:n,params:a,input:o,maskDataUrl:i,signal:l,onTextDelta:c,onOutputItems:u,onImageToolStarted:f,onImagePartialImage:d,onImageToolCompleted:g,onImageToolFailed:m}=e,x=ya[a.output_format]||"image/png",b=sn(),h=ha(r.apiProxy,b),y=new AbortController,v=setTimeout(()=>y.abort(lo(r.timeout)),r.timeout*1e3),I=()=>y.abort();l!=null&&l.aborted&&y.abort(),l==null||l.addEventListener("abort",I,{once:!0});try{const S={model:r.model,instructions:OI(t,(n??r).codexCli?a.size:void 0),input:o,tools:$I(a,r,t,i)};r.reasoningEffort&&(S.reasoning={effort:r.reasoningEffort}),r.streamImages&&(S.stream=!0);const k=await Dr(ps(r.baseUrl,"responses",b,h),{method:"POST",headers:zf(r),cache:"no-store",body:JSON.stringify(S),signal:y.signal});if(!k.ok){const N=await va(k);throw new Error(Hi(N,k.status,r.streamImages))}if(r.streamImages&&nd(k))return await KI(k,x,y.signal,l,c,u,f,d,g,m);const j=await k.json(),A=id(j);if(!A)throw new Error("Agent 接口返回格式无效");return Qt(y.signal,l),{responseId:A.id,text:Wf(A),images:sc(A,x),outputItems:A.output,rawResponsePayload:JSON.stringify(A,null,2)}}finally{clearTimeout(v),l==null||l.removeEventListener("abort",I)}}async function qI(e){const{profile:t,prompt:r,imageDataUrls:n,signal:a}=e,o=sn(),i=ha(t.apiProxy,o),l=new AbortController,c=setTimeout(()=>l.abort(lo(t.timeout)),t.timeout*1e3),u=()=>l.abort();a!=null&&a.aborted&&l.abort(),a==null||a.addEventListener("abort",u,{once:!0});try{const f=[{type:"input_text",text:`The following is the first message the user sent in a conversation. Generate a title for this conversation.
|
|
27
|
+
|
|
28
|
+
${r}`}];for(const x of n??[])f.push({type:"input_image",image_url:x});const d={model:t.model,instructions:BI,input:[{role:"user",content:f}]};t.reasoningEffort&&(d.reasoning={effort:t.reasoningEffort});const g=await Dr(ps(t.baseUrl,"responses",o,i),{method:"POST",headers:zf(t),cache:"no-store",body:JSON.stringify(d),signal:l.signal});if(!g.ok)throw new Error(await va(g));const m=id(await g.json());if(!m)throw new Error("Agent 标题接口返回格式无效");return VI(Wf(m))}finally{clearTimeout(c),a==null||a.removeEventListener("abort",u)}}async function JI(e){const{profile:t,params:r,batchItemId:n,prompt:a,referenceImageDataUrls:o,referenceIds:i,allowPromptRewrite:l,signal:c,onImageToolStarted:u,onPartialImage:f,onImageToolCompleted:d}=e,g=ya[r.output_format]||"image/png",m=sn(),x=ha(t.apiProxy,m),b=new AbortController,h=setTimeout(()=>b.abort(lo(t.timeout)),t.timeout*1e3),y=()=>b.abort();c!=null&&c.aborted&&b.abort(),c==null||c.addEventListener("abort",y,{once:!0});try{const v=o.length>0?`Attached reference images correspond to these ids, in order: ${(i??[]).map(W=>`<ref id="${W}" />`).join(", ")||"reference images"}.`:"",I=l?a:`${Gc}
|
|
29
|
+
${a}`,S=[v,I].filter(Boolean).join(`
|
|
30
|
+
|
|
31
|
+
`);let k;o.length>0?k=[{role:"user",content:[{type:"input_text",text:S},...o.map(W=>({type:"input_image",image_url:W}))]}]:k=S;const j={type:"image_generation",action:o.length>0?"auto":"generate",output_format:r.output_format,moderation:r.moderation,quality:r.quality},A=Ri(t);A&&(j.model=A),t.codexCli||(j.size=r.size),r.output_format!=="png"&&r.output_compression!=null&&(j.output_compression=r.output_compression),t.streamImages&&(j.partial_images=t.streamPartialImages??kr);const N={model:t.model,input:k,tools:[j],tool_choice:"required"};t.reasoningEffort&&(N.reasoning={effort:t.reasoningEffort}),t.streamImages&&(N.stream=!0);const C=await Dr(ps(t.baseUrl,"responses",m,x),{method:"POST",headers:zf(t),cache:"no-store",body:JSON.stringify(N),signal:b.signal});if(!C.ok){const W=await va(C);return{batchItemId:n,image:null,error:Hi(Fp(W),C.status,t.streamImages)}}if(t.streamImages&&nd(C)){await(u==null?void 0:u());let W=null,F;return await sd(C,async _=>{var J;const O=Er(_,"type");if(O==="response.image_generation_call.partial_image"){const H=Er(_,"partial_image_b64");H&&await(f==null?void 0:f({image:Rr(H,g),partialImageIndex:Dl(_,"partial_image_index")}));return}if(O==="response.output_item.done"){const H=Lu(_),K=(J=H==null?void 0:H.output)==null?void 0:J[0];if(K){const te=cx(K,g);te&&(W=te,await(d==null?void 0:d(te)))}return}if(O==="response.completed"||Vi(_.response)){const H=Lu(_);if(H&&(F=JSON.stringify(H,null,2)),!W&&H){const K=sc(H,g);K.length>0&&(W=K[0],await(d==null?void 0:d(W)))}}},{signals:[b.signal,c],formatErrorMessage:Qc,getEventErrorMessage:lx}),{batchItemId:n,image:W,error:W?null:"流式响应未返回图片",rawResponsePayload:F}}const T=id(await C.json());if(!T)throw new Error("图像接口返回格式无效");const U=sc(T,g)[0]??null;return U&&await(d==null?void 0:d(U)),{batchItemId:n,image:U,error:U?null:"接口未返回图片数据",rawResponsePayload:JSON.stringify(T,null,2)}}catch(v){return b.signal.aborted||c!=null&&c.aborted?{batchItemId:n,image:null,error:"请求已取消"}:{batchItemId:n,image:null,error:v instanceof Error?v.message:String(v)}}finally{clearTimeout(h),c==null||c.removeEventListener("abort",y)}}function ld(e){try{const t=JSON.parse(e);if(!t||!Array.isArray(t.images))return null;const r=[],n=new Set;for(const a of t.images){if(!a||typeof a!="object")continue;const o=a,i=typeof o.prompt=="string"?o.prompt.trim():"";if(!i)continue;const l=(typeof o.id=="string"?o.id.trim():"")||`image_${r.length+1}`;let c=l;for(let u=2;n.has(c);u++)c=`${l}_${u}`;n.add(c),r.push({id:c,prompt:i})}return r.length>0?r:null}catch{return null}}const GI=/@(?:第)?(\d+)轮图(\d+)/g;function ac(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Hf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ZI(e,t){if(!Hf(e))return null;const r=e;if(typeof r.id!="string"||!r.id||typeof r.userMessageId!="string"||!r.userMessageId)return null;const n=r.status==="running"?"error":r.status==="error"||r.status==="done"?r.status:"done",a=Array.isArray(r.responseOutput)?Ns(r.responseOutput):void 0;return{id:r.id,index:typeof r.index=="number"?r.index:t+1,parentRoundId:typeof r.parentRoundId=="string"?r.parentRoundId:null,userMessageId:r.userMessageId,...typeof r.assistantMessageId=="string"?{assistantMessageId:r.assistantMessageId}:{},prompt:typeof r.prompt=="string"?r.prompt:"",inputImageIds:ac(r.inputImageIds),maskTargetImageId:typeof r.maskTargetImageId=="string"?r.maskTargetImageId:null,maskImageId:typeof r.maskImageId=="string"?r.maskImageId:null,outputTaskIds:ac(r.outputTaskIds),...typeof r.responseId=="string"?{responseId:r.responseId}:{},...a?{responseOutput:a}:{},status:n,error:n==="error"?typeof r.error=="string"?r.error:"上次请求已中断":null,createdAt:typeof r.createdAt=="number"?r.createdAt:Date.now(),finishedAt:typeof r.finishedAt=="number"?r.finishedAt:null}}function QI(e){if(!Hf(e))return null;const t=e;return typeof t.id!="string"||!t.id||t.role!=="user"&&t.role!=="assistant"||typeof t.roundId!="string"||!t.roundId?null:{id:t.id,role:t.role,content:typeof t.content=="string"?t.content:"",roundId:t.roundId,...Array.isArray(t.inputImageIds)?{inputImageIds:ac(t.inputImageIds)}:{},maskTargetImageId:typeof t.maskTargetImageId=="string"?t.maskTargetImageId:null,maskImageId:typeof t.maskImageId=="string"?t.maskImageId:null,...Array.isArray(t.outputTaskIds)?{outputTaskIds:ac(t.outputTaskIds)}:{},createdAt:typeof t.createdAt=="number"?t.createdAt:Date.now()}}function Yf(e){return e.rounds.length===0&&e.messages.length===0&&!e.activeRoundId}function Ho(e){if(!Array.isArray(e))return[];const t=new Set;return e.filter(r=>{if(!Hf(r))return!1;const n=r.id;return typeof n!="string"||!n||t.has(n)?!1:(t.add(n),!0)}).map(r=>{var f;const n=new Set,a=Array.isArray(r.rounds)?r.rounds.map(ZI).filter(d=>!d||n.has(d.id)?!1:(n.add(d.id),!0)):[],o=a.some(d=>d.parentRoundId),i=typeof r.activeRoundId=="string",l=o||i?a:a.map((d,g)=>({...d,parentRoundId:g>0?a[g-1].id:null})),c=new Set,u=Array.isArray(r.messages)?r.messages.map(QI).filter(d=>!d||!n.has(d.roundId)||c.has(d.id)?!1:(c.add(d.id),!0)):[];return{id:r.id,title:typeof r.title=="string"&&r.title.trim()?r.title:"新对话",activeRoundId:typeof r.activeRoundId=="string"&&n.has(r.activeRoundId)?r.activeRoundId:((f=l[l.length-1])==null?void 0:f.id)??null,createdAt:typeof r.createdAt=="number"?r.createdAt:Date.now(),updatedAt:typeof r.updatedAt=="number"?r.updatedAt:Date.now(),rounds:l,messages:u}})}function oc(e,t){return e.rounds.filter(r=>(r.parentRoundId??null)===t)}function dx(e,t=null){var a,o;let r=t;if(!r){const i=oc(e,null);r=((a=i[i.length-1])==null?void 0:a.id)??null}const n=new Set;for(;r&&!n.has(r);){n.add(r);const i=oc(e,r),l=((o=i[i.length-1])==null?void 0:o.id)??null;if(!l)return r;r=l}return null}function ys(e,t){if(!t)return[];const r=new Map(e.rounds.map(i=>[i.id,i])),n=[],a=new Set;let o=r.get(t)??null;for(;o&&!a.has(o.id);)a.add(o.id),n.unshift(o),o=o.parentRoundId?r.get(o.parentRoundId)??null:null;return n}function fa(e){const t=e.activeRoundId&&e.rounds.some(r=>r.id===e.activeRoundId)?e.activeRoundId:dx(e);return ys(e,t??null)}function e2(e){const t=new Map,r=new Set,n=(a,o)=>{for(const i of oc(e,a))r.has(i.id)||(r.add(i.id),t.set(i.id,o),n(i.id,o+1))};return n(null,1),{...e,rounds:e.rounds.map(a=>({...a,index:t.get(a.id)??a.index}))}}function Vf(e,t,r){if(!e||t.length===0)return e;const n=new Map(r.map((a,o)=>[a.id,o+1]));return e.replace(GI,(a,o,i)=>{const l=t[Number(o)-1];if(!l)return a;const c=n.get(l.id);return c?`@第${c}轮图${i}`:`@已删除轮次图${i}`})}function t2(e,t,r=Date.now()){var g;const n=e.rounds.find(m=>m.id===t);if(!n)return e;const a=new Map(e.rounds.map(m=>[m.id,ys(e,m.id)])),o=e.rounds.filter(m=>m.id!==t).map(m=>m.parentRoundId===t?{...m,parentRoundId:n.parentRoundId??null}:m),i=e.messages.filter(m=>m.roundId!==t),l=e2({...e,rounds:o,messages:i,activeRoundId:e.activeRoundId===t?null:e.activeRoundId??null}),c=new Map(l.rounds.map(m=>[m.id,ys(l,m.id)])),u=l.messages.map(m=>{const x=a.get(m.roundId)??[],b=c.get(m.roundId)??[],h=Vf(m.content,x,b);return h===m.content?m:{...m,content:h}}),f={...l,messages:u},d=fa(f);return{...f,activeRoundId:f.activeRoundId??((g=d[d.length-1])==null?void 0:g.id)??null,updatedAt:r}}function Jm(e,t){return oc(e,t.parentRoundId??null)}function r2(e,t){return dx(e,t)??t}function gn(e){return Array.from(new Set(e.filter(Boolean)))}function n2(e,t){if(!e)return[];const r=new Set(t.map(a=>a.id)),n=new Set(e.rounds.map(a=>a.id));return gn([...e.rounds.flatMap(a=>a.outputTaskIds),...t.filter(a=>a.agentConversationId===e.id||!!(a.agentRoundId&&n.has(a.agentRoundId))).map(a=>a.id)]).filter(a=>r.has(a))}function ux(e){return[e.title,...e.messages.map(t=>t.content),...e.rounds.map(t=>t.prompt)].map(gr).join(`
|
|
32
|
+
`).toLocaleLowerCase()}const s2=/@(?:第)?(\d+)轮图(\d+)/g,a2=/<ref\b[^>]*\bid=(["'])(round-(\d+)-(?:image|reference)-(\d+))\1[^>]*\/?>/g;function ic(e,t){return`round-${e.index}-reference-${t+1}`}function Ja(e,t){return`round-${e.index}-image-${t+1}`}function Gm(e){return`<ref id="${e}" />`}function o2(e){return`<removed_ref id="${e}" />`}function cd(e,t){const r=[];for(const n of e.outputTaskIds){const a=t.find(o=>o.id===n);if(!a){r.push(null);continue}r.push(...a.outputImages)}return r}function wl(e){return Array.from(e.matchAll(a2),t=>t[2]).filter(t=>!!t)}function fx(e,t,r,n){const a=$i(e,t.inputImageIds.length,l=>Gm(ic(t,l))),o=(l,c,u)=>{const f=Number(c)-1,d=Number(u)-1,g=r[f];if(!g||d<0)return l;const m=cd(g,n)[d];if(!m)return o2(Ja(g,d));const x=t.inputImageIds.indexOf(m),b=x>=0?ic(t,x):Ja(g,d);return Gm(b)},i=a.replace(s2,o);return gr(i)}function es(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Kf(e){if(e.type!=="image_generation_call"||e.result==null)return e;if(typeof e.result=="string"){const{result:i,...l}=e;return l}if(!es(e.result))return e;const{b64_json:t,base64:r,image:n,data:a,...o}=e.result;if(Object.keys(o).length===0){const{result:i,...l}=e;return l}return{...e,result:o}}function Xf(e){return e.map(t=>({...t,rounds:t.rounds.map(r=>{var n;return(n=r.responseOutput)!=null&&n.length?{...r,responseOutput:r.responseOutput.map(Kf)}:r})}))}function i2(e){return Array.isArray(e)?e.map(t=>!es(t)||!Array.isArray(t.rounds)?t:{...t,rounds:t.rounds.map(r=>!es(r)||!Array.isArray(r.responseOutput)?r:{...r,responseOutput:Ns(r.responseOutput).map(Kf)})}):e}function l2(e){if(!e)return e;try{const t=JSON.parse(e);if(!Array.isArray(t.output))return e;const r=Ns(t.output).map(Kf);return JSON.stringify({...t,output:r},null,2)}catch{return e}}function c2(e){if(!e)return null;try{const t=JSON.parse(e);return Array.isArray(t.output)?Ns(t.output):null}catch{return null}}function d2(e){if(e.type==="web_search_call"||e.type==="image_generation_call")return null;if(e.type==="message"){const t=(e.content??[]).map(r=>(r.type==="output_text"||r.type==="text")&&typeof r.text=="string"?{type:"output_text",text:r.text}:r.type==="refusal"&&typeof r.refusal=="string"?{type:"output_text",text:r.refusal}:null).filter(r=>!!r);return t.length>0?{role:"assistant",content:t}:null}return e}function gx(e,t={}){const r=e.map(d2).filter(o=>o!=null);if(t.allowPendingFunctionCalls)return r;const n=new Set,a=new Set;for(const o of r){if(!es(o))continue;const i=typeof o.call_id=="string"?o.call_id:"";i&&(o.type==="function_call"&&n.add(i),o.type==="function_call_output"&&a.add(i))}return r.filter(o=>{if(!es(o))return!0;const i=typeof o.call_id=="string"?o.call_id:"";return o.type==="function_call"?i&&a.has(i):o.type==="function_call_output"?i&&n.has(i):!0})}function Zm(e){let t=!1;const r=e.map(n=>{if(n.type!=="function_call"||n.name!=="generate_image_batch")return n;const a=ld(n.arguments??"");if(!a)return n;try{const o=JSON.parse(n.arguments??"{}");if(!es(o))return n;const i=JSON.stringify({...o,images:a});return i===n.arguments?n:(t=!0,{...n,arguments:i})}catch{return n}});return t?r:e}function Yo(e,t,r,n){const a=new Set(r.map(x=>x.id)),o=new Set(r.filter(x=>x.agentRoundId===e.id&&x.agentToolCallId).map(x=>x.agentToolCallId));if(a.size===0)return t;const i=new Set(r.filter(x=>x.agentToolCallId&&!x.agentBatchCallId).map(x=>x.agentToolCallId)),l=new Map(n.map(x=>[x.id,x])),c=new Map;for(const x of t){if(x.type!=="function_call"||x.name!=="generate_image_batch"||!x.call_id)continue;const b=ld(x.arguments??"");b&&c.set(x.call_id,b)}const u=new Map,f=new Map;for(const x of new Set(r.map(b=>b.agentBatchCallId).filter(b=>!!b))){const b=e.outputTaskIds.map(v=>l.get(v)).filter(v=>(v==null?void 0:v.agentBatchCallId)===x);if(f.set(x,b),b.length>0&&b.every(v=>a.has(v.id))){i.add(x);continue}const h=(c.get(x)??[]).map(v=>v.id),y=new Set;for(let v=0;v<b.length;v++){const I=b[v];if(!a.has(I.id))continue;const S=h.length===b.length?h[v]:I.agentBatchItemId;S&&y.add(S)}y.size>0&&u.set(x,y)}let d=0,g=!1;const m=[];for(const x of t){if(x.type==="image_generation_call"){const y=e.outputTaskIds[d];if(d+=1,x.id&&o.has(x.id)||!x.id&&a.has(y)){g=!0;continue}m.push(x);continue}const b=x.call_id??"";if(b&&i.has(b)&&(x.type==="function_call"||x.type==="function_call_output")){g=!0;continue}const h=b?u.get(b):void 0;if(!(h!=null&&h.size)||x.type!=="function_call"&&x.type!=="function_call_output"){m.push(x);continue}if(x.type==="function_call"){try{const y=JSON.parse(x.arguments??"{}"),v=c.get(b);if(!v){m.push(x);continue}const I=JSON.stringify({...y,images:v.filter(S=>!h.has(S.id))});if(I===x.arguments){m.push(x);continue}g=!0,m.push({...x,arguments:I})}catch{m.push(x)}continue}if(typeof x.output!="string"){m.push(x);continue}try{const y=JSON.parse(x.output);if(!Array.isArray(y.images)){m.push(x);continue}const v=c.get(b),I=f.get(b),k=(v&&(I==null?void 0:I.length)===v.length&&y.images.length===v.length?y.images.map((A,N)=>es(A)?{...A,id:v[N].id}:A):y.images).filter(A=>!es(A)||typeof A.id!="string"||!h.has(A.id)),j=JSON.stringify({...y,images:k});if(j===x.output){m.push(x);continue}g=!0,m.push({...x,output:j})}catch{m.push(x)}}return g?m:t}function u2(e,t,r,n){if(!e.rawResponsePayload)return e;try{const a=JSON.parse(e.rawResponsePayload);if(!Array.isArray(a.output))return e;const o=Ns(a.output),i=Yo(t,o,r,n);return JSON.stringify(i)===JSON.stringify(a.output)?e:{...e,rawResponsePayload:JSON.stringify({...a,output:i},null,2)}}catch{return e}}function Yd(e,t){const r=[...e];for(const n of t){const a=n.id?r.findIndex(o=>o.id===n.id):-1;a>=0?r[a]=n:r.push(n)}return r}function mx(e){return e.filter(t=>t.type==="image_generation_call").length}function f2(e,t){var r;if((r=e.responseOutput)!=null&&r.length)return e.responseOutput;for(const n of e.outputTaskIds){const a=t.find(i=>i.id===n),o=c2(a==null?void 0:a.rawResponsePayload);if(o!=null&&o.length)return o}return null}function qf(e){return new Set(e.filter(t=>t.type==="function_call_output"&&t.call_id).map(t=>t.call_id))}function g2(e,t){const r=e.responseOutput??[];if(r.length===0)return null;const n=qf(r),a=[],o=[];let i=!1,l=!0;for(const c of r)if(!(c.type!=="function_call"||!c.call_id||n.has(c.call_id))){if(c.name==="generate_image"){const u=(()=>{try{const g=JSON.parse(c.arguments??"{}");return typeof g.id=="string"&&g.id.trim()?g.id.trim():"image"}catch{return"image"}})(),f=t.find(g=>g.agentRoundId===e.id&&g.agentToolCallId===c.call_id);if(!f||f.status==="running"||f.falRecoverable||f.customRecoverable){i=!0;continue}o.push(f.id);const d=f.status==="done"&&f.outputImages.length>0;d||(l=!1),a.push({type:"function_call_output",call_id:c.call_id,output:JSON.stringify({id:u,status:d?"done":"error",...d?{}:{error:f.error||"图像生成失败"}})});continue}if(c.name==="generate_image_batch"){const u=ld(c.arguments??"");if(!(u!=null&&u.length))continue;const f=e.outputTaskIds.map(g=>t.find(m=>m.id===g)).filter(g=>!!(g&&g.agentBatchCallId===c.call_id));if(f.length<u.length||f.some(g=>g.status==="running"||g.falRecoverable||g.customRecoverable)){i=!0;continue}o.push(...f.map(g=>g.id));const d=u.map((g,m)=>{const x=f[m],b=(x==null?void 0:x.status)==="done"&&x.outputImages.length>0;return b||(l=!1),{id:g.id,status:b?"done":"error",...b?{}:{error:(x==null?void 0:x.error)||"图像生成失败"}}});a.push({type:"function_call_output",call_id:c.call_id,output:JSON.stringify({images:d})})}}return i||a.length===0?null:{additions:a,recoveredTaskIds:o,allSuccessful:l}}function m2(e,t){var i;const r=g2(e,t);if(r)return r;if(!((i=e.responseOutput)!=null&&i.length)||e.outputTaskIds.length===0)return null;const n=qf(e.responseOutput);if(e.responseOutput.some(l=>l.type==="function_call"&&(l.name==="generate_image"||l.name==="generate_image_batch")&&l.call_id&&!n.has(l.call_id)))return null;const o=e.outputTaskIds.map(l=>t.find(c=>c.id===l)).filter(l=>!!l);return o.length===0||o.some(l=>l.status==="running"||l.falRecoverable||l.customRecoverable)?null:{additions:[],recoveredTaskIds:o.map(l=>l.id),allSuccessful:o.every(l=>l.status==="done"&&l.outputImages.length>0)}}function h2(e,t){const n=e.filter(i=>i.type==="function_call_output").reduce((i,l)=>{if(typeof l.output!="string"||!l.output)return i;try{const c=JSON.parse(l.output);return Array.isArray(c.images)?i+c.images.filter(u=>es(u)&&u.status==="done").length:c.status==="done"?i+1:i}catch{return i}},0),a=mx(e),o=t.filter(i=>i.status==="done").length;return Math.max(n+a,o)}function p2(e,t){const r=e.outputTaskIds.map(n=>t.find(a=>a.id===n)).filter(n=>!!(n&&n.status==="error"&&!n.falRecoverable&&!n.customRecoverable));return r.length===0?"图像生成失败":r.length===1?r[0].error||"图像生成失败":"部分图像生成任务失败。"}async function x2(e,t,r,n,a){const o=[];for(const u of t.inputImageIds){const f=await a(u);f&&o.push(f)}const i=ys(e,t.id),l=fx(r.content,t,i,n),c=t.inputImageIds.length>0?`
|
|
33
|
+
|
|
34
|
+
<available_refs>${t.inputImageIds.map((u,f)=>`
|
|
35
|
+
<ref id="${ic(t,f)}" />`).join("")}
|
|
36
|
+
</available_refs>`:"";return{role:"user",content:[{type:"input_text",text:`${l}${c}`},...o.map(u=>({type:"input_image",image_url:u}))]}}function b2(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function hx(e,t,r){const n=ai(typeof t.prompt=="string"?t.prompt:"",t.inputImageIds.length).replace(/\s+/g," ").trim(),a=n.length>1200?`${n.slice(0,1200)}...`:n,o=a?` prompt="${b2(a)}"`:"";return{type:"input_text",text:`<ref id="${Ja(e,r)}"${o} />`}}async function y2(e,t,r){const n=[];let a=0;for(const o of e.outputTaskIds){const i=t.find(l=>l.id===o);if(!i){n.push({type:"input_text",text:`<removed_ref id="${Ja(e,a)}" />`}),a+=1;continue}for(const l of i.outputImages){const c=await r(l);c&&n.push({type:"input_image",image_url:c}),n.push(hx(e,i,a)),a+=1}}return n.length>0?{role:"user",content:n}:null}async function v2(e,t,r,n){const a=[];let o=0;for(const l of e.outputTaskIds){if(r.includes(l))break;const c=t.find(u=>u.id===l);o+=c?c.outputImages.length:1}let i=o;for(const l of r){const c=t.find(u=>u.id===l);if(!(!c||c.status!=="done"))for(const u of c.outputImages){const f=await n(u);f&&a.push({type:"input_image",image_url:f}),a.push(hx(e,c,i)),i+=1}}return a.length>0?{role:"user",content:a}:null}function Qm(e){return{role:"assistant",content:[{type:"output_text",text:e}]}}async function w2(e){const t=[],r=ys(e.conversation,e.currentRound.id);for(const n of r){const a=e.conversation.messages.find(i=>i.id===n.userMessageId);if(!a||(t.push(await x2(e.conversation,n,a,e.tasks,e.loadImage)),n.id===e.currentRound.id))continue;const o=f2(n,e.tasks);if(o!=null&&o.length){const i=gx(o);if(i.length>0)t.push(...i);else{const l=n.assistantMessageId?e.conversation.messages.find(c=>c.id===n.assistantMessageId):null;t.push(Qm((l==null?void 0:l.content)||"图像已生成。"))}}else{const i=n.assistantMessageId?e.conversation.messages.find(l=>l.id===n.assistantMessageId):null;t.push(Qm((i==null?void 0:i.content)||"[No text response]"))}if(n.outputTaskIds.length>0){const i=await y2(n,e.tasks,e.loadImage);i&&t.push(i)}}return t}async function e0(e){const t=new Set((e.functionCallOutputs??[]).filter(l=>l.type==="function_call_output"&&l.call_id).map(l=>l.call_id)),r=e.currentRoundOutput.filter(l=>l.type!=="function_call_output"||!l.call_id||!t.has(l.call_id)),n=[...e.baseInput,...gx(r,{allowPendingFunctionCalls:!0}),...e.functionCallOutputs??[]],a=await v2(e.currentRound,e.tasks,e.batchTaskIds,e.loadImage);a&&n.push(a);const o=cd(e.currentRound,e.tasks).map((l,c)=>l?`<ref id="${Ja(e.currentRound,c)}" />`:null).filter(l=>!!l),i=["[System] The app has saved your generated outputs and is continuing the same Agent turn."];return o.length>0&&i.push(`The following image ref ids are now available for you to reference in subsequent image_generation prompts: ${o.join(", ")}`),i.push("Continue generating. Do NOT repeat what you already said in earlier responses.","If you still need another round after this (e.g. more dependent images), call continue_generation.",`Tool-call budget: ${e.toolCallsUsed}/${e.maxToolCalls} used.`),n.push({role:"user",content:[{type:"input_text",text:i.join(`
|
|
37
|
+
`)}]}),n}function px(){return typeof window>"u"||!("Notification"in window)?null:window.Notification}function xx(){return typeof window<"u"&&window.isSecureContext}function k2(){const e=px();return e?xx()?e.permission==="granted"?{ok:!0}:{ok:!1,reason:e.permission}:{ok:!1,reason:"insecure"}:{ok:!1,reason:"unsupported"}}async function bx(){const e=k2();if(e.ok||e.reason!=="default")return e;try{const t=await window.Notification.requestPermission();return t==="granted"?{ok:!0}:t==="denied"?{ok:!1,reason:"denied"}:{ok:!1,reason:"default"}}catch(t){return{ok:!1,reason:"error",error:t}}}function I2(e,t){const r=px();if(!r||!xx()||r.permission!=="granted")return!1;try{const n=new r(e,{tag:"task-completion",requireInteraction:!1,...t});return n.onclick=()=>{window.focus(),n.close()},!0}catch{return!1}}const Ou="1360x1024",C2=4,j2=10;function yx(e){return zt(e).provider==="fal"?C2:j2}function Mn(e,t,r={}){const n=zt(t),a=yx(t),o={...e,size:ad(e.size)||Qr.size,n:Math.min(a,Math.max(1,e.n||Qr.n))};return ei(t,n.provider)&&n.codexCli&&(o.size=Of(o.size),o.quality=Qr.quality),n.provider==="fal"&&(!r.hasInputImages&&o.size==="auto"&&(o.size=Ou),o.quality==="auto"&&(o.quality="high"),o.moderation=Qr.moderation,o.output_compression=Qr.output_compression),(o.quality==="xhigh"||o.quality==="max")&&!ff(Ri(n))&&(o.quality="high"),o.output_format==="png"&&(o.output_compression=Qr.output_compression),o}function vx(e,t){const r={};for(const n of Object.keys(t))e[n]!==t[n]&&(r[n]=t[n]);return r}const Bu="#00FF00",Uu="#FF00FF",Fu={[Bu]:{r:0,g:255,b:0},[Uu]:{r:255,g:0,b:255}},S2=["[Background instructions]","Background color rule: if the subject contains any green tones (green, teal, yellow-green, grass green, etc.), use a solid magenta (#FF00FF) background; otherwise always use a solid green (#00FF00) background.","Background requirements: fill the entire canvas with the chosen solid color only, with no gradients, textures, shadows, lighting changes, ground, or environmental elements.","Subject requirements: a single subject, fully visible, with clean and sharp outlines. Keep a clean edge separation between the subject and the background, with no color bleeding or blending.","Forbidden: the chosen background color must not appear in the subject itself, its outlines, glows, shadows, or reflections."].join(`
|
|
38
|
+
`);function N2(e){return`${e.trim()}
|
|
39
|
+
|
|
40
|
+
${S2}`}function wx(e){return{...e,output_format:e.output_format==="webp"?"webp":"png",output_compression:e.output_format==="webp"?e.output_compression:null,transparent_output:!0}}function kx(e){return{transparentOutput:!0,effectivePrompt:N2(e)}}async function t0(e,t,r="png",n){const a=await On(e),o=document.createElement("canvas");o.width=a.naturalWidth,o.height=a.naturalHeight;const i=o.getContext("2d",{willReadFrequently:!0});if(!i)throw new Error("当前浏览器不支持 Canvas,无法执行透明背景后处理");i.drawImage(a,0,0);const l=i.getImageData(0,0,o.width,o.height),c=A2(l.data,o.width,o.height);P2(l.data,o.width,o.height,c),i.putImageData(l,0,0);const u=r==="webp"&&n!=null?Math.max(0,Math.min(1,1-n/100)):void 0;return o.toDataURL(`image/${r}`,u)}function A2(e,t,r){const n=[];for(let c=0;c<t;c+=1)n.push(c),n.push((r-1)*t+c);for(let c=1;c<r-1;c+=1)n.push(c*t),n.push(c*t+t-1);let a=0,o=0;const i=Fu[Bu],l=Fu[Uu];for(const c of n){const u=c*4,f=e[u],d=e[u+1],g=e[u+2],m=Math.sqrt((f-i.r)**2+(d-i.g)**2+(g-i.b)**2),x=Math.sqrt((f-l.r)**2+(d-l.g)**2+(g-l.b)**2);m<100&&(a+=1),x<100&&(o+=1)}return o>a?Uu:Bu}function P2(e,t,r,n){if(e.length<t*r*4)throw new Error("透明背景像素数据尺寸不匹配");const a=O2(n),o=T2(e,t,r,a);return R2(e,o,t,r,a),e}function T2(e,t,r,n){const a=M2(e,t,r,n);return E2(e,t,r,n,a),a}function M2(e,t,r,n){const a=t*r,o=new Uint8Array(a),i=new Uint8Array(a),l=new Uint32Array(a);let c=0,u=0;const f=d=>{i[d]||(i[d]=1,!(Vo(e,d,n)<.18)&&(o[d]=1,l[u]=d,u+=1))};for(let d=0;d<t;d+=1)f(d),f((r-1)*t+d);for(let d=1;d<r-1;d+=1)f(d*t),f(d*t+t-1);for(;c<u;){const d=l[c];c+=1;const g=d%t,m=Math.floor(d/t);g>0&&f(d-1),g<t-1&&f(d+1),m>0&&f(d-t),m<r-1&&f(d+t)}return o}function E2(e,t,r,n,a){const o=t*r,i=new Uint8Array(o),l=new Uint32Array(o),c=new Uint32Array(o);for(let u=0;u<o;u+=1){if(a[u]||i[u]||Vo(e,u,n)<.68)continue;let f=0,d=0,g=0,m=0,x=0,b=0;i[u]=1,l[d]=u,d+=1;const h=k=>{k<0||a[k]||i[k]||Vo(e,k,n)<.24||(i[k]=1,l[d]=k,d+=1)};for(;f<d;){const k=l[f];f+=1;const j=Vo(e,k,n);c[g]=k,g+=1,m+=j,j>=.68&&(x+=1),j>=.86&&(b+=1);const A=k%t,N=Math.floor(k/t);h(A>0?k-1:-1),h(A<t-1?k+1:-1),h(N>0?k-t:-1),h(N<r-1?k+t:-1)}const y=m/g,v=x/g,I=b/g;if(y>=.42||v>=.18||I>=.05||g<=3&&y>=.34)for(let k=0;k<g;k+=1)a[c[k]]=1}}function R2(e,t,r,n,a){const o=_2(t,r,n,4),i=r*n;for(let l=0;l<i;l+=1){const c=l*4,u=e[c],f=e[c+1],d=e[c+2],g=Vo(e,l,a);let m=255;if(t[l])m=0;else{const b=o[l];if(b>0){const h=D2(u,f,d,g,b,a);h>0&&(m=Math.round(255*(1-h))),m=Math.max(m,b===1?48:b===2?128:196)}else{const h=Jf(u,f,d,a);g>=.46&&h>=.45&&(m=Math.round(255*(1-h*.75)),m=Math.max(m,96))}}const x=L2(u,f,d,m,a,g,o[l]);e[c]=x.r,e[c+1]=x.g,e[c+2]=x.b,e[c+3]=m}}function _2(e,t,r,n){const a=t*r,o=new Uint8Array(a);let i=[];for(let l=0;l<a;l+=1){if(e[l])continue;const c=l%t,u=Math.floor(l/t);(c>0&&e[l-1]||c<t-1&&e[l+1]||u>0&&e[l-t]||u<r-1&&e[l+t])&&(o[l]=1,i.push(l))}for(let l=1;l<n;l+=1){const c=[];for(const u of i){const f=u%t,d=Math.floor(u/t);kl(o,e,c,f>0?u-1:-1,l),kl(o,e,c,f<t-1?u+1:-1,l),kl(o,e,c,d>0?u-t:-1,l),kl(o,e,c,d<r-1?u+t:-1,l)}if(i=c,!i.length)break}return o}function kl(e,t,r,n,a){n<0||t[n]||e[n]!==0||(e[n]=a+1,r.push(n))}function Vo(e,t,r){const n=t*4,a=Math.sqrt((e[n]-r.r)**2+(e[n+1]-r.g)**2+(e[n+2]-r.b)**2);return Ga((150-a)/150)}function D2(e,t,r,n,a,o){const i=a<=1?1:a===2?.75:a===3?.45:.25,l=Ga((n-.08)/.84*i),c=Jf(e,t,r,o)*i;return Ga(Math.max(l,c))}function Jf(e,t,r,n){return n.g===255?Ga((t-Math.min(e,r))/255):Ga((Math.min(e,r)-t*.65)/255)}function L2(e,t,r,n,a,o,i){if(n===0)return{r:e,g:t,b:r};const l=i<=0?o>=.46?.35:0:i===1?.55:i===2?.32:.16,c=Jf(e,t,r,a)*l,u=Ga(Math.max((255-n)/255,(o-.1)/.9*l,c));if(u<=0)return{r:e,g:t,b:r};const f=Math.max(.08,1-u);return{r:Vd((e-a.r*u)/f),g:Vd((t-a.g*u)/f),b:Vd((r-a.b*u)/f)}}function O2(e){const t=Fu[e.toUpperCase()];if(!t)throw new Error("透明背景键色不支持");return t}function Ga(e){return Math.max(0,Math.min(1,e))}function Vd(e){return Math.max(0,Math.min(255,Math.round(e)))}const hn=new Map,yn=new Map,vs=new Map,ci=new Set,Ra=new Map,zs=new Map,lc=new Map;let Kd=!1;const B2=8,U2=200,F2=4;function Ix(e,t){if(!t.startsWith("blob:"))return;if(!zs.has(e)){URL.revokeObjectURL(t);return}const r=lc.get(e);r?r.push(t):lc.set(e,[t])}function dd(e){const t=yn.get(e);t&&(yn.delete(e),Ix(e,t.src))}function Cx(){for(const e of yn.keys()){if(yn.size<=U2)return;zs.has(e)||dd(e)}}function En(e){const t=hn.get(e);return t&&(hn.delete(e),hn.set(e,t)),t}function Xt(e,t){for(hn.delete(e),hn.set(e,t);hn.size>B2;){const r=hn.keys().next().value;if(r==null)break;hn.delete(r)}}function jx(e){hn.delete(e)}function cc(e){const t=yn.get(e);if((t==null?void 0:t.thumbnailVersion)===Dn)return yn.delete(e),yn.set(e,t),t;t&&dd(e)}function Ki(e,t){if(t.thumbnailVersion!==Dn)return;const r=yn.get(e);yn.delete(e),yn.set(e,t),r&&r.src!==t.src&&Ix(e,r.src),Cx()}function $2(e){hn.delete(e),dd(e),vs.delete(e),ci.delete(e),Ra.delete(e)}function z2(){hn.clear();for(const e of[...yn.keys()])dd(e);vs.clear()}async function kt(e){const t=En(e);if(t)return t;const r=await qn(e);if(r)return Xt(e,r.dataUrl),r.dataUrl}async function Sx(e){const t=cc(e);if(t)return t;const r=De?await W2(e):await lk(e,Dn);if(!r){$u([e],"visible");return}const n=cc(e);return n?(n.src!==r.src&&r.src.startsWith("blob:")&&URL.revokeObjectURL(r.src),n):(Ki(e,r),r)}async function W2(e){const t=await Uh(e);if(!(!t||t.meta.thumbnailVersion!==Dn))return{src:t.meta.mime===Bh?Lv(t.meta.mime,t.bytes):URL.createObjectURL(new Blob([t.bytes],{type:t.meta.mime})),width:t.meta.width??void 0,height:t.meta.height??void 0,thumbnailVersion:t.meta.thumbnailVersion}}function Nx(e,t){let r=Ra.get(e);r||(r=new Set,Ra.set(e,r)),r.add(t),zs.set(e,(zs.get(e)??0)+1);let n=!0;return()=>{if(!n)return;n=!1,r==null||r.delete(t),(r==null?void 0:r.size)===0&&Ra.get(e)===r&&Ra.delete(e);const a=(zs.get(e)??1)-1;if(a>0){zs.set(e,a);return}zs.delete(e);for(const o of lc.get(e)??[])URL.revokeObjectURL(o);lc.delete(e),Cx()}}function $u(e,t="background"){for(const r of e){if(cc(r)||ci.has(r))continue;(!vs.get(r)||t==="visible")&&vs.set(r,t)}Gf()}async function Ax(e){try{const t=new Set(De?(await of()).filter(r=>r.thumbnailVersion===Dn).map(r=>r.id):await ik(Dn));$u(e.filter(r=>!t.has(r)))}catch(t){console.warn("查询图片信息失败,改为全部补全缩略图",t),$u(e)}}function Gf(){if(Kd||vs.size===0)return;Kd=!0;const e=()=>{Kd=!1,H2()};typeof window<"u"&&"requestIdleCallback"in window?window.requestIdleCallback(e,{timeout:2e3}):globalThis.setTimeout(e,250)}async function H2(){if(ci.size>0)return;const e=await Y2();for(const t of e)X2(t);vs.size>0&&Gf()}async function Y2(){const e=V2().slice(0,F2);if(e.length===0)return[];const t=De?new Map((await of().catch(()=>[])).map(o=>[o.id,o])):void 0,r=await Promise.all(e.map(async o=>{const i=t?t.get(o):await yp(o);return{width:(i==null?void 0:i.width)??void 0,height:(i==null?void 0:i.height)??void 0}})),n=K2(r),a=e.slice(0,n);for(const o of a)vs.delete(o);return a}function V2(){const e=[],t=[];for(const[r,n]of vs)n==="visible"?e.push(r):t.push(r);return[...e,...t]}function K2(e){let t=0;for(const{width:r,height:n}of e){if(!r||!n)return 1;t=Math.max(t,r*n/1e6)}return t>=8?1:t>=4?2:t>=2?3:4}async function X2(e){var t;ci.add(e);try{if(cc(e))return;const r=await kp(e);r!=null&&r.thumbnailDataUrl&&(Ki(e,{src:r.thumbnailDataUrl,width:r.width,height:r.height,thumbnailVersion:r.thumbnailVersion}),(t=Ra.get(e))==null||t.forEach(n=>n({src:r.thumbnailDataUrl,width:r.width,height:r.height})))}catch{}finally{ci.delete(e),Gf()}}let zu=0;function Zf(e,t){return e.some(r=>r.status==="running"||r.falRecoverable||r.customRecoverable)||t.some(r=>r.rounds.some(n=>n.status==="running"))}function Px(e){return e.apiProvider==="fal"&&!!(e.falRequestId&&e.falEndpoint)&&(e.status==="running"||!!e.falRecoverable)}function Tx(e){return!!e.customTaskId&&(e.status==="running"||!!e.customRecoverable)}function Mx(e,t,r){return zu>0||!!(r&&r.started<r.total)||e.some(n=>n.status==="running"&&!Px(n)&&!Tx(n))||t.some(n=>n.rounds.some(a=>a.status==="running"))}async function Ba(e){zu++;try{return await e()}finally{zu--}}function di(e){const t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}_${t(e.getHours())}-${t(e.getMinutes())}-${t(e.getSeconds())}`}function Ex(e,t,r){return r>1?`${e}-${String(t+1).padStart(2,"0")}`:e}function dc(e){return e.trim().replace(/[<>:"/\\|?*\x00-\x1f]+/g,"-").replace(/\s+/g," ").slice(0,120)}var r0={},q2=(function(e,t,r,n,a){var o=new Worker(r0[t]||(r0[t]=URL.createObjectURL(new Blob([e+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));return o.onmessage=function(i){var l=i.data,c=l.$e$;if(c){var u=new Error(c[0]);u.code=c[1],u.stack=c[2],a(u,null)}else a(null,l)},o.postMessage(r,n),o}),jt=Uint8Array,wr=Uint16Array,Xi=Int32Array,uo=new jt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fo=new jt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ui=new jt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rx=function(e,t){for(var r=new wr(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var a=new Xi(r[30]),n=1;n<30;++n)for(var o=r[n];o<r[n+1];++o)a[o]=o-r[n]<<5|n;return{b:r,r:a}},_x=Rx(uo,2),Qf=_x.b,uc=_x.r;Qf[28]=258,uc[258]=28;var Dx=Rx(fo,0),Lx=Dx.b,Wu=Dx.r,fi=new wr(32768);for(var St=0;St<32768;++St){var ds=(St&43690)>>1|(St&21845)<<1;ds=(ds&52428)>>2|(ds&13107)<<2,ds=(ds&61680)>>4|(ds&3855)<<4,fi[St]=((ds&65280)>>8|(ds&255)<<8)>>1}var rn=(function(e,t,r){for(var n=e.length,a=0,o=new wr(t);a<n;++a)e[a]&&++o[e[a]-1];var i=new wr(t);for(a=1;a<t;++a)i[a]=i[a-1]+o[a-1]<<1;var l;if(r){l=new wr(1<<t);var c=15-t;for(a=0;a<n;++a)if(e[a])for(var u=a<<4|e[a],f=t-e[a],d=i[e[a]-1]++<<f,g=d|(1<<f)-1;d<=g;++d)l[fi[d]>>c]=u}else for(l=new wr(n),a=0;a<n;++a)e[a]&&(l[a]=fi[i[e[a]-1]++]>>15-e[a]);return l}),ts=new jt(288);for(var St=0;St<144;++St)ts[St]=8;for(var St=144;St<256;++St)ts[St]=9;for(var St=256;St<280;++St)ts[St]=7;for(var St=280;St<288;++St)ts[St]=8;var Za=new jt(32);for(var St=0;St<32;++St)Za[St]=5;var Ox=rn(ts,9,0),Bx=rn(ts,9,1),Ux=rn(Za,5,0),Fx=rn(Za,5,1),Ll=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Gr=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},Ol=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},qi=function(e){return(e+7)/8|0},wa=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new jt(e.subarray(t,r))},$x=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Bt=function(e,t,r){var n=new Error(t||$x[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Bt),!r)throw n;return n},zx=function(e,t,r,n){var a=e.length,o=n?n.length:0;if(!a||t.f&&!t.l)return r||new jt(0);var i=!r,l=i||t.i!=2,c=t.i;i&&(r=new jt(a*3));var u=function(D){var ue=r.length;if(D>ue){var ke=new jt(Math.max(ue*2,D));ke.set(r),r=ke}},f=t.f||0,d=t.p||0,g=t.b||0,m=t.l,x=t.d,b=t.m,h=t.n,y=a*8;do{if(!m){f=Gr(e,d,1);var v=Gr(e,d+1,3);if(d+=3,v)if(v==1)m=Bx,x=Fx,b=9,h=5;else if(v==2){var j=Gr(e,d,31)+257,A=Gr(e,d+10,15)+4,N=j+Gr(e,d+5,31)+1;d+=14;for(var C=new jt(N),T=new jt(19),R=0;R<A;++R)T[ui[R]]=Gr(e,d+R*3,7);d+=A*3;for(var U=Ll(T),W=(1<<U)-1,F=rn(T,U,1),R=0;R<N;){var _=F[Gr(e,d,W)];d+=_&15;var I=_>>4;if(I<16)C[R++]=I;else{var O=0,J=0;for(I==16?(J=3+Gr(e,d,3),d+=2,O=C[R-1]):I==17?(J=3+Gr(e,d,7),d+=3):I==18&&(J=11+Gr(e,d,127),d+=7);J--;)C[R++]=O}}var H=C.subarray(0,j),K=C.subarray(j);b=Ll(H),h=Ll(K),m=rn(H,b,1),x=rn(K,h,1)}else Bt(1);else{var I=qi(d)+4,S=e[I-4]|e[I-3]<<8,k=I+S;if(k>a){c&&Bt(0);break}l&&u(g+S),r.set(e.subarray(I,k),g),t.b=g+=S,t.p=d=k*8,t.f=f;continue}if(d>y){c&&Bt(0);break}}l&&u(g+131072);for(var te=(1<<b)-1,P=(1<<h)-1,B=d;;B=d){var O=m[Ol(e,d)&te],$=O>>4;if(d+=O&15,d>y){c&&Bt(0);break}if(O||Bt(2),$<256)r[g++]=$;else if($==256){B=d,m=null;break}else{var Q=$-254;if($>264){var R=$-257,L=uo[R];Q=Gr(e,d,(1<<L)-1)+Qf[R],d+=L}var G=x[Ol(e,d)&P],se=G>>4;G||Bt(3),d+=G&15;var K=Lx[se];if(se>3){var L=fo[se];K+=Ol(e,d)&(1<<L)-1,d+=L}if(d>y){c&&Bt(0);break}l&&u(g+131072);var Y=g+Q;if(g<K){var le=o-K,ie=Math.min(K,Y);for(le+g<0&&Bt(3);g<ie;++g)r[g]=n[le+g]}for(;g<Y;++g)r[g]=r[g-K]}}t.l=m,t.p=B,t.b=g,t.f=f,m&&(f=1,t.m=b,t.d=x,t.n=h)}while(!f);return g!=r.length&&i?wa(r,0,g):r.subarray(0,g)},An=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},Pa=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},Bl=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var a=r.length,o=r.slice();if(!a)return{t:tg,l:0};if(a==1){var i=new jt(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(k,j){return k.f-j.f}),r.push({s:-1,f:25001});var l=r[0],c=r[1],u=0,f=1,d=2;for(r[0]={s:-1,f:l.f+c.f,l,r:c};f!=a-1;)l=r[r[u].f<r[d].f?u++:d++],c=r[u!=f&&r[u].f<r[d].f?u++:d++],r[f++]={s:-1,f:l.f+c.f,l,r:c};for(var g=o[0].s,n=1;n<a;++n)o[n].s>g&&(g=o[n].s);var m=new wr(g+1),x=fc(r[f-1],m,0);if(x>t){var n=0,b=0,h=x-t,y=1<<h;for(o.sort(function(j,A){return m[A.s]-m[j.s]||j.f-A.f});n<a;++n){var v=o[n].s;if(m[v]>t)b+=y-(1<<x-m[v]),m[v]=t;else break}for(b>>=h;b>0;){var I=o[n].s;m[I]<t?b-=1<<t-m[I]++-1:++n}for(;n>=0&&b;--n){var S=o[n].s;m[S]==t&&(--m[S],++b)}x=t}return{t:new jt(m),l:x}},fc=function(e,t,r){return e.s==-1?Math.max(fc(e.l,t,r+1),fc(e.r,t,r+1)):t[e.s]=r},Hu=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new wr(++t),n=0,a=e[0],o=1,i=function(c){r[n++]=c},l=1;l<=t;++l)if(e[l]==a&&l!=t)++o;else{if(!a&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(a),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(a);o=1,a=e[l]}return{c:r.subarray(0,n),n:t}},Ta=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},eg=function(e,t,r){var n=r.length,a=qi(t+2);e[a]=n&255,e[a+1]=n>>8,e[a+2]=e[a]^255,e[a+3]=e[a+1]^255;for(var o=0;o<n;++o)e[a+o+4]=r[o];return(a+4+n)*8},Yu=function(e,t,r,n,a,o,i,l,c,u,f){An(t,f++,r),++a[256];for(var d=Bl(a,15),g=d.t,m=d.l,x=Bl(o,15),b=x.t,h=x.l,y=Hu(g),v=y.c,I=y.n,S=Hu(b),k=S.c,j=S.n,A=new wr(19),N=0;N<v.length;++N)++A[v[N]&31];for(var N=0;N<k.length;++N)++A[k[N]&31];for(var C=Bl(A,7),T=C.t,R=C.l,U=19;U>4&&!T[ui[U-1]];--U);var W=u+5<<3,F=Ta(a,ts)+Ta(o,Za)+i,_=Ta(a,g)+Ta(o,b)+i+14+3*U+Ta(A,T)+2*A[16]+3*A[17]+7*A[18];if(c>=0&&W<=F&&W<=_)return eg(t,f,e.subarray(c,c+u));var O,J,H,K;if(An(t,f,1+(_<F)),f+=2,_<F){O=rn(g,m,0),J=g,H=rn(b,h,0),K=b;var te=rn(T,R,0);An(t,f,I-257),An(t,f+5,j-1),An(t,f+10,U-4),f+=14;for(var N=0;N<U;++N)An(t,f+3*N,T[ui[N]]);f+=3*U;for(var P=[v,k],B=0;B<2;++B)for(var $=P[B],N=0;N<$.length;++N){var Q=$[N]&31;An(t,f,te[Q]),f+=T[Q],Q>15&&(An(t,f,$[N]>>5&127),f+=$[N]>>12)}}else O=Ox,J=ts,H=Ux,K=Za;for(var N=0;N<l;++N){var L=n[N];if(L>255){var Q=L>>18&31;Pa(t,f,O[Q+257]),f+=J[Q+257],Q>7&&(An(t,f,L>>23&31),f+=uo[Q]);var G=L&31;Pa(t,f,H[G]),f+=K[G],G>3&&(Pa(t,f,L>>5&8191),f+=fo[G])}else Pa(t,f,O[L]),f+=J[L]}return Pa(t,f,O[256]),f+J[256]},Wx=new Xi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),tg=new jt(0),Hx=function(e,t,r,n,a,o){var i=o.z||e.length,l=new jt(n+i+5*(1+Math.ceil(i/7e3))+a),c=l.subarray(n,l.length-a),u=o.l,f=(o.r||0)&7;if(t){f&&(c[0]=o.r>>3);for(var d=Wx[t-1],g=d>>13,m=d&8191,x=(1<<r)-1,b=o.p||new wr(32768),h=o.h||new wr(x+1),y=Math.ceil(r/3),v=2*y,I=function(we){return(e[we]^e[we+1]<<y^e[we+2]<<v)&x},S=new Xi(25e3),k=new wr(288),j=new wr(32),A=0,N=0,C=o.i||0,T=0,R=o.w||0,U=0;C+2<i;++C){var W=I(C),F=C&32767,_=h[W];if(b[F]=_,h[W]=F,R<=C){var O=i-C;if((A>7e3||T>24576)&&(O>423||!u)){f=Yu(e,c,0,S,k,j,N,T,U,C-U,f),T=A=N=0,U=C;for(var J=0;J<286;++J)k[J]=0;for(var J=0;J<30;++J)j[J]=0}var H=2,K=0,te=m,P=F-_&32767;if(O>2&&W==I(C-P))for(var B=Math.min(g,O)-1,$=Math.min(32767,C),Q=Math.min(258,O);P<=$&&--te&&F!=_;){if(e[C+H]==e[C+H-P]){for(var L=0;L<Q&&e[C+L]==e[C+L-P];++L);if(L>H){if(H=L,K=P,L>B)break;for(var G=Math.min(P,L-2),se=0,J=0;J<G;++J){var Y=C-P+J&32767,le=b[Y],ie=Y-le&32767;ie>se&&(se=ie,_=Y)}}}F=_,_=b[F],P+=F-_&32767}if(K){S[T++]=268435456|uc[H]<<18|Wu[K];var D=uc[H]&31,ue=Wu[K]&31;N+=uo[D]+fo[ue],++k[257+D],++j[ue],R=C+H,++A}else S[T++]=e[C],++k[e[C]]}}for(C=Math.max(C,R);C<i;++C)S[T++]=e[C],++k[e[C]];f=Yu(e,c,u,S,k,j,N,T,U,C-U,f),u||(o.r=f&7|c[f/8|0]<<3,f-=7,o.h=h,o.p=b,o.i=C,o.w=R)}else{for(var C=o.w||0;C<i+u;C+=65535){var ke=C+65535;ke>=i&&(c[f/8|0]=u,ke=i),f=eg(c,f+1,e.subarray(C,ke))}o.i=i}return wa(l,0,n+qi(f)+a)},J2=(function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var r=t,n=9;--n;)r=(r&1&&-306674912)^r>>>1;e[t]=r}return e})(),Yx=function(){var e=-1;return{p:function(t){for(var r=e,n=0;n<t.length;++n)r=J2[r&255^t[n]]^r>>>8;e=r},d:function(){return~e}}},Vx=function(e,t,r,n,a){if(!a&&(a={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new jt(o.length+e.length);i.set(o),i.set(e,o.length),e=i,a.w=o.length}return Hx(e,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,a)},ud=function(e,t){var r={};for(var n in e)r[n]=e[n];for(var n in t)r[n]=t[n];return r},n0=function(e,t,r){for(var n=e(),a=e.toString(),o=a.slice(a.indexOf("[")+1,a.lastIndexOf("]")).replace(/\s+/g,"").split(","),i=0;i<n.length;++i){var l=n[i],c=o[i];if(typeof l=="function"){t+=";"+c+"=";var u=l.toString();if(l.prototype)if(u.indexOf("[native code]")!=-1){var f=u.indexOf(" ",8)+1;t+=u.slice(f,u.indexOf("(",f))}else{t+=u;for(var d in l.prototype)t+=";"+c+".prototype."+d+"="+l.prototype[d].toString()}else t+=u}else r[c]=l}return t},Il=[],G2=function(e){var t=[];for(var r in e)e[r].buffer&&t.push((e[r]=new e[r].constructor(e[r])).buffer);return t},Z2=function(e,t,r,n){if(!Il[r]){for(var a="",o={},i=e.length-1,l=0;l<i;++l)a=n0(e[l],a,o);Il[r]={c:n0(e[i],a,o),e:o}}var c=ud({},Il[r].e);return q2(Il[r].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+t.toString()+"}",r,c,G2(c),n)},Q2=function(){return[jt,wr,Xi,uo,fo,ui,Qf,Lx,Bx,Fx,fi,$x,rn,Ll,Gr,Ol,qi,wa,Bt,zx,rg,fd,Kx]},eC=function(){return[jt,wr,Xi,uo,fo,ui,uc,Wu,Ox,ts,Ux,Za,fi,Wx,tg,rn,An,Pa,Bl,fc,Hu,Ta,eg,Yu,qi,wa,Hx,Vx,gd,fd]},fd=function(e){return postMessage(e,[e.buffer])},Kx=function(e){return e&&{out:e.size&&new jt(e.size),dictionary:e.dictionary}},Xx=function(e,t,r,n,a,o){var i=Z2(r,n,a,function(l,c){i.terminate(),o(l,c)});return i.postMessage([e,t],t.consume?[e.buffer]:[]),function(){i.terminate()}},Pn=function(e,t){return e[t]|e[t+1]<<8},Zr=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Xd=function(e,t){return Zr(e,t)+Zr(e,t+4)*4294967296},nr=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function tC(e,t,r){return r||(r=t,t={}),typeof r!="function"&&Bt(7),Xx(e,t,[eC],function(n){return fd(gd(n.data[0],n.data[1]))},0,r)}function gd(e,t){return Vx(e,t||{},0,0)}function rC(e,t,r){return r||(r=t,t={}),typeof r!="function"&&Bt(7),Xx(e,t,[Q2],function(n){return fd(rg(n.data[0],Kx(n.data[1])))},1,r)}function rg(e,t){return zx(e,{i:2},t&&t.out,t&&t.dictionary)}var ng=function(e,t,r,n){for(var a in e){var o=e[a],i=t+a,l=n;Array.isArray(o)&&(l=ud(n,o[1]),o=o[0]),ArrayBuffer.isView(o)?r[i]=[o,l]:(r[i+="/"]=[new jt(0),l],ng(o,i,r,n))}},s0=typeof TextEncoder<"u"&&new TextEncoder,Vu=typeof TextDecoder<"u"&&new TextDecoder,nC=0;try{Vu.decode(tg,{stream:!0}),nC=1}catch{}var sC=function(e){for(var t="",r=0;;){var n=e[r++],a=(n>127)+(n>223)+(n>239);if(r+a>e.length)return{s:t,r:wa(e,r-1)};a?a==3?(n=((n&15)<<18|(e[r++]&63)<<12|(e[r++]&63)<<6|e[r++]&63)-65536,t+=String.fromCharCode(55296|n>>10,56320|n&1023)):a&1?t+=String.fromCharCode((n&31)<<6|e[r++]&63):t+=String.fromCharCode((n&15)<<12|(e[r++]&63)<<6|e[r++]&63):t+=String.fromCharCode(n)}};function ga(e,t){var r;if(s0)return s0.encode(e);for(var n=e.length,a=new jt(e.length+(e.length>>1)),o=0,i=function(u){a[o++]=u},r=0;r<n;++r){if(o+5>a.length){var l=new jt(o+8+(n-r<<1));l.set(a),a=l}var c=e.charCodeAt(r);c<128||t?i(c):c<2048?(i(192|c>>6),i(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|e.charCodeAt(++r)&1023,i(240|c>>18),i(128|c>>12&63),i(128|c>>6&63),i(128|c&63)):(i(224|c>>12),i(128|c>>6&63),i(128|c&63))}return wa(a,0,o)}function sg(e,t){if(t){for(var r="",n=0;n<e.length;n+=16384)r+=String.fromCharCode.apply(null,e.subarray(n,n+16384));return r}else{if(Vu)return Vu.decode(e);var a=sC(e),o=a.s,r=a.r;return r.length&&Bt(8),o}}var aC=function(e,t){return t+30+Pn(e,t+26)+Pn(e,t+28)},oC=function(e,t,r){var n=Pn(e,t+28),a=Pn(e,t+30),o=sg(e.subarray(t+46,t+46+n),!(Pn(e,t+8)&2048)),i=t+46+n,l=iC(e,i,a,r,Zr(e,t+20),Zr(e,t+24),Zr(e,t+42)),c=l[0],u=l[1],f=l[2];return[Pn(e,t+10),c,u,o,i+a+Pn(e,t+32),f]},iC=function(e,t,r,n,a,o,i){var l=a==4294967295,c=o==4294967295,u=i==4294967295,f=t+r,d=l+c+u;if(n&&d){for(;t+4<f;t+=4+Pn(e,t+2))if(Pn(e,t)==1)return[l?Xd(e,t+4+8*c):a,c?Xd(e,t+4):o,u?Xd(e,t+4+8*(c+l)):i,1];n<2&&Bt(13)}return[a,o,i,0]},gi=function(e){var t=0;if(e)for(var r in e){var n=e[r].length;n>65535&&Bt(9),t+=n+4}return t},gc=function(e,t,r,n,a,o,i,l){var c=n.length,u=r.extra,f=l&&l.length,d=gi(u);nr(e,t,i!=null?33639248:67324752),t+=4,i!=null&&(e[t++]=20,e[t++]=r.os),e[t]=20,t+=2,e[t++]=r.flag<<1|(o<0&&8),e[t++]=a&&8,e[t++]=r.compression&255,e[t++]=r.compression>>8;var g=new Date(r.mtime==null?Date.now():r.mtime),m=g.getFullYear()-1980;if((m<0||m>119)&&Bt(10),nr(e,t,m<<25|g.getMonth()+1<<21|g.getDate()<<16|g.getHours()<<11|g.getMinutes()<<5|g.getSeconds()>>1),t+=4,o!=-1&&(nr(e,t,r.crc),nr(e,t+4,o<0?-o-2:o),nr(e,t+8,r.size)),nr(e,t+12,c),nr(e,t+14,d),t+=16,i!=null&&(nr(e,t,f),nr(e,t+6,r.attrs),nr(e,t+10,i),t+=14),e.set(n,t),t+=c,d)for(var x in u){var b=u[x],h=b.length;nr(e,t,+x),nr(e,t+2,h),e.set(b,t+4),t+=4+h}return f&&(e.set(l,t),t+=f),t},qx=function(e,t,r,n,a){nr(e,t,101010256),nr(e,t+8,r),nr(e,t+10,r),nr(e,t+12,n),nr(e,t+16,a)};function lC(e,t,r){r||(r=t,t={}),typeof r!="function"&&Bt(7);var n={};ng(e,"",n,t);var a=Object.keys(n),o=a.length,i=0,l=0,c=o,u=new Array(o),f=[],d=function(){for(var h=0;h<f.length;++h)f[h]()},g=function(h,y){mc(function(){r(h,y)})};mc(function(){g=r});var m=function(){var h=new jt(l+22),y=i,v=l-i;l=0;for(var I=0;I<c;++I){var S=u[I];try{var k=S.c.length;gc(h,l,S,S.f,S.u,k);var j=30+S.f.length+gi(S.extra),A=l+j;h.set(S.c,A),gc(h,i,S,S.f,S.u,k,l,S.m),i+=16+j+(S.m?S.m.length:0),l=A+k}catch(N){return g(N,null)}}qx(h,i,u.length,v,y),g(null,h)};o||m();for(var x=function(h){var y=a[h],v=n[y],I=v[0],S=v[1],k=Yx(),j=I.length;k.p(I);var A=ga(y),N=A.length,C=S.comment,T=C&&ga(C),R=T&&T.length,U=gi(S.extra),W=S.level==0?0:8,F=function(_,O){if(_)d(),g(_,null);else{var J=O.length;u[h]=ud(S,{size:j,crc:k.d(),c:O,f:A,m:T,u:N!=y.length||T&&C.length!=R,compression:W}),i+=30+N+U+J,l+=76+2*(N+U)+(R||0)+J,--o||m()}};if(N>65535&&F(Bt(11,0,1),null),!W)F(null,I);else if(j<16e4)try{F(null,gd(I,S))}catch(_){F(_,null)}else f.push(tC(I,S,F))},b=0;b<c;++b)x(b);return d}function cC(e,t){t||(t={});var r={},n=[];ng(e,"",r,t);var a=0,o=0;for(var i in r){var l=r[i],c=l[0],u=l[1],f=u.level==0?0:8,d=ga(i),g=d.length,m=u.comment,x=m&&ga(m),b=x&&x.length,h=gi(u.extra);g>65535&&Bt(11);var y=f?gd(c,u):c,v=y.length,I=Yx();I.p(c),n.push(ud(u,{size:c.length,crc:I.d(),c:y,f:d,m:x,u:g!=i.length||x&&m.length!=b,o:a,compression:f})),a+=30+g+h+v,o+=76+2*(g+h)+(b||0)+v}for(var S=new jt(o+22),k=a,j=o-a,A=0;A<n.length;++A){var d=n[A];gc(S,d.o,d,d.f,d.u,d.c.length);var N=30+d.f.length+gi(d.extra);S.set(d.c,d.o+N),gc(S,a,d,d.f,d.u,d.c.length,d.o,d.m),a+=16+N+(d.m?d.m.length:0)}return qx(S,a,n.length,j,k),S}var mc=typeof queueMicrotask=="function"?queueMicrotask:typeof setTimeout=="function"?setTimeout:function(e){e()};function dC(e,t,r){r||(r=t,t={}),typeof r!="function"&&Bt(7);var n=[],a=function(){for(var h=0;h<n.length;++h)n[h]()},o={},i=function(h,y){mc(function(){r(h,y)})};mc(function(){i=r});for(var l=e.length-22;Zr(e,l)!=101010256;--l)if(!l||e.length-l>65558)return i(Bt(13,0,1),null),a;var c=Pn(e,l+8);if(c){var u=c,f=Zr(e,l+16),d=Zr(e,l-20)==117853008;if(d){var g=Zr(e,l-12);d=Zr(e,g)==101075792,d&&(u=c=Zr(e,g+32),f=Zr(e,g+48))}for(var m=t&&t.filter,x=function(h){var y=oC(e,f,d),v=y[0],I=y[1],S=y[2],k=y[3],j=y[4],A=y[5],N=aC(e,A);f=j;var C=function(R,U){R?(a(),i(R,null)):(U&&(o[k]=U),--c||i(null,o))};if(!m||m({name:k,size:I,originalSize:S,compression:v}))if(!v)C(null,wa(e,N,N+I));else if(v==8){var T=e.subarray(N,N+I);if(S<524288||I>.8*S)try{C(null,rg(T,{out:new jt(S)}))}catch(R){C(R,null)}else n.push(rC(T,{size:S},C))}else C(Bt(14,"unknown compression type "+v,1),null);else C(null,null)},b=0;b<u;++b)x(b)}else i(null,{});return a}const ag=2*1024*1024*1024,uC=256*1024*1024,fC=128*1024*1024,Jx=1024*1024,Gx=1024;function Zx(e){if(e.customProviders.length)return e;const{customProviders:t,...r}=e;return r}async function gC(e){var f;const t=new Date(e.exportedAt),r=e.options.exportTasks?e.imageTasks??e.tasks:[],n=yC(r),a=vC(r),o={},i={},l={},c=new Set;if(e.options.exportTasks)for(const d of e.images){const{ext:g,bytes:m}="bytes"in d?d:Jg(d.dataUrl),x=wC(a.get(d.id)||`image-${d.id}`,g,c),b=x.slice(7,-(g.length+1)),h=d.createdAt??n.get(d.id)??e.exportedAt;o[d.id]={path:x,createdAt:h,source:d.source,width:d.width,height:d.height,...(f=e.imageSourceUrls)!=null&&f[d.id]?{sourceUrl:e.imageSourceUrls[d.id]}:{}},l[x]=[m,{mtime:new Date(h),level:0}];const y=e.thumbnailsByImageId.get(d.id),v=y&&!("bytes"in y)?y.thumbnailDataUrl:"",I=y&&"bytes"in y?y:v?Jg(v):null;if(y&&I){const{ext:S,bytes:k}=I,j=`thumbnails/${b}.${S}`;o[d.id].width=o[d.id].width??y.width,o[d.id].height=o[d.id].height??y.height,i[d.id]={path:j,width:y.width,height:y.height,thumbnailVersion:y.thumbnailVersion},l[j]=[k,{mtime:new Date(h),level:0}]}}const u={version:3,exportedAt:t.toISOString()};return e.backupPart&&(u.backupPart=e.backupPart),e.options.exportConfig&&e.includeManifestData!==!1&&(u.settings=Zx(e.settings)),e.options.exportTasks&&((e.includeManifestData!==!1||e.tasks.length)&&(u.tasks=e.tasks),(e.includeManifestData!==!1||e.agentConversations.length)&&(u.agentConversations=e.agentConversations),e.includeManifestData!==!1&&(u.favoriteCollections=e.favoriteCollections,u.defaultFavoriteCollectionId=e.defaultFavoriteCollectionId),u.imageFiles=o,u.thumbnailFiles=i),l["manifest.json"]=[ga(JSON.stringify(u,null,2)),{mtime:t}],{manifest:u,bytes:await new Promise((d,g)=>{lC(l,{level:6},(m,x)=>{if(m){g(m);return}d(x)})})}}function mC(e,t,r={}){const n=r.maxBytes??ag,a=Math.min(fC,Math.floor(n*.1)),o=Math.min(r.partBytes??uC,n-a),i=bC(e),l=e.options.exportTasks?e.tasks:[],c=e.options.exportTasks?e.agentConversations:[],u=l.map(a0),f=c.map(a0),d=e.options.exportTasks?t:[];if(i+u.reduce((h,y)=>h+y,0)+f.reduce((h,y)=>h+y,0)+d.reduce((h,y)=>h+y.bytes,0)<o)return[{imageIds:d.map(h=>h.id),tasks:l,agentConversations:c,includeBaseData:!0}];const m=[{imageIds:[],tasks:[],agentConversations:[],includeBaseData:!0}],x=[i],b=(h,y,v)=>{let I=m.length-1;if((m[I].imageIds.length>0||m[I].tasks.length>0||m[I].agentConversations.length>0)&&x[I]+h>=o&&(m.push({imageIds:[],tasks:[],agentConversations:[],includeBaseData:!1}),x.push(Jx),I++),x[I]+h>=n)throw new Error(y);v(m[I]),x[I]+=h};for(let h=0;h<l.length;h++)b(u[h],"单条任务或 Agent 对话超过 2 GB,无法生成备份。",y=>y.tasks.push(l[h]));for(let h=0;h<c.length;h++)b(f[h],"单条任务或 Agent 对话超过 2 GB,无法生成备份。",y=>y.agentConversations.push(c[h]));for(const h of d)b(h.bytes,`图片 ${h.id} 过大,无法放入小于 2 GB 的备份分卷。`,y=>y.imageIds.push(h.id));return m}function hC(e){if(e.byteLength>=ag)throw new Error("生成的备份文件超过浏览器支持的大小,请重试。");const t=[],r=256*1024*1024;for(let n=0;n<e.byteLength;n+=r)t.push(e.subarray(n,Math.min(n+r,e.byteLength)));return new Blob(t,{type:"application/zip"})}async function pC(e,t=!0){const r=new Set,a=(await Qx(e,{filter:i=>(t&&r.add(i.name),i.name==="manifest.json")}))["manifest.json"];if(!a)throw new Error("ZIP 中缺少 manifest.json");const o=JSON.parse(sg(a));return t&&eb(o,i=>r.has(i)),o}async function xC(e){const t=await Qx(e),r=t["manifest.json"];if(!r)throw new Error("ZIP 中缺少 manifest.json");const n=JSON.parse(sg(r));return eb(n,a=>t[a]!=null),{manifest:n,files:t}}function Qx(e,t={}){return new Promise((r,n)=>{dC(e,t,(a,o)=>{if(a){n(a);return}r(o)})})}function eb(e,t){const n=[...Object.values(e.imageFiles??{}).map(a=>a.path),...Object.values(e.thumbnailFiles??{}).map(a=>a.path)].find(a=>!t(a));if(n)throw new Error(`ZIP 中缺少 ${n}`)}function bC(e){const t={version:3,exportedAt:new Date(e.exportedAt).toISOString(),...e.options.exportConfig?{settings:Zx(e.settings)}:{},...e.options.exportTasks?{tasks:[],favoriteCollections:e.favoriteCollections,defaultFavoriteCollectionId:e.defaultFavoriteCollectionId,agentConversations:[]}:{}};return Jx+ga(JSON.stringify(t)).byteLength}function a0(e){return ga(JSON.stringify(e)).byteLength+Gx}function o0(e,t){return e+(t??0)+Gx*(t!=null?2:1)}function i0(e,t){const r=e[t];return r?Ov(r,t):null}function yC(e){const t=new Map;for(const r of e)for(const n of[...r.inputImageIds||[],...r.maskImageId?[r.maskImageId]:[],...r.outputImages||[],...r.transparentOriginalImages||[],...r.streamPartialImageIds||[]]){if(!n)continue;const a=t.get(n);(a==null||r.createdAt<a)&&t.set(n,r.createdAt)}return t}function vC(e){const t=new Map;for(const r of e)Cl(t,r.outputImages||[],`task-${r.id}`);for(const r of e)Cl(t,r.transparentOriginalImages||[],`task-${r.id}-orig`);for(const r of e)Cl(t,r.streamPartialImageIds||[],`task-${r.id}-partial`);for(const r of e)Cl(t,r.inputImageIds||[],`task-${r.id}-input`);for(const r of e)r.maskImageId&&!t.has(r.maskImageId)&&t.set(r.maskImageId,`task-${r.id}-mask`);return t}function Cl(e,t,r){const n=t.filter(Boolean);for(let a=0;a<n.length;a++)e.has(n[a])||e.set(n[a],Ex(r,a,n.length))}function wC(e,t,r){const n=dc(e)||"image";let a=`images/${n}.${t}`,o=2;for(;r.has(a);)a=`images/${n}-${String(o).padStart(2,"0")}.${t}`,o++;return r.add(a),a}const hc=/^image\/(\w+)$/;async function kC(e,t){var n,a;if(De){const o=new Set(e);return(await of()).filter(i=>o.has(i.id)).map(i=>({id:i.id,bytes:o0(i.bytes,i.thumbnailVersion===Dn?i.thumbnailBytes??void 0:void 0)}))}const r=[];for(const[o,i]of e.entries()){t==null||t(o);const l=await Kc(i);if(!l)continue;const c=await Xc(i),u=(c==null?void 0:c.thumbnailVersion)!==Dn?void 0:((n=c.blob)==null?void 0:n.size)??(c.thumbnailDataUrl?qa(c.thumbnailDataUrl):void 0);r.push({id:i,bytes:o0(((a=l.blob)==null?void 0:a.size)??qa(l.dataUrl??""),u)})}return r}async function IC(e,t){const r=[],n=new Map,a=De?8:1;for(let o=0;o<e.length;o+=a){const i=await Promise.all(e.slice(o,o+a).map(l=>CC(l)));for(const l of i){if(!l)continue;if(r.push(l.image),l.thumbnail){n.set(l.image.id,l.thumbnail);continue}const c=await kp(l.image.id);c!=null&&c.thumbnailDataUrl&&(n.set(l.image.id,c),Ki(l.image.id,{src:c.thumbnailDataUrl,width:c.width,height:c.height,thumbnailVersion:c.thumbnailVersion}))}t==null||t(Math.min(o+a,e.length))}return{images:r,thumbnailsByImageId:n}}async function CC(e){var i,l;if(!De)return jC(e);const t=await Bv(e);if(!t)return;const r=(i=hc.exec(t.meta.mime))==null?void 0:i[1],n=r?{id:e,ext:r,bytes:t.bytes,createdAt:t.meta.createdAt??void 0,source:t.meta.source??void 0,width:t.meta.width??void 0,height:t.meta.height??void 0}:await qn(e);if(!n)return;const a=await Uh(e),o=a&&((l=hc.exec(a.meta.mime))==null?void 0:l[1]);return!a||!o||a.meta.thumbnailVersion!==Dn?{image:n}:{image:n,thumbnail:{id:e,ext:o,bytes:a.bytes,width:a.meta.width??void 0,height:a.meta.height??void 0,thumbnailVersion:a.meta.thumbnailVersion}}}async function jC(e){var u,f;const t=await Kc(e);if(!t)return;const r=t.blob&&((u=hc.exec(t.blob.type))==null?void 0:u[1]),{blob:n,dataUrl:a,...o}=t,i=r&&n?{...o,ext:r,bytes:new Uint8Array(await n.arrayBuffer())}:await pp(t);if(!i)return;const l=await Xc(e),c=(l==null?void 0:l.blob)&&((f=hc.exec(l.blob.type))==null?void 0:f[1]);return!(l!=null&&l.blob)||!c||l.thumbnailVersion!==Dn?{image:i}:{image:i,thumbnail:{id:e,ext:c,bytes:new Uint8Array(await l.blob.arrayBuffer()),width:l.width,height:l.height,thumbnailVersion:l.thumbnailVersion}}}const SC=4320*60*1e3;function Ji(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function NC(e){return Array.isArray(e)?e.map(t=>!Ji(t)||typeof t.id!="string"?null:{id:t.id,dataUrl:typeof t.dataUrl=="string"?t.dataUrl:""}).filter(t=>t!=null):[]}function AC(e){return!Ji(e)||typeof e.targetImageId!="string"||typeof e.maskDataUrl!="string"?null:{targetImageId:e.targetImageId,maskDataUrl:e.maskDataUrl,updatedAt:typeof e.updatedAt=="number"?e.updatedAt:Date.now()}}function pc(e,t=Date.now()){const r=Ji(e)?e:{},n=typeof r.updatedAt=="number"&&Number.isFinite(r.updatedAt)?r.updatedAt:t;return{prompt:typeof r.prompt=="string"?r.prompt:"",inputImages:NC(r.inputImages),maskDraft:AC(r.maskDraft),maskEditorImageId:typeof r.maskEditorImageId=="string"?r.maskEditorImageId:null,updatedAt:n}}function tb(e,t){if(!Ji(e))return{};const r=new Set(t.map(a=>a.id)),n={};for(const[a,o]of Object.entries(e)){if(!r.has(a))continue;const i=pc(o);rs(i)||(n[a]=i)}return n}function PC(e){if(!Ji(e))return{};const t={};for(const[r,n]of Object.entries(e)){const a=pc(n);rs(a)||(t[r]=a)}return t}function rb(e,t,r=Date.now()){const n=r-SC,a={};for(const[o,i]of Object.entries(e))(o===t||(i.updatedAt??r)>=n)&&(a[o]=i);return a}function Ku(){return{prompt:"",inputImages:[],maskDraft:null,maskEditorImageId:null}}function md(e){return{prompt:e.prompt,inputImages:e.inputImages.map(t=>({...t})),maskDraft:e.maskDraft?{...e.maskDraft}:null,maskEditorImageId:e.maskEditorImageId,updatedAt:e.updatedAt??Date.now()}}function nb(e){return{prompt:e.prompt,inputImages:e.inputImages,maskDraft:e.maskDraft,maskEditorImageId:e.maskEditorImageId,updatedAt:Date.now()}}function rs(e){return e.prompt.length===0&&e.inputImages.length===0&&!e.maskDraft&&!e.maskEditorImageId}function sb(e,t,r){const n={...e};return rs(r)?delete n[t]:n[t]=md(r),n}function _a(e){return e.appMode!=="agent"||!e.activeAgentConversationId?e.agentInputDrafts:sb(e.agentInputDrafts,e.activeAgentConversationId,nb(e))}function xc(e){if(e.appMode!=="gallery")return e.galleryInputDraft;const t=nb(e);return rs(t)?null:md(t)}function hd(e){return e?{prompt:e.prompt,inputImages:e.inputImages.map(t=>({...t})),maskDraft:e.maskDraft?{...e.maskDraft}:null,maskEditorImageId:e.maskEditorImageId}:Ku()}function Xs(e,t){const r=t?e[t]:null;return hd(r??null)}function Nn(e,t){const r={prompt:t.prompt??e.prompt,inputImages:t.inputImages??e.inputImages,maskDraft:t.maskDraft!==void 0?t.maskDraft:e.maskDraft,maskEditorImageId:t.maskEditorImageId!==void 0?t.maskEditorImageId:e.maskEditorImageId};return e.appMode==="gallery"?{...t,galleryInputDraft:rs(r)?null:md(r)}:e.activeAgentConversationId?{...t,agentInputDrafts:sb(e.agentInputDrafts,e.activeAgentConversationId,r)}:t}function Ws(e,t,r={}){const n=r.clearMissingMask!==!1&&!!e.maskDraft&&!t.some(a=>{var o;return a.id===((o=e.maskDraft)==null?void 0:o.targetImageId)});return{inputImages:t,prompt:jf(e.prompt,e.inputImages,t,r.equivalentImageIds),...n?{maskDraft:null,maskEditorImageId:null}:{}}}function TC(e,t,r,n){const a=e[t];return a?{...e,[t]:{...a,prompt:Vf(a.prompt,r,n)}}:e}function MC(e){const t=_a(e),r=new Set(e.agentConversations.map(a=>a.id)),n={};for(const[a,o]of Object.entries(t))!r.has(a)||rs(o)||(n[a]={...md(o),inputImages:o.inputImages.map(i=>({id:i.id,dataUrl:""}))});return n}const or="__all_favorites__",mi="__default_favorites__",og="默认";function ig(e){return e.trim().replace(/\s+/g," ")}function lg(e=Date.now()){return{id:mi,name:og,createdAt:e,updatedAt:e}}function hi(e,t=Date.now()){const r=Array.isArray(e)?e:[],n=[],a=new Set;for(const o of r){if(!o||typeof o!="object")continue;const i=o;if(typeof i.id!="string"||!i.id.trim()||i.id===or||a.has(i.id))continue;const l=ig(typeof i.name=="string"?i.name:"");l&&(a.add(i.id),n.push({id:i.id,name:l.slice(0,60),createdAt:typeof i.createdAt=="number"?i.createdAt:t,updatedAt:typeof i.updatedAt=="number"?i.updatedAt:t}))}return n}function pd(e,t=Date.now()){return e.length>0?e:[lg(t)]}function ab(e){var t,r;return((t=e.find(n=>n.id===mi))==null?void 0:t.id)??((r=e.find(n=>n.name===og))==null?void 0:r.id)??null}function EC(e,t=Date.now()){return ab(e)?e:[lg(t),...e]}function Gi(e,t){var r;return t===null?null:typeof t=="string"&&e.some(n=>n.id===t)?t:e.some(n=>n.id===mi)?mi:((r=e[0])==null?void 0:r.id)??null}function Qa(e){return Array.isArray(e)?Array.from(new Set(e.map(String).filter(t=>t&&t!==or))):[]}function RC(e,t){if(e.length!==t.length)return!1;const r=new Set(t);return e.every(n=>r.has(n))}function Vr(e,t){const r=Qa(e.favoriteCollectionIds);return r.length>0?r:e.isFavorite&&t?[t]:[]}function _C(e,t,r){if("favoriteCollectionIds"in t){const n=Qa(t.favoriteCollectionIds);return{...t,favoriteCollectionIds:n,isFavorite:n.length>0}}if("isFavorite"in t){if(t.isFavorite){const n=Qa(e.favoriteCollectionIds);return{...t,favoriteCollectionIds:n.length?n:r?[r]:[]}}return{...t,favoriteCollectionIds:[]}}return t}function ob(e,t=[]){if(!e.filterFavorite)return null;const r=new Set(e.favoriteCollections.map(a=>a.id)),n=[...new Set([e.activeFavoriteCollectionId??"",...t])].filter(a=>r.has(a));return!n.length&&e.defaultFavoriteCollectionId&&n.push(e.defaultFavoriteCollectionId),n.length?{favoriteCollectionIds:n,isFavorite:!0}:null}function ib(e,t,r,n=Date.now()){let a=!1;const o=pd(hi(t,n),n),i=new Set(o.map(m=>m.id)),l=e.some(m=>!!m.isFavorite&&!Qa(m.favoriteCollectionIds).some(x=>i.has(x))),c=l?EC(o,n):o,u=Gi(c,r),f=new Set(c.map(m=>m.id)),d=l?ab(c):null;return{tasks:e.map(m=>{const x=Qa(m.favoriteCollectionIds).filter(v=>f.has(v)),b=x.length>0?x:m.isFavorite&&d?[d]:[],h=b.length>0||!!m.isFavorite,y=Array.isArray(m.favoriteCollectionIds)?m.favoriteCollectionIds:[];return b.length===y.length&&b.every((v,I)=>v===y[I])&&!!m.isFavorite===h?m:(a=!0,{...m,favoriteCollectionIds:b,isFavorite:h})}),collections:c,defaultFavoriteCollectionId:u,changed:a}}function DC(e,t,r=Date.now()){const n=hi(t,r);return n.length?{collections:pd(hi([...e,...n],r),r),importedCollections:n}:{collections:e,importedCollections:n}}function LC(e){var i;if(!e.collectionId||e.collectionId===or||e.collections.length<=1||!e.collections.some(l=>l.id===e.collectionId))return null;const t=e.collections.filter(l=>l.id!==e.collectionId),r=new Set(t.map(l=>l.id)),n=[],a=[];for(const l of e.tasks){const c=Vr(l,e.defaultFavoriteCollectionId);if(!c.includes(e.collectionId))continue;const u=c.filter(d=>d!==e.collectionId&&r.has(d));if(e.deleteTasks&&!u.length){n.push(l.id);continue}const f={...l,favoriteCollectionIds:u,isFavorite:u.length>0};a.push(f)}const o=e.activeFavoriteCollectionId===e.collectionId;return{collections:t,defaultFavoriteCollectionId:e.defaultFavoriteCollectionId===e.collectionId?((i=t[0])==null?void 0:i.id)??null:Gi(t,e.defaultFavoriteCollectionId),activeFavoriteCollectionId:o?null:e.activeFavoriteCollectionId,selectedFavoriteCollectionIds:o?[]:e.selectedFavoriteCollectionIds.filter(l=>l!==e.collectionId),selectedTaskIds:o?[]:e.selectedTaskIds,updatedTasks:a,taskIdsToDelete:n}}function Ko(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qd(e,t){return Array.isArray(e)?e.filter(r=>typeof r=="string"):t}function OC(e,t){return Ko(e)?{size:typeof e.size=="string"?e.size:t.size,quality:e.quality==="auto"||e.quality==="low"||e.quality==="medium"||e.quality==="high"||e.quality==="xhigh"||e.quality==="max"?e.quality:t.quality,output_format:e.output_format==="png"||e.output_format==="jpeg"||e.output_format==="webp"?e.output_format:t.output_format,output_compression:e.output_compression===null||typeof e.output_compression=="number"&&Number.isFinite(e.output_compression)?e.output_compression:t.output_compression,moderation:e.moderation==="auto"||e.moderation==="low"?e.moderation:t.moderation,n:typeof e.n=="number"&&Number.isFinite(e.n)?e.n:t.n,transparent_output:typeof e.transparent_output=="boolean"?e.transparent_output:t.transparent_output}:t}function BC(e,t=!1){const r=Me(e.settings),n=xc(e);return{settings:r,previousPresetConfig:e.previousPresetConfig??null,dismissedPresetProfileIds:e.dismissedPresetProfileIds??[],dismissedPresetProviderIds:e.dismissedPresetProviderIds??[],params:e.params,...r.persistInputOnRestart&&(e.appMode==="gallery"||n)?{prompt:(n==null?void 0:n.prompt)??"",inputImages:(n==null?void 0:n.inputImages.map(a=>({id:a.id,dataUrl:""})))??[]}:{},dismissedCodexCliPrompts:e.dismissedCodexCliPrompts,appMode:e.appMode,galleryInputDraft:r.persistInputOnRestart&&n?{...n,inputImages:n.inputImages.map(a=>({id:a.id,dataUrl:""}))}:null,...t?{agentConversations:Xf(e.agentConversations)}:{},activeAgentConversationId:e.activeAgentConversationId,agentInputDrafts:r.persistInputOnRestart?MC(e):{},agentSidebarCollapsed:e.agentSidebarCollapsed,agentAssetTab:e.agentAssetTab,agentAssetPanelCollapsed:e.agentAssetPanelCollapsed,favoriteCollections:e.favoriteCollections,defaultFavoriteCollectionId:e.defaultFavoriteCollectionId,supportPromptDismissed:e.supportPromptDismissed,supportPromptOpen:e.supportPromptOpen,supportPromptSkippedForImportedData:e.supportPromptSkippedForImportedData,imageSourceUrls:e.imageSourceUrls}}function UC(e,t){return Ko(e)?{...e,agentConversations:i2(e.agentConversations)}:e}function FC(e,t,r=Date.now()){var h;if(!Ko(e))return null;const n=Me(e.settings??t.settings),a=Ko(e.previousPresetConfig)&&Array.isArray(e.previousPresetConfig.profiles)?(()=>{const y=Me(e.previousPresetConfig),v=yf(e.previousPresetConfig.agent,y.profiles);return{customProviders:y.customProviders,profiles:e.previousPresetConfig.profiles.length?y.profiles:[],...v?{agent:v}:{}}})():null,o=Array.isArray(e.agentConversations),i=o?Ho(e.agentConversations):t.agentConversations,l=typeof e.activeAgentConversationId=="string"&&(!o||i.some(y=>y.id===e.activeAgentConversationId))?e.activeAgentConversationId:((h=i[0])==null?void 0:h.id)??null,c=e.appMode==="agent"?"agent":"gallery",u=n.persistInputOnRestart?pc(e.galleryInputDraft??{prompt:e.prompt,inputImages:e.inputImages,maskDraft:null,maskEditorImageId:null},r):null,f=n.persistInputOnRestart?o?tb(e.agentInputDrafts,i):PC(e.agentInputDrafts):{},d=rb(f,l,r),g=c==="agent"&&l&&!d[l]&&n.persistInputOnRestart&&typeof e.prompt=="string"?{...d,[l]:pc({prompt:e.prompt,inputImages:e.inputImages,maskDraft:null,maskEditorImageId:null},r)}:d,m=n.persistInputOnRestart&&c==="agent"&&l?g[l]??null:null,x=Array.isArray(e.favoriteCollections)?pd(hi(e.favoriteCollections,r),r):t.favoriteCollections,b=e.defaultFavoriteCollectionId===null||typeof e.defaultFavoriteCollectionId=="string"?e.defaultFavoriteCollectionId:t.defaultFavoriteCollectionId;return{state:{settings:n,previousPresetConfig:a,dismissedPresetProfileIds:qd(e.dismissedPresetProfileIds,t.dismissedPresetProfileIds??[]),dismissedPresetProviderIds:qd(e.dismissedPresetProviderIds,t.dismissedPresetProviderIds??[]),params:OC(e.params,t.params),dismissedCodexCliPrompts:qd(e.dismissedCodexCliPrompts,t.dismissedCodexCliPrompts),appMode:c,galleryInputDraft:u&&!rs(u)?u:null,agentConversations:i,activeAgentConversationId:l,agentInputDrafts:g,agentSidebarCollapsed:!!e.agentSidebarCollapsed,agentAssetTab:e.agentAssetTab==="references"?"references":"outputs",agentAssetPanelCollapsed:!!e.agentAssetPanelCollapsed,favoriteCollections:x,defaultFavoriteCollectionId:Gi(x,b),supportPromptDismissed:!!e.supportPromptDismissed,supportPromptOpen:!!e.supportPromptOpen,supportPromptSkippedForImportedData:!!e.supportPromptSkippedForImportedData,imageSourceUrls:Ko(e.imageSourceUrls)?Object.fromEntries(Object.entries(e.imageSourceUrls).filter(y=>Ir(y[1]))):{},prompt:m?m.prompt:(u==null?void 0:u.prompt)??"",inputImages:m?m.inputImages:(u==null?void 0:u.inputImages)??[],maskDraft:m?m.maskDraft:(u==null?void 0:u.maskDraft)??null,maskEditorImageId:m?m.maskEditorImageId:(u==null?void 0:u.maskEditorImageId)??null},hasLegacyAgentConversations:o,shouldMigrateAgentConversations:o&&i.length>0}}function l0(e,t){const r=new Map;for(const n of e)r.set(n.id,n);for(const n of t){const a=r.get(n.id);(!a||n.updatedAt>=a.updatedAt)&&r.set(n.id,n)}return[...r.values()].sort((n,a)=>n.createdAt-a.createdAt)}function xd(e,t){return{status:"done",error:null,finishedAt:t,elapsed:t-(e.startedAt??e.createdAt)}}function Wr(e,t,r){return{status:"error",error:t,finishedAt:r,elapsed:r-(e.startedAt??e.createdAt)}}function $C(e,t){const r=[];return{tasks:e.map(a=>{const o=(a.apiProvider??"openai")!=="fal";if(a.status!=="running"||!o||a.customTaskId)return a;const i={...a,...Wr(a,"请求中断",t),falRecoverable:!1,elapsed:Math.max(0,t-(a.startedAt??a.createdAt))};return r.push(i),i}),interruptedTasks:r}}function bd(e){return!!(e&&Object.keys(e).length>0)}function bc(e){return e==null?void 0:e.find(bd)}function cg(e,t){const r=t==null?void 0:t.reduce((n,a,o)=>{const i=e[o];return i&&bd(a)&&(n[i]=a),n},{});return r&&Object.keys(r).length>0?r:void 0}function Xu(e){return!!(e!=null&&e.size)}function lb(e,t){return Xu(e)||!(t!=null&&t.width)||!t.height?e:{...e??{},size:`${t.width}x${t.height}`}}function c0(e,t){return{...lb(bd(e)?e:void 0,t)??{},n:1}}function zC(e,t,r,n,a){if(e==="fal"||t)return bc(n);const o=bc(n);return{...r,size:(r==null?void 0:r.size)??(o==null?void 0:o.size),n:a}}function WC(e,t){const r=t==null?void 0:t.reduce((n,a,o)=>{const i=e[o];return i&&(a!=null&&a.trim())&&(n[i]=a),n},{});return r&&Object.keys(r).length>0?r:void 0}let dg=!1;function cb(e){dg=e}let pi=null;function d0(e){pi=e}function HC(e,t){const r=URL.createObjectURL(e),n=document.createElement("a");n.href=r,n.download=t,document.body.appendChild(n),n.click(),n.remove(),window.setTimeout(()=>URL.revokeObjectURL(r),1e3)}const jl=8*1024*1024;async function db(e,t,r){var n;try{const a=t instanceof Blob?t.size:t.byteLength;for(let o=0;o<a;o+=jl){Qt(r==null?void 0:r.signal);const i=t instanceof Blob?new Uint8Array(await t.slice(o,o+jl).arrayBuffer()):t.subarray(o,o+jl);await Nt("save_write",i,{headers:{"x-id":String(e)}}),(n=r==null?void 0:r.onProgress)==null||n.call(r,Math.min(o+jl,a),a)}return Qt(r==null?void 0:r.signal),await Nt("save_commit",{id:e})}catch(a){throw await Nt("save_abort",{id:e}).catch(o=>console.warn("丢弃临时文件失败",o)),a}}async function yc(e,t,r){if(!De)return HC(e instanceof Blob?e:new Blob([e]),t),t;if(pi&&!await pi())return null;if(dg)return await yd(await Nt("download_dir_use"),e,t,r);const n=await Nt("save_file",{name:t});return n===null?null:await db(n,e,r)}async function ug(){return pi&&!await pi()?null:await Nt(dg?"download_dir_use":"save_dir_pick")}async function yd(e,t,r,n){return await db(await Nt("save_dir_begin",{token:e.token,name:r}),t,n)}function ub(){return Nt("download_dir_get")}function YC(){return Nt("download_dir_pick")}function VC(){return Nt("download_dir_migrate")}function KC(){return Nt("download_dir_open")}const ws=Mi(()=>({progress:null})),Ma=Mi(()=>({mode:null})),XC=100;let Ua=null,qu=0;function fb(e,t){return Ua=new AbortController,qu=Date.now(),ws.setState({progress:{mode:e,stage:"准备中",done:0,total:0,cancelable:t}}),Ua.signal}function mn(e,t=0,r=0,n){const a=ws.getState().progress;if(!a)return;const o=Date.now();!(a.stage!==e||a.unit!==n||a.total!==r)&&t<r&&o-qu<XC||(qu=o,ws.setState({progress:{...a,stage:e,done:t,total:r,unit:n}}))}function qC(e){const t=ws.getState().progress;t&&t.cancelable!==e&&ws.setState({progress:{...t,cancelable:e}})}function JC(){var e;(e=ws.getState().progress)!=null&&e.cancelable&&(Ua==null||Ua.abort())}function gb(){Ua=null,ws.setState({progress:null})}function GC(e,t){return{startedAt:t,hiddenTaskIds:new Set(e.tasks.map(r=>r.id)),hiddenConversationIds:new Set(e.agentConversations.filter(r=>!Yf(r)).map(r=>r.id)),inputSnapshot:{appMode:e.appMode,prompt:e.prompt,inputImages:e.inputImages,maskDraft:e.maskDraft,maskEditorImageId:null,galleryInputDraft:e.galleryInputDraft,agentInputDrafts:e.agentInputDrafts,activeAgentConversationId:e.activeAgentConversationId,reusedTaskApiProfileId:e.reusedTaskApiProfileId,reusedTaskApiProfileName:e.reusedTaskApiProfileName,reusedTaskApiProfileMissing:e.reusedTaskApiProfileMissing,reusedTaskApiModel:e.reusedTaskApiModel},stoppedBatchPrompts:e.batchProgress?e.batchProgress.total-e.batchProgress.started:0}}function mb(e,t){return e?t.createdAt<e.startedAt||e.hiddenConversationIds.has(t.id):!1}function vc(e,t){return e?t.createdAt<e.startedAt||e.hiddenTaskIds.has(t.id)||!!(t.agentConversationId&&e.hiddenConversationIds.has(t.agentConversationId)):!1}function hb(e){if(!e)return[];const t=e.inputSnapshot;return[t,t.galleryInputDraft,...Object.values(t.agentInputDrafts)].flatMap(r=>(r==null?void 0:r.inputImages.map(n=>n.id))??[])}function ZC(e,t){const r=xc(e),n=_a(e);return{galleryInputDraft:r,agentInputDrafts:n,...t.appMode==="gallery"?hd(r):Xs(n,t.activeAgentConversationId),maskEditorImageId:null,reusedTaskApiProfileId:e.reusedTaskApiProfileId,reusedTaskApiProfileName:e.reusedTaskApiProfileName,reusedTaskApiProfileMissing:e.reusedTaskApiProfileMissing,reusedTaskApiModel:e.reusedTaskApiModel}}const QC=1e4,ej=1e4,xi=50,Xo=new Map,qo=new Map,wc=new Map,ur=new Map,ta=new Map,Ul=new Set,kc=new Map;let fg=!1,Ic=!1;const nn="已停止生成。",pb="AgentRecoveryPauseError",u0=28,tj=80;function rj(e){var a;const t=e.trim();if(!t)return"操作失败";const r=((a=t.split(/\r?\n/)[0])==null?void 0:a.trim())??"",n=r.search(/[::]/);if(n>0){const o=r.slice(0,n).trim();if(sj(o))return o}return r.length>tj?"操作失败,请查看详情":r||"操作失败"}function nj(e,t){return t==="error"?rj(e):e}function sj(e){return/(?:失败|错误|异常|报错|无法|不能|超时|中断|断开|请先|请输入|已达上限|不存在|已丢失)$/.test(e)}const aj="也可尝试打开「流式传输」,并提高「请求中间步骤图像数」来维持连接。",oj="官方流式接口不发送心跳,当前「请求中间步骤图像数」为 0,连接可能因无数据传输而断开。建议提高到 2 或 3。",ij="也可尝试提高「请求中间步骤图像数」来维持连接,避免长时间无数据传输导致断开。";function Fl(e){if((e==null?void 0:e.provider)!=="openai")return"";const t=e.streamPartialImages??sr.streamPartialImages??0;return e.streamImages!==!0?aj:t===0?oj:t<3?ij:""}function lj(e,t){return`请求超时:超过 ${e} 秒仍未完成,请稍后重试或提高超时时间。${Fl(t)}`}function f0(e,t){if(!t)return e;const r=e.findIndex(o=>o.id===t);if(r<=0)return e;const n=[...e],[a]=n.splice(r,1);return n.unshift(a),n}function vn(e){return e.sourceMode==="agent"||!!(e.agentConversationId||e.agentRoundId)}function ks(e,t,r="task-completion"){Me(w.getState().settings).taskCompletionNotification&&I2(e,{body:t,tag:r})}function eo(e){return vc(w.getState().privacyMode,e)}function Ju(e){var t;return!!((t=w.getState().privacyMode)!=null&&t.hiddenConversationIds.has(e))}function bi(e){vn(e)||ro.has(e.id)||eo(e)||ks("图像生成失败","请回到应用查看详情。","task-failure")}function to(e){return e.reduce((t,r)=>t+(r.status==="done"&&!vn(r)?r.outputImages.length:0),0)}function cj(e){const t=to(e);w.setState(r=>r.supportPromptDismissed?{}:t<=xi?{supportPromptSkippedForImportedData:!1}:r.supportPromptOpen?{}:{supportPromptSkippedForImportedData:!0})}function dj(e){const t=to(e);w.setState(r=>r.supportPromptDismissed||r.supportPromptOpen?{}:t<=xi?{supportPromptSkippedForImportedData:!1}:r.supportPromptSkippedForImportedData?{}:{supportPromptOpen:!0})}function uj(e,t,r){const n=w.getState();if(n.supportPromptDismissed||n.supportPromptOpen||n.supportPromptSkippedForImportedData)return;const a=e.find(c=>c.id===r),o=t.find(c=>c.id===r);if(!o||(a==null?void 0:a.status)==="done"||o.status!=="done"||o.outputImages.length===0)return;const i=to(e),l=to(t);i<=xi&&l>xi&&w.setState({supportPromptOpen:!0})}function fj(e,t){const r=[...e],n=new Map(r.map((a,o)=>[a.id,o]));for(const a of t){const o=n.get(a.id);o==null?(n.set(a.id,r.length),r.push(a)):r[o]=a}return r}function gj(e=Date.now()){return{id:fr(),title:"新对话",activeRoundId:null,createdAt:e,updatedAt:e,rounds:[],messages:[]}}function mj(e,t){const r=e.replace(/\s+/g," ").trim();if(!r)return t;const n=Array.from(r);return n.length<=u0?r:`${n.slice(0,u0-3).join("")}...`}function hj(e){return e.reduce((t,r)=>t?r.updatedAt!==t.updatedAt?r.updatedAt>t.updatedAt?r:t:r.createdAt>t.createdAt?r:t:r,null)}function pj(e){const t=e.privacyMode?{...e,...e.privacyMode.inputSnapshot}:e;return BC(t,Ic&&!fg)}async function gg(e){await Fk(e.map(xb))}function xb(e){return Xf([e])[0]}function xj(e,t){const r=FC(e,t);return r?(r.shouldMigrateAgentConversations&&(Ic=!0),{...t,...r.state,activeFavoriteCollectionId:null,favoritePickerTaskIds:null}):t}function $l(e,t){var r;return e.inputImages.some(n=>n.id===t)||(r=e.galleryInputDraft)!=null&&r.inputImages.some(n=>n.id===t)||Object.values(e.agentInputDrafts).some(n=>n.inputImages.some(a=>a.id===t))||hb(e.privacyMode).includes(t)||e.tasks.some(n=>{var a,o;return n.inputImageIds.includes(t)||n.outputImages.includes(t)||((a=n.transparentOriginalImages)==null?void 0:a.includes(t))||((o=n.streamPartialImageIds)==null?void 0:o.includes(t))||n.maskTargetImageId===t||n.maskImageId===t})?!0:e.agentConversations.some(n=>n.rounds.some(a=>a.inputImageIds.includes(t)||a.maskTargetImageId===t||a.maskImageId===t)||n.messages.some(a=>{var o;return((o=a.inputImageIds)==null?void 0:o.includes(t))||a.maskTargetImageId===t||a.maskImageId===t}))}async function bb(e){if(!$l(w.getState(),e))try{await vb(e)}catch{}}function yb(e){e in w.getState().imageSourceUrls&&w.setState(t=>{const r={...t.imageSourceUrls};return delete r[e],{imageSourceUrls:r}})}async function vb(e){if($l(w.getState(),e))return;const[t,r]=await Promise.all([qn(e),Pf(e)]);if(!$l(w.getState(),e)){if(await wp(e),!$l(w.getState(),e)){$2(e),yb(e);return}t&&(await ea(t),Xt(t.id,t.dataUrl)),r&&(await Va(r),Ki(r.id,{src:r.thumbnailDataUrl,width:r.width,height:r.height,thumbnailVersion:r.thumbnailVersion}))}}const w=Mi()(sw((e,t)=>({appMode:"gallery",setAppMode:r=>{if(r==="gallery"){const l=t(),c=_a(l),u=xc(l);e(f=>({appMode:r,agentInputDrafts:c,galleryInputDraft:u,agentMobileHeaderVisible:!0,selectedTaskIds:[],selectedFavoriteCollectionIds:[],agentEditingRoundId:null,...f.appMode==="agent"?hd(u):{}}));return}const n=t(),a=Me(n.settings),o=zt(a),i=vd(a);if(!i){const l=xc(n);e(c=>({appMode:"agent",galleryInputDraft:l,agentMobileHeaderVisible:!1,agentSidebarCollapsed:!0,agentAssetPanelCollapsed:!0,selectedTaskIds:[],selectedFavoriteCollectionIds:[],...Xs(c.agentInputDrafts,c.activeAgentConversationId)}));return}if(a.agentApiConfigMode==="off"&&o.provider==="openai"&&o.apiMode!=="responses"){n.setConfirmDialog({title:"需要 Responses API 配置",message:`当前配置「${o.name}」使用的是 Images API,仅支持生成图片,无 Agent 模式需要的对话能力。
|
|
41
|
+
|
|
42
|
+
请在「设置 → API 配置」中将当前配置调整为 Responses API,或切换/新建一个支持 Responses API 的配置。`,confirmText:"去设置",cancelText:"取消",action:()=>{w.getState().setShowSettings(!0,"api")}});return}if(a.agentApiConfigMode!=="off"){n.setConfirmDialog({title:"Agent API 配置不完整",message:`${i.message}
|
|
43
|
+
|
|
44
|
+
请在「设置 → Agent 配置」中选择或新建可用配置。`,confirmText:"去设置",cancelText:"取消",action:()=>{w.getState().setShowSettings(!0,"agent")}});return}n.setConfirmDialog({title:"配置不支持 Agent 模式",message:`当前配置「${o.name}」所属的服务商暂不支持 Agent 模式。Agent 模式需要使用支持 Responses API 的 OpenAI 配置。
|
|
45
|
+
|
|
46
|
+
请在「设置 → API 配置」中切换或新建一个支持 Responses API 的配置。`,confirmText:"去设置",cancelText:"取消",action:()=>{w.getState().setShowSettings(!0,"api")}})},settings:{...sr},previousPresetConfig:null,dismissedPresetProfileIds:[],dismissPresetProfile:r=>e(n=>({dismissedPresetProfileIds:n.dismissedPresetProfileIds.includes(r)?n.dismissedPresetProfileIds:[...n.dismissedPresetProfileIds,r]})),restorePresetProfile:r=>e(n=>({dismissedPresetProfileIds:n.dismissedPresetProfileIds.filter(a=>a!==r)})),dismissedPresetProviderIds:[],dismissPresetProvider:r=>e(n=>({dismissedPresetProviderIds:n.dismissedPresetProviderIds.includes(r)?n.dismissedPresetProviderIds:[...n.dismissedPresetProviderIds,r]})),restorePresetProvider:r=>e(n=>({dismissedPresetProviderIds:n.dismissedPresetProviderIds.filter(a=>a!==r)})),setSettings:r=>e(n=>{const a=Me(n.settings),o=r,i=o.baseUrl!==void 0||o.apiKey!==void 0||o.model!==void 0||o.timeout!==void 0||o.apiMode!==void 0||o.codexCli!==void 0||o.apiProxy!==void 0||o.streamImages!==void 0||o.streamPartialImages!==void 0,l=Me({...a,...o});i&&o.profiles===void 0&&(l.profiles=l.profiles.map(d=>d.id===l.activeProfileId?{...d,baseUrl:o.baseUrl??d.baseUrl,apiKey:o.apiKey??d.apiKey,model:o.model??d.model,timeout:o.timeout??d.timeout,apiMode:o.apiMode==="images"||o.apiMode==="responses"?o.apiMode:d.apiMode,codexCli:o.codexCli??d.codexCli,apiProxy:o.apiProxy??d.apiProxy,streamImages:o.streamImages??d.streamImages,streamPartialImages:o.streamPartialImages??d.streamPartialImages}:d));const c=n.dismissedPresetProviderIds.filter(d=>!ni(d,a.profiles)),u=Me(fm(l,{dismissedPresetProviderIds:c})),f=n.reusedTaskApiProfileId&&u.activeProfileId===n.reusedTaskApiProfileId;return{settings:u,...f?{reusedTaskApiProfileId:null,reusedTaskApiProfileName:null,reusedTaskApiProfileMissing:!1,reusedTaskApiModel:null}:{}}}),setPresetImportedSettings:async(r,n)=>{e(a=>{var b;const o=Bn(),i=If(),l=a.dismissedPresetProfileIds.filter(h=>o.has(h)),c=Fi(),u=(((b=ri())==null?void 0:b.profiles)??a.settings.profiles).filter(h=>!l.includes(h.id)),f=a.dismissedPresetProviderIds.filter(h=>i.has(h)),d=f.filter(h=>!ni(h,u)),g=Hw(a.settings,r,{lockPresetParams:io(),dismissedPresetProfileIds:c?[]:l,dismissedPresetProviderIds:d,previousPresetConfig:a.previousPresetConfig,usedPresetProfileIds:a.tasks.flatMap(h=>h.apiProfileId?[h.apiProfileId]:[])}),m=Me(fm(Me((n==null?void 0:n(g.settings))??g.settings),{dismissedPresetProviderIds:d})),x=a.reusedTaskApiProfileId&&m.activeProfileId===a.reusedTaskApiProfileId;return{settings:m,previousPresetConfig:ri()?g.presetConfig:null,dismissedPresetProfileIds:l,dismissedPresetProviderIds:f,reusedTaskApiProfileId:x?null:a.reusedTaskApiProfileId,...x?{reusedTaskApiProfileName:null,reusedTaskApiProfileMissing:!1,reusedTaskApiModel:null}:{}}})},dismissedCodexCliPrompts:[],dismissCodexCliPrompt:r=>e(n=>({dismissedCodexCliPrompts:n.dismissedCodexCliPrompts.includes(r)?n.dismissedCodexCliPrompts:[...n.dismissedCodexCliPrompts,r]})),prompt:"",setPrompt:r=>e(n=>Nn(n,{prompt:r})),promptSelection:null,setPromptSelection:r=>e(n=>({promptSelection:{...r,prompt:n.prompt}})),inputImages:[],addInputImage:r=>e(n=>n.inputImages.find(a=>a.id===r.id)?n:Nn(n,{inputImages:[...n.inputImages,r]})),replaceInputImage:(r,n)=>{let a=null;e(o=>{var c;if(r<0||r>=o.inputImages.length)return o;const i=o.inputImages[r];if(!i||i.id===n.id||o.inputImages.some((u,f)=>f!==r&&u.id===n.id))return o;a=i.id;const l=o.inputImages.map((u,f)=>f===r?n:u);return Nn(o,Ws(o,l,{equivalentImageIds:{[i.id]:n.id},clearMissingMask:i.id===((c=o.maskDraft)==null?void 0:c.targetImageId)}))}),a&&bb(a)},removeInputImage:r=>e(n=>{var i;const a=n.inputImages[r],o=n.inputImages.filter((l,c)=>c!==r);return Nn(n,Ws(n,o,{clearMissingMask:(a==null?void 0:a.id)===((i=n.maskDraft)==null?void 0:i.targetImageId)}))}),clearInputImages:()=>e(r=>{for(const n of r.inputImages)jx(n.id);return Nn(r,{...Ws(r,[]),maskDraft:null,maskEditorImageId:null})}),setInputImages:(r,n)=>e(a=>{var i;const o=f0(r,(i=a.maskDraft)==null?void 0:i.targetImageId);return Nn(a,Ws(a,o,{equivalentImageIds:n==null?void 0:n.equivalentImageIds}))}),moveInputImage:(r,n)=>e(a=>{var d,g;const o=[...a.inputImages];if(r<0||r>=o.length)return a;const i=(d=a.maskDraft)==null?void 0:d.targetImageId;if(i&&((g=o[r])==null?void 0:g.id)===i)return a;const l=i&&o.some(m=>m.id===i)?1:0,c=Math.max(l,Math.min(o.length,n)),u=r<c?c-1:c;if(u===r)return a;const[f]=o.splice(r,1);return o.splice(u,0,f),Nn(a,Ws(a,o,{clearMissingMask:!1}))}),maskDraft:null,setMaskDraft:r=>e(n=>{const a=f0(n.inputImages,r==null?void 0:r.targetImageId);return Nn(n,{maskDraft:r,inputImages:a,prompt:jf(n.prompt,n.inputImages,a)})}),clearMaskDraft:()=>e(r=>Nn(r,{maskDraft:null})),maskEditorImageId:null,setMaskEditorImageId:r=>{r&&xr(),e(n=>Nn(n,{maskEditorImageId:r}))},galleryInputDraft:null,params:{...Qr},setParams:r=>e(n=>({params:{...n.params,...r}})),reusedTaskApiProfileId:null,reusedTaskApiProfileName:null,reusedTaskApiProfileMissing:!1,reusedTaskApiModel:null,setReusedTaskApiProfile:(r,n=!1,a=null,o=null)=>e({reusedTaskApiProfileId:r,reusedTaskApiProfileName:a,reusedTaskApiProfileMissing:n,reusedTaskApiModel:r?o:null}),setReusedTaskApiModel:r=>e({reusedTaskApiModel:r}),batchProgress:null,setBatchProgress:r=>e({batchProgress:r}),agentConversations:[],agentConversationsLoaded:!1,activeAgentConversationId:null,agentInputDrafts:{},agentSidebarCollapsed:!0,agentAssetTab:"outputs",agentAssetPanelCollapsed:!1,agentMobileHeaderVisible:!1,agentEditingRoundId:null,agentEditingConversationId:null,agentGeneratingTitleIds:{},createAgentConversation:()=>{const r=Date.now(),n=hj(t().agentConversations);if(n&&Yf(n))return e(o=>{const i=_a(o);return{agentConversations:o.agentConversations.map(l=>l.id===n.id?{...l,createdAt:r,updatedAt:r}:l),activeAgentConversationId:n.id,agentInputDrafts:i,agentSidebarCollapsed:!0,agentEditingRoundId:null,...Xs(i,n.id)}}),n.id;const a=gj(r);return e(o=>{const i=_a(o);return{agentConversations:[...o.agentConversations,a],activeAgentConversationId:a.id,agentInputDrafts:i,agentSidebarCollapsed:!0,agentEditingRoundId:null,...Xs(i,a.id)}}),a.id},setActiveAgentConversationId:r=>e(n=>{if(n.activeAgentConversationId===r)return{activeAgentConversationId:r,agentSidebarCollapsed:!0,agentAssetPanelCollapsed:!0,agentEditingRoundId:null};const a=_a(n);return{activeAgentConversationId:r,agentInputDrafts:a,agentSidebarCollapsed:!0,agentAssetPanelCollapsed:!0,agentEditingRoundId:null,...Xs(a,r)}}),setActiveAgentRoundId:(r,n)=>e(a=>({agentConversations:a.agentConversations.map(o=>o.id===r?{...o,activeRoundId:n,updatedAt:Date.now()}:o)})),renameAgentConversation:(r,n)=>e(a=>({agentConversations:a.agentConversations.map(o=>o.id===r?{...o,title:n,updatedAt:Date.now()}:o)})),deleteAgentConversation:r=>e(n=>{const a={...n.agentInputDrafts};delete a[r];const o=n.activeAgentConversationId===r;return{agentConversations:n.agentConversations.filter(i=>i.id!==r),activeAgentConversationId:o?null:n.activeAgentConversationId,agentInputDrafts:a,...o?Ku():{}}}),deleteAgentRound:(r,n)=>Xj(r,n),deleteAgentAssistantMessage:(r,n)=>qj(r,n),setAgentSidebarCollapsed:r=>e({agentSidebarCollapsed:r}),setAgentAssetTab:r=>e({agentAssetTab:r}),setAgentAssetPanelCollapsed:r=>e({agentAssetPanelCollapsed:r}),setAgentMobileHeaderVisible:r=>e({agentMobileHeaderVisible:r}),setAgentEditingRoundId:r=>e({agentEditingRoundId:r}),setAgentEditingConversationId:r=>e({agentEditingConversationId:r}),tasks:[],setTasks:r=>e(()=>({tasks:r,...to(r)<=xi?{supportPromptSkippedForImportedData:!1}:{}})),favoriteCollections:[lg()],setFavoriteCollections:r=>e(n=>{const a=pd(hi(r));return{favoriteCollections:a,defaultFavoriteCollectionId:Gi(a,n.defaultFavoriteCollectionId)}}),defaultFavoriteCollectionId:mi,setDefaultFavoriteCollectionId:r=>e(n=>r===null||n.favoriteCollections.some(a=>a.id===r)?{defaultFavoriteCollectionId:r}:n),activeFavoriteCollectionId:null,isManageCollectionsModalOpen:!1,setActiveFavoriteCollectionId:r=>e({activeFavoriteCollectionId:r,selectedTaskIds:[],selectedFavoriteCollectionIds:[]}),openManageCollectionsModal:()=>e({isManageCollectionsModalOpen:!0}),closeManageCollectionsModal:()=>e({isManageCollectionsModalOpen:!1}),favoritePickerTaskIds:null,openFavoritePicker:r=>{r.length&&(xr(),e({favoritePickerTaskIds:Array.from(new Set(r)).filter(Boolean)}))},closeFavoritePicker:()=>e({favoritePickerTaskIds:null}),streamPreviews:{},streamPreviewSlots:{},setTaskStreamPreview:(r,n,a=0)=>e(o=>{if(n){if(!o.tasks.some(f=>f.id===r))return o;const c=String(a),u=o.streamPreviewSlots[r]??{};return o.streamPreviews[r]===n&&u[c]===n?o:{streamPreviews:{...o.streamPreviews,[r]:n},streamPreviewSlots:{...o.streamPreviewSlots,[r]:{...u,[c]:n}}}}if(!(r in o.streamPreviews)&&!(r in o.streamPreviewSlots))return o;const i={...o.streamPreviews},l={...o.streamPreviewSlots};return delete i[r],delete l[r],{streamPreviews:i,streamPreviewSlots:l}}),searchQuery:"",setSearchQuery:r=>e({searchQuery:r}),filterStatus:"all",setFilterStatus:r=>e({filterStatus:r}),filterFavorite:!1,setFilterFavorite:r=>e(r?{filterFavorite:r,selectedTaskIds:[],selectedFavoriteCollectionIds:[]}:{filterFavorite:r,activeFavoriteCollectionId:null,selectedTaskIds:[],selectedFavoriteCollectionIds:[]}),selectedTaskIds:[],setSelectedTaskIds:r=>e(n=>({selectedTaskIds:typeof r=="function"?r(n.selectedTaskIds):r})),toggleTaskSelection:(r,n)=>e(a=>{const o=a.selectedTaskIds.includes(r),i=n!==void 0?n:!o;return i===o?a:{selectedTaskIds:i?[...a.selectedTaskIds,r]:a.selectedTaskIds.filter(l=>l!==r)}}),clearSelection:()=>e({selectedTaskIds:[]}),selectedFavoriteCollectionIds:[],setSelectedFavoriteCollectionIds:r=>e(n=>({selectedFavoriteCollectionIds:typeof r=="function"?r(n.selectedFavoriteCollectionIds):r})),toggleFavoriteCollectionSelection:(r,n)=>e(a=>{const o=a.selectedFavoriteCollectionIds.includes(r),i=n!==void 0?n:!o;return i===o?a:{selectedFavoriteCollectionIds:i?[...a.selectedFavoriteCollectionIds,r]:a.selectedFavoriteCollectionIds.filter(l=>l!==r)}}),clearFavoriteCollectionSelection:()=>e({selectedFavoriteCollectionIds:[]}),detailTaskId:null,setDetailTaskId:r=>{r&&xr(),e({detailTaskId:r})},lightboxImageId:null,lightboxImageList:[],lightboxCommentPrompt:null,setLightboxImageId:(r,n,a=null)=>{r&&xr(),e({lightboxImageId:r,lightboxImageList:n??(r?[r]:[]),lightboxCommentPrompt:r?a:null})},sketchBoard:null,setSketchBoard:r=>{r&&xr(),e({sketchBoard:r})},showSettings:!1,settingsTabRequest:null,setShowSettings:(r,n)=>{r&&xr(),e({showSettings:r,...n?{settingsTabRequest:n}:{},...r?{}:{settingsTabRequest:null}})},supportPromptOpen:!1,supportPromptDismissed:!1,supportPromptSkippedForImportedData:!1,imageSourceUrls:{},setSupportPromptOpen:r=>e({supportPromptOpen:r}),dismissSupportPrompt:()=>e({supportPromptOpen:!1,supportPromptDismissed:!0}),toast:null,showToast:(r,n="info")=>{const o={message:nj(r,n),type:n};e({toast:o}),setTimeout(()=>{e(i=>i.toast===o?{toast:null}:i)},3e3)},confirmDialog:null,setConfirmDialog:r=>{r&&xr(),e({confirmDialog:r})},privacyMode:null,privacyModeEpoch:0,settingsModalEpoch:0,togglePrivacyMode:()=>{const r=t();if(r.privacyMode){e({privacyMode:null,...ZC(r.privacyMode.inputSnapshot,r)});const i=r.privacyMode.stoppedBatchPrompts;i>0&&t().showToast(`进入隐私模式时停止了批量提交,${i} 条提示词未提交`,"info");return}const n=GC(r,Date.now());r.batchProgress&&ra(Is),xr();const a=!!Ma.getState().mode,o=r.agentConversations.find(i=>i.id===r.activeAgentConversationId);e({privacyMode:n,privacyModeEpoch:r.privacyModeEpoch+1,appMode:"gallery",...Ku(),galleryInputDraft:null,agentInputDrafts:{},activeAgentConversationId:o&&!mb(n,o)?o.id:null,reusedTaskApiProfileId:null,reusedTaskApiProfileName:null,reusedTaskApiProfileMissing:!1,reusedTaskApiModel:null,agentMobileHeaderVisible:!0,agentEditingRoundId:null,agentEditingConversationId:null,searchQuery:"",filterStatus:"all",filterFavorite:!1,activeFavoriteCollectionId:null,selectedTaskIds:[],selectedFavoriteCollectionIds:[],...a?{}:{showSettings:!1,settingsTabRequest:null,confirmDialog:null,settingsModalEpoch:r.settingsModalEpoch+1},detailTaskId:null,lightboxImageId:null,lightboxImageList:[],lightboxCommentPrompt:null,sketchBoard:null,favoritePickerTaskIds:null,isManageCollectionsModalOpen:!1,toast:null})}}),{name:"gpt-image-playground",storage:zh(()=>De?lf:window.localStorage),version:2,migrate:UC,partialize:pj,merge:xj}));let Cc=w.getState().agentConversations,Jd=!1,Jo=!1;async function wb(){if(Jd){Jo=!0;return}Jd=!0;try{do{Jo=!1;const e=w.getState().agentConversations;await gg(e),Cc=e}while(Jo||w.getState().agentConversations!==Cc)}finally{Jd=!1}}w.subscribe(e=>{if(e.agentConversations!==Cc){if(!fg){Jo=!0;return}wb()}});let bj=0;function fr(){return Date.now().toString(36)+(++bj).toString(36)+Math.random().toString(36).slice(2,6)}function mg(e){const t=l2(e.rawResponsePayload);return t===e.rawResponsePayload?e:{...e,rawResponsePayload:t}}function wn(e){return bp(mg(e))}function kb(e){const t=zt(e);return`${t.baseUrl}
|
|
47
|
+
${t.apiKey}`}function Ib(e){return e.status==="running"&&(e.apiProvider??"openai")!=="fal"}function Cb(e,t,r){const n=Rn(e,t);return n!=null&&n.poll?!!(r&&n.editSubmit?n.editSubmit:n.submit).taskIdPath:!1}function yi(e){const t=wc.get(e);t&&clearTimeout(t),wc.delete(e)}function yj(e,t,r=Date.now()){const n=w.getState().tasks.find(a=>a.id===e);return!n||!Ib(n)?!1:(Rt(e,{...Wr(n,t,r),falRecoverable:!1,elapsed:Math.max(0,r-(n.startedAt??n.createdAt))}),bi(n),!0)}function vj(e,t,r){yi(e);const n=w.getState().tasks.find(l=>l.id===e);if(!n||!Ib(n))return;const a=Math.max(0,t*1e3),o=Math.max(0,a-(Date.now()-(n.startedAt??n.createdAt))),i=setTimeout(()=>{wc.delete(e),yj(e,lj(t,r))&&!eo(n)&&w.getState().showToast("OpenAI 任务请求超时","error")},o);wc.set(e,i)}function wj(e,t,r,n){return(r.n>0?r.n:1)<=1?!1:t.provider==="openai"?t.apiMode==="responses"?!0:t.apiMode==="images"&&(t.codexCli||t.streamImages):t.provider!=="fal"&&t.codexCli&&!Cb(e,t.provider,n)}function jb(e){var t;return!!((t=e.outputErrors)!=null&&t.length)}function vi(e,t){return t==="all"?!0:t==="error"?e.status==="error"||jb(e):e.status===t}function jc(e,t){const r=t.trim().toLowerCase();if(!r)return!0;const n=ai(e.prompt||"",e.inputImageIds.length).toLowerCase(),a=JSON.stringify(e.params).toLowerCase(),o=[e.error,...(e.outputErrors??[]).map(i=>i.error)].filter(Boolean).join(`
|
|
48
|
+
`).toLowerCase();return n.includes(r)||a.includes(r)||o.includes(r)}function Gu(e=!1,t="接口返回的提示词已被改写"){const r=w.getState(),n=r.settings,a=kb(n);if(!e&&(n.codexCli||r.dismissedCodexCliPrompts.includes(a)))return;const o=n.allowPromptRewrite?"当前已允许模型改写优化提示词,因此不会额外加入不改写要求。":"同时,提示词文本开头会加入简短的不改写要求,避免模型重写提示词,偏离原意。";r.setConfirmDialog({title:"检测到 Codex CLI API",message:`${t},当前 API 来源很可能是 Codex CLI。
|
|
49
|
+
|
|
50
|
+
是否开启 Codex CLI 兼容模式?开启后会禁用在此处无效的质量参数,并在 Images API 多图生成时使用并发请求,解决该 API 数量参数无效的问题。${o}`,confirmText:"开启",action:()=>{const i=w.getState();i.dismissCodexCliPrompt(a),i.setSettings({codexCli:!0})},cancelAction:()=>w.getState().dismissCodexCliPrompt(a)})}function kj(e,t){const r=wi(e,t);return(r==null?void 0:r.provider)==="fal"&&t.apiProvider==="fal"?r:null}function Ij(e,t){const r=wi(e,t);return r&&r.provider===t.apiProvider&&r.provider!=="openai"&&r.provider!=="fal"?r:null}function wi(e,t){const r=Me(e);if(!t.apiProfileId)return null;const n=r.profiles.find(a=>a.id===t.apiProfileId);return n?oo(n,t.apiModel):null}function kn(e,t){const r=Me(e);return Me({...r,baseUrl:t.baseUrl,apiKey:t.apiKey,model:t.model,timeout:t.timeout,apiMode:t.apiMode,codexCli:t.codexCli,apiProxy:t.apiProxy,profiles:r.profiles.map(n=>n.id===t.id?t:n),activeProfileId:t.id})}function vd(e){const t=Me(e),r=Bi(t);if(!r||r.provider!=="openai"||r.apiMode!=="responses")return{profile:r,message:"Agent 模式需要使用支持 Responses API 的 OpenAI 兼容文本模型配置。"};const n=ti(r);if(n)return{profile:r,message:`文本模型 API 配置不完整:${n}`};if(t.agentApiConfigMode==="hybrid"){const a=Ui(t);if(!a)return{profile:null,message:"图像模型 API 配置不存在,请在「设置 → Agent 配置」中选择可用的图像模型配置。"};const o=ti(a);if(o)return{profile:a,message:`图像模型 API 配置不完整:${o}`}}return null}function Cj(e,t,r){if(!t)return null;const n=Me(e).profiles.find(a=>a.id===t);return n?oo(n,r??void 0):null}function jj(e){return e.apiProfileName||e.apiModel||"未知配置"}function Sc(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"||e instanceof Lc)return!0;const t=e instanceof Error?e.message:String(e);return/abort|network|failed to fetch|fetch failed|load failed|timeout|连接|断开|中断/i.test(t)}function Sj(e){if(e instanceof Lc)return!0;if(e instanceof TypeError){const t=e.message.toLowerCase();return/failed to fetch|fetch failed|load failed|networkerror|network request failed/i.test(t)}return!1}function Nj(e){return e==="responses"?"Responses API":"Image API"}function Sb(e,t,r,n){if(!Sj(e))return null;const a=Math.max(0,(Date.now()-t)/1e3);return e instanceof Lc&&!e.message.startsWith("无法连接到服务器")&&(a<=15||!/^(连接被服务器重置|服务器未返回响应就关闭了连接)/.test(e.message))?null:a<=15?r&&!De?"提示:请求立即失败,请检查 API 代理服务是否正常运行。":`提示:请求立即失败,可能原因:
|
|
51
|
+
· API 服务器不可达或地址有误,请检查 API URL 是否正确、服务是否正常运行${(n==null?void 0:n.provider)==="openai"?`
|
|
52
|
+
· API 不支持 ${Nj(n.apiMode)}`:""}${De?"":`
|
|
53
|
+
· 接口不支持浏览器跨域请求,可使用 Docker 部署版或本地运行版并配置 API 代理解决`}`:a>=55&&a<=75?`提示:请求等待约 60 秒后被断开,这通常是 Nginx 等反向代理的默认超时,而非接口本身报错。可调大代理的超时时间(如 proxy_read_timeout),或降低图片尺寸/质量后重试。${Fl(n)}`:a>=110&&a<=140?`提示:请求等待约 120 秒后被断开,这通常是 Cloudflare 等 CDN/网关的超时限制,而非接口本身报错。如果使用 Cloudflare,可考虑升级套餐或使用不经过 CDN 的直连地址。${Fl(n)}`:`提示:请求等待较长时间后被断开,通常是反向代理或网关的超时限制,而非接口本身报错。可检查代理超时设置,或降低图片尺寸/质量后重试。${Fl(n)}`}function wd(e){if(!(e instanceof Error))return{};const t="rawImageUrls"in e?e.rawImageUrls:void 0,r="rawResponsePayload"in e?e.rawResponsePayload:void 0;return{rawImageUrls:Array.isArray(t)&&t.length?t.filter(n=>typeof n=="string"):void 0,rawResponsePayload:typeof r=="string"?r:void 0}}function ki(e){const t=Xo.get(e);t&&clearTimeout(t),Xo.delete(e)}function Ii(e,t=QC){if(Xo.has(e)||!w.getState().tasks.some(n=>n.id===e))return;const r=setTimeout(()=>{Xo.delete(e),Mj(e)},t);Xo.set(e,r)}function Ci(e){const t=qo.get(e);t&&clearTimeout(t),qo.delete(e)}function kd(e,t=ej){if(qo.has(e)||!w.getState().tasks.some(n=>n.id===e))return;const r=setTimeout(()=>{qo.delete(e),Qj(e)},t);qo.set(e,r)}async function Aj(e){if(!(typeof Image>"u"))return new Promise(t=>{let r=!1;const n=new Image,a=i=>{r||(r=!0,clearTimeout(o),t(i))},o=setTimeout(()=>a(void 0),2e3);n.onload=()=>{n.naturalWidth>0&&n.naturalHeight>0?a({size:`${n.naturalWidth}x${n.naturalHeight}`}):a(void 0)},n.onerror=()=>a(void 0),n.src=e,n.complete&&n.naturalWidth>0&&n.naturalHeight>0&&a({size:`${n.naturalWidth}x${n.naturalHeight}`})})}async function Pj(e){return Promise.all(e.map(t=>Aj(t)))}async function hg(e,t,r){const n=e.map((o,i)=>lb(t==null?void 0:t[i],r==null?void 0:r[i]));if(n.every(Xu))return n;const a=await Pj(e);return e.map((o,i)=>{const l=n[i],c=a[i];return Xu(l)?l:c!=null&&c.size?{...l??{},size:c.size}:bd(l)?l:c})}async function Tj(e,t){const r=w.getState().tasks.find(u=>u.id===e.id);if(!r||r.status==="done"||r.error===nn||r.status!=="running"&&!r.falRecoverable)return;const{outputIds:n,outputDataUrls:a,outputImageSizes:o,transparentOriginalImageIds:i}=await xg(e,t.images),l=await hg(a,t.actualParamsList,o),c=w.getState().tasks.find(u=>u.id===e.id);if(!c||c.status==="done"||c.error===nn||c.status!=="running"&&!c.falRecoverable){await ns([...n,...i??[]]);return}Rt(e.id,{outputImages:n,transparentOriginalImages:i,actualParams:bc(l),actualParamsByImage:cg(n,l),revisedPromptByImage:void 0,...xd(e,Date.now()),falRecoverable:!1}),eo(e)||(w.getState().showToast(`fal.ai 任务已恢复,共 ${n.length} 张图片`,"success"),vn(e)||ks("图像生成完成",`fal.ai 任务已恢复,共 ${n.length} 张图片。`)),vn(e)&&Id(e.id)}async function Mj(e){const{settings:t,tasks:r}=w.getState(),n=r.find(o=>o.id===e);if(!n||n.apiProvider!=="fal"||!n.falRequestId||!n.falEndpoint||n.status==="done")return;const a=kj(t,n);if(!a){Ii(e);return}try{const o=await G1(a,n.falEndpoint,n.falRequestId,n.params);ki(e),await Tj(n,o);return}catch(o){if(!w.getState().tasks.some(l=>l.id===e))return;if(Sc(o)){Ii(e);return}ki(e);const i=Wp(o)??(o instanceof Error?o.message:String(o));Rt(e,{...Wr(n,i,Date.now()),...wd(o),falRecoverable:!1}),bi(n),vn(n)&&Id(e)}}async function Ej(){var C;const e=Ho(w.getState().agentConversations),t=await Af(),r=Ho(await Ok());let n=l0(r,e);const a=Ho(w.getState().agentConversations);n=l0(n,a);const o=w.getState().activeAgentConversationId&&n.some(T=>T.id===w.getState().activeAgentConversationId)?w.getState().activeAgentConversationId:((C=n[0])==null?void 0:C.id)??null;n.length>0||e.length>0?(w.setState(T=>{const R=rb(tb(T.agentInputDrafts,n),o);return{agentConversations:n,agentConversationsLoaded:!0,activeAgentConversationId:o,agentInputDrafts:R,...T.appMode==="agent"?Xs(R,o):{}}}),await gg(n)):w.setState({agentConversationsLoaded:!0});const i=Ic;fg=!0,Ic=!1,(Jo||w.getState().agentConversations!==Cc)&&await wb(),i&&w.setState({});const{tasks:l,interruptedTasks:c}=$C(t,Date.now()),u=new Set(c.map(T=>T.id)),f=w.getState(),d=ib(l.map(mg),f.favoriteCollections,f.defaultFavoriteCollectionId),g=d.tasks;d.collections!==f.favoriteCollections&&f.setFavoriteCollections(d.collections),d.defaultFavoriteCollectionId!==f.defaultFavoriteCollectionId&&w.getState().setDefaultFavoriteCollectionId(d.defaultFavoriteCollectionId),await Promise.all(g.filter((T,R)=>{var U;return d.changed||u.has(T.id)||T.rawResponsePayload!==((U=l[R])==null?void 0:U.rawResponsePayload)}).map(T=>wn(T))),w.getState().setTasks(g),dj(g);for(const T of g)Px(T)&&Ii(T.id,0),Tx(T)&&kd(T.id,0);const m=new Set,x=w.getState(),b=x.inputImages,h=x.galleryInputDraft,y=x.agentConversations,v=x.agentInputDrafts;for(const T of b)m.add(T.id);if(h)for(const T of h.inputImages)m.add(T.id);for(const T of Object.values(v))for(const R of T.inputImages)m.add(R.id);for(const T of y)for(const R of T.rounds)for(const U of R.inputImageIds)m.add(U);for(const T of g)pg(m,T);const I=await vp(),S=[];for(const T of I)m.has(T)?S.push(T):await wp(T);const k=w.getState().imageSourceUrls;Object.keys(k).some(T=>!m.has(T))&&w.setState({imageSourceUrls:Object.fromEntries(Object.entries(k).filter(([T])=>m.has(T)))}),Ax(S),De||setTimeout(()=>void uk(),2e3);const j=[];for(const T of b){if(T.dataUrl){j.push(T),Xt(T.id,T.dataUrl);continue}const R=await qn(T.id);R!=null&&R.dataUrl&&(j.push({...T,dataUrl:R.dataUrl}),Xt(T.id,R.dataUrl))}if((j.length!==b.length||j.some((T,R)=>{var U;return T.dataUrl!==((U=b[R])==null?void 0:U.dataUrl)}))&&w.getState().setInputImages(j),h){const T=[];for(const F of h.inputImages){if(F.dataUrl){T.push(F),Xt(F.id,F.dataUrl);continue}const _=await qn(F.id);_!=null&&_.dataUrl&&(T.push({...F,dataUrl:_.dataUrl}),Xt(F.id,_.dataUrl))}const R={...h,...Ws(h,T)},U=h.maskDraft!==R.maskDraft;if(T.length!==h.inputImages.length||T.some((F,_)=>{var O;return F.dataUrl!==((O=h.inputImages[_])==null?void 0:O.dataUrl)})||U){const F=w.getState(),_=rs(R)?null:R;w.setState({galleryInputDraft:_,...F.appMode==="gallery"?hd(_):{}})}}const A={};let N=!1;for(const[T,R]of Object.entries(v)){const U=[];for(const _ of R.inputImages){if(_.dataUrl){U.push(_),Xt(_.id,_.dataUrl);continue}const O=await qn(_.id);O!=null&&O.dataUrl&&(U.push({..._,dataUrl:O.dataUrl}),Xt(_.id,O.dataUrl))}const W={...R,...Ws(R,U)},F=R.maskDraft!==W.maskDraft;rs(W)||(A[T]=W),(U.length!==R.inputImages.length||U.some((_,O)=>{var J;return _.dataUrl!==((J=R.inputImages[O])==null?void 0:J.dataUrl)})||F)&&(N=!0)}if(N){const T=w.getState();w.setState({agentInputDrafts:A,...T.appMode==="agent"?Xs(A,T.activeAgentConversationId):{}})}}async function ji(e={}){const t=w.getState(),{settings:r,params:n,showToast:a,setConfirmDialog:o}=t,i=e.input,l=i?i.prompts[0]??"":t.prompt,c=(i==null?void 0:i.inputImages)??t.inputImages,u=i?null:t.maskDraft,{reusedTaskApiProfileId:f,reusedTaskApiProfileName:d,reusedTaskApiProfileMissing:g,reusedTaskApiModel:m}=i?{reusedTaskApiProfileId:null,reusedTaskApiProfileName:null,reusedTaskApiProfileMissing:!1,reusedTaskApiModel:null}:t,x=Me(r);let b=zt(r),h=kn(x,b);if(x.reuseTaskApiProfileTemporarily&&(f||g)){const W=Cj(x,f,m);if(W)b=W,h=kn(x,W);else if(e.useCurrentApiProfileWhenReusedMissing)w.getState().setReusedTaskApiProfile(null);else return o({title:"找不到 API 配置",message:`找不到复用任务所使用的 API 配置「${d||"未知配置"}」,要使用当前的 API 配置「${b.name}」提交任务吗?`,confirmText:"使用当前配置提交",cancelText:"放弃提交",action:()=>{ji({...e,useCurrentApiProfileWhenReusedMissing:!0})}}),[]}if(ti(b))return a(`请先完善请求 API 配置:${ti(b)}`,"error"),w.getState().setShowSettings(!0),[];if(!l.trim())return a("请输入提示词","error"),[];const y=i&&i.prompts.length>1?i.prompts:x.showBatchPrompt&&x.batchPromptEnabled?Yh(l):[];if(w.getState().batchProgress)return a("批量任务进行中,请等待完成或停止后再提交","error"),[];const v=y.length?Rj(y.length):0;let I=c,S=null,k=null;if(u)try{if(I=Yp(c,u.targetImageId),await Kp(u.maskDataUrl,I[0].dataUrl)==="full"&&!e.allowFullMask)return o({title:"确认编辑整张图片?",message:"当前遮罩覆盖了整张图片,提交后可能会重绘全部内容。是否继续?",confirmText:"继续提交",tone:"warning",action:()=>{ji({allowFullMask:!0})}}),ra(v),[];S=await Qn(u.maskDataUrl,"mask"),Xt(S,u.maskDataUrl),k=u.targetImageId}catch(W){return c.some(F=>F.id===u.targetImageId)||w.getState().clearMaskDraft(),a(W instanceof Error?W.message:String(W),"error"),ra(v),[]}try{for(const W of I)await Qn(W.dataUrl)}catch(W){return console.error("保存参考图失败",W),ra(v),a(`保存参考图失败:${W instanceof Error?W.message:String(W)}`,"error"),[]}const j=Mn(n,h,{hasInputImages:I.length>0}),N=(j.output_format==="png"||j.output_format==="webp")&&j.transparent_output?wx(j):{...j,transparent_output:!1},C=vx(n,N);Object.keys(C).length&&w.getState().setParams(C);const T=!i&&x.saveTasksToActiveFavoriteCollection,R=[],U=async W=>{const F=T?ob({filterFavorite:t.filterFavorite,activeFavoriteCollectionId:t.activeFavoriteCollectionId,favoriteCollections:w.getState().favoriteCollections,defaultFavoriteCollectionId:w.getState().defaultFavoriteCollectionId}):null,_=N.transparent_output&&b.transparentBackgroundMethod==="local"?kx(W):null,O={id:fr(),prompt:W,params:N,apiProvider:b.provider,apiProfileId:b.id,apiProfileName:b.name,apiMode:b.apiMode,apiModel:b.model,inputImageIds:I.map(J=>J.id),maskTargetImageId:k,maskImageId:S,transparentOutput:_==null?void 0:_.transparentOutput,transparentPrompt:_==null?void 0:_.effectivePrompt,outputImages:[],status:"running",error:null,createdAt:Date.now(),finishedAt:null,elapsed:null,...F};return w.getState().setTasks([O,...w.getState().tasks]),await wn(O),v&&ro.add(O.id),R.push(O.id),Tb(O.id),O.id};if(y.length?w.getState().showToast(`已开始批量提交 ${y.length} 条提示词`,"success"):(await U(l.trim()),w.getState().showToast("任务已提交","success")),i||(r.clearInputAfterSubmit&&(w.getState().setPrompt(""),w.getState().clearInputImages()),w.getState().setReusedTaskApiProfile(null)),y.length){const W=x.batchPromptMode==="queue"?1:x.batchPromptConcurrencyLimited?x.batchPromptConcurrency:y.length;await _j(v,y,W,U)}return R}let Is=0;const ro=new Set;function Rj(e){return Is+=1,w.getState().setBatchProgress({total:e,started:0,finished:0}),Is}function ra(e){!e||e!==Is||(Is+=1,ro.clear(),w.getState().setBatchProgress(null))}function Nb(e,t){const r=n=>{var a;return t()||((a=n.find(o=>o.id===e))==null?void 0:a.status)!=="running"};return new Promise(n=>{if(r(w.getState().tasks)){n();return}const a=w.subscribe(o=>{r(o.tasks)&&(a(),n())})})}async function _j(e,t,r,n){const a=()=>e!==Is,o=t.length;let i=0,l=0,c=0;if(await dw(t,r,async f=>{var d;i+=1,w.getState().setBatchProgress({total:o,started:i,finished:l});try{const g=await n(f);await Nb(g,a),((d=w.getState().tasks.find(m=>m.id===g))==null?void 0:d.status)==="error"&&(c+=1)}catch(g){c+=1,console.error("批量提交任务失败",g)}l+=1,a()||w.getState().setBatchProgress({total:o,started:i,finished:l})},a),a())return;ra(e);const u=c>0?`批量生成完成:成功 ${o-c} 条,失败 ${c} 条`:`批量生成完成,共 ${o} 条`;w.getState().showToast(u,c>0?"error":"success"),ks("批量生成完成",`${u}。`)}function Dj(){const e=w.getState().batchProgress;e&&(ra(Is),w.getState().showToast(`已停止批量提交,共提交 ${e.started} / ${e.total} 条,已开始的任务会继续完成`,"info"))}function Lj(){const e=w.getState(),t=e.agentConversations.find(n=>n.id===e.activeAgentConversationId);if(t)return t;const r=e.createAgentConversation();return w.getState().agentConversations.find(n=>n.id===r)}function ar(e,t){w.setState(r=>({agentConversations:r.agentConversations.map(n=>n.id===e?t(n):n)}))}function Vn(e,t){return`${e}:${t}`}function g0(e,t,r){return Array.from(kc.values()).filter(n=>n.controller===r&&n.task.agentConversationId===e&&n.task.agentRoundId===t).map(n=>n.task)}function us(){return new DOMException("Agent 请求已停止","AbortError")}function m0(){const e=new Error("Agent recovery paused");return e.name=pb,e}function h0(e){return e instanceof Error&&e.name===pb}function Oj(e){const t=e.trimEnd();return t?t.endsWith(nn)?t:`${t}
|
|
54
|
+
|
|
55
|
+
${nn}`:nn}function Bj(e,t,r=Date.now()){const n=w.getState().tasks.filter(a=>(a.status==="running"||a.falRecoverable||a.customRecoverable)&&a.agentConversationId===e&&a.agentRoundId===t);for(const a of n)ki(a.id),Ci(a.id),Rt(a.id,{...Wr(a,nn,r),falRecoverable:!1,customRecoverable:!1,elapsed:Math.max(0,r-(a.startedAt??a.createdAt))});return n.length>0}function p0(e,t,r,n,a=()=>!0,o=Date.now()){const i=w.getState().tasks.filter(l=>l.status==="running"&&l.agentConversationId===e&&l.agentRoundId===t&&a(l));for(const l of i)w.getState().setTaskStreamPreview(l.id),Rt(l.id,{...Wr(l,r,o),...n?{rawResponsePayload:n}:{},falRecoverable:!1,customRecoverable:!1,elapsed:Math.max(0,o-(l.startedAt??l.createdAt))});return i.length>0}function Zu(e,t){const r=Date.now(),n=Bj(e,t,r);let a=!1;return ar(e,o=>{const i=o.rounds.find(u=>u.id===t);if(!i||i.status!=="running")return o;a=!0;const l=o.messages.find(u=>u.roundId===t&&u.role==="assistant"),c=(l==null?void 0:l.id)??fr();return{...o,updatedAt:r,rounds:o.rounds.map(u=>u.id===t?{...u,...c?{assistantMessageId:c}:{},status:"error",error:nn,finishedAt:r}:u),messages:l?o.messages.map(u=>u.id===l.id?{...u,content:Oj(u.content)}:u):[...o.messages,{id:c,role:"assistant",content:nn,roundId:t,createdAt:r}]}}),a||n}function Gd(e,t,r){r&&ar(e,n=>({...n,updatedAt:Date.now(),messages:n.messages.map(a=>a.id===t?{...a,content:`${a.content}${r}`}:a)}))}async function Uj(e,t,r,n,a,o){w.setState(i=>({agentGeneratingTitleIds:{...i.agentGeneratingTitleIds,[e]:!0}}));try{const i=await Wj(r),l=await qI({settings:n,profile:a,prompt:t,imageDataUrls:i});if(!l||l===o)return;ar(e,c=>{const u=c.rounds[0];return!u||gr(u.prompt)!==t||c.title!==o?c:{...c,title:l,updatedAt:Date.now()}})}catch{}finally{w.setState(i=>{const l={...i.agentGeneratingTitleIds};return delete l[e],{agentGeneratingTitleIds:l}})}}function Fj(e=w.getState().activeAgentConversationId){if(!e)return;const t=w.getState().agentConversations.find(o=>o.id===e);if(!t)return;const n=[...fa(t)].reverse().find(o=>o.status==="running")??t.rounds.find(o=>o.status==="running");if(!n)return;const a=ta.get(Vn(e,n.id));if(a){a.abort(),Zu(e,n.id)&&w.getState().showToast("已停止生成","info");return}Zu(e,n.id),w.getState().showToast("已停止生成","info")}function $j(e,t=w.getState().agentConversations,r=w.getState().agentInputDrafts){for(const n of t){for(const a of n.rounds){for(const o of a.inputImageIds)e.add(o);a.maskImageId&&e.add(a.maskImageId)}for(const a of n.messages)a.maskImageId&&e.add(a.maskImageId)}for(const n of Object.values(r))for(const a of n.inputImages)e.add(a.id)}function zj(e,t){if(t)for(const r of t.inputImages)e.add(r.id)}function pg(e,t){for(const r of t.inputImageIds||[])e.add(r);t.maskImageId&&e.add(t.maskImageId);for(const r of t.outputImages||[])e.add(r);for(const r of t.transparentOriginalImages||[])r&&e.add(r);for(const r of t.streamPartialImageIds||[])e.add(r)}async function xg(e,t){const r=[],n=[],a=[],o=[],i=[];try{for(const l of t){let c=l;if(e.transparentOutput){const f=await oi(l,"generated");i.push(f.id),Xt(f.id,l);try{c=e.params.output_format==="webp"?await t0(l,void 0,"webp",e.params.output_compression):await t0(l),o.push(f.id)}catch(d){console.warn("透明背景后处理失败,已回退为原始输出",d),r.push(f.id),n.push(l),a.push(f),o.push("");continue}}const u=await oi(c,"generated");i.push(u.id),Xt(u.id,c),r.push(u.id),n.push(c),a.push(u)}return{outputIds:r,outputDataUrls:n,outputImageSizes:a,transparentOriginalImageIds:o.length?o:void 0}}catch(l){throw await ns(i),l}}async function ns(e){const t=Array.from(new Set(Array.from(e).filter(Boolean)));if(t.length===0)return;const{tasks:r,inputImages:n,galleryInputDraft:a,privacyMode:o}=w.getState(),i=new Set(hb(o));for(const l of r)pg(i,l);$j(i),zj(i,a);for(const l of n)i.add(l.id);for(const l of t)i.has(l)||await vb(l)}async function Oo(e,t,r){try{const n=await Qn(t,"generated");Xt(n,t);const a=w.getState().tasks.find(i=>i.id===e);if(!a||a.status==="done"||r&&ur.get(e)!==r){await ns([n]);return}const o=a.streamPartialImageIds||[];if(o.includes(n))return;Rt(e,{streamPartialImageIds:[...o,n]})}catch(n){console.error(n)}}async function Wj(e){const t=[];for(const r of e){const n=await kt(r);n&&t.push(n)}return t}function Ab(e){const t=new Map,r=new Set;for(const o of e){if(o.sourceMode!=="agent"||!o.agentConversationId||!o.agentRoundId)continue;const i=Vn(o.agentConversationId,o.agentRoundId);t.set(i,[...t.get(i)??[],o]),r.add(o.agentConversationId)}if(t.size===0)return{updatedTasks:[],updatedConversations:[]};const n=[],a=[];return w.setState(o=>{const i=new Map;for(const d of[...o.tasks,...e]){if(!d.agentConversationId||!d.agentRoundId)continue;const g=Vn(d.agentConversationId,d.agentRoundId);t.has(g)&&i.set(g,[...i.get(g)??[],d])}const l=new Map;let c=!1;const u=o.agentConversations.map(d=>{if(!r.has(d.id))return d;let g=!1;const m=d.rounds.map(b=>{var I;const h=Vn(d.id,b.id),y=t.get(h);if(!y||(l.set(h,b),!((I=b.responseOutput)!=null&&I.length)))return b;const v=Yo(b,b.responseOutput,y,i.get(h)??y);return v===b.responseOutput?b:(g=!0,{...b,responseOutput:v})});if(!g)return d;c=!0;const x={...d,rounds:m};return a.push(x),x}),f=o.tasks.map(d=>{if(!d.agentConversationId||!d.agentRoundId)return d;const g=Vn(d.agentConversationId,d.agentRoundId),m=t.get(g);if(!m)return d;const x=l.get(g);if(!x)return d;const b=u2(d,x,m,i.get(g)??m);return b.rawResponsePayload===d.rawResponsePayload?d:(n.push(b),b)});return!c&&n.length===0?o:{...c?{agentConversations:u}:{},...n.length>0?{tasks:f}:{}}}),{updatedTasks:n,updatedConversations:a}}async function Pb(e,t){const r=t.updatedTasks.map(mg),n=t.updatedConversations.map(xb);try{await Dk(e,r,n)}catch(a){console.warn("原子清理任务关联数据失败,改用逐项持久化",a),await Promise.all([...e.map(o=>_k(o)),...r.map(o=>bp(o)),...n.map(o=>Bk(o))])}}function Hj(e,t,r){ar(e,n=>({...n,updatedAt:Date.now(),rounds:n.rounds.map(a=>{if(a.id!==t)return a;const o=a.responseOutput??[],i=qf(o),l=r.filter(c=>c.call_id&&!i.has(c.call_id));return l.length>0?{...a,responseOutput:[...o,...l]}:a})}))}async function Id(e){var a;const r=w.getState().tasks.find(o=>o.id===e);if(!(r!=null&&r.agentConversationId)||!r.agentRoundId)return;const n=Vn(r.agentConversationId,r.agentRoundId);if(!(ta.has(n)||Ul.has(n))){Ul.add(n);try{const o=w.getState(),i=o.agentConversations.find(k=>k.id===r.agentConversationId),l=i==null?void 0:i.rounds.find(k=>k.id===r.agentRoundId);if(!i||!l||l.status==="done"||l.error===nn)return;const c=k=>{ar(i.id,j=>({...j,updatedAt:Date.now(),rounds:j.rounds.map(A=>A.id===l.id?{...A,status:"error",error:k,finishedAt:Date.now()}:A)})),Ju(i.id)||ks("Agent 回复失败","请回到应用查看详情。","task-failure")},u=m2(l,o.tasks);if(!u)return;Hj(i.id,l.id,u.additions);const f=w.getState(),d=f.agentConversations.find(k=>k.id===i.id),g=d==null?void 0:d.rounds.find(k=>k.id===l.id);if(!d||!g)return;if(!u.allSuccessful){c(p2(g,f.tasks));return}const m=Me(f.settings),x=vd(m);if(x){c(`无法继续恢复任务:${x.message}`);return}const b=Bi(m),h=Ui(m);if(!b||!h){c("Agent API 配置不存在,无法继续恢复任务。");return}const y=f.tasks.filter(k=>k.agentRoundId===l.id),v=((a=y.find(k=>k.params))==null?void 0:a.params)??Mn(f.params,kn(m,h),{hasInputImages:l.inputImageIds.length>0}),I=Number.isFinite(m.agentMaxToolRounds)?Math.max(1,Math.trunc(m.agentMaxToolRounds)):Jn,S=h2(g.responseOutput??[],y);ar(i.id,k=>({...k,updatedAt:Date.now(),rounds:k.rounds.map(j=>j.id===l.id?{...j,status:"running",error:null,finishedAt:null}:j)})),Nc(i.id,l.id,v,kn(m,b),b,h,{responseOutput:g.responseOutput??[],recoveredTaskIds:u.recoveredTaskIds,toolCallsUsed:S})}finally{Ul.delete(n)}}}async function Yj(){var te;const e=w.getState(),{settings:t,prompt:r,inputImages:n,maskDraft:a,params:o,showToast:i}=e;if(e.batchProgress){i("画廊批量任务进行中,请等待完成或回到画廊停止后再提交","error");return}const l=Me(t),c=vd(l);if(c){i(`请先完善 Agent API 配置:${c.message}`,"error"),e.setShowSettings(!0,l.agentApiConfigMode==="off"?"api":"agent");return}const u=Bi(l),f=Ui(l),d=r.trim();if(!d){i("请输入消息","error");return}const g=Lj();if(g.rounds.some(P=>P.status==="running")){i("请等待生成完成,或先停止生成","info");return}let m=n,x=null,b=null;if(a)try{m=Yp(n,a.targetImageId),await Kp(a.maskDataUrl,m[0].dataUrl),x=await Qn(a.maskDataUrl,"mask"),Xt(x,a.maskDataUrl),b=a.targetImageId}catch(P){n.some(B=>B.id===a.targetImageId)||e.clearMaskDraft(),i(P instanceof Error?P.message:String(P),"error");return}const h=gn(m.map(P=>P.id));for(const P of m)await Qn(P.dataUrl);const y=kn(l,u),v=kn(l,f),I=Date.now(),S=e.agentEditingRoundId?g.rounds.find(P=>P.id===e.agentEditingRoundId)??null:null,k=S!=null&&S.assistantMessageId?g.messages.find(P=>P.id===S.assistantMessageId)??null:g.messages.find(P=>P.roundId===(S==null?void 0:S.id)&&P.role==="assistant")??null,j=!!k,A=!!((S==null?void 0:S.status)==="error"&&(k!=null&&k.content.startsWith("请求失败:"))),N=S?g.rounds.some(P=>(P.parentRoundId??null)===S.id):!1,C=!!(S&&!N&&(!j||A)),T=C&&S?S.id:fr(),R=C&&S?S.userMessageId:fr(),U=fa(g),W=((te=U[U.length-1])==null?void 0:te.id)??null,F=S?S.parentRoundId??null:W,_=F?ys(g,F):[],O={...Mn(o,v,{hasInputImages:h.length>0}),n:Qr.n,transparent_output:!1},J={id:T,index:C&&S?S.index:_.length+1,parentRoundId:F,...A&&k?{assistantMessageId:k.id}:{},userMessageId:R,prompt:d,inputImageIds:h,maskTargetImageId:b,maskImageId:x,outputTaskIds:[],status:"running",error:null,createdAt:I,finishedAt:null},H={id:R,role:"user",content:d,roundId:T,inputImageIds:h,maskTargetImageId:b,maskImageId:x,createdAt:I};let K=null;ar(g.id,P=>{const B=P.rounds.length===0?mj(gr(d),P.title):P.title;P.rounds.length===0&&(K=B);const $=C?P.messages.some(Q=>Q.id===R)?P.messages.map(Q=>Q.id===R?H:A&&Q.id===(k==null?void 0:k.id)?{...Q,content:"",outputTaskIds:[]}:Q):[...P.messages,H]:[...P.messages,H];return{...P,title:B,activeRoundId:T,updatedAt:I,rounds:C?P.rounds.map(Q=>Q.id===T?J:Q):[...P.rounds,J],messages:$}}),e.setPrompt(""),e.clearInputImages(),e.clearMaskDraft(),e.setAgentEditingRoundId(null),K&&Uj(g.id,gr(d),h,y,u,K),Nc(g.id,T,O,y,u,f)}async function Vj(e,t){var j;const r=w.getState(),{settings:n,params:a,showToast:o}=r,i=Me(n),l=vd(i);if(l){o(`请先完善 Agent API 配置:${l.message}`,"error"),r.setShowSettings(!0,i.agentApiConfigMode==="off"?"api":"agent");return}const c=Bi(i),u=Ui(i),f=r.agentConversations.find(A=>A.id===e),d=(f==null?void 0:f.rounds.find(A=>A.id===t))??null,g=d?(f==null?void 0:f.messages.find(A=>A.id===d.userMessageId))??null:null;if(!f||!d||!g){o("找不到要重新生成的 Agent 消息","error");return}if(f.rounds.some(A=>A.status==="running")){o("请等待生成完成,或先停止生成","info");return}const m=gn(d.inputImageIds),x=kn(i,c),b=kn(i,u),h={...Mn(a,b,{hasInputImages:m.length>0}),n:Qr.n,transparent_output:!1},y=Date.now();if(d.status==="error"){const A=d.assistantMessageId??((j=f.messages.find(N=>N.roundId===d.id&&N.role==="assistant"))==null?void 0:j.id);ar(e,N=>({...N,activeRoundId:d.id,updatedAt:y,rounds:N.rounds.map(C=>C.id===d.id?{...C,outputTaskIds:[],responseId:void 0,responseOutput:void 0,status:"running",error:null,finishedAt:null}:C),messages:A?N.messages.map(C=>C.id===A?{...C,content:"",outputTaskIds:[]}:C):N.messages})),r.setAgentEditingRoundId(null),Nc(e,d.id,h,x,c,u);return}const v=fr(),I=fr(),S={id:v,index:d.index,parentRoundId:d.parentRoundId??null,userMessageId:I,prompt:d.prompt||g.content.trim(),inputImageIds:m,maskTargetImageId:d.maskTargetImageId??g.maskTargetImageId??null,maskImageId:d.maskImageId??g.maskImageId??null,outputTaskIds:[],status:"running",error:null,createdAt:y,finishedAt:null},k={id:I,role:"user",content:g.content,roundId:v,inputImageIds:m,maskTargetImageId:d.maskTargetImageId??g.maskTargetImageId??null,maskImageId:d.maskImageId??g.maskImageId??null,createdAt:y};ar(e,A=>({...A,activeRoundId:v,updatedAt:y,rounds:[...A.rounds,S],messages:[...A.messages,k]})),r.setAgentEditingRoundId(null),Nc(e,v,h,x,c,u)}async function Nc(e,t,r,n,a,o,i){var f;const l=Date.now(),c=new AbortController,u=Vn(e,t);ta.set(u,c);try{const d=w.getState(),g=d.agentConversations.find(ne=>ne.id===e);if(!g)return;const m=g.rounds.find(ne=>ne.id===t),x=m?g.messages.find(ne=>ne.id===m.userMessageId):null;if(!m||!x)return;const b=m.maskImageId?await kt(m.maskImageId):void 0;if(m.maskImageId&&!b)throw new Error("遮罩图片已不存在");const h=await w2({conversation:g,currentRound:m,tasks:d.tasks,loadImage:kt});if(c.signal.aborted)throw us();const y=m.assistantMessageId?g.messages.find(ne=>ne.id===m.assistantMessageId)??null:g.messages.find(ne=>ne.roundId===t&&ne.role==="assistant")??null,v=(y==null?void 0:y.id)??fr(),I=i?(y==null?void 0:y.content.trim())??"":"",S=a.streamImages===!0,k=kn(n,o),j=Mn(r,k,{hasInputImages:m.inputImageIds.length>0}),A=i?[...m.outputTaskIds]:[],N=new Map,C=new Map,T=()=>{const ne=g0(e,t,c),ge=new Set(ne.map(fe=>fe.id)),xe=new Set(w.getState().tasks.map(fe=>fe.id));for(const[fe,be]of N){const Z=C.get(fe);Z&&!xe.has(be)&&!ge.has(be)&&ne.push(Z)}return ne},R=()=>{var ne;return(ne=w.getState().agentConversations.find(ge=>ge.id===e))==null?void 0:ne.rounds.find(ge=>ge.id===t)},U=ne=>{A.includes(ne)||(A.push(ne),ar(e,ge=>({...ge,updatedAt:Date.now(),rounds:ge.rounds.map(xe=>xe.id===t?{...xe,outputTaskIds:xe.outputTaskIds.includes(ne)?xe.outputTaskIds:[...xe.outputTaskIds,ne]}:xe),messages:ge.messages.map(xe=>xe.id===v?{...xe,outputTaskIds:[...new Set([...xe.outputTaskIds??[],ne])]}:xe)})))},W=async(ne,ge="",xe=m.inputImageIds??[],fe={})=>{const be=N.get(ne);if(be)return be;const Z=w.getState().tasks.find(he=>he.agentToolCallId===ne);if(Z)return N.set(ne,Z.id),C.set(ne,Z),U(Z.id),Z.id;const de={id:fr(),prompt:ge,params:fe.taskParams??{...j,n:1},apiProvider:o.provider,apiProfileId:o.id,apiProfileName:o.name,apiMode:o.apiMode,apiModel:o.model,inputImageIds:xe,maskTargetImageId:fe.maskTargetImageId!==void 0?fe.maskTargetImageId:m.maskTargetImageId??null,maskImageId:fe.maskImageId!==void 0?fe.maskImageId:m.maskImageId??null,outputImages:[],status:"running",error:null,createdAt:fe.createdAt??Date.now(),finishedAt:null,elapsed:null,sourceMode:"agent",agentConversationId:e,agentRoundId:t,agentMessageId:v,agentToolCallId:ne,...fe.agentBatchCallId?{agentBatchCallId:fe.agentBatchCallId}:{},...fe.agentBatchItemId?{agentBatchItemId:fe.agentBatchItemId}:{}};return N.set(ne,de.id),C.set(ne,de),w.getState().setTasks([de,...w.getState().tasks]),U(de.id),await wn(de),de.id},F=async(ne,ge)=>{const xe=ne.toolCallId??fr(),fe=await W(xe),be=w.getState().tasks.find(pe=>pe.id===fe);if((be==null?void 0:be.status)==="done"&&be.outputImages.length>0)return{taskId:fe,committed:!0};const Z=await oi(ne.dataUrl,"generated");Xt(Z.id,ne.dataUrl);const de=w.getState().tasks.find(pe=>pe.id===fe);if(!de)return await ns([Z.id]),{taskId:fe,committed:!1};const he=c0(ne.actualParams,Z);return Rt(fe,{prompt:ne.revisedPrompt??de.prompt,outputImages:[Z.id],actualParams:he,actualParamsByImage:{[Z.id]:he},revisedPromptByImage:ne.revisedPrompt?{[Z.id]:ne.revisedPrompt}:void 0,rawResponsePayload:ge,...xd(de,Date.now()),agentToolAction:ne.action}),w.getState().setTaskStreamPreview(fe),{taskId:fe,committed:!0}},_=(ne,ge,xe)=>{const fe=N.get(ne);if(!fe)return;const be=w.getState().tasks.find(Z=>Z.id===fe);!be||be.status!=="running"||(w.getState().setTaskStreamPreview(fe),Rt(fe,{...Wr(be,ge,Date.now()),rawResponsePayload:xe,falRecoverable:!1,customRecoverable:!1}))},O=(ne,ge)=>{const xe=N.get(ne);if(!xe||!Sc(ge))return!1;const fe=w.getState().tasks.find(be=>be.id===xe);return!fe||fe.status!=="running"?!1:fe.apiProvider==="fal"&&fe.falRequestId&&fe.falEndpoint?(w.getState().setTaskStreamPreview(xe),Rt(xe,{...Wr(fe,"与 fal.ai 的连接已断开,之后会继续查询任务结果。",Date.now()),falRecoverable:!0}),Ii(xe),!0):fe.customTaskId?(w.getState().setTaskStreamPreview(xe),Rt(xe,{...Wr(fe,"与自定义异步任务的连接已断开,之后会继续查询任务结果。",Date.now()),customRecoverable:!0}),kd(xe),!0):!1};S&&ar(e,ne=>({...ne,updatedAt:Date.now(),rounds:ne.rounds.map(ge=>ge.id===t?{...ge,assistantMessageId:v}:ge),messages:ne.messages.some(ge=>ge.id===v)?ne.messages.map(ge=>ge.id===v?i?{...ge,outputTaskIds:[...new Set([...ge.outputTaskIds??[],...m.outputTaskIds])]}:{...ge,content:"",outputTaskIds:[]}:ge):[...ne.messages,{id:v,role:"assistant",content:"",roundId:t,createdAt:Date.now()}]}));const J=Number.isFinite(n.agentMaxToolRounds)?Math.max(1,Math.trunc(n.agentMaxToolRounds)):Jn;let H=(i==null?void 0:i.responseOutput)??[],K=I;const te=I?[I]:[];let P=m.responseId,B=(i==null?void 0:i.toolCallsUsed)??0,$=h;if(i){const ne=w.getState();$=await e0({baseInput:h,currentRound:m,tasks:ne.tasks,currentRoundOutput:H,batchTaskIds:i.recoveredTaskIds,toolCallsUsed:B,maxToolCalls:J,loadImage:kt})}let Q=i?B>=J:!1,L=!1;const G=async ne=>{const ge=[],xe=[],fe=[],be=w.getState().imageSourceUrls;for(const Z of ne){const de=w.getState().agentConversations.find(he=>he.id===e);if(de)for(const he of ys(de,t)){for(let Be=0;Be<he.inputImageIds.length;Be++)if(ic(he,Be)===Z){const Ue=he.inputImageIds[Be],lt=await kt(Ue);lt&&(ge.push(lt),fe.push(be[Ue]??null)),xe.push(Ue)}const pe=cd(he,w.getState().tasks);for(let Be=0;Be<pe.length;Be++)if(Ja(he,Be)===Z){const Ue=pe[Be];if(!Ue)continue;const lt=await kt(Ue);lt&&(ge.push(lt),fe.push(be[Ue]??null)),xe.push(Ue)}}}return{dataUrls:ge,imageIds:xe,sourceUrls:fe}},se=ne=>{try{const ge=JSON.parse(ne),xe=typeof ge.prompt=="string"?ge.prompt.trim():"";return xe?{id:typeof ge.id=="string"&&ge.id.trim()?ge.id.trim():"image",prompt:xe}:null}catch{return null}},Y=async ne=>{var fe,be,Z,de;const ge=await ix({settings:k,prompt:$i(ne.prompt,ne.referenceImageDataUrls.length),params:ne.taskParams,inputImageDataUrls:ne.referenceImageDataUrls,inputImageUrls:ne.referenceImageSourceUrls,skipCodexCliSizePrompt:!0,onPartialImage:ne.onPartialImage?he=>{var pe;(pe=ne.onPartialImage)==null||pe.call(ne,{image:he.image,partialImageIndex:he.partialImageIndex??he.requestIndex})}:void 0,onFalRequestEnqueued:he=>{Rt(ne.taskId,{falRequestId:he.requestId,falEndpoint:he.endpoint,falRecoverable:!1})},onCustomTaskEnqueued:he=>{Rt(ne.taskId,{customTaskId:he.taskId,customRecoverable:!1})}});if(ne.signal.aborted)throw us();const xe=ge.images[0];return{image:xe?{dataUrl:xe,actualParams:((fe=ge.actualParamsList)==null?void 0:fe[0])??ge.actualParams,revisedPrompt:((be=ge.revisedPrompts)==null?void 0:be[0])??ne.prompt}:null,error:((de=(Z=ge.failedRequests)==null?void 0:Z[0])==null?void 0:de.error)??(xe?null:"接口未返回图片数据"),rawResponsePayload:JSON.stringify({imageCount:ge.images.length,actualParams:ge.actualParams,actualParamsList:ge.actualParamsList,revisedPrompts:ge.revisedPrompts,rawImageUrls:ge.rawImageUrls,failedRequests:ge.failedRequests},null,2)}},le=async ne=>{const ge=ne.call_id??"",xe=se(ne.arguments??"");if(!xe)return JSON.stringify({error:"Invalid or empty image arguments"});const fe=gn(wl(xe.prompt)),be=await G(fe),Z=ge||fr(),de={...Mn(j,k,{hasInputImages:be.dataUrls.length>0}),n:1},he=await W(Z,xe.prompt,be.imageIds,{createdAt:Date.now(),taskParams:de,maskTargetImageId:null,maskImageId:null});try{const pe=await Y({taskId:he,prompt:xe.prompt,referenceImageDataUrls:be.dataUrls,referenceImageSourceUrls:be.sourceUrls,taskParams:de,signal:c.signal,onPartialImage:async({image:Be,partialImageIndex:Oe})=>{if(c.signal.aborted)return;const Ue=N.get(Z);Ue&&(w.getState().setTaskStreamPreview(Ue,Be,Oe),(Oe===0||Oe==null)&&Oo(Ue,Be))}});if(c.signal.aborted)throw us();return pe.image?(await F({...pe.image,toolCallId:Z},pe.rawResponsePayload)).committed?(B+=1,JSON.stringify({id:xe.id,status:"done"})):null:(_(Z,pe.error,pe.rawResponsePayload),JSON.stringify({id:xe.id,status:"error",error:pe.error}))}catch(pe){const Be=pe instanceof Error?pe.message:String(pe);if(c.signal.aborted)throw us();if(O(Z,pe))throw m0();return _(Z,Be),JSON.stringify({id:xe.id,status:"error",error:Be})}},ie=async ne=>{const ge=ne.call_id??"",xe=ne.arguments??"",fe=ld(xe);if(!fe||fe.length===0)return JSON.stringify({error:"Invalid or empty batch arguments"});const be=[];for(const Oe of fe){const Ue=gn(wl(Oe.prompt)),lt=await G(Ue),ut=fr(),Ve=n.agentApiConfigMode==="hybrid"?{...Mn(j,k,{hasInputImages:lt.dataUrls.length>0}),n:1}:{...j,n:1};await W(ut,Oe.prompt,lt.imageIds,{createdAt:Date.now(),taskParams:Ve,maskTargetImageId:null,maskImageId:null,...ge?{agentBatchCallId:ge}:{},agentBatchItemId:Oe.id}),be.push({item:Oe,batchToolCallId:ut,references:lt,referenceIds:Ue,taskParams:Ve})}const Z=be.map(async({item:Oe,batchToolCallId:Ue,references:lt,referenceIds:ut,taskParams:Ve})=>{let He=!1;const vt=n.agentApiConfigMode==="hybrid"?{batchItemId:Oe.id,...await Y({taskId:N.get(Ue),prompt:Oe.prompt,referenceImageDataUrls:lt.dataUrls,referenceImageSourceUrls:lt.sourceUrls,taskParams:Ve,signal:c.signal,onPartialImage:async({image:rt,partialImageIndex:V})=>{if(c.signal.aborted)return;const X=N.get(Ue);X&&(w.getState().setTaskStreamPreview(X,rt,V),(V===0||V==null)&&Oo(X,rt))}})}:await JI({profile:o,params:Ve,batchItemId:Oe.id,prompt:Oe.prompt,referenceImageDataUrls:lt.dataUrls,referenceIds:ut,allowPromptRewrite:n.allowPromptRewrite,signal:c.signal,onImageToolStarted:S?async()=>{c.signal.aborted}:void 0,onPartialImage:S?async({image:rt,partialImageIndex:V})=>{if(c.signal.aborted)return;const X=N.get(Ue);X&&(w.getState().setTaskStreamPreview(X,rt,V),(V===0||V==null)&&Oo(X,rt))}:void 0,onImageToolCompleted:S?async rt=>{c.signal.aborted||(He=(await F({...rt,toolCallId:Ue})).committed)}:void 0});if(c.signal.aborted)throw us();vt.image&&(n.agentApiConfigMode==="hybrid"||!S)&&(He=(await F({...vt.image,toolCallId:Ue},vt.rawResponsePayload)).committed);const ct=w.getState().tasks.find(rt=>rt.id===N.get(Ue));return{...vt,committed:He||(ct==null?void 0:ct.status)==="done"&&ct.outputImages.length>0}}),de=await Promise.allSettled(Z);if(c.signal.aborted)throw us();const he=[];let pe=!1;for(let Oe=0;Oe<fe.length;Oe++){const Ue=de[Oe],lt=fe[Oe],ut=N.get(be[Oe].batchToolCallId);if(!(!ut||!w.getState().tasks.some(Ve=>Ve.id===ut)))if(Ue.status==="fulfilled"){const Ve=Ue.value;if(Ve.image&&!Ve.committed)continue;Ve.image||_(be[Oe].batchToolCallId,Ve.error,Ve.rawResponsePayload),he.push({id:Ve.batchItemId,status:Ve.image?"done":"error",...Ve.error?{error:Ve.error}:{}})}else{const Ve=Ue.reason instanceof Error?Ue.reason.message:String(Ue.reason);if(h0(Ue.reason)||O(be[Oe].batchToolCallId,Ue.reason)){pe=!0;continue}_(be[Oe].batchToolCallId,Ve),he.push({id:lt.id,status:"error",error:Ve})}}if(pe)throw m0();const Be=he.filter(Oe=>Oe.status==="done").length;return B+=Be,JSON.stringify({images:he})};for(;;){if(c.signal.aborted)throw us();if(Q)break;const ne=K;let ge=[];const xe=await XI({settings:n,profile:a,imageProfile:o,params:j,input:$,maskDataUrl:b,signal:c.signal,onTextDelta:S?ae=>{c.signal.aborted||(L&&ae&&K.trim()&&(K+=`
|
|
56
|
+
|
|
57
|
+
`,Gd(e,v,`
|
|
58
|
+
|
|
59
|
+
`)),L=!1,K+=ae,Gd(e,v,ae))}:void 0,onOutputItems:S?ae=>{c.signal.aborted||(ge=Zm(ae),ar(e,_e=>({..._e,rounds:_e.rounds.map(Ye=>Ye.id===t?{...Ye,responseOutput:Yd(H,ge)}:Ye)})))}:void 0,onImageToolStarted:S?async({toolCallId:ae})=>{c.signal.aborted||await W(ae)}:void 0,onImagePartialImage:S?async({toolCallId:ae,image:_e,partialImageIndex:Ye})=>{if(c.signal.aborted)return;const wt=await W(ae);c.signal.aborted||(w.getState().setTaskStreamPreview(wt,_e,Ye),(Ye===0||Ye==null)&&Oo(wt,_e))}:void 0,onImageToolCompleted:S?async ae=>{c.signal.aborted||await F(ae)}:void 0,onImageToolFailed:S?async({toolCallId:ae,error:_e})=>{c.signal.aborted||(await W(ae),!c.signal.aborted&&_(ae,_e))}:void 0});if(c.signal.aborted)throw us();P=xe.responseId??P,ge=Zm(ge.length?ge:xe.outputItems??[]);const fe=T(),be=R();be&&(ge=Yo(be,ge,fe,[...w.getState().tasks,...fe])),H=Yd(H,ge),ar(e,ae=>({...ae,updatedAt:Date.now(),rounds:ae.rounds.map(_e=>_e.id===t?{..._e,responseId:P,responseOutput:H}:_e)}));const Z=xe.text.trim();if(Z&&K===ne){const ae=K?`
|
|
60
|
+
|
|
61
|
+
${Z}`:Z;K+=ae,S&&Gd(e,v,ae)}const de=K.slice(ne.length).trim();de&&te.push(de);for(const ae of xe.images){if(ae.toolCallId&&N.has(ae.toolCallId)){const tt=await F(ae,xe.rawResponsePayload);if(!tt.committed)continue;const Pt=tt.taskId,Ct=gn(wl(ae.revisedPrompt??""));if(Ct.length>0){const Ht=await G(Ct);if(Ht.imageIds.length>0){const Dt=w.getState().tasks.find(Tt=>Tt.id===Pt);if(Dt){const Tt=gn([...Dt.inputImageIds,...Ht.imageIds]);Tt.length!==Dt.inputImageIds.length&&Rt(Pt,{inputImageIds:Tt})}}}continue}const _e=gn(wl(ae.revisedPrompt??"")),Ye=await G(_e),wt=await oi(ae.dataUrl,"generated");Xt(wt.id,ae.dataUrl);const xt=c0(ae.actualParams,wt),qe={id:fr(),prompt:ae.revisedPrompt??(m==null?void 0:m.prompt)??x.content,params:j,apiProvider:o.provider,apiProfileId:o.id,apiProfileName:o.name,apiMode:o.apiMode,apiModel:o.model,inputImageIds:gn([...(m==null?void 0:m.inputImageIds)??[],...Ye.imageIds]),maskTargetImageId:(m==null?void 0:m.maskTargetImageId)??null,maskImageId:(m==null?void 0:m.maskImageId)??null,outputImages:[wt.id],actualParams:xt,actualParamsByImage:{[wt.id]:xt},revisedPromptByImage:ae.revisedPrompt?{[wt.id]:ae.revisedPrompt}:void 0,rawResponsePayload:xe.rawResponsePayload,status:"done",error:null,createdAt:l,finishedAt:Date.now(),elapsed:Date.now()-l,sourceMode:"agent",agentConversationId:e,agentRoundId:t,agentMessageId:v,agentToolCallId:ae.toolCallId,agentToolAction:ae.action};w.getState().setTasks([qe,...w.getState().tasks]),U(qe.id),await wn(qe)}if(xe.rawResponsePayload&&A.length>0)for(const ae of A){const _e=w.getState().tasks.find(Ye=>Ye.id===ae);_e&&!_e.rawResponsePayload&&Rt(ae,{rawResponsePayload:xe.rawResponsePayload})}const he=ge.filter(ae=>ae.type==="function_call"&&ae.name==="generate_image"),pe=ge.filter(ae=>ae.type==="function_call"&&ae.name==="generate_image_batch"),Be=ge.filter(ae=>ae.type==="function_call"&&ae.name==="continue_generation"),Oe=mx(ge);B+=Oe;const Ue=[];if(he.length>0)for(const ae of he){const _e=await le(ae);_e!=null&&Ue.push({type:"function_call_output",call_id:ae.call_id,output:_e})}if(pe.length>0)for(const ae of pe){const _e=await ie(ae);Ue.push({type:"function_call_output",call_id:ae.call_id,output:_e})}for(const ae of Be)Ue.push({type:"function_call_output",call_id:ae.call_id,output:JSON.stringify({status:"continued"})});const lt=T(),ut=w.getState().agentConversations.find(ae=>ae.id===e),Ve=ut==null?void 0:ut.rounds.find(ae=>ae.id===t),He=(Ve==null?void 0:Ve.responseOutput)??H,vt=Yd(He,Ue),ct=Ve?Yo(Ve,vt,lt,[...w.getState().tasks,...lt]):vt,rt=new Set(Ue.map(ae=>ae.call_id).filter(Boolean)),V=ct.filter(ae=>ae.type==="function_call_output"&&ae.call_id&&rt.has(ae.call_id));if(V.length===0){H=ct,ar(e,ae=>({...ae,updatedAt:Date.now(),rounds:ae.rounds.map(_e=>_e.id===t?{..._e,responseId:P,responseOutput:H}:_e)}));break}if(ar(e,ae=>({...ae,updatedAt:Date.now(),rounds:ae.rounds.map(_e=>_e.id===t?{..._e,responseId:P,responseOutput:ct}:_e)})),B>=J){Q=!0;break}const X=w.getState(),me=X.agentConversations.find(ae=>ae.id===e),ve=me==null?void 0:me.rounds.find(ae=>ae.id===t);if(!ve)break;$=await e0({baseInput:h,currentRound:ve,tasks:X.tasks,currentRoundOutput:ct,functionCallOutputs:V,batchTaskIds:A,toolCallsUsed:B,maxToolCalls:J,loadImage:kt}),H=ct,L=!0}p0(e,t,n.agentApiConfigMode==="hybrid"?"自定义图像生成工具未返回图片":"内置 image_generation 工具未返回图片",void 0,ne=>!!(ne.agentToolCallId&&!ne.agentBatchCallId));const D=w.getState().tasks,ue=new Set(D.map(ne=>ne.id)),ke=A.filter(ne=>ue.has(ne)),we=ke.flatMap(ne=>{var ge;return((ge=D.find(xe=>xe.id===ne))==null?void 0:ge.outputImages)??[]}),We=w.getState().agentConversations.find(ne=>ne.id===e),Ne=We==null?void 0:We.rounds.find(ne=>ne.id===t),Fe=T(),Ee=Ne?Yo(Ne,H,Fe,[...D,...Fe]):H,Ge=Q?`已达到最大工具调用次数(${J}),已停止自动续跑。`:"",Xe=te.join(`
|
|
62
|
+
|
|
63
|
+
`).trim(),ht=[Xe,Ge].filter(Boolean).join(Xe?`
|
|
64
|
+
|
|
65
|
+
`:"")||(ke.length>0||we.length>0?"图像已生成。":""),Pe={id:v,role:"assistant",content:ht,roundId:t,outputTaskIds:ke,createdAt:Date.now()};ar(e,ne=>({...ne,updatedAt:Date.now(),rounds:ne.rounds.map(ge=>ge.id===t?{...ge,assistantMessageId:v,outputTaskIds:ke,responseId:P,responseOutput:Ee,status:"done",error:null,finishedAt:Date.now()}:ge),messages:ne.messages.some(ge=>ge.id===v)?ne.messages.map(ge=>ge.id===v?Pe:ge):[...ne.messages,Pe]})),Ju(e)||(w.getState().showToast(we.length>0?"Agent 已生成图片":"Agent 已回复","success"),ks(we.length>0?"Agent 已生成图片":"Agent 已回复",we.length>0?`Agent 回复已结束,共生成 ${we.length} 张图片。`:"Agent 回复已结束。"))}catch(d){if(c.signal.aborted){Zu(e,t)&&w.getState().showToast("已停止生成","info");return}if(h0(d))return;let g=d instanceof Error?d.message:String(d);const m=a.apiProxy??n.apiProxy,x=Sb(d,l,m,a);x&&!g.includes(Ea)&&(g+=`
|
|
66
|
+
${x}`),p0(e,t,g,wd(d).rawResponsePayload),ar(e,b=>{const h=b.rounds.find(I=>I.id===t),y=h!=null&&h.assistantMessageId?b.messages.find(I=>I.id===h.assistantMessageId):b.messages.find(I=>I.roundId===t&&I.role==="assistant"),v=`请求失败:${g}`;return{...b,title:b.rounds.length===1&&b.rounds[0].id===t?"新对话":b.title,updatedAt:Date.now(),rounds:b.rounds.map(I=>I.id===t?{...I,...y?{assistantMessageId:y.id}:{},status:"error",error:g,finishedAt:Date.now()}:I),messages:y?b.messages.map(I=>I.id===y.id?{...I,content:v}:I):[...b.messages,{id:fr(),role:"assistant",content:v,roundId:t,createdAt:Date.now()}]}}),Ju(e)||(w.getState().showToast(`Agent 请求失败:${g}`,"error"),ks("Agent 回复失败","请回到应用查看详情。","task-failure"))}finally{ta.get(u)===c&&ta.delete(u);const d=g0(e,t,c);try{const g=Ab(d);(g.updatedTasks.length>0||g.updatedConversations.length>0)&&await Pb([],g)}catch(g){console.warn("清理已删除 Agent 任务的响应失败",g)}finally{for(const g of d)((f=kc.get(g.id))==null?void 0:f.controller)===c&&kc.delete(g.id)}}}async function Tb(e){var f,d,g,m;const{settings:t}=w.getState(),r=w.getState().tasks.find(x=>x.id===e);if(!r)return;const n=Symbol(e);ur.set(e,n);const a=wi(t,r);if(!a&&r.apiProfileId){Rt(e,{...Wr(r,"找不到此任务所使用的 API 配置。",Date.now()),falRecoverable:!1,customRecoverable:!1}),bi(r),ur.delete(e);return}const o=a??zt(t),i=kn(t,o),l=(a==null?void 0:a.provider)??r.apiProvider??o.provider;let c=r.falRequestId&&r.falEndpoint?{requestId:r.falRequestId,endpoint:r.falEndpoint}:null,u=r.customTaskId?{taskId:r.customTaskId}:null;l!=="fal"&&!Cb(i,l,r.inputImageIds.length>0)&&!wj(i,o,r.params,r.inputImageIds.length>0)&&vj(e,o.timeout,o);try{const x=[];for(const P of r.inputImageIds){const B=await kt(P);if(!B)throw new Error("输入图片已不存在");x.push(B)}let b;if(r.maskImageId&&(b=await kt(r.maskImageId),!b))throw new Error("遮罩图片已不存在");const h=r.transparentOutput&&r.transparentPrompt?r.transparentPrompt:r.prompt,y=await ix({settings:i,prompt:$i(h,x.length),params:r.params,nativeTransparentBackground:r.params.transparent_output&&!r.transparentOutput,inputImageDataUrls:x,inputImageUrls:r.inputImageIds.map(P=>w.getState().imageSourceUrls[P]??null),maskDataUrl:b,skipCodexCliSizePrompt:r.sourceMode==="agent",onFalRequestEnqueued:P=>{ur.get(e)===n&&(c=P,Rt(e,{falRequestId:P.requestId,falEndpoint:P.endpoint,falRecoverable:!1}))},onCustomTaskEnqueued:P=>{ur.get(e)===n&&(u=P,Rt(e,{customTaskId:P.taskId,customRecoverable:!1}))},onPartialImage:P=>{ur.get(e)===n&&(w.getState().setTaskStreamPreview(e,P.image,P.requestIndex),Oo(e,P.image,n))}}),v=w.getState().tasks.find(P=>P.id===e);if(ur.get(e)!==n)return;if(!v||v.status!=="running"){w.getState().setTaskStreamPreview(e);return}const{outputIds:I,outputDataUrls:S,outputImageSizes:k,transparentOriginalImageIds:j}=await xg(r,y.images),A=l!=="fal"&&l!=="openai"&&!!u,N=await hg(S,A?void 0:y.actualParamsList,k),C=zC(l,A,y.actualParams,N,I.length),T=l!=="fal"&&!A,R=cg(I,N),U=o.codexCli&&r.sourceMode!=="agent"?(f=y.revisedPrompts)==null?void 0:f.map(P=>P==null?P:sI(P,h,r.params.size)):y.revisedPrompts,W=T?WC(I,U):void 0,F=T&&(U==null?void 0:U.some(P=>(P==null?void 0:P.trim())&&P.trim()!==h.trim())),_=T&&(U==null?void 0:U.some(P=>P==null?void 0:P.trim()));ur.get(e)===n&&l==="openai"&&o.apiMode==="responses"&&!o.codexCli&&(F?Gu():_||Gu(!1,"接口没有返回官方 API 会返回的部分信息"));const O=w.getState().tasks.find(P=>P.id===e);if(ur.get(e)!==n||!O||O.status!=="running"){ur.get(e)===n&&w.getState().setTaskStreamPreview(e),await ns([...I,...j??[]]);return}const J=O.streamPartialImageIds||[];yi(e),w.getState().setTaskStreamPreview(e),Rt(e,{outputImages:I,transparentOriginalImages:j,outputErrors:(d=y.failedRequests)!=null&&d.length?y.failedRequests:void 0,streamPartialImageIds:void 0,rawImageUrls:(g=y.rawImageUrls)!=null&&g.length?y.rawImageUrls:void 0,actualParams:C,actualParamsByImage:R,revisedPromptByImage:W,...xd(r,Date.now()),falRecoverable:!1,customRecoverable:!1}),ns(J);const H=((m=y.failedRequests)==null?void 0:m.length)??0,K=H>0?`生成完成:成功 ${I.length} 张,失败 ${H} 张`:`生成完成,共 ${I.length} 张图片`;!ro.has(e)&&!eo(r)&&(w.getState().showToast(K,H>0?"error":"success"),vn(r)||ks("图像生成完成",`${K}。`));const te=w.getState().maskDraft;b&&te&&te.targetImageId===r.maskTargetImageId&&te.maskDataUrl===b&&w.getState().clearMaskDraft()}catch(x){if(ur.get(e)!==n)return;yi(e);const b=w.getState().tasks.find(v=>v.id===e);if(!b||b.status!=="running")return;w.getState().setTaskStreamPreview(e);const h=c??(b.falRequestId&&b.falEndpoint?{requestId:b.falRequestId,endpoint:b.falEndpoint}:null),y=u??(b.customTaskId?{taskId:b.customTaskId}:null);if(b.apiProvider==="fal"&&h&&Sc(x))Rt(e,{...Wr(r,"与 fal.ai 的连接已断开,之后会继续查询任务结果。",Date.now()),falRequestId:h.requestId,falEndpoint:h.endpoint,falRecoverable:!0}),Ii(e);else if(y&&Sc(x))Rt(e,{...Wr(r,"与自定义异步任务的连接已断开,之后会继续查询任务结果。",Date.now()),customTaskId:y.taskId,customRecoverable:!0}),kd(e);else{let v=x instanceof Error?x.message:String(x);const I=w.getState().settings,S=wi(I,b),k=(S==null?void 0:S.apiProxy)??I.apiProxy,j=zt(I),A=S??{provider:b.apiProvider??j.provider,apiMode:I.apiMode,streamImages:j.streamImages,streamPartialImages:j.streamPartialImages},N=Sb(x,b.startedAt??b.createdAt,k,A);N&&!v.includes(Ea)&&(v+=`
|
|
67
|
+
${N}`),Rt(e,{...Wr(r,v,Date.now()),...wd(x),falRecoverable:!1,customRecoverable:!1}),!ro.has(e)&&!eo(r)&&w.getState().setDetailTaskId(e),bi(r)}}finally{if(ur.get(e)===n&&ur.delete(e),!ur.has(e))for(const x of r.inputImageIds)jx(x)}}function Rt(e,t){const{tasks:r,setTasks:n,defaultFavoriteCollectionId:a}=w.getState(),o=r.map(l=>l.id===e?{...l,..._C(l,t,a)}:l),i=o.find(l=>l.id===e);n(o),uj(r,o,e),i&&wn(i)}function Mb(e){const t=ig(e);if(!t)return null;if(Array.from(t).length>60)return w.getState().showToast("收藏夹名称最多 60 个字符","error"),null;const r=w.getState(),n=r.favoriteCollections.find(i=>i.name===t);if(n)return n;const a=Date.now(),o={id:fr(),name:t,createdAt:a,updatedAt:a};return r.setFavoriteCollections([...r.favoriteCollections,o]),r.showToast(`已创建收藏夹「${t}」`,"success"),o}function bg(e,t){const r=ig(t);if(!r||e===or)return;if(Array.from(r).length>60){w.getState().showToast("收藏夹名称最多 60 个字符","error");return}const{favoriteCollections:n,setFavoriteCollections:a,showToast:o}=w.getState();a(n.map(i=>i.id===e?{...i,name:r,updatedAt:Date.now()}:i)),o("收藏夹名称已更新","success")}async function Kj(e,t){const r=Qa(t),n=Array.from(new Set(e)).filter(Boolean);if(!n.length)return;const{tasks:a,setTasks:o,clearSelection:i,showToast:l,defaultFavoriteCollectionId:c}=w.getState(),u=new Set(n),f=new Set,d=a.map(g=>!u.has(g.id)||RC(Vr(g,c),r)?g:(f.add(g.id),{...g,favoriteCollectionIds:r,isFavorite:r.length>0}));if(!f.size){i();return}o(d),await Promise.all(d.filter(g=>f.has(g.id)).map(g=>wn(g))),i(),l(r.length?"收藏夹已更新":"已取消收藏","success")}async function Cd(e,t=!1){const r=w.getState(),n=r.favoriteCollections.find(o=>o.id===e),a=LC({collections:r.favoriteCollections,defaultFavoriteCollectionId:r.defaultFavoriteCollectionId,activeFavoriteCollectionId:r.activeFavoriteCollectionId,selectedFavoriteCollectionIds:r.selectedFavoriteCollectionIds,selectedTaskIds:r.selectedTaskIds,tasks:r.tasks,collectionId:e,deleteTasks:t});if(!(!n||!a)){if(w.setState({favoriteCollections:a.collections,defaultFavoriteCollectionId:a.defaultFavoriteCollectionId,activeFavoriteCollectionId:a.activeFavoriteCollectionId,selectedFavoriteCollectionIds:a.selectedFavoriteCollectionIds,selectedTaskIds:a.selectedTaskIds}),a.updatedTasks.length){const o=new Map(a.updatedTasks.map(l=>[l.id,l])),i=w.getState().tasks.map(l=>{const c=o.get(l.id);return c?{...l,favoriteCollectionIds:c.favoriteCollectionIds,isFavorite:c.isFavorite}:l});w.getState().setTasks(i),await Promise.all(i.filter(l=>o.has(l.id)).map(l=>wn(l)))}a.taskIdsToDelete.length&&await Zi(a.taskIdsToDelete),w.getState().showToast(`已删除收藏夹「${n.name}」`,"success")}}async function Eb(e){const t=w.getState(),{settings:r,tasks:n}=t,a=n.find(b=>b.id===e.id);if(!a||a.status==="running"||a.falRecoverable||a.customRecoverable)return;const o=zt(r),i=Mn(a.params,r,{hasInputImages:a.inputImageIds.length>0}),c=(i.output_format==="png"||i.output_format==="webp")&&i.transparent_output?wx(i):{...i,transparent_output:!1},u=c.transparent_output&&o.transparentBackgroundMethod==="local"?kx(a.prompt.trim()):null,f=!vn(a)&&(r.retryMode==="overwriteAll"||r.retryMode==="overwriteFailed"&&a.status==="error"),d=f?a.id:fr(),g=Date.now(),m=!f&&r.saveTasksToActiveFavoriteCollection&&t.appMode==="gallery"?ob(t,Vr(a,t.defaultFavoriteCollectionId)):null,x={...f?a:{},...m,id:d,prompt:a.prompt,params:c,apiProvider:o.provider,apiProfileId:o.id,apiProfileName:o.name,apiMode:o.apiMode,apiModel:o.model,inputImageIds:[...a.inputImageIds],maskTargetImageId:a.maskTargetImageId??null,maskImageId:a.maskImageId??null,transparentOutput:u==null?void 0:u.transparentOutput,transparentPrompt:u==null?void 0:u.effectivePrompt,outputImages:[],outputErrors:void 0,transparentOriginalImages:void 0,actualParams:void 0,actualParamsByImage:void 0,revisedPromptByImage:void 0,rawImageUrls:void 0,rawResponsePayload:void 0,streamPartialImageIds:void 0,falRequestId:void 0,falEndpoint:void 0,falRecoverable:!1,customTaskId:void 0,customRecoverable:!1,status:"running",error:null,createdAt:f?a.createdAt:g,startedAt:g,finishedAt:null,elapsed:null};f&&(ur.delete(d),ro.delete(d),yi(d),ki(d),Ci(d),w.getState().setTaskStreamPreview(d)),w.getState().setTasks(f?n.map(b=>b.id===d?x:b):[x,...n]),await wn(x),f&&ns([...a.outputImages,...a.transparentOriginalImages??[],...a.streamPartialImageIds??[]]),Tb(d)}async function yg(e){const{settings:t,setPrompt:r,setParams:n,setInputImages:a,setMaskDraft:o,clearMaskDraft:i,showToast:l,setConfirmDialog:c,setReusedTaskApiProfile:u}=w.getState(),f=Me(t),d=zt(t),g=f.reuseTaskApiProfileTemporarily?wi(f,e):null,m=g&&(!Cn()||Cf(g.id))?g:null,x=!!(m&&m.id!==d.id),b=f.reuseTaskApiProfileTemporarily&&!m,h=(m==null?void 0:m.name)??jj(e),y=f.profiles.find(j=>j.id===d.id);!x&&e.apiModel&&y&&y.selectedModel!==e.apiModel&&ca(y.model).includes(e.apiModel)&&w.getState().setSettings({profiles:f.profiles.map(j=>j.id===d.id?{...j,selectedModel:e.apiModel}:j)});const v=Me(w.getState().settings),I=x&&m?kn(v,m):v;n(Mn(e.params,I,{hasInputImages:e.inputImageIds.length>0})),u(x&&m?m.id:null,b,h,x&&m?m.model:null),i();const S=[];for(const j of e.inputImageIds){const A=await kt(j);A&&S.push({id:j,dataUrl:A})}a(S),r(jf(e.prompt,e.inputImageIds.map(j=>({id:j,dataUrl:""})),w.getState().inputImages));const k=e.maskTargetImageId??(e.maskImageId?e.inputImageIds[0]:null);if(k&&e.maskImageId&&S.some(j=>j.id===k)){const j=await kt(e.maskImageId);j?o({targetImageId:k,maskDataUrl:j,updatedAt:Date.now()}):i()}else i();if(b){c({title:"找不到 API 配置",message:`找不到复用任务所使用的 API 配置「${h}」,要使用当前的 API 配置「${d.name}」提交任务吗?`,confirmText:"使用当前配置提交",cancelText:"放弃提交",action:()=>{ji({useCurrentApiProfileWhenReusedMissing:!0})}});return}l(x&&m?`已临时复用该任务的 API 配置「${m.name}」`:"已复用配置到输入框","success")}async function vg(e){var o;const{inputImages:t,addInputImage:r,showToast:n}=w.getState();if(!((o=e.outputImages)!=null&&o.length))return;let a=0;for(const i of e.outputImages){if(t.find(c=>c.id===i))continue;const l=await kt(i);l&&(r({id:i,dataUrl:l}),a++)}n(`已添加 ${a} 张输出图到输入`,"success")}function Rb(e,t,r){const n=new Set(e.messages.filter(a=>a.roundId===t.id).map(a=>a.id));return n.add(t.userMessageId),t.assistantMessageId&&n.add(t.assistantMessageId),gn([...t.outputTaskIds,...e.messages.filter(a=>n.has(a.id)).flatMap(a=>a.outputTaskIds??[]),...r.filter(a=>a.agentRoundId===t.id||!!(a.agentMessageId&&n.has(a.agentMessageId))).map(a=>a.id)])}function _b(e,t,r,n){const a=n.agentConversations.find(o=>o.id===e);if(a!=null&&a.rounds.some(o=>t.has(o.id)&&o.status==="running")||n.tasks.some(o=>r.has(o.id)&&o.status==="running"))return!0;for(const o of t){const i=Vn(e,o),l=a==null?void 0:a.rounds.find(u=>u.id===o),c=ta.get(i);if(c&&!c.signal.aborted||Ul.has(i)&&(l==null?void 0:l.status)!=="done"&&(l==null?void 0:l.error)!==nn)return!0}return!1}function Db(e,t,r,n){let a=!1;const o=e.rounds.map(l=>{const c=l.outputTaskIds.filter(f=>!t.has(f)),u=!!(l.assistantMessageId&&r.has(l.assistantMessageId));return c.length===l.outputTaskIds.length&&!u?l:(a=!0,{...l,...u?{assistantMessageId:void 0}:{},outputTaskIds:c})}),i=e.messages.map(l=>{var c;return(c=l.outputTaskIds)!=null&&c.some(u=>t.has(u))?(a=!0,{...l,outputTaskIds:l.outputTaskIds.filter(u=>!t.has(u))}):l});return a?{...e,rounds:o,messages:i,updatedAt:n}:e}async function Xj(e,t){const r=w.getState(),n=r.agentConversations.find(l=>l.id===e),a=n==null?void 0:n.rounds.find(l=>l.id===t);if(!n||!a)return"not-found";const o=new Set(Rb(n,a,r.tasks));if(_b(e,new Set([t]),o,r))return"running";let i=!1;try{await jd([...o],(l,c)=>{const u=l.agentConversations.find(I=>I.id===e),f=u==null?void 0:u.rounds.find(I=>I.id===t);if(!u||!f)return null;const d=fa(u),g=t2(u,t),m=fa(g),x=new Set([f.userMessageId,...f.assistantMessageId?[f.assistantMessageId]:[],...u.messages.filter(I=>I.roundId===t).map(I=>I.id)]),b=new Set(u.messages.filter(I=>I.role==="assistant"&&x.has(I.id)).map(I=>I.id));f.assistantMessageId&&b.add(f.assistantMessageId);const h=Date.now(),y=l.agentConversations.map(I=>{const S=I.id===e?{...g,messages:g.messages.filter(k=>!x.has(k.id))}:I;return Db(S,c,b,h)}),v=TC(l.agentInputDrafts,e,d,m);return i=!0,{agentConversations:y,agentInputDrafts:v,...l.activeAgentConversationId===e&&l.appMode==="agent"?{prompt:Vf(l.prompt,d,m)}:{},agentEditingRoundId:l.agentEditingRoundId===t?null:l.agentEditingRoundId}})}catch(l){if(!i)throw l;return console.warn("Agent 轮次已删除,但持久化或图片清理失败",l),"deleted-with-warning"}return i?"deleted":"not-found"}async function qj(e,t){const r=w.getState(),n=r.agentConversations.find(u=>u.id===e),a=n==null?void 0:n.messages.find(u=>u.id===t&&u.role==="assistant");if(!n||!a)return"not-found";const o=n.rounds.find(u=>u.id===a.roundId),i=new Set(gn([...a.outputTaskIds??[],...o?Rb(n,o,r.tasks):[],...r.tasks.filter(u=>u.agentMessageId===t).map(u=>u.id)])),l=new Set([a.roundId,...n.rounds.filter(u=>u.assistantMessageId===t).map(u=>u.id)]);if(_b(e,l,i,r))return"running";let c=!1;try{await jd([...i],(u,f)=>{const d=u.agentConversations.find(h=>h.id===e),g=d==null?void 0:d.messages.find(h=>h.id===t&&h.role==="assistant");if(!d||!g)return null;const m=Date.now(),x=new Set([t]),b=u.agentConversations.map(h=>{const y=h.id===e?{...h,messages:h.messages.filter(v=>v.id!==t),updatedAt:m}:h;return Db(y,f,x,m)});return c=!0,{agentConversations:b}})}catch(u){if(!c)throw u;return console.warn("Agent 消息已删除,但持久化或图片清理失败",u),"deleted-with-warning"}return c?"deleted":"not-found"}async function jd(e,t){const r=new Set(e);let n=[];if(w.setState(c=>{n=c.tasks.filter(d=>r.has(d.id));const u={...c.streamPreviews},f={...c.streamPreviewSlots};for(const d of r)delete u[d],delete f[d];return{tasks:c.tasks.filter(d=>!r.has(d.id)),selectedTaskIds:c.selectedTaskIds.filter(d=>!r.has(d)),streamPreviews:u,streamPreviewSlots:f}}),n.length===0&&!t)return 0;const a=new Set;for(const c of n){pg(a,c);const u=c.agentConversationId&&c.agentRoundId?ta.get(Vn(c.agentConversationId,c.agentRoundId)):void 0;u&&kc.set(c.id,{task:c,controller:u}),ki(c.id),Ci(c.id),yi(c.id),ur.delete(c.id)}const o=Ab(n),i=[];t&&w.setState(c=>{const u=t(c,r);if(!u)return c;if(u.agentConversations){const f=new Map(c.agentConversations.map(d=>[d.id,d]));i.push(...u.agentConversations.filter(d=>f.get(d.id)!==d))}return u});const l=new Map(o.updatedConversations.map(c=>[c.id,c]));for(const c of i)l.set(c.id,c);return await Pb(n.map(c=>c.id),{...o,updatedConversations:[...l.values()]}),await ns(a),n.length}async function Zi(e){if(!e.length)return;const t=await jd(e);t!==0&&w.getState().showToast(`已删除 ${t} 个任务`,"success")}async function Jj(e){const t=e?new Set(e):null,r=w.getState().tasks.filter(o=>vi(o,"error")&&(!t||t.has(o.id))),n=r.filter(o=>o.status==="error").map(o=>o.id),a=new Set(r.filter(o=>o.status!=="error"&&jb(o)).map(o=>o.id));if(n.length&&await Zi(n),a.size){const{tasks:o,setTasks:i,selectedTaskIds:l,setSelectedTaskIds:c,showToast:u}=w.getState(),f=o.map(g=>a.has(g.id)?{...g,outputErrors:void 0}:g);i(f);const d=l.filter(g=>!a.has(g));d.length!==l.length&&c(d),await Promise.all(f.filter(g=>a.has(g.id)).map(g=>wn(g))),u(`已清除 ${a.size} 条部分失败记录`,"success")}}async function wg(e){await jd([e.id])!==0&&w.getState().showToast("任务已删除","success")}async function Gj(e={clearConfig:!0,clearTasks:!0}){const{setTasks:t,clearInputImages:r,clearMaskDraft:n,setSettings:a,setParams:o,showToast:i}=w.getState();if(w.getState().batchProgress&&ra(Is),e.clearTasks&&(await Lk(),await Uk(),await $k(),z2(),t([]),w.setState({agentConversations:[],activeAgentConversationId:null,supportPromptOpen:!1,supportPromptSkippedForImportedData:!1,imageSourceUrls:{}}),r(),n()),e.clearConfig){const l=ri();w.setState({dismissedPresetProfileIds:[],dismissedPresetProviderIds:[],dismissedCodexCliPrompts:[],supportPromptDismissed:!1}),l?(w.setState({settings:{...sr}}),await w.getState().setPresetImportedSettings(l)):a({...sr}),o({...Qr})}i("所选数据已清空","success")}async function Zj(e,t){const r=w.getState().tasks.find(u=>u.id===e.id);if(!r||r.status==="done"||r.error===nn||r.status!=="running"&&!r.customRecoverable)return;const{outputIds:n,outputDataUrls:a,outputImageSizes:o,transparentOriginalImageIds:i}=await xg(e,t.images),l=await hg(a,void 0,o),c=w.getState().tasks.find(u=>u.id===e.id);if(!c||c.status==="done"||c.error===nn||c.status!=="running"&&!c.customRecoverable){await ns([...n,...i??[]]);return}Rt(e.id,{outputImages:n,transparentOriginalImages:i,actualParams:bc(l),actualParamsByImage:cg(n,l),revisedPromptByImage:void 0,...xd(e,Date.now()),customRecoverable:!1}),eo(e)||(w.getState().showToast(`自定义异步任务已恢复,共 ${n.length} 张图片`,"success"),vn(e)||ks("图像生成完成",`自定义异步任务已恢复,共 ${n.length} 张图片。`)),vn(e)&&Id(e.id)}async function Qj(e){const{settings:t,tasks:r}=w.getState(),n=r.find(i=>i.id===e);if(!n||!n.customTaskId||n.status==="done")return;const a=Ij(t,n),o=a?Rn(t,a.provider):null;if(!a||!(o!=null&&o.poll)){kd(e);return}try{const i=await AI(a,o,n.customTaskId,n.params);Ci(e),await Zj(n,i)}catch(i){if(Ci(e),!w.getState().tasks.some(c=>c.id===e))return;const l=i instanceof Error?i.message:String(i);Rt(e,{...Wr(n,l,Date.now()),...wd(i),customRecoverable:!1}),bi(n),vn(n)&&Id(e)}}async function e5(e={exportConfig:!0,exportTasks:!0}){const t=fb("export",!0);let r=0;try{const n=w.getState();if(e.exportTasks&&Zf(n.tasks,n.agentConversations))throw new Error("有任务正在进行,完成或停止后再导出。");const a=e.exportTasks?await Af():[],o=e.exportTasks?await vp():[],{settings:i,agentConversations:l,favoriteCollections:c,defaultFavoriteCollectionId:u}=n,f=Date.now(),d={options:e,exportedAt:f,settings:i,tasks:a,imageTasks:a,imageSourceUrls:n.imageSourceUrls,favoriteCollections:c,defaultFavoriteCollectionId:u,agentConversations:e.exportTasks?Xf(l):[]},g=await kC(o,S=>{Qt(t),mn("统计图片",S,o.length,"image")});Qt(t);const m=mC(d,g),x=`${f}`;De&&m.length>1&&mn("选择保存位置");const b=De&&m.length>1?await ug():null;if(De&&m.length>1&&!b)return;let h="";const y=m.reduce((S,k)=>S+k.imageIds.length,0);let v=0;for(let S=0;S<m.length;S++){const k=S+1,j=m.length>1?`(第 ${k} / ${m.length} 卷)`:"";Qt(t);const{images:A,thumbnailsByImageId:N}=await IC(m[S].imageIds,F=>{Qt(t),mn(`读取图片${j}`,v+F,y,"image")});v+=m[S].imageIds.length,Qt(t),mn(`打包${j}`);const C=await gC({...d,tasks:m[S].tasks,agentConversations:m[S].agentConversations,images:A,thumbnailsByImageId:N,includeManifestData:m[S].includeBaseData,backupPart:m.length>1?{id:x,index:k,total:m.length}:void 0}),T=m.length>1?`_${String(m.length).padStart(2,"0")}parts_part${String(k).padStart(2,"0")}`:"",R=`gpt-image-playground-backup_${di(new Date(f))}${T}.zip`;Qt(t),mn(`保存文件${j}`);const U={signal:t,onProgress:(F,_)=>mn(`保存文件${j}`,F,_,"byte")};if(b){await yd(b,C.bytes,R,U),r++;continue}const W=await yc(De?C.bytes:hC(C.bytes),R,U);if(!W)return;r++,h=W,k<m.length&&await new Promise(F=>setTimeout(F,150))}const I=b?`已导出 ${m.length} 个 ZIP 到 ${b.path}`:m.length>1?`正在下载 ${m.length} 个 ZIP,如被浏览器拦截,请允许多文件下载`:De?`已导出到 ${h}`:"数据已导出";w.getState().showToast(I,"success")}catch(n){if(t.aborted){w.getState().showToast(r?`已取消导出,已${De?"保存":"下载"}的 ${r} 个分卷不完整,可以删除`:"已取消导出","info");return}console.error("exportData failed",n);const a=n instanceof Error?n.message.trim():String(n).trim();w.getState().showToast(a?`导出失败,${a}`:"导出失败","error")}finally{gb()}}async function t5(e){const t=If(),r=Bn(),n=e.providerIds.filter(l=>t.has(l)),a=e.profileIds.filter(l=>r.has(l));if(!n.length&&!a.length)return!1;const o=w.getState();for(const l of n)o.restorePresetProvider(l);for(const l of a)o.restorePresetProfile(l);const i=ri();return i&&await w.getState().setPresetImportedSettings(i),!0}async function r5(e,t={importConfig:!0,importTasks:!0}){const r=fb("import",!0);try{const n=w.getState();if(t.importTasks&&Zf(n.tasks,n.agentConversations))throw new Error("有任务正在进行,完成或停止后再导入。");const a=Array.isArray(e)?e:[e];if(!a.length)throw new Error("没有选择备份文件。");if(a.some(m=>m.size>=ag))throw new Error("单个 ZIP 不能超过 2 GB,请使用分卷备份。");const o=[];for(const[m,x]of a.entries()){mn("解析备份",m,a.length>1?a.length:0,a.length>1?"file":void 0);const b=await pC(new Uint8Array(await x.arrayBuffer()),t.importTasks);o.push({file:x,manifest:b}),Qt(r)}if(o.some(m=>m.manifest.backupPart!=null)){if(o.some(h=>!h.manifest.backupPart))throw new Error("不能同时选择分卷备份和普通备份。");const m=o[0].manifest.backupPart,x=new Set(o.map(h=>h.manifest.backupPart.index));if(!o.every(h=>{const y=h.manifest.backupPart;return y.id===m.id&&y.total===m.total&&y.index>=1&&y.index<=m.total})||x.size!==o.length)throw new Error("所选分卷不属于同一份备份,或有重复。");if(t.importTasks&&(o.length!==m.total||x.size!==m.total))throw new Error(`分卷不全,请一次选择全部 ${m.total} 个 ZIP。`);o.sort((h,y)=>h.manifest.backupPart.index-y.manifest.backupPart.index)}const l=o.filter(m=>m.manifest.settings);if(t.importConfig&&!t.importTasks&&!l.length)throw new Error("这份备份里没有配置。");const c=o.flatMap(m=>m.manifest.tasks??[]),u=o.flatMap(m=>m.manifest.agentConversations??[]),f=o.some(m=>m.manifest.tasks!=null||m.manifest.imageFiles!=null);qC(!1),Qt(r);const d=[];if(t.importTasks&&f){const m=o.reduce((N,C)=>N+Object.keys(C.manifest.imageFiles??{}).length+Object.keys(C.manifest.thumbnailFiles??{}).length,0);let x=0;for(const[N,C]of o.entries()){mn(o.length>1?`读取备份(第 ${N+1} / ${o.length} 个)`:"读取备份",x,m,"file");const{manifest:T,files:R}=await xC(new Uint8Array(await C.file.arrayBuffer()));for(const[U,W]of Object.entries(T.imageFiles??{})){mn("写入图片和缩略图",++x,m,"file");const F=i0(R,W.path);if(F){if(await ea({id:U,dataUrl:F,createdAt:W.createdAt,source:W.source,width:W.width,height:W.height}),Xt(U,F),Ir(W.sourceUrl)){const _=W.sourceUrl;w.setState(O=>({imageSourceUrls:{...O.imageSourceUrls,[U]:_}}))}d.push(U)}}for(const[U,W]of Object.entries(T.thumbnailFiles??{})){mn("写入图片和缩略图",++x,m,"file");const F=i0(R,W.path);F&&(await Va({id:U,thumbnailDataUrl:F,width:W.width,height:W.height,thumbnailVersion:W.thumbnailVersion}),Ki(U,{src:F,width:W.width,height:W.height,thumbnailVersion:W.thumbnailVersion}))}}mn("写入任务和会话");for(const N of c)await wn(Number.isFinite(N.startedAt)||N.startedAt===void 0?N:{...N,startedAt:void 0});const b=await Af(),h=w.getState(),y=o.flatMap(N=>N.manifest.favoriteCollections??[]),v=DC(h.favoriteCollections,y),I=v.collections,S=o.map(N=>N.manifest.defaultFavoriteCollectionId).find(N=>N!=null&&I.some(C=>C.id===N)),k=v.importedCollections.length?Gi(I,S):h.defaultFavoriteCollectionId,j=ib(b,I,k);w.setState({tasks:j.tasks,favoriteCollections:j.collections,defaultFavoriteCollectionId:j.defaultFavoriteCollectionId}),j.changed&&await Promise.all(j.tasks.map(N=>wn(N)));const A=Ho(u).filter(N=>!Yf(N));w.setState(N=>{var R,U;const C=fj(N.agentConversations,A),T=N.activeAgentConversationId&&C.some(W=>W.id===N.activeAgentConversationId)?N.activeAgentConversationId:((R=A[0])==null?void 0:R.id)??((U=C[0])==null?void 0:U.id)??null;return{agentConversations:C,activeAgentConversationId:T}}),await gg(w.getState().agentConversations),cj(b),Ax(d)}if(t.importConfig&&l.length){const m=w.getState(),x=new Set(l.flatMap(S=>{var k,j;return((j=(k=S.manifest.settings)==null?void 0:k.customProviders)==null?void 0:j.map(A=>A.id))??[]})),b=new Set(l.flatMap(S=>{var k;return((k=S.manifest.settings)==null?void 0:k.profiles.map(j=>j.id))??[]})),h=If(),y=Bn();for(const S of x)h.has(S)&&m.restorePresetProvider(S);for(const S of b)y.has(S)&&m.restorePresetProfile(S);const v=w.getState(),I=l.reduce((S,k)=>kf(S,k.manifest.settings,{preserveInternalIds:!0}),v.settings);v.setSettings(I)}let g="导入完成";return t.importTasks&&f?g=`已导入 ${c.length} 个任务`:t.importConfig&&l.length&&(g="配置已导入"),w.getState().showToast(g,"success"),!0}catch(n){if(r.aborted)return w.getState().showToast("已取消导入","info"),!1;console.error("importData failed",n);const a=n instanceof Error?n.message.trim():String(n).trim();return w.getState().showToast(a?`导入失败,${a}`:"导入失败","error"),!1}finally{gb()}}async function n5(e){const t=await kg(e);t&&w.getState().addInputImage(t)}async function kg(e){if(!e.type.startsWith("image/"))return null;const t=await Uv(e),r=await Qn(t,"upload");return Xt(r,t),yb(r),{id:r,dataUrl:t}}async function Lb(e){const t=await Dr(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);const r=await t.blob();if(!r.type.startsWith("image/"))throw new Error("不是有效的图片");const n=await oa(r),a=await Qn(n,"upload");Xt(a,n),Ir(e)&&w.setState(o=>({imageSourceUrls:{...o.imageSourceUrls,[a]:e}})),w.getState().addInputImage({id:a,dataUrl:n})}const Ob=["settings","profileId","apiUrl","apiKey","codexCli","apiMode","model","imageGenerationModel","profileName","reasoningEffort","streamImages","streamPartialImages","transparentBackgroundMethod"];function x0(e){var t;return JSON.stringify([e.provider,e.baseUrl.trim().toLowerCase(),e.apiKey.trim(),wf(e.model),(t=e.imageGenerationModel)==null?void 0:t.trim(),e.apiMode,e.reasoningEffort,e.codexCli===!0,e.streamImages===!0,e.streamPartialImages??0,e.transparentBackgroundMethod])}function Bb(e){let t=`openai-url-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;for(;e.has(t);)t=`openai-url-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;return e.add(t),t}function b0(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return{customProviders:t.customProviders,profiles:t.profiles}}function Sd(e){const t=e.get("settings");if(!t)return null;try{const r=JSON.parse(t);return r&&typeof r=="object"&&"settings"in r?b0(r.settings??null):b0(r)}catch{return null}}function Ub(e){var o;const t=new Set,r=new Set,n=Sd(e);if(n&&typeof n=="object"&&!Array.isArray(n)){const i=n;if(Array.isArray(i.customProviders))for(const l of i.customProviders){if(!l||typeof l!="object"||Array.isArray(l))continue;const c=typeof l.id=="string"?String(l.id).trim():"";c&&t.add(c)}if(Array.isArray(i.profiles))for(const l of i.profiles){if(!l||typeof l!="object"||Array.isArray(l))continue;const c=typeof l.id=="string"?String(l.id).trim():"";c&&r.add(c)}}const a=(o=e.get("profileId"))==null?void 0:o.trim();return a&&r.add(a),{providerIds:[...t],profileIds:[...r]}}function Fb(e,t){if(!e||typeof e!="object"||Array.isArray(e))return e;const r=e;if(!Array.isArray(r.profiles))return e;const n=new Set(Me(t).profiles.map(o=>o.id)),a=new Set;for(const o of r.profiles){if(!o||typeof o!="object"||Array.isArray(o))continue;const i=typeof o.id=="string"?o.id.trim():"";i&&n.add(i)}return{...r,profiles:r.profiles.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return o;const i=o;return typeof i.id=="string"&&i.id.trim()&&!a.has(i.id.trim())?(a.add(i.id.trim()),{...i,id:i.id.trim()}):{...i,id:Bb(n)}})}}function s5(e,t){if(!t||typeof t!="object"||Array.isArray(t))return e;const r=t;if(!Array.isArray(r.profiles)||r.profiles.length===0)return e;const n=Me({customProviders:r.customProviders,profiles:r.profiles}),a=n.profiles[0],o=e.profiles.find(l=>l.id===a.id);if(o)return Me({...e,activeProfileId:o.id});const i=np(e,a,n.customProviders);return i?Me({...e,activeProfileId:i.id}):e}function a5(e,t,r=!1){var h;const n=Me(e),a=((h=t.get("profileId"))==null?void 0:h.trim())??"",o=a&&Cf(a)?n.profiles.find(y=>y.id===a):void 0;if(a&&!o)return{};const i=o??n.profiles.find(y=>y.id===n.activeProfileId)??n.profiles[0];if(!i)return{};const l=i.provider==="openai",c={},u=Fb(Sd(t),e);if(u&&typeof u=="object"&&!Array.isArray(u)){const y=u.profiles;if(Array.isArray(y)){const v=o?y.find(I=>{if(!I||typeof I!="object"||Array.isArray(I))return!1;const S=I;return S.id===o.id&&(S.provider===void 0||S.provider===i.provider)}):y.find(I=>{if(!I||typeof I!="object"||Array.isArray(I))return!1;const S=I.provider;return S===void 0||S===i.provider});v&&(typeof v.apiKey=="string"&&(c.apiKey=v.apiKey),r||(typeof v.name=="string"&&v.name.trim()&&(c.name=v.name.trim()),typeof v.baseUrl=="string"&&(c.baseUrl=v.baseUrl),typeof v.model=="string"&&v.model.trim()&&(c.model=v.model.trim()),typeof v.imageGenerationModel=="string"&&(c.imageGenerationModel=v.imageGenerationModel.trim()),typeof v.timeout=="number"&&Number.isFinite(v.timeout)&&(c.timeout=v.timeout),typeof v.apiProxy=="boolean"&&(c.apiProxy=v.apiProxy),v.responseFormatB64Json===!0&&(c.responseFormatB64Json=!0),(v.transparentBackgroundMethod==="api"||v.transparentBackgroundMethod==="local")&&(c.transparentBackgroundMethod=v.transparentBackgroundMethod),i.provider!=="fal"&&typeof v.codexCli=="boolean"&&(c.codexCli=v.codexCli),l&&((v.apiMode==="images"||v.apiMode==="responses")&&(c.apiMode=v.apiMode),v.reasoningEffort!==void 0&&(c.reasoningEffort=ia(v.reasoningEffort)),typeof v.streamImages=="boolean"&&(c.streamImages=v.streamImages),v.streamPartialImages!==void 0&&(c.streamPartialImages=Yr(v.streamPartialImages)))))}}const f=t.get("apiUrl"),d=t.get("apiKey"),g=t.get("model"),m=t.get("imageGenerationModel"),x=t.get("profileName"),b=t.get("transparentBackgroundMethod");if(d!==null&&(c.apiKey=d.trim()),r||(x!=null&&x.trim()&&(c.name=x.trim()),f!==null&&(c.baseUrl=Tn(f.trim())),g!=null&&g.trim()&&(c.model=g.trim()),m!==null&&(c.imageGenerationModel=m.trim()),(b==="api"||b==="local")&&(c.transparentBackgroundMethod=b)),i.provider!=="fal"&&!r){const y=t.get("codexCli");y!==null&&(c.codexCli=y.trim().toLowerCase()==="true")}if(l&&!r){const y=t.get("apiMode"),v=t.get("reasoningEffort"),I=t.get("streamImages"),S=t.get("streamPartialImages");(y==="images"||y==="responses")&&(c.apiMode=y),v!==null&&(c.reasoningEffort=ia(v)),I!==null&&(c.streamImages=I.trim().toLowerCase()==="true"),S!==null&&(c.streamPartialImages=Yr(S))}return Object.keys(c).length===0&&!o?{}:Me({...n,profiles:n.profiles.map(y=>y.id===i.id?{...y,...c,provider:y.provider}:y),activeProfileId:(o==null?void 0:o.id)??n.activeProfileId})}function $b(e){return Ob.some(t=>e.has(t))}function o5(e){for(const t of Ob)e.delete(t)}function i5(e,t){const r=Fb(Sd(t),e),n=t.get("profileId"),a=t.get("apiUrl"),o=t.get("apiKey"),i=t.get("codexCli"),l=t.get("apiMode"),c=t.get("model"),u=t.get("imageGenerationModel"),f=t.get("reasoningEffort"),d=t.get("profileName"),g=(d==null?void 0:d.trim())??"",m=t.get("streamImages"),x=t.get("streamPartialImages"),b=t.get("transparentBackgroundMethod"),h=b==="api"||b==="local"?b:void 0,y=l==="images"||l==="responses"?l:void 0,v=a!==null||o!==null||i!==null||y!==void 0||c!==null||u!==null||d!==null||f!==null||m!==null||x!==null,I=r==null?Me(e):s5(kf(e,r),r),S=(n==null?void 0:n.trim())??"",k=S?I.profiles.find(j=>j.id===S&&j.provider!=="openai"):void 0;if(k&&(h!==void 0||k.provider!=="fal"&&i!==null))return Me({...I,profiles:I.profiles.map(j=>j.id===S?{...j,...k.provider!=="fal"&&i!==null?{codexCli:i.trim().toLowerCase()==="true"}:{},...h?{transparentBackgroundMethod:h}:{}}:j),activeProfileId:S});if(!S&&h!==void 0&&!v)return Me({...I,profiles:I.profiles.map(j=>j.id===I.activeProfileId?{...j,transparentBackgroundMethod:h}:j)});if(v||h!==void 0){if(S?I.profiles.find(R=>R.id===S&&R.provider==="openai"):void 0){const R={};return a!==null&&(R.baseUrl=Tn(a.trim())),o!==null&&(R.apiKey=o.trim()),y!==void 0&&(R.apiMode=y),c!=null&&c.trim()&&(R.model=c.trim()),u!==null&&(R.imageGenerationModel=u.trim()),f!==null&&(R.reasoningEffort=ia(f)),g&&(R.name=g),i!==null&&(R.codexCli=i.trim().toLowerCase()==="true"),m!==null&&(R.streamImages=m.trim().toLowerCase()==="true"),x!==null&&(R.streamPartialImages=Yr(x)),h!==void 0&&(R.transparentBackgroundMethod=h),Me({...I,profiles:I.profiles.map(U=>U.id===S?{...U,...R}:U),activeProfileId:S})}const A=y??"images",N=In({id:S||Bb(new Set(I.profiles.map(R=>R.id))),name:"URL 参数配置",apiMode:A,model:(c==null?void 0:c.trim())||(A==="responses"?Wa:ir)});if(a!==null&&(N.baseUrl=Tn(a.trim())),o!==null&&(N.apiKey=o.trim()),u!==null&&(N.imageGenerationModel=u.trim()),f!==null&&(N.reasoningEffort=ia(f)),g&&(N.name=g),i!==null&&(N.codexCli=i.trim().toLowerCase()==="true"),m!==null&&(N.streamImages=m.trim().toLowerCase()==="true"),x!==null&&(N.streamPartialImages=Yr(x)),h!==void 0&&(N.transparentBackgroundMethod=h),S?I.profiles.find(R=>R.id===S):null)return Me({...I,profiles:I.profiles.map(R=>R.id===S?{...N,isDefault:R.isDefault}:R),activeProfileId:S});const T=I.profiles.find(R=>x0(R)===x0(N)&&(!g||R.name.trim()===g));return Me(T?{...I,activeProfileId:T.id}:{...I,profiles:[...I.profiles,N],activeProfileId:N.id})}return r==null?{}:I}function zb(e,t){return Cn()?a5(e,t,io()):i5(e,t)}const Ig=mr("embedded-config:ewogICJjdXN0b21Qcm92aWRlcnMiOiBbCiAgICB7CiAgICAgICJpZCI6ICJjdXN0b20tYXBpbWFydCIsCiAgICAgICJuYW1lIjogIkFQSU1hcnQiLAogICAgICAic3VibWl0IjogewogICAgICAgICJwYXRoIjogImltYWdlcy9nZW5lcmF0aW9ucyIsCiAgICAgICAgIm1ldGhvZCI6ICJQT1NUIiwKICAgICAgICAiY29udGVudFR5cGUiOiAianNvbiIsCiAgICAgICAgImJvZHkiOiB7CiAgICAgICAgICAibW9kZWwiOiAiJHByb2ZpbGUubW9kZWwiLAogICAgICAgICAgInByb21wdCI6ICIkcHJvbXB0IiwKICAgICAgICAgICJzaXplIjogIiRwYXJhbXMuc2l6ZSIsCiAgICAgICAgICAicXVhbGl0eSI6ICIkcGFyYW1zLnF1YWxpdHkiLAogICAgICAgICAgIm91dHB1dF9mb3JtYXQiOiAiJHBhcmFtcy5vdXRwdXRfZm9ybWF0IiwKICAgICAgICAgICJvdXRwdXRfY29tcHJlc3Npb24iOiAiJHBhcmFtcy5vdXRwdXRfY29tcHJlc3Npb24iLAogICAgICAgICAgIm1vZGVyYXRpb24iOiAiJHBhcmFtcy5tb2RlcmF0aW9uIiwKICAgICAgICAgICJuIjogIiRwYXJhbXMubiIsCiAgICAgICAgICAiYmFja2dyb3VuZCI6ICIkcGFyYW1zLmJhY2tncm91bmQiLAogICAgICAgICAgImltYWdlX3VybHMiOiAiJGlucHV0SW1hZ2VzLmRhdGFVcmxzIiwKICAgICAgICAgICJtYXNrX3VybCI6ICIkbWFzay5kYXRhVXJsIgogICAgICAgIH0sCiAgICAgICAgInRhc2tJZFBhdGgiOiAiZGF0YS4wLnRhc2tfaWQiCiAgICAgIH0sCiAgICAgICJwb2xsIjogewogICAgICAgICJwYXRoIjogInRhc2tzL3t0YXNrX2lkfSIsCiAgICAgICAgIm1ldGhvZCI6ICJHRVQiLAogICAgICAgICJpbnRlcnZhbFNlY29uZHMiOiA1LAogICAgICAgICJzdGF0dXNQYXRoIjogImRhdGEuc3RhdHVzIiwKICAgICAgICAic3VjY2Vzc1ZhbHVlcyI6IFsiY29tcGxldGVkIl0sCiAgICAgICAgImZhaWx1cmVWYWx1ZXMiOiBbImZhaWxlZCJdLAogICAgICAgICJlcnJvclBhdGgiOiAiZGF0YS5lcnJvci5tZXNzYWdlIiwKICAgICAgICAicmVzdWx0IjogewogICAgICAgICAgImltYWdlVXJsUGF0aHMiOiBbImRhdGEucmVzdWx0LmltYWdlcy4qLnVybC4qIl0sCiAgICAgICAgICAiYjY0SnNvblBhdGhzIjogW10KICAgICAgICB9CiAgICAgIH0KICAgIH0KICBdLAogICJwcm9maWxlcyI6IFsKICAgIHsKICAgICAgImlkIjogImdwdF9pbWFnZV9wbGF5Z3JvdW5kLWRlZmF1bHQtb3BlbmFpIiwKICAgICAgIm5hbWUiOiAi6buY6K6kIiwKICAgICAgInByb3ZpZGVyIjogIm9wZW5haSIsCiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vYXBpLm9wZW5haS5jb20vdjEiLAogICAgICAibW9kZWwiOiAiZ3B0LWltYWdlLTIuNS1zdW5idXJzdCIsCiAgICAgICJhcGlNb2RlIjogImltYWdlcyIsCiAgICAgICJpc0RlZmF1bHQiOiB0cnVlCiAgICB9LAogICAgewogICAgICAiaWQiOiAiYXBpbWFydCIsCiAgICAgICJuYW1lIjogIkFQSU1hcnQiLAogICAgICAiZGVzY3JpcHRpb24iOiAiW0FQSU1hcnRdKGh0dHBzOi8vZ28uYXBpbWFydC5haS9naC1ncHRfaW1hZ2VfcGxheWdyb3VuZCkg5piv5LiT5rOoIEFJIOWbvueJhy/op4bpopHnlJ/miJDnmoTkvY7ku7cgQVBJIOW5s+WPsO+8jEdQVC1JbWFnZS0yIOS9juiHsyAkMC4wMDYv5byg77yMMSDnvo7lhYPlj6/lh7rlm74gMTYwKyDlvKDjgILlm77niYfjgIHop4bpopHkuIDlpZflvILmraUgQVBJIOmAmuWQg++8jOaPkOS6pOS7u+WKoeaLvyBJROOAgeWbnuiwg+WPlue7k+aenO+8jOi3keaJueS4h+W8oOS4jei2heaXtuOAgeaNouaooeWei+S4jeaUueS7o+eggeOAguaMiemHj+S7mOi0ueOAgeaXoOaciOi0ue+8jOmAmui/h1vmraTms6jlhozpk77mjqVdKGh0dHBzOi8vZ28uYXBpbWFydC5haS9naC1ncHRfaW1hZ2VfcGxheWdyb3VuZCnms6jlhozljbPlj6/lvIDnlKjjgIIiLAogICAgICAicHJvdmlkZXIiOiAiY3VzdG9tLWFwaW1hcnQiLAogICAgICAiYmFzZVVybCI6ICJodHRwczovL2FwaS5hcGltYXJ0LmFpL3YxIiwKICAgICAgIm1vZGVsIjogImdwdC1pbWFnZS0yIiwKICAgICAgImFwaU1vZGUiOiAiaW1hZ2VzIgogICAgfSwKICAgIHsKICAgICAgImlkIjogIm1veXV1LWFpIiwKICAgICAgIm5hbWUiOiAi5pG46bG8IEFJIiwKICAgICAgImRlc2NyaXB0aW9uIjogIlvmkbjpsbwgQUldKGh0dHBzOi8vbW95dXUuY2MvcmVnaXN0ZXI/YWZmPXo5NXIp77yM6K6pIEFJIEFQSSDmjqXlhaXmm7TnroDljZXjgILmmI7noIHmoIfku7fvvIzlhYXlgLwgMTox77yM5pSv5oyBIEdQVOOAgUNsYXVkZeOAgUdlbWluaSDnrYnkuLvmtYHmqKHlnovvvIzph43mlrDlrprkuYnjgIzkvr/lrpwgwrcg56iz5a6aIMK3IOmrmOmAn+OAjSIsCiAgICAgICJwcm92aWRlciI6ICJvcGVuYWkiLAogICAgICAiYmFzZVVybCI6ICJodHRwczovL2xvbmcubW95dXUuY2MvdjEiLAogICAgICAibW9kZWwiOiAiZ3B0LWltYWdlLTIiLAogICAgICAiYXBpTW9kZSI6ICJpbWFnZXMiCiAgICB9LAogICAgewogICAgICAiaWQiOiAianVjb2RleCIsCiAgICAgICJuYW1lIjogIkp1Q29kZXgiLAogICAgICAiZGVzY3JpcHRpb24iOiAiW0p1Q29kZXhdKGh0dHBzOi8vanVjb2RleC5jb20vcmVnaXN0ZXI/YWZmPTNKRFcpIOS4uuS8geS4mue6p+eUqOaIt+aJk+mAoOeahOmrmOWPr+eUqOOAgeS9juW7tui/n+OAgeaegeiHtOaAp+S7t+avlOeahOS4rei9rOerme+8jOaPkOS+myBDb2RleOOAgUNsYXVkZSBDb2Rl44CBR3JvayDnrYnkuLvmtYHlpKfmqKHlnovkuK3ovazmnI3liqHvvIzmlrDnlKjmiLfms6jlhozpgIEgMyDlhYPvvIhRUSDpgq7nrrHvvInvvIzmsLjkuYXmib/or7ogMCDmsLQgMCDmm7/jgIHmqKHlnosgMTAwJSDkv53nnJ/jgIJb55Sf5Zu+5bel5L2c5Y+wXShodHRwczovL2ltYWdlLmp1Y29kZXguY29tKSIsCiAgICAgICJwcm92aWRlciI6ICJvcGVuYWkiLAogICAgICAiYmFzZVVybCI6ICJodHRwczovL2FwaS5zei1saW5rLmNvbS92MSIsCiAgICAgICJtb2RlbCI6ICJncHQtaW1hZ2UtMi41LXN1bmJ1cnN0IiwKICAgICAgImFwaU1vZGUiOiAiaW1hZ2VzIgogICAgfSwKICAgIHsKICAgICAgImlkIjogIm1hcnVjb2RlIiwKICAgICAgIm5hbWUiOiAiTWFydUNvZGUiLAogICAgICAiZGVzY3JpcHRpb24iOiAiW01hcnVDb2RlXShodHRwczovL2FwaS5tdXRla2kuc2l0ZS9yZWdpc3Rlcj9hZmY9Q29va1NsZWVwJnByb21vPUNvb2tTbGVlcCkg5piv5LiA5a625YG25bCU5YGa5YGa5oWI5ZaE55qE5bCP56C056uZIEFQSe+8jOiHquiQpeWPt+axoO+8jOS4u+imgeaPkOS+myBPcGVuQUnjgIFBbnRocm9waWPjgIFHUFQgSW1hZ2Ug562J5Li75rWB5qih5Z6L77yM5pSv5oyBIFdlYnNvY2tldCDljY/orq7vvIzmmI7noIHmoIfku7coT0FJIDAuM3gsIEHDtyAxLjd4Ke+8jOmAj+aYjuaxh+eOhygxOjEp77yMW+aWsOeUqOaIt+azqOWGjOmAgSAxIOWIgF0oaHR0cHM6Ly9hcGkubXV0ZWtpLnNpdGUvcmVnaXN0ZXI/YWZmPUNvb2tTbGVlcCZwcm9tbz1Db29rU2xlZXAp44CCW+eUn+WbvuW3peS9nOWPsPCflrzvuI9dKGh0dHBzOi8vaW1hZ2VzLTIubXV0ZWtpLnNpdGUpIiwKICAgICAgInByb3ZpZGVyIjogIm9wZW5haSIsCiAgICAgICJiYXNlVXJsIjogImh0dHBzOi8vYXBpLm11dGVraS5zaXRlIiwKICAgICAgIm1vZGVsIjogImdwdC1pbWFnZS0yLjUtc3VuYnVyc3QiLAogICAgICAiYXBpTW9kZSI6ICJpbWFnZXMiLAogICAgICAidHJhbnNwYXJlbnRCYWNrZ3JvdW5kTWV0aG9kIjogImxvY2FsIgogICAgfSwKICAgIHsKICAgICAgImlkIjogInN1Ymx5eCIsCiAgICAgICJuYW1lIjogIlN1Ymx5eCIsCiAgICAgICJkZXNjcmlwdGlvbiI6ICJbU3VibHl4XShodHRwczovL2FwaS5zdWJseXgub3JnL3JlZ2lzdGVyP2FmZj1VNjJQQVpFUkNIRUEpIOaYr+S4gOWutueos+WumumrmOaViOeahCBBSSBBUEkg6IGa5ZCI572R5YWz77yM5pSv5oyBIE9wZW5BSeOAgUNsYXVkZeOAgUdyb2vjgIFDb2RleOOAgWdwdC1pbWFnZS0yIOetieS4u+a1geaooeWei++8jOWFvOWuuSBPcGVuQUkgU0RL44CBQ2xhdWRlIENvZGXjgIFDb2RleOOAgUNoZXJyeSBTdHVkaW8g562J5bi455So5bel5YW344CC6YCa6L+HW+mTvuaOpeazqOWGjF0oaHR0cHM6Ly9hcGkuc3VibHl4Lm9yZy9yZWdpc3Rlcj9hZmY9VTYyUEFaRVJDSEVBKeW5tuS9v+eUqOS8mOaDoOeggSBgSU1HMmDvvIzlj6/pop3lpJbpooblj5YgMTAg5YiA6aKd5bqm44CCW+eUn+WbvuW3peS9nOWPsF0oaHR0cHM6Ly9pbWcyLmljZWRpdC5haSkiLAogICAgICAicHJvdmlkZXIiOiAic2IyYXBpLWFzeW5jIiwKICAgICAgImJhc2VVcmwiOiAiaHR0cHM6Ly9hcGkuc3VibHl4Lm9yZy92MSIsCiAgICAgICJtb2RlbCI6ICJncHQtaW1hZ2UyLjUtZmxhcmUiLAogICAgICAiYXBpTW9kZSI6ICJpbWFnZXMiCiAgICB9CiAgXQp9Cg==");function l5(e=Ig){const t=e.trim();if(Wb(t))return"";try{return new URL(t).searchParams.has("settings")?t:""}catch{return""}}function Wb(e=Ig){return e.trim().startsWith(ql)}function c5(e=Ig){const t=e.trim();if(!t.startsWith(ql))return null;const r=Uint8Array.from(atob(t.slice(ql.length)),n=>n.charCodeAt(0));return vf(new TextDecoder().decode(r),[],{deploymentConfig:!0})}function d5(e){try{const t=new URL(e).searchParams.get("settings");if(!t)return null;const r=JSON.parse(t);return r&&typeof r=="object"&&!Array.isArray(r)&&"settings"in r?JSON.stringify(r.settings??null):t}catch{return null}}async function u5(e){const t=e.trim();if(!t)return null;const r=d5(t);return r?vf(r,[],{deploymentConfig:!0}):null}const y0="docker-api-url-migration-notice-v1";function f5(){const e=w(t=>t.setConfirmDialog);p.useEffect(()=>{if(mr(void 0)!=="true"||mr(void 0)!=="true"||localStorage.getItem(y0)==="true")return;const t=()=>{localStorage.setItem(y0,"true")};e({title:"Docker 部署配置变更",message:"当前版本已将 Docker 环境变量 `API_URL` 拆分为 `DEFAULT_API_URL` 和 `API_PROXY_URL`。\n\n`DEFAULT_API_URL` 只用于前端设置中的默认 API 地址;`API_PROXY_URL` 只用于容器内 Nginx 的 API 代理转发目标。\n\n为避免升级后立即失效,旧的 `API_URL` 会自动同时作为两个新变量的兜底值。建议后续更新 docker run 或 docker-compose 配置,显式使用新变量。",confirmText:"我知道了",showCancel:!1,icon:"info",minConfirmDelayMs:3e3,action:t,cancelAction:t})},[e])}function g5(){const e=w(a=>a.settings.uiFont),t=w(a=>a.settings.uiFontName),r=w(a=>a.settings.monoFont),n=w(a=>a.settings.monoFontName);p.useLayoutEffect(()=>{rm("ui",Gl("ui",e,t))},[e,t]),p.useLayoutEffect(()=>{rm("mono",Gl("mono",r,n))},[r,n])}const v0="color-mode";function m5(e,t){return e==="dark"||e==="system"&&t}function h5(){const e=w(t=>t.settings.colorMode);p.useLayoutEffect(()=>{try{localStorage.getItem(v0)!==e&&localStorage.setItem(v0,e)}catch(n){console.warn("缓存颜色模式失败:",n)}const t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>{document.documentElement.classList.toggle("dark",m5(e,t.matches))};if(r(),e==="system")return t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[e])}function p5(e){const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>t.disconnect()}function x5(){return p.useSyncExternalStore(p5,()=>document.documentElement.classList.contains("dark"))}function b5(){p.useEffect(()=>{if(!De)return;let e=!1;Fv(async()=>{const t=w.getState();if(!Mx(t.tasks,t.agentConversations,t.batchProgress)||e)return!0;let r=!1;const n={title:"关闭客户端",message:"当前有任务或数据操作正在进行,关闭后会被中断。确定要关闭吗?",confirmText:"关闭",tone:"warning",action:()=>{r=!0}};return e=!0,t.setConfirmDialog(n),await new Promise(a=>{const o=w.subscribe(i=>{i.confirmDialog!==n&&(o(),a())})}),e=!1,r})},[])}async function y5(e,t){await Nt("plugin:clipboard-manager|write_text",{label:t==null?void 0:t.label,text:e})}async function Hb(){return await Nt("plugin:clipboard-manager|read_text")}async function v5(){return await Nt("plugin:deep-link|get_current")}async function w5(e){return await Fh("deep-link://new-url",t=>{e(t.payload)})}const zl=new Set,k5=mr(void 0).replace(/\/+$/,""),Yb="gpt-image-playground:";function I5(e,t,r=k5){return e?r?`${r}/`:`${Yb}//`:t}function C5(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function j5(e){if(!e)return!1;try{const t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function S5(e){const t=e.trim();if(!t||t.length>32768||/\s/.test(t))return null;let r;try{r=new URL(t)}catch{return null}const n=r.searchParams;if(r.protocol===Yb)return $b(n)?n:null;if(r.protocol!=="http:"&&r.protocol!=="https:")return null;const a=Sd(n);return C5(a)&&Array.isArray(a.profiles)&&a.profiles.length>0||j5(n.get("apiUrl"))?n:null}function N5(e,t){const r=Ub(e),n=ri(),a=((n==null?void 0:n.profiles)??[]).filter(_=>r.profileIds.includes(_.id)&&!t.profiles.some(O=>O.id===_.id)),o=((n==null?void 0:n.customProviders)??[]).filter(_=>r.providerIds.includes(_.id)&&!t.customProviders.some(O=>O.id===_.id)),i=a.length||o.length?Me({...t,customProviders:[...t.customProviders,...o],profiles:[...t.profiles,...a]}):t,l=Me({...i,...zb(i,e)}),c=_=>_.replace(/\s+/g," ").trim(),u=(_,O=80)=>{const J=c(_);return J.length>O?`${J.slice(0,O)}…`:J},f={text:"(空)",hint:!0},d=_=>u(_)||"(空)",g=_=>_?{text:_}:f,m=_=>{try{const O=new URL(Tn(_.trim()));return`${O.protocol}//${O.host}${u(`${O.pathname}${O.search}`.replace(/^\/$/,""),40)}`}catch{return c(_)}},x=_=>({text:_,fixed:!0}),b=_=>x(_?"开启":"关闭"),h=[["服务商类型",_=>Rn(l,_.provider)?g(u(Ys(l,_.provider))):x(Ys(l,_.provider))],["API 代理",_=>b(_.apiProxy)],["API 接口",_=>_.apiMode==="responses"?x("Responses API"):_.apiMode==="images"?x("Images API"):g(u(String(_.apiMode)))],["首页选中的模型",_=>g(u(_.selectedModel??""))],["图像生成模型",_=>g(u(_.imageGenerationModel??""))],["推理强度",_=>_.reasoningEffort?g(u(_.reasoningEffort)):x("默认")],["流式传输",_=>b(_.streamImages)],["请求中间步骤图像数",_=>g(String(_.streamPartialImages??kr))],["透明背景实现方式",_=>_.transparentBackgroundMethod==="local"?x("本地后处理"):_.transparentBackgroundMethod==="api"?x("API 原生"):g(u(String(_.transparentBackgroundMethod)))],["返回 Base64 图片数据",_=>b(_.responseFormatB64Json)],["Codex CLI 兼容模式",_=>b(_.codexCli)],["请求超时 (秒)",_=>g(u(String(_.timeout)))],["配置说明",_=>g(u(_.description??""))]],y=new Set(["name","baseUrl","model","apiKey","provider","apiProxy","apiMode","selectedModel","imageGenerationModel","reasoningEffort","streamImages","streamPartialImages","transparentBackgroundMethod","responseFormatB64Json","codexCli","timeout","description"]),v=_=>JSON.stringify(Object.entries(_).filter(([O])=>!y.has(O))),I=(_,O,J)=>h.filter(([,H])=>JSON.stringify(H(_))!==JSON.stringify(H(O))&&(J||!H(O).hint)).map(([H,K])=>J?{label:H,before:K(_),after:K(O)}:{label:H,after:K(O)}),S=new Map(i.profiles.map(_=>[_.id,_])),k=l.profiles.filter(_=>!S.has(_.id)),j=l.profiles.filter(_=>{const O=S.get(_.id);return O&&JSON.stringify(O)!==JSON.stringify(_)}),A=new Set(i.customProviders.map(_=>_.id)),N=l.customProviders.filter(_=>!A.has(_.id)).map(_=>d(_.name));j.sort((_,O)=>+(O.baseUrl!==S.get(O.id).baseUrl)-+(_.baseUrl!==S.get(_.id).baseUrl));const C=[...j.map(_=>{const O=S.get(_.id),J=O.baseUrl!==_.baseUrl,H=O.apiKey===_.apiKey&&!!_.apiKey,K=[];return O.name!==_.name&&K.push({label:"名称",before:g(u(O.name)),after:g(u(_.name))}),J&&K.push({label:"API 地址",before:g(m(O.baseUrl)),after:g(m(_.baseUrl))}),O.model!==_.model&&K.push({label:"模型",before:g(u(O.model)),after:g(u(_.model))}),K.push(...I(O,_,!0)),O.apiKey!==_.apiKey?K.push({label:"API Key",before:O.apiKey?{text:"已保存的 Key",hint:!0}:f,after:_.apiKey?{text:"链接中的 Key",hint:!0}:f}):H&&K.push({label:"API Key",note:J?"将继续使用该配置已保存的 API Key,并发送到新的 API 地址":"将继续使用该配置已保存的 API Key"}),v(O)!==v(_)&&K.push({label:"其他设置",note:"将修改该配置的其他内部设置"}),{title:`修改配置「${d(O.name)}」`,keyReuse:J&&H?!0:void 0,rows:K}}),...k.map(_=>{const O=Me({...l,profiles:[{id:_.id,name:_.name,provider:_.provider,baseUrl:_.baseUrl,apiKey:_.apiKey,model:_.model,imageGenerationModel:In().imageGenerationModel}]}).profiles.find(J=>J.id===_.id)??_;return{title:`新增配置「${d(_.name)}」`,rows:[{label:"API 地址",after:g(m(_.baseUrl))},{label:"模型",after:g(u(_.model))},...I(O,_,!1),_.apiKey?{label:"API Key",after:{text:"链接中的 Key",hint:!0}}:{label:"API Key",note:"链接中未包含 API Key"}]}})],T=j.length+k.length,R=[...o,...a].map(_=>d(_.name)),U=l.activeProfileId!==i.activeProfileId?l.profiles.find(_=>_.id===l.activeProfileId):void 0,W=[...j.length?[`修改 ${j.length} 个`]:[],...k.length?[`新增 ${k.length} 个`]:[]];return{summary:T===1?"请只导入来源可信的链接。":T?`链接将${W.join("、")}配置${W.length>1?`,共 ${T} 个`:""}。请只导入来源可信的链接。`:N.length?`链接将新增 ${N.length} 个自定义服务商。请只导入来源可信的链接。`:U?`已存在相同的配置,导入后将切换到「${d(U.name)}」。`:R.length?"链接将恢复已删除的预置配置。":"链接中的配置不会改变当前设置(已存在相同配置,或受当前部署限制)。",notes:[...R.length?[`将恢复预置配置:${R.join("、")}`]:[],...N.length?[`新增自定义服务商:${N.join("、")}`]:[],...!T&&N.length&&U?[`导入后将切换到「${d(U.name)}」`]:[]],groups:C}}function Ot(e=500){const[t,r]=p.useState(!1),n=p.useRef(null),a=p.useRef(!1),o=p.useRef(!1),i=p.useCallback(()=>{n.current!=null&&(window.clearTimeout(n.current),n.current=null)},[]),l=p.useCallback(()=>{i(),a.current=!0,o.current=!1,r(!1)},[i]);p.useEffect(()=>()=>{i()},[i]),p.useEffect(()=>ip(l),[l]);const c=p.useCallback(()=>{a.current=!1,r(!0)},[]),u=p.useCallback(()=>{r(!1)},[]);return{visible:t,handlers:{onMouseEnter:c,onMouseLeave:u,onFocus:c,onBlur:u,onTouchStart:()=>{i(),o.current=!1,n.current=window.setTimeout(()=>{o.current=!0,a.current||r(!0),n.current=null},e)},onTouchMove:i,onClick:()=>{i()},onTouchEnd:d=>{i(),o.current&&d.cancelable&&d.preventDefault(),o.current=!1},onTouchCancel:()=>{i(),o.current=!1}},show:c,dismiss:l}}var lr=$v();function pt({visible:e,children:t,className:r=""}){const n=p.useRef(null),a=p.useRef(null),[o,i]=p.useState(null),[l,c]=p.useState(!1);p.useEffect(()=>{if(!e){c(!1);return}return ip(()=>c(!0))},[e]);const u=e&&!l,f=(d,g)=>{const m=g.left+g.width/2,x=g.top+g.height/2;if(m<0||m>window.innerWidth||x<0||x>window.innerHeight)return!1;const b=document.elementFromPoint(m,x);return!!b&&d.contains(b)};return p.useEffect(()=>{if(!u)return;const d=g=>{var b,h;const m=g.target,x=(b=n.current)==null?void 0:b.parentElement;m instanceof Node&&(x!=null&&x.contains(m)||(h=a.current)!=null&&h.contains(m)||c(!0))};return document.addEventListener("pointerdown",d,!0),document.addEventListener("touchstart",d,!0),()=>{document.removeEventListener("pointerdown",d,!0),document.removeEventListener("touchstart",d,!0)}},[u]),p.useEffect(()=>{if(!u){i(null);return}const d=()=>{var N;const g=(N=n.current)==null?void 0:N.parentElement,m=a.current;if(!g||!m)return;const x=8,b=8,h=g.getBoundingClientRect();if(!g.getClientRects().length||h.width===0&&h.height===0){i(null);return}if(!f(g,h)){i(null);return}const y=m.getBoundingClientRect(),v=h.left+h.width/2,I=Math.max(x,window.innerWidth-y.width-x),S=Math.min(Math.max(v-y.width/2,x),I),k=h.top-y.height-b,j=k>=x+cf?"top":"bottom",A=j==="top"?k:h.bottom+b;i({left:S,top:A,arrowLeft:v-S,placement:j})};return d(),window.addEventListener("resize",d),window.addEventListener("scroll",d,!0),()=>{window.removeEventListener("resize",d),window.removeEventListener("scroll",d,!0)}},[u,t]),s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:n,className:"hidden","aria-hidden":!0}),u&&lr.createPortal(s.jsxs("div",{ref:a,className:`fixed pointer-events-none rounded-lg bg-gray-800 px-3 py-2 text-xs font-normal text-white shadow-lg ${r}`,style:{left:(o==null?void 0:o.left)??0,top:(o==null?void 0:o.top)??0,visibility:o?"visible":"hidden",zIndex:120},children:[t,s.jsx("div",{className:`absolute left-0 border-4 border-transparent ${(o==null?void 0:o.placement)==="bottom"?"bottom-full border-b-gray-800":"top-full border-t-gray-800"}`,style:{left:(o==null?void 0:o.arrowLeft)??0,transform:"translateX(-50%)"}})]}),document.body)]})}const w0="将继续使用该配置已保存的 API Key,并发送到新的 API 地址,请确认该地址可信。",k0=e=>`min-w-0 break-all ${e.hint?"font-sans italic opacity-80":e.fixed?"font-sans":""}`;function A5(){const e=Ot();return s.jsxs("button",{type:"button","aria-label":w0,className:"mt-0.5 shrink-0 text-orange-500 transition hover:text-orange-600 dark:text-orange-400 dark:hover:text-orange-300",...e.handlers,onClick:()=>{e.handlers.onClick(),e.show()},children:[s.jsxs("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),s.jsx("path",{d:"M12 9v4"}),s.jsx("path",{d:"M12 17h.01"})]}),s.jsx(pt,{visible:e.visible,className:"max-w-[16rem] leading-relaxed",children:w0})]})}function P5({desc:e}){return s.jsxs("div",{className:"space-y-3 text-sm",children:[e.notes.map(t=>s.jsx("p",{className:"text-gray-500 dark:text-gray-400 break-all",children:t},t)),e.groups.map((t,r)=>s.jsxs("div",{className:"rounded-2xl border border-gray-200/70 p-3 dark:border-white/[0.08]",children:[s.jsxs("div",{className:"mb-2 flex items-start gap-1.5 font-semibold text-gray-700 dark:text-gray-200",children:[s.jsx("span",{className:"min-w-0 break-all",children:t.title}),t.keyReuse&&s.jsx(A5,{})]}),s.jsx("div",{className:"space-y-2",children:t.rows.map(n=>s.jsxs("div",{children:[s.jsx("div",{className:"mb-1 text-xs text-gray-400 dark:text-gray-500",children:n.label}),s.jsxs("div",{className:"overflow-hidden rounded-lg font-mono text-xs leading-relaxed",children:[n.before&&s.jsxs("div",{className:"flex gap-1.5 bg-red-50 px-2 py-1 text-red-600 dark:bg-red-500/10 dark:text-red-400",children:[s.jsx("span",{className:"shrink-0 select-none",children:"-"}),s.jsx("span",{className:k0(n.before),children:n.before.text})]}),n.after&&s.jsxs("div",{className:"flex gap-1.5 bg-green-50 px-2 py-1 text-green-600 dark:bg-green-500/10 dark:text-green-400",children:[s.jsx("span",{className:"shrink-0 select-none",children:"+"}),s.jsx("span",{className:k0(n.after),children:n.after.text})]}),n.note&&s.jsx("div",{className:"bg-gray-50 px-2 py-1 font-sans text-gray-500 dark:bg-white/[0.04] dark:text-gray-400",children:n.note})]})]},n.label))})]},r))]})}async function T5(e,t){const r=Ub(t),n=await t5(r),a=w.getState().settings,o=n?{...a,...e,customProviders:a.customProviders,profiles:a.profiles}:e,i=zb(o,t);return Object.keys(i).length?i:o}let I0=Promise.resolve(),C0=!1;function M5(){const e=()=>{const t=w.getState();return!t.confirmDialog&&!t.showSettings};return new Promise(t=>{if(e())return t();const r=w.subscribe(()=>{e()&&(r(),t())})})}function Wl(e,t=!1){const r=typeof e=="string"?e.trim():"";if(!t&&zl.has(r))return;const n=typeof e=="string"?S5(r):e;n&&(r&&zl.add(r),I0=I0.then(async()=>{t&&w.getState().showSettings&&w.getState().showToast("关闭设置后将提示导入配置","info"),await M5();const a=N5(n,w.getState().settings),o={title:"导入配置",message:a.summary,content:a.notes.length||a.groups.length?p.createElement(P5,{desc:a}):void 0,confirmText:"导入",icon:"info",awaitAction:!0,action:async()=>{try{const i=w.getState(),l=JSON.stringify(Me(i.settings));i.setSettings(await T5(i.settings,n));const c=JSON.stringify(Me(w.getState().settings))!==l;i.showToast(c?"配置已导入":"链接中的配置未生效(已存在相同配置或受当前部署限制)",c?"success":"info")}catch(i){console.error("导入链接中的配置失败:",i),w.getState().showToast("导入配置失败","error")}}};w.getState().setConfirmDialog(o),await new Promise(i=>{const l=w.subscribe(c=>{c.confirmDialog!==o&&((c.confirmDialog||c.privacyMode)&&zl.delete(r),l(),i())})})}))}function E5(e){p.useEffect(()=>{if(!De||!e)return;const t=()=>void Hb().then(n=>Wl(n),()=>{}),r=[_o().onFocusChanged(({payload:n})=>{n&&t()}),w5(n=>n.forEach(a=>Wl(a,!0)))];return C0||(C0=!0,v5().then(n=>n==null?void 0:n.forEach(a=>Wl(a,!0))).catch(n=>console.warn("读取启动链接失败:",n))),t(),()=>{for(const n of r)n.then(a=>a())}},[e])}const Cg="CookSleep/gpt_image_playground",Ac=`https://github.com/${Cg}/releases`,R5=`https://github.com/${Cg}/blob/main/LICENSE`,Vb=10,Kb=3600*1e3,Xb=60*1e3;function _5(e){return`https://api.github.com/repos/${Cg}/releases?per_page=${Vb}&page=${e}`}function Cs(e,t){const r=i=>i.trim().replace(/^v/i,"").split(/[-+]/)[0].split(".").map(l=>Number.parseInt(l,10)||0),n=r(e),a=r(t),o=Math.max(n.length,a.length);for(let i=0;i<o;i+=1){const l=(n[i]??0)-(a[i]??0);if(l!==0)return l}return 0}function D5(e){if(!e||typeof e!="object")return null;const t=e;if(t.draft===!0||t.prerelease===!0)return null;const r=typeof t.tag_name=="string"?t.tag_name.trim():"";return r?{tag:r,version:r.replace(/^v/i,""),body:typeof t.body=="string"?t.body:"",publishedAt:typeof t.published_at=="string"?t.published_at:"",url:typeof t.html_url=="string"&&t.html_url.startsWith("https://")?t.html_url:`${Ac}/tag/${encodeURIComponent(r)}`}:null}function L5(e,t){var o,i;const r=e.split(/\r?\n/),n=r.findIndex(l=>l.trim()),a=(o=r[n])==null?void 0:o.match(/^\s*#{1,6}\s+(.*)$/);return!a||!((i=a[1].match(/\d+(?:\.\d+)*/g))!=null&&i.includes(t))?e:r.slice(n+1).join(`
|
|
68
|
+
`).replace(/^(\s*\n)+/,"")}function qb(e){if(!Array.isArray(e))throw new Error("Release 数据格式不正确");return{rawCount:e.length,releases:e.map(D5).filter(t=>t!==null)}}function Jb(e,t,r,n){const a=t===1||!e?[]:e.releases,o=new Set(a.map(i=>i.tag));return{fetchedAt:t===1||!e?n:e.fetchedAt,pages:t,hasMore:r.rawCount>=Vb,releases:[...a,...r.releases.filter(i=>!o.has(i.tag))]}}function Gb(e){if(!e)return null;try{const t=JSON.parse(e);if(typeof t.fetchedAt!="number"||typeof t.pages!="number"||!Array.isArray(t.releases))return null;const r=qb(t.releases.map(n=>({tag_name:n==null?void 0:n.tag,body:n==null?void 0:n.body,published_at:n==null?void 0:n.publishedAt,html_url:n==null?void 0:n.url}))).releases;return{fetchedAt:t.fetchedAt,pages:t.pages,hasMore:t.hasMore===!0,releases:r}}catch{return null}}function O5(e,t,r=Kb){return!!(e&&e.pages>0&&t>=e.fetchedAt&&t-e.fetchedAt<r)}function Zb(e,t,r){return!e||Cs(e.version,t)<=0?!1:!r||Cs(e.version,r)>0}function Qi(e){try{return De?lf.getItem(e):localStorage.getItem(e)}catch{return null}}function el(e,t){try{De?lf.setItem(e,t):localStorage.setItem(e,t)}catch(r){console.warn(`保存本地记录失败(${e}):`,r)}}const Pc="release-cache-v1",Qb="ignored-release-version",er=Mi(()=>({releases:[],pages:0,hasMore:!1,ignoredVersion:Qi(Qb)??"",modalOpen:!1,checkError:""})),Bo=p.createRef();async function ey(e){const t=await Dr(_5(e),{headers:{Accept:"application/vnd.github+json"}});if(t.status===403||t.status===429)throw new Error("GitHub 请求过于频繁,请稍后再试");if(!t.ok)throw new Error(`HTTP ${t.status}`);return qb(await t.json())}function Hl(e){er.setState({releases:e.releases,pages:e.pages,hasMore:e.hasMore,checkError:""})}let Zd=null;function Tc(e=Kb){return Zd??(Zd=(async()=>{const t=Gb(Qi(Pc));if(O5(t,Date.now(),e))return Hl(t),t.releases[0];try{const r=Jb(null,1,await ey(1),Date.now());return el(Pc,JSON.stringify(r)),Hl(r),r.releases[0]}catch(r){throw t&&Hl(t),er.setState({checkError:r instanceof Error?r.message:String(r)}),r}})().finally(()=>{Zd=null})),Zd}let Qd=null;function B5(){return Qd??(Qd=(async()=>{var r;const e=((r=Gb(Qi(Pc)))==null?void 0:r.fetchedAt)??Date.now(),t=er.getState().releases.length;for(;;){const n=er.getState(),a=Jb({fetchedAt:e,pages:n.pages,hasMore:n.hasMore,releases:n.releases},n.pages+1,await ey(n.pages+1),Date.now());if(el(Pc,JSON.stringify(a)),Hl(a),a.releases.length>t||!a.hasMore)return}})().finally(()=>{Qd=null})),Qd}function U5(e){el(Qb,e),er.setState({ignoredVersion:e})}function Fa(e){er.setState({modalOpen:e})}let j0=!1;function F5(e){p.useEffect(()=>{!e||j0||(j0=!0,Tc().catch(t=>console.warn("检查更新失败:",t)))},[e])}const ty="save-location-asked";function ry(){el(ty,"1")}let eu=null;async function $5(){const e=await ub().catch(t=>(console.warn("读取默认保存地址失败:",t),typeof t=="string"?t:"读取失败"));return await new Promise(t=>{const r=o=>{ry(),cb(o==="default"),w.getState().setSettings({saveLocationMode:o}),t(!0)},n={title:"选择保存方式",message:`保存图片和备份时,「每次询问」会弹出窗口选择保存位置;「默认地址」直接保存到下方地址,遇到同名文件自动加序号,不会覆盖。
|
|
69
|
+
选择之后可在「设置 → 习惯配置」中更改。`,content:s.jsx("div",{"data-selectable-text":!0,className:"break-all rounded-xl bg-black/[0.03] px-3 py-2 text-xs leading-relaxed text-gray-600 dark:bg-white/[0.04] dark:text-gray-300",children:e}),buttons:[{label:"每次询问",tone:"secondary",action:()=>r("ask")},{label:"默认地址",tone:"primary",action:()=>r("default")}]};w.getState().setConfirmDialog(n);const a=w.subscribe(o=>{o.confirmDialog!==n&&(a(),t(!1))})})}function z5(){p.useEffect(()=>{if(De)return d0(async()=>Qi(ty)||w.getState().settings.saveLocationMode==="default"?!0:(eu??(eu=$5().finally(()=>{eu=null})),await eu)),()=>d0(null)},[])}let Po=null;function ss(){return"classicScrollbar"in document.documentElement.dataset?(Po!=null&&Po.isConnected||(Po=document.querySelector("[data-page-scroll]")),Po??window):window}function tn(){const e=ss();return e instanceof Window?e.scrollY:e.scrollTop}let ny=!1;function S0(e){ny=e}function W5(){const e=w(t=>t.settings.privacyModeShortcut);p.useEffect(()=>{if(!e)return;const t=r=>{ny||r.isComposing||hf(r)!==e||(r.preventDefault(),r.stopPropagation(),!r.repeat&&(w.getState().togglePrivacyMode(),w.getState().privacyMode&&(Fa(!1),ss().scrollTo({top:0}))))};return window.addEventListener("keydown",t,!0),()=>window.removeEventListener("keydown",t,!0)},[e])}function sy(){const e=w(r=>r.tasks),t=w(r=>r.privacyMode);return p.useMemo(()=>t?e.filter(r=>!vc(t,r)):e,[e,t])}function ay(){const e=w(r=>r.agentConversations),t=w(r=>r.privacyMode);return p.useMemo(()=>t?e.filter(r=>!mb(t,r)):e,[e,t])}const N0={platform:"string",os:"string",language:"string",version:"version",imageCount:"number",taskCount:"number",standalone:"boolean",now:"date"},H5="16 / 9",Hs=e=>typeof e=="string"?e.trim():"",Si=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function oy(e,t="",r=0){const n=`${t} ${e}`;return/android/i.test(n)?"android":/iphone|ipad|ipod|\bios\b/i.test(n)||/macintosh/i.test(e)&&r>1?"ios":/windows|win32|win64/i.test(n)?"windows":/mac/i.test(n)?"macos":/linux|x11|cros/i.test(n)?"linux":"other"}class iy extends Error{}const na=e=>{throw new iy(e)};function To(e,t,r){return e==="version"||e==="date"?Uo(e,t,r)===0:(typeof r!=typeof t&&na(`类型不符:${JSON.stringify(r)}`),t===r)}function Uo(e,t,r){if(e==="version"&&typeof r=="string"&&/^v?\d+(\.\d+)*$/.test(r))return Cs(String(t),r);if(e==="number"&&typeof r=="number"&&Number.isFinite(r))return t-r;if(e==="date"&&typeof r=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(r)){const n=Date.parse(r);if(!Number.isNaN(n))return Date.parse(String(t))-n}return na(`无法比较:${JSON.stringify(r)}`)}function Y5(e,t,r){if(Array.isArray(r))return r.map(a=>To(e,t,a)).some(Boolean);if(!Si(r))return To(e,t,r);const n=Object.entries(r);return n.length||na("比较对象为空"),n.map(([a,o])=>{switch(a){case"eq":return To(e,t,o);case"ne":return!To(e,t,o);case"in":return Array.isArray(o)?o.map(i=>To(e,t,i)).some(Boolean):na("in 需要数组");case"gt":return Uo(e,t,o)>0;case"gte":return Uo(e,t,o)>=0;case"lt":return Uo(e,t,o)<0;case"lte":return Uo(e,t,o)<=0;default:return na(`未知运算符:${a}`)}}).every(Boolean)}const tu=(e,t)=>(Array.isArray(e)?e:[e]).map(r=>ly(r,t));function ly(e,t){return Si(e)?Object.entries(e).map(([r,n])=>{if(r==="all")return tu(n,t).every(Boolean);if(r==="any")return tu(n,t).some(Boolean);if(r==="not")return!tu(n,t).every(Boolean);if(!Object.prototype.hasOwnProperty.call(N0,r))return na(`未知变量:${r}`);const a=r;return Y5(N0[a],t[a],n)}).every(Boolean):na(`条件需为对象:${JSON.stringify(e)}`)}const A0=new Set;function V5(e,t,r=""){if(e===void 0)return!0;try{return ly(e,t)}catch(n){if(!(n instanceof iy))throw n;const a=`公告 ${r} 的显示条件无效:${n.message}`;return A0.has(a)||(A0.add(a),console.warn(a)),!1}}function K5(e,t){if(!Si(e))return;const r=e.type,n=Hs(e.src);if(r!=="html"&&r!=="image"||!n||n.startsWith("/"))return;let a;try{a=new URL(n,t)}catch{return}if(a.origin!==new URL(t).origin)return;const o=Hs(e.aspectRatio).match(/^(\d+(?:\.\d+)?)\s*[/:]\s*(\d+(?:\.\d+)?)$/),i=o&&Number(o[1])>0&&Number(o[2])>0?`${o[1]} / ${o[2]}`:H5;return{type:r,src:a.href,aspectRatio:i}}function X5(e,t){if(!Si(e))return null;const r=Hs(e.id),n=Hs(e.title);if(!r||!n||typeof e.content!="string")return null;const a={id:r,title:n,content:e.content},o=Hs(e.note);o&&(a.note=o),e.when!==void 0&&(a.when=e.when);const i=Si(e.action)?e.action:null,l=Hs(i==null?void 0:i.label),c=Hs(i==null?void 0:i.url);l&&/^https?:\/\//i.test(c)&&(a.action={label:l,url:c});const u=K5(e.media,t);return u&&(a.media=u),a}function q5(e,t){if(!Array.isArray(e))return[];const r=new Set,n=[];for(const a of e){const o=X5(a,t);!o||r.has(o.id)||(r.add(o.id),n.push(o))}return n}function J5(e,t,r){return e.filter(n=>!r.includes(n.id)&&V5(n.when,t,n.id))}function G5(e){if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}catch{return[]}}const gs=[];let Z5=0;function Q5(e){e.key==="Escape"&&gs.length!==0&&(e.preventDefault(),gs[gs.length-1].handler())}let P0=!1;function eS(){P0||(P0=!0,window.addEventListener("keydown",Q5))}function Kr(e,t){const r=p.useRef(null),n=p.useRef(t);n.current=t,p.useEffect(()=>{if(!e){if(r.current!==null){const o=gs.findIndex(i=>i.id===r.current);o!==-1&&gs.splice(o,1),r.current=null}return}eS();const a=Z5++;return r.current=a,gs.push({id:a,handler:()=>n.current()}),()=>{const o=gs.findIndex(i=>i.id===a);o!==-1&&gs.splice(o,1),r.current=null}},[e])}let Mo=0,T0="",M0="",E0="";function R0(e,t){if(!(e instanceof Node)||!t)return null;const r=Array.isArray(t)?t:[t];for(const n of r){const a=n.current;if(a!=null&&a.contains(e))return a}return null}function _0(e,t,r){if(r===0)return!1;const n=window.getComputedStyle(e),a=t==="y"?n.overflowY:n.overflowX;return/(auto|scroll|overlay)/.test(a)?t==="y"?e.scrollHeight<=e.clientHeight?!1:r<0?e.scrollTop>0:e.scrollTop+e.clientHeight<e.scrollHeight-1:e.scrollWidth<=e.clientWidth?!1:r<0?e.scrollLeft>0:e.scrollLeft+e.clientWidth<e.scrollWidth-1:!1}function tS(e,t){return _0(e,"y",t.y)||_0(e,"x",t.x)}function rS(e){return e instanceof HTMLElement?e:e instanceof Node?e.parentElement:null}function D0(e,t,r){let n=rS(t);for(;n&&e.contains(n);){if(tS(n,r))return!0;if(n===e)break;n=n.parentElement}return!1}function Lr(e,t){p.useEffect(()=>{if(!e)return;Mo===0&&(T0=document.body.style.overflow,M0=document.body.style.overscrollBehavior,E0=document.documentElement.style.overscrollBehavior,document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",document.documentElement.style.overscrollBehavior="none"),Mo+=1;let r=0,n=0;const a=l=>{const c=R0(l.target,t);(!c||!D0(c,l.target,{x:l.deltaX,y:l.deltaY}))&&l.preventDefault()},o=l=>{const c=l.touches[0];c&&(r=c.clientX,n=c.clientY)},i=l=>{const c=l.touches[0],u=R0(l.target,t);if(!c||!u){l.preventDefault();return}const f={x:r-c.clientX,y:n-c.clientY};r=c.clientX,n=c.clientY,D0(u,l.target,f)||l.preventDefault()};return document.addEventListener("wheel",a,{capture:!0,passive:!1}),document.addEventListener("touchstart",o,{capture:!0,passive:!0}),document.addEventListener("touchmove",i,{capture:!0,passive:!1}),()=>{document.removeEventListener("wheel",a,{capture:!0}),document.removeEventListener("touchstart",o,{capture:!0}),document.removeEventListener("touchmove",i,{capture:!0}),Mo=Math.max(0,Mo-1),Mo===0&&(document.body.style.overflow=T0,document.body.style.overscrollBehavior=M0,document.documentElement.style.overscrollBehavior=E0)}},[e,t])}function zr(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function _r(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function cy(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function qt(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}function nS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 3H3v5m13-5h5v5M8 21H3v-5m18 0v5h-5"})})}function sS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 8h5V3m8 0v5h5M3 16h5v5m8 0v-5h5"})})}function Nd(e){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function aS(e){return s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...e,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("polyline",{points:"19 12 12 19 5 12"})]})}function dy(e){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",...e,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function jg(e){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",...e,children:s.jsx("polyline",{points:"9 18 15 12 9 6"})})}function oS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})}function iS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"})})}function qs(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})}function Hr(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function Go(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function uy(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})})}function ma(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})})}function Sg(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"})})}function lS(e){return s.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",...e,children:s.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function L0(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6a2 2 0 012-2h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM9 4v16"})})}function as({filled:e,...t}){return s.jsx("svg",{fill:e?"currentColor":"none",stroke:"currentColor",viewBox:"0 0 24 24",...t,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})}function no(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8h16M4 16h16"})})}function fy(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})})}function cS(e){return s.jsxs("svg",{fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",...e,children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("polyline",{points:"7 10 12 15 17 10"}),s.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})}function dS(e){return s.jsxs("svg",{fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",...e,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("path",{d:"M8 21h8M12 17v4"}),s.jsx("path",{d:"M12 6.5v6M9 9.5l3 3 3-3"})]})}function uS(e){return s.jsxs("svg",{fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",...e,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]})}function fS(e){return s.jsxs("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function gS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function mS(e){return s.jsxs("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4h16v16H4z"}),s.jsx("path",{fill:"currentColor",fillOpacity:.6,stroke:"none",d:"M4 4h8v8H4zM12 12h8v8h-8z"})]})}function hS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.53 16.12a3 3 0 00-5.78 1.13 2.25 2.25 0 01-2.4 2.25 4.5 4.5 0 008.4-2.25c0-.4-.08-.78-.22-1.13zm0 0a15.998 15.998 0 003.39-1.62m-5.04-.03a15.994 15.994 0 011.62-3.39m3.42 3.42a15.995 15.995 0 004.76-4.65l3.88-5.81a1.15 1.15 0 00-1.6-1.6l-5.81 3.88a15.996 15.996 0 00-4.65 4.76m3.42 3.42a6.776 6.776 0 00-3.42-3.42"})})}function pS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"})})}function gy({d:e,viewBox:t="0 0 24 24",...r}){return s.jsx("svg",{fill:"currentColor",fillRule:"evenodd",viewBox:t,"aria-hidden":"true",...r,children:s.jsx("path",{clipRule:"evenodd",d:e})})}function xS(e){return s.jsx(gy,{...e,d:"M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0V10.95h3V5h17.998v5.949zM6 10.949h1.488V8.102H6v2.847zm10.51 0H18V8.102h-1.49v2.847z"})}function bS(e){return s.jsx(gy,{...e,d:"M8.086.457a6.105 6.105 0 013.046-.415c1.333.153 2.521.72 3.564 1.7a.117.117 0 00.107.029c1.408-.346 2.762-.224 4.061.366l.063.03.154.076c1.357.703 2.33 1.77 2.918 3.198.278.679.418 1.388.421 2.126a5.655 5.655 0 01-.18 1.631.167.167 0 00.04.155 5.982 5.982 0 011.578 2.891c.385 1.901-.01 3.615-1.183 5.14l-.182.22a6.063 6.063 0 01-2.934 1.851.162.162 0 00-.108.102c-.255.736-.511 1.364-.987 1.992-1.199 1.582-2.962 2.462-4.948 2.451-1.583-.008-2.986-.587-4.21-1.736a.145.145 0 00-.14-.032c-.518.167-1.04.191-1.604.185a5.924 5.924 0 01-2.595-.622 6.058 6.058 0 01-2.146-1.781c-.203-.269-.404-.522-.551-.821a7.74 7.74 0 01-.495-1.283 6.11 6.11 0 01-.017-3.064.166.166 0 00.008-.074.115.115 0 00-.037-.064 5.958 5.958 0 01-1.38-2.202 5.196 5.196 0 01-.333-1.589 6.915 6.915 0 01.188-2.132c.45-1.484 1.309-2.648 2.577-3.493.282-.188.55-.334.802-.438.286-.12.573-.22.861-.304a.129.129 0 00.087-.087A6.016 6.016 0 015.635 2.31C6.315 1.464 7.132.846 8.086.457zm-.804 7.85a.848.848 0 00-1.473.842l1.694 2.965-1.688 2.848a.849.849 0 001.46.864l1.94-3.272a.849.849 0 00.007-.854l-1.94-3.393zm5.446 6.24a.849.849 0 000 1.695h4.848a.849.849 0 000-1.696h-4.848z"})}function yS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"})})}function vS(){const[e,t]=p.useState(window.innerWidth<640);return p.useEffect(()=>{const r=()=>t(window.innerWidth<640);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function wS({appMode:e,isFavoriteCollectionOverview:t=!1,onClose:r}){const n=vS(),a=p.useRef(null),o=e==="agent";return Kr(!0,r),Lr(!0,a),lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[100] flex items-center justify-center p-4",onClick:r,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{ref:a,className:"relative z-10 w-full max-w-md rounded-3xl border border-white/50 bg-white/95 p-5 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex flex-col max-h-[85vh] custom-scrollbar",onClick:i=>i.stopPropagation(),children:[s.jsxs("div",{className:"mb-5 flex items-center justify-between gap-4",children:[s.jsxs("h3",{className:"text-base font-semibold text-gray-800 dark:text-gray-100 flex items-center gap-2",children:[s.jsxs("svg",{className:"w-5 h-5 text-blue-500",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("path",{d:"M12 17h.01"})]}),"操作指南"]}),s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("button",{onClick:r,className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto overscroll-contain mb-6 text-sm text-gray-600 dark:text-gray-300 space-y-6 custom-scrollbar pr-2",children:[o?s.jsx(s.Fragment,{children:s.jsx("section",{children:s.jsx("div",{className:"space-y-4",children:s.jsxs("ul",{className:"list-disc pl-4 space-y-2",children:[s.jsx("li",{children:"需要使用 Responses API 配置。"}),s.jsxs("li",{children:["如需 Agent 搜索互联网或读取 URL 内容,可在",s.jsx("strong",{className:"font-semibold",children:"「设置 → Agent 配置」"}),"中开启“网络搜索”。"]}),s.jsxs("li",{children:["输入 ",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"@"})," 可引用参考图或前面轮次生成的图片;Agent 也会自行参考上下文中的图片。"]}),s.jsx("li",{children:"编辑某轮消息重新发送,或重新生成某轮消息,会产生可切换的分支。"}),s.jsx("li",{children:"生成的图片会同步到画廊;删除对话默认不会删除画廊中的任务。"})]})})})}):t?s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h7"})}),"多选收藏夹"]}),s.jsx("div",{className:"space-y-4",children:n?s.jsxs("p",{children:["在收藏夹卡片上",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"左右滑动"}),"即可选中或取消选中该卡片。"]}):s.jsxs("ul",{className:"list-disc pl-4 space-y-2",children:[s.jsxs("li",{children:["使用鼠标在空白处",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"拖拽框选"}),"收藏夹卡片。"]}),s.jsxs("li",{children:["按住 ",s.jsx("kbd",{className:"px-1.5 py-0.5 rounded-md bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-xs font-sans",children:"Ctrl"})," 或 ",s.jsx("kbd",{className:"px-1.5 py-0.5 rounded-md bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-xs font-sans",children:"⌘"})," 并点击卡片,可添加或移除单项。"]}),s.jsx("li",{children:"再次框选已选中的卡片会将其取消选中。"}),s.jsx("li",{children:"点击卡片外任意空白处可取消所有选择。"})]})})]}),s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"批量操作"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("p",{children:["选中一个或多个收藏夹后,页面底部会出现操作栏,支持",s.jsx("strong",{className:"text-gray-500 dark:text-gray-400 font-medium",children:"取消选择"}),"、",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"全选收藏夹"}),"、",s.jsx("strong",{className:"text-purple-500 dark:text-purple-400 font-medium",children:"反选收藏夹"}),"、",s.jsx("strong",{className:"text-green-500 dark:text-green-400 font-medium",children:"下载选中"}),",和",s.jsx("strong",{className:"text-red-500 dark:text-red-400 font-medium",children:"删除选中"}),"。"]})})]})]}):n?s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h7"})}),"多选任务"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("p",{children:["在历史任务卡片上",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"左右滑动"}),"即可选中或取消选中该卡片。"]})})]}),s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"批量操作"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("p",{children:["选中一个或多个任务后,页面底部会出现操作栏,支持",s.jsx("strong",{className:"text-gray-500 dark:text-gray-400 font-medium",children:"取消选择"}),"、",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"全选任务"}),"、",s.jsx("strong",{className:"text-purple-500 dark:text-purple-400 font-medium",children:"反选任务"}),"、",s.jsx("strong",{className:"text-yellow-500 dark:text-yellow-400 font-medium",children:"编辑收藏夹"}),"、",s.jsx("strong",{className:"text-green-500 dark:text-green-400 font-medium",children:"下载选中"}),",和",s.jsx("strong",{className:"text-red-500 dark:text-red-400 font-medium",children:"删除选中"}),"。"]})})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h7"})}),"多选任务"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("ul",{className:"list-disc pl-4 space-y-2",children:[s.jsxs("li",{children:["使用鼠标在空白处",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"拖拽框选"}),"。"]}),s.jsxs("li",{children:["按住 ",s.jsx("kbd",{className:"px-1.5 py-0.5 rounded-md bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-xs font-sans",children:"Ctrl"})," 或 ",s.jsx("kbd",{className:"px-1.5 py-0.5 rounded-md bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-xs font-sans",children:"⌘"})," 并点击卡片,可添加或移除单项。"]}),s.jsx("li",{children:"再次框选已选中的卡片会将其取消选中。"}),s.jsx("li",{children:"点击卡片外任意空白处可取消所有选择。"})]})})]}),s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"批量操作"]}),s.jsx("div",{className:"space-y-4",children:s.jsxs("p",{children:["选中一个或多个任务后,页面底部会出现操作栏,支持",s.jsx("strong",{className:"text-gray-500 dark:text-gray-400 font-medium",children:"取消选择"}),"、",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"全选任务"}),"、",s.jsx("strong",{className:"text-purple-500 dark:text-purple-400 font-medium",children:"反选任务"}),"、",s.jsx("strong",{className:"text-yellow-500 dark:text-yellow-400 font-medium",children:"编辑收藏夹"}),"、",s.jsx("strong",{className:"text-green-500 dark:text-green-400 font-medium",children:"下载选中"}),",和",s.jsx("strong",{className:"text-red-500 dark:text-red-400 font-medium",children:"删除选中"}),"。"]})})]})]}),s.jsxs("section",{children:[s.jsxs("h4",{className:"mb-4 text-sm font-medium text-gray-800 dark:text-gray-200 flex items-center gap-1.5",children:[s.jsx(ma,{className:"w-4 h-4 text-gray-400 dark:text-gray-500"}),"导入配置链接"]}),s.jsx("ul",{className:"list-disc pl-4 space-y-2",children:De?s.jsxs(s.Fragment,{children:[s.jsxs("li",{children:["在浏览器或其他地方",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"复制导入链接"}),"后切回客户端,客户端会提示导入,确认后才会导入。"]}),s.jsxs("li",{children:["点击 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 text-[0.85em] text-gray-700 dark:bg-white/[0.06] dark:text-gray-200",children:"gpt-image-playground://"})," 开头的链接可以直接唤起客户端并提示导入。"]})]}):s.jsxs("li",{children:["打开带有配置参数的",s.jsx("strong",{className:"text-blue-500 dark:text-blue-400 font-medium",children:"导入链接"}),"时,页面会先提示导入,确认后才会导入。"]})})]})]}),s.jsx("div",{className:"pt-4 border-t border-gray-200 dark:border-white/[0.08] flex justify-center",children:s.jsxs("a",{href:"https://github.com/CookSleep/gpt_image_playground",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm font-medium text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors group",children:[s.jsx("svg",{className:"w-5 h-5 group-hover:scale-110 transition-transform",viewBox:"0 0 24 24",fill:"currentColor",children:s.jsx("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"})}),"@CookSleep"]})})]})]}),document.body)}function Sl({tooltip:e,className:t,disabled:r=!1,onClick:n,onMouseDown:a,children:o}){const i=Ot();return s.jsxs("span",{className:"relative inline-flex",...i.handlers,children:[s.jsx("button",{type:"button",className:t,disabled:r,"aria-label":e,onClick:l=>{i.dismiss(),n==null||n(l)},onMouseDown:l=>{i.dismiss(),a==null||a(l)},children:o}),s.jsx(pt,{visible:i.visible,className:"whitespace-nowrap",children:e})]})}function kS(e){const t=new Date(e),r=new Date,n=new Date(r.getFullYear(),r.getMonth(),r.getDate()).getTime(),a=n-1440*60*1e3,o=r.getDay()||7,i=n-(o-1)*24*60*60*1e3,l=t.getTime();return l>=n?"今天":l>=a?"昨天":l>=i?"本周":"更早"}function IS(e){const t=new Date(e),r=new Date,n=t.getFullYear()===r.getFullYear();return new Intl.DateTimeFormat("zh-CN",{...n?{}:{year:"numeric"},month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).format(t).replace(/\//g,"-")}function CS({onClose:e,ignoreOutsideClickRef:t}){const r=ay(),n=w(R=>R.activeAgentConversationId),a=w(R=>R.setActiveAgentConversationId),o=w(R=>R.renameAgentConversation),i=w(R=>R.deleteAgentConversation),l=w(R=>R.setConfirmDialog),c=w(R=>!!R.confirmDialog),u=w(R=>R.setAppMode),f=w(R=>R.tasks),d=w(R=>R.agentGeneratingTitleIds),g=w(R=>R.agentEditingConversationId),m=w(R=>R.setAgentEditingConversationId),[x,b]=p.useState(""),[h,y]=p.useState("");p.useEffect(()=>{if(g){const R=r.find(U=>U.id===g);R&&b(R.title)}},[g,r]),p.useEffect(()=>()=>{m(null)},[m]);const v=p.useMemo(()=>[...r].sort((R,U)=>U.updatedAt-R.updatedAt),[r]),I=p.useMemo(()=>{const R=h.trim().toLocaleLowerCase();return R?v.filter(U=>ux(U).includes(R)):v},[h,v]),S=R=>{g||(u("agent"),a(R),e())},k=(R,U,W)=>{R.stopPropagation(),!d[U]&&(m(U),b(W))},j=()=>{g&&x.trim()&&!d[g]&&o(g,x.trim()),m(null)},A=R=>{R.key==="Enter"?(R.preventDefault(),j()):R.key==="Escape"&&(R.preventDefault(),m(null))},N=(R,U)=>{R.stopPropagation();const W=r.find(J=>J.id===U)??null,F=n2(W,f),_=new Set(F),O=new Set(f.filter(J=>_.has(J.id)).flatMap(J=>J.outputImages||[])).size;l({title:"删除对话",message:"确定要删除这个 Agent 对话吗?",checkbox:F.length>0?{label:O>0?`同时删除对话中生成的图片(${O} 张)和关联任务`:`同时删除对话关联任务(${F.length} 个)`,tone:"danger"}:void 0,action:async(J=!1)=>{J&&F.length>0&&await Zi(F),i(U),r.length<=1&&e()}})},C=p.useRef(null);p.useEffect(()=>{const R=U=>{var W;c||(W=t==null?void 0:t.current)!=null&&W.contains(U.target)||C.current&&!C.current.contains(U.target)&&e()};return document.addEventListener("mousedown",R,{capture:!0}),document.addEventListener("touchstart",R,{capture:!0}),()=>{document.removeEventListener("mousedown",R,{capture:!0}),document.removeEventListener("touchstart",R,{capture:!0})}},[c,t,e]);const T={};for(const R of I){const U=kS(R.updatedAt);T[U]||(T[U]=[]),T[U].push(R)}return s.jsxs("div",{ref:C,className:"absolute top-12 left-0 w-80 sm:w-96 max-w-[calc(100vw-2rem)] max-h-[70vh] bg-white dark:bg-[#1c1c1e] rounded-xl shadow-2xl overflow-hidden flex flex-col border border-gray-200 dark:border-white/10 z-50 text-gray-900 dark:text-gray-200 animate-dropdown-down",children:[s.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-gray-200 dark:border-white/10 shrink-0",children:[s.jsx("input",{type:"text",placeholder:"搜索聊天...",value:h,onChange:R=>y(R.target.value),className:"flex-1 bg-transparent border-none outline-none text-sm px-2 text-gray-900 dark:text-white placeholder-gray-400"}),s.jsx(Sl,{tooltip:"关闭",onClick:e,className:"p-1 hover:bg-gray-100 dark:hover:bg-white/10 rounded-lg text-gray-500 dark:text-gray-400 transition-colors",children:s.jsx(qt,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-1 overscroll-contain",children:[I.length===0&&s.jsx("div",{className:"px-3 py-8 text-center text-sm text-gray-500",children:"没有找到匹配的聊天"}),Object.entries(T).map(([R,U])=>s.jsxs("div",{children:[s.jsx("div",{className:"mt-4 mb-1 px-3 text-xs font-medium text-gray-500",children:R}),U.map(W=>s.jsxs("div",{className:"group flex h-14 items-center justify-between gap-2 rounded-lg px-3 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors cursor-pointer",onClick:()=>S(W.id),children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[s.jsx("svg",{className:"w-4 h-4 shrink-0 opacity-80",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),g===W.id?s.jsx("input",{type:"text",className:"h-7 flex-1 bg-white dark:bg-black/20 border border-blue-400/50 dark:border-white/20 rounded px-1.5 py-0 text-sm leading-7 outline-none text-gray-900 dark:text-white focus:border-blue-500 dark:focus:border-white/40 shadow-sm min-w-0",value:x,onChange:F=>b(F.target.value),onKeyDown:A,onClick:F=>F.stopPropagation(),autoFocus:!0,onBlur:j}):s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`text-sm truncate ${W.id===n?"text-gray-900 dark:text-white font-medium":"text-gray-600 dark:text-gray-300"}`,children:W.title}),s.jsx("div",{className:"hidden sm:block mt-0.5 text-[11px] leading-none text-gray-500",children:IS(W.updatedAt)})]})]}),s.jsx("div",{className:`flex shrink-0 items-center justify-end gap-1 overflow-hidden transition-all duration-150 ${g===W.id?"w-7 opacity-100":"w-0 opacity-0 group-hover:w-16 group-hover:opacity-100 group-focus-within:w-16 group-focus-within:opacity-100"}`,children:g===W.id?s.jsx(Sl,{tooltip:"确认",onClick:F=>F.stopPropagation(),onMouseDown:F=>{F.preventDefault(),F.stopPropagation(),j()},className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-green-500 dark:text-green-400 hover:text-green-600 dark:hover:text-green-300 transition-colors",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}):s.jsxs(s.Fragment,{children:[s.jsx(Sl,{tooltip:"重命名",onClick:F=>k(F,W.id,W.title),className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-white disabled:text-gray-300 disabled:hover:text-gray-300 dark:disabled:text-gray-600 dark:disabled:hover:text-gray-600 disabled:hover:bg-transparent disabled:cursor-not-allowed transition-colors",disabled:!!d[W.id],children:s.jsx(Hr,{className:"w-3.5 h-3.5"})}),s.jsx(Sl,{tooltip:"删除",onClick:F=>N(F,W.id),className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-gray-400 hover:text-red-500 dark:hover:text-red-400 transition-colors",children:s.jsx(_r,{className:"w-3.5 h-3.5"})})]})})]},W.id))]},R))]})]})}function jS({containerSelector:e,itemSelector:t,getItemId:r,onSelectionChange:n,initialSelectedIds:a=[],onSuppressClick:o}){const[i,l]=p.useState(null),c=p.useRef(!1),u=p.useRef(null),f=p.useRef(null),d=p.useRef(!1),g=p.useRef(null),m=p.useRef(null),x=p.useRef(!1),b=p.useRef(!1),h=p.useRef([]),y=/Mac|iPod|iPhone|iPad/.test(navigator.platform),v=p.useCallback((k,j)=>({pageX:k+window.scrollX,pageY:j+tn()}),[]),I=p.useCallback((k,j,A,N)=>{const C=v(j,A);x.current=!!k.closest(t),b.current=N,h.current=[...a],c.current=!0,d.current=!1,u.current=C,f.current={x:j,y:A},document.body.classList.add("select-none"),document.body.classList.add("drag-selecting"),l({startPageX:C.pageX,startPageY:C.pageY,currentPageX:C.pageX,currentPageY:C.pageY})},[v,a,t]),S=p.useCallback((k,j)=>{const A=u.current;if(!A)return;const N=Math.min(A.pageX,k),C=Math.max(A.pageX,k),T=Math.min(A.pageY,j),R=Math.max(A.pageY,j),U=document.querySelectorAll(e),W=tn(),F=new Set(h.current),_=new Set(h.current);U.forEach(O=>{O.querySelectorAll(t).forEach(H=>{const K=H.getBoundingClientRect(),te=r(H);if(!te)return;const P=K.left+window.scrollX,B=K.right+window.scrollX,$=K.top+W,Q=K.bottom+W;N<B&&C>P&&T<Q&&R>$?_.has(te)?F.delete(te):F.add(te):_.has(te)||F.delete(te)})}),n(Array.from(F))},[e,r,t,n]);return p.useEffect(()=>{const k=()=>{g.current&&(clearInterval(g.current),g.current=null),m.current=null},j=F=>{g.current&&m.current===F||(k(),m.current=F,g.current=window.setInterval(()=>{ss().scrollBy({top:F*15,behavior:"instant"})},16))},A=(F=!1,_=!1)=>{c.current&&(document.body.classList.remove("select-none"),document.body.classList.remove("drag-selecting")),c.current&&F&&!d.current&&!x.current&&!b.current&&n([]),_&&d.current&&(o==null||o()),k(),c.current=!1,u.current=null,f.current=null,l(null)},N=F=>F.target instanceof Element?F.target:document.elementFromPoint(F.clientX,F.clientY),C=F=>{if(F.button!==0)return;const _=N(F);if(!_||!_.closest(e)||_.closest("[data-input-bar]")||_.closest("[data-no-drag-select], [data-lightbox-root]"))return;const O=_.closest('button, a, input, textarea, select, [draggable="true"]');if(O)return O.closest(".reference-thumb-wrapper"),void 0;const J=y?F.metaKey:F.ctrlKey;I(_,F.clientX,F.clientY,J),F.preventDefault()},T=F=>{if(!c.current||!u.current)return;const _=u.current,O=v(F.clientX,F.clientY);if(f.current={x:F.clientX,y:F.clientY},Math.hypot(O.pageX-_.pageX,O.pageY-_.pageY)<6&&!d.current)return;d.current=!0,l({startPageX:_.pageX,startPageY:_.pageY,currentPageX:O.pageX,currentPageY:O.pageY}),S(O.pageX,O.pageY),F.preventDefault();const H=40;F.clientY<H?j(-1):F.clientY>window.innerHeight-H?j(1):k()},R=()=>{if(!c.current||!u.current||!f.current||!d.current)return;const F=v(f.current.x,f.current.y),_=u.current;l({startPageX:_.pageX,startPageY:_.pageY,currentPageX:F.pageX,currentPageY:F.pageY}),S(F.pageX,F.pageY)},U=F=>{if(c.current){if((F.buttons&1)===0){A();return}d.current&&(!F.ctrlKey&&!F.metaKey||F.preventDefault())}},W=()=>{A(!0,!0)};return document.addEventListener("mousedown",C,!0),document.addEventListener("mousemove",T,!0),document.addEventListener("mouseup",W,!0),document.addEventListener("wheel",U,{capture:!0,passive:!1}),window.addEventListener("scroll",R,!0),()=>{k(),document.removeEventListener("mousedown",C,!0),document.removeEventListener("mousemove",T,!0),document.removeEventListener("mouseup",W,!0),document.removeEventListener("wheel",U,!0),window.removeEventListener("scroll",R,!0)}},[I,e,y,t,n,o,S]),{selectionBox:i,isDragging:c.current}}function Ke({tooltip:e,className:t,wrapperClassName:r="relative inline-flex",disabled:n=!1,showOnClick:a=!1,stopPropagation:o=!1,onClick:i,onMouseDown:l,children:c}){const u=Ot();return s.jsxs("span",{className:r,...u.handlers,children:[s.jsx("button",{type:"button",className:t,"aria-label":e,"aria-disabled":n,disabled:n&&!a,onClick:f=>{o&&f.stopPropagation(),a?u.show():u.dismiss(),!n&&(i==null||i(f))},onMouseDown:f=>{u.dismiss(),!n&&(l==null||l(f))},children:c}),s.jsx(pt,{visible:u.visible,className:"whitespace-nowrap",children:e})]})}function SS(e){return s.jsx("svg",{fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",...e,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 7a2 2 0 012-2h4.172a2 2 0 011.414.586L12 7h7a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"})})}function NS({task:e}){var a;const[t,r]=p.useState(""),n=(a=e==null?void 0:e.outputImages)==null?void 0:a[0];return p.useEffect(()=>{if(r(""),!n)return;let o=!1;const i=Nx(n,l=>{o||r(l.src)});return Sx(n).then(l=>{!o&&l&&r(l.src)}).catch(()=>{}),()=>{o=!0,i()}},[n]),t?s.jsx("img",{src:t,alt:"",className:"h-full w-full object-cover"}):s.jsx("div",{className:"flex h-full w-full items-center justify-center bg-yellow-50 text-yellow-500 dark:bg-[#2a2211] dark:text-yellow-500",children:s.jsx(as,{filled:!0,className:"h-8 w-8 opacity-80"})})}function AS({card:e,coverTask:t,isVirtualAll:r,isDefault:n,canDelete:a,isSelected:o,editingId:i,editingName:l,setEditingName:c,confirmRename:u,handleRenameKeyDown:f,startRename:d,handleSetDefault:g,handleDelete:m,onOpen:x,onToggleSelection:b,suppressClickUntilRef:h}){const[y,v]=p.useState(!1),[I,S]=p.useState(!1),[k,j]=p.useState(!1),[A,N]=p.useState(0),C=p.useRef(null),T=p.useRef(null),R=p.useRef(!1),U=p.useRef(0),W=p.useRef(null),F=p.useRef(null),_=p.useRef(0),O=p.useRef(0),J=G=>{_.current=G,C.current&&(C.current.style.transform=G?`translateX(${G}px)`:"")},H=()=>{F.current!=null&&(window.cancelAnimationFrame(F.current),F.current=null)},K=G=>{F.current==null&&_.current===G||(O.current=G,F.current==null&&(F.current=window.requestAnimationFrame(()=>{F.current=null,J(O.current)})))},te=()=>{T.current=null,R.current=!1,v(!1),N(0),j(!1),H(),J(0)},P=G=>{if(G.target.closest("button, a, input, textarea, select")){te();return}W.current!=null&&(window.clearTimeout(W.current),W.current=null),T.current={x:G.touches[0].clientX,y:G.touches[0].clientY},R.current=!1,S(o),j(!1),N(0),H(),J(0),v(!0)},B=G=>{if(!T.current)return;const se=G.touches[0].clientX-T.current.x,Y=G.touches[0].clientY-T.current.y;if(Math.abs(se)>Math.abs(Y)&&Math.abs(se)>10){R.current=!0,G.preventDefault();const le=Math.max(-60,Math.min(60,se));N(le>0?1:le<0?-1:0),j(Math.abs(se)>=40),K(le)}},$=G=>{if(v(!1),H(),N(0),!T.current)return;const se=G.changedTouches[0].clientX-T.current.x;T.current=null;const Y=R.current&&Math.abs(se)>40;R.current=!1,j(Y),W.current=window.setTimeout(()=>{j(!1),W.current=null},220),Y&&(U.current=Date.now()+350,G.preventDefault(),G.stopPropagation(),b())};p.useEffect(()=>()=>{W.current!=null&&window.clearTimeout(W.current),H()},[]),p.useEffect(()=>{y||J(0)},[y]);const Q=k,L=Q?I?"bg-gray-500 dark:bg-gray-600":"bg-blue-500":"bg-gray-200 dark:bg-gray-700";return s.jsxs("div",{className:"relative rounded-xl",children:[s.jsx("div",{className:`absolute inset-0 rounded-xl flex items-center transition-opacity duration-200 pointer-events-none ${y||A!==0||k?"opacity-100":"opacity-0"} ${L} ${A>0?"justify-start pl-6":"justify-end pr-6"}`,children:s.jsx("svg",{className:`w-8 h-8 transition-transform duration-150 ${Q?"scale-110 text-white":"scale-90 text-white/60"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:I&&Q?s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"}):s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),s.jsx("article",{ref:C,className:`relative bg-white dark:bg-gray-900 rounded-xl border overflow-hidden cursor-pointer touch-pan-y will-change-transform duration-200 hover:shadow-lg dark:hover:bg-gray-800/80 ${y?"transition-[box-shadow,border-color,background-color]":"transition-[box-shadow,border-color,background-color,transform]"} ${o?"border-blue-500 shadow-md ring-2 ring-blue-500/50":"border-gray-200 dark:border-white/[0.08] hover:border-gray-300 dark:hover:border-white/[0.18]"}`,onClick:G=>{if(Date.now()<h.current||Date.now()<U.current){G.preventDefault(),G.stopPropagation();return}if(/Mac|iPod|iPhone|iPad/.test(navigator.platform)?G.metaKey:G.ctrlKey){G.preventDefault(),b();return}x()},onTouchStart:P,onTouchMove:B,onTouchEnd:$,onTouchCancel:te,children:s.jsxs("div",{className:"flex h-40",children:[s.jsx("div",{className:"w-40 min-w-[10rem] h-full bg-gray-100 dark:bg-black/20 relative flex items-center justify-center overflow-hidden flex-shrink-0",children:s.jsx(NS,{task:t})}),s.jsxs("div",{className:"flex-1 p-3 flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex-1 min-h-0 mb-2 overflow-hidden",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-bold text-gray-900 dark:text-gray-100 mb-2",children:[r?s.jsx(as,{filled:!0,className:"h-4 w-4 shrink-0 text-yellow-500"}):s.jsx(SS,{className:"h-4 w-4 shrink-0 text-gray-400 dark:text-gray-400"}),i===e.id?s.jsx("input",{type:"text",className:"h-6 min-w-0 flex-1 rounded border border-blue-400/50 bg-white px-1.5 py-0 text-[14px] leading-6 text-gray-900 shadow-sm outline-none focus:border-blue-500 dark:border-white/20 dark:bg-black/20 dark:text-white dark:focus:border-white/40",value:l,onChange:G=>c(G.target.value),onKeyDown:f,onClick:G=>G.stopPropagation(),autoFocus:!0,onBlur:u}):s.jsx("span",{className:"truncate",title:e.name,children:e.name})]}),s.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-2",children:[e.tasks.length," 条任务"]})]}),s.jsx("div",{className:"mt-auto flex items-center justify-end gap-1",children:!r&&e.collection&&s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:n?"取消默认收藏夹":"设为默认收藏夹",onClick:G=>{G.stopPropagation(),g(e.collection)},className:`p-1.5 rounded-md transition ${n?"text-yellow-500 hover:bg-yellow-50 dark:hover:bg-yellow-500/10":"text-gray-400 hover:text-yellow-500 hover:bg-yellow-50 dark:hover:bg-yellow-500/10"}`,children:s.jsx(as,{filled:n,className:"w-4 h-4"})}),i===e.id?s.jsx(Ke,{tooltip:"确认",onMouseDown:G=>{G.preventDefault(),G.stopPropagation(),u()},className:"p-1.5 rounded-md hover:bg-green-50 dark:hover:bg-green-950/30 text-green-500 hover:text-green-600 dark:text-green-400 dark:hover:text-green-300 transition",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}):s.jsx(Ke,{tooltip:"编辑名称",onClick:G=>d(G,e.collection),className:"p-1.5 rounded-md hover:bg-green-50 dark:hover:bg-green-950/30 text-gray-400 hover:text-green-500 transition",children:s.jsx(Hr,{className:"w-4 h-4"})}),s.jsx(Ke,{tooltip:a?"删除收藏夹":"至少保留一个收藏夹",disabled:!a,onClick:G=>{G.stopPropagation(),m(e.collection,e.tasks)},className:`p-1.5 rounded-md transition ${a?"hover:bg-red-500/[0.1] dark:hover:bg-red-500/[0.16] text-gray-400 hover:text-red-600":"text-gray-300 dark:text-gray-600 cursor-not-allowed"}`,children:s.jsx(_r,{className:"w-4 h-4"})})]})})]})]})})]})}function PS(e,t){if(e.length!==t.length)return!1;const r=new Set(t);return e.every(n=>r.has(n))}function TS(e,t){if(!e.length)return t?[t]:[];const r=e.map(o=>Vr(o,t));if(!r.some(o=>o.length>0))return t?[t]:[];const a=r[0]??[];return r.every(o=>PS(o,a))?a:[]}function O0(e,t,r){const n=t.filter(a=>a.isFavorite);return e===or?n:n.filter(a=>Vr(a,r).includes(e))}function MS(e){return[...e].filter(t=>{var r;return(r=t.outputImages)==null?void 0:r.length}).sort((t,r)=>r.createdAt-t.createdAt)[0]}function ES(){const e=w(N=>N.tasks),t=w(N=>N.favoriteCollections),r=w(N=>N.defaultFavoriteCollectionId),n=w(N=>N.setDefaultFavoriteCollectionId),a=w(N=>N.searchQuery),o=w(N=>N.setActiveFavoriteCollectionId),i=w(N=>N.setConfirmDialog),l=w(N=>N.selectedFavoriteCollectionIds),c=w(N=>N.setSelectedFavoriteCollectionIds),u=w(N=>N.toggleFavoriteCollectionSelection),[f,d]=p.useState(null),[g,m]=p.useState(""),x=p.useRef(0),b=p.useMemo(()=>{const N=O0(or,e,r);return[{id:or,name:"全部",tasks:N},...t.map(C=>({id:C.id,name:C.name,collection:C,tasks:O0(C.id,e,r)}))]},[t,r,e]),h=p.useMemo(()=>{if(!a.trim())return b;const N=a.toLowerCase();return b.filter(C=>C.name.toLowerCase().includes(N))},[b,a]),y=p.useCallback(N=>{c(N)},[c]),{selectionBox:v}=jS({containerSelector:"[data-drag-select-surface]",itemSelector:".favorite-collection-card-wrapper",getItemId:N=>N.getAttribute("data-favorite-collection-id"),onSelectionChange:y,initialSelectedIds:l,onSuppressClick:()=>{x.current=Date.now()+250}}),I=(N,C)=>{N.preventDefault(),N.stopPropagation(),d(C.id),m(C.name)},S=()=>{f&&g.trim()&&bg(f,g.trim()),d(null),m("")},k=N=>{N.key==="Enter"?(N.preventDefault(),S()):N.key==="Escape"&&(N.preventDefault(),d(null),m(""))},j=(N,C)=>{if(t.length<=1)return;const T=new Set(C.flatMap(R=>R.outputImages||[])).size;i({title:"删除收藏夹",message:`确定要删除收藏夹「${N.name}」吗?`,checkbox:T>0?{label:`同时删除收藏夹中的图片(${T} 张)`,tone:"danger"}:void 0,action:(R=!1)=>{Cd(N.id,R)}})},A=N=>{if(N.id===r){n(null);return}const C=t.find(T=>T.id===r);if(!C){n(N.id);return}i({title:"修改默认收藏夹",message:`确定要将默认收藏夹从「${C.name}」改为「${N.name}」吗?`,action:()=>n(N.id)})};return s.jsxs("div",{"data-favorite-collections-root":!0,className:"relative min-h-[50vh]",children:[h.length===0?s.jsxs("div",{className:"py-32 text-center text-gray-400 dark:text-gray-500",children:[s.jsx(as,{className:"mx-auto mb-4 h-12 w-12 text-gray-300 dark:text-gray-600"}),s.jsx("p",{className:"text-sm",children:b.length===0?"还没有收藏的图片":"没有找到匹配的收藏夹"})]}):s.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 pb-10",children:h.map(N=>{const C=MS(N.tasks),T=N.id===or,R=N.id===r,U=t.length>1;return s.jsx("div",{className:"favorite-collection-card-wrapper","data-favorite-collection-id":N.id,children:s.jsx(AS,{card:N,coverTask:C,isVirtualAll:T,isDefault:R,canDelete:U,isSelected:l.includes(N.id),editingId:f,editingName:g,setEditingName:m,confirmRename:S,handleRenameKeyDown:k,startRename:I,handleSetDefault:A,handleDelete:j,onOpen:()=>o(N.id),onToggleSelection:()=>u(N.id),suppressClickUntilRef:x})},N.id)})}),v&&s.jsx("div",{className:"fixed bg-blue-500/20 border border-blue-500/50 pointer-events-none z-[30]",style:{left:Math.min(v.startPageX,v.currentPageX)-window.scrollX,top:Math.min(v.startPageY,v.currentPageY)-tn(),width:Math.abs(v.currentPageX-v.startPageX),height:Math.abs(v.currentPageY-v.startPageY)}})]})}function en({checked:e,onChange:t,label:r,tone:n="primary",className:a,...o}){const i=n==="danger"?"border-red-300/80 hover:border-red-400/80 checked:bg-red-500/85 checked:border-transparent focus:ring-red-500/20 dark:border-red-500/30 dark:hover:border-red-500/50 dark:checked:bg-red-500/60 dark:checked:border-transparent":"border-gray-300 hover:border-gray-400 checked:bg-blue-500 checked:border-blue-500 focus:ring-blue-500/20 dark:border-white/15 dark:hover:border-white/30 dark:checked:bg-blue-500 dark:checked:border-transparent";return s.jsxs("label",{className:`flex items-center gap-2.5 cursor-pointer group ${a||""}`,children:[s.jsxs("div",{className:"relative flex items-center justify-center",children:[s.jsx("input",{type:"checkbox",checked:e,onChange:l=>t(l.target.checked),className:`peer appearance-none w-4 h-4 rounded-[4px] border bg-white focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-offset-white dark:bg-white/5 dark:focus:ring-offset-gray-900 transition-all cursor-pointer ${i}`,...o}),s.jsx("svg",{className:"absolute w-2.5 h-2.5 pointer-events-none opacity-0 peer-checked:opacity-100 scale-50 peer-checked:scale-100 transition-all duration-200 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2.5,children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M4.5 12.5l3.5 3.5L19 6.5"})})]}),r&&s.jsx("span",{className:"text-[13px] font-medium text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-gray-100 transition-colors select-none",children:r})]})}function RS(){const e=w(Y=>Y.favoritePickerTaskIds),t=w(Y=>Y.tasks),r=w(Y=>Y.favoriteCollections),n=w(Y=>Y.defaultFavoriteCollectionId),a=w(Y=>Y.setDefaultFavoriteCollectionId),o=w(Y=>Y.setFavoriteCollections),i=w(Y=>Y.setConfirmDialog),l=w(Y=>Y.closeFavoritePicker),[c,u]=p.useState([]),[f,d]=p.useState(""),[g,m]=p.useState(null),[x,b]=p.useState(""),h=p.useRef(null),y=!!(e!=null&&e.length),[v,I]=p.useState(null),[S,k]=p.useState(null),[j,A]=p.useState(null),[N,C]=p.useState(null),T=p.useRef(null),R=p.useMemo(()=>t.filter(Y=>e==null?void 0:e.includes(Y.id)),[t,e]),U=r;if(p.useEffect(()=>{y&&(u(TS(R,n)),d(""),m(null),b(""))},[n,y,R]),Kr(y,l),Lr(y,h),p.useEffect(()=>{if(!N)return;const Y=ue=>{ue.preventDefault()},le={passive:!1,capture:!0},ie=document.body.style.overflow,D=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",window.addEventListener("touchmove",Y,le),()=>{document.body.style.overflow=ie,document.body.style.overscrollBehavior=D,window.removeEventListener("touchmove",Y,le)}},[N]),!y||!e)return null;const W=(Y,le)=>{u(ie=>le?Array.from(new Set([...ie,Y])):ie.filter(D=>D!==Y))},F=()=>{const Y=Mb(f);Y&&(u(le=>Array.from(new Set([...le,Y.id]))),d(""))},_=()=>{Kj(e,c),l()},O=(Y,le)=>{I(le),Y.dataTransfer.effectAllowed="move",Y.dataTransfer.setData("text/plain",le)},J=(Y,le)=>{Y.preventDefault(),Y.dataTransfer.dropEffect="move";const ie=Y.currentTarget,D=ie.getBoundingClientRect(),ue=Y.clientY<D.top+D.height/2?"before":"after";(S!==le||j!==ue)&&(k(le),A(ue));const ke=ie.closest(".custom-scrollbar");if(ke){const we=ke.getBoundingClientRect(),We=30;Y.clientY<we.top+We?ke.scrollTop-=10:Y.clientY>we.bottom-We&&(ke.scrollTop+=10)}},H=()=>{I(null),k(null),A(null),C(null),T.current=null},K=(Y,le)=>{if(!Y.target.closest("[data-drag-handle]"))return;const ie=Y.touches[0],D=Y.currentTarget.getBoundingClientRect();Y.preventDefault(),Y.stopPropagation(),T.current={id:le.id,startX:ie.clientX,startY:ie.clientY,moved:!1},I(le.id),C({label:le.name,x:ie.clientX,y:ie.clientY,width:D.width,height:D.height,offsetX:ie.clientX-D.left,offsetY:ie.clientY-D.top})},te=Y=>{const le=T.current;if(!le)return;const ie=Y.touches[0];if(!le.moved)if(Math.abs(ie.clientX-le.startX)>5||Math.abs(ie.clientY-le.startY)>5)le.moved=!0;else return;Y.preventDefault(),C(Fe=>Fe&&{...Fe,x:ie.clientX,y:ie.clientY});const D=document.elementFromPoint(ie.clientX,ie.clientY),ue=D==null?void 0:D.closest("[data-collection-id]");if(!ue)return;const ke=ue.getAttribute("data-collection-id");if(!ke)return;const we=ue.getBoundingClientRect(),We=ie.clientY<we.top+we.height/2?"before":"after";k(ke),A(We);const Ne=ue.closest(".custom-scrollbar");if(Ne){const Fe=Ne.getBoundingClientRect(),Ee=30;ie.clientY<Fe.top+Ee?Ne.scrollTop-=10:ie.clientY>Fe.bottom-Ee&&(Ne.scrollTop+=10)}},P=Y=>{const le=T.current;if(le){if(le.moved&&S&&S!==le.id){Y.preventDefault();const ie=le.id,D=S,ue=U.findIndex(we=>we.id===ie),ke=U.findIndex(we=>we.id===D);if(ue>=0&&ke>=0){const we=[...U],[We]=we.splice(ue,1);let Ne=ke;j==="after"&&Ne++,ue<ke&&Ne--,we.splice(Ne,0,We),o(we)}}H()}},B=(Y,le)=>{Y.preventDefault(),Y.stopPropagation();const ie=v||Y.dataTransfer.getData("text/plain");if(!ie||ie===le)return H();const D=U.findIndex(Ne=>Ne.id===ie),ue=U.findIndex(Ne=>Ne.id===le);if(D<0||ue<0)return H();const ke=[...U],[we]=ke.splice(D,1);let We=ue;j==="after"&&We++,D<ue&&We--,ke.splice(We,0,we),o(ke),H()},$=(Y,le)=>{Y.preventDefault(),Y.stopPropagation(),m(le.id),b(le.name)},Q=()=>{g&&x.trim()&&bg(g,x.trim()),m(null),b("")},L=Y=>{Y.key==="Enter"?(Y.preventDefault(),Q()):Y.key==="Escape"&&(Y.preventDefault(),m(null),b(""))},G=(Y,le)=>{if(Y.preventDefault(),Y.stopPropagation(),r.length<=1)return;const ie=t.filter(ue=>Vr(ue,n).includes(le.id)),D=new Set(ie.flatMap(ue=>ue.outputImages||[])).size;i({title:"删除收藏夹",message:`确定要删除收藏夹「${le.name}」吗?`,checkbox:D>0?{label:`同时删除收藏夹中的图片(${D} 张)`,tone:"danger"}:void 0,action:(ue=!1)=>{Cd(le.id,ue)}})},se=(Y,le)=>{if(Y.preventDefault(),Y.stopPropagation(),le.id===n){a(null);return}const ie=r.find(D=>D.id===n);if(!ie){a(le.id);return}i({title:"修改默认收藏夹",message:`确定要将默认收藏夹从「${ie.name}」改为「${le.name}」吗?`,action:()=>a(le.id)})};return lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[105] flex items-center justify-center p-4 sm:p-0",onClick:l,children:[s.jsx("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{ref:h,className:"relative z-10 flex max-h-[85vh] w-full max-w-[400px] flex-col overflow-hidden rounded-3xl bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] ring-1 ring-black/5 dark:ring-white/10 animate-modal-in",onClick:Y=>Y.stopPropagation(),children:[s.jsxs("div",{className:"px-6 pt-6 pb-4 shrink-0 relative border-b border-gray-100 dark:border-[#333]",children:[s.jsx(Ke,{tooltip:"关闭",onClick:l,wrapperClassName:"absolute right-5 top-5 inline-flex",className:"shrink-0 rounded-full p-1.5 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200",children:s.jsx(qt,{className:"h-5 w-5"})}),s.jsxs("h2",{className:"mb-2 pr-8 flex items-center gap-2.5 text-lg font-semibold text-gray-800 dark:text-gray-100 leading-snug",children:[s.jsx(as,{filled:!0,className:"h-5 w-5 shrink-0 text-yellow-500"}),"保存到收藏夹"]}),s.jsx("p",{className:"text-[13px] text-gray-500 dark:text-gray-400 leading-relaxed",children:"取消勾选会将任务从对应的收藏夹中移除。"})]}),s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden pt-3 pb-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5 px-6 shrink-0",children:[s.jsx("span",{className:"text-[13px] font-medium text-gray-500 dark:text-gray-400",children:"选择要保存的收藏夹"}),s.jsxs("div",{className:"flex gap-4",children:[s.jsx("button",{type:"button",onClick:()=>u(U.map(Y=>Y.id)),className:"text-[13px] font-medium text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300 transition-colors",children:"全选"}),s.jsx("button",{type:"button",onClick:()=>u([]),className:"text-[13px] font-medium text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 transition-colors",children:"取消"})]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar relative",children:U.length===0?s.jsx("div",{className:"py-8 text-center text-sm text-gray-400 dark:text-gray-500",children:"暂无收藏夹"}):U.map(Y=>{const le=Y.id===n,ie=r.length>1;return s.jsxs("div",{"data-collection-id":Y.id,draggable:g!==Y.id,onDragStart:D=>O(D,Y.id),onDragEnd:H,onTouchStart:D=>K(D,Y),onTouchMove:te,onTouchEnd:P,onTouchCancel:H,onClick:D=>{const ue=D.target;g===Y.id||ue.closest("button,input,[data-drag-handle]")||W(Y.id,!c.includes(Y.id))},className:`group relative flex items-center justify-between transition-colors ${v===Y.id?"opacity-40 bg-gray-100 dark:bg-white/[0.04]":"hover:bg-gray-50 dark:hover:bg-white/[0.04]"}`,onDragOver:D=>J(D,Y.id),onDrop:D=>B(D,Y.id),children:[S===Y.id&&j==="before"&&v!==Y.id&&s.jsx("div",{className:"absolute top-0 left-0 right-0 h-[2px] bg-blue-500 z-40 pointer-events-none"}),S===Y.id&&j==="after"&&v!==Y.id&&s.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[2px] bg-blue-500 z-40 pointer-events-none"}),s.jsxs("div",{className:"flex h-12 cursor-pointer items-center flex-1 min-w-0 gap-3 pl-4 pr-3",children:[s.jsx("div",{"data-drag-handle":!0,className:"flex cursor-grab active:cursor-grabbing items-center justify-center text-gray-400 opacity-60 transition-opacity hover:opacity-100 dark:text-gray-500 shrink-0",style:{touchAction:"none"},children:s.jsx(no,{className:"h-3.5 w-3.5"})}),s.jsx("div",{onClick:D=>D.stopPropagation(),children:s.jsx(en,{checked:c.includes(Y.id),onChange:D=>W(Y.id,D),className:"shrink-0 scale-110"})}),g===Y.id?s.jsx("input",{type:"text",className:"h-6 min-w-0 flex-1 rounded border border-blue-400/50 bg-white px-1.5 py-0 text-[15px] leading-6 text-gray-900 shadow-sm outline-none focus:border-blue-500 dark:border-white/20 dark:bg-black/20 dark:text-white dark:focus:border-white/40",value:x,onChange:D=>b(D.target.value),onKeyDown:L,onClick:D=>D.stopPropagation(),autoFocus:!0,onBlur:Q}):s.jsx("span",{className:"min-w-0 flex-1 truncate text-[15px] font-medium text-gray-700 dark:text-gray-200",title:Y.name,children:Y.name})]}),s.jsx("div",{className:`flex shrink-0 items-center justify-end gap-2 overflow-hidden pr-4 transition-all duration-150 ${g===Y.id?"w-12":"w-28"}`,children:g===Y.id?s.jsx(Ke,{tooltip:"确认",onMouseDown:D=>{D.preventDefault(),D.stopPropagation(),Q()},className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-green-500 dark:text-green-400 hover:text-green-600 dark:hover:text-green-300 transition-colors",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}):s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:le?"取消默认收藏夹":"设为默认收藏夹",onClick:D=>se(D,Y),className:`p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md transition-colors ${le?"text-yellow-500 dark:text-yellow-400":"text-gray-400 hover:text-yellow-500 dark:hover:text-yellow-400"}`,children:s.jsx(as,{filled:le,className:"w-3.5 h-3.5"})}),s.jsx(Ke,{tooltip:"重命名",onClick:D=>$(D,Y),className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-white transition-colors",children:s.jsx(Hr,{className:"w-3.5 h-3.5"})}),s.jsx(Ke,{tooltip:ie?"删除":"至少保留一个收藏夹",disabled:!ie,onClick:D=>G(D,Y),className:`p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md transition-colors ${ie?"text-gray-400 hover:text-red-500 dark:hover:text-red-400":"text-gray-300 dark:text-gray-600 cursor-not-allowed"}`,children:s.jsx(_r,{className:"w-3.5 h-3.5"})})]})})]},Y.id)})})]}),s.jsxs("div",{className:"border-t border-gray-200 p-6 dark:border-[#333] shrink-0",children:[s.jsxs("div",{className:"flex gap-3",children:[s.jsx("input",{value:f,onChange:Y=>d(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"&&F()},type:"text",placeholder:"新建收藏夹...",className:"min-w-0 flex-1 rounded-xl border border-transparent bg-black/[0.04] px-4 py-2 text-sm outline-none transition focus:border-blue-500 focus:ring-1 focus:ring-blue-500 dark:bg-white/[0.06] dark:text-white dark:focus:border-white/30 dark:focus:ring-white/30"}),s.jsx("button",{type:"button",onClick:F,disabled:!f.trim(),className:"inline-flex items-center justify-center rounded-xl bg-gray-200 px-5 py-2 text-sm font-medium text-gray-800 transition hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-white/10 dark:text-gray-300 dark:hover:bg-white/20",children:"新建"})]}),s.jsxs("div",{className:"mt-5 flex gap-4",children:[s.jsx("button",{type:"button",onClick:l,className:"flex-1 rounded-xl border border-transparent bg-black/[0.04] px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-black/[0.07] transition-colors dark:bg-white/[0.06] dark:text-gray-200 dark:hover:bg-white/[0.1]",children:"取消"}),s.jsx("button",{type:"button",onClick:_,className:"flex-1 rounded-xl bg-blue-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-blue-600 transition-colors shadow-sm border border-transparent",children:"确认"})]})]})]})]}),document.body)}function _S(){const e=w(B=>B.isManageCollectionsModalOpen),t=w(B=>B.closeManageCollectionsModal),r=w(B=>B.favoriteCollections),n=w(B=>B.defaultFavoriteCollectionId),a=w(B=>B.setDefaultFavoriteCollectionId),o=w(B=>B.setFavoriteCollections),i=w(B=>B.setConfirmDialog),l=w(B=>B.tasks),[c,u]=p.useState(""),[f,d]=p.useState(null),[g,m]=p.useState(""),x=p.useRef(null),[b,h]=p.useState(null),[y,v]=p.useState(null),[I,S]=p.useState(null),[k,j]=p.useState(null),A=p.useRef(null),N=r;if(Kr(e,t),Lr(e,x),p.useEffect(()=>{e&&(u(""),d(null),m(""))},[e]),p.useEffect(()=>{if(!k)return;const B=G=>{G.preventDefault()},$={passive:!1,capture:!0},Q=document.body.style.overflow,L=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",window.addEventListener("touchmove",B,$),()=>{document.body.style.overflow=Q,document.body.style.overscrollBehavior=L,window.removeEventListener("touchmove",B,$)}},[k]),!e)return null;const C=()=>{c.trim()&&(Mb(c),u(""))},T=(B,$)=>{h($),B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",$)},R=(B,$)=>{B.preventDefault(),B.dataTransfer.dropEffect="move";const Q=B.currentTarget,L=Q.getBoundingClientRect(),G=B.clientY<L.top+L.height/2?"before":"after";(y!==$||I!==G)&&(v($),S(G));const se=Q.closest(".custom-scrollbar");if(se){const Y=se.getBoundingClientRect(),le=30;B.clientY<Y.top+le?se.scrollTop-=10:B.clientY>Y.bottom-le&&(se.scrollTop+=10)}},U=()=>{h(null),v(null),S(null),j(null),A.current=null},W=(B,$)=>{if(!B.target.closest("[data-drag-handle]"))return;const Q=B.touches[0],L=B.currentTarget.getBoundingClientRect();B.preventDefault(),B.stopPropagation(),A.current={id:$.id,startX:Q.clientX,startY:Q.clientY,moved:!1},h($.id),j({label:$.name,x:Q.clientX,y:Q.clientY,width:L.width,height:L.height,offsetX:Q.clientX-L.left,offsetY:Q.clientY-L.top})},F=B=>{const $=A.current;if(!$)return;const Q=B.touches[0];if(!$.moved)if(Math.abs(Q.clientX-$.startX)>5||Math.abs(Q.clientY-$.startY)>5)$.moved=!0;else return;B.preventDefault(),j(D=>D&&{...D,x:Q.clientX,y:Q.clientY});const L=document.elementFromPoint(Q.clientX,Q.clientY),G=L==null?void 0:L.closest("[data-collection-id]");if(!G)return;const se=G.getAttribute("data-collection-id");if(!se)return;const Y=G.getBoundingClientRect(),le=Q.clientY<Y.top+Y.height/2?"before":"after";v(se),S(le);const ie=G.closest(".custom-scrollbar");if(ie){const D=ie.getBoundingClientRect(),ue=30;Q.clientY<D.top+ue?ie.scrollTop-=10:Q.clientY>D.bottom-ue&&(ie.scrollTop+=10)}},_=B=>{const $=A.current;if($){if($.moved&&y&&y!==$.id){B.preventDefault();const Q=$.id,L=y,G=N.findIndex(Y=>Y.id===Q),se=N.findIndex(Y=>Y.id===L);if(G>=0&&se>=0){const Y=[...N],[le]=Y.splice(G,1);let ie=se;I==="after"&&ie++,G<se&&ie--,Y.splice(ie,0,le),o(Y)}}U()}},O=(B,$)=>{B.preventDefault(),B.stopPropagation();const Q=b||B.dataTransfer.getData("text/plain");if(!Q||Q===$)return U();const L=N.findIndex(ie=>ie.id===Q),G=N.findIndex(ie=>ie.id===$);if(L<0||G<0)return U();const se=[...N],[Y]=se.splice(L,1);let le=G;I==="after"&&le++,L<G&&le--,se.splice(le,0,Y),o(se),U()},J=(B,$)=>{B.preventDefault(),B.stopPropagation(),d($.id),m($.name)},H=()=>{f&&g.trim()&&bg(f,g.trim()),d(null),m("")},K=B=>{B.key==="Enter"?(B.preventDefault(),H()):B.key==="Escape"&&(B.preventDefault(),d(null),m(""))},te=(B,$)=>{if(B.preventDefault(),B.stopPropagation(),r.length<=1)return;const Q=l.filter(G=>Vr(G,n).includes($.id)),L=new Set(Q.flatMap(G=>G.outputImages||[])).size;i({title:"删除收藏夹",message:`确定要删除收藏夹「${$.name}」吗?`,checkbox:L>0?{label:`同时删除收藏夹中的图片(${L} 张)`,tone:"danger"}:void 0,action:(G=!1)=>{Cd($.id,G)}})},P=(B,$)=>{if(B.preventDefault(),B.stopPropagation(),$.id===n){a(null);return}const Q=r.find(L=>L.id===n);if(!Q){a($.id);return}i({title:"修改默认收藏夹",message:`确定要将默认收藏夹从「${Q.name}」改为「${$.name}」吗?`,action:()=>a($.id)})};return lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[105] flex items-center justify-center p-4 sm:p-0",onClick:t,children:[s.jsx("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{ref:x,className:"relative z-10 flex max-h-[85vh] w-full max-w-[400px] flex-col overflow-hidden rounded-3xl bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] ring-1 ring-black/5 dark:ring-white/10 animate-modal-in",onClick:B=>B.stopPropagation(),children:[s.jsxs("div",{className:"px-6 pt-6 pb-4 shrink-0 relative border-b border-gray-100 dark:border-[#333]",children:[s.jsx(Ke,{tooltip:"关闭",onClick:t,wrapperClassName:"absolute right-5 top-5 inline-flex",className:"shrink-0 rounded-full p-1.5 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200",children:s.jsx(qt,{className:"h-5 w-5"})}),s.jsx("h2",{className:"mb-2 pr-8 flex items-center gap-2.5 text-lg font-semibold text-gray-800 dark:text-gray-100 leading-snug",children:"管理收藏夹"}),s.jsx("p",{className:"text-[13px] text-gray-500 dark:text-gray-400 leading-relaxed",children:"在这里管理你的收藏夹列表及排序。"})]}),s.jsx("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden pt-3 pb-1",children:s.jsx("div",{className:"flex-1 overflow-y-auto custom-scrollbar relative",children:N.length===0?s.jsx("div",{className:"py-8 text-center text-sm text-gray-400 dark:text-gray-500",children:"暂无收藏夹"}):N.map(B=>{const $=B.id===n,Q=r.length>1;return s.jsxs("div",{"data-collection-id":B.id,draggable:f!==B.id,onDragStart:L=>T(L,B.id),onDragEnd:U,onTouchStart:L=>W(L,B),onTouchMove:F,onTouchEnd:_,onTouchCancel:U,className:`group relative flex items-center justify-between transition-colors ${b===B.id?"opacity-40 bg-gray-100 dark:bg-white/[0.04]":"hover:bg-gray-50 dark:hover:bg-white/[0.04]"}`,onDragOver:L=>R(L,B.id),onDrop:L=>O(L,B.id),children:[y===B.id&&I==="before"&&b!==B.id&&s.jsx("div",{className:"absolute top-0 left-0 right-0 h-[2px] bg-blue-500 z-40 pointer-events-none"}),y===B.id&&I==="after"&&b!==B.id&&s.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[2px] bg-blue-500 z-40 pointer-events-none"}),s.jsxs("div",{className:"flex h-12 items-center flex-1 min-w-0 gap-3 pl-4 pr-3",children:[s.jsx("div",{"data-drag-handle":!0,className:"flex cursor-grab active:cursor-grabbing items-center justify-center text-gray-400 opacity-60 transition-opacity hover:opacity-100 dark:text-gray-500 shrink-0",style:{touchAction:"none"},children:s.jsx(no,{className:"h-3.5 w-3.5"})}),f===B.id?s.jsx("input",{type:"text",className:"h-6 min-w-0 flex-1 rounded border border-blue-400/50 bg-white px-1.5 py-0 text-[15px] leading-6 text-gray-900 shadow-sm outline-none focus:border-blue-500 dark:border-white/20 dark:bg-black/20 dark:text-white dark:focus:border-white/40",value:g,onChange:L=>m(L.target.value),onKeyDown:K,onClick:L=>L.stopPropagation(),autoFocus:!0,onBlur:H}):s.jsx("span",{className:"min-w-0 flex-1 truncate text-[15px] font-medium text-gray-700 dark:text-gray-200",title:B.name,children:B.name})]}),s.jsx("div",{className:`flex shrink-0 items-center justify-end gap-2 overflow-hidden pr-4 transition-all duration-150 ${f===B.id?"w-12":"w-28"}`,children:f===B.id?s.jsx(Ke,{tooltip:"确认",onMouseDown:L=>{L.preventDefault(),L.stopPropagation(),H()},className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-green-500 dark:text-green-400 hover:text-green-600 dark:hover:text-green-300 transition-colors",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}):s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:$?"取消默认收藏夹":"设为默认收藏夹",onClick:L=>P(L,B),className:`p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md transition-colors ${$?"text-yellow-500 dark:text-yellow-400":"text-gray-400 hover:text-yellow-500 dark:hover:text-yellow-400"}`,children:s.jsx(as,{filled:$,className:"w-3.5 h-3.5"})}),s.jsx(Ke,{tooltip:"重命名",onClick:L=>J(L,B),className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-gray-400 hover:text-gray-700 dark:hover:text-white transition-colors",children:s.jsx(Hr,{className:"w-3.5 h-3.5"})}),s.jsx(Ke,{tooltip:Q?"删除":"至少保留一个收藏夹",disabled:!Q,onClick:L=>te(L,B),className:`p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md transition-colors ${Q?"text-gray-400 hover:text-red-500 dark:hover:text-red-400":"text-gray-300 dark:text-gray-600 cursor-not-allowed"}`,children:s.jsx(_r,{className:"w-3.5 h-3.5"})})]})})]},B.id)})})}),s.jsx("div",{className:"border-t border-gray-200 p-6 dark:border-[#333] shrink-0",children:s.jsxs("div",{className:"flex gap-3",children:[s.jsx("input",{value:c,onChange:B=>u(B.target.value),onKeyDown:B=>{B.key==="Enter"&&C()},type:"text",placeholder:"新建收藏夹...",className:"min-w-0 flex-1 rounded-xl border border-transparent bg-black/[0.04] px-4 py-2 text-sm outline-none transition focus:border-blue-500 focus:ring-1 focus:ring-blue-500 dark:bg-white/[0.06] dark:text-white dark:focus:border-white/30 dark:focus:ring-white/30"}),s.jsx("button",{type:"button",onClick:C,disabled:!c.trim(),className:"inline-flex items-center justify-center rounded-xl bg-gray-200 px-5 py-2 text-sm font-medium text-gray-800 transition hover:bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-white/10 dark:text-gray-300 dark:hover:bg-white/20",children:"新建"})]})})]})]}),document.body)}function DS(){var r;const e=w(n=>n.activeFavoriteCollectionId),t=w(n=>n.favoriteCollections);return e?e===or?"全部":((r=t.find(n=>n.id===e))==null?void 0:r.name)??og:""}var Oh;const LS=!De&&oy(navigator.userAgent,(Oh=navigator.userAgentData)==null?void 0:Oh.platform,navigator.maxTouchPoints)==="windows";function B0(){const e=window.navigator;return window.matchMedia("(display-mode: standalone)").matches||e.standalone===!0}function OS(){const e=w(P=>P.appMode),t=w(P=>P.setAppMode),r=w(P=>P.setShowSettings),n=w(P=>P.setConfirmDialog),a=w(P=>P.agentMobileHeaderVisible),o=w(P=>P.agentConversations),i=w(P=>P.activeAgentConversationId),l=w(P=>P.filterFavorite),c=w(P=>P.activeFavoriteCollectionId),u=o.find(P=>P.id===i),f=DS(),d=e==="gallery"&&!!c,g=er(P=>P.releases[0]),m=er(P=>Zb(P.releases[0],"0.8.4",P.ignoredVersion)),[x,b]=p.useState(!1),[h,y]=p.useState(null),[v,I]=p.useState(B0),[S,k]=p.useState(!1),[j,A]=p.useState("up"),[N,C]=p.useState(!1),T=p.useRef(null),R=w(P=>P.createAgentConversation),U=w(P=>P.privacyModeEpoch),[W,F]=p.useState(U);W!==U&&(F(U),b(!1),C(!1));const _=e==="agent"&&!a?"hidden":e==="gallery"&&j==="down"?"compact":void 0;p.useEffect(()=>{const P=document.documentElement;_?P.dataset.header=_:delete P.dataset.header},[_]),p.useEffect(()=>{if(e==="agent"){A("up");return}let P=tn(),B=!1;const $=()=>{B||(window.requestAnimationFrame(()=>{const L=tn();L<20?A("up"):L>P+10?A("down"):L<P-10&&A("up"),P=L,B=!1}),B=!0)},Q=ss();return Q.addEventListener("scroll",$,{passive:!0}),()=>Q.removeEventListener("scroll",$)},[e]),p.useEffect(()=>{if(e==="agent"&&!a){k(!0);const P=setTimeout(()=>{k(!1)},1500);return()=>clearTimeout(P)}},[e,a]);const O=Ot(),J=Ot(),H=Ot(),K=Ot();p.useEffect(()=>{const P=$=>{$.preventDefault(),y($),I(!1)},B=()=>{y(null),I(!0)};return window.addEventListener("beforeinstallprompt",P),window.addEventListener("appinstalled",B),()=>{window.removeEventListener("beforeinstallprompt",P),window.removeEventListener("appinstalled",B)}},[]);const te=async()=>{if(h){const P=h;y(null);try{await P.prompt();const B=await P.userChoice;I(B.outcome==="accepted")}catch{I(B0())}}else{const P=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;n(P?{title:"安装为应用",message:"在 Safari 浏览器中,点击底部「分享」按钮,选择「添加到主屏幕」即可安装此应用。",showCancel:!1,confirmText:"我知道了",icon:"info",action:()=>{}}:{title:"安装为应用",message:`请在浏览器的菜单中选择「添加到主屏幕」或「安装应用」。
|
|
70
|
+
|
|
71
|
+
(如果在微信等内置浏览器中,请先在外部浏览器打开)`,showCancel:!1,confirmText:"我知道了",icon:"info",action:()=>{}})}};return s.jsxs(s.Fragment,{children:[s.jsxs("header",{"data-no-drag-select":!0,className:`safe-area-top pr-[var(--page-scrollbar-width)] fixed top-0 left-0 right-0 z-40 bg-white/80 dark:bg-gray-950/80 backdrop-blur border-b border-gray-200 dark:border-white/[0.08] transition-transform duration-300 ease-in-out ${e==="agent"&&!a?"-translate-y-full sm:translate-y-0":"translate-y-0"}`,children:[s.jsxs("div",{className:"safe-area-x safe-header-inner max-w-7xl mx-auto flex items-center justify-between relative",children:[s.jsxs("div",{className:"flex-1 min-w-0 pr-2 flex items-center gap-2",children:[s.jsxs("h1",{className:"inline-flex min-w-0 items-start relative mr-2",children:[d?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate text-[17px] font-bold tracking-tight text-gray-800 dark:text-gray-100 sm:hidden",title:f,children:f}),s.jsx("a",{href:"https://github.com/CookSleep/gpt_image_playground",target:"_blank",rel:"noopener noreferrer",className:"hidden text-lg font-bold tracking-tight text-gray-800 transition-colors hover:text-gray-600 dark:text-gray-100 dark:hover:text-gray-300 sm:inline",children:"GPT Image Playground"})]}):s.jsx("a",{href:"https://github.com/CookSleep/gpt_image_playground",target:"_blank",rel:"noopener noreferrer",className:"text-[17px] sm:text-lg font-bold tracking-tight text-gray-800 dark:text-gray-100 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:"GPT Image Playground"}),m&&g&&s.jsx("button",{type:"button",onClick:()=>Fa(!0),className:"absolute -right-1 -top-1 translate-x-full -translate-y-1/4 px-1 py-0.5 rounded-[4px] border border-red-500/30 text-[9px] font-black bg-red-500 text-white hover:bg-red-600 transition-all animate-fade-in leading-none shadow-sm before:absolute before:left-0 before:-right-[9px] before:-inset-y-[9px] before:content-['']",title:`新版本 ${g.tag}`,children:"NEW"})]}),e==="agent"&&s.jsxs("div",{className:"hidden sm:flex items-center gap-1 relative",children:[s.jsx("button",{ref:T,type:"button",onClick:()=>C(P=>!P),className:"p-1.5 text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.04] rounded-lg transition-colors",title:"历史任务",children:s.jsx(fy,{className:"w-5 h-5"})}),s.jsx("button",{type:"button",onClick:()=>{t("agent"),R()},className:"p-1.5 text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.04] rounded-lg transition-colors",title:"新对话",children:s.jsx(Hr,{className:"w-5 h-5"})}),N&&s.jsx(CS,{onClose:()=>C(!1),ignoreOutsideClickRef:T})]})]}),e==="agent"&&u&&s.jsx("div",{className:"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 hidden sm:flex max-w-[30%]",children:s.jsx("button",{type:"button",onClick:()=>{C(!0),setTimeout(()=>{w.getState().setAgentEditingConversationId(u.id)},0)},className:"text-sm font-semibold text-gray-700 dark:text-gray-300 truncate hover:bg-gray-100 dark:hover:bg-white/[0.04] px-2 py-1 rounded transition-colors",children:u.title||"Agent"})}),d&&s.jsx("div",{className:"absolute left-1/2 top-1/2 hidden max-w-[30%] -translate-x-1/2 -translate-y-1/2 sm:flex",children:s.jsx("div",{className:"truncate rounded px-2 py-1 text-sm font-semibold text-gray-700 dark:text-gray-300",title:f,children:f})}),s.jsxs("div",{className:"hidden sm:flex items-center gap-1 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] p-1 mr-4",children:[s.jsx("button",{type:"button",onClick:()=>t("gallery"),className:`px-4 py-1.5 rounded-lg text-sm transition-colors ${e==="gallery"?"bg-white dark:bg-white/[0.12] text-gray-900 dark:text-white shadow-sm font-medium":"text-gray-500 hover:text-gray-800 dark:hover:text-gray-200"}`,children:"画廊"}),s.jsx("button",{type:"button",onClick:()=>t("agent"),className:`px-4 py-1.5 rounded-lg text-sm transition-colors ${e==="agent"?"bg-white dark:bg-white/[0.12] text-gray-900 dark:text-white shadow-sm font-medium":"text-gray-500 hover:text-gray-800 dark:hover:text-gray-200"}`,children:"Agent"})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[!De&&!v&&s.jsxs("div",{className:"relative",...O.handlers,children:[s.jsx("button",{onClick:()=>{xr(),te()},className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"安装为应用",children:s.jsx(cS,{className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),s.jsx(pt,{visible:O.visible,className:"whitespace-nowrap",children:"安装为应用"})]}),LS&&s.jsxs("div",{className:"relative hidden sm:block",...J.handlers,children:[s.jsx("a",{href:`${Ac}/latest`,target:"_blank",rel:"noopener noreferrer",onClick:()=>xr(),className:"block p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"下载客户端",children:s.jsx(dS,{className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),s.jsx(pt,{visible:J.visible,className:"whitespace-nowrap",children:"下载客户端"})]}),s.jsxs("div",{className:"relative",...H.handlers,children:[s.jsx("button",{onClick:()=>{xr(),b(!0)},className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"操作指南",children:s.jsx(uS,{className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),s.jsx(pt,{visible:H.visible,className:"whitespace-nowrap",children:"操作指南"})]}),s.jsxs("div",{className:"relative",...K.handlers,children:[s.jsx("button",{onClick:()=>r(!0),className:"p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-900 transition-colors","aria-label":"设置",children:s.jsx(fS,{className:"w-5 h-5 text-gray-600 dark:text-gray-400"})}),s.jsx(pt,{visible:K.visible,className:"whitespace-nowrap",children:"设置"})]})]})]}),s.jsx("div",{className:`safe-area-x sm:hidden overflow-hidden transition-all duration-300 ease-in-out ${e==="gallery"&&j==="down"?"max-h-0 opacity-0 pb-0":"max-h-20 opacity-100 pb-2"}`,children:s.jsxs("div",{className:"grid grid-cols-2 gap-1 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] p-1 mx-2",children:[s.jsx("button",{type:"button",onClick:()=>t("gallery"),className:`px-4 py-1.5 rounded-lg text-sm transition-colors ${e==="gallery"?"bg-white dark:bg-white/[0.12] text-gray-900 dark:text-white shadow-sm font-medium":"text-gray-500 hover:text-gray-800 dark:hover:text-gray-200"}`,children:"画廊"}),s.jsx("button",{type:"button",onClick:()=>t("agent"),className:`px-4 py-1.5 rounded-lg text-sm transition-colors ${e==="agent"?"bg-white dark:bg-white/[0.12] text-gray-900 dark:text-white shadow-sm font-medium":"text-gray-500 hover:text-gray-800 dark:hover:text-gray-200"}`,children:"Agent"})]})})]}),s.jsx("div",{className:`fixed top-0 left-0 right-0 pr-[var(--page-scrollbar-width)] z-30 flex justify-center pointer-events-none transition-all duration-300 ease-in-out sm:hidden ${e==="agent"&&S&&!a?"translate-y-[var(--safe-area-top)] opacity-100":"-translate-y-full opacity-0"}`,children:s.jsx("div",{className:"bg-black/60 backdrop-blur-sm text-white text-xs px-3 py-1.5 rounded-b-xl shadow-lg",children:"下拉展示顶栏"})}),s.jsxs("div",{className:`safe-area-top invisible pointer-events-none transition-all duration-300 ease-in-out ${e==="agent"&&!a?"max-h-0 sm:max-h-[500px] opacity-0 sm:opacity-100 overflow-hidden sm:overflow-visible":"max-h-[500px] opacity-100"}`,"aria-hidden":"true",children:[s.jsx("div",{className:"safe-header-inner"}),s.jsx("div",{className:`safe-area-x sm:hidden overflow-hidden transition-all duration-300 ease-in-out ${e==="gallery"&&j==="down"?"max-h-0 pb-0":"max-h-20 pb-2"}`,children:s.jsx("div",{className:"p-1",children:s.jsx("div",{className:"py-1.5 text-sm",children:"占位"})})})]}),x&&s.jsx(wS,{appMode:e,isFavoriteCollectionOverview:e==="gallery"&&l&&!c,onClose:()=>b(!1)})]})}const Nl=8,BS=/(auto|scroll|hidden|clip)/,Mc=240,my="flex flex-col overflow-hidden rounded-xl border border-transparent bg-white/95 shadow-[0_8px_30px_rgb(0,0,0,0.12)] ring-1 ring-black/5 backdrop-blur-xl dark:bg-gray-800/95 dark:shadow-[0_8px_30px_rgb(0,0,0,0.4)] dark:ring-white/[0.06]",hy="custom-scrollbar ios-rounded-scroll-fix min-h-0 overflow-y-auto rounded-[11px]";function py(e){const t=e.getBoundingClientRect();let r=window.innerHeight-t.bottom-Nl,n=t.top-Nl,a=e.parentElement;for(;a&&a!==document.body;){const o=window.getComputedStyle(a);if(BS.test(`${o.overflow} ${o.overflowY}`)){const i=a.getBoundingClientRect();r=Math.min(r,i.bottom-t.bottom-Nl),n=Math.min(n,t.top-i.top-Nl)}a=a.parentElement}return{above:n,below:r}}function US(e,t=Mc){return Math.max(0,Math.min(t,Math.floor(py(e).below)))}function _t({value:e,onChange:t,onReorder:r,options:n,disabled:a,className:o,onOpenChange:i,showValueTooltips:l=!1,prefix:c,menuClassName:u}){const[f,d]=p.useState(!1),[g,m]=p.useState(Mc),[x,b]=p.useState("bottom"),[h,y]=p.useState(null),[v,I]=p.useState(null),[S,k]=p.useState(null),[j,A]=p.useState(null),N=p.useRef(null),C=p.useRef(null),T=p.useRef(null),R=p.useRef(null),U=Ot(),[W,F]=p.useState(null),_=p.useRef(null),O=p.useRef(!1),J=()=>{_.current&&(window.clearTimeout(_.current),_.current=null)},H=n.find(P=>P.value===e);p.useEffect(()=>()=>{C.current&&clearInterval(C.current),J()},[]),p.useEffect(()=>{i==null||i(f),f||(J(),F(null),O.current=!1)},[f,i]),p.useEffect(()=>{if(!j)return;const P=L=>{L.preventDefault()},B={passive:!1,capture:!0},$=document.body.style.overflow,Q=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",window.addEventListener("touchmove",P,B),()=>{document.body.style.overflow=$,document.body.style.overscrollBehavior=Q,window.removeEventListener("touchmove",P,B)}},[j]),p.useEffect(()=>{const P=B=>{T.current&&!T.current.contains(B.target)&&d(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[]),p.useEffect(()=>{if(!f)return;const P=()=>{if(!R.current)return;const B=py(R.current),$=B.below<120&&B.above>B.below;b($?"top":"bottom"),m(Math.max(0,Math.min(Mc,Math.floor($?B.above:B.below))))};return P(),window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[f]);const K=P=>{a||(P.preventDefault(),P.stopPropagation(),d(!f))},te=()=>{N.current=null,A(null),y(null),I(null),k(null),J(),O.current=!1,C.current&&(clearInterval(C.current),C.current=null)};return s.jsxs("div",{ref:T,className:"relative w-full",children:[s.jsxs("div",{ref:R,...l?U.handlers:{},onClick:P=>{var B,$;l&&(($=(B=U.handlers).onClick)==null||$.call(B)),K(P),U.dismiss()},className:`flex items-center justify-between gap-1 w-full cursor-pointer select-none ${o??""} ${a?"!opacity-50 !cursor-not-allowed !bg-gray-100/50 dark:!bg-white/[0.05]":""}`,children:[s.jsxs("span",{className:"truncate",children:[c,s.jsx("span",{style:H==null?void 0:H.style,children:(H==null?void 0:H.label)??e})]}),s.jsx(Nd,{className:`w-3.5 h-3.5 flex-shrink-0 text-gray-400 dark:text-gray-500 transition-transform duration-200 ${f?"rotate-180":""}`}),l&&s.jsx(pt,{visible:U.visible,className:"max-w-[300px] break-words whitespace-pre-wrap",children:(H==null?void 0:H.label)??e})]}),f&&s.jsx("div",{className:`absolute z-50 w-full ${my} ${u??""} ${x==="top"?"bottom-full mb-1.5 animate-dropdown-up":"top-full mt-1.5 animate-dropdown-down"}`,style:{maxHeight:g},children:s.jsx("div",{className:hy,children:n.map(P=>{var B;return s.jsxs("div",{"data-option-value":String(P.value),draggable:P.draggable,onDragStart:$=>{P.draggable&&(y(P.value),$.dataTransfer.effectAllowed="move",$.dataTransfer.setData("text/plain",String(P.value)))},onDragOver:$=>{if(!P.draggable||!h)return;$.preventDefault(),$.dataTransfer.dropEffect="move";const Q=$.currentTarget,L=Q.getBoundingClientRect(),G=$.clientY<L.top+L.height/2?"before":"after";(v!==P.value||S!==G)&&(I(P.value),k(G));const se=Q.parentElement;if(se){const Y=se.getBoundingClientRect(),le=30;$.clientY<Y.top+le?se.scrollTop-=10:$.clientY>Y.bottom-le&&(se.scrollTop+=10)}},onDragEnd:()=>{y(null),I(null),k(null)},onDrop:$=>{if(!P.draggable||!r)return;$.preventDefault(),y(null),I(null),k(null);const Q=$.dataTransfer.getData("text/plain"),L=n.find(G=>String(G.value)===Q);L&&L.value!==P.value&&r(L.value,P.value,S)},onTouchStart:$=>{if(!P.draggable){if(!l)return;J(),O.current=!1,_.current=window.setTimeout(()=>{O.current=!0,F(P.value)},500);return}if(!$.target.closest("[data-drag-handle]")){if(!l)return;J(),O.current=!1,_.current=window.setTimeout(()=>{O.current=!0,F(P.value)},500);return}const L=$.touches[0],G=$.currentTarget.getBoundingClientRect();$.stopPropagation(),N.current={value:P.value,startX:L.clientX,startY:L.clientY,moved:!1},y(P.value),A({label:P.label,x:L.clientX,y:L.clientY,width:G.width,height:G.height,offsetX:L.clientX-G.left,offsetY:L.clientY-G.top})},onTouchMove:$=>{J();const Q=N.current;if(!Q||!P.draggable)return;const L=$.touches[0];if(!Q.moved)if(Math.abs(L.clientX-Q.startX)>5||Math.abs(L.clientY-Q.startY)>5)Q.moved=!0;else return;$.preventDefault(),A(ie=>ie&&{...ie,x:L.clientX,y:L.clientY});const G=document.getElementById("touch-drag-preview");G&&(G.style.pointerEvents="none");const se=document.elementFromPoint(L.clientX,L.clientY),Y=se==null?void 0:se.closest("[data-option-value]");if(Y){const ie=Y.getAttribute("data-option-value");if(ie){const D=n.find(ue=>String(ue.value)===ie);if(D&&D.draggable){const ue=Y.getBoundingClientRect(),ke=L.clientY<ue.top+ue.height/2?"before":"after";(v!==D.value||S!==ke)&&(I(D.value),k(ke))}}}const le=Y==null?void 0:Y.closest(".custom-scrollbar");if(le){const ie=le.getBoundingClientRect(),D=30;C.current&&(clearInterval(C.current),C.current=null),L.clientY<ie.top+D?C.current=window.setInterval(()=>{le.scrollTop-=5},16):L.clientY>ie.bottom-D&&(C.current=window.setInterval(()=>{le.scrollTop+=5},16))}},onTouchEnd:$=>{J(),O.current&&$.cancelable&&$.preventDefault(),O.current=!1;const Q=N.current;if(!Q||!Q.moved){te();return}$.preventDefault(),r&&v!==null&&v!==Q.value&&r(Q.value,v,S),te()},onTouchCancel:te,onClick:$=>{$.target.closest("button, [data-drag-handle]")||($.preventDefault(),t(P.value),d(!1),J(),F(null))},onMouseEnter:()=>l&&F(P.value),onMouseLeave:()=>{J(),F(null)},onFocus:()=>l&&F(P.value),onBlur:()=>{J(),F(null)},className:`relative flex min-h-9 cursor-pointer items-center justify-between gap-2 px-3 py-2 text-xs transition-colors ${h===P.value?"opacity-40 bg-gray-100 dark:bg-white/[0.04]":P.variant==="action"?"font-semibold text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-500/10":P.variant==="danger"?"font-semibold text-red-600 hover:bg-red-500/[0.1] dark:text-red-400/90 dark:hover:bg-red-500/[0.16]":P.value===e?"bg-black/[0.05] dark:bg-white/[0.08] text-blue-600 dark:text-blue-400 font-medium":"text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-white/[0.06]"}`,children:[v===P.value&&S==="before"&&h!==P.value&&s.jsx("div",{className:"absolute -top-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),v===P.value&&S==="after"&&h!==P.value&&s.jsx("div",{className:"absolute -bottom-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),l&&W===P.value&&s.jsx(pt,{visible:!0,className:"max-w-[300px] break-words whitespace-pre-wrap",children:P.label}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[P.draggable&&s.jsx("div",{"data-drag-handle":!0,className:"flex cursor-grab active:cursor-grabbing items-center justify-center text-gray-400 opacity-60 transition-opacity hover:opacity-100 dark:text-gray-500",style:{touchAction:"none"},title:"拖拽排序",children:s.jsx(no,{className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"min-w-0 truncate",style:P.style,children:P.label})]}),(B=P.actions)!=null&&B.length?s.jsx("span",{className:"ml-auto flex shrink-0 items-center gap-1",children:P.actions.map($=>s.jsx("button",{type:"button",title:$.label,onPointerDown:Q=>{Q.stopPropagation()},onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),$.onClick(),d(!1)},className:`flex h-5 w-5 shrink-0 items-center justify-center rounded transition ${$.variant==="danger"?"text-red-600 hover:bg-red-500/[0.1] dark:text-red-400/90 dark:hover:bg-red-500/[0.16]":"text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200"}`,children:$.label==="编辑"?s.jsx(Hr,{className:"w-3.5 h-3.5"}):$.label==="删除"?s.jsx(_r,{className:"w-3.5 h-3.5"}):$.label},$.label))}):null,P.variant==="action"&&s.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:s.jsx(cy,{className:"h-4 w-4"})})]},P.value)})})}),j&&lr.createPortal(s.jsx("div",{id:"touch-drag-preview",className:"fixed pointer-events-none z-[110] flex items-center justify-between gap-2 rounded-xl bg-white/95 px-3 py-2 text-xs text-gray-700 shadow-xl ring-1 ring-black/5 backdrop-blur-xl dark:bg-gray-900/95 dark:text-gray-300 dark:ring-white/10",style:{left:j.x-j.offsetX,top:j.y-j.offsetY,width:j.width,minHeight:j.height},children:s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[s.jsx(no,{className:"h-3.5 w-3.5 shrink-0 text-gray-400 dark:text-gray-500"}),s.jsx("span",{className:"min-w-0 truncate",children:j.label})]})}),document.body)]})}function U0({tooltip:e,className:t,disabled:r=!1,onClick:n,children:a}){const o=Ot();return s.jsxs("span",{className:"relative inline-flex",...o.handlers,children:[s.jsx("button",{type:"button",onClick:()=>{o.dismiss(),!r&&n()},disabled:r,className:t,"aria-label":e,children:a}),s.jsx(pt,{visible:o.visible,className:"whitespace-nowrap",children:e})]})}function FS(){const e=p.useRef(null),t=p.useRef(null),r=w(k=>k.searchQuery),n=w(k=>k.setSearchQuery),a=w(k=>k.filterStatus),o=w(k=>k.setFilterStatus),i=w(k=>k.clearSelection),l=w(k=>k.filterFavorite),c=w(k=>k.setFilterFavorite),u=w(k=>k.activeFavoriteCollectionId),f=w(k=>k.setActiveFavoriteCollectionId),d=w(k=>k.openManageCollectionsModal),g=w(k=>{const j=k.searchQuery.trim().toLowerCase();return k.tasks.filter(A=>!vi(A,"error")||vc(k.privacyMode,A)||k.filterFavorite&&(!A.isFavorite||k.activeFavoriteCollectionId&&k.activeFavoriteCollectionId!==or&&!Vr(A,k.defaultFavoriteCollectionId).includes(k.activeFavoriteCollectionId))?!1:jc(A,j)).length}),m=w(k=>k.setConfirmDialog),x=w(k=>!!k.privacyMode),b=l&&!u,h=a==="error",y=u?"返回收藏夹":l?"退出收藏夹":"收藏夹";p.useEffect(()=>{const k=j=>{var N,C;if(document.activeElement!==t.current)return;const A=j.target instanceof Element?j.target:document.elementFromPoint(j.clientX,j.clientY);A&&((N=e.current)!=null&&N.contains(A)||A.closest("[data-drag-select-surface]")&&(A.closest(".task-card-wrapper, .favorite-collection-card-wrapper")||(C=t.current)==null||C.blur()))};return document.addEventListener("mousedown",k,!0),()=>document.removeEventListener("mousedown",k,!0)},[]);const v=()=>{if(u){f(null);return}c(!l)},I=()=>{const k=w.getState(),j=k.searchQuery.trim().toLowerCase(),A=k.tasks.filter(C=>!vi(C,"error")||vc(k.privacyMode,C)||k.filterFavorite&&(!C.isFavorite||k.activeFavoriteCollectionId&&k.activeFavoriteCollectionId!==or&&!Vr(C,k.defaultFavoriteCollectionId).includes(k.activeFavoriteCollectionId))?!1:jc(C,j)).map(C=>C.id),N=A.length;N!==0&&m({title:"清除失败记录",message:`确定清除筛选范围内的失败记录吗?
|
|
72
|
+
纯失败任务会被删除;部分失败任务只会清除失败标记,保留已成功图片。共 ${N} 条记录。`,confirmText:"清除",cancelText:"取消",tone:"danger",action:()=>Jj(A)})},S=k=>{k!==a&&(o(k),i())};return s.jsxs("div",{ref:e,"data-no-drag-select":!0,className:"mt-6 mb-4 flex gap-3",children:[s.jsxs("div",{className:"flex gap-2 flex-shrink-0 z-20",children:[!x&&s.jsx(U0,{tooltip:y,onClick:v,className:`p-2.5 rounded-xl border transition-all ${l?"border-transparent bg-yellow-400/[0.15] dark:bg-yellow-500/[0.15] text-yellow-500":"border-transparent bg-black/[0.04] dark:bg-white/[0.06] text-gray-400 hover:bg-black/[0.07] dark:hover:bg-white/[0.1]"}`,children:u?s.jsx(dy,{className:"w-5 h-5"}):s.jsx(as,{filled:l,className:"w-5 h-5"})}),b&&s.jsx(U0,{tooltip:"管理收藏夹",onClick:d,className:"p-2.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] text-gray-400 hover:bg-black/[0.07] dark:hover:bg-white/[0.1] transition-all",children:s.jsx(gS,{className:"w-5 h-5"})}),!b&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"relative w-[88px]",children:s.jsx(_t,{value:a,onChange:S,options:[{label:"全部",value:"all"},{label:"已完成",value:"done"},{label:"生成中",value:"running"},{label:"失败",value:"error"}],className:"px-3 py-2.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 transition"})}),h&&s.jsx("button",{type:"button",onClick:I,disabled:g===0,title:g>0?`清除 ${g} 条失败记录`:"没有失败记录","aria-label":g>0?`清除 ${g} 条失败记录`:"没有失败记录",className:"flex h-[42px] w-[42px] shrink-0 items-center justify-center rounded-xl border border-transparent bg-black/[0.04] text-gray-400 transition-all hover:bg-black/[0.07] hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500/30 disabled:cursor-not-allowed disabled:opacity-55 disabled:hover:bg-black/[0.07] disabled:hover:text-gray-400 dark:bg-white/[0.06] dark:text-gray-500 dark:hover:bg-white/[0.1] dark:hover:text-gray-300 dark:disabled:hover:bg-gray-900 dark:disabled:hover:text-gray-500",children:s.jsx(_r,{className:"h-[18px] w-[18px]"})})]})]}),s.jsxs("div",{className:"relative z-10 flex-1",children:[s.jsx("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 dark:text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),s.jsx("input",{ref:t,value:r,onChange:k=>n(k.target.value),type:"text",placeholder:b?"搜索收藏夹名称...":"搜索提示词、参数...",className:"w-full pl-10 pr-4 py-2.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 transition"})]})]})}function F0(e,t,r,n,a){const o=Math.ceil(e/t.columns);if(!o)return{startIndex:0,endIndex:0,paddingTop:0,paddingBottom:0};const i=t.rowHeight+t.rowGap,l=Math.min(o-1,Math.max(0,Math.floor((r-a)/i))),c=Math.min(o,Math.max(l+1,Math.ceil((n+a)/i)));return{startIndex:l*t.columns,endIndex:Math.min(e,c*t.columns),paddingTop:l*i,paddingBottom:(o-c)*i}}function $S(e,t,r){const n=t.rowHeight+t.rowGap,a=(t.width-(t.columns-1)*t.columnGap)/t.columns,o=a+t.columnGap,i=Math.ceil(e/t.columns),l=Math.max(0,Math.floor(r.top/n)),c=Math.min(i-1,Math.floor(r.bottom/n)),u=[];for(let f=l;f<=c;f++){const d=f*n;if(r.top<d+t.rowHeight&&r.bottom>d)for(let g=0;g<t.columns;g++){const m=f*t.columns+g;if(m>=e)break;const x=g*o;r.left<x+a&&r.right>x&&u.push(m)}}return u}const $0={columns:1,rowHeight:162,rowGap:16,columnGap:16,width:0};function zS(e,t){const r=p.useRef($0),n=p.useRef(null),a=p.useRef(t);a.current=t;const[o,i]=p.useState(()=>F0(t,$0,0,window.innerHeight,window.innerHeight)),l=p.useCallback(()=>{const f=e.current;if(!f)return;const d=r.current,g=window.innerHeight,m=-f.getBoundingClientRect().top,x=d.rowHeight+d.rowGap,b=Math.floor(m/x);n.current=m>0?{index:b*d.columns,offset:m-b*x}:null;const h=F0(a.current,d,m,m+g,g);i(y=>y.startIndex===h.startIndex&&y.endIndex===h.endIndex&&y.paddingTop===h.paddingTop&&y.paddingBottom===h.paddingBottom?y:h)},[e]),c=p.useCallback(()=>{var b;const f=e.current;if(!f)return;const d=getComputedStyle(f),g=r.current,m={columns:d.gridTemplateColumns.split(" ").length,rowHeight:((b=f.firstElementChild)==null?void 0:b.getBoundingClientRect().height)||g.rowHeight,rowGap:parseFloat(d.rowGap)||0,columnGap:parseFloat(d.columnGap)||0,width:f.clientWidth};r.current=m;const x=n.current;if(x&&(m.columns!==g.columns||m.rowHeight!==g.rowHeight||m.rowGap!==g.rowGap)){const h=Math.floor(x.index/m.columns)*(m.rowHeight+m.rowGap)+x.offset;ss().scrollBy(0,h+f.getBoundingClientRect().top)}l()},[e,l]),u=t>0;return p.useLayoutEffect(()=>{const f=e.current;if(!u||!f)return;c();const d=new ResizeObserver(c);d.observe(f);const g=ss();return g.addEventListener("scroll",l,{passive:!0}),window.addEventListener("resize",c),()=>{d.disconnect(),n.current=null,g.removeEventListener("scroll",l),window.removeEventListener("resize",c)}},[e,u,c,l]),p.useLayoutEffect(()=>l(),[t,l]),{...o,metricsRef:r}}let z0=null;const Qu=new WeakMap;function WS(){return z0??(z0=new IntersectionObserver(e=>{var t;for(const r of e)r.isIntersecting&&((t=Qu.get(r.target))==null||t())},{rootMargin:"100% 0px"})),z0}function HS(e){const[t,r]=p.useState(()=>typeof IntersectionObserver>"u");return p.useEffect(()=>{const n=e.current;if(t||!n)return;const a=WS();return Qu.set(n,()=>r(!0)),a.observe(n),()=>{a.unobserve(n),Qu.delete(n)}},[t,e]),t}function Js({value:e,className:t="",variant:r="highlight"}){const[n,a]=p.useState(!1),o=p.useRef(null),i=r==="normal"?"bg-gray-100 text-gray-500 dark:bg-white/[0.04] dark:text-gray-400":"bg-yellow-100 text-yellow-800 dark:bg-yellow-500/20 dark:text-yellow-300";p.useEffect(()=>()=>{o.current!=null&&window.clearTimeout(o.current)},[]);const l=()=>{o.current!=null&&(window.clearTimeout(o.current),o.current=null)};return s.jsxs("span",{className:`relative inline-flex cursor-help ${i} ${t}`,role:"button",tabIndex:0,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onFocus:()=>a(!0),onBlur:()=>a(!1),onClick:()=>a(!0),onTouchStart:()=>{l(),o.current=window.setTimeout(()=>{a(!0),o.current=null},450)},onTouchEnd:l,onTouchCancel:l,children:[e,s.jsx(pt,{visible:n,className:"whitespace-nowrap",children:"API 实际响应值"})]})}function Fo(e,t,r=e.actualParams){const n=e.sourceMode==="agent"&&t==="n"?"auto":e.params[t],a=r==null?void 0:r[t],o=a!=null,i=o?a:n,l=o&&n!=="auto"&&String(a)!==String(n);return{displayValue:String(i),isMismatch:l,requestedValue:String(n),isAutoResolved:o&&n==="auto"&&String(a)!==String(n)}}function Eo({task:e,paramKey:t,className:r="",actualParams:n}){const{displayValue:a,isMismatch:o,requestedValue:i,isAutoResolved:l}=Fo(e,t,n);return o?s.jsxs("span",{className:`inline-flex items-center gap-1 ${r}`,children:[s.jsx("span",{className:"text-gray-700 dark:text-gray-300",children:i}),s.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"|"}),s.jsx(Js,{value:a,className:"rounded px-1 py-0.5"})]}):l?s.jsxs("span",{className:`inline-flex items-center gap-1 ${r}`,children:[s.jsx("span",{className:"text-gray-700 dark:text-gray-300",children:i}),s.jsx("span",{className:"text-gray-300 dark:text-gray-600",children:"|"}),s.jsx(Js,{value:a,variant:"normal",className:"rounded px-1 py-0.5"})]}):s.jsx("span",{className:`text-gray-700 dark:text-gray-300 ${r}`,children:a})}function xy(e){return(e.sourceMode==="agent"||!!(e.agentConversationId||e.agentRoundId))&&e.status==="running"&&!e.prompt.trim()}function Ro({tooltip:e,className:t,disabled:r=!1,onClick:n,children:a}){const[o,i]=p.useState(!1);return s.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:[s.jsx("button",{type:"button",onClick:n,className:t,disabled:r,"aria-label":e,children:a}),s.jsx(pt,{visible:o,className:"whitespace-nowrap",children:e})]})}function by({task:e,onReuse:t,onEditOutputs:r,onDelete:n,onClick:a,isSelected:o,disableSwipe:i}){var vt,ct,rt,V;const[l,c]=p.useState(""),[u,f]=p.useState(""),[d,g]=p.useState(""),[m,x]=p.useState(Date.now()),[b,h]=p.useState(!1),[y,v]=p.useState(!1),[I,S]=p.useState(!1),[k,j]=p.useState(0),[A,N]=p.useState(!1),C=w(X=>X.toggleTaskSelection),T=w(X=>X.settings),R=w(X=>X.openFavoritePicker),U=w(X=>!!X.privacyMode),W=w(X=>X.streamPreviews[e.id]||""),F=p.useRef(null),_=p.useRef(null),O=p.useRef(0),J=p.useRef(!1),H=p.useRef(0),K=p.useRef(!1),te=p.useRef(null),P=HS(te),B=p.useRef(0),$=p.useRef(0),Q=p.useRef(null),L=X=>{H.current!==X&&(H.current=X,j(X))},G=X=>{K.current!==X&&(K.current=X,S(X))},se=X=>{B.current=X,te.current&&(te.current.style.transform=X?`translateX(${X}px)`:"")},Y=()=>{Q.current!=null&&(window.cancelAnimationFrame(Q.current),Q.current=null)},le=X=>{Q.current==null&&B.current===X||($.current=X,Q.current==null&&(Q.current=window.requestAnimationFrame(()=>{Q.current=null,se($.current)})))},ie=X=>X instanceof Element&&!!X.closest("[data-tag-scroll-area]"),D=X=>{if(i||ie(X.target)){F.current=null,J.current=!1,h(!1),Y(),se(0),L(0),G(!1);return}_.current!=null&&(window.clearTimeout(_.current),_.current=null),F.current={x:X.touches[0].clientX,y:X.touches[0].clientY},J.current=!1,v(!!o),G(!1),L(0),Y(),se(0),h(!0)},ue=X=>{if(ie(X.target)||!F.current)return;const me=X.touches[0].clientX-F.current.x,ve=X.touches[0].clientY-F.current.y;if(Math.abs(me)>Math.abs(ve)&&Math.abs(me)>10){J.current=!0,X.preventDefault();const ae=Math.max(-60,Math.min(60,me)),_e=ae>0?1:ae<0?-1:0,Ye=Math.abs(me)>=40;le(ae),L(_e),G(Ye)}},ke=X=>{if(ie(X.target)){F.current=null,J.current=!1,h(!1),Y(),L(0),G(!1);return}if(h(!1),Y(),L(0),!F.current)return;const me=X.changedTouches[0].clientX-F.current.x;F.current=null;const ve=J.current&&Math.abs(me)>40;J.current=!1,G(ve),_.current=window.setTimeout(()=>{G(!1),_.current=null},220),ve&&(O.current=Date.now()+350,X.preventDefault(),X.stopPropagation(),C(e.id))},we=()=>{F.current=null,J.current=!1,h(!1),Y(),L(0),G(!1)};p.useEffect(()=>()=>{_.current!=null&&window.clearTimeout(_.current),Y()},[]),p.useEffect(()=>{b||se(0)},[b]),p.useEffect(()=>{N(!1)},[W,e.id]),p.useEffect(()=>{if(e.status!=="running"&&!(e.status==="error"&&(e.falRecoverable||e.customRecoverable)))return;const X=setInterval(()=>x(Date.now()),1e3);return x(Date.now()),()=>clearInterval(X)},[e.customRecoverable,e.falRecoverable,e.status]),p.useEffect(()=>{var _e;if(!P)return;f(""),g(""),c("");let X=!1;const me=(_e=e.outputImages)==null?void 0:_e[0];let ve;const ae=Ye=>{X||(c(Ye.src),Ye.width&&Ye.height&&(f(Zp(Ye.width,Ye.height)),g(`${Ye.width}×${Ye.height}`)))};return me&&(ve=Nx(me,ae),Sx(me).then(Ye=>{X||!Ye||ae(Ye)}).catch(()=>{X||c("")})),()=>{X=!0,ve==null||ve()}},[P,e.outputImages]);const We=(()=>{let X;if(e.status==="running"||e.falRecoverable||e.customRecoverable)X=Math.floor((m-(e.startedAt??e.createdAt))/1e3);else if(e.elapsed!=null)X=Math.floor(e.elapsed/1e3);else return"00:00";const me=String(Math.floor(X/60)).padStart(2,"0"),ve=String(X%60).padStart(2,"0");return`${me}:${ve}`})(),Ne=I,Fe=e.status==="error"&&e.falRecoverable,Ee=e.status==="error"&&e.customRecoverable,Ge=e.status==="running"||Fe||Ee,Xe=Ne?y?"bg-gray-500 dark:bg-gray-600":"bg-blue-500":"bg-gray-200 dark:bg-gray-700",ht=Fo(e,"quality"),Pe=e.params.quality!=="auto"||ht.isMismatch,ne=Fo(e,"size"),ge=e.params.size!=="auto"||ne.isMismatch,xe=Fo(e,"output_format"),fe=e.params.output_format!=="png"||xe.isMismatch,be=e.transparentOutput||e.params.transparent_output,Z=Fo(e,"n"),de=e.sourceMode==="agent"||!!(e.agentConversationId||e.agentRoundId),he=xy(e),pe=!de&&(e.params.n>1||Z.isMismatch),Be=((vt=e.outputErrors)==null?void 0:vt.length)??0,Oe=((ct=e.outputImages)==null?void 0:ct.length)??0,Ue=Math.max(e.params.n,Oe+Be),lt=e.status==="done"&&Be>0,ut=e.apiProvider==="fal"?_i:ir,Ve=e.apiModel&&e.apiModel!==ut,He=e.status==="error"&&e.error==="已停止生成。";return s.jsxs("div",{className:"relative rounded-xl",children:[s.jsx("div",{className:`absolute inset-0 rounded-xl flex items-center transition-opacity duration-200 pointer-events-none ${b||k!==0||I?"opacity-100":"opacity-0"} ${Xe} ${k>0?"justify-start pl-6":"justify-end pr-6"}`,children:s.jsx("svg",{className:`w-8 h-8 transition-transform duration-150 ${Ne?"scale-110 text-white":"scale-90 text-white/60"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:y&&Ne?s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"}):s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),s.jsxs("div",{ref:te,className:`relative bg-white dark:bg-gray-900 rounded-xl border overflow-hidden cursor-pointer touch-pan-y will-change-transform duration-200 hover:shadow-lg dark:hover:bg-gray-800/80 ${b?"!bg-white dark:!bg-gray-900":""} ${b?"transition-[box-shadow,border-color,background-color]":"transition-[box-shadow,border-color,background-color,transform]"} ${e.status==="running"?"border-blue-400 generating":o?"border-blue-500 shadow-md ring-2 ring-blue-500/50":"border-gray-200 dark:border-white/[0.08] hover:border-gray-300 dark:hover:border-white/[0.18]"}`,onClick:X=>{if(Date.now()<O.current){X.preventDefault(),X.stopPropagation();return}a(X)},onTouchStart:D,onTouchMove:ue,onTouchEnd:ke,onTouchCancel:we,draggable:e.status==="done"&&((rt=e.outputImages)==null?void 0:rt.length)>0,onDragStart:X=>{var ve;if(e.status!=="done"||!((ve=e.outputImages)!=null&&ve.length))return;const me=e.outputImages;if(X.dataTransfer.setData("text/plain",`agent-images:${me.join(",")}`),X.dataTransfer.effectAllowed="copy",l){const ae=document.createElement("div");ae.style.cssText="position:fixed;left:-1000px;top:-1000px;width:100px;height:100px;border-radius:12px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.25);";const _e=document.createElement("img");_e.src=l,_e.style.cssText="width:100px;height:100px;object-fit:cover;display:block;",ae.appendChild(_e),document.body.appendChild(ae),X.dataTransfer.setDragImage(ae,50,50),setTimeout(()=>ae.remove(),0)}},children:[o&&s.jsx("div",{className:"absolute top-2 right-2 z-10 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center shadow-sm",children:s.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}),s.jsxs("div",{className:"flex h-40",children:[s.jsxs("div",{className:"w-40 min-w-[10rem] h-full bg-gray-100 dark:bg-black/20 relative flex items-center justify-center overflow-hidden flex-shrink-0",children:[e.status==="running"&&W&&s.jsxs(s.Fragment,{children:[s.jsx("img",{src:W,className:`h-full w-full object-cover ${A?"":"hidden"}`,alt:"",onLoad:()=>N(!0),onError:()=>N(!1)}),A&&s.jsx("span",{className:"absolute top-1.5 right-1.5 flex items-center gap-1 rounded bg-blue-500 px-1.5 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm sm:text-xs",children:"预览"})]}),e.status==="running"&&(!W||!A)&&s.jsxs("div",{className:"flex flex-col items-center gap-2",children:[s.jsxs("svg",{className:"w-8 h-8 text-blue-400 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),s.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"生成中..."})]}),e.status==="error"&&Fe&&s.jsxs("div",{className:"flex flex-col items-center gap-1 px-2",children:[s.jsx("svg",{className:"w-7 h-7 text-yellow-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),s.jsx("span",{className:"text-xs text-yellow-500 text-center leading-tight",children:"重连中"})]}),e.status==="error"&&!Fe&&s.jsxs("div",{className:"flex flex-col items-center gap-1 px-2",children:[s.jsx("svg",{className:`w-7 h-7 ${He?"text-yellow-400":"text-red-400"}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx("span",{className:`text-xs text-center leading-tight ${He?"text-yellow-500":"text-red-400"}`,children:He?"已停止":"失败"})]}),e.status==="done"&&l&&s.jsxs(s.Fragment,{children:[s.jsx("img",{src:l,"data-image-id":e.outputImages[0],"data-output-image-ids":e.outputImages.join(","),className:"saveable-image w-full h-full object-cover",loading:"lazy",alt:""}),(lt||e.outputImages.length>1)&&s.jsx("span",{className:"absolute bottom-1 right-1 bg-black/60 text-white text-xs px-1.5 py-0.5 rounded",children:lt?s.jsxs(s.Fragment,{children:[Ue," | ",s.jsx("span",{className:"font-semibold text-yellow-300",children:Oe})]}):e.outputImages.length})]}),e.status==="done"&&!l&&s.jsx("svg",{className:"w-8 h-8 text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),s.jsx("div",{className:"absolute top-1.5 left-1.5 flex items-center gap-1",children:Ge||e.status!=="done"||!u||!d?s.jsxs("span",{className:"flex items-center gap-1 bg-black/50 text-white text-[10px] sm:text-xs px-1.5 py-0.5 rounded backdrop-blur-sm font-mono",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),We]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"bg-black/50 text-white text-[10px] sm:text-xs px-1.5 py-0.5 rounded backdrop-blur-sm font-mono",children:u}),s.jsx("span",{className:"bg-black/50 text-white/90 text-[10px] sm:text-xs px-1.5 py-0.5 rounded backdrop-blur-sm font-medium",children:d})]})})]}),s.jsxs("div",{className:"flex-1 p-3 flex flex-col min-w-0",children:[s.jsx("div",{className:"flex-1 min-h-0 mb-2 overflow-hidden",children:he?s.jsxs("div",{className:"leading-relaxed",children:[s.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:"正在生成……"}),s.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"输入内容将在响应完成时接收"})]}):s.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300 leading-relaxed line-clamp-3",children:ai(e.prompt,e.inputImageIds.length)||"(无提示词)"})}),s.jsxs("div",{className:"mt-auto flex flex-col gap-1.5",children:[s.jsxs("div",{"data-tag-scroll-area":!0,className:"flex overflow-x-auto hide-scrollbar pt-0.5 gap-1.5 whitespace-nowrap mask-edge-r min-w-0 pr-2",onTouchStart:X=>X.stopPropagation(),onTouchMove:X=>X.stopPropagation(),onTouchEnd:X=>X.stopPropagation(),onTouchCancel:X=>X.stopPropagation(),children:[(e.apiProfileName||e.apiProvider)&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 text-xs flex-shrink-0",title:e.apiProfileName||e.apiProvider,children:[s.jsx(uy,{className:"w-3 h-3 flex-shrink-0 text-gray-400"}),s.jsx("span",{className:"truncate max-w-[8rem]",children:e.apiProfileName||e.apiProvider})]}),Ve&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 text-xs flex-shrink-0",title:e.apiModel,children:[s.jsx("svg",{className:"w-3 h-3 flex-shrink-0 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"})}),s.jsx("span",{className:"truncate max-w-[8rem]",children:e.apiModel})]}),e.maskImageId&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 text-xs flex-shrink-0",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})}),"局部重绘"]}),be&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-emerald-50 dark:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-xs flex-shrink-0",children:[s.jsx(mS,{className:"w-3 h-3 flex-shrink-0"}),"透明背景"]}),Pe&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"质量"}),ht.isMismatch?s.jsx(Js,{value:ht.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:ht.displayValue})]}),ge&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"尺寸"}),ne.isMismatch?s.jsx(Js,{value:ne.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:ne.displayValue})]}),fe&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"格式"}),xe.isMismatch?s.jsx(Js,{value:xe.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:xe.displayValue})]}),pe&&s.jsxs("span",{className:"flex items-center gap-1 px-1.5 py-0.5 rounded bg-gray-100 dark:bg-white/[0.04] text-xs flex-shrink-0",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"数量"}),Z.isMismatch?s.jsx(Js,{value:Z.displayValue,className:"px-1 rounded-sm"}):s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:Z.displayValue})]})]}),s.jsxs("div",{"data-tag-scroll-area":!0,className:"flex items-center gap-1 flex-shrink-0 mt-0.5 ml-auto max-w-full overflow-x-auto hide-scrollbar mask-edge-r pr-2",onClick:X=>X.stopPropagation(),onTouchStart:X=>X.stopPropagation(),onTouchMove:X=>X.stopPropagation(),onTouchEnd:X=>X.stopPropagation(),onTouchCancel:X=>X.stopPropagation(),children:[(e.status==="error"&&!Fe&&!Ee||e.status==="done"&&T.alwaysShowRetryButton)&&s.jsx(Ro,{tooltip:"重试任务",onClick:()=>Eb(e),className:"p-1.5 rounded-md hover:bg-blue-50 dark:hover:bg-blue-950/30 text-gray-400 hover:text-blue-500 transition",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),!U&&s.jsx(Ro,{tooltip:e.isFavorite?"编辑收藏夹":"收藏任务",onClick:()=>R([e.id]),className:`p-1.5 rounded-md transition ${e.isFavorite?"text-yellow-400 hover:bg-yellow-50 dark:hover:bg-yellow-500/10":"text-gray-400 hover:text-yellow-400 hover:bg-yellow-50 dark:hover:bg-yellow-500/10"}`,children:s.jsx("svg",{className:"w-4 h-4",fill:e.isFavorite?"currentColor":"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})}),s.jsx(Ro,{tooltip:"复用配置",onClick:t,className:"p-1.5 rounded-md hover:bg-blue-50 dark:hover:bg-blue-950/30 text-gray-400 hover:text-blue-500 transition",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})})}),s.jsx(Ro,{tooltip:"编辑输出",onClick:r,className:"p-1.5 rounded-md hover:bg-green-50 dark:hover:bg-green-950/30 text-gray-400 hover:text-green-500 transition disabled:opacity-30",disabled:!((V=e.outputImages)!=null&&V.length),children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}),s.jsx(Ro,{tooltip:"删除任务",onClick:n,className:"p-1.5 rounded-md hover:bg-red-500/[0.1] dark:hover:bg-red-500/[0.16] text-gray-400 hover:text-red-600 transition",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})]})]})]})]})]})}function YS(){const e=sy(),t=w($=>$.searchQuery),r=w($=>$.filterStatus),n=w($=>$.filterFavorite),a=w($=>$.activeFavoriteCollectionId),o=w($=>$.defaultFavoriteCollectionId),i=w($=>$.setDetailTaskId),l=w($=>$.setConfirmDialog),c=w($=>$.setShowSettings),u=w($=>$.selectedTaskIds),f=w($=>$.setSelectedTaskIds),d=w($=>$.clearSelection),g=p.useRef(null),m=p.useRef(null),[x,b]=p.useState(null),h=p.useRef(null),y=p.useRef(null),v=p.useRef(!1),I=p.useRef(!1),S=p.useRef(null),k=p.useRef(null),j=p.useRef(0),A=p.useRef(0),N=p.useRef(!1),C=p.useRef(!1),T=p.useRef([]),R=/Mac|iPod|iPhone|iPad/.test(navigator.platform),U=p.useMemo(()=>{const $=[...e].sort((L,G)=>G.createdAt-L.createdAt),Q=t.trim().toLowerCase();return $.filter(L=>n&&(!L.isFavorite||a&&a!==or&&!Vr(L,o).includes(a))||!vi(L,r)?!1:jc(L,Q))},[e,t,r,n,a,o]),W=p.useRef(U);W.current=U;const{startIndex:F,endIndex:_,paddingTop:O,paddingBottom:J,metricsRef:H}=zS(m,U.length),K=$=>{l({title:"删除任务",message:"确定要删除这个任务吗?关联的图片资源也会被清理(如果没有其他任务引用)。",action:()=>wg($)})},te=($,Q)=>({pageX:$+window.scrollX,pageY:Q+tn()}),P=($,Q,L,G)=>{const se=te(Q,L);N.current=!!$.closest(".task-card-wrapper"),C.current=G,T.current=[...w.getState().selectedTaskIds],I.current=!0,v.current=!1,h.current=se,y.current={x:Q,y:L},document.body.classList.add("select-none"),document.body.classList.add("drag-selecting"),b({startPageX:se.pageX,startPageY:se.pageY,currentPageX:se.pageX,currentPageY:se.pageY})},B=($,Q)=>{const L=h.current;if(!L||!m.current)return;const G=Math.min(L.pageX,$),se=Math.max(L.pageX,$),Y=Math.min(L.pageY,Q),le=Math.max(L.pageY,Q),ie=W.current,D=m.current.getBoundingClientRect(),ue=D.left+window.scrollX,ke=D.top+tn(),we=new Set($S(ie.length,H.current,{left:G-ue,right:se-ue,top:Y-ke,bottom:le-ke})),We=new Set(T.current),Ne=new Set(T.current);ie.forEach((Fe,Ee)=>{const Ge=Fe.id;we.has(Ee)?Ne.has(Ge)?We.delete(Ge):We.add(Ge):Ne.has(Ge)||We.delete(Ge)}),f(Array.from(We))};return p.useEffect(()=>{const $=()=>{S.current&&(clearInterval(S.current),S.current=null),k.current=null},Q=ue=>{S.current&&k.current===ue||($(),k.current=ue,S.current=window.setInterval(()=>{ss().scrollBy({top:ue*15,behavior:"instant"})},16))},L=(ue=!1,ke=!1)=>{I.current&&(document.body.classList.remove("select-none"),document.body.classList.remove("drag-selecting")),I.current&&ue&&!v.current&&!N.current&&!C.current&&d(),I.current&&ke&&v.current&&(A.current=Date.now()+250),$(),I.current=!1,h.current=null,y.current=null,b(null)},G=ue=>ue.target instanceof Element?ue.target:document.elementFromPoint(ue.clientX,ue.clientY),se=ue=>{if(ue.button!==0)return;const ke=G(ue);if(!ke||!ke.closest("[data-drag-select-surface]")||ke.closest("[data-input-bar]")||ke.closest("[data-no-drag-select], [data-lightbox-root]")||ke.closest("button, a, input, textarea, select"))return;const we=R?ue.metaKey:ue.ctrlKey;P(ke,ue.clientX,ue.clientY,we),ue.preventDefault()},Y=ue=>{if(!I.current||!h.current)return;const ke=h.current,we=te(ue.clientX,ue.clientY);if(y.current={x:ue.clientX,y:ue.clientY},Math.hypot(we.pageX-ke.pageX,we.pageY-ke.pageY)<6&&!v.current)return;v.current=!0,b({startPageX:ke.pageX,startPageY:ke.pageY,currentPageX:we.pageX,currentPageY:we.pageY}),B(we.pageX,we.pageY),ue.preventDefault();const Ne=40;ue.clientY<Ne?Q(-1):ue.clientY>window.innerHeight-Ne?Q(1):$()},le=()=>{if(!I.current||!h.current||!y.current||!v.current)return;const ue=te(y.current.x,y.current.y),ke=h.current;b({startPageX:ke.pageX,startPageY:ke.pageY,currentPageX:ue.pageX,currentPageY:ue.pageY}),B(ue.pageX,ue.pageY)},ie=ue=>{if(!I.current)return;if((ue.buttons&1)===0){L();return}if(!v.current||!ue.ctrlKey&&!ue.metaKey)return;ue.preventDefault();const ke=Date.now();if(ke-j.current>3e3){j.current=ke;const we=R?"⌘":"Ctrl";w.getState().showToast(`松开 ${we} 键使用滚轮,或拖至边缘自动滚动`,"info")}},D=()=>{L(!0,!0)};return document.addEventListener("mousedown",se,!0),document.addEventListener("mousemove",Y,!0),document.addEventListener("mouseup",D,!0),document.addEventListener("wheel",ie,{capture:!0,passive:!1}),window.addEventListener("scroll",le,!0),()=>{$(),document.removeEventListener("mousedown",se,!0),document.removeEventListener("mousemove",Y,!0),document.removeEventListener("mouseup",D,!0),document.removeEventListener("wheel",ie,!0),window.removeEventListener("scroll",le,!0)}},[d,R]),U.length?s.jsxs("div",{ref:g,"data-task-grid-root":!0,className:"relative min-h-[50vh] pb-10",children:[s.jsx("div",{ref:m,className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",style:{paddingTop:O,paddingBottom:J},children:U.slice(F,_).map($=>s.jsx("div",{className:"task-card-wrapper","data-task-id":$.id,children:s.jsx(by,{task:$,onClick:Q=>{if(Date.now()<A.current){Q.preventDefault();return}if(A.current=0,R?Q.metaKey:Q.ctrlKey){w.getState().toggleTaskSelection($.id);return}i($.id)},onReuse:()=>yg($),onEditOutputs:()=>vg($),onDelete:()=>K($),isSelected:u.includes($.id)})},$.id))}),x&&s.jsx("div",{className:"fixed bg-blue-500/20 border border-blue-500/50 pointer-events-none z-[30]",style:{left:Math.min(x.startPageX,x.currentPageX)-window.scrollX,top:Math.min(x.startPageY,x.currentPageY)-tn(),width:Math.abs(x.currentPageX-x.startPageX),height:Math.abs(x.currentPageY-x.startPageY)}})]}):s.jsx("div",{className:"text-center py-20 text-gray-400 dark:text-gray-500",children:t||n?s.jsx("p",{className:"text-sm",children:"没有找到匹配的任务"}):s.jsxs(s.Fragment,{children:[s.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 text-gray-200 dark:text-gray-700",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),s.jsx("p",{className:"text-sm",children:"输入提示词开始生成图片"}),De&&!e.length&&s.jsxs("p",{className:"mt-3 text-xs",children:["从网页版迁移:在网页版的",s.jsx("strong",{className:"font-semibold",children:"「设置 → 数据管理」"}),"中导出备份,再",s.jsx("button",{type:"button",onClick:()=>c(!0,"data"),className:"mx-0.5 text-blue-500 hover:text-blue-600 hover:underline dark:text-blue-400 dark:hover:text-blue-300",children:"在这里导入"})]})]})})}async function fn(e){var r;if(De)return await y5(e);let t=null;if((r=navigator.clipboard)!=null&&r.writeText)try{await navigator.clipboard.writeText(e);return}catch(n){t=n}if(!VS(e))throw t??new Error("Clipboard API is not available")}async function yy(e){if(!vy())throw new Error("Clipboard image API is not available");if(!KS("image/png"))throw new Error("当前浏览器不支持图像剪贴板写入");const t=(async()=>{const r=await e;if(!r)throw new Error("Image source is not available");const a=await(await Dr(r)).blob();if(!a.type.startsWith("image/"))throw new Error("Clipboard item is not an image");return a.type==="image/png"?a:await XS(a)})();t.catch(()=>{}),await navigator.clipboard.write([new ClipboardItem({"image/png":t})])}function vy(){var e;return window.isSecureContext&&!!((e=navigator.clipboard)!=null&&e.write)&&typeof ClipboardItem<"u"}function $r(e,t){return qS()&&JS(t)?"复制失败:内嵌页面未授予剪贴板权限":t instanceof Error&&t.message.startsWith("当前浏览器不支持")?`复制失败:${t.message}`:e}function VS(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select(),t.setSelectionRange(0,t.value.length);try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(t)}}function KS(e){const t=ClipboardItem.supports;return t?t(e):e==="image/png"}async function XS(e){const t=await createImageBitmap(e);try{const r=document.createElement("canvas");r.width=t.width,r.height=t.height;const n=r.getContext("2d");if(!n)throw new Error("Canvas is not available");return n.drawImage(t,0,0),await new Promise((a,o)=>{r.toBlob(i=>{i?a(i):o(new Error("Image conversion failed"))},"image/png")})}finally{t.close()}}function qS(){try{return window.self!==window.top}catch{return!0}}function JS(e){return e instanceof Error?e.name==="NotAllowedError"||/permission|permissions policy|not allowed|denied/i.test(e.message):!1}function GS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ZS(e,t){const r=e[t];return typeof r=="string"&&r.trim()?r:void 0}function QS(e){return typeof e=="string"&&e.trim()?e:GS(e)?ZS(e,"type")??"search":"search"}function e4(e){return e==="open_page"?"正在读取网页":e==="find_in_page"?"正在查找内容":"正在搜索网页"}function t4(e){return(e??[]).filter(t=>t.type==="web_search_call").map(t=>({...t.id?{id:t.id}:{},...t.status?{status:t.status}:{},actionType:QS(t.action)}))}function r4(e){const t=e[e.length-1];if(!t)return null;if(e.some(n=>n.status==="failed"))return{text:"搜索失败",completed:!0};const r=e.every(n=>n.status==="completed");return{text:r?"完成搜索":e4(t.actionType),completed:r}}function n4(e,t){var r;if(!e)return[];if((r=e.responseOutput)!=null&&r.length)return e.responseOutput;for(const n of e.outputTaskIds){const a=t.find(o=>o.id===n);if(a!=null&&a.rawResponsePayload)try{const o=JSON.parse(a.rawResponsePayload),i=Ns(o.output);if(i.length)return i}catch{continue}}return[]}const s4="已停止生成。";function a4(e){return(e==null?void 0:e.status)==="error"&&e.error===s4}function W0(e){return e.completed?e:{text:e.text.replace(/^正在/,"已停止"),completed:!0}}function H0(e,t){return t.type==="image_generation_call"?!!(e.agentToolCallId&&e.agentToolCallId===t.id):t.type==="function_call"&&t.name==="generate_image"&&t.call_id?e.agentToolCallId===t.call_id:t.type==="function_call"&&t.name==="generate_image_batch"&&t.call_id?e.agentBatchCallId===t.call_id:!1}function o4(e){if(e.type!=="function_call"||e.name!=="generate_image_batch"||!e.arguments)return 0;try{const t=JSON.parse(e.arguments);return Array.isArray(t.images)?t.images.filter(r=>{if(!r||typeof r!="object")return!1;const n=r.prompt;return typeof n=="string"&&!!n.trim()}).length:0}catch{return 0}}function i4(e){return e.type!=="message"?"":(e.content??[]).map(t=>(t.type==="output_text"||t.type==="text")&&typeof t.text=="string"?t.text:t.type==="refusal"&&typeof t.refusal=="string"?t.refusal:"").filter(Boolean).join(`
|
|
73
|
+
`).trim()}function l4(e,t,r,n){const a=n4(e,r),o=new Set,i=t.filter(k=>o.has(k.taskId)?!1:(o.add(k.taskId),!0)),l=a4(e),c=[],u=new Set,f=k=>{u.has(k.taskId)||(u.add(k.taskId),c.push(k.task?{type:"image-task",task:k.task,key:`image:${k.taskId}`}:{type:"deleted-image-task",taskId:k.taskId,key:`deleted-image:${k.taskId}`}))};if(a.length===0){n&&c.push({type:"text",key:"text:fallback"});for(const k of i)f(k);return c}const d=[],g=new Set,m=new Set;let x=0;for(const[k,j]of a.entries()){const A=j.type==="image_generation_call"||j.type==="function_call"&&j.name==="generate_image",N=j.type==="function_call"&&j.name==="generate_image_batch";if(!A&&!N)continue;const C=j.type==="image_generation_call"&&j.id?`image_generation_call:${j.id}`:j.type==="function_call"&&j.call_id?`${j.name}:${j.call_id}`:null;if(C&&m.has(C)){g.add(k);continue}C&&m.add(C);const T=i.map((_,O)=>_.task&&H0(_.task,j)?O:-1).filter(_=>_>=0),R=A?1:Math.max(o4(j),T.length),U=R>i.length&&T.length>0?T.length:R;if(U===0||U>i.length)continue;let W=-1;for(let _=x;_+U<=i.length;_+=1)if(!i.slice(_,_+U).some(J=>J.task&&!H0(J.task,j))&&!T.some(J=>J<_||J>=_+U)){W=_;break}if(W<0)continue;const F=W+U;d.push({outputIndex:k,start:W,end:F,before:[],slots:i.slice(W,F),after:[]}),x=F}const b=new Set(d.flatMap(k=>k.slots.map(j=>j.taskId)));for(const[k,j]of i.entries()){if(j.task||b.has(j.taskId))continue;let A;for(const C of d){if(C.end>k)break;A=C}if(A){A.after.push(j),b.add(j.taskId);continue}const N=d.find(C=>C.start>k);N&&(N.before.push(j),b.add(j.taskId))}const h=new Map(d.map(k=>[k.outputIndex,k]));let y=0,v=[],I=-1;const S=()=>{if(v.length===0)return;const k=r4(t4(v));k&&c.push({type:"web-search",status:l?W0(k):k,key:`web-search:${I}`}),v=[],I=-1};for(const[k,j]of a.entries()){if(j.type==="web_search_call"){v.length===0&&(I=k),v.push(j);continue}S();const A=j.type==="image_generation_call"||j.type==="function_call"&&j.name==="generate_image",N=j.type==="function_call"&&j.name==="generate_image_batch";if(g.has(k))continue;const C=h.get(k);if(C){for(const T of[...C.before,...C.slots,...C.after])f(T);continue}if(!A){if(((e==null?void 0:e.status)==="running"||l)&&N){c.push({type:"batch-params",status:l?W0({text:"正在填写并发图像生成参数",completed:!1}):{text:"正在填写并发图像生成参数",completed:!1},key:`batch-params:${j.call_id??j.id??k}:${k}`});continue}if(j.type==="message"){const T=i4(j);T&&(y+=1,c.push({type:"text",key:`text:${j.id??k}:${k}`,content:T}))}}}S(),n&&y===0&&c.push({type:"text",key:"text:fallback"});for(const k of i)f(k);return c}function c4(e,t){if(!t.some(n=>n.type!=="text"))return e;const r=t.filter(n=>n.type==="text").map(n=>n.content??"").map(n=>n.trim()).filter(Boolean);return r.length>0?r.join(`
|
|
74
|
+
|
|
75
|
+
`):e}function d4(e,t){return e?e.outputTaskIds.map(r=>({taskId:r,task:t.find(n=>n.id===r)??null})):[]}const u4={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function Kn(e,t){return t?`${e},已保存到 ${t}`:e}function Zt(e){return typeof e=="string"?`下载失败,${e}`:"下载失败"}async function Xn(e,t="images",r){if(e.length===0)return{successCount:0,failCount:0};let n=0,a=0,o,i;const l=e.length>1,c=r??(De&&l?await ug():null);return De&&l&&!c?{successCount:n,failCount:a,canceled:!0}:Ba(async()=>{for(let u=0;u<e.length;u++)try{const f=await wy(e[u]),d=String(u+1).padStart(2,"0"),g=l?`${t}-${d}.${Yl(f)}`:`${t}.${Yl(f)}`,m=De?dc(g)||`image-${d}.${Yl(f)}`:g,x=c?await yd(c,f,m):await yc(f,m);if(!x)return{successCount:n,failCount:a,canceled:!0};De&&(o=(c==null?void 0:c.path)??x),n++,l&&!c&&await f4(100)}catch(f){console.error(f),typeof f=="string"&&(i=f),a++}return{successCount:n,failCount:a,location:o,error:i}})}async function so(e,t="images",r){return e.length===0?{successCount:0,failCount:0}:Ba(async()=>{let n=0,a=0,o;const i={},l=new Set;for(let c=0;c<e.length;c++){const u=e[c];try{const f=await wy(u.imageId),d=String(c+1).padStart(2,"0"),g=dc(u.fileNameBase||`image-${d}`)||`image-${d}`,m=Yl(f);let x=`${g}.${m}`,b=2;for(;l.has(x);)x=`${g}-${String(b).padStart(2,"0")}.${m}`,b++;l.add(x),i[x]=[new Uint8Array(await f.arrayBuffer()),{mtime:new Date}],n++}catch(f){console.error(f),a++}}if(n>0){const c=cC(i,{level:6}),u=`${dc(t)||"images"}.zip`;if(r)await yd(r,c,u),o=r.path;else if(De){const f=await yc(c,u);if(!f)return{successCount:0,failCount:a,canceled:!0};o=f}else{const f=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);await yc(new Blob([f],{type:"application/zip"}),u)}}return{successCount:n,failCount:a,location:o}})}function Y0(e){return[...e].sort((t,r)=>r.createdAt-t.createdAt).flatMap(t=>Ni(t.outputImages||[],`task-${t.id}`))}function Ni(e,t="image"){return e.map((r,n)=>({imageId:r,fileNameBase:Ex(t,n,e.length)}))}async function wy(e){let t=e;!e.startsWith("data:")&&!e.startsWith("http://")&&!e.startsWith("https://")&&(t=await kt(e)??e);const r=await Dr(t);if(!r.ok&&!t.startsWith("data:"))throw new Error(`读取图片失败:${e}`);return await r.blob()}function Yl(e){return u4[e.type.toLowerCase()]??e.type.split("/")[1]??"png"}function f4(e){return new Promise(t=>window.setTimeout(t,e))}const Gs=26;function ky({index:e,active:t=!1,className:r="",style:n,...a}){return s.jsx("div",{...a,className:`flex origin-bottom-left select-none items-center justify-center rounded-full rounded-bl-[3px] bg-blue-500 text-[11px] font-semibold tabular-nums text-white shadow-[0_2px_6px_rgba(0,0,0,0.25)] ring-2 ring-white transition-transform dark:ring-white/40 ${t?"scale-110":""} ${r}`,style:{width:Gs,height:Gs,...n},children:e+1})}function Ng({count:e,className:t}){return s.jsxs("span",{className:`absolute z-10 flex items-center gap-0.5 rounded bg-blue-500/90 px-1 py-0.5 text-[8px] font-bold leading-none text-white backdrop-blur-sm pointer-events-none ${t}`,children:[s.jsx("svg",{className:"h-2 w-2",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:s.jsx("path",{d:"M4 3h16a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-8l-6 4.5V18H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"})}),e]})}const g4=new Set(["http:","https:","mailto:","tel:"]);function m4({node:e,src:t,onError:r,...n}){const[a,o]=p.useState();return t?a===t?s.jsx("span",{className:"text-muted-foreground text-xs italic",children:"图片不可用"}):s.jsx("img",{...n,src:t,onError:i=>{o(t),r==null||r(i)}}):null}function ef(e){try{const t=new URL(e,window.location.origin);return g4.has(t.protocol)?e:"#blocked"}catch{return"#blocked"}}const h4={a({children:e,href:t,node:r,...n}){const a=!!(t&&t!=="#blocked");return s.jsx("a",{...n,href:t,rel:a?"noreferrer":void 0,target:a?"_blank":void 0,children:e})},img:m4},p4={a({children:e,href:t,...r}){const n=ef(t??""),a=n!=="#blocked";return s.jsx("a",{...r,href:n,rel:a?"noreferrer":void 0,target:a?"_blank":void 0,children:e})}},x4={copied:"已复制",copyCode:"复制代码",copyLink:"复制链接",copyTable:"复制表格",copyTableAsCsv:"复制为 CSV",copyTableAsMarkdown:"复制为 Markdown",copyTableAsTsv:"复制为 TSV",downloadFile:"下载文件",downloadImage:"下载图片",downloadTable:"下载表格",downloadTableAsCsv:"下载为 CSV",downloadTableAsMarkdown:"下载为 Markdown",externalLinkWarning:"即将打开外部链接",imageNotAvailable:"图片不可用",openExternalLink:"打开外部链接",openLink:"打开链接",tableFormatCsv:"CSV",tableFormatMarkdown:"Markdown",tableFormatTsv:"TSV",viewFullscreen:"全屏查看"},b4=(()=>{try{return new RegExp("(?<=a)b"),typeof Array.prototype.at=="function"}catch{return!1}})();let V0=null,K0=null;function X0(){return K0??(K0=Promise.all([aa(()=>import("./index-BBj85vBi.js"),__vite__mapDeps([2,3,4,5,6,7,8]),import.meta.url),aa(()=>import("./index-BugPYPDb.js"),__vite__mapDeps([9,8,3,10]),import.meta.url)]).then(([e,t])=>({type:"legacy",module:{ReactMarkdown:e.default,remarkGfm:t.default}})).catch(e=>(console.error("Legacy markdown renderer failed to load:",e),{type:"plain"}))),K0}function y4(){return b4?(V0??(V0=Promise.all([aa(()=>import("./mermaid-GHXKKRXX-Dxz-gSLM.js").then(e=>e.i),__vite__mapDeps([11,4,5,8,3,6,7,12,9,10]),import.meta.url),aa(()=>import("./index-PLZKjL94.js"),__vite__mapDeps([13,3,10,12,7]),import.meta.url)]).then(([e,t])=>({type:"modern",Component:e.Streamdown,math:{math:t.createMathPlugin({errorColor:"var(--muted-foreground)",singleDollarTextMath:!0})}})).catch(e=>(console.error("Streamdown failed to load:",e),X0()))),V0):X0()}function v4({content:e,className:t=""}){return s.jsx("div",{className:`markdown-renderer ${t}`.trim(),dir:"auto",style:{whiteSpace:"pre-wrap"},children:e})}const Ai=p.memo(function({content:t,streaming:r=!1,className:n=""}){const[a,o]=p.useState({type:"loading"});if(p.useEffect(()=>{let l=!1;return y4().then(c=>{l||o(c)}),()=>{l=!0}},[]),a.type==="legacy"){const{ReactMarkdown:l,remarkGfm:c}=a.module;return s.jsx("div",{className:`markdown-renderer ${n}`.trim(),dir:"auto",children:s.jsx(l,{components:p4,remarkPlugins:[c],urlTransform:ef,children:t})})}if(a.type!=="modern")return s.jsx(v4,{content:t,className:n});const i=a.Component;return s.jsx(i,{className:`markdown-renderer ${n}`.trim(),components:h4,controls:{code:{copy:!0,download:!1},mermaid:!1,table:{copy:!0,download:!1,fullscreen:!0}},dir:"auto",isAnimating:r,lineNumbers:!1,mode:r?"streaming":"static",parseIncompleteMarkdown:r,plugins:{math:a.math.math},translations:x4,urlTransform:ef,children:t})});function w4({imageId:e,imageIndex:t,maskImageId:r,round:n}){const[a,o]=p.useState(()=>En(e)||""),i=w(c=>c.setLightboxImageId),l=Ya(n.prompt,t).length;return p.useEffect(()=>{let c=!1;if(r)return Promise.all([kt(e),kt(r)]).then(async([f,d])=>!f||!d?f||"":rd(f,d)).then(f=>{!c&&f&&o(f)}).catch(()=>{c||o(En(e)||"")}),()=>{c=!0};const u=En(e);return u?(o(u),()=>{c=!0}):(kt(e).then(f=>{!c&&f&&o(f)}),()=>{c=!0})},[e,r]),s.jsxs("div",{className:`relative h-16 w-16 shrink-0 overflow-hidden rounded-lg shadow-sm cursor-pointer transition-opacity hover:opacity-90 ${r||l>0?"border-2 border-blue-500":"border border-gray-200 dark:border-white/[0.08]"}`,onClick:()=>i(e,n.inputImageIds,n.prompt),children:[a?s.jsx("img",{src:a,className:"h-full w-full object-cover",alt:""}):s.jsx("div",{className:"h-full w-full bg-gray-100 dark:bg-white/[0.04]"}),r&&s.jsx("span",{className:"absolute left-1 top-1 z-10 rounded bg-blue-500/90 px-1.5 py-0.5 text-[8px] font-bold leading-none tracking-wider text-white backdrop-blur-sm pointer-events-none",children:"MASK"}),l>0&&s.jsx(Ng,{count:l,className:r?"left-1 top-[18px]":"left-1 top-1"}),s.jsx("span",{className:"absolute bottom-1 left-1 z-10 flex h-4 w-4 items-center justify-center rounded-full bg-black/55 text-[9px] font-semibold text-white backdrop-blur-sm pointer-events-none",children:t+1})]})}function k4(){return s.jsx("span",{"aria-label":"正在生成",className:"ml-1 inline-block h-2 w-2 animate-pulse rounded-full bg-blue-500 align-baseline dark:bg-blue-400"})}function I4(e){return new Date(e).toLocaleString()}function Iy({status:e}){return s.jsx("span",{className:"inline-flex text-sm font-medium text-gray-500 dark:text-gray-400",children:s.jsx("span",{className:e.completed?void 0:"agent-web-search-running-text",children:e.text})})}function C4({statuses:e}){return e.length===0?null:s.jsx("div",{className:"mb-2 space-y-1",children:e.map((t,r)=>s.jsx("div",{children:s.jsx(Iy,{status:t})},`${t.text}-${r}`))})}const q0=24,J0=48,j4=24;function S4(){const e=ay(),t=w(V=>V.agentConversationsLoaded),r=w(V=>V.activeAgentConversationId),n=w(V=>V.createAgentConversation),a=w(V=>V.setActiveAgentConversationId),o=w(V=>V.renameAgentConversation),i=w(V=>V.deleteAgentConversation),l=w(V=>V.deleteAgentRound),c=w(V=>V.deleteAgentAssistantMessage),u=w(V=>V.agentSidebarCollapsed),f=w(V=>V.setAgentSidebarCollapsed),d=w(V=>V.agentMobileHeaderVisible),g=w(V=>V.setAgentMobileHeaderVisible),m=w(V=>V.appMode),x=w(V=>V.tasks),b=w(V=>V.setConfirmDialog),h=w(V=>V.setDetailTaskId),y=w(V=>V.setPrompt),v=w(V=>V.setInputImages),I=w(V=>V.setMaskDraft),S=w(V=>V.clearMaskDraft),k=w(V=>V.setAppMode),j=w(V=>V.settings.agentScrollToBottomAfterSubmit),A=w(V=>V.agentEditingRoundId),N=w(V=>V.agentEditingConversationId),C=w(V=>V.setAgentEditingConversationId),T=w(V=>V.setAgentEditingRoundId),R=w(V=>V.setActiveAgentRoundId),U=w(V=>V.showToast),W=w(V=>V.openFavoritePicker),F=w(V=>!!V.privacyMode),_=w(V=>V.agentGeneratingTitleIds),O=e.find(V=>V.id===r)??null,[J,H]=p.useState(""),K=p.useRef(null),te=p.useRef(null),P=p.useRef(new Map),[B,$]=p.useState(null),[Q,L]=p.useState(0),[G,se]=p.useState(!0),[Y,le]=p.useState(""),[ie,D]=p.useState(null),[ue,ke]=p.useState(!0),we=p.useRef(-1),We=p.useRef(null),Ne=p.useRef({conversationId:null,lastUserMessageSignature:null}),Fe=p.useRef(null),Ee=p.useCallback(()=>{var me;const V=te.current;if(m!=="agent"||!V){ke(!0);return}const X=((me=window.visualViewport)==null?void 0:me.height)??window.innerHeight;ke(V.getBoundingClientRect().top<=X+24)},[m]),Ge=p.useCallback(()=>{ss().scrollTo({top:Number.MAX_SAFE_INTEGER,behavior:"smooth"})},[]),Xe=V=>{var me;const X=((me=V.touches[0])==null?void 0:me.clientY)??-1;if(m!=="agent"||d||tn()>0||X<j4){we.current=-1,L(0);return}we.current=X},ht=V=>{we.current=V.touches[0].clientY},Pe=V=>{if(we.current<=0||d)return;const X=V.touches[0].clientY-we.current;if(X<=0){L(0);return}if(V.cancelable&&V.preventDefault(),X>=q0){g(!0),L(0),we.current=-1;return}L(Math.min(X,J0))},ne=V=>{we.current>0&&!d&&V.changedTouches[0].clientY-we.current>=q0&&g(!0),L(0),we.current=-1};p.useEffect(()=>{u&&C(null)},[u,C]),p.useEffect(()=>{if(m==="agent")return document.documentElement.classList.add("agent-no-pull-refresh"),()=>document.documentElement.classList.remove("agent-no-pull-refresh")},[m]),p.useEffect(()=>{if(!d||m!=="agent")return;const V=X=>{X.target.closest("header[data-no-drag-select]")||g(!1)};return document.addEventListener("mousedown",V,{capture:!0}),document.addEventListener("touchstart",V,{capture:!0}),()=>{document.removeEventListener("mousedown",V,{capture:!0}),document.removeEventListener("touchstart",V,{capture:!0})}},[d,m,g]),p.useEffect(()=>{if(m!=="agent"||!u)return;const V=X=>{if(!(X.ctrlKey||!(X.target instanceof Element)||!X.target.closest("[data-page-scroll]"))){if(d){X.deltaY>0&&!X.target.closest("header[data-no-drag-select]")&&g(!1);return}X.deltaY<0&&tn()<=0&&g(!0)}};return window.addEventListener("wheel",V,{passive:!0}),()=>window.removeEventListener("wheel",V)},[d,m,g,u]),p.useEffect(()=>{if(m!=="agent")return;se(!0);let V=tn(),X=!1;const me=()=>{X||(window.requestAnimationFrame(()=>{const Ye=tn();Ye<20?se(!0):Ye>V+10?se(!1):Ye<V-10&&se(!0),Ee(),V=Ye,X=!1}),X=!0)},ve=window.requestAnimationFrame(Ee),ae=window.visualViewport,_e=ss();return _e.addEventListener("scroll",me,{passive:!0}),window.addEventListener("resize",Ee),ae==null||ae.addEventListener("resize",Ee),()=>{window.cancelAnimationFrame(ve),_e.removeEventListener("scroll",me),window.removeEventListener("resize",Ee),ae==null||ae.removeEventListener("resize",Ee)}},[m,Ee]),p.useEffect(()=>{if(m==="agent"&&t){if(e.length===0)n();else if(!O){const V=[...e].sort((X,me)=>me.updatedAt-X.updatedAt)[0];V&&V.messages.length===0?a(V.id):n()}}},[m,t,e,O,n,a]);const ge=p.useMemo(()=>[...e].sort((V,X)=>X.updatedAt-V.updatedAt),[e]),xe=p.useMemo(()=>{const V=Y.trim().toLocaleLowerCase();return V?ge.filter(X=>ux(X).includes(V)):ge},[Y,ge]),fe=p.useMemo(()=>O?fa(O):[],[O]),be=p.useMemo(()=>{if(!O)return[];const V=[];for(const X of fe){const me=O.messages.find(ae=>ae.id===X.userMessageId);me&&V.push(me);const ve=X.assistantMessageId?O.messages.find(ae=>ae.id===X.assistantMessageId):O.messages.find(ae=>ae.roundId===X.id&&ae.role==="assistant");ve&&V.push(ve)}return V},[fe,O]);p.useEffect(()=>{const V=(O==null?void 0:O.id)??null,X=be[be.length-1]??null,me=(X==null?void 0:X.role)==="user"?`${X.id}:${X.createdAt}:${X.content}`:null,ve=Ne.current,ae=m==="agent"&&j&&ve.conversationId===V&&(X==null?void 0:X.role)==="user"&&me!=null&&ve.lastUserMessageSignature!==me;if(Ne.current={conversationId:V,lastUserMessageSignature:me},!ae)return;const _e=window.requestAnimationFrame(()=>{Ge()});return()=>window.cancelAnimationFrame(_e)},[be,j,m,O==null?void 0:O.id,Ge]),p.useEffect(()=>{const V=window.requestAnimationFrame(Ee);return()=>window.cancelAnimationFrame(V)},[be,fe,Ee]),p.useEffect(()=>{if(!B)return;const V=window.requestAnimationFrame(()=>{var X;(X=P.current.get(B))==null||X.scrollIntoView({block:"center"}),$(null)});return()=>window.cancelAnimationFrame(V)},[be,B]);const Z=(V,X)=>{if(!O)return;const me=Jm(O,V);if(me.length<=1)return;const ve=me.findIndex(Ye=>Ye.id===V.id),ae=me[(ve+X+me.length)%me.length],_e=r2(O,ae.id);R(O.id,_e),T(null),$(ae.id)},de=V=>{const X=e.find(qe=>qe.id===V)??null,me=new Set((X==null?void 0:X.rounds.map(qe=>qe.id))??[]),ve=(X==null?void 0:X.rounds.flatMap(qe=>qe.outputTaskIds))??[],ae=x.filter(qe=>qe.agentConversationId===V||!!(qe.agentRoundId&&me.has(qe.agentRoundId))),_e=new Set(x.map(qe=>qe.id)),Ye=Array.from(new Set([...ve,...ae.map(qe=>qe.id)])).filter(qe=>_e.has(qe)),wt=new Set(Ye),xt=new Set(x.filter(qe=>wt.has(qe.id)).flatMap(qe=>qe.outputImages||[])).size;b({title:"删除对话",message:"确定要删除这个 Agent 对话吗?",checkbox:xt>0?{label:`同时删除对话中生成的图片(${xt} 张)`,tone:"danger"}:void 0,action:async(qe=!1)=>{i(V),qe&&Ye.length>0&&await Zi(Ye)}})},he=(V,X,me)=>{if(V.stopPropagation(),_[X]){U("标题生成中,暂不能修改标题","info");return}C(X),H(me)},pe=()=>{N&&J.trim()&&!_[N]&&o(N,J.trim()),C(null)},Be=V=>{V.key==="Enter"?(V.preventDefault(),pe()):V.key==="Escape"&&(V.preventDefault(),C(null))};p.useEffect(()=>{if(N){const V=e.find(X=>X.id===N);V&&H(V.title)}},[N,e]);const Oe=()=>{We.current!=null&&(window.clearTimeout(We.current),We.current=null)},Ue=(V,X)=>{X.pointerType!=="mouse"&&(Oe(),We.current=window.setTimeout(()=>{D(V),We.current=null},450))},lt=V=>{a(V),ie&&ie!==V&&D(null)};p.useEffect(()=>{if(!ie)return;const V=X=>{const me=X.target;me!=null&&me.closest("[data-agent-conversation-item]")||D(null)};return document.addEventListener("pointerdown",V,{capture:!0}),()=>document.removeEventListener("pointerdown",V,{capture:!0})},[ie]);const ut=(V,X)=>{const me=V.role==="user",ve=O==null?void 0:O.id;b({title:me?"删除轮次":"删除消息",message:me?"确定要删除这轮任务吗?这会删除这条消息和它的输出,后续消息会被保留。":"确定要删除这条消息吗?这会同时删除这条回复生成的图片。",awaitAction:!0,action:async()=>{if(!ve)return!0;try{const ae=me?await l(ve,X.id):await c(ve,V.id);return ae==="running"?(U("该轮次仍在生成,请先停止生成后再删除","info"),!0):ae==="not-found"?(U(me?"该轮次已不存在":"该消息已不存在","info"),!0):ae==="deleted-with-warning"?(U("已删除,但本地存储或图片清理未完成","error"),!0):(U(me?"已删除轮次":"已删除消息","success"),!0)}catch(ae){return console.error(ae),U(me?"删除轮次失败":"删除消息失败","error"),!1}}})},Ve=V=>{b({title:"切换到画廊模式?",message:"复用参数会应用到画廊输入区。切换到画廊模式后,当前 Agent 对话仍会保留。",confirmText:"切换并复用",cancelText:"取消",action:()=>{k("gallery"),yg(V)}})},He=async(V,X)=>{T(V.id),S();const me=await Promise.all(V.inputImageIds.map(async ae=>({id:ae,dataUrl:await kt(ae)||""})));v(me);const ve=V.maskTargetImageId??(V.maskImageId?V.inputImageIds[0]:null);if(ve&&V.maskImageId&&me.some(ae=>ae.id===ve)){const ae=await kt(V.maskImageId);ae&&I({targetImageId:ve,maskDataUrl:ae,updatedAt:Date.now()})}y(X)},vt=async(V,X="提示词已复制",me="复制提示词失败")=>{try{await fn(V),U(X,"success")}catch(ve){U($r(me,ve),"error")}},ct=V=>{Fe.current={x:V.clientX,y:V.clientY}},rt=(V,X)=>{V.stopPropagation();const me=Fe.current;if(Fe.current=null,me&&Math.hypot(V.clientX-me.x,V.clientY-me.y)>4)return;const ve=window.getSelection();if(ve&&!ve.isCollapsed&&ve.toString().trim()){const ae=V.currentTarget;if(ve.anchorNode&&ae.contains(ve.anchorNode)||ve.focusNode&&ae.contains(ve.focusNode))return}vt(X,"完整报错已复制","复制完整报错失败")};return s.jsxs("main",{"data-agent-workspace":!0,className:"safe-area-x mx-auto flex min-h-[calc(100vh-100px)] flex-col lg:flex-row max-w-7xl lg:gap-3 px-3 lg:px-0 relative overflow-visible transition-all duration-300",children:[Q>0&&!d&&s.jsx("div",{className:"fixed top-0 left-0 right-0 z-50 flex justify-center items-end pointer-events-none sm:hidden",style:{height:`${Q+10}px`,opacity:Q/J0},children:s.jsx("div",{className:"bg-black/60 backdrop-blur-sm text-white rounded-full p-1 mb-2 shadow-lg",children:s.jsx(Nd,{className:"w-4 h-4"})})}),!u&&s.jsx("div",{className:"fixed inset-0 z-40 bg-black/50 lg:hidden",onClick:()=>f(!0)}),s.jsx("aside",{className:`fixed inset-y-0 left-0 z-50 flex w-4/5 max-w-[320px] flex-col border-r border-gray-200 bg-white/95 shadow-2xl backdrop-blur transition-transform duration-300 dark:border-white/[0.08] dark:bg-gray-950/95 lg:hidden ${u?"-translate-x-full":"translate-x-0"}`,children:s.jsxs("div",{className:"pl-[max(1rem,env(safe-area-inset-left))] flex h-full min-h-0 w-full flex-col",children:[s.jsx("div",{className:"safe-area-top shrink-0",children:s.jsxs("div",{className:"flex h-14 items-center justify-between gap-2 px-4",children:[s.jsx("button",{type:"button",onClick:()=>f(!0),className:"lg:hidden p-2 -ml-2 text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 rounded-lg transition-colors",title:"折叠左侧边栏",children:s.jsx(L0,{className:"w-5 h-5"})}),s.jsx("button",{type:"button",onClick:n,className:"p-2 -mr-2 text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 lg:hover:bg-gray-100 lg:dark:hover:bg-white/[0.04] rounded-lg transition-colors",title:"新对话",children:s.jsx(Hr,{className:"w-5 h-5"})})]})}),s.jsx("div",{className:"shrink-0 px-4 pb-3",children:s.jsx("input",{type:"text",value:Y,onChange:V=>le(V.target.value),placeholder:"搜索聊天...",className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2 text-sm text-gray-900 outline-none transition-colors placeholder:text-gray-400 focus:border-blue-400 focus:bg-white dark:bg-white/[0.06] dark:text-white dark:focus:border-blue-400 dark:focus:bg-white/[0.07]"})}),s.jsxs("div",{className:"space-y-1 overflow-y-auto flex-1 px-4 pb-4",children:[xe.length===0&&s.jsx("div",{className:"px-2 py-8 text-center text-sm text-gray-400",children:"没有找到匹配的聊天"}),xe.map(V=>{const X=!!_[V.id];return s.jsxs("div",{"data-agent-conversation-item":!0,className:"group flex h-14 items-center gap-2 rounded-lg px-2 hover:bg-gray-100 dark:hover:bg-white/[0.04]",onPointerDown:me=>Ue(V.id,me),onPointerUp:Oe,onPointerCancel:Oe,onPointerLeave:Oe,onContextMenu:me=>{ie===V.id&&me.preventDefault()},children:[N===V.id?s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center h-[38px]",children:s.jsx("input",{type:"text",className:"h-7 flex-1 bg-white dark:bg-black/20 border border-blue-400/50 dark:border-white/20 rounded px-1.5 py-0 text-sm leading-7 outline-none text-gray-900 dark:text-white focus:border-blue-500 dark:focus:border-white/40 shadow-sm min-w-0",value:J,onChange:me=>H(me.target.value),onKeyDown:Be,onClick:me=>me.stopPropagation(),autoFocus:!0,onBlur:pe})}):s.jsxs("button",{type:"button",className:"min-w-0 flex-1 text-left",onClick:()=>lt(V.id),children:[s.jsx("div",{className:`truncate ${V.id===r?"font-semibold text-gray-900 dark:text-white":"text-gray-700 dark:text-gray-300"}`,children:V.title}),s.jsx("div",{className:"text-xs text-gray-400",children:I4(V.updatedAt)})]}),s.jsx("div",{className:`flex shrink-0 items-center gap-1 overflow-hidden transition-all duration-150 ${N===V.id?"w-6 opacity-100":`group-hover:w-[4.5rem] group-hover:opacity-100 group-focus-within:w-[4.5rem] group-focus-within:opacity-100 ${ie===V.id?"w-[4.5rem] opacity-100":"w-0 opacity-0"}`}`,children:N===V.id?s.jsx(Ke,{tooltip:"确认",onClick:me=>me.stopPropagation(),onMouseDown:me=>{me.preventDefault(),me.stopPropagation(),pe()},className:"p-1.5 hover:bg-gray-200 dark:hover:bg-white/10 rounded-md text-green-500 hover:text-green-600 transition-colors",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}):s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:"编辑标题",className:"p-1.5 text-gray-400 hover:text-gray-700 disabled:text-gray-300 disabled:hover:text-gray-300 disabled:cursor-not-allowed dark:hover:text-gray-200 dark:disabled:text-gray-600 dark:disabled:hover:text-gray-600",onClick:me=>he(me,V.id,V.title),disabled:X,children:s.jsx(Hr,{className:"w-4 h-4"})}),s.jsx(Ke,{tooltip:"删除",className:"p-1.5 text-gray-400 hover:text-red-600",onClick:me=>{me.stopPropagation(),de(V.id)},children:s.jsx(_r,{className:"w-4 h-4"})})]})})]},V.id)})]})]})}),s.jsxs("section",{className:"min-w-0 flex-1 flex flex-col relative",children:[s.jsx("div",{className:`sticky top-0 z-20 lg:hidden overflow-hidden transition-all duration-300 ease-in-out ${G?"max-h-16 opacity-100 mb-2":"max-h-0 opacity-0 mb-0 pointer-events-none"}`,children:s.jsxs("div",{className:"flex h-14 items-center justify-between border-b border-gray-200 bg-white/80 px-2 backdrop-blur dark:border-white/[0.08] dark:bg-gray-950/80",onTouchStart:ht,onTouchMove:Pe,onTouchEnd:ne,children:[s.jsx("button",{type:"button",onClick:()=>f(!1),className:"p-2 text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.04] rounded-lg transition-colors",title:"展开对话列表",children:s.jsx(L0,{className:"w-5 h-5"})}),s.jsx("button",{type:"button",onClick:()=>{f(!1),O&&w.getState().setAgentEditingConversationId(O.id)},className:"text-sm font-semibold text-gray-700 dark:text-gray-300 truncate flex-1 text-center px-2 hover:bg-gray-100 dark:hover:bg-white/[0.04] rounded transition-colors",children:(O==null?void 0:O.title)||"Agent"}),s.jsx("button",{type:"button",onClick:n,className:"p-2 text-gray-500 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/[0.04] rounded-lg transition-colors",title:"新对话",children:s.jsx(Hr,{className:"w-5 h-5"})})]})}),s.jsxs("div",{ref:K,className:"flex-1 space-y-4 overflow-visible pb-[calc(var(--input-bar-clearance,12rem)+1.5rem)] px-1 lg:pt-14 lg:px-4",onTouchStart:Xe,onTouchMove:Pe,onTouchEnd:ne,children:[O?(()=>{if(be.length===0)return s.jsxs("div",{className:"py-20 text-center text-gray-400",children:[s.jsx("p",{className:"mb-2",children:"开始新的 Agent 对话"}),s.jsx("p",{className:"text-xs",children:"在底部输入框发送消息即可创建第一轮对话。"})]});const V=be.map(me=>{var tr;const ve=O.rounds.find(Le=>Le.id===me.roundId),ae=me.role==="assistant",_e=ae&&(ve==null?void 0:ve.status)==="running",Ye=!ae&&(ve==null?void 0:ve.id)===A,wt=!ae&&ve?Jm(O,ve):[],xt=ve?wt.findIndex(Le=>Le.id===ve.id):-1,qe=wt.length>1,tt=ae?d4(ve??null,x):[],Pt=tt.map(Le=>Le.task).filter(Boolean),Ct=Pt.length>0,Ht=Pt.filter(Le=>{var gt;return(((gt=Le.outputImages)==null?void 0:gt.length)??0)>0}),Dt=Ht.length>0,Tt=Dt&&Ht.every(Le=>Le.isFavorite),Ce=ae?l4(ve??null,tt,x,!!me.content.trim()):[],Or=((ve==null?void 0:ve.inputImageIds)||[]).map(Le=>({id:Le,dataUrl:""})),nt=fp(me.content,Or);return s.jsx("div",{className:`flex w-full mb-6 ${ae?"justify-start":"justify-end"}`,children:s.jsxs("div",{ref:Le=>{!ae&&Le?P.current.set(me.roundId,Le):ae||P.current.delete(me.roundId)},className:`group flex max-w-[95%] flex-col md:max-w-[85%] lg:max-w-[75%] ${ae?"items-start":"items-end"}`,children:[s.jsxs("article",{className:`relative flex min-w-[16rem] max-w-full flex-col rounded-2xl p-4 transition-all duration-200 ${ae?"bg-black/[0.04] dark:bg-white/[0.06] border border-transparent rounded-tl-sm hover:bg-black/[0.07] dark:hover:bg-white/[0.08]":`bg-gray-100 dark:bg-[#2A2D31] rounded-tr-sm ${Ye?"ring-2 ring-blue-500/50 dark:ring-blue-400/50":""}`}`,children:[s.jsx("div",{className:"mb-2 flex items-center justify-between gap-4 text-sm text-gray-500 dark:text-gray-400",children:s.jsxs("span",{className:"font-medium",children:[s.jsx("span",{className:ae?"text-blue-600 dark:text-blue-400 font-semibold":"text-gray-700 dark:text-gray-200 font-semibold",children:ae?"Agent":"用户"})," ",s.jsxs("span",{className:"opacity-60 font-normal ml-1",children:["· 第 ",(ve==null?void 0:ve.index)??"?"," 轮"]})]})}),me.role==="user"&&ve&&ve.inputImageIds.length>0&&s.jsx("div",{className:"flex gap-2 mb-3 overflow-x-auto pb-1",onClick:Le=>Le.stopPropagation(),children:ve.inputImageIds.map((Le,gt)=>s.jsx(w4,{imageId:Le,imageIndex:gt,maskImageId:Le===(ve.maskTargetImageId??ve.inputImageIds[0])?ve.maskImageId:null,round:ve},Le))}),(ve==null?void 0:ve.status)==="error"&&ae&&me.content.startsWith("请求失败:")?s.jsx("div",{"data-selectable-text":!0,className:"-m-2 flex cursor-copy select-text flex-col rounded-xl p-2 transition-colors hover:bg-red-500/[0.1] dark:hover:bg-red-500/[0.16]",title:"点击复制完整报错",onPointerDown:ct,onClick:Le=>rt(Le,me.content),children:(()=>{const Le=me.content.replace(/^请求失败:/,""),[gt,...Ut]=Le.split(`
|
|
76
|
+
提示:`);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-start gap-2 text-red-500 dark:text-red-400",children:[s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"w-[18px] h-[18px] mt-[1.5px] flex-shrink-0",children:s.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})}),s.jsx("div",{className:"whitespace-pre-wrap text-[14px] leading-relaxed break-words font-medium",children:gt})]}),Ut.length>0&&s.jsxs("div",{className:"pl-[26px] mt-1.5 whitespace-pre-wrap text-[13px] leading-relaxed text-gray-500 dark:text-gray-400 break-words opacity-90",children:[s.jsx("span",{className:"font-medium",children:"提示:"}),Ut.join(`
|
|
77
|
+
提示:`)]})]})})()}):s.jsx("div",{"data-selectable-text":!0,className:`text-[15px] leading-relaxed text-gray-800 dark:text-gray-100 ${ae?"":"select-text"}`,children:ae?s.jsx(s.Fragment,{children:Ce.length>0?Ce.map((Le,gt)=>Le.type==="web-search"?s.jsx(C4,{statuses:[Le.status]},Le.key):Le.type==="text"?s.jsx("div",{className:gt>0?"mt-3":void 0,children:s.jsx(Ai,{content:Le.content??me.content,streaming:_e})},Le.key):Le.type==="batch-params"?s.jsx("div",{className:gt>0?"mt-3":void 0,children:s.jsx(Iy,{status:Le.status})},Le.key):Le.type==="deleted-image-task"?s.jsxs("div",{className:"mt-4 w-full min-w-[16rem] max-w-sm rounded-xl bg-gray-50/50 dark:bg-white/[0.02] border border-dashed border-gray-200 dark:border-white/[0.08] p-4 flex min-h-[120px] flex-col items-center justify-center text-gray-400 dark:text-gray-500",onClick:Ut=>Ut.stopPropagation(),children:[s.jsx(_r,{className:"w-6 h-6 mb-2 opacity-50"}),s.jsx("span",{className:"text-xs",children:"[Image Removed]"})]},Le.key):s.jsx("div",{className:"mt-4 max-w-sm",onClick:Ut=>Ut.stopPropagation(),children:s.jsx(by,{task:Le.task,disableSwipe:!0,onClick:()=>h(Le.task.id),onReuse:()=>Ve(Le.task),onEditOutputs:()=>vg(Le.task),onDelete:()=>b({title:"删除任务",message:"确定要删除这个任务吗?",action:()=>wg(Le.task)})})},Le.key)):_e?s.jsx(k4,{}):null}):nt.some(Le=>Le.type==="mention")?s.jsx("div",{className:"whitespace-pre-wrap break-words",children:nt.map((Le,gt)=>Le.type==="text"?s.jsx("span",{children:Le.text},gt):s.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded-md bg-blue-100/50 text-blue-700 dark:bg-blue-500/30 dark:text-blue-300 text-xs font-medium mx-0.5 align-baseline",children:Le.text},gt))}):s.jsx(Ai,{content:((tr=nt[0])==null?void 0:tr.text)??""})})]}),!_e&&s.jsxs("div",{className:`mt-2 flex w-full min-w-fit items-center justify-between gap-3 px-1 transition-opacity duration-200 ${Ye||qe?"opacity-100":"opacity-100 lg:opacity-0 lg:group-hover:opacity-100"}`,onClick:Le=>Le.stopPropagation(),children:[s.jsx("div",{className:"flex min-w-0 items-center gap-2",children:Ye&&s.jsxs("div",{className:"inline-flex items-center rounded-md bg-blue-100 px-2 py-1 text-xs text-blue-700 dark:bg-blue-500/20 dark:text-blue-300",children:[s.jsx("span",{className:"truncate",children:"正在编辑"}),s.jsx(Ke,{tooltip:"取消编辑",className:"ml-1 -mr-1 p-0.5 rounded-full hover:bg-blue-200 dark:hover:bg-blue-500/40 transition-colors",onClick:Le=>{Le.stopPropagation(),y(""),v([]),S(),T(null)},children:s.jsx(qt,{className:"w-3 h-3"})})]})}),s.jsxs("div",{className:"flex items-center gap-2 ml-auto text-gray-400",children:[!ae&&ve&&qe&&xt>=0&&s.jsxs("div",{className:"inline-flex items-center text-sm font-bold text-gray-400 dark:text-gray-500 mr-1",children:[s.jsx(Ke,{tooltip:"上一分支",className:"p-1 rounded-md hover:bg-gray-200/50 dark:hover:bg-white/10 hover:text-gray-800 dark:hover:text-gray-200 transition-colors",onClick:()=>Z(ve,-1),children:s.jsx(dy,{className:"w-4 h-4"})}),s.jsxs("span",{className:"px-1 tabular-nums tracking-widest",children:[xt+1,"/",wt.length]}),s.jsx(Ke,{tooltip:"下一分支",className:"p-1 rounded-md hover:bg-gray-200/50 dark:hover:bg-white/10 hover:text-gray-800 dark:hover:text-gray-200 transition-colors",onClick:()=>Z(ve,1),children:s.jsx(jg,{className:"w-4 h-4"})})]}),ae?s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:"复制输出文本",className:`p-1.5 rounded-md transition-colors ${me.content.trim()?"text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:hover:text-gray-200 dark:hover:bg-white/[0.06]":"text-gray-300 dark:text-gray-600 opacity-50 cursor-not-allowed"}`,disabled:!me.content.trim(),onClick:()=>{vt(c4(me.content,Ce),"输出文本已复制","复制输出文本失败")},children:s.jsx(zr,{className:"w-4 h-4"})}),s.jsx(Ke,{tooltip:"重新生成",className:"p-1.5 rounded-md text-gray-400 hover:text-blue-500 hover:bg-blue-50 dark:hover:bg-blue-500/10 transition-colors",onClick:()=>{O&&ve&&Vj(O.id,ve.id)},children:s.jsx(Go,{className:"w-4 h-4"})}),!F&&s.jsx(Ke,{tooltip:Tt?"编辑收藏夹":"收藏所有图片",className:`p-1.5 rounded-md transition-colors ${Dt?Tt?"text-yellow-500 hover:bg-yellow-50 dark:hover:bg-yellow-500/10":"text-gray-400 hover:text-yellow-500 hover:bg-yellow-50 dark:hover:bg-yellow-500/10":"text-gray-300 dark:text-gray-600 opacity-50 cursor-not-allowed"}`,disabled:!Dt,onClick:()=>{Dt&&W(Ht.map(Le=>Le.id))},children:s.jsx(as,{className:"w-4 h-4",filled:Tt})}),s.jsx(Ke,{tooltip:"下载所有图片",className:`p-1.5 rounded-md transition-colors ${Ct?"text-gray-400 hover:text-green-500 hover:bg-green-50 dark:hover:bg-green-500/10":"text-gray-300 dark:text-gray-600 opacity-50 cursor-not-allowed"}`,disabled:!Ct,onClick:async()=>{const Le=Pt.flatMap(gt=>gt.outputImages||[]);if(Le.length!==0)try{const Ut="agent-round-"+((ve==null?void 0:ve.index)??0),rr=w.getState().settings.zipDownloadRoutes.includes("agent-round-all")?await so(Ni(Le,Ut),Ut):await Xn(Le,Ut),{successCount:Ft,failCount:Sr,canceled:Jt}=rr;if(Jt)return;Ft===0?w.getState().showToast(Zt(rr.error),"error"):Sr>0?w.getState().showToast("部分下载失败:成功 "+Ft+",失败 "+Sr,"error"):w.getState().showToast(Kn(Ft>1?"下载成功:"+Ft+" 张图片":"下载成功",rr.location),"success")}catch(gt){console.error(gt),w.getState().showToast(Zt(gt),"error")}},children:s.jsx(qs,{className:"w-4 h-4"})}),s.jsx(Ke,{tooltip:"删除消息",className:"p-1.5 hover:text-red-600 hover:bg-red-500/[0.1] dark:hover:bg-red-500/[0.16] rounded-md transition-colors",onClick:()=>{ve&&ut(me,ve)},children:s.jsx(_r,{className:"w-4 h-4"})})]}):s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:"复制提示词",className:"p-1.5 rounded-md hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-200/50 dark:hover:bg-white/[0.04] transition-colors",onClick:()=>{vt(ve?fx(me.content,ve,ys(O,ve.id),x):me.content)},children:s.jsx(zr,{className:"w-4 h-4"})}),s.jsx(Ke,{tooltip:"编辑",className:"p-1.5 rounded-md hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-200/50 dark:hover:bg-white/[0.04] transition-colors",onClick:()=>{ve&&He(ve,me.content)},children:s.jsx(Hr,{className:"w-4 h-4"})}),s.jsx(Ke,{tooltip:"删除",className:"p-1.5 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-500/[0.1] dark:hover:bg-red-500/[0.16] rounded-md transition-colors",onClick:()=>{ve&&ut(me,ve)},children:s.jsx(_r,{className:"w-4 h-4"})})]})]})]})]})},me.id)}),X=fe.filter(me=>me.status==="running"&&!O.messages.some(ve=>ve.roundId===me.id&&ve.role==="assistant"));return s.jsxs(s.Fragment,{children:[V,X.map(me=>s.jsx("div",{className:"flex w-full justify-start mb-6",children:s.jsxs("article",{className:"flex min-w-[16rem] max-w-[95%] flex-col rounded-2xl rounded-tl-sm border border-transparent bg-black/[0.04] p-4 dark:bg-white/[0.06] md:max-w-[85%] lg:max-w-[75%]",children:[s.jsxs("div",{className:"mb-2 text-sm text-gray-500 dark:text-gray-400",children:[s.jsx("span",{className:"text-blue-600 dark:text-blue-400 font-semibold",children:"Agent"})," ",s.jsxs("span",{className:"ml-1 font-normal opacity-60",children:["· 第 ",me.index," 轮"]})]}),s.jsx("div",{className:"flex items-center gap-3 text-sm text-gray-500 dark:text-gray-400",children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{children:"正在生成回复"}),s.jsxs("span",{className:"flex gap-1",children:[s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-current"}),s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-current [animation-delay:150ms]"}),s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-current [animation-delay:300ms]"})]})]})})]})},`running-${me.id}`))]})})():s.jsxs("div",{className:"py-20 text-center text-gray-400",children:[s.jsx("p",{className:"mb-3",children:"还没有 Agent 对话"}),s.jsx("button",{type:"button",onClick:n,className:"rounded-lg bg-blue-500 px-4 py-2 text-white hover:bg-blue-600 transition-colors",children:"创建对话"})]}),s.jsx("div",{ref:te,"aria-hidden":"true"})]}),s.jsx("button",{onClick:Ge,className:`fixed bottom-[calc(var(--input-bar-clearance,12rem)+1.5rem)] left-[calc((100%-var(--page-scrollbar-width))/2)] -translate-x-1/2 z-30 flex h-10 w-10 items-center justify-center rounded-full bg-white/90 backdrop-blur shadow-[0_2px_12px_rgba(0,0,0,0.1)] border border-gray-200/50 text-gray-500 transition-all duration-300 hover:bg-gray-50 hover:text-gray-800 dark:border-white/[0.08] dark:bg-gray-800/90 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-200 ${!ue&&be.length>0?"translate-y-0 opacity-100":"translate-y-4 opacity-0 pointer-events-none"}`,"aria-label":"滚动到底部",children:s.jsx(aS,{className:"h-5 w-5"})})]})]})}function ru(e){if(!e||!e.isConnected||typeof e.getBoundingClientRect!="function")return null;try{return e.getBoundingClientRect()}catch{return null}}let Ec=0;function Rc(e=450){Ec=Math.max(Ec,Date.now()+e)}function N4(){p.useEffect(()=>{const e=t=>{Date.now()>Ec||(Ec=0,t.cancelable&&t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation())};return document.addEventListener("click",e,{capture:!0}),()=>document.removeEventListener("click",e,{capture:!0})},[])}function tl(e){var t;return((t=e.textContent)==null?void 0:t.length)??0}function tf(e){var t;return e.nodeType===Node.TEXT_NODE?((t=e.textContent)==null?void 0:t.length)??0:e instanceof HTMLElement&&e.classList.contains("mention-tag")?tl(e):Array.from(e.childNodes).reduce((r,n)=>r+tf(n),0)}function nu(e,t){let r=0,n=!1;const a=o=>{var i;if(!n){if(o===t){n=!0;return}if(o.nodeType===Node.TEXT_NODE){r+=((i=o.textContent)==null?void 0:i.length)??0;return}if(o instanceof HTMLElement&&o.classList.contains("mention-tag")){r+=tl(o);return}o.childNodes.forEach(a)}};return e.childNodes.forEach(a),r}function A4(e,t){const r=t.nodeType===Node.ELEMENT_NODE?t:t.parentElement,n=r==null?void 0:r.closest(".mention-tag");return n&&e.contains(n)?n:null}function P4(e,t,r){try{const n=document.createRange();return n.selectNodeContents(e),n.setEnd(t,r),n.toString().length}catch{return tl(e)}}function rf(e,t,r,n,a){var l,c,u,f;if(t===e){let d=0;for(const g of Array.from(e.childNodes).slice(0,r))d+=tf(g);return d}if(!e.contains(t)){const d=e.compareDocumentPosition(t);if(d&Node.DOCUMENT_POSITION_PRECEDING)return 0;if(d&Node.DOCUMENT_POSITION_FOLLOWING)return((l=e.textContent)==null?void 0:l.length)??0;if(t.contains(e)){const m=Array.from(t.childNodes).indexOf(e);return r<=m?0:((c=e.textContent)==null?void 0:c.length)??0}return n==="start"?0:((u=e.textContent)==null?void 0:u.length)??0}const o=A4(e,t);if(o){const d=nu(e,o),g=tl(o);if(!a)return n==="start"?d:d+g;const m=P4(o,t,r);return d+(m<g/2?0:g)}if(t.nodeType===Node.TEXT_NODE)return nu(e,t)+r;const i=t.nodeType===Node.ELEMENT_NODE?t:null;if(i){let d=i===e?0:nu(e,i);for(const g of Array.from(i.childNodes).slice(0,r))d+=tf(g);return d}return((f=e.textContent)==null?void 0:f.length)??0}function T4(e){var n,a;const t=window.getSelection();if(!t||t.rangeCount===0)return((n=e.textContent)==null?void 0:n.length)??0;const r=t.getRangeAt(0);return e.contains(r.startContainer)?rf(e,r.startContainer,r.startOffset,"start",r.collapsed):((a=e.textContent)==null?void 0:a.length)??0}function Na(e){var o;const t=window.getSelection();if(!t||t.rangeCount===0){const i=((o=e.textContent)==null?void 0:o.length)??0;return{start:i,end:i}}const r=t.getRangeAt(0),n=rf(e,r.startContainer,r.startOffset,"start",r.collapsed),a=r.collapsed?n:rf(e,r.endContainer,r.endOffset,"end",!1);return{start:n,end:a}}function G0(e){let t="";const r=n=>{if(n.nodeType===Node.TEXT_NODE){t+=n.textContent??"";return}if(n instanceof HTMLElement&&n.classList.contains("mention-tag")){t+=n.dataset.mentionText??n.textContent??"";return}n.childNodes.forEach(r)};return e.childNodes.forEach(r),t.replace(/\r\n?/g,`
|
|
78
|
+
`)}function Z0(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function su(e,t=Vc(e)){return`<span contenteditable="false" class="mention-tag" data-mention-text="${Z0(t)}">${Z0(e)}</span>`}function Us(e){const t=e.querySelectorAll(".mention-tag"),r=window.getSelection();if(!r||r.rangeCount===0){t.forEach(a=>a.classList.remove("selected"));return}const n=r.getRangeAt(0);if(n.collapsed){t.forEach(a=>a.classList.remove("selected"));return}t.forEach(a=>{let o=!1;try{o=n.intersectsNode(a)}catch{o=!1}a.classList.toggle("selected",o)})}function Al(e,t){var i;const r=window.getSelection();if(!r)return;const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let a=t,o=null;for(;n.nextNode();){o=n.currentNode;const l=(i=o.parentElement)==null?void 0:i.closest(".mention-tag");if(l){if(a<=o.length){const c=document.createRange();a<o.length/2?c.setStartBefore(l):c.setStartAfter(l),c.collapse(!0),r.removeAllRanges(),r.addRange(c);return}a-=o.length;continue}if(a<=o.length){const c=document.createRange();c.setStart(o,a),c.collapse(!0),r.removeAllRanges(),r.addRange(c);return}a-=o.length}if(o){const l=document.createRange();l.setStart(o,o.length),l.collapse(!0),r.removeAllRanges(),r.addRange(l)}}function Q0(e,t,r){const n=window.getSelection();if(!n)return;const a=(u,f)=>{let d=u,g={type:"offset",node:e,offset:0};const m=x=>{if(x.nodeType===Node.TEXT_NODE){const b=x;return g={type:"offset",node:b,offset:b.length},d<=b.length?{type:"offset",node:b,offset:d}:(d-=b.length,null)}if(x instanceof HTMLElement&&x.classList.contains("mention-tag")){const b=tl(x);return d<=0?{type:"before",element:x}:d<b?f==="start"?{type:"before",element:x}:{type:"after",element:x}:d===b?{type:"after",element:x}:(d-=b,null)}for(const b of Array.from(x.childNodes)){const h=m(b);if(h)return h}return null};return m(e)??g},o=(u,f,d)=>{if(f.type==="before"){d==="start"?u.setStartBefore(f.element):u.setEndBefore(f.element);return}if(f.type==="after"){d==="start"?u.setStartAfter(f.element):u.setEndAfter(f.element);return}d==="start"?u.setStart(f.node,f.offset):u.setEnd(f.node,f.offset)},i=a(t,"start"),l=a(r,"end"),c=document.createRange();o(c,i,"start"),o(c,l,"end"),n.removeAllRanges(),n.addRange(c)}function Fs(e={}){const{autoHideMs:t,touchDelayMs:r=450}=e,[n,a]=p.useState(!1),o=p.useRef(null),i=p.useRef(null),l=p.useRef(e.enabled);l.current=e.enabled;const c=p.useCallback(()=>{o.current!=null&&(window.clearTimeout(o.current),o.current=null)},[]),u=p.useCallback(()=>{i.current!=null&&(window.clearTimeout(i.current),i.current=null)},[]),f=p.useCallback(()=>{a(!1),c(),u()},[u,c]),d=p.useCallback(()=>{l.current&&!l.current()||(c(),u(),a(!0),t!=null&&(i.current=window.setTimeout(()=>{a(!1),i.current=null},t)))},[t,u,c]),g=p.useCallback(()=>{l.current&&!l.current()||(c(),o.current=window.setTimeout(()=>{o.current=null,d()},r))},[c,d,r]);return p.useEffect(()=>()=>{c(),u()},[u,c]),p.useMemo(()=>({visible:n,show:d,hide:f,clearTimer:c,startTouch:g}),[c,f,d,g,n])}const Cy=["1K","2K","4K"],M4=`由于模型限制,不符合要求的分辨率会被自动规整:
|
|
79
|
+
宽高均为 16 的倍数,最大边长 3840px,宽高比不超过 3:1,总像素限制为 655360-8294400。`,E4=`由于模型和 Codex CLI 限制,不符合要求的分辨率会被自动规整:
|
|
80
|
+
宽高均为 16 的倍数,宽高比不超过 3:1,分辨率不超过 1K。`,R4="由于模型限制,原始分辨率已被自动规整",jy=[{label:"1:1",value:"1:1"},{label:"3:2",value:"3:2"},{label:"2:3",value:"2:3"},{label:"16:9",value:"16:9"},{label:"9:16",value:"9:16"},{label:"4:3",value:"4:3"},{label:"3:4",value:"3:4"},{label:"21:9",value:"21:9"}];function _4(e){const t=e.match(/^\s*(\d+)\s*[xX×]\s*(\d+)\s*$/);return t?{width:t[1],height:t[2]}:null}function D4(e){const t=ad(e);for(const r of Cy)for(const n of jy)if(Uf(r,n.value)===t)return{tier:r,ratio:n.value};return null}function L4({currentSize:e,onSelect:t,onClose:r,allowAuto:n=!0,codexCli:a=!1}){Lr(!0);const o=p.useRef(null),i=p.useRef(null),l=se=>{i.current=se.target},c=se=>{const Y=i.current,le=se.target;o.current&&Y&&!o.current.contains(Y)&&le&&!o.current.contains(le)&&r(),i.current=null},u=D4(e),f=_4(e),[d,g]=p.useState(()=>!e||e==="auto"?n?"auto":"ratio":u?"ratio":"resolution"),[m,x]=p.useState((u==null?void 0:u.tier)??"1K"),[b,h]=p.useState((u==null?void 0:u.ratio)??(n?"1:1":"4:3")),[y,v]=p.useState("16:9"),[I,S]=p.useState((f==null?void 0:f.width)??"1024"),[k,j]=p.useState((f==null?void 0:f.height)??"1024"),[A,N]=p.useState(!1),C=p.useRef(null),[T,R]=p.useState(null),U=p.useRef(null);p.useEffect(()=>()=>{C.current!=null&&window.clearTimeout(C.current),U.current!=null&&window.clearTimeout(U.current)},[]);const W=a?Of:ad,F=a?E4:M4,_=b==="custom"?y:b,O=Gp(y),J=b!=="custom"||!!O,H=!!(b==="custom"&&O&&Math.max(O.width,O.height)/Math.min(O.width,O.height)>3),K=p.useMemo(()=>{if(d==="auto")return"auto";if(d==="ratio"){const se=Uf(m,_);return se?W(se):""}if(d==="resolution"){const se=parseInt(I,10),Y=parseInt(k,10);return Number.isFinite(se)&&Number.isFinite(Y)&&se>0&&Y>0?W(`${se}x${Y}`):""}return""},[d,m,_,I,k,W]),te=p.useMemo(()=>{if(!K||K==="auto")return!1;if(d==="ratio"&&b==="custom")return H;if(d==="resolution"){const se=parseInt(I,10),Y=parseInt(k,10);if(Number.isFinite(se)&&Number.isFinite(Y)&&se>0&&Y>0)return`${se}x${Y}`!==K}return!1},[d,b,H,I,k,K]),P=()=>N(!0),B=()=>{N(!1),$()},$=()=>{C.current!=null&&(window.clearTimeout(C.current),C.current=null)},Q=()=>{C.current=window.setTimeout(()=>{N(!0),C.current=null},450)},L=()=>{K&&(t(K),r())},G=se=>`rounded-xl border px-3 py-2 text-sm transition ${se?"border-blue-400 bg-blue-50 text-blue-600 dark:border-blue-500/50 dark:bg-blue-500/10 dark:text-blue-300":"border-transparent bg-black/[0.04] text-gray-600 hover:bg-black/[0.07] dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1]"}`;return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",onMouseDown:l,onMouseUp:c,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{ref:o,className:"relative z-10 w-full max-w-md rounded-3xl border border-white/50 bg-white/95 p-5 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10",children:[s.jsxs("div",{className:"mb-5 flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-base font-semibold text-gray-800 dark:text-gray-100",children:"设置图像尺寸"}),s.jsxs("p",{className:"mt-1 text-xs text-gray-400 dark:text-gray-500",children:["当前:",e||"auto"]})]}),s.jsx("button",{onClick:r,className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx("svg",{className:"h-5 w-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex rounded-xl bg-gray-100/80 p-1 dark:bg-white/[0.04]",children:[n&&s.jsx("button",{onClick:()=>g("auto"),className:`flex-1 rounded-lg py-1.5 text-sm font-medium transition ${d==="auto"?"bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`,children:"自动"}),s.jsx("button",{onClick:()=>g("ratio"),className:`flex-1 rounded-lg py-1.5 text-sm font-medium transition ${d==="ratio"?"bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`,children:"按比例"}),s.jsx("button",{onClick:()=>g("resolution"),className:`flex-1 rounded-lg py-1.5 text-sm font-medium transition ${d==="resolution"?"bg-white text-gray-800 shadow-sm dark:bg-gray-700 dark:text-gray-100":"text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"}`,children:"自定义宽高"})]}),s.jsxs("div",{className:"h-[380px] max-h-[55vh] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-200 dark:scrollbar-thumb-white/10 pr-1 -mr-1 pb-2",children:[d==="auto"&&s.jsx("div",{className:"flex h-full animate-fade-in items-center justify-center pt-8 pb-4 text-center",children:s.jsxs("div",{children:[s.jsx("div",{className:"mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-blue-50 text-blue-500 dark:bg-blue-500/10",children:s.jsx("svg",{className:"h-8 w-8",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})})}),s.jsx("h4",{className:"text-sm font-medium text-gray-800 dark:text-gray-200",children:"自动尺寸"}),s.jsxs("p",{className:"mt-2 text-xs text-gray-400 leading-relaxed dark:text-gray-500",children:["不向模型传递具体的分辨率参数",s.jsx("br",{}),"由模型自己决定生成尺寸"]})]})}),d==="ratio"&&s.jsxs("div",{className:"space-y-5 animate-fade-in",children:[s.jsxs("section",{children:[s.jsx("div",{className:"mb-2 text-xs font-medium text-gray-400 dark:text-gray-500",children:"基准分辨率"}),s.jsx("div",{className:"grid grid-cols-3 gap-2",children:Cy.map(se=>{const Y=a&&se!=="1K";return s.jsxs("div",{className:"relative",onMouseEnter:()=>{U.current!=null&&window.clearTimeout(U.current),Y&&R(se)},onMouseLeave:()=>R(null),onTouchStart:()=>{Y&&(U.current!=null&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{R(se),U.current=null},450))},onTouchEnd:()=>{U.current!=null&&window.clearTimeout(U.current),U.current=window.setTimeout(()=>{R(null),U.current=null},1500)},onTouchCancel:()=>{U.current!=null&&window.clearTimeout(U.current),U.current=null,R(null)},children:[s.jsx("button",{className:`${G(m===se)} w-full disabled:cursor-not-allowed disabled:opacity-40`,onClick:()=>x(se),disabled:Y,children:se}),s.jsx(pt,{visible:T===se,className:"w-52 text-center",children:"Codex CLI 不支持 1K 以上的分辨率"})]},se)})})]}),s.jsxs("section",{children:[s.jsx("div",{className:"mb-2 text-xs font-medium text-gray-400 dark:text-gray-500",children:"图像比例"}),s.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[jy.map(se=>{const[Y,le]=se.value.split(":").map(Number),ie=Y>le,D=Y===le;return s.jsxs("button",{className:`${G(b===se.value)} flex flex-col items-center justify-center gap-1.5 !py-2.5`,onClick:()=>h(se.value),children:[s.jsx("div",{className:"flex h-5 w-5 items-center justify-center",children:s.jsx("div",{className:"border-[1.5px] border-current rounded-[3px] opacity-60",style:{width:ie||D?"100%":`${Y/le*100}%`,height:!ie||D?"100%":`${le/Y*100}%`}})}),s.jsx("span",{className:"text-xs",children:se.label})]},se.value)}),s.jsx("button",{className:`${G(b==="custom")} col-span-4`,onClick:()=>h("custom"),children:"自定义比例"})]})]}),b==="custom"&&s.jsxs("label",{className:"block animate-fade-in",children:[s.jsx("span",{className:"mb-2 block text-xs font-medium text-gray-400 dark:text-gray-500",children:"输入自定义比例"}),s.jsx("input",{value:y,onChange:se=>v(se.target.value),placeholder:"例如 5:4 / 2.39:1",className:`w-full rounded-xl border px-3 py-2 text-sm outline-none transition ${J?"border-transparent bg-black/[0.04] text-gray-700 focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50":"border-red-300 bg-white/60 text-gray-700 focus:border-red-400 dark:border-red-500/40 dark:bg-white/[0.03] dark:text-gray-200"}`})]})]}),d==="resolution"&&s.jsxs("div",{className:"space-y-5 animate-fade-in",children:[s.jsxs("section",{children:[s.jsx("div",{className:"mb-4 text-xs font-medium text-gray-400 dark:text-gray-500",children:"输入具体像素值"}),s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("label",{className:"flex-1",children:[s.jsx("span",{className:"mb-1.5 block text-xs text-gray-500 dark:text-gray-400",children:"宽度 (Width)"}),s.jsx("input",{type:"number",value:I,onChange:se=>S(se.target.value),className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50",placeholder:"例如 1024"})]}),s.jsx("div",{className:"mt-5 text-gray-300 dark:text-gray-600",children:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),s.jsxs("label",{className:"flex-1",children:[s.jsx("span",{className:"mb-1.5 block text-xs text-gray-500 dark:text-gray-400",children:"高度 (Height)"}),s.jsx("input",{type:"number",value:k,onChange:se=>j(se.target.value),className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50",placeholder:"例如 1024"})]})]})]}),s.jsx("div",{className:"rounded-xl border border-transparent bg-black/[0.04] p-3 text-xs text-gray-600 dark:bg-white/[0.06] dark:text-gray-400",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("svg",{className:"mt-[2px] h-4 w-4 flex-shrink-0 text-blue-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx("div",{className:"whitespace-pre-line leading-relaxed",children:F})]})})]})]}),s.jsxs("div",{className:"rounded-2xl bg-gray-50 px-4 py-3 dark:bg-white/[0.03]",children:[s.jsx("div",{className:"text-xs text-gray-400 dark:text-gray-500",children:"将使用"}),s.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[s.jsx("span",{className:"font-mono text-lg font-semibold text-gray-800 dark:text-gray-100",children:K||"尺寸无效"}),te&&s.jsxs("div",{className:"relative flex items-center",onMouseEnter:P,onMouseLeave:B,onTouchStart:Q,onTouchEnd:$,onTouchCancel:B,onClick:P,children:[s.jsx("svg",{className:"w-5 h-5 text-yellow-500 cursor-pointer",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx(pt,{visible:A,className:"w-56 whitespace-pre-line text-center",children:R4})]})]})]})]}),s.jsxs("div",{className:"mt-5 flex gap-2",children:[s.jsx("button",{onClick:r,className:"flex-1 rounded-xl bg-gray-100 px-4 py-2.5 text-sm text-gray-600 transition hover:bg-gray-200 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1]",children:"取消"}),s.jsx("button",{onClick:L,disabled:!K,className:"flex-1 rounded-xl bg-blue-500 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-blue-600 disabled:cursor-not-allowed disabled:opacity-50",children:"确定"})]})]})]})}function O4({onClose:e}){const[t,r]=p.useState(""),[n,a]=p.useState(()=>new Set),[o,i]=p.useState(null),l=w(g=>yr-g.inputImages.length),c=p.useRef(null),u=p.useRef(null),f=()=>{o||e()};Kr(!0,f),Lr(!0,c);const d=async()=>{if(o)return;const g=w.getState().showToast,m=t.split(`
|
|
81
|
+
`).map(j=>j.trim());if(!m.some(Boolean)){g("请输入图片链接","error");return}const x=m.flatMap((j,A)=>{if(!j)return[];if(/\s/.test(j))return[A];try{return/^https?:$/.test(new URL(j).protocol)?[]:[A]}catch{return[A]}});if(x.length){a(new Set(x)),g(`${x.length<m.filter(Boolean).length?"部分":""}链接不是有效的 http / https 链接`,"error");return}const b=[...new Set(m.filter(Boolean))];if(b.length>l){g(`参考图最多 ${yr} 张,当前还能添加 ${l} 张`,"error");return}a(new Set),i({done:0,total:b.length});const h=w.getState().privacyModeEpoch,y=w.getState().inputImages.length,v=[];for(const j of b){if(w.getState().privacyModeEpoch!==h)return;try{await Lb(j)}catch(A){console.warn("addImageFromUrl failed",j,A),v.push({url:j,reason:A instanceof TypeError?De?"可能是链接失效或网络异常":"可能是链接不允许跨域访问、链接失效或网络异常":A instanceof Error?A.message:String(A)})}i(A=>A&&{...A,done:A.done+1})}if(w.getState().privacyModeEpoch!==h)return;i(null);const I=w.getState().inputImages.length-y,S=b.length-v.length-I,k=[I>0&&`已添加 ${I} 张参考图`,S>0&&`跳过 ${S} 张重复图片`].filter(Boolean).join(",");if(!v.length){g(k,"success"),e();return}if(r(v.map(j=>j.url).join(`
|
|
82
|
+
`)),a(new Set(v.map((j,A)=>A))),v.length===1){const j=`链接添加失败,${v[0].reason}`;g(k?`${k};${j}`:j,"error");return}w.getState().setConfirmDialog({title:"部分链接添加失败",message:`${k?`${k}。`:""}以下链接添加失败,已保留在输入框中:`,content:s.jsx("div",{className:"space-y-2",children:v.map(j=>s.jsxs("div",{className:"overflow-hidden rounded-lg text-xs leading-relaxed",children:[s.jsx("div",{className:"break-all bg-red-50 px-2 py-1 font-mono text-red-600 dark:bg-red-500/10 dark:text-red-400",children:j.url}),s.jsx("div",{className:"bg-black/[0.03] px-2 py-1 text-gray-500 dark:bg-white/[0.04] dark:text-gray-400",children:j.reason})]},j.url))}),confirmText:"知道了",showCancel:!1})};return lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",onClick:f,children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{ref:c,className:"relative z-10 flex max-h-full w-full max-w-md flex-col rounded-3xl border border-white/50 bg-white/90 p-6 shadow-[0_8px_40px_rgb(0,0,0,0.12)] ring-1 ring-black/5 backdrop-blur-xl animate-confirm-in dark:border-white/[0.08] dark:bg-gray-900/90 dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] dark:ring-white/10",onClick:g=>g.stopPropagation(),children:[s.jsxs("h3",{className:"mb-2 flex shrink-0 items-center gap-2 text-base font-bold text-gray-800 dark:text-gray-100",children:[s.jsx(ma,{className:"h-5 w-5 shrink-0 text-blue-500"}),"添加链接"]}),s.jsxs("div",{className:"custom-scrollbar -mx-2 min-h-0 overflow-y-auto overscroll-contain px-2",children:[s.jsxs("p",{className:"mb-3 text-sm leading-relaxed text-gray-500 dark:text-gray-400 text-pretty",children:["每行一个图片链接,按顺序添加为参考图,当前还能添加 ",l," 张。原链接会随参考图保留,供只接受链接参考图的自定义服务商使用。"]}),s.jsxs("div",{className:"relative h-40",children:[s.jsx("div",{"aria-hidden":!0,className:`absolute inset-0 overflow-hidden whitespace-pre rounded-xl border border-transparent bg-black/[0.04] font-mono text-xs leading-relaxed text-gray-700 dark:bg-white/[0.06] dark:text-gray-200 ${o?"opacity-60":""}`,children:s.jsx("div",{ref:u,className:"px-3 py-2",children:t.split(`
|
|
83
|
+
`).map((g,m)=>s.jsx("div",{className:n.has(m)?"text-red-500 dark:text-red-400":void 0,children:g||" "},m))})}),s.jsx("textarea",{value:t,onChange:g=>{r(g.target.value),a(new Set)},onScroll:g=>{u.current&&(u.current.style.transform=`translate(${-g.currentTarget.scrollLeft}px, ${-g.currentTarget.scrollTop}px)`)},onKeyDown:g=>{g.key==="Enter"&&(g.ctrlKey||g.metaKey)&&(g.preventDefault(),d())},disabled:!!o,autoFocus:!0,wrap:"off",spellCheck:!1,placeholder:`https://example.com/a.png
|
|
84
|
+
https://example.com/b.jpg`,className:"custom-scrollbar absolute inset-0 h-full w-full resize-none rounded-xl border border-transparent bg-transparent px-3 py-2 font-mono text-xs leading-relaxed text-transparent caret-gray-700 outline-none transition placeholder:text-gray-400 focus:border-blue-300 dark:caret-gray-200 dark:placeholder:text-gray-500 dark:focus:border-blue-500/50"})]})]}),s.jsxs("div",{className:"mt-4 flex shrink-0 gap-2",children:[s.jsx("button",{onClick:f,disabled:!!o,className:"flex-1 py-2 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] text-sm text-gray-600 dark:text-gray-400 hover:bg-black/[0.07] dark:hover:bg-white/[0.1] transition disabled:cursor-not-allowed disabled:opacity-60",children:"取消"}),s.jsx("button",{onClick:()=>void d(),disabled:!!o||l<=0,className:"flex-1 py-2 rounded-xl bg-blue-500 text-sm font-medium text-white hover:bg-blue-600 transition disabled:cursor-not-allowed disabled:opacity-60",children:o?`添加中 ${o.done}/${o.total}`:"添加"})]})]})]}),document.body)}function Mr({visible:e,text:t}){return e?s.jsx(pt,{visible:!0,className:"z-10 whitespace-nowrap",children:t}):null}function B4({visible:e,atImageLimit:t,maxImages:r}){return e?s.jsx("div",{className:"fixed inset-0 z-[100] bg-white/60 dark:bg-gray-900/60 backdrop-blur-md flex flex-col items-center justify-center pointer-events-none",children:s.jsxs("div",{className:"flex flex-col items-center gap-4 p-8 rounded-3xl",children:[s.jsx("div",{className:`w-20 h-20 rounded-full border-2 border-dashed flex items-center justify-center ${t?"bg-red-50 dark:bg-red-500/10 border-red-300":"bg-blue-50 dark:bg-blue-500/10 border-blue-400"}`,children:t?s.jsx("svg",{className:"w-10 h-10 text-red-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"})}):s.jsx("svg",{className:"w-10 h-10 text-blue-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),s.jsx("div",{className:"text-center",children:t?s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-lg font-semibold text-red-500",children:["已达上限 ",r," 张"]}),s.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"请先移除部分参考图后再添加"})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-lg font-semibold text-gray-700 dark:text-gray-200",children:"释放以上传图片"}),s.jsx("p",{className:"text-sm text-gray-400 mt-1",children:"支持 JPG、PNG、WebP 等格式"})]})})]})}):null}function un({tooltip:e,className:t,onClick:r,children:n}){const a=Ot();return s.jsxs("span",{className:"relative inline-flex",...a.handlers,children:[s.jsx("button",{type:"button",onClick:()=>{a.dismiss(),r()},className:t,"aria-label":e,children:n}),s.jsx(pt,{visible:a.visible,className:"whitespace-nowrap",children:e})]})}function U4({showFavoriteCollectionBatchBar:e,showTaskBatchBar:t,selectedTaskIds:r,tasks:n,clearFavoriteCollectionSelection:a,onSelectAllVisibleFavoriteCollections:o,onInvertVisibleFavoriteCollections:i,onDownloadSelectedFavoriteCollections:l,onDeleteSelectedFavoriteCollections:c,clearSelection:u,onSelectAllVisibleTasks:f,onInvertVisibleTasks:d,onToggleFavorite:g,onDownloadSelected:m,onDeleteSelected:x}){return e?s.jsx("div",{className:"flex justify-center mb-3",children:s.jsxs("div",{className:"bg-white/90 dark:bg-gray-800/90 backdrop-blur shadow-[0_8px_30px_rgb(0,0,0,0.12)] dark:shadow-lg rounded-full flex items-center p-1 border border-gray-200/50 dark:border-white/10 pointer-events-auto",children:[s.jsx(un,{onClick:a,className:"p-2 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors",tooltip:"取消选择",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx(un,{onClick:o,className:"p-2 text-blue-500 dark:text-blue-400 hover:text-blue-600 dark:hover:text-blue-300 transition-colors",tooltip:"全选收藏夹",children:s.jsxs("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]})}),s.jsx(un,{onClick:i,className:"p-2 text-purple-500 dark:text-purple-400 hover:text-purple-600 dark:hover:text-purple-300 transition-colors",tooltip:"反选收藏夹",children:s.jsxs("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeDasharray:"4 4",d:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z"}),s.jsx("path",{d:"M8 12h8M13 9l3 3-3 3"})]})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx(un,{onClick:l,className:"p-2 text-green-500 dark:text-green-400 hover:text-green-600 dark:hover:text-green-300 transition-colors",tooltip:"下载选中",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx(un,{onClick:c,className:"p-2 text-red-500 dark:text-red-400 hover:text-red-600 dark:hover:text-red-300 transition-colors",tooltip:"删除选中",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})}):t?s.jsx("div",{className:"flex justify-center mb-3",children:s.jsxs("div",{className:"bg-white/90 dark:bg-gray-800/90 backdrop-blur shadow-[0_8px_30px_rgb(0,0,0,0.12)] dark:shadow-lg rounded-full flex items-center p-1 border border-gray-200/50 dark:border-white/10 pointer-events-auto",children:[s.jsx(un,{onClick:u,className:"p-2 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white transition-colors",tooltip:"取消选择",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx(un,{onClick:f,className:"p-2 text-blue-500 dark:text-blue-400 hover:text-blue-600 dark:hover:text-blue-300 transition-colors",tooltip:"全选任务",children:s.jsxs("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]})}),s.jsx(un,{onClick:d,className:"p-2 text-purple-500 dark:text-purple-400 hover:text-purple-600 dark:hover:text-purple-300 transition-colors",tooltip:"反选任务",children:s.jsxs("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeDasharray:"4 4",d:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2z"}),s.jsx("path",{d:"M8 12h8M13 9l3 3-3 3"})]})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),g&&s.jsxs(s.Fragment,{children:[s.jsx(un,{onClick:g,className:"p-2 text-yellow-500 dark:text-yellow-400 hover:text-yellow-600 dark:hover:text-yellow-300 transition-colors",tooltip:"编辑收藏夹",children:r.length>0&&r.every(b=>{var h;return(h=n.find(y=>y.id===b))==null?void 0:h.isFavorite})?s.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})}):s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:s.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"})]}),s.jsx(un,{onClick:m,className:"p-2 text-green-500 dark:text-green-400 hover:text-green-600 dark:hover:text-green-300 transition-colors",tooltip:"下载选中",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})})}),s.jsx("div",{className:"w-px h-5 bg-gray-200 dark:bg-white/20 mx-1"}),s.jsx(un,{onClick:x,className:"p-2 text-red-500 dark:text-red-400 hover:text-red-600 dark:hover:text-red-300 transition-colors",tooltip:"删除选中",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})}):null}const Sy="h-8 px-3.5 rounded-full text-xs transition-colors duration-200 focus:outline-none",Ny="bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-gray-700 dark:text-gray-200",eh=240,F4="bg-blue-500/[0.1] dark:bg-blue-500/[0.16] hover:bg-blue-500/[0.14] dark:hover:bg-blue-500/[0.22] text-blue-600 dark:text-blue-400";function th({label:e,summary:t,active:r=!1,className:n="",children:a}){const[o,i]=p.useState(!1),[l,c]=p.useState(!1),u=p.useRef(null),f=p.useRef(null);return p.useEffect(()=>{if(!o)return;const d=m=>{var b,h;const x=m.target;!((b=f.current)!=null&&b.contains(x))&&!((h=u.current)!=null&&h.contains(x))&&i(!1)},g=m=>{m.key==="Escape"&&i(!1)};return document.addEventListener("pointerdown",d),document.addEventListener("keydown",g),()=>{document.removeEventListener("pointerdown",d),document.removeEventListener("keydown",g)}},[o]),s.jsxs("div",{className:`relative min-w-0 max-sm:flex-auto ${n}`,children:[s.jsxs("button",{ref:u,type:"button",onClick:()=>{var g;xr();const d=(g=u.current)==null?void 0:g.getBoundingClientRect();d&&c(d.left+eh>window.innerWidth-8),i(m=>!m)},"aria-expanded":o,className:`flex w-full items-center gap-1 min-w-0 ${Sy} ${r?F4:Ny} ${o&&!r?"!bg-black/[0.07] dark:!bg-white/[0.1]":""}`,children:[s.jsx("span",{className:"flex-shrink-0",children:e}),t&&s.jsxs("span",{className:`flex-1 truncate text-left ${r?"opacity-75":"text-gray-400 dark:text-gray-500"}`,children:["· ",t]}),s.jsx(Nd,{className:`w-3.5 h-3.5 flex-shrink-0 transition-transform duration-200 ${r?"":"text-gray-400 dark:text-gray-500"} ${o?"rotate-180":""}`})]}),o&&s.jsx("div",{ref:f,style:{width:eh},className:`absolute bottom-full ${l?"right-0":"left-0"} z-40 mb-2 flex flex-col gap-2 rounded-xl bg-white/95 p-3 shadow-[0_8px_30px_rgb(0,0,0,0.12)] ring-1 ring-black/5 backdrop-blur-xl animate-dropdown-up dark:bg-gray-800/95 dark:shadow-[0_8px_30px_rgb(0,0,0,0.4)] dark:ring-white/[0.06]`,children:a})]})}const Pl=`${Sy} ${Ny}`,rh="h-8 px-3.5 rounded-full bg-black/[0.03] dark:bg-white/[0.04] opacity-50 cursor-not-allowed text-xs text-gray-700 dark:text-gray-200",Wn="relative flex items-center justify-between gap-3",Hn="text-gray-500 dark:text-gray-400",nh="px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.04] opacity-50 cursor-not-allowed text-xs transition-all duration-200";function sh({checked:e,disabled:t,label:r,onToggle:n}){return s.jsx("button",{type:"button",onClick:n,disabled:t,className:`relative inline-flex h-4 w-7 flex-shrink-0 items-center rounded-full transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${e?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e,"aria-label":r,children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e?"translate-x-[14px]":"translate-x-[2px]"}`})})}function ah(e,t){const r=Number(e);return e.trim()&&Number.isFinite(r)?Vh(r):t}function $4({value:e,disabled:t,onCommit:r}){const[n,a]=p.useState(String(e)),[o,i]=p.useState(!1),l=p.useRef({input:n,value:e,onCommit:r});l.current={input:n,value:e,onCommit:r},p.useEffect(()=>()=>{const u=l.current,f=ah(u.input,u.value);f!==u.value&&u.onCommit(f)},[]);const c=()=>{const u=ah(n,e);a(String(u)),u!==e&&r(u)};return s.jsxs(s.Fragment,{children:[s.jsx("input",{value:n,onChange:u=>a(u.target.value),onFocus:()=>i(!0),onBlur:()=>{i(!1),c()},onKeyDown:u=>{u.key==="Enter"&&u.currentTarget.blur()},disabled:t,type:"number",min:1,className:`w-28 px-3 py-1.5 rounded-xl border border-transparent focus:border-blue-300 dark:focus:border-blue-500/50 focus:outline-none text-xs transition-all duration-200 ${t?"bg-black/[0.03] dark:bg-white/[0.04] opacity-50 cursor-not-allowed":"bg-black/[0.04] dark:bg-white/[0.06]"}`}),s.jsx(Mr,{visible:o&&Number(n)>Jl,text:`并发数超过 ${Jl} 可能导致${De?"客户端":"浏览器"}卡顿或触发服务商限流`})]})}function z4({params:e,setParams:t,activeProfile:r,modelOptions:n,onModelChange:a,isFalProvider:o,isFalTextToImage:i,displaySize:l,qualityOptions:c,selectClass:u,transparentOutputAvailable:f,showTransparentOutputControl:d,transparentOutputEnabled:g,transparentOutputHint:m,onTransparentOutputMenuOpenChange:x,compressionHint:b,compressionDisabled:h,outputCompressionInput:y,setOutputCompressionInput:v,commitOutputCompression:I,moderationHint:S,moderationDisabled:k,agentAutoImageCount:j,outputImageLimit:A,nInput:N,setNInputFocused:C,commitN:T,handleNInputChange:R,handleNLimitIncreaseAttempt:U,showAgentNHint:W,hideNLimitHint:F,startAgentNHintTouch:_,clearAgentNHintTouchTimer:O,nLimitHint:J,nLimitHintText:H,streamConcurrentByN:K,streamConcurrentHint:te,sizeHint:P,qualityHint:B,onOpenSizePicker:$,showBatch:Q,batchEnabled:L,batchMode:G,batchConcurrencyLimited:se,batchConcurrency:Y,batchPromptCount:le,batchProgress:ie,onBatchChange:D,onStopBatch:ue}){const ke=[e.output_format.toUpperCase(),d?`透明 ${g}`:h?null:`压缩 ${y||"默认"}`,k?null:`审核 ${e.moderation}`].filter(Boolean).join(" · "),we=Ne=>s.jsx("span",{className:"mr-1.5 text-gray-400 dark:text-gray-500",children:Ne}),We=ie?`${ie.finished}/${ie.total}`:L?`${le} 条`:void 0;return s.jsxs("div",{className:"flex flex-1 flex-wrap sm:flex-nowrap items-center gap-2 min-w-0 text-xs",children:[s.jsx("div",{className:"min-w-0 max-w-full sm:shrink-[0.01] max-sm:flex-auto",children:s.jsx(_t,{value:r.model,onChange:Ne=>a(String(Ne)),options:n,showValueTooltips:!0,menuClassName:"min-w-max",className:Pl})}),s.jsxs("div",{className:"relative max-sm:flex-auto sm:shrink-0",onMouseEnter:P.show,onMouseLeave:P.hide,onTouchStart:P.startTouch,onTouchEnd:P.clearTimer,onTouchCancel:P.hide,onClick:P.show,children:[s.jsxs("button",{type:"button",onClick:()=>{xr(),$()},className:`flex w-full items-center ${Pl}`,children:[we("尺寸"),s.jsx("span",{className:"font-mono",children:l})]}),s.jsx(Mr,{visible:(i||r.codexCli)&&P.visible,text:i?s.jsxs(s.Fragment,{children:["fal.ai 的文生图模式不支持 ",s.jsx("code",{className:"rounded bg-white/10 px-1 py-0.5 font-mono",children:"auto"})," 参数"]}):"Codex CLI 不支持尺寸参数,此处设置仅基于提示词工程"})]}),s.jsxs("div",{className:"relative max-sm:flex-auto sm:shrink-0",onMouseEnter:B.show,onMouseLeave:B.hide,onTouchStart:B.startTouch,onTouchEnd:B.clearTimer,onTouchCancel:B.hide,onClick:B.show,children:[s.jsx(_t,{value:r.codexCli?"auto":o&&e.quality==="auto"?"high":e.quality,onChange:Ne=>{r.codexCli||t({quality:Ne})},options:c,disabled:r.codexCli,prefix:we("质量"),menuClassName:"min-w-max",className:r.codexCli?rh:Pl}),s.jsx(Mr,{visible:(r.codexCli||o)&&B.visible,text:o?s.jsxs(s.Fragment,{children:["fal.ai 不支持 ",s.jsx("code",{className:"rounded bg-white/10 px-1 py-0.5 font-mono",children:"auto"})," 质量参数"]}):"Codex CLI 不支持质量参数"})]}),s.jsxs("label",{className:`relative flex items-center max-sm:flex-auto sm:shrink-0 ${j?rh:`${Pl} cursor-text`}`,onMouseEnter:()=>{W(),te.show()},onMouseLeave:()=>{F(),te.hide()},onTouchStart:()=>{_(),te.startTouch()},onTouchEnd:()=>{O(),te.clearTimer()},onTouchCancel:()=>{O(),F(),te.hide()},onClick:()=>{W(),te.show()},children:[we("数量"),s.jsx("input",{value:N,onChange:Ne=>R(Ne.target.value),onFocus:()=>C(!0),onBlur:()=>{C(!1),T()},onKeyDown:Ne=>{Ne.key==="ArrowUp"&&U(()=>Ne.preventDefault())},onWheel:Ne=>{Ne.deltaY<0&&U(()=>Ne.preventDefault())},disabled:j,type:j?"text":"number",min:j?void 0:1,max:j?void 0:A,style:{width:`${Math.max(1,N.length)}ch`},className:"bg-transparent text-xs focus:outline-none disabled:cursor-not-allowed [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"}),s.jsx(Mr,{visible:J.visible,text:H}),s.jsx(Mr,{visible:K&&te.visible&&!J.visible,text:"数量大于 1 时会将多图生成拆分为并发单图"})]}),s.jsxs(th,{label:"更多",summary:ke,className:"sm:min-w-[5rem]",children:[s.jsxs("div",{className:Wn,children:[s.jsx("span",{className:Hn,children:"格式"}),s.jsx("div",{className:"w-28",children:s.jsx(_t,{value:e.output_format,onChange:Ne=>{t({output_format:Ne,...Ne==="png"?{output_compression:null}:{},...Ne==="jpeg"?{transparent_output:!1}:{}})},options:[{label:"PNG",value:"png"},{label:"JPEG",value:"jpeg"},{label:"WebP",value:"webp"}],className:u})})]}),d&&s.jsxs("div",{className:Wn,onMouseEnter:m.show,onMouseLeave:m.hide,onTouchStart:m.startTouch,onTouchEnd:m.clearTimer,onTouchCancel:m.hide,onClick:m.show,children:[s.jsx("span",{className:Hn,children:"透明背景"}),s.jsx("div",{className:"w-28",children:s.jsx(_t,{value:g?"on":"off",onChange:Ne=>{f&&t({transparent_output:Ne==="on",...e.output_format==="png"?{output_compression:null}:{}})},options:[{label:"false",value:"off"},{label:"true",value:"on"}],className:u,onOpenChange:x})}),s.jsx(Mr,{visible:m.visible,text:s.jsxs(s.Fragment,{children:["实现方式可在",s.jsx("strong",{className:"font-semibold",children:"「设置 → API 配置」"}),"中选择"]})})]}),!d&&s.jsxs("label",{className:Wn,onMouseEnter:b.show,onMouseLeave:b.hide,onTouchStart:b.startTouch,onTouchEnd:b.clearTimer,onTouchCancel:b.hide,onClick:b.show,children:[s.jsx("span",{className:Hn,children:"压缩率"}),s.jsx("input",{value:y,onChange:Ne=>v(Ne.target.value),onBlur:I,disabled:h,type:"number",min:0,max:100,placeholder:"0-100",className:`w-28 px-3 py-1.5 rounded-xl border border-transparent focus:border-blue-300 dark:focus:border-blue-500/50 focus:outline-none text-xs transition-all duration-200 ${h?"bg-black/[0.03] dark:bg-white/[0.04] opacity-50 cursor-not-allowed":"bg-black/[0.04] dark:bg-white/[0.06]"}`}),s.jsx(Mr,{visible:b.visible,text:o?"fal.ai 不支持压缩率参数":"仅 JPEG 和 WebP 支持压缩率"})]}),s.jsxs("div",{className:Wn,onMouseEnter:S.show,onMouseLeave:S.hide,onTouchStart:S.startTouch,onTouchEnd:S.clearTimer,onTouchCancel:S.hide,onClick:S.show,children:[s.jsx("span",{className:Hn,children:"审核"}),s.jsx("div",{className:"w-28",children:s.jsx(_t,{value:k?"auto":e.moderation,onChange:Ne=>{k||t({moderation:Ne})},options:[{label:"auto",value:"auto"},{label:"low",value:"low"}],disabled:k,className:k?nh:u})}),s.jsx(Mr,{visible:k&&S.visible,text:"fal.ai 不支持审核参数"})]})]}),Q&&s.jsxs(th,{label:"批量",summary:We,active:L||!!ie,className:"sm:shrink-0",children:[s.jsxs("div",{className:Wn,children:[s.jsx("span",{className:Hn,children:"多提示词批量提交"}),s.jsx(sh,{checked:L,disabled:!!ie,label:"多提示词批量提交",onToggle:()=>D({batchPromptEnabled:!L})})]}),L&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:Wn,children:[s.jsx("span",{className:Hn,children:"执行方式"}),s.jsx("div",{className:"w-28",children:s.jsx(_t,{value:G,onChange:Ne=>D({batchPromptMode:Ne}),options:[{label:"排队",value:"queue"},{label:"并发",value:"concurrent"}],disabled:!!ie,className:ie?nh:u})})]}),G==="concurrent"&&s.jsxs("div",{className:Wn,children:[s.jsx("span",{className:Hn,children:"限制并发数"}),s.jsx(sh,{checked:se,disabled:!!ie,label:"限制并发数",onToggle:()=>D({batchPromptConcurrencyLimited:!se})})]}),G==="concurrent"&&se&&s.jsxs("label",{className:Wn,children:[s.jsx("span",{className:Hn,children:"并发数"}),s.jsx($4,{value:Y,disabled:!!ie,onCommit:Ne=>D({batchPromptConcurrency:Ne})})]}),G==="concurrent"&&!se&&s.jsxs("p",{className:"rounded-lg bg-amber-500/[0.1] px-2.5 py-2 text-[11px] leading-relaxed text-amber-700 dark:bg-amber-500/[0.14] dark:text-amber-400/90",children:["不限制并发时会同时发出全部请求,提示词较多时可能导致",De?"客户端":"浏览器","卡顿甚至崩溃,也容易触发服务商限流。"]}),s.jsxs("p",{className:"text-[11px] leading-relaxed text-gray-400 dark:text-gray-500",children:["提示词之间空两行分隔,当前共 ",le," 条;参考图和参数对每条提示词都生效。"]})]}),ie&&s.jsxs("div",{className:Wn,children:[s.jsxs("span",{className:Hn,children:["已完成 ",ie.finished," / ",ie.total]}),s.jsx("button",{type:"button",onClick:ue,className:"rounded-xl bg-red-500/[0.12] px-3 py-1.5 text-xs font-medium text-red-600 transition-colors hover:bg-red-500/[0.18] dark:bg-red-500/[0.18] dark:text-red-400/90 dark:hover:bg-red-500/[0.25]",children:"停止批量"})]})]})]})}function oh(e,t,r){const n=t.filter(a=>a.isFavorite);return e===or?n:n.filter(a=>Vr(a,r).includes(e))}function W4(e){return new Promise(t=>window.setTimeout(t,e))}function H4(){const[e,t]=p.useState(window.innerWidth<640);return p.useEffect(()=>{const r=()=>t(window.innerWidth<640);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function Y4(e,t){const r=e.trim().toLowerCase();if(!r)return!0;const n=t.toLowerCase();return n.includes(r)||n.replace(/^@/,"").includes(r)}function V4({option:e}){const[t,r]=p.useState(e.type==="input"?e.dataUrl:En(e.imageId)||"");return p.useEffect(()=>{if(e.type==="input"){r(e.dataUrl);return}let n=!1;return r(En(e.imageId)||""),kt(e.imageId).then(a=>{!n&&a&&r(a)}),()=>{n=!0}},[e]),s.jsx("span",{className:"h-9 w-9 shrink-0 overflow-hidden rounded-lg border border-gray-200/70 bg-gray-100 dark:border-white/[0.08] dark:bg-white/[0.04]",children:t&&s.jsx("img",{src:t,className:"h-full w-full object-cover",alt:""})})}function K4(){const e=w(E=>E.prompt),t=w(E=>E.appMode),r=w(E=>E.setPrompt),n=w(E=>E.inputImages),a=w(E=>E.addInputImage),o=w(E=>E.setSketchBoard),i=w(E=>E.removeInputImage),l=w(E=>E.clearInputImages),c=w(E=>E.params),u=w(E=>E.setParams),f=w(E=>E.setSettings),d=w(E=>E.batchProgress),g=w(E=>E.settings),m=w(E=>E.reusedTaskApiProfileId),x=w(E=>E.reusedTaskApiModel),b=w(E=>E.setReusedTaskApiModel),h=w(E=>E.setShowSettings),y=w(E=>E.setLightboxImageId),v=w(E=>E.showToast),I=w(E=>E.setConfirmDialog),S=w(E=>E.selectedTaskIds),k=w(E=>E.setSelectedTaskIds),j=w(E=>E.clearSelection),A=w(E=>E.selectedFavoriteCollectionIds),N=w(E=>E.setSelectedFavoriteCollectionIds),C=w(E=>E.clearFavoriteCollectionSelection),T=sy(),R=w(E=>E.favoriteCollections),U=w(E=>E.defaultFavoriteCollectionId),W=w(E=>E.agentConversations),F=w(E=>E.activeAgentConversationId),_=w(E=>E.filterStatus),O=w(E=>E.filterFavorite),J=w(E=>E.activeFavoriteCollectionId),H=w(E=>E.openFavoritePicker),K=w(E=>!!E.privacyMode),te=w(E=>E.searchQuery),P=p.useMemo(()=>{const E=[...T].sort((ce,Ie)=>Ie.createdAt-ce.createdAt),q=te.trim().toLowerCase();return E.filter(ce=>O&&(!ce.isFavorite||J&&J!==or&&!Vr(ce,U).includes(J))||!vi(ce,_)?!1:jc(ce,q))},[T,te,_,O,J,U]),B=O&&!J,$=p.useMemo(()=>[{id:or,name:"全部",tasks:oh(or,T,U)},...R.map(E=>({id:E.id,name:E.name,collection:E,tasks:oh(E.id,T,U)}))],[U,R,T]),Q=p.useMemo(()=>{if(!te.trim())return $;const E=te.toLowerCase();return $.filter(q=>q.name.toLowerCase().includes(E))},[$,te]),L=p.useCallback(()=>{k(P.map(E=>E.id))},[P,k]),G=p.useCallback(()=>{const E=new Set(P.map(q=>q.id));k(q=>{const ce=new Set(q),Ie=q.filter(je=>!E.has(je));return P.forEach(je=>{ce.has(je.id)||Ie.push(je.id)}),Ie})},[P,k]),se=p.useCallback(()=>{N(Q.map(E=>E.id))},[Q,N]),Y=p.useCallback(()=>{const E=new Set(Q.map(q=>q.id));N(q=>{const ce=new Set(q),Ie=q.filter(je=>!E.has(je));return Q.forEach(je=>{ce.has(je.id)||Ie.push(je.id)}),Ie})},[Q,N]),le=p.useCallback(()=>{H(S)},[H,S]),ie=p.useCallback(()=>{I({title:"批量删除",message:`确定要删除选中的 ${S.length} 个任务吗?`,action:()=>{Zi(S)}})},[S,I]),D=p.useCallback(async()=>{const E=T.filter(ce=>S.includes(ce.id)),q=E.flatMap(ce=>ce.outputImages||[]);if(q.length===0){v("选中的任务没有图片","info");return}try{const Ie=`batch-${di(new Date)}`,je=g.zipDownloadRoutes.includes("task-selection")?await so(Y0(E),Ie):await Xn(q,Ie);if(je.canceled)return;je.successCount===0?v(Zt(je.error),"error"):je.failCount>0?v(`部分下载失败:成功 ${je.successCount},失败 ${je.failCount}`,"error"):v(Kn(je.successCount>1?`下载成功:${je.successCount} 张图片`:"下载成功",je.location),"success")}catch(ce){console.error(ce),v(Zt(ce),"error")}j()},[T,S,g.zipDownloadRoutes,v,j]),ue=p.useCallback(async()=>{const E=new Set(A),q=$.filter(Et=>E.has(Et.id));if(q.length===0)return;let ce=0,Ie=0,je=0,et,mt;const Fn=g.zipDownloadRoutes.includes("favorite-collection-selection"),Sn=di(new Date);try{const Et=De&&q.length>1?await ug():null;if(De&&q.length>1&&!Et)return;for(const pr of q){const ln=Y0(pr.tasks);if(ln.length===0)continue;const Ls=pr.id===or?`favorites-all-${Sn}`:`favorites-${pr.name}-${Sn}`,cn=Fn?await so(ln,Ls,Et):await Xn(ln.map(Fd=>Fd.imageId),Ls,Et);if(cn.canceled)return;ce+=cn.successCount,Ie+=cn.failCount,et=(Et==null?void 0:Et.path)??cn.location??et,mt=cn.error??mt,cn.successCount>0&&je++,q.length>1&&!Et&&await W4(100)}ce===0&&Ie>0?v(Zt(mt),"error"):ce===0?v("选中的收藏夹没有图片","info"):Ie>0?v(`部分下载失败:成功 ${ce},失败 ${Ie}`,"error"):v(Kn(Fn&&je>1?`下载成功:${je} 个压缩包,${ce} 张图片`:`下载成功:${ce} 张图片`,et),"success")}catch(Et){console.error(Et),v(Zt(Et),"error")}C()},[C,$,A,g.zipDownloadRoutes,v]),ke=p.useCallback(()=>{const E=new Set(A),q=R.filter(je=>E.has(je.id));if(q.length===0){v("没有可删除的收藏夹","info");return}if(R.length-q.length<1){v("至少保留一个收藏夹","error");return}const ce=new Set(q.map(je=>je.id)),Ie=new Set(T.filter(je=>Vr(je,U).some(et=>ce.has(et))).flatMap(je=>je.outputImages||[])).size;I({title:"批量删除收藏夹",message:`确定要删除选中的 ${q.length} 个收藏夹吗?`,checkbox:Ie>0?{label:`同时删除收藏夹中的图片(${Ie} 张)`,tone:"danger"}:void 0,action:async(je=!1)=>{for(const et of q)await Cd(et.id,je);C()}})},[C,U,R,A,I,v,T]),we=w(E=>E.maskDraft),We=w(E=>E.moveInputImage),Ne=p.useRef(null),Fe=p.useRef(null),Ee=p.useRef(null),Ge=p.useRef(null),Xe=p.useRef(null),ht=p.useRef(42),[Pe,ne]=p.useState(!1),[ge,xe]=p.useState(!0),[fe,be]=p.useState(!1),[Z,de]=p.useState(0),[he,pe]=p.useState(!1),[Be,Oe]=p.useState(!1),[Ue,lt]=p.useState(!1),[ut,Ve]=p.useState(!1),[He,vt]=p.useState(!1),[ct,rt]=p.useState(null),[V,X]=p.useState(!1),[me,ve]=p.useState(!1),[ae,_e]=p.useState(!1),[Ye,wt]=p.useState(!1),[xt,qe]=p.useState(""),[tt,Pt]=p.useState(null),[Ct,Ht]=p.useState(null),[Dt,Tt]=p.useState(0),[Ce,Or]=p.useState(!1),[nt,tr]=p.useState(null),Le=p.useRef(null),gt=p.useRef({startY:0,moved:!1}),Ut=p.useRef(0),jr=p.useRef(null),rr=p.useRef({index:null,startX:0,startY:0,moved:!1}),Ft=p.useRef(null),Sr=p.useRef(null),Jt=p.useRef(!1),cr=p.useRef(!1),jn=p.useRef(!1),Xr=p.useRef(!1),Mt=p.useRef(null),[os,Nr]=p.useState(0),[Ar,an]=p.useState(0),oe=fe||he,Te=p.useCallback(()=>{var Ie;const E=(Ie=Ge.current)==null?void 0:Ie.closest("[data-input-bar]");if(!E)return;const q=E.getBoundingClientRect(),ce=Math.max(0,window.innerHeight-q.top);document.documentElement.style.setProperty("--input-bar-clearance",`${Math.ceil(ce)}px`)},[]);p.useLayoutEffect(()=>{var je;const E=(je=Ge.current)==null?void 0:je.closest("[data-input-bar]");if(!E)return;const q=window.requestAnimationFrame(Te),ce=new ResizeObserver(Te);ce.observe(E);const Ie=window.visualViewport;return window.addEventListener("resize",Te),Ie==null||Ie.addEventListener("resize",Te),Ie==null||Ie.addEventListener("scroll",Te),()=>{window.cancelAnimationFrame(q),ce.disconnect(),window.removeEventListener("resize",Te),Ie==null||Ie.removeEventListener("resize",Te),Ie==null||Ie.removeEventListener("scroll",Te),document.documentElement.style.removeProperty("--input-bar-clearance")}},[Te]),p.useLayoutEffect(()=>{if(!fe)return;const E=document.querySelector("header");if(!E)return;const q=()=>de(Math.max(0,E.getBoundingClientRect().bottom)+8),ce=new ResizeObserver(q);return ce.observe(E),q(),window.addEventListener("resize",q),E.addEventListener("transitionend",q),()=>{ce.disconnect(),window.removeEventListener("resize",q),E.removeEventListener("transitionend",q)}},[fe]);const Qe=p.useRef(null),[z,ee]=p.useState(c.output_compression==null?"":String(c.output_compression)),[re,Ae]=p.useState(String(c.n)),[$e,dt]=p.useState(!1),Je=p.useRef(0),It=H4(),it=p.useMemo(()=>zt(g),[g]),Yt=p.useMemo(()=>t==="agent"?Ui(g)??it:it,[t,g,it]),ft=p.useMemo(()=>{const E=t!=="agent"&&g.reuseTaskApiProfileTemporarily&&m?g.profiles.find(q=>q.id===m):void 0;return E?oo(E,x??void 0):Yt},[t,Yt,x,m,g]),At=ft.id!==Yt.id,Ps=p.useMemo(()=>{var E;return ca(((E=g.profiles.find(q=>q.id===ft.id))==null?void 0:E.model)??ft.model).map(q=>({label:q,value:q}))},[ft.id,ft.model,g.profiles]),mo=p.useCallback(E=>{if(At){b(E);return}f({profiles:g.profiles.map(q=>q.id===ft.id?{...q,selectedModel:E}:q)})},[ft.id,At,b,f,g.profiles]),is=t==="agent"?W.find(E=>E.id===F)??null:null,dr=!!(is!=null&&is.rounds.some(E=>E.status==="running")),ho=p.useMemo(()=>ft.id===it.id?g:Me({...g,activeProfileId:ft.id}),[ft.id,it.id,g]),Br=!!ft.apiKey,ls=!!d,Ts=!!(e.trim()&&Br&&!dr&&!ls),cs=t==="gallery"&&g.showBatchPrompt&&g.batchPromptEnabled,Td=t==="gallery"&&(g.showBatchPrompt||ls),po=p.useMemo(()=>cs?Yh(e).length:0,[cs,e]),nl=dr?"停止生成":Br?we?"遮罩编辑":cs?`批量生成 ${po} 条`:"生成图像":"请先配置 API",sl=dr?"停止生成":Br?t==="agent"?"画廊批量任务进行中,请等待完成或回到画廊停止后再提交":"批量任务进行中,请等待完成或停止后再提交":"尚未完成 API 配置,请在右上角设置中进行",al=cs?"每条提示词之间空两行分隔,可输入 @ 来指定参考图...":"描述你想生成的图片,可输入 @ 来指定参考图...",ka=p.useCallback(()=>{t==="agent"?Yj():ji()},[t]),ol=p.useCallback(()=>{Fj(F)},[F]),Ms=p.useCallback(()=>{const E=Ee.current;if(!E)return;cr.current=!0;const q=Na(E);Nr(q.start),Us(E),r(G0(E))},[r]),Un=ft.provider==="fal",$t=t==="agent",xo=Un,bo=t==="gallery",il=bo&&(c.output_format==="png"||c.output_format==="webp"),Md=bo&&il&&c.transparent_output,ll=c.output_format==="png"||Un,on=yx(ho),Es=Un&&n.length===0,cl=Number(re),Ed=Number.isNaN(cl)?c.n:cl,dl=ft.provider==="openai"&&ft.streamImages===!0&&!$t&&Ed>1,Rd=$t?"Agent 模式下数量由模型根据提示词自动决定":Un?`fal.ai 最大请求数量为 ${on}`:`OpenAI 最大请求数量为 ${on}`,_d=Es&&c.size==="auto"?Ou:(ft.codexCli?Of(c.size):ad(c.size))||Qr.size,Dd=[...Un?[]:[{label:"auto",value:"auto"}],{label:"low",value:"low"},{label:"medium",value:"medium"},{label:"high",value:"high"},...ff(Ri(ft))?[{label:"xhigh",value:"xhigh"},{label:"max",value:"max"}]:[]],Ia=n.length>=yr,ul=Ia?`参考图数量已达上限(${yr} 张),无法继续添加`:"添加图片",yo=Fs(),M=p.useCallback(E=>{E&&yo.hide()},[yo.hide]),ye=Fs({enabled:()=>ll}),Re=Fs({enabled:()=>xo}),Se=Fs({enabled:()=>Es||ft.codexCli}),ot=Fs({enabled:()=>ft.codexCli||Un}),st=Fs({autoHideMs:2e3}),Gt=Fs({enabled:()=>dl}),at=we?n.find(E=>E.id===we.targetImageId)??null:null,hr=at?n.filter(E=>E.id!==at.id):n,Vt=os,qr=gr(e),Og=p.useMemo(()=>is?fa(is).flatMap(E=>cd(E,T).flatMap((q,ce)=>{if(!q)return[];const Ie=`@第${E.index}轮图${ce+1}`;return{type:"agent-output",key:`agent-output:${E.id}:${ce}:${q}`,label:Ie,imageId:q,insertText:Ie}})):[],[is,T]),Ld=n.length+Og.length,Od=Jw(e,Vt)?null:gm(qr,Vt,{length:Ld}),Rs=Od?[...n.map((E,q)=>({type:"input",key:`input:${E.id}:${q}`,label:zo(q),imageId:E.id,dataUrl:E.dataUrl,imageIndex:q})).filter(E=>Gw(Od.query,E.imageIndex)),...Og.filter(E=>Y4(Od.query,E.label))]:[],Bg=!Ce&&Rs.length>0,Ug=p.useCallback(E=>{const q=Ee.current,ce=q?T4(q):e.length,Ie=gm(gr(e),ce,{length:Ld});if(Or(!0),Tt(0),!Ie)return;const je=E.type==="input"?zo(E.imageIndex):E.insertText,et=Ie.start+je.length;if(q&&(q.focus(),Q0(q,Ie.start,ce),document.execCommand("insertHTML",!1,su(je)))){Al(q,et),Ms();return}const mt=E.type==="input"?mm(e,Ie.start,ce,E.imageIndex):up(e,Ie.start,ce,E.insertText);cr.current=!1,r(mt.prompt),window.setTimeout(()=>{Ee.current&&(Ee.current.focus(),Al(Ee.current,mt.cursor))},0)},[Ld,e,r,Ms]),Bd=p.useCallback(E=>{const q=Ee.current;if(q&&!E.includes(`
|
|
85
|
+
`)&&(q.focus(),document.execCommand("insertText",!1,E))){Ms();return}const ce=q?Na(q):{start:e.length,end:e.length},Ie=ms(e,ce.start),je=ms(e,ce.end),et=`${e.slice(0,Ie)}${E}${e.slice(je)}`,mt=ce.start+E.length;cr.current=!1,r(et),window.setTimeout(()=>{Ee.current&&(Ee.current.focus(),Al(Ee.current,mt))},0)},[e,r,Ms]),cv=p.useCallback(()=>{cr.current=!1,r(""),Ee.current&&(Ee.current.innerHTML="",Ee.current.focus())},[r]);p.useEffect(()=>{ee(c.output_compression==null?"":String(c.output_compression))},[c.output_compression]),p.useEffect(()=>{Ae($t?"auto":String(c.n))},[$t,c.n]),p.useEffect(()=>{const E=Mn(c,ho,{hasInputImages:n.length>0}),q=vx(c,E);Object.keys(q).length&&u(q)},[n.length,c,ho,u]),p.useEffect(()=>()=>{var E;Qe.current!=null&&window.clearTimeout(Qe.current),(E=Mt.current)==null||E.call(Mt)},[]),p.useEffect(()=>{let E=!1;if(!we||!at){qe("");return}return rd(at.dataUrl,we.maskDataUrl).then(q=>{E||qe(q)}).catch(()=>{E||qe("")}),()=>{E=!0}},[we,at==null?void 0:at.id,at==null?void 0:at.dataUrl]);const dv=p.useCallback(()=>{if(z.trim()===""){ee(""),u({output_compression:null});return}const E=Number(z);if(Number.isNaN(E)){ee(c.output_compression==null?"":String(c.output_compression));return}ee(String(E)),u({output_compression:E})},[z,c.output_compression,u]),uv=p.useCallback(()=>{if(st.hide(),$t){Ae("auto");return}const E=Number(re),q=re.trim()===""?Qr.n:Number.isNaN(E)?c.n:E,ce=Math.min(on,Math.max(1,q));Ae(String(ce)),u({n:ce})},[$t,re,st,on,c.n,u]),_s=p.useCallback(()=>{st.show()},[st]),Ud=p.useCallback(()=>{st.hide()},[st]),fv=p.useCallback(()=>{$t&&_s()},[$t,_s]),gv=p.useCallback(()=>{st.clearTimer()},[st]),mv=p.useCallback(()=>{$t&&st.startTouch()},[$t,st]),hv=p.useCallback(E=>{if($t){Ae("auto");return}Ae(E);const q=Number(E);!Number.isNaN(q)&&q>on?_s():Ud()},[$t,Ud,on,_s]),pv=p.useCallback(E=>{if($t){E(),_s();return}const q=Number(re),ce=Number.isNaN(q)?c.n:q;!$e||ce<on||(E(),_s())},[$t,re,$e,on,c.n,_s]),vo=()=>{Qe.current!=null&&(window.clearTimeout(Qe.current),Qe.current=null)},xv=E=>rt(E),fl=()=>{Xr.current||(rt(null),vo())},Fg=()=>{var E;Xr.current=!1,(E=Mt.current)==null||E.call(Mt),Mt.current=null,rt(null),vo()},$g=E=>{if(Xr.current){rt(E);return}Xr.current=!0,rt(E);const q=()=>{window.removeEventListener("mouseup",q),window.removeEventListener("pointerup",q),window.removeEventListener("dragend",q),Mt.current===q&&(Mt.current=null,Xr.current=!1,rt(null),vo())};Mt.current=q,window.addEventListener("mouseup",q),window.addEventListener("pointerup",q),window.addEventListener("dragend",q)},zg=async E=>{try{const q=w.getState().inputImages.length;if(q>=yr){w.getState().showToast(`参考图数量已达上限(${yr} 张),无法继续添加`,"error");return}const ce=yr-q,Ie=Array.from(E).filter(mt=>mt.type.startsWith("image/")),je=Ie.slice(0,ce),et=Ie.length-je.length;for(const mt of je)await n5(mt);et>0&&w.getState().showToast(`已达上限 ${yr} 张,${et} 张图片被丢弃`,"error")}catch(q){w.getState().showToast(`图片添加失败:${q instanceof Error?q.message:String(q)}`,"error")}},gl=p.useRef(zg);gl.current=zg;const Wg=async E=>{await gl.current(E.target.files||[]),E.target.value=""},bv=E=>{var q;if(!(E.key==="Enter"&&(E.nativeEvent.isComposing||jn.current||E.nativeEvent.keyCode===229))){if(Bg){if(E.key==="ArrowDown"){E.preventDefault(),Tt(ce=>(ce+1)%Rs.length);return}if(E.key==="ArrowUp"){E.preventDefault(),Tt(ce=>(ce-1+Rs.length)%Rs.length);return}if(E.key==="Enter"&&!E.shiftKey||E.key==="Tab"){E.preventDefault(),Ug(Rs[Dt]??Rs[0]);return}if(E.key==="Escape"){E.preventDefault(),Tt(0),(q=Ee.current)==null||q.blur();return}}if(E.key==="Enter"){E.preventDefault();const ce=E.ctrlKey||E.metaKey;g.enterSubmit?E.shiftKey?Bd(`
|
|
86
|
+
`):ce||Ts&&ka():ce?Ts&&ka():Bd(`
|
|
87
|
+
`);return}}},yv=E=>{const q=E.clipboardData.getData("text/plain");q&&(Array.from(E.clipboardData.items).some(ce=>ce.type.startsWith("image/"))||(E.preventDefault(),Bd(q.replace(/\r\n?/g,`
|
|
88
|
+
`))))},vv=E=>{const q=Ee.current;if(!q)return;const ce=Na(q);if(ce.start===ce.end)return;const Ie=ms(e,ce.start),je=ms(e,ce.end),et=gr(e.slice(Ie,je)),mt=/^\s*@图\d+\s*$/.test(et)?et.trim():et;E.preventDefault(),E.clipboardData.setData("text/plain",mt)};p.useEffect(()=>{const E=q=>{var je;const ce=(je=q.clipboardData)==null?void 0:je.items;if(!ce)return;const Ie=[];for(const et of Array.from(ce))if(et.type.startsWith("image/")){const mt=et.getAsFile();mt&&Ie.push(mt)}Ie.length>0&&(q.preventDefault(),gl.current(Ie))};return document.addEventListener("paste",E),()=>document.removeEventListener("paste",E)},[]),p.useEffect(()=>{const E=je=>{var et;je.preventDefault(),je.stopPropagation(),Je.current++,(et=je.dataTransfer)!=null&&et.types.includes("Files")&&ne(!0)},q=je=>{je.preventDefault(),je.stopPropagation()},ce=je=>{je.preventDefault(),je.stopPropagation(),Je.current--,Je.current===0&&ne(!1)},Ie=je=>{var Sn,Et;je.preventDefault(),je.stopPropagation(),Je.current=0,ne(!1);const et=(Sn=je.dataTransfer)==null?void 0:Sn.files;if(et&&et.length>0){gl.current(et);return}const mt=(Et=je.dataTransfer)==null?void 0:Et.getData("text/plain"),Fn=mt!=null&&mt.startsWith("agent-images:")?mt.slice(13).split(","):mt!=null&&mt.startsWith("agent-image:")?[mt.slice(12)]:[];Fn.length>0&&Promise.all(Fn.map(async pr=>{const ln=await kt(pr);if(!ln){v("部分图片已不存在","error");return}a({id:pr,dataUrl:ln})})).then(()=>{v("已上传图片","success")}).catch(pr=>v(`上传图片失败:${pr instanceof Error?pr.message:String(pr)}`,"error"))};return document.addEventListener("dragenter",E),document.addEventListener("dragover",q),document.addEventListener("dragleave",ce),document.addEventListener("drop",Ie),()=>{document.removeEventListener("dragenter",E),document.removeEventListener("dragover",q),document.removeEventListener("dragleave",ce),document.removeEventListener("drop",Ie)}},[a,v]);const Ds=p.useCallback(()=>{var ln,Ls,cn;const E=Ee.current;if(!E)return;const ce=(((ln=Xe.current)==null?void 0:ln.offsetHeight)??0)+140,Ie=Math.max(window.innerHeight*.4-ce,80),je=fe?Math.max(((Ls=E.parentElement)==null?void 0:Ls.clientHeight)??0,80):Ie;E.style.transition="none",E.style.height="0",E.style.overflowY="hidden";const et=E.scrollHeight,mt=(cn=E.parentElement)==null?void 0:cn.querySelector(".prompt-placeholder"),Fn=mt?mt.scrollHeight:0,Sn=Math.max(42,Fn),Et=Math.max(et,Sn),pr=Et>je?je:Et;xe(Et<=Sn),pe(Et>Ie),E.style.height=ht.current+"px",E.offsetHeight,E.style.transition="height 150ms ease, border-color 200ms, box-shadow 200ms",E.style.height=pr+"px",E.style.overflowY=Et>je?"auto":"hidden",ht.current=pr},[fe]);p.useEffect(()=>{const E=Ee.current;if(!E)return;if(cr.current){cr.current=!1;return}const q=fp(e,n),ce=e?q.map(Ie=>Ie.type==="mention"?su(Ie.text,Ie.mentionText):Ie.text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")).join(""):"";E.innerHTML!==ce&&(E.innerHTML=ce)},[e,n]),p.useEffect(()=>{const E=Ee.current;if(!E)return;const q=E.lastChild,ce=q instanceof HTMLBRElement&&q.dataset.sentinelBr==="true",Ie=e.endsWith(`
|
|
89
|
+
`);if(Ie&&!ce){const je=document.createElement("br");je.dataset.sentinelBr="true",E.appendChild(je)}else!Ie&&ce&&q.remove()},[e,n]),p.useEffect(()=>{Ds()},[e,n,Ds,It,V,fe]),p.useEffect(()=>{const E=()=>{const q=Ee.current;if(!q)return;const ce=window.getSelection();if(!ce||ce.rangeCount===0)return;const Ie=ce.getRangeAt(0);try{if(!Ie.intersectsNode(q)){Us(q);return}}catch{return}const je=Na(q);Nr(je.start),q.contains(Ie.startContainer)&&q.contains(Ie.endContainer)&&w.getState().setPromptSelection(je),Us(q);const et=Ie.getBoundingClientRect(),mt=q.getBoundingClientRect();et.width===0&&et.height===0||an(et.left-mt.left)};return document.addEventListener("selectionchange",E),()=>document.removeEventListener("selectionchange",E)},[]),p.useEffect(()=>{if(!ae)return;const E=q=>{q.target instanceof Element&&q.target.closest("[data-add-image-menu]")||(Rc(),_e(!1))};return window.addEventListener("mousedown",E,{capture:!0}),window.addEventListener("touchstart",E,{capture:!0}),()=>{window.removeEventListener("mousedown",E,{capture:!0}),window.removeEventListener("touchstart",E,{capture:!0})}},[ae]),p.useEffect(()=>{const E=q=>{const ce=q.target;ce&&document.activeElement instanceof HTMLElement&&document.activeElement.closest("[data-input-bar]")&&(ce.closest("[data-input-bar]")||document.activeElement.blur())};return document.addEventListener("mousedown",E,!0),()=>{document.removeEventListener("mousedown",E,!0)}},[]),p.useEffect(()=>{Ds()},[n.length,!!we,xt,Ds]),p.useEffect(()=>(window.addEventListener("resize",Ds),()=>window.removeEventListener("resize",Ds)),[Ds]),p.useEffect(()=>{const E=Le.current;if(!E)return;const q=je=>{gt.current={startY:je.touches[0].clientY,moved:!1}},ce=je=>{const et=je.touches[0].clientY-gt.current.startY;Math.abs(et)>10&&(gt.current.moved=!0),et>30&&X(!0),et<-30&&X(!1)},Ie=()=>{gt.current.moved&&(Ut.current=Date.now()+500)};return E.addEventListener("touchstart",q,{passive:!0}),E.addEventListener("touchmove",ce,{passive:!0}),E.addEventListener("touchend",Ie),()=>{E.removeEventListener("touchstart",q),E.removeEventListener("touchmove",ce),E.removeEventListener("touchend",Ie)}},[]);const wv="px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200",kv=E=>{var je;const q=(je=document.elementFromPoint(E.clientX,E.clientY))==null?void 0:je.closest("[data-input-image-index]");if(!q)return null;const ce=Number(q.dataset.inputImageIndex);if(!Number.isInteger(ce))return null;const Ie=ru(q);return Ie?E.clientX<Ie.left+Ie.width/2?ce:ce+1:null},Iv=E=>Math.max(at?1:0,Math.min(n.length,E)),Cv=E=>{if(!at)return!1;const q=document.querySelector('[data-input-image-index="0"]');if(!q)return!1;const ce=ru(q);return ce?E<ce.left+ce.width/2:!1},ml=()=>{var E;Pt(null),Ht(null),jr.current=null,Ft.current=null,rr.current={index:null,startX:0,startY:0,moved:!1},tr(null),(E=Sr.current)==null||E.remove(),Sr.current=null,fl()};p.useEffect(()=>{if(!nt)return;const E=document.body.style.overflow,q=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",()=>{document.body.style.overflow=E,document.body.style.overscrollBehavior=q}},[nt]);const jv=E=>{const q=E.dataTransfer.getData("text/plain"),ce=Number(q);return Number.isInteger(ce)?ce:null},Hg=(E,q)=>{const ce=jr.current;if(ce!==null&&at&&(E===0||q!=null&&Cv(q))){xv(at.id),Ft.current=null,Ht(null);return}ce!==null&&fl();const Ie=E==null?null:Iv(E),et=ce!==null&&Ie!==null&&(Ie===ce||Ie===ce+1)?null:Ie;Ft.current=et,Ht(et)},Sv=(E,q)=>{const ce=(we==null?void 0:we.targetImageId)===E.id,Ie=Ya(e,q).length,je=ce?"遮罩图必须为第一张图":"",et=ce&&xt?xt:E.dataUrl,mt=tt===q,Fn=q===n.length-1,Sn=Ct===q&&tt!==q,Et=Ct===n.length&&Fn&&tt!==q,pr=bt=>{if(ce){$g(E.id),bt.preventDefault();return}fl(),jr.current=q,Pt(q),bt.dataTransfer.effectAllowed="move",bt.dataTransfer.setData("text/plain",String(q));const yt=document.createElement("div");yt.style.cssText="position:fixed;left:-1000px;top:-1000px;width:52px;height:52px;border-radius:12px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.25);";const Lt=document.createElement("img");Lt.src=et,Lt.style.cssText="width:52px;height:52px;object-fit:cover;display:block;",yt.appendChild(Lt),document.body.appendChild(yt),Sr.current=yt,bt.dataTransfer.setDragImage(yt,26,26)},ln=bt=>{bt.preventDefault(),bt.dataTransfer.dropEffect="move";const yt=jr.current;if(yt===null||yt===q)return;const Lt=ru(bt.currentTarget);Lt&&Hg(bt.clientX<Lt.left+Lt.width/2?q:q+1,bt.clientX)},Ls=bt=>{bt.preventDefault();const yt=jr.current??jv(bt),Lt=Ft.current;yt!==null&&Lt!==null&&We(yt,Lt),ml()},cn=bt=>{if(ce){const Lt=bt.touches[0];rr.current={index:q,startX:Lt.clientX,startY:Lt.clientY,moved:!1};return}const yt=bt.touches[0];jr.current=q,rr.current={index:q,startX:yt.clientX,startY:yt.clientY,moved:!1},tr(null)},Fd=bt=>{const yt=bt.touches[0],Lt=rr.current;if(Lt.index===null)return;if(ce){(Math.abs(yt.clientX-Lt.startX)>6||Math.abs(yt.clientY-Lt.startY)>6)&&(bt.preventDefault(),$g(E.id));return}Lt.moved=!0,vo(),rt(null),Jt.current=!0,bt.preventDefault(),Pt(Lt.index),tr({src:et,x:yt.clientX,y:yt.clientY});const Ca=kv(yt);Hg(Ca,yt.clientX)},Pv=bt=>{const yt=rr.current;vo(),yt.index!==null&&Ft.current!==null&&(bt.preventDefault(),We(yt.index,Ft.current),window.setTimeout(()=>{Jt.current=!1},0)),ml(),Fg()},Tv=()=>{Jt.current=!1,Fg(),ml()};return s.jsxs("div",{"data-input-image-index":q,className:`relative group inline-block h-[52px] w-[52px] shrink-0 self-start transition-opacity ${mt?"opacity-40":""}`,style:{touchAction:ce?"auto":"none"},draggable:!It,onMouseLeave:fl,onDragStart:pr,onDragOver:ln,onDrop:Ls,onDragEnd:ml,onTouchStart:cn,onTouchMove:Fd,onTouchEnd:Pv,onTouchCancel:Tv,onContextMenu:bt=>{bt.preventDefault();const yt=Ee.current,Lt=gr(e).length,Ca=w.getState().promptSelection,hl=(Ca==null?void 0:Ca.prompt)===e?Ca:{start:Lt,end:Lt};if(yt&&(yt.focus(),Q0(yt,hl.start,hl.end),document.execCommand("insertHTML",!1,su(zo(q))))){Ms();return}const qg=mm(e,hl.start,hl.end,q);cr.current=!1,r(qg.prompt),window.setTimeout(()=>{Ee.current&&(Ee.current.focus(),Al(Ee.current,qg.cursor))},0)},children:[s.jsx(Mr,{visible:ct===E.id&&!!je&&(!It||ce),text:je}),Sn&&s.jsx("div",{className:"absolute -left-[5px] top-0 bottom-0 w-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),Et&&s.jsx("div",{className:"absolute -right-[5px] top-0 bottom-0 w-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),s.jsxs("div",{className:`relative w-[52px] h-[52px] rounded-xl overflow-hidden shadow-sm cursor-grab active:cursor-grabbing select-none ${ce||Ie>0?"border-2 border-blue-500":"border border-gray-200 dark:border-white/[0.08]"}`,onClick:()=>{Jt.current||y(E.id,n.map(bt=>bt.id),e)},children:[et&&s.jsx("div",{className:"h-full w-full overflow-hidden",children:s.jsx("img",{src:et,className:"w-full h-full object-cover hover:opacity-90 transition-opacity pointer-events-none",alt:""})}),ce&&s.jsx("span",{className:"absolute left-1 top-1 rounded bg-blue-500/90 px-1.5 py-0.5 text-[8px] leading-none text-white font-bold tracking-wider backdrop-blur-sm z-10 pointer-events-none",children:"MASK"}),Ie>0&&s.jsx(Ng,{count:Ie,className:ce?"left-1 top-[18px]":"left-1 top-1"}),s.jsx("span",{className:"absolute bottom-1 left-1 flex h-4 w-4 items-center justify-center rounded-full bg-black/55 text-[9px] font-semibold text-white backdrop-blur-sm z-10 pointer-events-none",children:q+1}),s.jsx("button",{className:"absolute inset-0 w-full h-full bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center cursor-pointer z-20 focus:outline-none border-none",onClick:bt=>{bt.stopPropagation(),y(E.id,n.map(yt=>yt.id),e)},title:"查看","aria-label":"查看参考图",children:s.jsxs("svg",{className:"w-5 h-5 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.25 12s3.5-6 9.75-6 9.75 6 9.75 6-3.5 6-9.75 6S2.25 12 2.25 12z"}),s.jsx("circle",{cx:"12",cy:"12",r:"2.75",strokeWidth:2})]})})]}),!ce&&s.jsx("span",{className:"absolute right-0 top-0 flex h-5 w-5 translate-x-1/2 -translate-y-1/2 cursor-pointer items-center justify-center rounded-full bg-red-500 text-white opacity-0 shadow-md transition-opacity hover:bg-red-600 group-hover:opacity-100 z-30",onClick:bt=>{bt.stopPropagation(),i(q)},children:s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M6 18L18 6M6 6l12 12"})})})]},E.id)},Yg=E=>s.jsxs("div",{"data-add-image-menu":!0,className:"relative flex-shrink-0",onMouseEnter:()=>vt(!0),onMouseLeave:()=>vt(!1),children:[!E&&s.jsx(Mr,{visible:He&&!ae,text:ul}),s.jsx("button",{onClick:()=>{Ia||(vt(!1),_e(!ae))},className:`p-2.5 rounded-xl transition-all shadow-sm ${Ia?"bg-gray-200 dark:bg-white/[0.04] text-gray-300 dark:text-gray-500 cursor-not-allowed":"bg-gray-200 dark:bg-white/[0.06] hover:bg-gray-300 dark:hover:bg-white/[0.1] text-gray-500 dark:text-gray-300 hover:shadow"}`,"aria-label":ul,"aria-expanded":ae,children:s.jsx("svg",{className:`w-5 h-5 transition-transform duration-200 ${ae?"rotate-45":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}),ae&&s.jsxs("div",{className:`absolute bottom-full ${E?"left-0":"right-0"} mb-2 w-32 bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-100 dark:border-gray-700 overflow-hidden z-50 animate-in fade-in slide-in-from-bottom-2 duration-200`,children:[E&&s.jsxs("button",{className:"w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",onClick:()=>{var q;_e(!1),(q=Fe.current)==null||q.click()},children:[s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"}),s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 13a3 3 0 11-6 0 3 3 0 016 0z"})]}),"拍照"]}),s.jsxs("button",{className:"w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",onClick:()=>{var q;_e(!1),(q=Ne.current)==null||q.click()},children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"})}),"上传图片"]}),s.jsxs("button",{className:"w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",onClick:()=>{_e(!1),wt(!0)},children:[s.jsx(ma,{className:"w-4 h-4"}),"添加链接"]}),s.jsxs("button",{className:"w-full px-4 py-3 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",onClick:()=>{_e(!1),o({baseImageSrc:null})},children:[s.jsx(hS,{className:"w-4 h-4"}),"画板"]})]})]}),Nv=()=>s.jsxs("button",{onClick:()=>I({title:at?"清空全部输入图":"清空参考图",message:at?`确定要清空遮罩主图、${hr.length} 张参考图和当前遮罩吗?`:`确定要清空全部 ${n.length} 张参考图吗?`,action:()=>l()}),className:"w-[52px] h-[52px] rounded-xl border border-dashed border-gray-300 dark:border-white/[0.08] flex flex-col items-center justify-center gap-0.5 text-gray-400 dark:text-gray-500 hover:text-red-600 hover:border-red-300 hover:bg-red-500/[0.1] dark:hover:bg-red-500/[0.16] transition-all cursor-pointer flex-shrink-0",title:at?"清空遮罩主图、参考图和遮罩":"清空全部参考图",children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),s.jsx("span",{className:"text-[8px] leading-none",children:at?"清空全部":"清空"})]}),Vg=()=>s.jsxs("div",{ref:Xe,className:"sm:[contain:inline-size]",children:[s.jsxs("div",{className:"grid grid-cols-[repeat(auto-fill,52px)] justify-between gap-x-2 gap-y-3 mb-3",children:[n.map((E,q)=>Sv(E,q)),Nv()]}),(nt==null?void 0:nt.src)&&lr.createPortal(s.jsx("div",{className:"fixed z-[140] h-[52px] w-[52px] overflow-hidden rounded-xl shadow-xl pointer-events-none opacity-90",style:{left:nt.x,top:nt.y,transform:"translate(-50%, -50%)"},children:s.jsx("img",{src:nt.src,className:"h-full w-full object-cover",alt:""})}),document.body)]}),Kg=()=>s.jsx(z4,{params:c,setParams:u,activeProfile:ft,modelOptions:Ps,onModelChange:mo,isFalProvider:Un,isFalTextToImage:Es,displaySize:_d,qualityOptions:Dd,selectClass:wv,transparentOutputAvailable:bo,showTransparentOutputControl:il,transparentOutputEnabled:Md,transparentOutputHint:yo,onTransparentOutputMenuOpenChange:M,compressionHint:ye,compressionDisabled:ll,outputCompressionInput:z,setOutputCompressionInput:ee,commitOutputCompression:dv,moderationHint:Re,moderationDisabled:xo,agentAutoImageCount:$t,outputImageLimit:on,nInput:re,setNInputFocused:dt,commitN:uv,handleNInputChange:hv,handleNLimitIncreaseAttempt:pv,showAgentNHint:fv,hideNLimitHint:Ud,startAgentNHintTouch:mv,clearAgentNHintTouchTimer:gv,nLimitHint:st,nLimitHintText:Rd,streamConcurrentByN:dl,streamConcurrentHint:Gt,sizeHint:Se,qualityHint:ot,onOpenSizePicker:()=>ve(!0),showBatch:Td,batchEnabled:cs,batchMode:g.batchPromptMode,batchConcurrencyLimited:g.batchPromptConcurrencyLimited,batchConcurrency:g.batchPromptConcurrency,batchPromptCount:po,batchProgress:d,onBatchChange:f,onStopBatch:Dj}),Xg=B&&A.length>0,Av=!Xg&&S.length>0;return s.jsxs(s.Fragment,{children:[s.jsx(B4,{visible:Pe,atImageLimit:Ia,maxImages:yr}),Ye&&s.jsx(O4,{onClose:()=>wt(!1)}),me&&s.jsx(L4,{currentSize:Es&&c.size==="auto"?Ou:c.size,onSelect:E=>u({size:E}),onClose:()=>ve(!1),allowAuto:!Es,codexCli:ft.codexCli}),s.jsxs("div",{"data-input-bar":!0,className:`fixed bottom-4 sm:bottom-6 left-[calc((100%-var(--page-scrollbar-width))/2)] -translate-x-1/2 z-30 w-[calc(100%-var(--page-scrollbar-width))] max-w-4xl sm:w-max sm:min-w-[min(56rem,calc(100%-var(--page-scrollbar-width)))] sm:max-w-[min(80rem,calc(100%-var(--page-scrollbar-width)))] px-3 sm:px-4 transition-all duration-300${fe?" flex flex-col":""}`,style:fe?{top:`${Z}px`,transitionProperty:"none"}:void 0,children:[s.jsx("div",{className:"sm:[contain:inline-size]",children:s.jsx(U4,{showFavoriteCollectionBatchBar:Xg,showTaskBatchBar:Av,selectedTaskIds:S,tasks:T,clearFavoriteCollectionSelection:C,onSelectAllVisibleFavoriteCollections:se,onInvertVisibleFavoriteCollections:Y,onDownloadSelectedFavoriteCollections:ue,onDeleteSelectedFavoriteCollections:ke,clearSelection:j,onSelectAllVisibleTasks:L,onInvertVisibleTasks:G,onToggleFavorite:K?void 0:le,onDownloadSelected:D,onDeleteSelected:ie})}),s.jsxs("div",{ref:Ge,className:`bg-white/70 dark:bg-gray-900/70 backdrop-blur-2xl border border-white/50 dark:border-white/[0.08] shadow-[0_8px_30px_rgb(0,0,0,0.08)] dark:shadow-[0_8px_30px_rgb(0,0,0,0.3)] rounded-2xl sm:rounded-3xl p-3 sm:p-4 ring-1 ring-black/5 dark:ring-white/10${fe?" flex min-h-0 flex-1 flex-col":""}`,children:[s.jsx("div",{ref:Le,className:fe?"hidden":"sm:hidden flex justify-center pt-0.5 pb-2 -mt-1 cursor-pointer touch-none",onClick:()=>{if(Date.now()<Ut.current){Ut.current=0;return}X(E=>!E)},children:s.jsx("div",{className:`w-10 h-1 rounded-full bg-gray-300 dark:bg-white/[0.06] transition-transform duration-200 ${V?"scale-x-75":""}`})}),n.length>0&&(It?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`collapse-section${V?" collapsed":""}`,children:s.jsx("div",{className:"collapse-inner",children:Vg()})}),V&&s.jsx("div",{className:"text-xs text-gray-400 dark:text-gray-500 mb-2 ml-1",children:we?`1 张遮罩主图 · ${hr.length} 张参考图`:`${n.length} 张参考图`})]}):Vg()),s.jsxs("div",{className:`relative grid sm:[contain:inline-size]${fe?" min-h-0 flex-1":""}`,children:[Bg&&s.jsxs("div",{style:{left:`${Ar}px`},className:"absolute bottom-full z-50 mb-2 w-64 overflow-hidden rounded-2xl border border-transparent bg-white/95 p-1.5 shadow-xl ring-1 ring-black/5 backdrop-blur-xl dark:bg-gray-800/95 dark:ring-white/[0.06]",children:[s.jsx("div",{className:"px-2 pb-1 pt-0.5 text-[11px] text-gray-400 dark:text-gray-500",children:"选择图片引用"}),s.jsx("div",{className:"max-h-56 overflow-y-auto custom-scrollbar",children:Rs.map((E,q)=>s.jsxs("button",{type:"button",onMouseDown:ce=>{ce.preventDefault(),Ug(E)},onMouseEnter:()=>Tt(q),className:`flex w-full items-center gap-2 rounded-xl px-2 py-1.5 text-left text-xs transition-colors ${q===Dt?"bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-300":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-white/[0.06]"}`,children:[s.jsx(V4,{option:E}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:E.label}),E.type==="agent-output"&&s.jsx("span",{className:"shrink-0 rounded bg-gray-100 px-1.5 py-0.5 text-[10px] text-gray-500 dark:bg-white/[0.06] dark:text-gray-400",children:"历史"})]},E.key))})]}),s.jsx("div",{ref:Ee,contentEditable:!0,suppressContentEditableWarning:!0,onInput:E=>{cr.current=!0;const q=E.currentTarget,ce=Na(q);Nr(ce.start),Us(q);const Ie=G0(q);r(Ie),Tt(0),Or(!1)},onSelect:E=>{const q=E.currentTarget,ce=Na(q);Nr(ce.start),Us(q),Tt(0),Or(!1)},onKeyDown:bv,onCompositionStart:()=>{jn.current=!0},onCompositionEnd:()=>{jn.current=!1},onPaste:yv,onCopy:vv,onClick:E=>{const q=Ee.current;if(!q)return;const ce=E.target;if(ce.classList.contains("mention-tag")){const Ie=window.getSelection();if(Ie){const je=document.createRange();je.selectNode(ce),Ie.removeAllRanges(),Ie.addRange(je),Us(q)}return}Us(q)},"aria-label":al,className:`col-start-1 row-start-1 min-h-[42px] w-full overflow-hidden ios-rounded-scroll-fix whitespace-pre-wrap break-words rounded-2xl border border-gray-200/60 bg-white/50 pl-4 pr-10 py-3 text-sm leading-relaxed shadow-sm outline-none transition-[border-color,box-shadow] duration-200 focus:ring-1 focus:ring-blue-300/40 dark:border-white/[0.08] dark:bg-white/[0.03] dark:text-gray-100 dark:focus:ring-blue-500/30${fe?" !h-full !overflow-y-auto":""}`}),e.length===0&&s.jsx("div",{className:`prompt-placeholder col-start-1 row-start-1 pointer-events-none pl-4 pr-10 py-3 text-sm leading-relaxed text-gray-400 dark:text-gray-500${It&&V?" truncate":""}`,children:al}),e.length>0&&s.jsxs("div",{className:`absolute z-10 ${ge?"right-3 top-1/2 -translate-y-1/2":"right-3 top-3"}`,onMouseEnter:()=>Oe(!0),onMouseLeave:()=>Oe(!1),children:[s.jsx(Mr,{visible:Be,text:"清空文本"}),s.jsx("button",{type:"button",onClick:()=>{Oe(!1),cv()},className:"flex items-center justify-center rounded-full p-1 text-gray-400 transition-all duration-200 hover:bg-gray-100 hover:text-gray-600 focus:outline-none dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":"清空文本",children:s.jsx(qt,{className:"w-3.5 h-3.5"})})]}),oe&&s.jsxs("div",{className:"absolute bottom-2.5 right-2.5 z-10",onMouseEnter:()=>lt(!0),onMouseLeave:()=>lt(!1),children:[s.jsx(Mr,{visible:Ue,text:fe?"恢复输入框":"展开输入框"}),s.jsx("button",{type:"button",onClick:()=>{lt(!1),be(E=>!E),X(!1)},className:"flex items-center justify-center rounded-md p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 focus:outline-none dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":fe?"恢复输入框":"展开输入框","aria-pressed":fe,children:fe?s.jsx(sS,{className:"h-4 w-4"}):s.jsx(nS,{className:"h-4 w-4"})})]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"hidden sm:flex items-center justify-between gap-3",children:[Kg(),s.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[Yg(!1),s.jsxs("div",{className:"relative",onMouseEnter:()=>Ve(!0),onMouseLeave:()=>Ve(!1),children:[s.jsx(Mr,{visible:(dr||!Br||ls)&&ut,text:sl}),s.jsx("button",{onClick:()=>dr?ol():Br?ka():h(!0),disabled:dr?!1:Br?!Ts:!1,className:`p-2.5 rounded-xl transition-all shadow-sm hover:shadow ${dr?"bg-red-500 text-white hover:bg-red-600":Br?"bg-blue-500 text-white hover:bg-blue-600 disabled:bg-gray-300 dark:disabled:bg-white/[0.04] disabled:opacity-50 disabled:cursor-not-allowed":"bg-gray-300 dark:bg-white/[0.06] text-white cursor-pointer"}`,"aria-label":nl,children:dr?s.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 24 24",children:s.jsx("rect",{x:"7",y:"7",width:"10",height:"10",rx:"1.5"})}):s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 7l5 5m0 0l-5 5m5-5H6"})})})]})]})]}),s.jsxs("div",{className:"sm:hidden flex flex-col gap-2",children:[s.jsx("div",{className:`collapse-section${V?" collapsed":""}`,children:s.jsxs("div",{className:"collapse-inner",children:[Kg(),s.jsx("div",{className:"h-2"})]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[Yg(!0),s.jsxs("div",{className:"relative flex-1",onMouseEnter:()=>Ve(!0),onMouseLeave:()=>Ve(!1),children:[s.jsx(Mr,{visible:(dr||!Br||ls)&&ut,text:sl}),s.jsxs("button",{onClick:()=>dr?ol():Br?ka():h(!0),disabled:dr?!1:Br?!Ts:!1,"aria-label":nl,className:`w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-medium transition-all shadow-sm ${dr?"bg-red-500 text-white hover:bg-red-600":Br?"bg-blue-500 text-white hover:bg-blue-600 disabled:bg-gray-300 dark:disabled:bg-white/[0.04] disabled:opacity-50 disabled:cursor-not-allowed":"bg-gray-300 dark:bg-white/[0.06] text-white cursor-pointer"}`,children:[dr?s.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 24 24",children:s.jsx("rect",{x:"7",y:"7",width:"10",height:"10",rx:"1.5"})}):s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 7l5 5m0 0l-5 5m5-5H6"})}),dr?"停止生成":we?"遮罩编辑":cs?`批量生成 ${po} 条`:"生成图像"]})]})]})]})]}),s.jsx("input",{ref:Ne,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Wg}),s.jsx("input",{ref:Fe,type:"file",accept:"image/*",capture:"environment",className:"hidden",onChange:Wg})]})]})]})}function X4(){var Xr,Mt,os,Nr,Ar,an;const e=w(oe=>oe.tasks),t=w(oe=>oe.detailTaskId),r=w(oe=>oe.setDetailTaskId),n=w(oe=>oe.setLightboxImageId),a=w(oe=>oe.setConfirmDialog),o=w(oe=>oe.showToast),i=w(oe=>oe.openFavoritePicker),l=w(oe=>!!oe.privacyMode),c=w(oe=>oe.settings),u=w(oe=>oe.dismissedCodexCliPrompts),f=w(oe=>t&&oe.streamPreviews[t]||""),d=w(oe=>t?oe.streamPreviewSlots[t]:void 0),[g,m]=p.useState(0),[x,b]=p.useState({}),[h,y]=p.useState({}),[v,I]=p.useState({}),[S,k]=p.useState({}),[j,A]=p.useState(""),[N,C]=p.useState(Date.now()),[T,R]=p.useState(!1),[U,W]=p.useState(!1),[F,_]=p.useState(!1),O=p.useRef(null),J=p.useRef(null),H=p.useRef(null),K=p.useRef(!1),te=p.useRef(!1),P=Ot(),B=Ot(),$=Ot(),Q=Ot(),L=Ot(),G=Ot(),se=Ot(),Y=Ot(),le=Ot(),ie=()=>{const oe=window.getSelection();oe&&!oe.isCollapsed&&oe.removeAllRanges()},D=p.useMemo(()=>e.find(oe=>oe.id===t)??null,[e,t]),ue=p.useMemo(()=>{const oe=d?Object.entries(d).filter(([,z])=>!!z).sort(([z],[ee])=>Number(z)-Number(ee)):[],Te=Math.max((D==null?void 0:D.status)==="running"?D.params.n:0,oe.length?Math.max(...oe.map(([z])=>Number(z)+1)):0,f?1:0),Qe=new Map(oe.map(([z,ee])=>[Number(z),ee]));return Array.from({length:Te},(z,ee)=>({key:String(ee),src:Qe.get(ee)??(ee===0?f:"")}))},[D==null?void 0:D.params.n,D==null?void 0:D.status,d,f]),ke=((Xr=ue[g])==null?void 0:Xr.src)||"";p.useEffect(()=>{_(!1)},[ke,t,g]),p.useEffect(()=>{var Te;const oe=(D==null?void 0:D.status)==="running"?ue.length:D?(Te=D.outputErrors)!=null&&Te.length?Math.max(D.params.n,D.outputImages.length+D.outputErrors.length):D.outputImages.length:0;oe>0&&g>=oe&&m(oe-1)},[g,ue.length,D,D==null?void 0:D.status]),Kr(!!D,()=>r(null)),Lr(!!D,[O,J,H]),p.useEffect(()=>{m(0)},[t]),p.useEffect(()=>{if((D==null?void 0:D.status)!=="running"&&!((D==null?void 0:D.status)==="error"&&(D.falRecoverable||D.customRecoverable)))return;const oe=window.setInterval(()=>C(Date.now()),1e3);return C(Date.now()),()=>window.clearInterval(oe)},[D==null?void 0:D.customRecoverable,D==null?void 0:D.falRecoverable,D==null?void 0:D.status]),p.useEffect(()=>{if(!D){b({}),y({}),I({}),k({});return}let oe=!1;const Te=[...new Set([...D.inputImageIds||[],...D.maskImageId?[D.maskImageId]:[]])],Qe={};for(const z of Te){const ee=En(z);ee&&(Qe[z]=ee)}b(Qe);for(const z of Te)Qe[z]||kt(z).then(ee=>{!oe&&ee&&b(re=>({...re,[z]:ee}))});return()=>{oe=!0}},[D]);const we=(D==null?void 0:D.maskTargetImageId)||null,We=we&&x[we]||"",Ne=D!=null&&D.maskImageId&&x[D.maskImageId]||"",Fe=(D==null?void 0:D.inputImageIds)??[],Ee=p.useMemo(()=>{if(!D)return[];const oe=D.outputErrors??[];if(oe.length===0)return D.outputImages.map((ee,re)=>({requestIndex:re,outputImageIndex:re,imageId:ee,error:""}));const Te=new Map(oe.map(ee=>[ee.requestIndex,ee.error])),Qe=Math.max(D.params.n,D.outputImages.length+oe.length);let z=0;return Array.from({length:Qe},(ee,re)=>{const Ae=Te.get(re);if(Ae)return{requestIndex:re,outputImageIndex:-1,imageId:"",error:Ae};const $e=D.outputImages[z]??"",dt={requestIndex:re,outputImageIndex:z,imageId:$e,error:""};return z+=1,dt})},[D]),Ge=Ee[g],Xe=(Ge==null?void 0:Ge.imageId)||"",ht=(Ge==null?void 0:Ge.outputImageIndex)??-1,Pe=(Ge==null?void 0:Ge.error)||"",ne=ht>=0&&((Mt=D==null?void 0:D.transparentOriginalImages)==null?void 0:Mt[ht])||"",ge=Xe&&h[Xe]||"";if(p.useEffect(()=>{const oe=(D==null?void 0:D.outputImages)??[];if(oe.length===0){y({});return}let Te=!1;const Qe=(z,ee)=>{Te||y(re=>({...re,[z]:ee}))};for(const z of oe){const ee=En(z);ee?Qe(z,ee):kt(z).then(re=>{re&&Qe(z,re)}).catch(()=>{})}return()=>{Te=!0}},[D==null?void 0:D.outputImages]),p.useEffect(()=>{let oe=!1;if(A(""),!(!We||!Ne))return rd(We,Ne).then(Te=>{oe||A(Te)}).catch(()=>{oe||A("")}),()=>{oe=!0}},[We,Ne]),!D)return null;const xe=D.sourceMode==="agent"||!!(D.agentConversationId||D.agentRoundId),fe=xy(D),be=D.status==="done"&&String(D.agentToolAction??"").toLowerCase()==="edit",Z=Fe.length>0||be,de=Ee.length,he=Xe?v[Xe]:"",pe=Xe?S[Xe]:"",Be=Xe?((os=D.actualParamsByImage)==null?void 0:os[Xe])??D.actualParams:D.actualParams,Oe=Be!=null&&Be.size||!pe?Be:{...Be??{},size:pe.replace("×","x")},Ue=Xe?(Ar=(Nr=D.revisedPromptByImage)==null?void 0:Nr[Xe])==null?void 0:Ar.trim():"",lt=D.transparentOutput&&D.transparentPrompt?D.transparentPrompt:D.prompt,ut=$i(lt,D.inputImageIds.length).trim(),Ve=!!(Ue&&Ue!==ut),He=kb(c),vt=c.codexCli||u.includes(He),ct=D.apiProvider,V=!!((ct??"openai")==="openai"&&D.apiMode==="responses"&&Xe&&(!Ue||Ve)&&!vt),X=ct?Ys(c,ct):"未知",me=D.apiProfileName||"未知",ve=D.apiModel||"未知",ae=!!(D.apiProvider||D.apiProfileName||D.apiModel),_e=D.status==="error"&&D.falRecoverable,Ye=D.status==="error"&&D.customRecoverable,wt=D.rawImageUrls??[],xt=ue.length,qe=ke,tt=D.streamPartialImageIds??[],Pt=D.params.output_format==="png"||D.params.output_format==="webp",Ct=D.transparentOutput||D.params.transparent_output?"true":"false",Ht=!!(Xe&&D.transparentOutput&&((an=D.transparentOriginalImages)==null?void 0:an[ht])===""),Dt=D.params.output_compression==null?"未设置":String(D.params.output_compression),Tt=oe=>oe?new Date(oe).toLocaleString("zh-CN"):"",Ce=()=>{if(D.status==="running"||_e||Ye){const z=Math.max(0,Math.floor((N-(D.startedAt??D.createdAt))/1e3)),ee=String(Math.floor(z/60)).padStart(2,"0"),re=String(z%60).padStart(2,"0");return`${ee}:${re}`}if(D.elapsed==null)return null;const oe=Math.floor(D.elapsed/1e3),Te=String(Math.floor(oe/60)).padStart(2,"0"),Qe=String(oe%60).padStart(2,"0");return`${Te}:${Qe}`},Or=()=>{yg(D),r(null)},nt=()=>{vg(D),r(null)},tr=()=>{r(null),a({title:"删除任务",message:"确定要删除这个任务吗?关联的图片资源也会被清理(如果没有其他任务引用)。",action:()=>wg(D)})},Le=()=>{i([D.id])},gt=async()=>{const oe=D.error||"生成失败";try{await fn(oe),o("完整报错已复制","success")}catch(Te){o($r("复制报错失败",Te),"error")}},Ut=async()=>{if(D.prompt)try{await fn(ai(D.prompt,D.inputImageIds.length)),o("提示词已复制","success")}catch(oe){o($r("复制提示词失败",oe),"error")}},jr=()=>{Gu(!0,Ue?"接口返回的提示词已被改写":"接口没有返回官方 API 会返回的部分信息")},rr=async()=>{const oe=Fe[0],Te=oe?x[oe]:"";if(Te)try{await yy(Te),o("参考图已复制","success")}catch(Qe){console.error(Qe),o($r("复制参考图失败",Qe),"error")}},Ft=async oe=>{if(oe.stopPropagation(),!(!Xe||!D))try{const Te=await Xn([Xe],`task-${D.id}`);if(Te.canceled)return;Te.successCount===0?o(Zt(Te.error),"error"):o(Kn("下载成功",Te.location),"success")}catch(Te){console.error(Te),o(Zt(Te),"error")}},Sr=async oe=>{if(oe.stopPropagation(),!(!ne||!D))try{const Te=await Xn([ne],`task-${D.id}-orig`);if(Te.canceled)return;Te.successCount===0?o(Zt(Te.error),"error"):o(Kn("原图下载成功",Te.location),"success")}catch(Te){console.error(Te),o(Zt(Te),"error")}},Jt=async oe=>{var Te;if(oe.stopPropagation(),!!((Te=D==null?void 0:D.outputImages)!=null&&Te.length))try{const Qe=`task-${D.id}`,z=c.zipDownloadRoutes.includes("task-detail-all")?await so(Ni(D.outputImages,Qe),Qe):await Xn(D.outputImages,Qe);if(z.canceled)return;z.successCount===0?o(Zt(z.error),"error"):z.failCount>0?o(`部分下载失败:成功 ${z.successCount},失败 ${z.failCount}`,"error"):o(Kn(z.successCount>1?`下载成功:${z.successCount} 张图片`:"下载成功",z.location),"success")}catch(Qe){console.error(Qe),o(Zt(Qe),"error")}},cr=async()=>{if(!(!D||!tt.length))try{const oe=`task-${D.id}-partial`,Te=c.zipDownloadRoutes.includes("task-detail-partial")?await so(Ni(tt,oe),oe):await Xn(tt,oe);if(Te.canceled)return;Te.successCount===0?o(Zt(Te.error),"error"):Te.failCount>0?o(`部分下载失败:成功 ${Te.successCount},失败 ${Te.failCount}`,"error"):o(Kn(`下载成功:${Te.successCount} 张中间步骤图`,Te.location),"success")}catch(oe){console.error(oe),o(Zt(oe),"error")}},jn=()=>{Eb(D),r(null)};return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-50 flex items-center justify-center p-4",onClick:()=>r(null),children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{ref:O,className:"relative bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] rounded-3xl shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col md:flex-row z-10 ring-1 ring-black/5 dark:ring-white/10 animate-modal-in",onClick:oe=>oe.stopPropagation(),children:[s.jsx("div",{className:"flex h-14 items-center justify-end px-4 md:hidden",children:s.jsx("button",{onClick:()=>r(null),className:"p-1 rounded-full hover:bg-gray-100 dark:hover:bg-white/[0.06] transition text-gray-400","aria-label":"关闭",children:s.jsx(qt,{className:"w-6 h-6"})})}),s.jsxs("div",{className:"md:w-1/2 w-full h-64 md:h-auto bg-gray-100 dark:bg-black/20 relative flex items-center justify-center flex-shrink-0 min-h-[16rem]",children:[D.status==="done"&&de>0&&(Xe||D.outputImages.length>0)&&s.jsxs("div",{className:"absolute right-3 top-[15px] z-20 flex items-center gap-1.5",children:[Xe&&s.jsxs("div",{className:"relative group flex",children:[s.jsx("button",{type:"button",...se.handlers,onClick:oe=>{se.handlers.onClick(),Ft(oe)},className:"flex items-center justify-center px-1.5 py-0.5 bg-black/50 text-white rounded backdrop-blur-sm hover:bg-black/70 transition focus:outline-none focus:ring-1 focus:ring-white/50","aria-label":"下载图片",children:s.jsx(qs,{className:"h-4 w-4"})}),s.jsx(pt,{visible:se.visible,className:"whitespace-nowrap",children:"下载图片"})]}),D.outputImages.length>1&&s.jsxs("div",{className:"relative group flex",children:[s.jsxs("button",{type:"button",...le.handlers,onClick:oe=>{le.handlers.onClick(),Jt(oe)},className:"flex items-center justify-center pl-1.5 pr-2 py-0.5 gap-0.5 bg-black/50 text-white rounded backdrop-blur-sm hover:bg-black/70 transition focus:outline-none focus:ring-1 focus:ring-white/50","aria-label":"下载全部",children:[s.jsx(qs,{className:"h-4 w-4"}),s.jsx("span",{className:"text-[9px] font-bold leading-none mt-[1px]",children:"ALL"})]}),s.jsx(pt,{visible:le.visible,className:"whitespace-nowrap",children:"下载全部"})]})]}),D.status==="done"&&de>0&&ge&&s.jsxs(s.Fragment,{children:[s.jsx("img",{src:ge,"data-image-id":Xe,className:"saveable-image max-w-[calc(100%-2rem)] max-h-[calc(100%-2rem)] object-contain cursor-pointer",onLoad:oe=>{const Te=oe.currentTarget;Xe&&Te.naturalWidth>0&&Te.naturalHeight>0&&(I(Qe=>({...Qe,[Xe]:Zp(Te.naturalWidth,Te.naturalHeight)})),k(Qe=>({...Qe,[Xe]:`${Te.naturalWidth}×${Te.naturalHeight}`})))},onClick:()=>n(Xe,D.outputImages),alt:""}),s.jsx("div",{"data-selectable-text":!0,className:"absolute left-4 top-[15px] flex items-center gap-1.5",children:he&&pe?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"bg-black/50 text-white text-xs px-2 py-0.5 rounded backdrop-blur-sm font-mono",children:he}),s.jsx("span",{className:"bg-black/50 text-white/90 text-xs px-2 py-0.5 rounded backdrop-blur-sm font-medium",children:pe})]}):Ce()&&s.jsxs("span",{className:"flex items-center gap-1 bg-black/50 text-white text-xs px-2 py-0.5 rounded backdrop-blur-sm font-mono",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),Ce()]})}),de>1&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>m((g-1+de)%de),className:"absolute left-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("button",{onClick:()=>m((g+1)%de),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}),s.jsxs("span",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 bg-black/50 text-white text-xs px-2 py-0.5 rounded-full",children:[g+1," / ",de]})]}),ne&&s.jsxs("div",{className:"absolute bottom-4 right-4 z-20 flex",children:[s.jsxs("button",{type:"button",...Y.handlers,onClick:oe=>{Y.handlers.onClick(),Sr(oe)},className:"flex items-center justify-center gap-0.5 rounded bg-black/50 py-0.5 pl-1.5 pr-2 text-white backdrop-blur-sm transition hover:bg-black/70 focus:outline-none focus:ring-1 focus:ring-white/50","aria-label":"下载原图",children:[s.jsx(qs,{className:"h-4 w-4"}),s.jsx("span",{className:"text-[9px] font-bold leading-none mt-[1px] uppercase",children:"orig"})]}),s.jsx(pt,{visible:Y.visible,className:"whitespace-nowrap",children:"下载原图"})]})]}),D.status==="done"&&de>0&&Pe&&s.jsxs("div",{className:"w-full max-w-md px-4 text-center",children:[s.jsx("svg",{className:"w-10 h-10 text-red-400 mx-auto mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsxs("p",{className:"text-sm font-medium text-red-500",children:["第 ",Ge.requestIndex+1," 张生成失败"]}),s.jsx("p",{className:"mt-2 overflow-hidden whitespace-pre-line text-sm leading-6 text-red-500 break-words",style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:8},children:Pe}),de>1&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>m((g-1+de)%de),className:"absolute left-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("button",{onClick:()=>m((g+1)%de),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}),s.jsxs("span",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 bg-black/50 text-white text-xs px-2 py-0.5 rounded-full",children:[g+1," / ",de]})]})]}),(D.status==="running"||_e)&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"absolute left-4 top-4 flex items-center gap-1 bg-black/50 text-white text-xs px-2 py-0.5 rounded backdrop-blur-sm font-mono",children:[s.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),Ce()]}),D.status==="running"&&xt>0&&s.jsxs(s.Fragment,{children:[qe?s.jsx("img",{src:qe,className:`max-w-[calc(100%-2rem)] max-h-[calc(100%-2rem)] object-contain ${F?"":"hidden"}`,alt:"",onLoad:()=>_(!0),onError:()=>_(!1)}):null,(!qe||!F)&&s.jsxs("svg",{className:"w-10 h-10 text-blue-400 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),F&&s.jsx("span",{className:"absolute top-4 right-4 flex items-center gap-1 rounded bg-blue-500 px-2 py-0.5 text-xs font-medium text-white backdrop-blur-sm",children:"流式预览"}),xt>1&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>m((g-1+xt)%xt),className:"absolute left-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("button",{onClick:()=>m((g+1)%xt),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full bg-black/30 text-white hover:bg-black/50 transition",children:s.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}),s.jsxs("span",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 bg-black/50 text-white text-xs px-2 py-0.5 rounded-full",children:[g+1," / ",xt]})]})]}),D.status==="running"&&xt===0&&s.jsxs("svg",{className:"w-10 h-10 text-blue-400 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]})]}),D.status==="error"&&_e&&s.jsxs("div",{className:"w-full max-w-md px-4 text-center",children:[s.jsx("svg",{className:"w-10 h-10 text-yellow-400 mx-auto mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),s.jsx("p",{className:"text-sm font-medium text-yellow-500",children:"重连中"})]}),D.status==="error"&&!_e&&s.jsxs("div",{className:"w-full max-w-md px-4 text-center",children:[s.jsx("svg",{className:"w-10 h-10 text-red-400 mx-auto mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx("p",{className:"overflow-hidden whitespace-pre-line text-sm leading-6 text-red-500 break-words",style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:10},children:D.error||"生成失败"}),s.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...P.handlers,onClick:()=>{P.handlers.onClick(),gt()},className:"inline-flex items-center justify-center rounded-full border border-red-200/80 bg-white/80 px-3 py-1.5 text-red-500 transition hover:bg-red-500/[0.1] dark:border-red-400/20 dark:bg-white/[0.04] dark:hover:bg-red-500/[0.16]","aria-label":"复制完整报错",children:s.jsx(zr,{className:"h-4 w-4"})}),s.jsx(pt,{visible:P.visible,className:"whitespace-nowrap",children:"复制完整报错"})]}),D.rawResponsePayload&&s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...$.handlers,onClick:()=>{xr(),W(!0)},className:"inline-flex items-center justify-center rounded-full border border-purple-200/80 bg-purple-50 px-3 py-1.5 text-purple-600 transition hover:bg-purple-100 dark:border-purple-500/20 dark:bg-purple-500/10 dark:text-purple-400 dark:hover:bg-purple-500/20","aria-label":"查看原始响应",children:s.jsx(uy,{className:"h-4 w-4"})}),s.jsx(pt,{visible:$.visible,className:"whitespace-nowrap",children:"查看原始响应"})]}),D.rawImageUrls&&D.rawImageUrls.length>0&&s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...B.handlers,onClick:async()=>{if(D.rawImageUrls.length===1){B.handlers.onClick();try{await fn(D.rawImageUrls[0]),o("图片链接已复制","success")}catch(oe){o($r("复制链接失败",oe),"error")}}else xr(),R(!0)},className:"inline-flex items-center justify-center rounded-full border border-green-200/80 bg-green-50 px-3 py-1.5 text-green-600 transition hover:bg-green-100 dark:border-green-500/20 dark:bg-green-500/10 dark:text-green-400 dark:hover:bg-green-500/20","aria-label":"复制图片链接",children:s.jsx(ma,{className:"h-4 w-4"})}),s.jsx(pt,{visible:B.visible,className:"whitespace-nowrap",children:"复制图片链接"})]}),tt.length>0&&s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...Q.handlers,onClick:()=>{Q.handlers.onClick(),cr()},className:"inline-flex items-center justify-center rounded-full border border-amber-200/80 bg-amber-50 px-3 py-1.5 text-amber-600 transition hover:bg-amber-100 dark:border-amber-500/20 dark:bg-amber-500/10 dark:text-amber-400 dark:hover:bg-amber-500/20","aria-label":"下载中间步骤图",children:s.jsx(qs,{className:"h-4 w-4"})}),s.jsx(pt,{visible:Q.visible,className:"whitespace-nowrap",children:"下载中间步骤图"})]}),!Ye&&s.jsxs("div",{className:"relative group",children:[s.jsx("button",{type:"button",...L.handlers,onClick:()=>{L.handlers.onClick(),jn()},className:"inline-flex items-center justify-center rounded-full border border-blue-200/80 bg-white/80 px-3 py-1.5 text-blue-500 transition hover:bg-blue-50 dark:border-blue-400/20 dark:bg-white/[0.04] dark:hover:bg-blue-500/10","aria-label":"重试任务",children:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}),s.jsx(pt,{visible:L.visible,className:"whitespace-nowrap",children:"重试任务"})]})]})]})]}),s.jsxs("div",{className:"md:w-1/2 w-full p-5 overflow-y-auto overscroll-contain flex flex-col",children:[s.jsx("button",{onClick:()=>r(null),className:"absolute top-3 right-3 hidden p-1 rounded-full hover:bg-gray-100 dark:hover:bg-white/[0.06] transition text-gray-400 z-10 md:block","aria-label":"关闭",children:s.jsx(qt,{className:"w-5 h-5"})}),s.jsxs("div",{"data-selectable-text":!0,className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsx("h3",{className:"text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider",children:"输入内容"}),D.prompt&&!fe&&s.jsx("button",{onClick:Ut,className:"p-1 rounded text-gray-400 hover:bg-gray-100 dark:text-gray-500 dark:hover:bg-white/[0.06] transition",title:"复制提示词",children:s.jsx(zr,{className:"h-4 w-4"})}),V&&s.jsx("span",{className:"relative inline-flex",children:s.jsx("button",{type:"button",className:"p-1 rounded text-amber-500 hover:bg-amber-50 dark:text-yellow-300 dark:hover:bg-yellow-500/10 transition",onClick:jr,"aria-label":"提示词已被改写",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"})})})})]}),fe?s.jsxs("div",{className:"mb-4 leading-relaxed",children:[s.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:"正在生成……"}),s.jsx("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:"输入内容将在响应完成时接收"})]}):s.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300 leading-relaxed whitespace-pre-wrap mb-4",children:ai(D.prompt,D.inputImageIds.length)||"(无提示词)"}),Ve&&Ue&&s.jsx("div",{className:"mb-4",children:s.jsx(Js,{value:Ue,className:"max-w-full rounded px-2 py-1 text-left text-xs leading-relaxed whitespace-pre-wrap"})}),Z&&s.jsxs("div",{className:"mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsx("h3",{className:"text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider",children:"参考图"}),Fe.length>0&&s.jsx("button",{onClick:rr,className:"p-1 rounded text-gray-400 hover:bg-gray-100 dark:text-gray-500 dark:hover:bg-white/[0.06] transition",title:"复制参考图",children:s.jsx(zr,{className:"h-4 w-4"})})]}),Fe.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap",children:Fe.map((oe,Te)=>{const Qe=oe===we,z=Ya(D.prompt,Te).length,ee=Qe&&j?j:x[oe]||"";return s.jsx("div",{className:"relative group inline-block",children:s.jsxs("div",{className:`relative w-16 h-16 rounded-lg overflow-hidden border cursor-pointer hover:opacity-80 transition ${Qe||z>0?"border-blue-500 border-2 shadow-sm":"border-gray-200 dark:border-white/[0.08]"}`,onClick:()=>n(oe,Fe,D.prompt),children:[ee&&s.jsx("img",{src:ee,"data-image-id":oe,className:"w-full h-full object-cover",alt:""}),Qe&&s.jsx("span",{className:"absolute left-1 top-1 rounded bg-blue-500/90 px-1.5 py-0.5 text-[8px] leading-none text-white font-bold tracking-wider backdrop-blur-sm z-10 pointer-events-none",children:"MASK"}),z>0&&s.jsx(Ng,{count:z,className:Qe?"left-1 top-[18px]":"left-1 top-1"})]})},oe)})}),xe&&s.jsx("div",{className:`${Fe.length>0?"mt-2 ":""}text-xs text-gray-500 dark:text-gray-400`,children:Fe.length>0?"由模型自主选择,可能包含其他图片":"由模型自主选择"})]}),s.jsx("h3",{className:"text-xs font-medium text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-2",children:"参数配置"}),ae&&s.jsxs("div",{className:"mb-2 min-w-0 overflow-hidden rounded-lg bg-gray-50 px-3 py-2 text-xs dark:bg-white/[0.03]",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"来源"}),s.jsx("br",{}),s.jsxs("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:[s.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-200",children:X}),s.jsxs("span",{className:"text-gray-400 dark:text-gray-500",children:[" · ",me," · ",ve]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs mb-4 min-w-0",children:[s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"尺寸"}),s.jsx("br",{}),s.jsx("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:s.jsx(Eo,{task:D,paramKey:"size",className:"font-medium",actualParams:Oe})})]}),s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"质量"}),s.jsx("br",{}),s.jsx("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:s.jsx(Eo,{task:D,paramKey:"quality",className:"font-medium",actualParams:Oe})})]}),s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"格式"}),s.jsx("br",{}),s.jsx("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:s.jsx(Eo,{task:D,paramKey:"output_format",className:"font-medium",actualParams:Oe})})]}),Pt&&s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"透明背景"}),s.jsx("br",{}),s.jsxs("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:[s.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-300",children:Ct}),Ht&&s.jsx("span",{className:"ml-1.5 rounded bg-red-50 px-1 py-0.5 text-[10px] font-medium uppercase leading-none text-red-600 dark:bg-red-500/10 dark:text-red-400",children:"failed"})]})]}),D.params.output_format!=="png"&&s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"压缩率"}),s.jsx("br",{}),s.jsx("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:s.jsx("span",{className:"font-medium text-gray-700 dark:text-gray-300",children:Dt})})]}),s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"审核"}),s.jsx("br",{}),s.jsx("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:s.jsx(Eo,{task:D,paramKey:"moderation",className:"font-medium",actualParams:Oe})})]}),!xe&&s.jsxs("div",{className:"bg-gray-50 dark:bg-white/[0.03] rounded-lg px-3 py-2 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-gray-400 dark:text-gray-500",children:"数量"}),s.jsx("br",{}),s.jsx("div",{className:"mt-0.5 overflow-x-auto hide-scrollbar whitespace-nowrap mask-edge-r pr-2",children:s.jsx(Eo,{task:D,paramKey:"n",className:"font-medium"})})]})]}),s.jsxs("div",{className:"text-xs text-gray-400 dark:text-gray-500 mb-4",children:[s.jsxs("span",{children:["创建于 ",Tt(D.createdAt)]}),D.startedAt!=null&&D.startedAt>D.createdAt&&s.jsxs("span",{className:"relative ml-1 inline-flex align-middle",children:[s.jsx("button",{type:"button",...G.handlers,className:"inline-flex text-gray-400 transition hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300","aria-label":"查看重试时间",children:s.jsx("svg",{className:"h-3.5 w-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),s.jsxs(pt,{visible:G.visible,className:"whitespace-nowrap",children:["重试于 ",Tt(D.startedAt)]})]}),Ce()&&s.jsxs("span",{children:[" · 耗时 ",Ce()]})]}),De&&s.jsx("div",{className:"mb-4 space-y-1 text-xs text-gray-400 dark:text-gray-500",children:[["任务 ID",D.id],["图片 ID",Xe]].filter(([,oe])=>oe).map(([oe,Te])=>s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:"shrink-0",children:oe}),s.jsx("span",{"data-selectable-text":!0,className:"min-w-0 truncate font-mono",children:Te}),s.jsx("button",{type:"button",onClick:()=>{fn(Te).then(()=>o(`${oe}已复制`,"success"),Qe=>o($r(`复制${oe}失败`,Qe),"error"))},className:"shrink-0 text-blue-500 hover:underline",children:"复制"})]},oe))})]}),s.jsxs("div",{className:"grid grid-cols-4 sm:flex gap-2 pt-4 border-t border-gray-100 dark:border-white/[0.08]",children:[s.jsxs("button",{onClick:Or,className:"col-span-2 sm:flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-500/20 transition text-sm font-medium whitespace-nowrap",children:[s.jsx("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})}),"复用配置"]}),s.jsxs("button",{onClick:nt,disabled:!de,className:"col-span-2 sm:flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-green-50 dark:bg-green-500/10 text-green-600 dark:text-green-400 hover:bg-green-100 dark:hover:bg-green-500/20 disabled:opacity-40 disabled:cursor-not-allowed transition text-sm font-medium whitespace-nowrap",children:[s.jsx(Hr,{className:"w-4 h-4 flex-shrink-0"}),"编辑输出"]}),s.jsxs("button",{onClick:tr,className:`${l?"col-span-4":"col-span-3"} sm:flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-red-50 dark:bg-red-500/10 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-500/20 transition text-sm font-medium whitespace-nowrap`,children:[s.jsx(_r,{className:"w-4 h-4 flex-shrink-0"}),"删除任务"]}),!l&&s.jsx("button",{onClick:Le,className:`col-span-1 sm:flex-none sm:w-11 w-full flex items-center justify-center rounded-xl transition ${D.isFavorite?"bg-yellow-50 text-yellow-500 hover:bg-yellow-100 dark:bg-yellow-500/10 dark:hover:bg-yellow-500/20":"bg-gray-50 text-gray-400 hover:bg-yellow-50 hover:text-yellow-500 dark:bg-white/[0.04] dark:hover:bg-yellow-500/10"}`,title:D.isFavorite?"编辑收藏夹":"收藏任务",children:s.jsx("svg",{className:"w-5 h-5",fill:D.isFavorite?"currentColor":"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"})})})]})]})]}),T&&wt.length>0&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4 backdrop-blur-sm sm:p-6",onPointerDown:oe=>{K.current=oe.target===oe.currentTarget},onClick:oe=>{oe.stopPropagation(),K.current&&oe.target===oe.currentTarget&&R(!1),K.current=!1},children:s.jsxs("div",{ref:J,className:"flex w-full max-w-2xl max-h-[90vh] flex-col overflow-hidden rounded-2xl bg-white shadow-xl dark:bg-[#1c1c1e]",onClick:oe=>oe.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-gray-100 px-5 py-4 dark:border-white/[0.08] shrink-0",children:[s.jsxs("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:["原始图片链接 (",wt.length,")"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:async()=>{try{await fn(wt.join(`
|
|
90
|
+
`)),o("复制成功","success")}catch(oe){o($r("复制失败",oe),"error")}},className:"flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg bg-gray-50 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.08] transition-colors text-xs font-medium",children:[s.jsx(zr,{className:"w-3.5 h-3.5"}),"全部复制"]}),s.jsx("button",{type:"button",onClick:()=>R(!1),className:"rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-white/[0.08] dark:hover:text-gray-300 transition-colors",children:s.jsx(qt,{className:"w-5 h-5"})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 sm:p-5 bg-gray-50/50 dark:bg-black/20 overscroll-contain",children:s.jsx("div",{className:"space-y-2.5",children:wt.map((oe,Te)=>s.jsxs("div",{className:"group flex items-center gap-3 p-3 sm:p-4 rounded-xl bg-white dark:bg-[#1c1c1e] border border-gray-100 dark:border-white/[0.06] shadow-sm hover:shadow-md transition-all",children:[s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-1",children:[s.jsxs("div",{className:"text-xs font-medium text-gray-400 dark:text-gray-500",children:["图片 ",Te+1]}),s.jsx("div",{className:"text-sm text-gray-700 dark:text-gray-300 truncate select-text",title:oe,children:oe})]}),s.jsxs("button",{type:"button",onClick:async()=>{try{await fn(oe),o("复制成功","success")}catch(Qe){o($r("复制失败",Qe),"error")}},className:"flex-shrink-0 p-2 sm:px-3 sm:py-1.5 flex items-center justify-center gap-1.5 rounded-lg bg-gray-50 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.08] transition-colors text-xs font-medium border border-transparent dark:border-white/[0.04]",title:"复制链接",children:[s.jsx(zr,{className:"w-4 h-4 sm:w-3.5 sm:h-3.5"}),s.jsx("span",{className:"hidden sm:inline",children:"复制"})]})]},Te))})})]})}),U&&(D==null?void 0:D.rawResponsePayload)&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/40 p-4 backdrop-blur-sm sm:p-6",onPointerDown:oe=>{te.current=oe.target===oe.currentTarget},onClick:oe=>{oe.stopPropagation(),te.current&&oe.target===oe.currentTarget&&W(!1),te.current=!1},children:s.jsxs("div",{ref:H,className:"flex w-full max-w-3xl max-h-[90vh] flex-col overflow-hidden rounded-2xl bg-white shadow-xl dark:bg-[#1c1c1e]",onPointerDown:oe=>{oe.target.closest("[data-selectable-text]")||ie()},onClick:oe=>oe.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-gray-100 px-5 py-4 dark:border-white/[0.08] shrink-0",children:[s.jsx("h3",{className:"text-base font-semibold text-gray-900 dark:text-white",children:"原始响应数据"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:async()=>{try{await fn(D.rawResponsePayload),o("复制成功","success")}catch(oe){o($r("复制失败",oe),"error")}},className:"flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg bg-gray-50 dark:bg-white/[0.04] text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.08] transition-colors text-xs font-medium",children:[s.jsx(zr,{className:"w-3.5 h-3.5"}),"全部复制"]}),s.jsx("button",{type:"button",onClick:()=>W(!1),className:"rounded-full p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-500 dark:hover:bg-white/[0.08] dark:hover:text-gray-300 transition-colors",children:s.jsx(qt,{className:"w-5 h-5"})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-5 bg-gray-50/50 dark:bg-black/20 overscroll-contain",children:s.jsx("pre",{"data-selectable-text":!0,className:"text-[11px] sm:text-xs text-gray-600 dark:text-gray-300 font-mono whitespace-pre-wrap break-all select-text",children:D.rawResponsePayload.replace(/"(b64_json|base64|data)":\s*"[^"]+"/g,'"$1": "<base64_data>"')})})]})})]})}const au=1,ou=10,Aa=10,q4=40,iu=350,ih=40;function lu(e,t,r){return Math.max(t,Math.min(r,e))}function J4(){const e=w(H=>H.lightboxImageId),t=w(H=>H.lightboxImageList),r=w(H=>H.setLightboxImageId),n=w(H=>H.maskDraft),a=w(H=>H.tasks),o=w(H=>H.inputImages),i=w(H=>H.lightboxCommentPrompt),l=w(H=>H.replaceInputImage),c=w(H=>H.setMaskEditorImageId),u=w(H=>H.setSketchBoard),f=w(H=>H.setConfirmDialog),d=w(H=>H.settings),g=w(H=>H.setSettings),m=w(H=>H.showToast),x=p.useRef(null),b=p.useRef(null),[h,y]=p.useState(""),[v,I]=p.useState(""),[S,k]=p.useState(""),j=p.useCallback(()=>r(null),[r]);Kr(!!e,j),Lr(!!e),p.useEffect(()=>{let H=!1;if(!e){y("");return}y("");const K=e,te=En(K);return te?y(te):kt(K).then(P=>{!H&&P&&y(P)}),()=>{H=!0}},[e]),p.useEffect(()=>{let H=!1;if(!e){I("");return}if((n==null?void 0:n.targetImageId)===e){I(n.maskDataUrl);return}I("");const K=a.find(te=>te.maskTargetImageId===e&&te.maskImageId);if(K!=null&&K.maskImageId){const te=K.maskImageId,P=En(te);P?I(P):kt(te).then(B=>{!H&&B&&I(B)})}else I("");return()=>{H=!0}},[e,n==null?void 0:n.targetImageId,n==null?void 0:n.maskDataUrl,a]),p.useEffect(()=>{let H=!1;if(!h||!v){k("");return}return rd(h,v).then(K=>{H||k(K)}).catch(()=>{H||k("")}),()=>{H=!0}},[h,v]);const A=e?t.indexOf(e):-1,N=t.length,C=N>1,T=p.useCallback(H=>{if(t.length===0)return;const K=(H%t.length+t.length)%t.length;r(t[K],t,i)},[i,t,r]),R=p.useCallback(()=>{C&&T(A-1)},[C,A,T]),U=p.useCallback(()=>{C&&T(A+1)},[C,A,T]),W=!!(e&&o.some(H=>H.id===e)),F=p.useCallback(()=>{var H;!e||!W||(b.current=e,(H=x.current)==null||H.click())},[W,e]),_=p.useCallback(async H=>{var P;const K=(P=H.target.files)==null?void 0:P[0];H.target.value="";const te=b.current;if(b.current=null,!(!K||!te))try{const B=await kg(K);if(!B){m("请选择有效图片","error");return}const $=w.getState().inputImages,Q=$.findIndex(G=>G.id===te);if(Q<0){bb(B.id),m("原参考图已不存在","error");return}if(te===B.id){m("参考图未变化","info");return}if($.some((G,se)=>se!==Q&&G.id===B.id)){m("这张图片已在参考图中","info");return}l(Q,B);const L=t.map(G=>G===te?B.id:G);r(B.id,L,i),m("参考图已替换","success")}catch(B){m(`参考图替换失败:${B instanceof Error?B.message:String(B)}`,"error")}},[i,t,l,r,m]),O=p.useCallback(()=>{if(!e||!W||!h)return;const H=e,K=h;if((n==null?void 0:n.targetImageId)===H){j(),c(H);return}const te=()=>{j(),u({baseImageSrc:K,replaceImageId:H})},P=()=>{if(n){m("只能有一张遮罩图,请先移除现有遮罩","info");return}j(),c(H)},B=($,Q)=>{Q&&g({referenceImageEditAction:$})};if(d.referenceImageEditAction==="sketch"){te();return}if(d.referenceImageEditAction==="mask"){P();return}f({title:"编辑图片",message:`画板可在图片上手绘、评论,标注修改意图;遮罩可指定需要重绘的区域。
|
|
91
|
+
若勾选下方选项,之后可在「设置 → 习惯配置」中修改。`,checkbox:{label:"以后默认执行此选择"},buttons:[{label:"遮罩",tone:"secondary",action:$=>{B("mask",$),P()}},{label:"画板",tone:"primary",action:$=>{B("sketch",$),te()}}]})},[j,W,e,n,f,c,g,u,d.referenceImageEditAction,m,h]);if(p.useEffect(()=>{if(!e||!C)return;const H=K=>{K.key==="ArrowLeft"&&(K.preventDefault(),R()),K.key==="ArrowRight"&&(K.preventDefault(),U())};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[e,C,R,U]),!e||!h)return null;const J=i!=null&&A>=0?Ya(i,A):[];return s.jsxs(s.Fragment,{children:[s.jsx(G4,{src:h,comments:J,imageId:e,maskPreviewSrc:S,onClose:j,showNav:C,currentIndex:A,total:N,onPrev:R,onNext:U,showInputActions:W,onReplace:F,onEdit:O}),s.jsx("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:_})]})}function G4({src:e,comments:t,imageId:r,maskPreviewSrc:n,onClose:a,showNav:o,currentIndex:i,total:l,onPrev:c,onNext:u,showInputActions:f,onReplace:d,onEdit:g}){const m=p.useRef(null),x=p.useRef(Date.now()),b=p.useRef(1),h=p.useRef(0),y=p.useRef(0),[,v]=p.useState(0),I=p.useCallback(()=>v(Pe=>Pe+1),[]),[S,k]=p.useState(!1),[j,A]=p.useState({imageId:r,indexes:[]});j.imageId!==r&&A({imageId:r,indexes:[]});const N=j.indexes,C=Pe=>{A({imageId:r,indexes:N.includes(Pe)?N.filter(ne=>ne!==Pe):[...N,Pe]})},T=p.useRef(null),R=p.useRef({active:!1,startX:0,startY:0,baseTx:0,baseTy:0}),U=p.useRef({active:!1,startDist:0,startScale:1,startTx:0,startTy:0,midX:0,midY:0}),W=p.useRef({time:0,x:0,y:0}),F=p.useRef(!1),_=p.useRef(!1),O=p.useRef(!1),J=p.useRef(null),H=p.useRef("none"),K=p.useRef(!1),te=p.useRef(!1),P=p.useRef(!1),B=p.useRef(null),$=p.useRef(!1),Q=p.useRef(!1),L=p.useRef(null);p.useEffect(()=>{x.current=Date.now(),b.current=1,h.current=0,y.current=0,I()},[e,I]),p.useEffect(()=>{const Pe=()=>{Q.current=!0};return window.addEventListener("image-context-menu-dismiss-lightbox-click",Pe),()=>window.removeEventListener("image-context-menu-dismiss-lightbox-click",Pe)},[]);const G=p.useCallback(()=>{var ne;const Pe=(ne=m.current)==null?void 0:ne.getBoundingClientRect();return Pe?{cx:Pe.left+Pe.width/2,cy:Pe.top+Pe.height/2}:{cx:0,cy:0}},[]),se=p.useCallback(()=>{B.current&&(clearTimeout(B.current),B.current=null)},[]),Y=p.useCallback(()=>{Q.current=!0,L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{Q.current=!1,L.current=null},350)},[]),le=p.useCallback(()=>{J.current=null,H.current="none",K.current=!1,te.current=!1,O.current=!1},[]),ie=p.useCallback((Pe,ne,ge)=>{const xe=lu(Pe,au,ou);b.current=xe,h.current=xe<=1?0:ne,y.current=xe<=1?0:ge,xe>1?(k(!0),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>k(!1),1500)):(k(!1),T.current&&clearTimeout(T.current)),I()},[I]);p.useEffect(()=>{const Pe=m.current;if(!Pe)return;const ne=ge=>{ge.preventDefault();const xe=b.current,fe=h.current,be=y.current,Z=Pe.getBoundingClientRect(),de=ge.clientX-Z.left-Z.width/2,he=ge.clientY-Z.top-Z.height/2,pe=ge.deltaY<0?1.15:1/1.15,Be=lu(xe*pe,au,ou),Oe=Be/xe;ie(Be,de-Oe*(de-fe),he-Oe*(he-be))};return Pe.addEventListener("wheel",ne,{passive:!1}),()=>Pe.removeEventListener("wheel",ne)},[ie]),p.useEffect(()=>{const Pe=m.current;if(!Pe)return;const ne=fe=>{fe.button===0&&($.current=!1,!(b.current<=1)&&(fe.preventDefault(),R.current={active:!0,startX:fe.clientX,startY:fe.clientY,baseTx:h.current,baseTy:y.current}))},ge=fe=>{const be=R.current;if(!be.active)return;const Z=fe.clientX-be.startX,de=fe.clientY-be.startY;(Math.abs(Z)>3||Math.abs(de)>3)&&($.current=!0),ie(b.current,be.baseTx+Z,be.baseTy+de)},xe=()=>{R.current.active=!1};return Pe.addEventListener("mousedown",ne),window.addEventListener("mousemove",ge),window.addEventListener("mouseup",xe),()=>{Pe.removeEventListener("mousedown",ne),window.removeEventListener("mousemove",ge),window.removeEventListener("mouseup",xe)}},[ie]);const D=p.useCallback(Pe=>{if(Q.current){Q.current=!1,Pe.stopPropagation();return}$.current||b.current>1&&Pe.target instanceof HTMLImageElement||a()},[a]),ue=p.useCallback(Pe=>{if(Pe.stopPropagation(),!(Date.now()-x.current<iu))if(b.current>1)ie(1,0,0);else{const{cx:ne,cy:ge}=G(),xe=Pe.clientX-ne,fe=Pe.clientY-ge;ie(3,-xe*2,-fe*2)}},[ie,G]);p.useEffect(()=>{const Pe=m.current;if(!Pe)return;const ne=be=>{if(be.touches.length===2){be.preventDefault(),se(),le(),F.current=!0,H.current="pinch",W.current={time:0,x:0,y:0};const[Z,de]=[be.touches[0],be.touches[1]],he=Math.hypot(Z.clientX-de.clientX,Z.clientY-de.clientY),{cx:pe,cy:Be}=G();U.current={active:!0,startDist:he,startScale:b.current,startTx:h.current,startTy:y.current,midX:(Z.clientX+de.clientX)/2-pe,midY:(Z.clientY+de.clientY)/2-Be},R.current.active=!1}else if(be.touches.length===1){const Z=be.touches[0],de=Date.now(),he=W.current;if(_.current=be.target instanceof HTMLImageElement,O.current=be.target instanceof Element&&!!be.target.closest("button"),J.current={x:Z.clientX,y:Z.clientY,time:de},H.current="none",K.current=!1,te.current=!1,_.current&&de-he.time<iu&&Math.abs(Z.clientX-he.x)<ih&&Math.abs(Z.clientY-he.y)<ih){if(be.preventDefault(),se(),Y(),P.current=!0,b.current>1)ie(1,0,0);else{const{cx:pe,cy:Be}=G(),Oe=Z.clientX-pe,Ue=Z.clientY-Be;ie(3,-Oe*2,-Ue*2)}W.current={time:0,x:0,y:0},le();return}W.current={time:de,x:Z.clientX,y:Z.clientY},b.current>1&&_.current&&(be.preventDefault(),R.current={active:!0,startX:Z.clientX,startY:Z.clientY,baseTx:h.current,baseTy:y.current})}},ge=be=>{if(U.current.active&&be.touches.length===2){be.preventDefault();const[Z,de]=[be.touches[0],be.touches[1]],he=Math.hypot(Z.clientX-de.clientX,Z.clientY-de.clientY),pe=U.current,Be=lu(pe.startScale*(he/pe.startDist),au,ou),Oe=Be/pe.startScale;ie(Be,pe.midX-Oe*(pe.midX-pe.startTx),pe.midY-Oe*(pe.midY-pe.startTy))}else if(R.current.active&&be.touches.length===1){be.preventDefault();const Z=be.touches[0],de=R.current,he=Z.clientX-de.startX,pe=Z.clientY-de.startY;(Math.abs(he)>Aa||Math.abs(pe)>Aa)&&(K.current=!0,H.current="zoom-pan"),ie(b.current,de.baseTx+he,de.baseTy+pe)}else if(b.current<=1&&be.touches.length===1&&J.current){const Z=be.touches[0],de=Z.clientX-J.current.x,he=Z.clientY-J.current.y,pe=Math.abs(de),Be=Math.abs(he);(pe>Aa||Be>Aa)&&(K.current=!0),H.current==="none"&&(pe>Aa||Be>Aa)&&(H.current=pe>Be?"horizontal-swipe":"vertical-move",H.current==="horizontal-swipe"&&se()),H.current==="horizontal-swipe"&&be.preventDefault()}},xe=be=>{if(be.touches.length<2&&(U.current.active=!1),be.touches.length===0){if(R.current.active=!1,F.current){F.current=!1,W.current={time:0,x:0,y:0},le();return}if(P.current){P.current=!1,le();return}const Z=J.current,de=be.changedTouches[0],he=Z&&de?de.clientX-Z.x:0,pe=H.current,Be=K.current;if(pe==="horizontal-swipe"&&b.current<=1){se(),Y(),te.current=Math.abs(he)>=q4,W.current={time:0,x:0,y:0},be.preventDefault(),te.current&&(he<0&&o&&u(),he>0&&o&&c()),le();return}if(Be||pe==="vertical-move"||pe==="zoom-pan"){Y(),W.current={time:0,x:0,y:0},le();return}if(Y(),O.current){le();return}b.current<=1&&_.current?(se(),B.current=setTimeout(()=>{B.current=null,Rc(),a()},iu)):_.current||(se(),Rc(),be.cancelable&&be.preventDefault(),a()),le()}},fe=()=>{se(),W.current={time:0,x:0,y:0},F.current=!1,P.current=!1,U.current.active=!1,R.current.active=!1,le()};return Pe.addEventListener("touchstart",ne,{passive:!1}),Pe.addEventListener("touchmove",ge,{passive:!1}),Pe.addEventListener("touchend",xe),Pe.addEventListener("touchcancel",fe),()=>{se(),L.current&&(clearTimeout(L.current),L.current=null),Pe.removeEventListener("touchstart",ne),Pe.removeEventListener("touchmove",ge),Pe.removeEventListener("touchend",xe),Pe.removeEventListener("touchcancel",fe)}},[ie,se,G,a,u,c,le,o,Y]);const ke=b.current,we=h.current,We=y.current,Ne=ke>1,Fe=R.current.active||U.current.active,Ee=Math.round(ke*100),Ge="absolute top-1/2 -translate-y-1/2 p-2 rounded-full bg-white/80 text-gray-800 hover:bg-white dark:bg-black/40 dark:text-white dark:hover:bg-black/60 transition-all z-10 backdrop-blur-sm shadow-md border border-gray-200/50 dark:border-transparent";return s.jsxs("div",{ref:m,"data-lightbox-root":!0,className:"fixed inset-0 z-[60] flex items-center justify-center select-none",style:{cursor:Ne?Fe?"grabbing":"grab":"pointer"},onClick:D,onDoubleClick:ue,children:[s.jsx("div",{className:"absolute inset-0 bg-black/35 dark:bg-black/70 backdrop-blur-md animate-fade-in"}),s.jsx("div",{className:"relative animate-zoom-in",children:s.jsxs("div",{className:"relative flex items-center justify-center",style:{transform:`translate(${we}px, ${We}px) scale(${ke})`,transition:Fe?"none":"transform 0.2s ease-out",willChange:"transform"},children:[s.jsx("img",{src:e,"data-image-id":r,className:"saveable-image max-w-[90vw] max-h-[70vh] sm:max-w-[85vw] sm:max-h-[75vh] object-contain rounded-lg shadow-2xl",onDragStart:Pe=>Pe.preventDefault(),alt:""}),n&&s.jsx("img",{src:n,className:"absolute inset-0 w-full h-full object-contain rounded-lg pointer-events-none",alt:""}),t.map((Pe,ne)=>s.jsxs("div",{className:"pointer-events-none absolute",style:{left:`${Pe.x*100}%`,bottom:`${(1-Pe.y)*100}%`,transform:`scale(${1/ke})`,transformOrigin:"0 100%",transition:Fe?"none":"transform 0.2s ease-out"},children:[s.jsx("button",{type:"button","aria-label":N.includes(ne)?`显示评论 ${ne+1}`:`隐藏评论 ${ne+1}`,"aria-pressed":!N.includes(ne),className:"pointer-events-auto block cursor-pointer",onClick:ge=>{ge.stopPropagation(),C(ne)},onDoubleClick:ge=>ge.stopPropagation(),children:s.jsx(ky,{index:ne})}),s.jsx("span",{className:`absolute bottom-0 w-max max-w-[18rem] whitespace-pre-wrap break-words rounded-xl border border-gray-200/80 bg-white/95 px-3 py-2 text-sm leading-snug text-gray-800 shadow-lg backdrop-blur-md transition-[opacity,transform] duration-150 ease-out dark:border-white/[0.08] dark:bg-gray-800/95 dark:text-gray-100 ${Pe.x>.6?"right-full mr-1.5 origin-bottom-right":"left-full ml-1.5 origin-bottom-left"} ${N.includes(ne)?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:Pe.text})]},ne))]})}),o&&!Ne&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:`${Ge} left-3 sm:left-5`,onClick:Pe=>{Pe.stopPropagation(),Xe()},children:s.jsx("svg",{className:"w-5 h-5 sm:w-6 sm:h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}),s.jsx("button",{className:`${Ge} right-3 sm:right-5`,onClick:Pe=>{Pe.stopPropagation(),ht()},children:s.jsx("svg",{className:"w-5 h-5 sm:w-6 sm:h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})})]}),f&&!Ne&&s.jsxs("div",{className:"absolute bottom-8 left-1/2 z-10 flex w-max -translate-x-1/2 items-center gap-2 rounded-2xl bg-white/90 dark:bg-black/60 p-2 backdrop-blur-xl border border-gray-200/80 dark:border-white/15 shadow-2xl transition-colors",onClick:Pe=>Pe.stopPropagation(),children:[s.jsxs("button",{type:"button",className:"flex items-center justify-center gap-2 whitespace-nowrap rounded-xl px-5 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-100 dark:text-white/90 dark:hover:bg-white/15 transition active:scale-95",onClick:d,children:[s.jsx(Go,{className:"w-4 h-4"}),s.jsx("span",{children:"替换图片"})]}),s.jsxs("button",{type:"button",className:"flex items-center justify-center gap-2 whitespace-nowrap rounded-xl bg-blue-500 px-5 py-2.5 text-sm font-medium text-white shadow-md transition hover:bg-blue-600 hover:shadow-blue-500/25 active:scale-95",onClick:g,children:[s.jsx(Hr,{className:"w-4 h-4"}),s.jsx("span",{children:"编辑图片"})]})]}),S&&Ne&&Ee!==100&&s.jsx("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 pointer-events-none",children:s.jsxs("span",{className:"px-3 py-1.5 bg-white/90 dark:bg-black/50 text-gray-800 dark:text-white/80 text-xs rounded-full backdrop-blur-sm transition-opacity duration-500 border border-gray-200/80 dark:border-transparent",children:[Ee,"%"]})}),o&&!Ne&&s.jsx("div",{className:"absolute top-6 left-1/2 -translate-x-1/2 pointer-events-none z-10",children:s.jsxs("span",{className:"px-3 py-1 bg-white/90 dark:bg-black/60 text-gray-800 dark:text-white/90 text-sm font-medium rounded-full backdrop-blur-md shadow-lg border border-gray-200/80 dark:border-white/15",children:[i+1," / ",l]})})]});function Xe(){c()}function ht(){u()}}function Z4(e,t,r,n){const a=new URL(e);a.search="",a.hash="";const o={...t,id:void 0,isDefault:void 0,apiKey:n.includeApiKey?t.apiKey:""};n.includeApiKey||(n.useNewApiAddress&&(o.baseUrl="{address}"),n.useNewApiKey&&(o.apiKey="{key}"),n.useNewApiModel&&(o.model="{model}")),a.searchParams.set("settings",JSON.stringify({...r?{customProviders:[r]}:{},profiles:[o]}));let i=a.toString();return n.includeApiKey||(n.useNewApiAddress&&(i=i.replace(/%7Baddress%7D/g,"{address}")),n.useNewApiKey&&(i=i.replace(/%7Bkey%7D/g,"{key}")),n.useNewApiModel&&(i=i.replace(/%7Bmodel%7D/g,"{model}"))),i}const lh=JSON.stringify({name:"自定义服务商",submit:{path:"images/generations",method:"POST",contentType:"json",body:{model:"$profile.model",prompt:"$prompt",size:"$params.size",quality:"$params.quality",output_format:"$params.output_format",moderation:"$params.moderation",output_compression:"$params.output_compression",n:"$params.n",background:"$params.background"},result:{imageUrlPaths:["data.*.url"],b64JsonPaths:["data.*.b64_json"]}},editSubmit:{path:"images/edits",method:"POST",contentType:"multipart",body:{model:"$profile.model",prompt:"$prompt",size:"$params.size",quality:"$params.quality",output_format:"$params.output_format",moderation:"$params.moderation",output_compression:"$params.output_compression",n:"$params.n",background:"$params.background"},files:[{field:"image[]",source:"inputImages",array:!0},{field:"mask",source:"mask"}],result:{imageUrlPaths:["data.*.url"],b64JsonPaths:["data.*.b64_json"]}}},null,2),Q4=`每个元素的顶层字段:id、name、submit、editSubmit、poll。
|
|
92
|
+
id 是服务商的唯一标识,用于 profiles 中的 provider 字段引用,建议使用 custom-{英文短名} 格式。
|
|
93
|
+
submit 是文生图提交配置,必填。
|
|
94
|
+
editSubmit 是图生图或局部重绘提交配置,可选。如果文生图和图生图使用同一个 JSON 接口,可以省略 editSubmit,并在 submit.body 中加入 image_urls。
|
|
95
|
+
poll 是异步任务查询配置,可选;同步接口不要写 poll。
|
|
96
|
+
|
|
97
|
+
submit/editSubmit 字段:
|
|
98
|
+
- path:接口路径,不带开头斜杠,不带 /v1/ 前缀,例如 images/generations 或 tasks/{task_id}。
|
|
99
|
+
- method:GET 或 POST,默认 POST。
|
|
100
|
+
- contentType:json 或 multipart。
|
|
101
|
+
- query:提交 query 参数对象,可选,例如 {"async":"true"}。
|
|
102
|
+
- body:请求体模板对象。
|
|
103
|
+
- files:multipart 文件字段数组,仅 contentType=multipart 时使用。
|
|
104
|
+
- taskIdPath:提交响应里的任务 ID JSON 路径;同步接口不要写。
|
|
105
|
+
- result:同步响应图片提取规则。
|
|
106
|
+
|
|
107
|
+
poll 字段:
|
|
108
|
+
- path:任务查询路径,使用 {task_id} 占位,例如 images/tasks/{task_id} 或 tasks/{task_id}。
|
|
109
|
+
- method:GET 或 POST,默认 GET。
|
|
110
|
+
- query:查询 query 参数对象,可选。
|
|
111
|
+
- intervalSeconds:轮询间隔秒数。
|
|
112
|
+
- statusPath:查询响应状态字段路径。
|
|
113
|
+
- successValues:成功状态值数组。
|
|
114
|
+
- failureValues:失败状态值数组。
|
|
115
|
+
- errorPath:失败原因路径,可选。
|
|
116
|
+
- result:成功后图片提取规则。
|
|
117
|
+
|
|
118
|
+
result 字段:
|
|
119
|
+
- imageUrlPaths:图片 URL 路径数组,支持 * 通配数组。例如 data.*.url、data.result.images.*.url.*。
|
|
120
|
+
- b64JsonPaths:base64 图片路径数组,支持 * 通配数组。例如 data.*.b64_json。
|
|
121
|
+
|
|
122
|
+
body 模板变量:
|
|
123
|
+
- $profile.model:用户在设置里填写的模型 ID。
|
|
124
|
+
- $prompt:当前提示词。
|
|
125
|
+
- $params.size、$params.quality、$params.output_format、$params.output_compression、$params.moderation、$params.n:应用内参数。
|
|
126
|
+
- $params.background:API 原生透明背景参数;启用时为 \`"transparent"\`,未启用时自动省略。
|
|
127
|
+
- $inputImages.dataUrls:参考图 data URL 数组;没有参考图时会自动省略该字段。
|
|
128
|
+
- $inputImages.base64:参考图 base64 数组,不含 \`data:image/png;base64,\` 前缀;没有参考图时会自动省略该字段。
|
|
129
|
+
- $inputImages.urls:参考图链接数组,只包含在输入框「+ → 添加链接」中添加的参考图;没有时会自动省略该字段。配置只用它传参考图时,如果有参考图不是通过链接添加的,提交会报错。
|
|
130
|
+
- $mask.dataUrl:遮罩图 data URL;没有遮罩时会自动省略该字段。
|
|
131
|
+
|
|
132
|
+
multipart files 示例:
|
|
133
|
+
- {"field":"image[]","source":"inputImages","array":true}
|
|
134
|
+
- {"field":"mask","source":"mask"}`,eN=`## 同步接口示例
|
|
135
|
+
{"customProviders":[{"id":"custom-example-sync","name":"示例同步服务商","submit":{"path":"images/generations","method":"POST","contentType":"json","body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","quality":"$params.quality","output_format":"$params.output_format","moderation":"$params.moderation","output_compression":"$params.output_compression","n":"$params.n","background":"$params.background"},"result":{"imageUrlPaths":["data.*.url"],"b64JsonPaths":["data.*.b64_json"]}},"editSubmit":{"path":"images/edits","method":"POST","contentType":"multipart","body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","quality":"$params.quality","output_format":"$params.output_format","moderation":"$params.moderation","output_compression":"$params.output_compression","n":"$params.n","background":"$params.background"},"files":[{"field":"image[]","source":"inputImages","array":true},{"field":"mask","source":"mask"}],"result":{"imageUrlPaths":["data.*.url"],"b64JsonPaths":["data.*.b64_json"]}}}],"profiles":[{"id":"custom-example-sync-profile","name":"示例同步服务商","provider":"custom-example-sync","baseUrl":"https://api.example.com/v1","model":"gpt-image-2.5-sunburst","apiMode":"images"}]}
|
|
136
|
+
|
|
137
|
+
## 异步接口示例
|
|
138
|
+
{"customProviders":[{"id":"custom-example-async","name":"示例异步服务商","submit":{"path":"images/generations","method":"POST","contentType":"json","query":{"async":"true"},"body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","n":"$params.n","background":"$params.background"},"taskIdPath":"data"},"editSubmit":{"path":"images/edits","method":"POST","contentType":"multipart","query":{"async":"true"},"body":{"model":"$profile.model","prompt":"$prompt","size":"$params.size","n":"$params.n","background":"$params.background"},"files":[{"field":"image[]","source":"inputImages","array":true}],"taskIdPath":"data"},"poll":{"path":"images/tasks/{task_id}","method":"GET","intervalSeconds":5,"statusPath":"data.status","successValues":["SUCCESS"],"failureValues":["FAILURE"],"errorPath":"data.fail_reason","result":{"imageUrlPaths":["data.data.data.*.url"],"b64JsonPaths":["data.data.data.*.b64_json"]}}}],"profiles":[{"id":"custom-example-async-profile","name":"示例异步服务商","provider":"custom-example-async","baseUrl":"","model":"gpt-image-2.5-sunburst","apiMode":"images"}]}
|
|
139
|
+
|
|
140
|
+
## 统一任务接口示例
|
|
141
|
+
{"customProviders":[{"id":"custom-example-task","name":"示例任务服务商","submit":{"path":"images/generations","method":"POST","contentType":"json","body":{"model":"$profile.model","prompt":"$prompt","n":"$params.n","size":"$params.size","resolution":"2k","quality":"$params.quality","image_urls":"$inputImages.dataUrls"},"taskIdPath":"data.0.task_id"},"poll":{"path":"tasks/{task_id}","method":"GET","query":{"language":"zh"},"intervalSeconds":5,"statusPath":"data.status","successValues":["completed"],"failureValues":["failed","cancelled"],"errorPath":"data.error.message","result":{"imageUrlPaths":["data.result.images.*.url.*"],"b64JsonPaths":[]}}}],"profiles":[{"id":"custom-example-task-profile","name":"示例任务服务商","provider":"custom-example-task","baseUrl":"","model":"gpt-image-2.5-sunburst","apiMode":"images"}]}`,tN=`# 角色
|
|
142
|
+
你是 API 文档解析助手。你的任务是根据用户提供的图像生成 API 文档,生成本应用可导入的自定义服务商配置 JSON。
|
|
143
|
+
|
|
144
|
+
# 工作流程
|
|
145
|
+
1. 先向用户索要 API 文档链接或完整文档文本。
|
|
146
|
+
2. 如果当前环境支持读取链接,主动读取;否则要求用户粘贴文档内容。
|
|
147
|
+
3. 在未获得文档前不要猜测,不要生成占位配置。
|
|
148
|
+
4. 从文档中判断提交接口、图生图接口、异步任务查询接口、状态值、结果图片路径。
|
|
149
|
+
5. 若文档中明确了默认模型 ID 或 API Base URL,在 profiles 中填入;若接口不在 /v1 路径下,baseUrl 必须以 / 结尾(如 https://api.example.com/ 配合 path=api/image-tasks),以直接基于该地址请求且不补齐 /v1;若未明确模型 ID,model 填 "gpt-image-2.5-sunburst";若未明确 API Base URL,baseUrl 留空字符串 "" 由用户导入后填写。
|
|
150
|
+
6. 输出最终 JSON;不要索要 API Key。
|
|
151
|
+
|
|
152
|
+
# 输出结构
|
|
153
|
+
输出 JSON 包含两个顶层字段:
|
|
154
|
+
- customProviders:自定义服务商 Manifest 数组,每项描述一个服务商的接口映射规则。
|
|
155
|
+
- profiles:API 配置数组,每项描述一个可直接使用的连接配置,引用 customProviders 中的服务商。
|
|
156
|
+
|
|
157
|
+
## customProviders 元素(Manifest)
|
|
158
|
+
${Q4}
|
|
159
|
+
|
|
160
|
+
## profiles 元素
|
|
161
|
+
每个元素的字段:
|
|
162
|
+
- id:配置的唯一标识。生成 JSON 时自动创建,建议使用 {provider-id}-profile 或其他不重复的英文 ID。
|
|
163
|
+
- name:配置名称,方便用户识别。
|
|
164
|
+
- provider:对应 customProviders 中某个元素的 id。
|
|
165
|
+
- baseUrl:API 基础地址。若文档明确给出则填入完整地址;若接口不在 /v1 路径下必须以 / 结尾(如 https://api.example.com/ 配合 path=api/image-tasks);否则留空字符串 ""。
|
|
166
|
+
- model:模型 ID。如果 API 文档明确了默认模型,填入该值;否则使用 "gpt-image-2.5-sunburst"。
|
|
167
|
+
- apiMode:固定为 "images"。
|
|
168
|
+
- apiProxy:可选。仅同步自定义服务商可以设为 true,用于配合部署端 API 代理隐藏真实上游地址;包含 taskIdPath 或 poll 的异步任务配置不要开启,应用不支持异步自定义服务商走代理。
|
|
169
|
+
- transparentBackgroundMethod:可选,\`"api"\`(默认)或 \`"local"\`。接口不支持原生透明背景时填写 \`"local"\`。
|
|
170
|
+
- isDefault:仅 profiles 包含多个配置时,为默认预置配置填写 true,其他配置省略;只能有一个配置为 true。只有一个配置时不要填写。默认项用于首次导入及重新部署后自动选择,不影响用户拖动后的列表顺序。
|
|
171
|
+
|
|
172
|
+
部署开关边界:LOCK_PRESET_CONFIG_PARAMS 锁定预置 profile 除 API Key 外的参数,禁止编辑预置 provider Manifest;provider 被当前锁定预置 profile 引用时不可删除,解除引用后可删除。PREVENT_PRESET_CONFIG_DELETION 禁止删除预置 profile 和 provider;SHOW_PRESET_CONFIG_ONLY 只允许使用当前部署的预置 profile,并禁止创建、复制、删除、拖动、切换 provider 和管理自定义 provider。API Key 始终可编辑。
|
|
173
|
+
|
|
174
|
+
profiles 中不要包含 apiKey(用户导入后自行填写)。
|
|
175
|
+
|
|
176
|
+
# 输出要求
|
|
177
|
+
- 最终回复只包含一个 \`\`\`json 代码块,代码块内是 JSON 对象。
|
|
178
|
+
- JSON 对象必须包含 customProviders 和 profiles 两个顶层字段。
|
|
179
|
+
- 代码块外不要附加解释文字。
|
|
180
|
+
- 不要输出 API Key、Authorization header。
|
|
181
|
+
- 如果文档返回 task_id,就必须配置 taskIdPath 和 poll。
|
|
182
|
+
- 如果结果 URL 是数组,路径必须写到数组元素,例如 data.result.images.*.url.*。
|
|
183
|
+
- profiles 包含多个配置时,只为默认预置配置输出 isDefault: true,其他普通预置配置省略该字段;只有一个配置时不要输出 isDefault。
|
|
184
|
+
|
|
185
|
+
${eN}`;function _c(e){return`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`}function Ay(e){var t;return!!(e!=null&&e.poll||e!=null&&e.submit.taskIdPath||(t=e==null?void 0:e.editSubmit)!=null&&t.taskIdPath)}function Vl(e,t){if(!ei(e,t.provider))return!1;const r=Rn(e,t.provider);return!Ay(r)}function nf(e){return e==="responses"?Wa:ir}function Py(e){var l;const t=sn(),r=Oc(t),n=uf(t),a=Fc()??Uc(e),o=e.profiles.map(c=>{const u=Vl(e,c)&&r?n||c.apiProxy:!1,f=c.provider!=="fal"&&u&&!c.baseUrl.trim(),d=c.id===a?qw():sr.baseUrl,g=c.provider==="fal"?c.baseUrl.trim().replace(/\/+$/,"")||(c.id===a?"":Gn):f?"":Tn(c.baseUrl.trim()||d),m=c.provider==="fal"?_i:nf(c.apiMode);return{...c,name:c.name.trim()||(c.id===a?"默认":"新配置"),baseUrl:g,model:c.model.trim()||m,timeout:Number(c.timeout)||sr.timeout,apiProxy:De?c.apiProxy:u,codexCli:ei(e,c.provider)?c.codexCli:!1,streamImages:c.provider==="openai"?c.streamImages:!1,streamPartialImages:c.provider==="openai"?Yr(c.streamPartialImages):kr}}),i=In({id:_c("openai")});return Me({...e,profiles:o.length?o:[i],activeProfileId:o.some(c=>c.id===e.activeProfileId)?e.activeProfileId:((l=o[0])==null?void 0:l.id)??i.id})}function Ty(e,t){const r=Bn().has(t),n=Fc()??Uc(e);return e.profiles.some(a=>a.id===t)?Cn()?"应用只允许使用预置的 API 配置,不能删除":e.profiles.length<=1?"至少要保留一个 API 配置":r&&Fi()?"预置的 API 配置不能删除":!r&&t===n?"默认 API 配置不能删除":null:"找不到这个 API 配置"}function My(e,t){const r=e.profiles.filter(n=>n.id!==t);return Me({...e,profiles:r,activeProfileId:e.activeProfileId===t?r[0].id:e.activeProfileId})}function Ey(e,t){return e.customProviders.some(r=>r.id===t)?Cn()||ni(t,e.profiles)?"预置的服务商不能删除":null:"找不到这个自定义服务商"}function Ry(e,t){return Me({...e,customProviders:e.customProviders.filter(r=>r.id!==t),profiles:e.profiles.map(r=>r.provider===t?ec(r,"openai"):r)})}function _y(e,t,r){const n=new Set(t.filter(o=>o.id!==r).map(o=>o.id)),a=Oi(r&&e&&typeof e=="object"?{...e,id:r}:e,n);if(!a)throw new Error("自定义服务商配置无效");return a}function rN(){const[e,t]=p.useState(zv),[r,n]=p.useState(()=>(e==null?void 0:e.mode)??"system"),[a,o]=p.useState(()=>(e==null?void 0:e.url)??""),[i,l]=p.useState(""),[c,u]=p.useState(!1),[f,d]=p.useState(!1),g=r==="custom"||f,m=a.includes("@");p.useEffect(()=>{e||df().then(h=>{t(h),n(h.mode),o(h.url)}).catch(h=>{console.error("读取代理设置失败:",h),l(typeof h=="string"?h:"读取代理设置失败")})},[]);const x=async h=>{if(!(e&&h.mode===e.mode&&h.url.trim()===e.url))try{const y=await $h(h);t(y),o(y.url),l(""),d(!1)}catch(y){if(console.warn("保存代理设置失败:",y),l(typeof y=="string"?y:"保存代理设置失败"),!e||h.mode!=="custom")return;n(e.mode),d(!0)}},b=h=>{n(h),l(""),d(!1),!(h==="custom"&&!a.trim())&&x({mode:h,url:a})};return s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"网络"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"网络代理"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:r,onChange:b,disabled:!e,options:[{label:"跟随系统",value:"system"},{label:"不使用代理",value:"none"},{label:"自定义",value:"custom"}],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),g&&s.jsxs("div",{className:"relative mt-2 mb-1",children:[s.jsx("input",{value:a,onChange:h=>{o(h.target.value),l("")},onBlur:()=>void x({mode:"custom",url:a}),onKeyDown:h=>{h.key==="Enter"&&x({mode:"custom",url:a})},type:m&&!c?"password":"text",spellCheck:!1,placeholder:"http://127.0.0.1:7890","aria-label":"代理地址",className:`w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50 ${m?"pr-10":""}`}),m&&s.jsx("button",{type:"button",onClick:()=>u(h=>!h),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 transition-colors",tabIndex:-1,"aria-label":c?"隐藏代理地址":"显示代理地址",children:c?s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}):s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})})]}),i&&s.jsx("div",{"data-selectable-text":!0,className:"mb-1 text-xs text-red-500 dark:text-red-400",children:i}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:g?"只支持 HTTP 代理,可带用户名和密码。本机地址始终直连。":r==="none"?"API 请求和应用内更新不经过代理。":"API 请求和应用内更新使用的代理,修改后立即生效。系统使用自动配置脚本(PAC)时,请改为自定义并填写代理地址。"})]})]})}const nN=navigator.userAgent.includes("Mac"),sN=new Set(["Ctrl+A","Ctrl+C","Ctrl+V","Ctrl+X","Ctrl+Z","Ctrl+Y","Ctrl+Shift+Z","Meta+A","Meta+C","Meta+V","Meta+X","Meta+Z","Shift+Meta+Z"]),ch="shrink-0 rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs font-medium text-gray-700 transition hover:bg-black/[0.07] hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white";function aN({value:e,defaultValue:t,onChange:r}){const[n,a]=p.useState(!1),o=p.useRef(r);return o.current=r,p.useEffect(()=>{if(!n)return;S0(!0);const i=l=>{if(l.preventDefault(),l.stopPropagation(),l.key==="Escape"&&!l.ctrlKey&&!l.altKey&&!l.shiftKey&&!l.metaKey){a(!1);return}const c=hf(l);!c||sN.has(c)||(o.current(c),a(!1))};return window.addEventListener("keydown",i,!0),()=>{S0(!1),window.removeEventListener("keydown",i,!0)}},[n]),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>a(i=>!i),onBlur:()=>a(!1),className:`min-w-[7.5rem] shrink-0 rounded-xl border px-3 py-1.5 text-xs font-medium tabular-nums transition ${n?"border-blue-400 bg-blue-50 text-blue-600 dark:border-blue-400/60 dark:bg-blue-500/10 dark:text-blue-300":"border-transparent bg-black/[0.04] text-gray-700 hover:bg-black/[0.07] dark:bg-white/[0.06] dark:text-gray-200 dark:hover:bg-white/[0.1]"}`,children:n?"请按下快捷键":e?ww(e,nN):"未设置"}),e!==t&&s.jsx("button",{type:"button",onClick:()=>r(t),className:ch,children:"默认"}),e&&s.jsx("button",{type:"button",onClick:()=>r(""),className:ch,children:"清除"})]})}function Zs(e){if(e<1024)return`${e} B`;const t=["B","KB","MB","GB","TB"],r=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1),n=e/1024**r;return`${n.toFixed(n<10?2:1)} ${t[r]}`}function Pi({rows:e}){return s.jsx("div",{"data-selectable-text":!0,className:"space-y-1.5 rounded-xl bg-black/[0.03] px-3 py-2.5 text-xs leading-relaxed dark:bg-white/[0.04]",children:e.map(([t,r])=>s.jsxs("div",{className:"flex gap-3",children:[s.jsx("span",{className:"shrink-0 text-gray-400 dark:text-gray-500",children:t}),s.jsx("span",{className:"min-w-0 break-all text-gray-600 dark:text-gray-300",children:r})]},t))})}function dh({title:e,items:t}){const r=async()=>{try{await fn(t.map(n=>n.path).join(`
|
|
186
|
+
`)),w.getState().showToast("已复制全部路径","success")}catch(n){w.getState().showToast($r("复制失败",n),"error")}};return s.jsxs("div",{className:"space-y-1.5",children:[s.jsx("div",{className:"text-xs font-medium text-gray-600 dark:text-gray-300",children:e}),s.jsxs("div",{className:"relative overflow-hidden rounded-xl bg-black/[0.03] dark:bg-white/[0.04]",children:[s.jsx("ul",{"data-selectable-text":!0,className:"custom-scrollbar ios-rounded-scroll-fix max-h-48 rounded-xl space-y-2 overflow-y-auto overscroll-contain py-2.5 pl-3 pr-10 text-xs leading-relaxed",children:t.map((n,a)=>s.jsxs("li",{children:[s.jsx("div",{className:"break-all text-gray-600 dark:text-gray-300",children:n.path}),s.jsx("div",{className:"break-all text-gray-400 dark:text-gray-500",children:n.error})]},a))}),s.jsx("button",{type:"button",onClick:()=>void r(),title:"复制全部路径","aria-label":"复制全部路径",className:"absolute right-1.5 top-1.5 rounded-lg p-1.5 text-gray-400 transition hover:bg-black/[0.05] hover:text-gray-600 dark:text-gray-500 dark:hover:bg-white/[0.08] dark:hover:text-gray-200",children:s.jsx(zr,{className:"h-3.5 w-3.5"})})]})]})}function oN(e){const t=w.getState();if(!e.failed.length&&!e.notRemoved.length){t.showToast(`已移动 ${e.moved} 项${e.renamed?`,其中 ${e.renamed} 项因重名改了名`:""}`,"success");return}const r=s.jsxs("div",{className:"space-y-3",children:[e.failed.length>0&&s.jsx(dh,{title:`未移动(${e.failed.length} 项)`,items:e.failed}),e.notRemoved.length>0&&s.jsx(dh,{title:`已复制,原文件未删除(${e.notRemoved.length} 项)`,items:e.notRemoved})]});t.setConfirmDialog({title:"部分文件未移动",message:`已移动 ${e.moved} 项。下面这些文件可能被其他程序占用,关闭后可手动处理。`,content:r,confirmText:"我知道了",showCancel:!1,tone:"warning"})}async function iN(){const e=await YC();if(!(e!=null&&e.previous))return(e==null?void 0:e.path)??null;const t=e.previous,r=w.getState();return t.blocked?(r.setConfirmDialog({title:"原文件未移动",message:`默认保存地址已更改,原地址中的文件保持不动。
|
|
187
|
+
${t.blocked}`,content:s.jsx(Pi,{rows:[["原地址",t.path],["新地址",e.path]]}),confirmText:"我知道了",showCancel:!1}),e.path):(r.setConfirmDialog({title:"迁移原有文件",message:`原地址中还有 **${t.files}** 个文件(${Zs(t.bytes)}),要一起移到新地址吗?`,content:s.jsxs("div",{className:"space-y-3",children:[s.jsx(Pi,{rows:[["原地址",t.path],["新地址",e.path]]}),s.jsxs("p",{className:"text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:[s.jsx("span",{className:"font-medium text-amber-600 dark:text-amber-400",children:"文件夹里的所有内容都会移走"}),",包括与本应用无关的文件。重名的自动加序号,",t.keepSource?"原文件夹会保留。":"原文件夹移空后删除。"]})]}),confirmText:"迁移",cancelText:"不迁移",busyText:"迁移中…",awaitAction:!0,action:async()=>{try{const n=await Ba(()=>VC());return oN(n),!n.failed.length&&!n.notRemoved.length}catch(n){return console.error("迁移原有文件失败:",n),w.getState().showToast(typeof n=="string"?n:"迁移原有文件失败","error"),!0}}}),e.path)}function lN({draft:e,zipDownloadRouteSummary:t,commitSettings:r,onOpenZipDownloadRouteManager:n,toggleTaskCompletionNotification:a}){const o=w(d=>d.showToast),[i,l]=p.useState("");p.useEffect(()=>{De&&ub().then(l).catch(d=>{console.error("读取默认保存地址失败:",d),l(typeof d=="string"?d:"读取失败")})},[]);const c=async()=>{try{const d=await iN();d&&l(d)}catch(d){console.error("更改默认保存地址失败:",d),o(typeof d=="string"?d:"更改默认保存地址失败","error")}},u=async()=>{try{await KC()}catch(d){console.error("打开默认保存地址失败:",d),o(typeof d=="string"?d:"打开默认保存地址失败","error")}},f=async()=>{try{await Wv()}catch(d){console.error("打开日志目录失败:",d),o(typeof d=="string"?d:"打开日志目录失败","error")}};return s.jsxs("div",{className:"space-y-8",children:[s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"输入"}),s.jsxs("div",{className:"hidden sm:block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"任务提交方式"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:e.enterSubmit?"enter":"ctrl-enter",onChange:d=>r({...e,enterSubmit:d==="enter"}),options:[{label:navigator.userAgent.includes("Mac")?"⌘ + Enter":"Ctrl + Enter",value:"ctrl-enter"},{label:"Enter",value:"enter"}],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["选择 ",navigator.userAgent.includes("Mac")?"⌘ + Enter":"Ctrl + Enter"," 时,Enter 换行;选择 Enter 时,Shift + Enter 换行。"]})]}),s.jsxs("div",{className:"sm:hidden",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"任务提交方式"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:e.enterSubmit?"enter":"button",onChange:d=>r({...e,enterSubmit:d==="enter"}),options:[{label:"发送按钮",value:"button"},{label:"回车/发送按钮",value:"enter"}],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"选择回车/发送按钮时,回车可提交;否则仅使用发送按钮提交。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"多提示词批量提交"}),s.jsx("button",{type:"button",onClick:()=>r({...e,showBatchPrompt:!e.showBatchPrompt}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.showBatchPrompt?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.showBatchPrompt,"aria-label":"多提示词批量提交",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.showBatchPrompt?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,首页参数栏会显示“批量”选项,可将空两行分隔的多条提示词一次提交,支持排队或并发执行。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"提交任务后清空输入框"}),s.jsx("button",{type:"button",onClick:()=>r({...e,clearInputAfterSubmit:!e.clearInputAfterSubmit}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.clearInputAfterSubmit?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.clearInputAfterSubmit,"aria-label":"提交任务后清空输入框",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.clearInputAfterSubmit?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,提交成功创建任务时会清空提示词和参考图。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"重启后加载上次的输入框"}),s.jsx("button",{type:"button",onClick:()=>r({...e,persistInputOnRestart:!e.persistInputOnRestart}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.persistInputOnRestart?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.persistInputOnRestart,"aria-label":"重启后加载上次的输入框",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.persistInputOnRestart?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"关闭后,不再持久化提示词和参考图,下次启动会使用空输入框。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"参考图编辑方式"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:e.referenceImageEditAction,onChange:d=>r({...e,referenceImageEditAction:d}),options:[{label:"每次询问",value:"ask"},{label:"画板",value:"sketch"},{label:"遮罩",value:"mask"}],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"控制在参考图预览中点击“编辑图片”时,是每次询问,还是直接用画板标注或添加遮罩。"})]})]}),s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"任务与下载"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"复用配置时临时复用该任务的 API 配置"}),s.jsx("button",{type:"button",onClick:()=>r({...e,reuseTaskApiProfileTemporarily:!e.reuseTaskApiProfileTemporarily}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.reuseTaskApiProfileTemporarily?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.reuseTaskApiProfileTemporarily,"aria-label":"复用配置时临时复用该任务的 API 配置",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.reuseTaskApiProfileTemporarily?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,复用历史任务时会临时使用该任务的 API 配置,找不到该配置时提交会提示;关闭后,会继续使用当前的 API 配置。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"收藏夹页的新任务加入当前收藏夹"}),s.jsx("button",{type:"button",onClick:()=>r({...e,saveTasksToActiveFavoriteCollection:!e.saveTasksToActiveFavoriteCollection}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.saveTasksToActiveFavoriteCollection?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.saveTasksToActiveFavoriteCollection,"aria-label":"收藏夹页的新任务加入当前收藏夹",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.saveTasksToActiveFavoriteCollection?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,在收藏夹页提交或重试出的新任务会自动加入当前收藏夹,重试出的任务同时沿用原任务的收藏夹;在收藏夹总览或“全部收藏”中提交的任务加入默认收藏夹。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"成功任务仍然展示重试按钮"}),s.jsx("button",{type:"button",onClick:()=>r({...e,alwaysShowRetryButton:!e.alwaysShowRetryButton}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.alwaysShowRetryButton?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.alwaysShowRetryButton,"aria-label":"成功任务仍然展示重试按钮",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.alwaysShowRetryButton?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,即使任务成功生成,也会在任务卡片上显示重试按钮。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"重试方式"}),s.jsx("div",{className:"w-32 shrink-0",children:s.jsx(_t,{value:e.retryMode,onChange:d=>r({...e,retryMode:d}),options:[{label:"新建任务",value:"new"},{label:"覆盖失败任务",value:"overwriteFailed"},...e.alwaysShowRetryButton?[{label:"覆盖任何任务",value:"overwriteAll"}]:[]],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"覆盖时保留原任务的创建时间和收藏,清空旧的结果和耗时后重新生成;重试 Agent 对话中的图片卡片时,始终新建任务。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"允许模型改写优化提示词"}),s.jsx("button",{type:"button",onClick:()=>r({...e,allowPromptRewrite:!e.allowPromptRewrite}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.allowPromptRewrite?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.allowPromptRewrite,"aria-label":"允许模型改写优化提示词",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.allowPromptRewrite?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,Codex CLI 兼容模式下的 Image API 请求和所有 Responses API 请求都不再附加防改写提示词,允许模型按服务商策略优化提示词。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"使用压缩包进行的批量下载途径"}),s.jsx("button",{type:"button",onClick:n,className:"shrink-0 rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs font-medium text-gray-700 transition hover:bg-black/[0.07] hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:"管理"})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:t})]}),De&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"文件保存位置"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:e.saveLocationMode,onChange:d=>{ry(),r({...e,saveLocationMode:d})},options:[{label:"每次询问",value:"ask"},{label:"默认地址",value:"default"}],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"下载图片、压缩包和导出备份时,每次选择保存位置,或直接保存到默认保存地址;直接保存时遇到同名文件会自动加序号,不会覆盖。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"默认保存地址"}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[s.jsx("button",{type:"button",onClick:c,className:"shrink-0 rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs font-medium text-gray-700 transition hover:bg-black/[0.07] hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:"更改"}),s.jsx("button",{type:"button",onClick:u,className:"shrink-0 rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs font-medium text-gray-700 transition hover:bg-black/[0.07] hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:"打开"})]})]}),s.jsx("div",{"data-selectable-text":!0,className:"break-all text-xs text-gray-500 dark:text-gray-500",children:i||"读取中…"})]})]})]}),s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"通知"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"任务完成或失败时发送系统通知"}),s.jsx("button",{type:"button",onClick:()=>{a()},className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.taskCompletionNotification?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.taskCompletionNotification,"aria-label":"任务完成或失败时发送系统通知",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.taskCompletionNotification?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:De?"开启后,画廊模式图像生成和 Agent 模式回复结束时(无论成功或失败)都会发送系统通知。如果没有收到通知,请检查 Windows 设置中本应用的通知开关。":"开启后,画廊模式图像生成和 Agent 模式回复结束时(无论成功或失败)都会发送浏览器系统通知。浏览器可能会请求通知权限或默认拒绝,请查看相关提示。"})]})]}),s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"隐私"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"隐私模式快捷键"}),s.jsx(aN,{value:e.privacyModeShortcut,defaultValue:mf,onChange:d=>r({...e,privacyModeShortcut:d})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"按下后关闭所有弹窗,隐藏历史记录、收藏夹和输入框内容,之前任务的通知不再提示;再按一次恢复。点击按钮后按下新组合即可修改。"})]})]}),s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"Agent 对话"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"发送消息后自动滚动到底部"}),s.jsx("button",{type:"button",onClick:()=>r({...e,agentScrollToBottomAfterSubmit:!e.agentScrollToBottomAfterSubmit}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.agentScrollToBottomAfterSubmit?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.agentScrollToBottomAfterSubmit,"aria-label":"发送消息后自动滚动到底部",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.agentScrollToBottomAfterSubmit?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,在 Agent 模式发送消息成功后会自动滚动到对话底部。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"公式输出提示"}),s.jsx("button",{type:"button",onClick:()=>r({...e,agentMathFormattingPrompt:!e.agentMathFormattingPrompt}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.agentMathFormattingPrompt?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.agentMathFormattingPrompt,"aria-label":"公式输出提示",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.agentMathFormattingPrompt?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["开启后,Agent 会被要求使用 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 font-mono text-[0.9em] text-gray-700 dark:bg-white/10 dark:text-gray-200",children:"$...$"})," 和 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 font-mono text-[0.9em] text-gray-700 dark:bg-white/10 dark:text-gray-200",children:"$$...$$"})," 输出数学公式,确保渲染效果正常。"]})]})]}),De&&s.jsx(rN,{}),s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"更新"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"自动检查更新"}),s.jsx("button",{type:"button",onClick:()=>r({...e,autoCheckUpdate:!e.autoCheckUpdate}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.autoCheckUpdate?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.autoCheckUpdate,"aria-label":"自动检查更新",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.autoCheckUpdate?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后,启动时会从 GitHub 获取版本信息,有新版本时在左上角显示 NEW 提示。关闭后可在“关于”中手动检查更新。"})]})]}),De&&s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"诊断"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"写入日志文件"}),s.jsx("button",{type:"button",onClick:()=>r({...e,writeLogFile:!e.writeLogFile}),className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${e.writeLogFile?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.writeLogFile,"aria-label":"写入日志文件",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.writeLogFile?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"记录警告和错误,便于排查问题。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"日志目录"}),s.jsx("button",{type:"button",onClick:f,className:"shrink-0 rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs font-medium text-gray-700 transition hover:bg-black/[0.07] hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:"打开"})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"日志保存在数据目录的 logs 文件夹中,反馈问题时可以附上。"})]})]})]})}const cN={ui:"永和九年,岁在癸丑 The quick brown fox 0123456789",mono:'const value = fn(42) => "你好" // 0O 1lI'};let uh=null;function dN(){return uh??(uh=(async()=>{const e=window.queryLocalFonts;if(typeof e!="function")return[];try{const t=await e();return Array.from(new Set(t.map(r=>r.family))).sort((r,n)=>r.localeCompare(n))}catch(t){return console.warn("读取本机字体失败:",t),[]}})()),uh}function fh({slot:e,label:t,description:r,mode:n,name:a,onChange:o}){const[i,l]=p.useState(a),[c,u]=p.useState([]),[f,d]=p.useState(!1),[g,m]=p.useState(-1),x=p.useRef(null),b=p.useId();p.useEffect(()=>{l(a)},[a]),p.useEffect(()=>{var C,T;(T=(C=x.current)==null?void 0:C.children[g])==null||T.scrollIntoView({block:"nearest"})},[g]);const h=C=>{const T=C.trim();l(T),T!==a&&o(n,T)},y=i.trim().toLowerCase(),v=c.filter(C=>C.toLowerCase().includes(y)),I=f&&v.length>0,S=C=>{h(C),d(!1),m(-1)},k=Gl(e,"default",""),j=["builtin","system","custom"].filter(C=>C!==k.source||C==="custom"),A=C=>({fontFamily:bu(e,C)}),N=n==="custom"?Kh("custom",i,""):Gl(e,n,a);return s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:t}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:n!=="custom"&&n===k.source?"default":n,onChange:C=>o(C,a),options:[{label:nm(k),value:"default",style:A(k)},...j.map(C=>C==="custom"?{label:"自定义",value:C}:{label:nm({source:C}),value:C,style:A({source:C})})],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),n==="custom"&&s.jsxs("div",{className:"relative mb-1.5",children:[s.jsx("input",{value:i,onChange:C=>{l(C.target.value),d(!0),m(-1)},onFocus:()=>{d(!0),dN().then(u)},onBlur:C=>{h(C.target.value),d(!1),m(-1)},onKeyDown:C=>{if((C.key==="ArrowDown"||C.key==="ArrowUp")&&v.length){C.preventDefault(),d(!0),m(T=>C.key==="ArrowDown"?(T+1)%v.length:T<=0?v.length-1:T-1);return}if(C.key==="Enter"){I&&v[g]?S(v[g]):h(C.currentTarget.value),d(!1),m(-1);return}C.key==="Escape"&&I&&(C.stopPropagation(),d(!1),m(-1))},placeholder:"本机已安装的字体名称","aria-label":`${t}名称`,role:"combobox","aria-expanded":I,"aria-autocomplete":"list","aria-controls":b,"aria-activedescendant":I&&g>=0?`${b}-${g}`:void 0,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"}),I&&s.jsx("div",{className:"absolute inset-x-0 top-full z-20 mt-1 overflow-hidden rounded-xl bg-white shadow-lg ring-1 ring-black/5 dark:bg-gray-800 dark:ring-white/10",children:s.jsx("ul",{ref:x,id:b,role:"listbox",className:"custom-scrollbar ios-rounded-scroll-fix max-h-56 overflow-y-auto rounded-xl p-1",children:v.map((C,T)=>s.jsx("li",{id:`${b}-${T}`,role:"option","aria-selected":T===g,onMouseDown:R=>{R.preventDefault(),S(C)},onMouseEnter:()=>m(T),className:`cursor-pointer truncate rounded-lg px-3 py-1.5 text-sm text-gray-700 dark:text-gray-200 ${T===g?"bg-black/[0.05] dark:bg-white/[0.08]":""}`,style:A({source:"custom",name:C}),children:C},C))})})]}),s.jsx("div",{className:"mb-1.5 truncate rounded-xl bg-black/[0.02] px-3 py-2 text-sm text-gray-700 dark:bg-white/[0.03] dark:text-gray-200",style:{fontFamily:bu(e,N)},children:cN[e]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:r})]})}function uN({draft:e,commitSettings:t}){return s.jsxs("div",{className:"space-y-8",children:[s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"颜色"}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"颜色模式"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:e.colorMode,onChange:r=>t({...e,colorMode:r}),options:[{label:"跟随系统",value:"system"},{label:"浅色",value:"light"},{label:"深色",value:"dark"}],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"选择“跟随系统”时,随系统的浅色或深色设置自动切换。"})]})]}),s.jsxs("section",{className:"space-y-4",children:[s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"字体"}),s.jsx(fh,{slot:"ui",label:"界面字体",description:"内置字体为 HarmonyOS Sans SC;选择“系统字体”时使用系统默认的字体。",mode:e.uiFont,name:e.uiFontName,onChange:(r,n)=>t({...e,uiFont:r,uiFontName:n})}),s.jsx(fh,{slot:"mono",label:"代码字体",description:"内置字体为 Maple Mono NF CN,用于代码块。",mode:e.monoFont,name:e.monoFontName,onChange:(r,n)=>t({...e,monoFont:r,monoFontName:n})})]})]})}function fN({draft:e,agentMaxToolRoundsInput:t,agentTextProfileOptions:r,agentImageProfileOptions:n,selectedAgentTextProfile:a,selectedAgentImageProfile:o,setAgentMaxToolRoundsInput:i,updateAgentApiConfigMode:l,commitSettings:c,commitAgentMaxToolRounds:u}){return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"使用独立的 API 配置"}),s.jsx("div",{className:"w-20 shrink-0",children:s.jsx(_t,{value:e.agentApiConfigMode,disabled:xl("apiConfigMode"),onChange:f=>l(f),options:[{label:"关闭",value:"off"},{label:"原生",value:"native"},{label:"混合",value:"hybrid"}],className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500 space-y-1",children:[["apiConfigMode","textProfileId","imageProfileId"].some(xl)&&s.jsx("div",{children:"部分选项由部署配置锁定。"}),s.jsxs("div",{children:["原生:使用原生的 Responses API 配置,由模型调用 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 font-mono text-[10px] dark:bg-white/[0.06]",children:"image_generation"})," 工具生成图片。"]}),s.jsxs("div",{children:["混合:使用非原生的混合 API 配置,由文本模型调用自定义工具,请求图像模型生成图像,解决部分服务商/模型不支持 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 font-mono text-[10px] dark:bg-white/[0.06]",children:"image_generation"})," 工具的问题。"]})]})]}),e.agentApiConfigMode!=="off"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"文本模型 API 配置"}),s.jsx("div",{className:"w-40 shrink-0",children:r.length>0?s.jsx(_t,{value:(a==null?void 0:a.id)??"请选择配置",disabled:xl("textProfileId"),onChange:f=>c({...e,agentTextProfileId:String(f)}),options:r,showValueTooltips:!0,className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"}):s.jsx("div",{className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-center text-xs text-gray-700 transition-all duration-200 dark:bg-white/[0.06] dark:text-gray-200",children:"没有可用配置"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"用于对话和调用工具,仅支持 Responses API 配置。"})]}),e.agentApiConfigMode==="hybrid"&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"图像模型 API 配置"}),s.jsx("div",{className:"w-40 shrink-0",children:n.length>0?s.jsx(_t,{value:(o==null?void 0:o.id)??"请选择配置",disabled:xl("imageProfileId"),onChange:f=>c({...e,agentImageProfileId:String(f)}),options:n,showValueTooltips:!0,className:"w-full px-3 py-1.5 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] hover:bg-black/[0.07] dark:hover:bg-white/[0.1] text-xs transition-all duration-200 text-gray-700 dark:text-gray-200 outline-none"}):s.jsx("div",{className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-center text-xs text-gray-700 transition-all duration-200 dark:bg-white/[0.06] dark:text-gray-200",children:"没有可用配置"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"用于生成图像,支持所有类型的 API 配置。"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"最大工具调用轮数"}),s.jsx("input",{value:t,onChange:f=>i(f.target.value),onBlur:u,type:"number",min:1,max:50,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsx("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs leading-relaxed text-gray-500 dark:text-gray-500",children:"默认 15。用于限制 Agent 连续调用工具时的最大轮数,防止无限循环。"})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"网络搜索"}),s.jsx("button",{type:"button",onClick:()=>{const f=t.trim()===""?Jn:Zl(t,e.agentMaxToolRounds);i(String(f)),c({...e,agentMaxToolRounds:f,agentWebSearch:!e.agentWebSearch})},className:`relative inline-flex h-4 w-7 shrink-0 items-center rounded-full transition-colors ${e.agentWebSearch?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":e.agentWebSearch,"aria-label":"网络搜索",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${e.agentWebSearch?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["启用 Responses API 的 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 font-mono text-[10px] dark:bg-white/[0.06]",children:"web_search"})," 工具。模型每次调用此工具会产生少量固定价格的额外计费。"]})]})]})}const hs="flex h-8 w-8 sm:h-9 sm:w-9 items-center justify-center rounded-xl text-gray-500 transition hover:bg-gray-100 hover:text-gray-800 disabled:pointer-events-none disabled:opacity-30 aria-disabled:pointer-events-none aria-disabled:opacity-30 dark:text-gray-400 dark:hover:bg-white/[0.08] dark:hover:text-gray-100";function fs(e){return`flex h-8 w-8 sm:h-9 sm:w-9 items-center justify-center rounded-xl transition-colors disabled:opacity-40 ${e?"bg-white text-blue-500 shadow-sm dark:bg-white/[0.12] dark:text-blue-400 dark:shadow-none":"text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100"}`}function Dy({onBackdropClick:e,children:t}){return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[80] flex items-center justify-center sm:p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-sm animate-overlay-in",onClick:e}),s.jsx("div",{className:"relative z-10 flex h-full w-full flex-col overflow-hidden bg-white shadow-2xl animate-modal-in dark:bg-gray-900 sm:h-[min(92vh,920px)] sm:max-w-5xl sm:rounded-3xl sm:border sm:border-white/50 sm:ring-1 sm:ring-black/5 sm:dark:border-white/[0.08] sm:dark:ring-white/10",children:t})]})}function Ly({left:e,center:t,right:r}){return s.jsxs("div",{className:"grid flex-none grid-cols-[1fr_auto_1fr] items-center gap-2 px-3 py-3 sm:px-4",children:[s.jsx("div",{className:"flex min-w-0 items-center gap-0.5",children:e}),s.jsx("div",{className:"flex items-center gap-0.5 rounded-2xl bg-gray-100/80 p-1 dark:bg-white/[0.06] sm:gap-1",children:t}),s.jsx("div",{className:"flex min-w-0 items-center justify-end gap-0.5",children:r})]})}function Oy({value:e,min:t,max:r,label:n,displayValue:a=e,disabled:o=!1,onChange:i,onAdjustStart:l,onAdjustEnd:c}){const u=Math.sqrt((e-t)/(r-t)),f=14,d=p.useRef(null),g=h=>{d.current||(d.current=h,l==null||l())},m=h=>{d.current===h&&(d.current=null,c==null||c())},x=h=>{const y=h.currentTarget.getBoundingClientRect(),v=Math.max(0,Math.min(1,1-(h.clientY-y.top-f)/(y.height-f*2)));i(Math.round(t+v*v*(r-t)))},b=h=>{h.currentTarget.hasPointerCapture(h.pointerId)&&(h.currentTarget.releasePointerCapture(h.pointerId),m("pointer"))};return s.jsxs("div",{className:`absolute left-3 top-1/2 z-10 flex -translate-y-1/2 flex-col items-center gap-2 sm:left-5 ${o?"pointer-events-none opacity-40":""}`,children:[s.jsxs("div",{className:"relative h-48 w-9 cursor-ns-resize touch-none select-none rounded-full border border-gray-200/80 bg-white/95 shadow-sm dark:border-white/[0.08] dark:bg-gray-800/95",role:"slider","aria-label":n,"aria-valuemin":t,"aria-valuemax":r,"aria-valuenow":e,"aria-disabled":o,tabIndex:o?-1:0,onKeyDown:h=>{const y=h.key==="ArrowUp"||h.key==="ArrowRight"?1:h.key==="ArrowDown"||h.key==="ArrowLeft"?-1:0;o||!y||(h.preventDefault(),g("key"),i(Math.min(r,Math.max(t,e+y))))},onKeyUp:()=>m("key"),onBlur:()=>m("key"),onMouseDown:h=>{document.activeElement instanceof HTMLTextAreaElement&&h.preventDefault()},onPointerDown:h=>{h.currentTarget.setPointerCapture(h.pointerId),g("pointer"),x(h)},onPointerMove:h=>{h.currentTarget.hasPointerCapture(h.pointerId)&&x(h)},onPointerUp:b,onPointerCancel:b,onLostPointerCapture:()=>m("pointer"),children:[s.jsx("div",{className:"absolute bottom-[14px] left-1/2 top-[14px] w-1 -translate-x-1/2 rounded-full bg-gray-200 dark:bg-white/10"}),s.jsx("div",{className:"absolute left-1/2 h-4 w-4 -translate-x-1/2 translate-y-1/2 rounded-full bg-blue-500 shadow-md ring-2 ring-white dark:ring-gray-800",style:{bottom:`calc(${f}px + (100% - ${f*2}px) * ${u})`}})]}),s.jsx("span",{className:"min-w-[2.5rem] text-center text-sm font-semibold tabular-nums text-gray-600 dark:text-gray-300",children:a})]})}function By({onClick:e}){return s.jsx(Ke,{tooltip:"重置视图",wrapperClassName:"absolute bottom-3 right-3 z-10 inline-flex",className:"flex h-9 w-9 items-center justify-center rounded-full border border-gray-200/80 bg-white/95 text-gray-600 shadow-sm transition hover:text-gray-900 dark:border-white/[0.08] dark:bg-gray-800/95 dark:text-gray-300 dark:hover:text-white",onClick:e,children:s.jsx(gN,{})})}function Uy({x:e,y:t,size:r}){return s.jsxs("div",{className:"pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-1/2",style:{left:e,top:t,width:Math.max(4,r),height:Math.max(4,r)},children:[s.jsx("div",{className:"absolute inset-0 rounded-full border border-white/90 shadow-[0_0_0_1px_rgba(0,0,0,0.4),inset_0_0_0_1px_rgba(0,0,0,0.4)]"}),s.jsx("div",{className:"absolute left-1/2 top-1/2 h-px w-[11px] -translate-x-1/2 -translate-y-1/2 bg-white shadow-[0_0_0_0.5px_rgba(0,0,0,0.55)]"}),s.jsx("div",{className:"absolute left-1/2 top-1/2 h-[11px] w-px -translate-x-1/2 -translate-y-1/2 bg-white shadow-[0_0_0_0.5px_rgba(0,0,0,0.55)]"})]})}function go({children:e,...t}){return s.jsx("svg",{className:"h-5 w-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",...t,children:e})}function Fy(){return s.jsxs(go,{children:[s.jsx("path",{d:"M21.17 6.81a1 1 0 0 0-3.98-3.98L3.84 16.17a2 2 0 0 0-.5.83l-1.32 4.35a.5.5 0 0 0 .62.62l4.35-1.32a2 2 0 0 0 .83-.5z"}),s.jsx("path",{d:"m15 5 4 4"})]})}function $y(){return s.jsx(go,{children:s.jsx("path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21M22 21H7M5 11l9 9"})})}function zy(){return s.jsxs(go,{children:[s.jsx("path",{d:"M9 14 4 9l5-5"}),s.jsx("path",{d:"M4 9h10.5a5.5 5.5 0 0 1 0 11H11"})]})}function Wy(){return s.jsxs(go,{children:[s.jsx("path",{d:"m15 14 5-5-5-5"}),s.jsx("path",{d:"M20 9H9.5a5.5 5.5 0 0 0 0 11H13"})]})}function gN(){return s.jsx(go,{children:s.jsx("path",{d:"M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"})})}function Hy(){return s.jsx(go,{children:s.jsx("path",{d:"M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})})}function Ad(){return s.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2.5,strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"m5 12.5 4.5 4.5L19 7.5"})})}const mN={claude:"Claude Code",agents:"Codex 等"},hN="text-sm font-bold text-gray-800 dark:text-gray-100",pN="text-xs text-gray-500 dark:text-gray-500",xN="overflow-hidden rounded-2xl bg-black/[0.04] divide-y divide-black/[0.05] dark:bg-white/[0.06] dark:divide-white/[0.06]",bN="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white text-gray-600 shadow-sm dark:bg-white/[0.08] dark:text-gray-300 dark:shadow-none max-sm:self-start",gh="mt-0.5 block text-xs text-gray-500 dark:text-gray-400",yN="mt-0.5 block text-xs text-amber-600 dark:text-amber-400/90",cu="rounded-lg bg-white px-3 py-1.5 text-xs font-medium text-gray-700 shadow-sm transition hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white/[0.08] dark:text-gray-200 dark:shadow-none dark:hover:bg-white/[0.12]";function mh({icon:e,title:t,path:r,note:n,warn:a,children:o}){const i=Ot();return s.jsxs("div",{className:"flex min-h-[56px] w-full items-center gap-3 px-4 py-2.5 max-sm:flex-wrap max-sm:gap-y-2",children:[s.jsx("span",{className:bN,children:e}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm text-gray-800 dark:text-gray-100",children:t}),r&&s.jsxs("span",{"data-selectable-text":!0,className:`${gh} truncate max-sm:whitespace-normal max-sm:[overflow-wrap:anywhere]`,...i.handlers,children:[r,s.jsx(pt,{visible:i.visible,className:"max-w-sm break-all",children:r})]}),n&&s.jsx("span",{className:a?yN:gh,children:n})]}),s.jsx("span",{className:"flex flex-shrink-0 items-center gap-1.5 max-sm:basis-full max-sm:justify-end",children:o})]})}function vN(){const e=w(f=>f.showToast),[t,r]=p.useState(null),[n,a]=p.useState(""),[o,i]=p.useState(""),l=p.useCallback(()=>{Nt("skill_info").then(f=>{r(f),a("")},f=>{console.warn("无法读取 Skill 的安装状态:",f),a(typeof f=="string"?f:"无法读取 Skill 的安装状态")})},[]);p.useEffect(l,[l]);const c=(f,d,g,m)=>{i(f),Nt(d,g).then(x=>{r(x),e(m,"success")}).catch(x=>{console.warn(`${d} 失败:`,x),e(typeof x=="string"?x:"操作失败,请重试","error")}).finally(()=>i(""))},u=()=>{Nt("skill_open_dir").catch(f=>{console.warn("打开 Skill 文件夹失败:",f),e(typeof f=="string"?f:"无法打开 Skill 所在的文件夹","error")})};return s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx("h4",{className:hN,children:"Skill"}),s.jsx("p",{"data-selectable-text":!0,className:pN,children:"Skill 为 AI 工具提供 GPT Image Playground CLI 的使用说明,包括何时调用、如何生图与修改设置。Claude Code 读取「~\\.claude\\skills」,Codex 读取「~\\.agents\\skills」,Cursor、VS Code 与 OpenCode 两处都会读取,安装其中一处即可。"}),n&&s.jsx("p",{"data-selectable-text":!0,className:"text-xs text-red-500 dark:text-red-400",children:n})]}),t&&s.jsxs("div",{className:xN,children:[t.skills.map(f=>{const d=`skill-${f.id}`,g=f.state==="outdated"?"与当前版本不一致,需要更新":f.state==="invalid"?"此目录已有另一个名为 gpt-image-playground 的 Skill":void 0;return s.jsxs(mh,{icon:f.id==="claude"?s.jsx(xS,{className:"h-4 w-4"}):s.jsx(bS,{className:"h-4 w-4"}),title:mN[f.id],path:g?void 0:f.path,note:g,warn:!0,children:[f.state==="added"&&s.jsxs("span",{className:"mr-1 inline-flex items-center gap-1 text-xs text-green-600 dark:text-green-400 [&_svg]:h-3.5 [&_svg]:w-3.5",children:[s.jsx(Ad,{}),"已安装"]}),(f.state==="absent"||f.state==="outdated")&&s.jsx("button",{type:"button",className:cu,disabled:o===d,onClick:()=>c(d,"skill_install",{target:f.id},f.state==="absent"?"已安装":"已更新"),children:f.state==="absent"?"安装":"更新"}),(f.state==="added"||f.state==="outdated")&&s.jsx("button",{type:"button",className:cu,disabled:o===d,onClick:()=>c(d,"skill_remove",{target:f.id},"已移除"),children:"移除"})]},f.id)}),s.jsx(mh,{icon:s.jsx(yS,{className:"h-4 w-4"}),title:"Skill 文件夹",path:t.skillDir,children:s.jsx("button",{type:"button",className:cu,onClick:u,children:"打开"})})]})]})}function wN({scrollBoundaryRef:e,onClose:t}){const[r,n]=p.useState(null),[a,o]=p.useState(!1);return p.useEffect(()=>{aa(()=>import("./third-party-notices-wN73bzzx.js"),[],import.meta.url).then(i=>n(i.default)).catch(i=>{console.error("加载第三方许可清单失败",i),o(!0)})},[]),lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[110] flex items-center justify-center p-4",onClick:t,children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 w-full max-w-2xl rounded-3xl bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] ring-1 ring-black/5 dark:ring-white/10 animate-confirm-in flex flex-col max-h-[85vh] sm:max-h-[90vh]",onClick:i=>i.stopPropagation(),children:[s.jsx("div",{className:"shrink-0 p-6 pb-2",children:s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("h3",{className:"text-base font-bold text-gray-800 dark:text-gray-100",children:"第三方许可"}),s.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})})]})}),s.jsx("div",{ref:e,className:"flex-1 overflow-y-auto px-6 pb-6 pt-2 custom-scrollbar min-h-0",children:r===null?s.jsx("div",{className:"py-8 text-center text-sm text-gray-500 dark:text-gray-400",children:a?"许可清单加载失败,请刷新页面后重试":"正在加载…"}):s.jsx("pre",{"data-selectable-text":!0,className:"whitespace-pre-wrap break-words rounded-xl bg-black/[0.04] p-3 font-mono text-[11px] leading-relaxed text-gray-600 dark:bg-white/[0.06] dark:text-gray-300",children:r})})]})]}),document.body)}function kN({editing:e,json:t,error:r,isImportingJson:n,scrollBoundaryRef:a,onClose:o,onCopyLlmPrompt:i,onImportJson:l,onJsonChange:c,onSave:u}){const f=p.useRef(null),[d,g]=p.useState(!1),m=()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)};return p.useEffect(()=>()=>m(),[]),lr.createPortal(s.jsxs("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in",onClick:o}),s.jsxs("div",{className:"relative z-10 w-full max-w-md rounded-3xl border border-white/50 bg-white/95 p-5 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex flex-col h-[85vh] sm:h-[680px] max-h-[90vh] overflow-hidden",children:[s.jsxs("div",{className:"mb-5 flex items-center justify-between gap-4 shrink-0",children:[s.jsx("h3",{className:"text-base font-bold text-gray-800 dark:text-gray-100",children:e?"编辑自定义服务商":"创建自定义服务商"}),s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("button",{type:"button",onClick:o,className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})})})]}),s.jsxs("div",{ref:a,className:"flex-1 flex flex-col min-h-0 px-1 -mx-1 pb-2",children:[s.jsxs("div",{className:"mb-6 shrink-0 rounded-2xl bg-black/[0.04] p-4 border border-transparent dark:bg-white/[0.06]",children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5 text-sm font-medium text-gray-800 dark:text-gray-200",children:[s.jsx("svg",{className:"h-4 w-4 text-blue-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),"AI 一键生成与导入"]}),s.jsx("div",{"data-selectable-text":!0,className:"mb-4 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:"复制提示词发给 LLM,可根据 API 文档自动生成完整的配置(包含服务商、模型、URL 等)。复制 LLM 输出的 JSON 后,点击“从剪贴板粘贴并导入”即可一键生效。"}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"relative inline-flex",children:[s.jsxs("button",{type:"button",onClick:i,"aria-label":"复制用于生成完整导入 JSON 的 LLM 提示词",onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),onFocus:()=>g(!0),onBlur:()=>g(!1),onTouchStart:()=>{m(),f.current=window.setTimeout(()=>{g(!0),f.current=null},450)},onTouchEnd:m,onTouchCancel:m,className:"flex items-center gap-1.5 rounded-xl bg-black/[0.04] px-3 py-2 text-xs font-medium text-gray-700 border border-transparent transition hover:bg-black/[0.07] hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:[s.jsx(ma,{className:"h-3.5 w-3.5"}),"复制生成提示词"]}),s.jsx(pt,{visible:d,className:"w-56 whitespace-normal text-center",children:"生成完整的服务商和配置信息,包含模型和接口地址,导入后只需填入 API Key。"})]}),s.jsx("button",{type:"button",onClick:l,disabled:n,className:"flex items-center gap-1.5 rounded-xl bg-black/[0.04] px-3 py-2 text-xs font-medium text-gray-700 border border-transparent transition hover:bg-black/[0.07] hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white",children:n?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"w-3.5 h-3.5 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"导入中..."]}):"从剪贴板粘贴并导入"})]})]}),s.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:s.jsxs("label",{className:"flex-1 flex flex-col min-h-0",children:[s.jsx("span",{className:"mb-1 shrink-0 block text-xs text-gray-500 dark:text-gray-400",children:"手动编辑 (仅接口映射 Manifest)"}),s.jsx("textarea",{value:t,onChange:x=>c(x.target.value),spellCheck:!1,className:"flex-1 min-h-[150px] w-full resize-none rounded-xl border border-transparent bg-black/[0.04] px-3 py-2 font-mono text-xs leading-relaxed text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50 custom-scrollbar"})]})}),r&&s.jsx("div",{"data-selectable-text":!0,className:"shrink-0 mt-2 rounded-lg bg-red-50 px-3 py-2 text-xs text-red-500 dark:bg-red-500/10 dark:text-red-300",children:r})]}),s.jsxs("div",{className:"mt-4 flex justify-end gap-2 shrink-0",children:[s.jsx("button",{type:"button",onClick:o,className:"rounded-xl bg-gray-100 px-4 py-2 text-sm text-gray-600 transition hover:bg-gray-200 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1]",children:"取消"}),s.jsx("button",{type:"button",onClick:u,className:"rounded-xl bg-blue-500 px-4 py-2 text-sm font-medium text-white transition hover:bg-blue-600",children:e?"保存修改":"创建并使用"})]})]})]}),document.body)}function IN({profile:e,options:t,onOptionsChange:r,onCopy:n,onClose:a}){return lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[110] flex items-center justify-center p-4",onClick:a,children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{className:"relative bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] rounded-3xl shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] max-w-sm w-full p-6 z-10 ring-1 ring-black/5 dark:ring-white/10 animate-confirm-in",onClick:o=>o.stopPropagation(),children:[s.jsx("button",{type:"button",onClick:a,className:"absolute right-4 top-4 shrink-0 rounded-full p-1.5 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})}),s.jsxs("h3",{className:"mb-3 pr-8 flex items-start gap-2.5 text-base font-bold text-gray-800 dark:text-gray-100 leading-snug",children:[s.jsx(zr,{className:"h-5 w-5 shrink-0 text-blue-500 mt-0.5"}),s.jsxs("span",{children:["复制导入配置「",e.name,"」的 URL"]})]}),s.jsx("div",{className:"text-[13px] text-gray-500 dark:text-gray-400 mb-5 leading-relaxed",children:"是否包含 API Key?如果选择「不包含」,可额外配置是否使用 New API 变量。"}),s.jsxs("div",{className:"mb-6 rounded-2xl bg-gray-50/80 p-4 dark:bg-white/[0.03] ring-1 ring-black/5 dark:ring-white/5",children:[s.jsx("div",{className:"text-[13px] font-bold text-gray-700 dark:text-gray-300 mb-3.5",children:"New API 变量配置"}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(en,{checked:t.useNewApiAddress,onChange:o=>r({useNewApiAddress:o}),label:s.jsxs(s.Fragment,{children:["使用 ",s.jsx("code",{className:"mx-0.5 rounded bg-gray-100 px-1.5 py-0.5 text-[0.85em] font-mono text-gray-700 dark:bg-white/[0.08] dark:text-gray-200",children:"{address}"})," (不含 /v1)"]})}),s.jsx(en,{checked:t.useNewApiKey,onChange:o=>r({useNewApiKey:o}),label:s.jsxs(s.Fragment,{children:["使用 ",s.jsx("code",{className:"mx-0.5 rounded bg-gray-100 px-1.5 py-0.5 text-[0.85em] font-mono text-gray-700 dark:bg-white/[0.08] dark:text-gray-200",children:"{key}"})]})}),s.jsx(en,{checked:t.useNewApiModel,onChange:o=>r({useNewApiModel:o}),label:s.jsxs(s.Fragment,{children:["使用 ",s.jsx("code",{className:"mx-0.5 rounded bg-gray-100 px-1.5 py-0.5 text-[0.85em] font-mono text-gray-700 dark:bg-white/[0.08] dark:text-gray-200",children:"{model}"})]})})]})]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:()=>n(!1),className:"flex-1 py-2 rounded-xl border border-transparent dark:bg-white/[0.06] text-sm text-gray-600 dark:text-gray-400 hover:bg-black/[0.07] dark:hover:bg-white/[0.1] transition",children:"不包含"}),s.jsx("button",{onClick:()=>n(!0),className:"flex-1 py-2 rounded-xl bg-blue-500 text-white text-sm font-medium hover:bg-blue-600 transition shadow-sm shadow-blue-500/20",children:"包含 API Key"})]})]})]}),document.body)}const Yy=[{route:"task-selection",label:"任务列表 > 多选",description:"主页或收藏夹详情中框选、Ctrl/⌘ 点选或移动端滑动选中任务后的“下载选中”。"},{route:"favorite-collection-selection",label:"收藏夹列表 > 多选",description:"收藏夹概览页选中一个或多个收藏夹后的“下载选中”。"},{route:"image-context-menu-all",label:"图片右键菜单 > 下载全部",description:"右键图片时下载同一组输出图片。"},{route:"task-detail-all",label:"任务详情 > 下载全部",description:"任务详情弹窗中下载当前任务的所有输出图。"},{route:"task-detail-partial",label:"任务详情 > 下载中间步骤图",description:"任务详情弹窗中下载流式生成保留的中间步骤图。"},{route:"agent-round-all",label:"Agent 对话轮次 > 下载所有图片",description:"Agent 对话中下载某轮回复关联的全部图片。"}];function CN({routes:e,scrollBoundaryRef:t,onSetEnabled:r,onClose:n}){return lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[110] flex items-center justify-center p-4",onClick:n,children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 w-full max-w-md rounded-3xl bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] ring-1 ring-black/5 dark:ring-white/10 animate-confirm-in flex flex-col max-h-[85vh] sm:max-h-[90vh]",onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"shrink-0 p-6 pb-2",children:[s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[s.jsx("h3",{className:"text-base font-bold text-gray-800 dark:text-gray-100",children:"使用压缩包进行批量下载"}),s.jsx("button",{type:"button",onClick:n,className:"shrink-0 rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-sm leading-relaxed text-gray-500 dark:text-gray-400",children:"开启后,在对应途径进行批量下载时会将结果下载为一个 ZIP,而不是多个图片文件。"})]}),s.jsx("div",{ref:t,className:"flex-1 overflow-y-auto px-6 space-y-3 custom-scrollbar min-h-0 py-2",children:Yy.map(a=>{const o=e.includes(a.route);return s.jsxs("div",{role:"checkbox","aria-checked":o,tabIndex:0,onClick:()=>r(a.route,!o),onKeyDown:i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),r(a.route,!o))},className:`cursor-pointer rounded-2xl border p-3.5 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/20 ${o?"border-transparent bg-blue-50 dark:bg-blue-500/[0.1]":"border-transparent bg-black/[0.04] hover:bg-black/[0.07] dark:bg-white/[0.06] dark:hover:bg-white/[0.08]"}`,children:[s.jsx("div",{onClick:i=>i.stopPropagation(),children:s.jsx(en,{checked:o,onChange:i=>r(a.route,i),label:s.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-200",children:a.label})})}),s.jsx("div",{"data-selectable-text":!0,className:"mt-1.5 pl-6 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:a.description})]},a.route)})}),s.jsx("div",{className:"shrink-0 p-6 pt-4 flex gap-2",children:s.jsx("button",{type:"button",onClick:n,className:"flex-1 rounded-xl bg-blue-500 py-2 text-sm font-medium text-white transition hover:bg-blue-600",children:"完成"})})]})]}),document.body)}function jN(){const e=w(u=>u.showToast),t=w(u=>u.setConfirmDialog),[r,n]=p.useState(null),[a,o]=p.useState("");p.useEffect(()=>{Hv().then(n).catch(u=>{console.error("读取存储信息失败:",u),o(u instanceof Error?u.message:String(u))})},[]);const i=async()=>{try{await Yv()}catch(u){console.error("打开数据目录失败:",u),e(u instanceof Error?u.message:"打开数据目录失败","error")}},l=async()=>{const u=await Vv().catch(f=>(console.error("选择数据目录失败:",f),t({title:"无法使用该目录",message:f instanceof Error?f.message:String(f),confirmText:"我知道了",showCancel:!1}),null));if(u){if(u.blocked){t({title:"无法使用该目录",message:u.blocked,content:s.jsx(Pi,{rows:[["当前目录",u.from],["所选目录",u.to]]}),confirmText:"我知道了",showCancel:!1});return}t({title:"更改数据目录",message:`将 **${u.files}** 个文件(${Zs(u.bytes)})复制到新目录,然后重启客户端。`,content:s.jsxs("div",{className:"space-y-3",children:[s.jsx(Pi,{rows:[["原目录",u.from],["新目录",u.to]]}),s.jsx("p",{className:"text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:"完成后会删除原目录。正在生成的任务会中断。"})]}),confirmText:"重启并更改",busyText:"正在重启…",awaitAction:!0,action:async()=>{try{return await Kv(),await Xv(),!1}catch(f){return console.error("更改数据目录失败:",f),e(f instanceof Error?f.message:"更改数据目录失败","error"),!0}}})}},c=r?[["数据库",Zs(r.dbBytes)],["原图",`${Zs(r.imageBytes)}(${r.imageCount} 张)`],["缩略图",Zs(r.thumbnailBytes)]]:[];return s.jsxs("div",{className:"rounded-2xl border border-transparent bg-black/[0.04] p-4 dark:bg-white/[0.06] space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("svg",{className:"w-4 h-4 text-gray-700 dark:text-gray-300",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"})}),s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"本地存储"})]}),a?s.jsx("p",{className:"text-xs text-red-500 dark:text-red-400 break-all",children:a}):s.jsxs("div",{className:"space-y-2 text-xs text-gray-500 dark:text-gray-400",children:[s.jsxs("div",{className:"break-all",children:[s.jsx("span",{className:"text-gray-600 dark:text-gray-300",children:"数据目录:"}),s.jsx("span",{className:"select-text",children:(r==null?void 0:r.dataDir)??"读取中…"}),r&&s.jsx("button",{type:"button",onClick:i,title:"打开数据目录","aria-label":"打开数据目录",className:"ml-1 inline-flex align-[-2px] text-gray-400 transition hover:text-blue-500 dark:text-gray-500 dark:hover:text-blue-400",children:s.jsx(Sg,{className:"h-3.5 w-3.5"})})]}),c.length>0?s.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-1",children:c.map(([u,f])=>s.jsxs("span",{children:[s.jsxs("span",{className:"text-gray-600 dark:text-gray-300",children:[u,":"]}),f]},u))}):s.jsx("div",{children:"正在统计占用空间…"})]}),s.jsx("button",{onClick:l,className:"w-full rounded-xl bg-gray-100/80 px-4 py-2.5 text-sm font-medium text-gray-700 transition-all hover:bg-gray-200 hover:text-gray-900 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white flex items-center justify-center gap-2",children:"更改数据目录"})]})}function $s({icon:e,title:t,subtitle:r,right:n,href:a,onClick:o,disabled:i,highlight:l}){const c=`flex min-h-[56px] w-full items-center gap-3 px-4 py-2.5 text-left outline-none transition-colors disabled:cursor-default ${l?"bg-blue-500/[0.08] hover:bg-blue-500/[0.12] focus-visible:bg-blue-500/[0.12] dark:bg-blue-500/[0.12] dark:hover:bg-blue-500/[0.16] dark:focus-visible:bg-blue-500/[0.16]":"hover:bg-black/[0.03] focus-visible:bg-black/[0.03] dark:hover:bg-white/[0.04] dark:focus-visible:bg-white/[0.04]"}`,u=s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${l?"bg-blue-500 text-white":"bg-white text-gray-600 shadow-sm dark:bg-white/[0.08] dark:text-gray-300 dark:shadow-none"}`,children:e}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:`block text-sm ${l?"font-medium text-blue-600 dark:text-blue-400":"text-gray-800 dark:text-gray-100"}`,children:t}),r&&s.jsx("span",{className:"mt-0.5 block text-xs text-gray-500 dark:text-gray-400",children:r})]}),n]});return a?s.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",className:c,children:u}):s.jsx("button",{type:"button",onClick:o,disabled:i,className:c,children:u})}function hh({icon:e,title:t,children:r}){return s.jsxs("div",{className:"overflow-hidden rounded-2xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06]",children:[s.jsxs("div",{className:"flex items-center gap-2 px-4 pb-1 pt-4 text-gray-700 dark:text-gray-300",children:[e,s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:t})]}),s.jsx("div",{className:"divide-y divide-black/[0.05] dark:divide-white/[0.06]",children:r})]})}const ph=s.jsx(jg,{className:"h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500"}),du=s.jsx(Sg,{className:"h-4 w-4 shrink-0 text-gray-400 dark:text-gray-500"});function SN({onOpenFontLicenses:e}){const t=w(u=>u.showToast),r=er(u=>u.releases[0]),n=er(u=>u.checkError),[a,o]=p.useState(!1),i=async()=>{o(!0);try{const u=await Tc(Xb);u&&Cs(u.version,"0.8.4")>0?Fa(!0):t("已是最新版本","success")}catch(u){t(`检查更新失败:${u instanceof Error?u.message:String(u)}`,"error")}finally{o(!1)}},l=!!(r&&Cs(r.version,"0.8.4")>0),c=a?s.jsx("span",{className:"shrink-0 text-xs text-gray-500 dark:text-gray-400",children:"正在检查…"}):n?s.jsx("span",{className:"shrink-0 text-xs text-red-500 dark:text-red-400",children:"检查失败"}):r?s.jsx("span",{className:"shrink-0 text-xs text-gray-500 dark:text-gray-400",children:"已是最新版本"}):null;return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-4 rounded-2xl border border-transparent bg-black/[0.04] p-4 dark:bg-white/[0.06]",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h4",{className:"text-base font-bold text-gray-800 dark:text-gray-100",children:s.jsx("a",{href:"https://github.com/CookSleep/gpt_image_playground",target:"_blank",rel:"noopener noreferrer",className:"rounded outline-none underline-offset-2 hover:underline focus-visible:underline focus-visible:ring-2 focus-visible:ring-blue-500/40",children:"GPT Image Playground"})}),s.jsx("p",{className:"mt-0.5 text-[13px] text-gray-500 dark:text-gray-400",children:s.jsx("a",{href:"https://github.com/CookSleep",target:"_blank",rel:"noopener noreferrer",className:"rounded outline-none underline-offset-2 transition-colors hover:text-gray-700 hover:underline focus-visible:text-gray-700 focus-visible:underline focus-visible:ring-2 focus-visible:ring-blue-500/40 dark:hover:text-gray-200 dark:focus-visible:text-gray-200",children:"@CookSleep"})}),s.jsx("p",{"data-selectable-text":!0,className:"mt-3 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:"本项目的成长离不开每一位用户的使用、反馈、贡献与支持,感谢一路有你。"})]}),s.jsx("a",{href:"https://github.com/CookSleep/gpt_image_playground",target:"_blank",rel:"noopener noreferrer","aria-label":"GitHub 仓库",title:"GitHub 仓库",className:"shrink-0 rounded-lg p-1 text-gray-400 outline-none transition-colors hover:text-gray-700 focus-visible:text-gray-700 focus-visible:ring-2 focus-visible:ring-blue-500/40 dark:text-gray-500 dark:hover:text-gray-200 dark:focus-visible:text-gray-200",children:s.jsx(lS,{className:"h-6 w-6"})})]}),s.jsxs(hh,{icon:s.jsx(Go,{className:"h-4 w-4"}),title:"版本与更新",children:[l&&!a?s.jsx($s,{highlight:!0,icon:s.jsx(Go,{className:"h-4 w-4"}),title:"发现新版本",subtitle:"当前版本 v0.8.4",onClick:()=>Fa(!0),right:s.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("span",{className:"rounded-full bg-blue-500 px-2 py-0.5 text-xs font-medium text-white",children:r==null?void 0:r.tag}),s.jsx(jg,{className:"h-4 w-4 text-blue-500 dark:text-blue-400"})]})}):s.jsx($s,{icon:s.jsx(Go,{className:`h-4 w-4 ${a?"animate-spin":""}`}),title:"检查更新",subtitle:n&&!a?n:"当前版本 v0.8.4",onClick:()=>void i(),disabled:a,right:c}),s.jsx($s,{icon:s.jsx(fy,{className:"h-4 w-4"}),title:"更新日志",onClick:()=>Fa(!0),right:ph})]}),s.jsxs(hh,{icon:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"})}),title:"支持与反馈",children:[s.jsx($s,{icon:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"})}),title:"反馈问题",href:"https://github.com/CookSleep/gpt_image_playground/issues",right:du}),s.jsx($s,{icon:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"})}),title:"赞助作者",href:"https://www.ifdian.net/a/cooksleep",right:du})]}),s.jsxs("div",{className:"divide-y divide-black/[0.05] overflow-hidden rounded-2xl border border-transparent bg-black/[0.04] dark:divide-white/[0.06] dark:bg-white/[0.06]",children:[s.jsx($s,{icon:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"})}),title:"开源协议",subtitle:"本软件以 MIT 协议开源",href:R5,right:du}),s.jsx($s,{icon:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),title:"第三方许可",subtitle:"本软件使用的字体与依赖库的许可",onClick:e,right:ph})]})]})}const xh="__add_custom_provider__",Vy="gpt-image-playground.copy-import-url-options",Tl={useNewApiAddress:!1,useNewApiKey:!0,useNewApiModel:!1};function bh(){if(typeof window>"u")return Tl;try{const e=window.localStorage.getItem(Vy);if(!e)return Tl;const t=JSON.parse(e);return!t||typeof t!="object"?Tl:{useNewApiAddress:!!t.useNewApiAddress,useNewApiKey:t.useNewApiKey===void 0?!0:!!t.useNewApiKey,useNewApiModel:!!t.useNewApiModel}}catch{return Tl}}function NN(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Vy,JSON.stringify({useNewApiAddress:e.useNewApiAddress,useNewApiKey:e.useNewApiKey,useNewApiModel:e.useNewApiModel}))}catch{}}function AN(e){const t=In({id:e.id,name:"新配置"});return e.name==="新配置"&&e.provider==="openai"&&e.baseUrl===sr.baseUrl&&e.apiKey===""&&e.model===ir&&e.imageGenerationModel===ir&&e.timeout===sr.timeout&&e.apiMode==="images"&&e.reasoningEffort===void 0&&e.codexCli===!1&&e.apiProxy===t.apiProxy&&e.streamImages===t.streamImages&&e.streamPartialImages===t.streamPartialImages&&e.transparentBackgroundMethod===t.transparentBackgroundMethod}function PN(e,t,r){const n=r.profiles.map(a=>np(e,a,r.customProviders)).find(a=>a!=null&&t.has(a.id));return n||(e.profiles.find(a=>!t.has(a.id))??e.profiles[0])}function TN(){const e=w(M=>M.showSettings),t=w(M=>M.settingsTabRequest),r=w(M=>M.setShowSettings),n=w(M=>M.settings),a=w(M=>M.setSettings),o=w(M=>M.dismissPresetProfile),i=w(M=>M.dismissPresetProvider),l=w(M=>M.restorePresetProvider),c=w(M=>M.reusedTaskApiProfileId),u=w(M=>M.setReusedTaskApiProfile),f=w(M=>M.setConfirmDialog),d=w(M=>M.showToast),g=w(M=>Zf(M.tasks,M.agentConversations)),m=p.useRef(null),x=p.useRef(null),b=p.useRef(null),h=p.useRef(0),y=p.useRef(null),v=p.useRef(null),I=p.useRef(null),S=p.useRef(null),k=p.useRef(null),j=p.useRef(null),A=p.useRef(null),N=p.useRef({}),[C,T]=p.useState(Me(n)),[R,U]=p.useState(String(zt(n).timeout)),[W,F]=p.useState(String(n.agentMaxToolRounds)),[_,O]=p.useState(!1),[J,H]=p.useState(!1),[K,te]=p.useState(Mc),[P,B]=p.useState(!1),[$,Q]=p.useState(!1),[L,G]=p.useState(!1),[se,Y]=p.useState(null),[le,ie]=p.useState(lh),[D,ue]=p.useState(null),[ke,we]=p.useState(!1),[We,Ne]=p.useState(!1),[Fe,Ee]=p.useState("api"),[Ge,Xe]=p.useState(!0),[ht,Pe]=p.useState(!0),[ne,ge]=p.useState(!0),[xe,fe]=p.useState(!0),[be,Z]=p.useState(!0),[de,he]=p.useState(!0),pe=Ma(M=>M.mode),Be=pe==="export",Oe=pe==="import",[Ue,lt]=p.useState(!1),[ut,Ve]=p.useState(null),[He,vt]=p.useState(null),[ct,rt]=p.useState(null),[V,X]=p.useState(null),me=p.useRef(null),[ve,ae]=p.useState(null),[_e,Ye]=p.useState(bh),wt=sn(),xt=Oc(wt),qe=uf(wt),tt=Cn(),Pt=Fi(),Ct=Bn(),Ht=tt?C.profiles.filter(M=>Ct.has(M.id)):C.profiles,Dt=tt&&Ht.length<=1,Tt=Fc()??Uc(C),Ce=C.profiles.find(M=>M.id===C.activeProfileId)??C.profiles[0]??zt(C),Or=Xw(Ce.id),nt=zc(Ce.id),tr=ei(C,Ce.provider),Le=tr||Ce.provider==="fal",gt=Rn(C,Ce.provider),Ut=!gt||Ei(gt),jr=Vl(C,Ce),rr=Ay(gt),Ft=jr&&(qe||Ce.apiProxy),Sr=xt&&jr&&Ft,Jt=["openai","sb2api-async","fal",...C.customProviders.map(M=>M.id)],cr=C.providerOrder||Jt,jn=[{label:"OpenAI 兼容接口",value:"openai",draggable:!0},{label:"sub2api(异步)",value:"sb2api-async",draggable:!0},{label:"fal.ai",value:"fal",draggable:!0},...C.customProviders.map(M=>{const ye=[...!tt&&!_l(M.id)?[{label:"编辑",onClick:()=>Rd(M)}]:[],...!tt&&!ni(M.id,C.profiles)?[{label:"删除",variant:"danger",onClick:()=>Dd(M)}]:[]];return{label:M.name,value:M.id,draggable:!0,actions:ye.length?ye:void 0}})],Xr=[...!tt&&!nt?[{label:"创建自定义服务商",value:xh,variant:"action"}]:[],...jn.sort((M,ye)=>{const Re=cr.indexOf(String(M.value)),Se=cr.indexOf(String(ye.value)),ot=Re!==-1?Re:Jt.indexOf(String(M.value)),st=Se!==-1?Se:Jt.indexOf(String(ye.value));return ot-st})],Mt=Yy.filter(M=>C.zipDownloadRoutes.includes(M.route)).length,os=Mt?`已开启 ${Mt} 项使用压缩包进行批量下载的途径`:"未开启任何使用压缩包进行批量下载的途径",Nr=(tt?Ht:C.profiles).filter(M=>M.apiKey.trim()?M.baseUrl.trim()||M.provider==="fal"?!0:xt&&Vl(C,M)&&(qe||M.apiProxy):!1),Ar=Nr.filter(Oa),an=Ar.find(M=>M.id===C.agentTextProfileId)??null,oe=Nr.find(M=>M.id===C.agentImageProfileId)??null,Te=Ar.map(M=>({label:`${M.name} · ${M.model||Wa}`,value:M.id})),Qe=Nr.map(M=>({label:`${M.name} · ${Ys(C,M.provider)} · ${M.model}`,value:M.id})),z=p.useRef(null);p.useEffect(()=>{if(!e){z.current=null,N.current={};return}if(z.current===n)return;z.current=n;const M=Me(n),ye=M.reuseTaskApiProfileTemporarily&&c&&M.profiles.some(Se=>Se.id===c)?Me({...M,activeProfileId:c}):M,Re=Me({...ye,profiles:ye.profiles.map(Se=>({...Se,apiProxy:Vl(ye,Se)&&xt?qe||Se.apiProxy:De&&Se.apiProxy}))});T(Re),U(String(zt(Re).timeout)),F(String(Re.agentMaxToolRounds))},[xt,qe,e,n,c]),p.useEffect(()=>{U(String(Ce.timeout))},[Ce.id,Ce.timeout]),p.useEffect(()=>{T(M=>M.saveLocationMode===n.saveLocationMode?M:{...M,saveLocationMode:n.saveLocationMode})},[n.saveLocationMode]),p.useEffect(()=>{e&&t&&Ee(t)},[t,e]),p.useLayoutEffect(()=>{A.current&&(A.current.scrollTop=N.current[Fe]??0)},[Fe,e]);const ee=p.useCallback(()=>{b.current&&te(US(b.current))},[]);p.useEffect(()=>{if(!J)return;const M=ye=>{var Re;(Re=x.current)!=null&&Re.contains(ye.target)||H(!1)};return ee(),document.addEventListener("pointerdown",M),window.addEventListener("resize",ee),window.addEventListener("scroll",ee,!0),()=>{document.removeEventListener("pointerdown",M),window.removeEventListener("resize",ee),window.removeEventListener("scroll",ee,!0)}},[J,ee]),p.useEffect(()=>()=>{y.current!=null&&window.clearTimeout(y.current),v.current!=null&&window.clearTimeout(v.current)},[]),p.useEffect(()=>{if(!V)return;const M=ot=>{ot.preventDefault()},ye={passive:!1,capture:!0},Re=document.body.style.overflow,Se=document.body.style.overscrollBehavior;return document.body.style.overflow="hidden",document.body.style.overscrollBehavior="none",window.addEventListener("touchmove",M,ye),()=>{document.body.style.overflow=Re,document.body.style.overscrollBehavior=Se,window.removeEventListener("touchmove",M,ye)}},[V]);const re=()=>{y.current!=null&&(window.clearTimeout(y.current),y.current=null)},Ae=()=>{v.current!=null&&(window.clearTimeout(v.current),v.current=null)},$e=M=>{a(Py(M)),z.current=w.getState().settings,T(z.current)},dt=(M,ye)=>{const Re=ye?Array.from(new Set([...C.zipDownloadRoutes,M])):C.zipDownloadRoutes.filter(Se=>Se!==M);$e({...C,zipDownloadRoutes:Re})},Je=M=>{Ye(ye=>{const Re={...ye,...M};return NN(Re),Re})},It=(M,ye)=>{var ot;const Re=I5(De,window.location.href),Se=new URL(Re);if(Se.search="",Se.hash="",M.provider==="openai"){const st=M.baseUrl.trim()||sr.baseUrl;Se.searchParams.set("apiUrl",ye.useNewApiAddress&&!ye.includeApiKey?"{address}":Tn(st)),ye.includeApiKey&&M.apiKey.trim()?Se.searchParams.set("apiKey",M.apiKey.trim()):!ye.includeApiKey&&ye.useNewApiKey&&Se.searchParams.set("apiKey","{key}"),Se.searchParams.set("apiMode",M.apiMode);const Gt=M.model.trim()||nf(M.apiMode);Se.searchParams.set("model",!ye.includeApiKey&&ye.useNewApiModel?"{model}":Gt),M.apiMode==="responses"&&Se.searchParams.set("imageGenerationModel",((ot=M.imageGenerationModel)==null?void 0:ot.trim())??""),M.name.trim()&&Se.searchParams.set("profileName",M.name.trim()),M.reasoningEffort&&Se.searchParams.set("reasoningEffort",M.reasoningEffort),M.codexCli&&Se.searchParams.set("codexCli","true"),M.streamImages!==sr.streamImages&&Se.searchParams.set("streamImages",String(!!M.streamImages)),M.streamPartialImages!==kr&&Se.searchParams.set("streamPartialImages",String(Yr(M.streamPartialImages))),M.transparentBackgroundMethod!=="api"&&Se.searchParams.set("transparentBackgroundMethod",M.transparentBackgroundMethod);let at=Se.toString();return ye.includeApiKey||(ye.useNewApiAddress&&(at=at.replace("%7Baddress%7D","{address}")),ye.useNewApiKey&&(at=at.replace("%7Bkey%7D","{key}")),ye.useNewApiModel&&(at=at.replace("%7Bmodel%7D","{model}"))),at}return Z4(Re,M,C.customProviders.find(st=>st.id===M.provider),ye)},it=async(M,ye)=>{try{const Re=It(M,ye);await fn(Re),zl.add(Re);const Se=ye.includeApiKey?"导入 URL 已复制(包含 API Key)":"导入 URL 已复制";d(De?`${Se},在其他设备的客户端中复制此链接后切回客户端即可导入`:Se,"success"),ae(null)}catch(Re){d($r("复制导入 URL 失败",Re),"error")}},Yt=M=>{H(!1),we(!1),ae(M),Ye(bh())},ft=M=>({...C,profiles:C.profiles.map(ye=>ye.id===Ce.id?{...ye,...M}:ye)}),At=(M,ye=!1)=>{if(nt&&(Object.keys(M).length!==1||M.apiKey===void 0))return;const Re=ft(M);T(Re),ye&&$e(Re)},Ps=M=>{if(nt&&(Object.keys(M).length!==1||M.apiKey===void 0))return;const ye=ft(M);$e(ye)},mo=()=>{if(Be||Oe){ls();return}if($){Q(!1);return}if(L){G(!1);return}const M=Number(R),ye=R.trim()===""||Number.isNaN(M)?sr.timeout:M,Re=W.trim()===""?Jn:Zl(W,C.agentMaxToolRounds),Se={...C,agentMaxToolRounds:Re,profiles:tr&&!nt?C.profiles.map(ot=>ot.id===Ce.id?{...ot,timeout:ye}:ot):C.profiles};F(String(Re)),$e(Se),r(!1)},is=p.useCallback(()=>{if(nt||!ei(C,Ce.provider))return;const M=Number(R),ye=R.trim()===""?sr.timeout:Number.isNaN(M)?Ce.timeout:M;U(String(ye)),At({timeout:ye},!0)},[C,Ce.id,Ce.provider,Ce.timeout,nt,R]),dr=p.useCallback(()=>{const M=W.trim()===""?Jn:Zl(W,C.agentMaxToolRounds);F(String(M)),M!==C.agentMaxToolRounds&&$e({...C,agentMaxToolRounds:M})},[W,C]),ho=M=>{M.reason==="unsupported"?d(De?"当前环境不支持系统通知":"当前浏览器不支持系统通知","error"):M.reason==="insecure"?d("系统通知需要 HTTPS 或 localhost 安全上下文","error"):M.reason==="denied"?d(De?"通知权限已被拒绝,请在 Windows 设置的「通知」中允许本应用发送通知":"通知权限已被浏览器拒绝,请在地址栏左侧的网站设置中手动开启","error"):d("没有开启系统通知","info")},Br=async()=>{if(C.taskCompletionNotification){$e({...C,taskCompletionNotification:!1});return}const M=await bx();M.ok?($e({...C,taskCompletionNotification:!0}),d("任务通知已开启","success")):ho(M)},ls=()=>{const M=Date.now();M-h.current<1e3||(h.current=M,d(pe==="export"?"正在导出":"正在导入","info"))};p.useEffect(()=>{if(h.current=0,!pe)return;document.activeElement instanceof HTMLElement&&document.activeElement.blur();const M=ye=>{ye.preventDefault(),ye.stopImmediatePropagation(),ls()};return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[pe,d]);const Ts=M=>{pe&&(M.preventDefault(),M.stopPropagation(),ls())},cs=M=>{pe&&(M.preventDefault(),M.stopPropagation())};Kr(e&&!pe,mo);const Td=er(M=>M.modalOpen);if(Lr(e,Td?Bo:$?k:L?j:P?S:I),!e)return null;const po=async()=>{if(ht&&g){d("有任务正在进行,完成或停止后再导出","error");return}Ma.setState({mode:"export"});try{await Ba(()=>e5({exportConfig:Ge,exportTasks:ht}))}finally{Ma.setState({mode:null})}},nl=async M=>{const ye=Array.from(M.target.files??[]);if(ye.length){if(xe&&g){d("有任务正在进行,完成或停止后再导入","error"),M.target.value="";return}Ma.setState({mode:"import"});try{if(await Ba(()=>r5(ye,{importConfig:tt?!1:ne,importTasks:xe}))){const Se=Me(w.getState().settings);T(Se),U(String(zt(Se).timeout)),H(!1)}}finally{Ma.setState({mode:null})}}M.target.value=""},sl=async()=>{await Ba(()=>Gj({clearConfig:be,clearTasks:de}));const M=Me(w.getState().settings);T(M),U(String(zt(M).timeout)),H(!1)},al=()=>{if(tt)return;u(null);const M=In({id:_c("openai"),name:"新配置"}),ye=Me({...C,profiles:[...C.profiles,M],activeProfileId:M.id});$e(ye),H(!1)},ka=M=>{var ye,Re,Se,ot;$e({...C,agentApiConfigMode:M,agentTextProfileId:M!=="off"?(an==null?void 0:an.id)??((ye=Ar.find(st=>st.id===Ce.id))==null?void 0:ye.id)??((Re=Ar[0])==null?void 0:Re.id)??C.agentTextProfileId:C.agentTextProfileId,agentImageProfileId:M==="hybrid"?(oe==null?void 0:oe.id)??((Se=Nr.find(st=>st.id===Ce.id))==null?void 0:Se.id)??((ot=Nr[0])==null?void 0:ot.id)??C.agentImageProfileId:C.agentImageProfileId})},ol=()=>{if(tt)return;u(null),Ne(!1);const M={...Ce,id:_c(Ce.provider==="openai"?"openai":"profile"),isDefault:void 0,name:`${Ce.name}(复制)`},ye=Me({...C,profiles:[...C.profiles,M],activeProfileId:M.id});$e(ye),H(!1)},Ms=M=>{if(tt&&!Ct.has(M))return;u(null);const ye=Me({...C,activeProfileId:M});$e(ye),H(!1)},Lg=(M,ye)=>{tt||(Ve(ye),M.dataTransfer.effectAllowed="move",M.dataTransfer.setData("text/plain",ye))},Un=(M,ye)=>{M.preventDefault(),M.dataTransfer.dropEffect="move";const Re=M.currentTarget,Se=Re.getBoundingClientRect(),ot=M.clientY>=Se.top+Se.height/2?"after":"before";(He!==ye||ct!==ot)&&(vt(ye),rt(ot));const st=Re.closest(".custom-scrollbar");if(st){const Gt=st.getBoundingClientRect(),at=30;M.clientY<Gt.top+at?st.scrollTop-=10:M.clientY>Gt.bottom-at&&(st.scrollTop+=10)}},$t=()=>{Ve(null),vt(null),rt(null),X(null),me.current=null},xo=(M,ye,Re)=>{if(tt||!M||M===ye)return;const Se=C.profiles.findIndex(Vt=>Vt.id===M),ot=C.profiles.findIndex(Vt=>Vt.id===ye);if(Se<0||ot<0)return;const st=[...C.profiles],[Gt]=st.splice(Se,1);let at=ot;Re==="after"&&at++,Se<ot&&at--,st.splice(at,0,Gt);const hr=Me({...C,profiles:st});$e(hr)},bo=(M,ye)=>{M.preventDefault(),xo(M.dataTransfer.getData("text/plain"),ye,ct),$t()},il=(M,ye)=>{if(tt||!M.target.closest("[data-drag-handle]"))return;const Re=M.touches[0],Se=M.currentTarget.getBoundingClientRect();M.preventDefault(),M.stopPropagation(),me.current={id:ye.id,startX:Re.clientX,startY:Re.clientY,moved:!1},Ve(ye.id),X({label:ye.name,providerLabel:Ys(C,ye.provider),x:Re.clientX,y:Re.clientY,width:Se.width,height:Se.height,offsetX:Re.clientX-Se.left,offsetY:Re.clientY-Se.top})},Md=M=>{const ye=me.current;if(!ye)return;const Re=M.touches[0];if(!ye.moved)if(Math.abs(Re.clientX-ye.startX)>5||Math.abs(Re.clientY-ye.startY)>5)ye.moved=!0;else return;M.preventDefault(),X(Vt=>Vt&&{...Vt,x:Re.clientX,y:Re.clientY});const Se=document.elementFromPoint(Re.clientX,Re.clientY),ot=Se==null?void 0:Se.closest("[data-profile-id]");if(!ot)return;const st=ot.getAttribute("data-profile-id");if(!st)return;const Gt=ot.getBoundingClientRect(),at=Re.clientY>=Gt.top+Gt.height/2?"after":"before";vt(st),rt(at);const hr=ot.closest(".custom-scrollbar");if(hr){const Vt=hr.getBoundingClientRect(),qr=30;Re.clientY<Vt.top+qr?hr.scrollTop-=10:Re.clientY>Vt.bottom-qr&&(hr.scrollTop+=10)}},ll=M=>{const ye=me.current;ye&&(ye.moved&&He&&He!==ye.id&&(M.preventDefault(),xo(ye.id,He,ct)),$t())},on=M=>{Ty(C,M)||(M===c&&u(null),Ct.has(M)&&o(M),$e(My(C,M)))},Es=(M,ye,Re)=>{const Se=C.providerOrder||["openai","sb2api-async","fal",...C.customProviders.map(qr=>qr.id)],ot=Se.indexOf(String(M)),st=Se.indexOf(String(ye));if(ot<0||st<0)return;const Gt=[...Se],[at]=Gt.splice(ot,1);let hr=st;Re==="after"&&hr++,ot<st&&hr--,Gt.splice(hr,0,at);const Vt=Me({...C,providerOrder:Gt});$e(Vt)},cl=M=>{if(tt||nt)return;if(M===xh){Y(null),ie(lh),B(!0),ue(null);return}const ye=String(M),Re=Rn(C,ye)??void 0;At(ec(Ce,ye,Re),!0)},Ed=()=>{B(!1),Y(null)},dl=()=>_y(JSON.parse(le),C.customProviders,se);function Rd(M){tt||_l(M.id)||(Y(M.id),ie(JSON.stringify({name:M.name,submit:M.submit,editSubmit:M.editSubmit,poll:M.poll},null,2)),B(!0),ue(null))}const _d=()=>{if(!(tt||se&&_l(se)))try{const M=dl();if(se){const Se=Me({...C,customProviders:C.customProviders.map(ot=>ot.id===se?M:ot)});$e(Se),B(!1),Y(null),ue(null),d("服务商配置已更新","success");return}const ye=ec(Ce,M.id,M),Re=Me({...C,customProviders:[...C.customProviders,M],profiles:C.profiles.map(Se=>Se.id===Ce.id?ye:Se)});l(M.id),$e(Re),B(!1),Y(null),ue(null)}catch(M){ue(M instanceof Error?M.message:String(M))}};function Dd(M){tt||ni(M.id,C.profiles)||f({title:"删除服务商",message:`确定要删除自定义服务商「${M.name}」吗?正在使用它的配置会切回 OpenAI 兼容接口。`,action:()=>Ia(M)})}function Ia(M){Ey(C,M.id)||($c(M.id)&&i(M.id),$e(Ry(C,M.id)),d("服务商已删除","success"))}const ul=async()=>{try{await fn(tN),d("LLM 生成提示词已复制","success")}catch(M){d($r("复制 LLM 生成提示词失败",M),"error")}},yo=async()=>{lt(!0);try{const M=De?await Hb().catch(()=>""):await navigator.clipboard.readText();if(!M.trim())throw new Error("剪贴板为空");const ye=vf(M,C.customProviders);if(ye.profiles.length>0){const Se=new Set(C.profiles.map(qr=>qr.id)),ot=kf(C,ye),st=PN(ot,Se,ye),Gt=Se.has(st.id),at=!se&&AN(Ce)&&!Gt,hr=!at&&Gt,Vt=Me(at?{...ot,profiles:ot.profiles.filter(qr=>qr.id!==Ce.id),activeProfileId:st.id}:{...ot,activeProfileId:st.id});for(const qr of ye.customProviders)l(qr.id);T(Vt),a(Vt),U(String(zt(Vt).timeout)),B(!1),Y(null),ue(null),d(at?"已覆盖当前空配置":hr?"已存在相同配置,已切换到已有配置":"JSON 配置已导入并切换","success");return}const Re=ye.customProviders[0];ie(JSON.stringify({name:Re.name,submit:Re.submit,editSubmit:Re.editSubmit,poll:Re.poll},null,2)),ue(null),d("JSON 配置已导入","success")}catch(M){const ye=M instanceof Error?M.message:String(M);ue(null),M instanceof Error&&M.name==="NotAllowedError"?d("无法读取剪贴板,请允许浏览器访问剪贴板,或直接粘贴到输入框中","error"):d(ye,"error")}finally{lt(!1)}};return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",onPointerDownCapture:Ts,onClickCapture:cs,onContextMenuCapture:Ts,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in",onClick:mo}),s.jsxs("div",{ref:I,className:"relative z-10 w-full max-w-3xl rounded-3xl border border-white/50 bg-white/95 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex h-[85vh] sm:h-[600px] flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between shrink-0 p-5 border-b border-gray-100 dark:border-white/[0.08]",children:[s.jsxs("h3",{className:"text-lg font-bold text-gray-800 dark:text-gray-100 flex items-center gap-2",children:[s.jsxs("svg",{className:"w-5 h-5 text-blue-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),"设置"]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"text-sm text-gray-400 dark:text-gray-500 font-mono select-none",children:["v","0.8.4"]}),s.jsx("button",{onClick:mo,className:"rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})})]})]}),s.jsxs("div",{className:"flex flex-1 min-h-0 flex-col sm:flex-row",children:[s.jsx("div",{className:"w-full sm:w-48 shrink-0 flex flex-col border-b sm:border-b-0 sm:border-r border-gray-100 dark:border-white/[0.08] bg-gray-50/50 dark:bg-white/[0.02]",children:s.jsxs("nav",{className:"flex-1 overflow-x-auto sm:overflow-y-auto custom-scrollbar p-3 space-x-1 sm:space-x-0 sm:space-y-1 flex sm:flex-col",children:[s.jsxs("button",{onClick:()=>Ee("api"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${Fe==="api"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"})}),"API 配置"]}),s.jsxs("button",{onClick:()=>Ee("general"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${Fe==="general"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 6v6l4 2m6-2a10 10 0 11-20 0 10 10 0 0120 0z"})}),"习惯配置"]}),s.jsxs("button",{onClick:()=>Ee("appearance"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${Fe==="appearance"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01"})}),"外观配置"]}),s.jsxs("button",{onClick:()=>Ee("agent"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${Fe==="agent"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8V4H8"}),s.jsx("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2}),s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2 14h2M20 14h2M15 13v2M9 13v2"})]}),"Agent 配置"]}),De&&s.jsxs("button",{onClick:()=>Ee("skill"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${Fe==="skill"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx(pS,{className:"w-4 h-4"}),"Skill"]}),s.jsxs("button",{onClick:()=>Ee("data"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${Fe==="data"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4"})}),"数据管理"]}),s.jsxs("button",{onClick:()=>Ee("about"),className:`whitespace-nowrap flex-shrink-0 flex items-center gap-2.5 px-3 py-2.5 text-sm rounded-xl transition-colors ${Fe==="about"?"bg-white dark:bg-white/[0.08] shadow-sm text-blue-600 dark:text-blue-400 font-medium":"text-gray-600 dark:text-gray-400 hover:bg-gray-100/80 dark:hover:bg-white/[0.04]"}`,children:[s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"关于"]})]})}),s.jsx("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 bg-transparent relative overflow-hidden",children:s.jsxs("div",{ref:A,onScroll:M=>{N.current[Fe]=M.currentTarget.scrollTop},className:"flex-1 overflow-y-auto overscroll-contain custom-scrollbar p-5 [scrollbar-gutter:stable_both-edges] sm:p-6",children:[Fe==="general"&&s.jsx(lN,{draft:C,zipDownloadRouteSummary:os,commitSettings:$e,onOpenZipDownloadRouteManager:()=>Q(!0),toggleTaskCompletionNotification:Br}),Fe==="appearance"&&s.jsx(uN,{draft:C,commitSettings:$e}),Fe==="agent"&&s.jsx(fN,{draft:C,agentMaxToolRoundsInput:W,agentTextProfileOptions:Te,agentImageProfileOptions:Qe,selectedAgentTextProfile:an,selectedAgentImageProfile:oe,setAgentMaxToolRoundsInput:F,updateAgentApiConfigMode:ka,commitSettings:$e,commitAgentMaxToolRounds:dr}),Fe==="api"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"当前配置"}),s.jsxs("span",{className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:()=>Yt(Ce),onMouseEnter:()=>we(!0),onMouseLeave:()=>we(!1),onFocus:()=>we(!0),onBlur:()=>we(!1),onTouchStart:()=>{re(),y.current=window.setTimeout(()=>{we(!0),y.current=null},450)},onTouchEnd:re,onTouchCancel:re,className:"flex h-5 w-5 items-center justify-center rounded-md text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":`复制导入配置「${Ce.name}」的 URL`,children:s.jsx(ma,{className:"h-3.5 w-3.5"})}),s.jsx(pt,{visible:ke,className:"whitespace-nowrap",children:"复制导入 URL"})]}),!tt&&s.jsxs("span",{className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:ol,onMouseEnter:()=>Ne(!0),onMouseLeave:()=>Ne(!1),onFocus:()=>Ne(!0),onBlur:()=>Ne(!1),onTouchStart:()=>{Ae(),v.current=window.setTimeout(()=>{Ne(!0),v.current=null},450)},onTouchEnd:Ae,onTouchCancel:Ae,className:"flex h-5 w-5 items-center justify-center rounded-md text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":`复制一份配置「${Ce.name}」`,children:s.jsx(zr,{className:"h-3.5 w-3.5"})}),s.jsx(pt,{visible:We,className:"whitespace-nowrap",children:"复制当前配置"})]})]}),s.jsxs("div",{ref:x,className:"relative",children:[s.jsxs("button",{ref:b,type:"button",onClick:()=>{Dt||(J||ee(),H(!J))},disabled:Dt,className:`flex w-full min-w-0 items-center justify-between gap-2 rounded-xl border border-transparent bg-black/[0.04] px-3 py-2 text-sm text-gray-700 outline-none transition dark:bg-white/[0.06] dark:text-gray-200 ${Dt?"cursor-not-allowed opacity-70":"hover:bg-gray-50 dark:hover:bg-white/[0.1]"}`,title:Ce.name,children:[s.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("span",{className:"min-w-0 truncate",children:Ce.name}),s.jsx("span",{className:"shrink-0 rounded bg-blue-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-600 dark:bg-blue-500/10 dark:text-blue-400",children:Ys(C,Ce.provider)})]}),s.jsx(Nd,{className:`w-3.5 h-3.5 flex-shrink-0 text-gray-400 dark:text-gray-500 transition-transform duration-200 ${J?"rotate-180":""}`})]}),J&&!Dt&&s.jsx(s.Fragment,{children:s.jsx("div",{className:`absolute right-0 top-full z-50 mt-1.5 w-full animate-dropdown-down ${my}`,style:{maxHeight:K},children:s.jsxs("div",{className:hy,children:[!tt&&s.jsxs("button",{type:"button",onClick:M=>{M.preventDefault(),al()},className:"flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-2 text-left text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-500/10",children:[s.jsx("span",{className:"truncate font-semibold",children:"创建新配置"}),s.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:s.jsx(cy,{className:"h-4 w-4"})})]}),s.jsx("div",{children:Ht.map(M=>{const ye=M.id===Tt,Re=Ct.has(M.id);return s.jsxs("div",{"data-profile-id":M.id,title:M.name,draggable:!tt,onDragStart:Se=>Lg(Se,M.id),onDragOver:Se=>Un(Se,M.id),onDrop:Se=>bo(Se,M.id),onDragEnd:$t,onTouchStart:Se=>il(Se,M),onTouchMove:Md,onTouchEnd:ll,onTouchCancel:$t,onClick:Se=>{Se.target.closest("[data-drag-handle]")||(Se.preventDefault(),Ms(M.id))},className:`relative group flex w-full cursor-pointer items-center justify-between px-3 py-2 text-left text-xs transition-colors ${ut===M.id?"opacity-40 bg-gray-100 dark:bg-white/[0.04]":M.id===Ce.id?"bg-black/[0.05] font-medium text-blue-600 dark:bg-white/[0.08] dark:text-blue-400":"text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-white/[0.06]"}`,children:[He===M.id&&ct==="before"&&ut!==M.id&&s.jsx("div",{className:"absolute -top-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),He===M.id&&ct==="after"&&ut!==M.id&&s.jsx("div",{className:"absolute -bottom-[1px] left-0 right-0 h-[2px] bg-blue-500 rounded-full z-40 shadow-sm pointer-events-none"}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[!tt&&s.jsx("div",{"data-drag-handle":!0,className:"flex cursor-grab active:cursor-grabbing items-center justify-center text-gray-400 opacity-60 transition-opacity hover:opacity-100 dark:text-gray-500",style:{touchAction:"none"},title:"拖拽排序",children:s.jsx(no,{className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"min-w-0 truncate",children:M.name}),s.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] shrink-0 ${M.id===Ce.id?"bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300":"bg-gray-100 text-gray-500 dark:bg-white/[0.08] dark:text-gray-400"}`,children:Ys(C,M.provider)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx("button",{type:"button",onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),Yt(M)},className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-400 opacity-60 transition-all hover:bg-gray-100 hover:text-gray-600 hover:opacity-100 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":`复制导入配置「${M.name}」的 URL`,title:"复制导入 URL",children:s.jsx(ma,{className:"h-3.5 w-3.5"})}),!tt&&(ye||C.profiles.length>1)&&s.jsx(Ke,{tooltip:Re&&Pt?"预置配置不可删除":"删除配置",disabled:Re&&Pt,showOnClick:Re&&Pt,stopPropagation:!0,onClick:Se=>{Se.preventDefault(),f({title:"删除配置",message:`确定要删除配置「${M.name}」吗?`,action:()=>on(M.id)})},wrapperClassName:"relative flex h-5 w-5 shrink-0",className:`flex h-5 w-5 shrink-0 items-center justify-center rounded opacity-60 transition-all ${Re&&Pt?"cursor-not-allowed text-gray-300 dark:text-gray-600":"text-gray-400 hover:bg-red-500/[0.1] hover:text-red-600 hover:opacity-100 dark:hover:bg-red-500/[0.16]"}`,children:s.jsx(_r,{className:"h-3.5 w-3.5"})})]})]},M.id)})})]})})})]}),Or&&s.jsxs("div",{"data-selectable-text":!0,className:"mt-2.5 flex items-start gap-3 rounded-xl border border-transparent bg-black/[0.04] px-3.5 py-3 text-sm leading-6 text-gray-600 dark:bg-white/[0.06] dark:text-gray-300",children:[s.jsx("svg",{className:"mt-0.5 h-5 w-5 shrink-0 text-blue-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsx(Ai,{content:Or,className:"min-w-0 flex-1"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"配置名称"}),s.jsx("input",{value:Ce.name,onChange:M=>At({name:M.target.value}),onBlur:M=>Ps({name:M.target.value}),type:"text",disabled:nt,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"})]}),s.jsxs("div",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"服务商类型"}),s.jsx(_t,{value:Ce.provider,onChange:cl,onReorder:Es,options:Xr,disabled:tt||nt,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"})]}),Le&&s.jsxs("label",{className:"block",children:[s.jsx("div",{className:"mb-1.5 flex items-center justify-between",children:s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"API URL"})}),s.jsx("input",{value:Ce.baseUrl,onChange:M=>At({baseUrl:M.target.value}),onBlur:M=>Ps({baseUrl:M.target.value}),type:"text",disabled:Sr||nt,placeholder:Ce.provider==="fal"?Gn:sr.baseUrl,className:`w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50 ${Sr?"opacity-50 cursor-not-allowed":""}`}),s.jsx("div",{"data-selectable-text":!0,className:"mt-1.5 min-h-[22px] flex items-center text-xs text-gray-500 dark:text-gray-500",children:Sr?s.jsx("span",{className:"text-yellow-600 dark:text-yellow-500",children:"已开启代理,实际请求目标由部署端决定,此处设置被忽略。"}):Ce.provider==="fal"?s.jsxs("span",{children:["默认使用 ",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:Gn}),";填写自定义地址时将作为 fal.ai 代理 URL。"]}):s.jsxs("span",{children:["末尾带 ",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"/"})," 时直接使用该地址拼接接口,不补 ",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"/v1"})," 前缀;支持通过链接参数导入(打开时会先确认):",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"?apiUrl="}),"。"]})})]}),xt&&tr&&!rr&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"API 代理"}),s.jsx("button",{type:"button",onClick:()=>{!qe&&!nt&&At({apiProxy:!Ce.apiProxy},!0)},disabled:qe||nt,className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${Ft?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"} ${qe?"cursor-not-allowed opacity-70":""}`,role:"switch","aria-checked":Ft,"aria-label":"API 代理",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${Ft?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:qe?"部署端已锁定代理开启,请求经服务器转发到上游 API,上方 URL 设置将失效。":"开启后请求经服务器转发到上游 API,可绕过浏览器跨域限制,上方 URL 设置将失效。"})]}),s.jsxs("div",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"API Key"}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{value:Ce.apiKey,onChange:M=>At({apiKey:M.target.value}),onBlur:M=>Ps({apiKey:M.target.value}),type:_?"text":"password",placeholder:Ce.provider==="fal"?"FAL_KEY":"sk-...",className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 pr-10 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsx("button",{type:"button",onClick:()=>O(M=>!M),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 transition-colors",tabIndex:-1,children:_?s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}):s.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:["支持通过链接参数导入:",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"?apiKey="})]})]}),Ce.provider==="openai"&&s.jsxs("div",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"API 接口"}),s.jsx(_t,{value:Ce.apiMode??sr.apiMode,onChange:M=>{At({apiMode:M},!0)},options:[{label:"Images API (/v1/images)",value:"images"},{label:"Responses API (/v1/responses)",value:"responses"}],disabled:nt,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:["支持通过链接参数导入:",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"apiMode=images"})," 或 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"apiMode=responses"}),"。"]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"模型 ID"}),s.jsx("input",{value:Ce.model,onChange:M=>At({model:M.target.value}),onBlur:M=>Ps({model:M.target.value}),type:"text",disabled:nt,placeholder:Ce.provider==="fal"?_i:nf(Ce.apiMode??sr.apiMode),className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:[Ce.provider==="fal"?s.jsxs(s.Fragment,{children:["当前支持:",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"openai/gpt-image-2"})," ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"openai/gpt-image-2.5/sunburst"})," ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"openai/gpt-image-2.5/flare"}),"。"]}):gt?s.jsxs(s.Fragment,{children:["当前使用 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:gt.name}),"。"]}):(Ce.apiMode??sr.apiMode)==="responses"?s.jsxs(s.Fragment,{children:["Responses API 需要使用支持 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"image_generation"})," 工具的文本模型,例如 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:Wa}),"。"]}):s.jsxs(s.Fragment,{children:["Images API 需要使用 GPT Image 模型,例如 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:ir}),"。"]}),"多个模型以逗号分隔,可在首页的模型参数中切换。",Ce.provider==="openai"&&s.jsxs(s.Fragment,{children:["支持通过链接参数导入:",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"?model="}),"。"]})]})]}),Ce.provider==="openai"&&Ce.apiMode==="responses"&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"图像生成模型"}),s.jsx("input",{value:Ce.imageGenerationModel??"",onChange:M=>At({imageGenerationModel:M.target.value}),onBlur:M=>Ps({imageGenerationModel:M.target.value}),type:"text",disabled:nt,placeholder:ir,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:["Responses API 的 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"image_generation"})," 工具需要使用 GPT Image 模型,例如 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:ir}),"。 留空时不发送工具模型 ID,保持 API 默认值。 支持通过链接参数导入:",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"?imageGenerationModel="}),"。"]})]}),(Ce.apiMode??sr.apiMode)==="responses"&&Ce.provider==="openai"&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"推理强度"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:Ce.reasoningEffort??"",onChange:M=>At({reasoningEffort:M||void 0},!0),options:[{label:"默认",value:""},...Wh.map(M=>({label:M,value:M}))],disabled:nt,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"mt-1.5 text-xs text-gray-500 dark:text-gray-500",children:["用于指导模型在执行任务时的思考深度,更高的档位会使模型花费更长时间进行思考,有助于提升 Agent 模式下模型完成复杂任务的能力。并非所有模型都支持全部推理强度。支持通过链接参数导入:",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"?reasoningEffort=high"}),"。"]})]}),Ce.provider==="openai"&&s.jsxs("div",{className:"block space-y-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"流式传输"}),s.jsx("button",{type:"button",onClick:()=>At({streamImages:!Ce.streamImages},!0),disabled:nt,className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${Ce.streamImages?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":!!Ce.streamImages,"aria-label":"流式传输",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${Ce.streamImages?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:"开启后请求以流式传输,并非所有服务商和网关都支持此功能。官方接口在流式模式下不发送心跳,需要配合请求中间步骤图像来维持连接,避免超时断开。官方接口仅支持单图流式传输,因此数量大于 1 时会将多图生成拆分为并发单图。"})]}),s.jsxs("div",{className:`block ${Ce.streamImages?"":"opacity-60"}`,children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"请求中间步骤图像数"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:Yr(Ce.streamPartialImages),onChange:M=>At({streamPartialImages:Yr(M)},!0),disabled:!Ce.streamImages||nt,options:[{label:"0,不请求",value:0},{label:"1 张",value:1},{label:"2 张",value:2},{label:"3 张",value:3}],className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["对应 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"partial_images"})," 参数(0-3)。建议设为 2 或 3 以避免长时间生成时连接超时断开。实际返回的每张中间图像会产生少量额外计费。设为 0 时不请求中间步骤图像,连接可能因无数据传输而被断开。"]})]})]}),s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between gap-3",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"透明背景实现方式"}),s.jsx("div",{className:"w-28 shrink-0",children:s.jsx(_t,{value:Ce.transparentBackgroundMethod,onChange:M=>At({transparentBackgroundMethod:M},!0),options:[{label:"API 原生",value:"api"},{label:"本地后处理",value:"local"}],disabled:nt||!Ut,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-1.5 text-xs text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"})})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:Ut?`API 原生会请求接口直接生成透明背景,需当前接口支持;本地后处理会生成纯色背景并在${De?"本地":"浏览器中"}去除。`:s.jsxs(s.Fragment,{children:["当前自定义服务商 Manifest 未映射 ",s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 dark:bg-white/[0.06]",children:"$params.background"}),",无法使用 API 原生透明背景。"]})})]}),tr&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"返回 Base64 图片数据"}),s.jsx("button",{type:"button",onClick:()=>At({responseFormatB64Json:!Ce.responseFormatB64Json},!0),disabled:nt,className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${Ce.responseFormatB64Json?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":!!Ce.responseFormatB64Json,"aria-label":"返回 Base64 图片数据",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${Ce.responseFormatB64Json?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["开启后在请求体中追加 ",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"response_format: b64_json"}),",使接口直接返回 Base64 编码的图片数据而非 URL。并非所有服务商和网关都支持此功能。"]})]}),tr&&s.jsxs("div",{className:"block",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("span",{className:"block text-sm text-gray-600 dark:text-gray-300",children:"Codex CLI 兼容模式"}),s.jsx("button",{type:"button",onClick:()=>At({codexCli:!Ce.codexCli},!0),disabled:nt,className:`relative inline-flex h-4 w-7 items-center rounded-full transition-colors ${Ce.codexCli?"bg-blue-500":"bg-gray-300 dark:bg-gray-600"}`,role:"switch","aria-checked":Ce.codexCli,"aria-label":"Codex CLI 兼容模式",children:s.jsx("span",{className:`inline-block h-3 w-3 transform rounded-full bg-white shadow transition-transform ${Ce.codexCli?"translate-x-[14px]":"translate-x-[2px]"}`})})]}),s.jsxs("div",{"data-selectable-text":!0,className:"text-xs text-gray-500 dark:text-gray-500",children:["开启后应用 Codex CLI 实际支持的参数。支持通过链接参数导入:",s.jsx("code",{className:"bg-gray-100 dark:bg-white/[0.06] px-1 py-0.5 rounded",children:"codexCli=true"}),"。"]})]}),tr&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1.5 block text-sm text-gray-600 dark:text-gray-300",children:"请求超时 (秒)"}),s.jsx("input",{value:R,onChange:M=>U(M.target.value),onBlur:is,type:"number",disabled:nt,min:10,max:600,className:"w-full rounded-xl border border-transparent bg-black/[0.04] px-3 py-2.5 text-sm text-gray-700 outline-none transition focus:border-blue-300 dark:bg-white/[0.06] dark:text-gray-200 dark:focus:border-blue-500/50"})]})]}),Fe==="data"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-2xl bg-black/[0.04] p-4 border border-transparent dark:bg-white/[0.06] flex items-start gap-3",children:[s.jsx("svg",{className:"w-5 h-5 text-blue-500 shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})}),s.jsx("div",{className:"text-[13px] leading-relaxed text-gray-500 dark:text-gray-400",children:De?"所有的配置、任务和生成的图片均仅保存在本机的数据目录中(除非您使用的服务商存储了它们)。如果您需要更换安装位置或使用其他设备,请先导出备份。":"所有的配置、任务和生成的图片均仅保存在您的浏览器本地(除非您使用的服务商存储了它们)。如果您需要清理浏览器站点数据、重置浏览器或使用其他设备,请先导出备份。"})]}),De&&s.jsx(jN,{}),s.jsxs("div",{className:"rounded-2xl border border-transparent bg-black/[0.04] p-4 dark:bg-white/[0.06] space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(oS,{className:"w-4 h-4 text-gray-700 dark:text-gray-300"}),s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"导出数据"})]}),s.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:De?`受文件大小限制,过大的备份将自动分卷,${C.saveLocationMode==="default"?"全部分卷保存到默认保存地址":"导出时选择一个文件夹保存全部分卷"}`:"受浏览器文件大小限制,过大的备份将自动分卷导出,请允许浏览器下载多个文件"}),s.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[s.jsx(en,{checked:Ge,onChange:Xe,label:"包含配置"}),s.jsx(en,{checked:ht,onChange:Pe,label:"包含任务和图片"})]}),s.jsx("button",{onClick:po,disabled:!Ge&&!ht||Be,className:"w-full rounded-xl bg-gray-100/80 px-4 py-2.5 text-sm font-medium text-gray-700 transition-all hover:bg-gray-200 hover:text-gray-900 disabled:opacity-50 disabled:hover:bg-gray-100/80 disabled:hover:text-gray-700 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white dark:disabled:hover:bg-white/[0.06] dark:disabled:hover:text-gray-300 flex items-center justify-center gap-2",children:Be?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"导出中..."]}):"导出所选数据"})]}),s.jsxs("div",{className:"rounded-2xl border border-transparent bg-black/[0.04] p-4 dark:bg-white/[0.06] space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(iS,{className:"w-4 h-4 text-gray-700 dark:text-gray-300"}),s.jsx("h4",{className:"text-sm font-bold text-gray-800 dark:text-gray-100",children:"导入数据"})]}),s.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"支持一次导入多个普通备份;分卷备份请一次性选中同一批次的全部分卷"}),s.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[!tt&&s.jsx(en,{checked:ne,onChange:ge,label:"包含配置"}),s.jsx(en,{checked:xe,onChange:fe,label:"包含任务和图片"})]}),s.jsx("button",{onClick:()=>{var M;return(M=m.current)==null?void 0:M.click()},disabled:!(!tt&&ne)&&!xe||Oe,className:"w-full rounded-xl bg-gray-100/80 px-4 py-2.5 text-sm font-medium text-gray-700 transition-all hover:bg-gray-200 hover:text-gray-900 disabled:opacity-50 disabled:hover:bg-gray-100/80 disabled:hover:text-gray-700 dark:bg-white/[0.06] dark:text-gray-300 dark:hover:bg-white/[0.1] dark:hover:text-white dark:disabled:hover:bg-white/[0.06] dark:disabled:hover:text-gray-300 flex items-center justify-center gap-2",children:Oe?s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"导入中..."]}):"从 ZIP 导入所选数据"}),s.jsx("input",{ref:m,type:"file",accept:".zip",multiple:!0,className:"hidden",onChange:nl})]}),s.jsxs("div",{className:"rounded-2xl bg-red-500/[0.06] p-4 dark:bg-red-500/[0.1] space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(_r,{className:"w-4 h-4 text-red-600 dark:text-red-400/90"}),s.jsx("h4",{className:"text-sm font-bold text-red-600 dark:text-red-400/90",children:"清除数据"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-6 gap-y-3",children:[s.jsx(en,{checked:be,onChange:Z,label:"包含配置",tone:"danger"}),s.jsx(en,{checked:de,onChange:he,label:"包含任务和图片",tone:"danger"})]}),s.jsx("button",{onClick:()=>f({title:"清空所选数据",message:"确定要清空所选的数据吗?此操作不可恢复。",action:()=>sl()}),disabled:!be&&!de,className:"w-full rounded-xl bg-red-500/[0.12] px-4 py-2.5 text-sm font-medium text-red-600 transition-all hover:bg-red-500/[0.18] hover:text-red-700 disabled:opacity-50 disabled:hover:bg-red-500/[0.12] disabled:hover:text-red-600 dark:bg-red-500/[0.18] dark:text-red-400/90 dark:hover:bg-red-500/[0.25] dark:hover:text-red-400 dark:disabled:hover:bg-red-500/[0.18] dark:disabled:hover:text-red-400/90",children:"清空所选数据"})]})]}),Fe==="skill"&&De&&s.jsx(vN,{}),Fe==="about"&&s.jsx(SN,{onOpenFontLicenses:()=>G(!0)})]})})]})]}),$&&s.jsx(CN,{routes:C.zipDownloadRoutes,scrollBoundaryRef:k,onSetEnabled:dt,onClose:()=>Q(!1)}),L&&s.jsx(wN,{scrollBoundaryRef:j,onClose:()=>G(!1)}),P&&s.jsx(kN,{editing:!!se,json:le,error:D,isImportingJson:Ue,scrollBoundaryRef:S,onClose:Ed,onCopyLlmPrompt:ul,onImportJson:yo,onJsonChange:M=>{ie(M),ue(null)},onSave:_d}),V&&lr.createPortal(s.jsx("div",{className:"fixed pointer-events-none z-[110] flex items-center justify-between gap-2 rounded-xl bg-white/95 px-3 py-2 text-xs text-gray-700 shadow-xl ring-1 ring-black/5 backdrop-blur-xl dark:bg-gray-900/95 dark:text-gray-300 dark:ring-white/10",style:{left:V.x-V.offsetX,top:V.y-V.offsetY,width:V.width,minHeight:V.height},children:s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[s.jsx(no,{className:"h-3.5 w-3.5 shrink-0 text-gray-400 dark:text-gray-500"}),s.jsx("span",{className:"min-w-0 truncate",children:V.label}),s.jsx("span",{className:"shrink-0 rounded bg-gray-100 px-1.5 py-0.5 text-[10px] text-gray-500 dark:bg-white/[0.08] dark:text-gray-400",children:V.providerLabel})]})}),document.body),ve&&s.jsx(IN,{profile:ve,options:_e,onOptionsChange:Je,onCopy:M=>it(ve,{..._e,includeApiKey:M}),onClose:()=>ae(null)})]})}function MN(){return Nt("update_ready")}function EN(e,t){const r=new qv;return r.onmessage=t,Nt("update_download",{version:e,onProgress:r})}function RN(){return Nt("update_install")}function _N(e){return e.total?`${Math.min(100,Math.floor(e.downloaded/e.total*100))}%`:`${(e.downloaded/1024/1024).toFixed(1)} MB`}const xn=Mi(()=>({status:"idle",progress:null,readyVersion:""})),Ky=e=>e instanceof Error?e.message:String(e),yh=()=>{const e=xn.getState().status;return e==="downloading"||e==="installing"};async function Ag(){try{return await MN()}catch(e){return console.warn("检查本地更新包失败:",e),null}}async function DN(){if(yh())return;const e=await Ag();yh()||xn.setState({status:e?"ready":"idle",readyVersion:e??""})}async function Xy(e){xn.setState({status:"downloading",progress:null});try{await EN(e,t=>xn.setState({progress:t})),xn.setState({status:"ready",readyVersion:e})}catch(t){console.warn("下载客户端更新失败:",t);const r=await Ag();xn.setState({status:r?"ready":"idle",readyVersion:r??""}),w.getState().showToast(Ky(t),"error")}}async function uu(){xn.setState({status:"installing"});try{await Jv(),await RN()}catch(e){console.warn("安装客户端更新失败:",e);const t=await Ag();xn.setState({status:t?"ready":"idle",readyVersion:t??""}),w.getState().showToast(Ky(e),"error")}}function LN(e){const t=w.getState(),r=xn.getState().readyVersion,n=Mx(t.tasks,t.agentConversations,t.batchProgress),a=Cs(r,e)<0;if(!n&&!a)return void uu();const o=`当前有任务或数据操作正在进行。
|
|
188
|
+
|
|
189
|
+
安装更新会关闭客户端,并中断这些操作。`;if(!a){t.setConfirmDialog({title:"安装更新",message:o,confirmText:"安装",tone:"warning",action:()=>void uu()});return}t.setConfirmDialog({title:"发现更新的版本",message:`最新版本为 v${e},已下载的是 v${r}。${n?`
|
|
190
|
+
|
|
191
|
+
${o}`:""}`,buttons:[{label:"取消",tone:"secondary",action:()=>{}},{label:"下载新版本",tone:"secondary",action:()=>void Xy(e)},{label:"继续安装",tone:n?"warning":"primary",action:()=>void uu()}]})}const ON=160,Kl=58,BN=450,UN=60;function fu(e){return e/(1+e/ON)}function FN(e,t){const[r,n]=p.useState(0),[a,o]=p.useState(!1),i=p.useRef(t);return i.current=t,p.useEffect(()=>{const l=e.current;if(!l)return;let c=0,u=0,f=!1,d=!1,g;const m=()=>l.scrollTop+l.clientHeight>=l.scrollHeight-1,x=S=>{c=Math.max(0,c+S),n(fu(c)),o(c>0)},b=S=>{const k=S&&fu(c)>=Kl;c=0,n(0),o(!1),k&&i.current()},h=S=>{const k=Math.min(S.deltaMode===1?S.deltaY*16:S.deltaY,UN);f||(d=m()),f=!0,clearTimeout(g),g=setTimeout(()=>{f=!1,c>0&&b(!1)},BN),!(!d||c===0&&(k<=0||!m()))&&(S.preventDefault(),x(k),!(fu(c)<Kl)&&(d=!1,b(!0)))},y=S=>{var k;u=((k=S.touches[0])==null?void 0:k.clientY)??0},v=S=>{const k=S.touches[0];if(!k)return;const j=u-k.clientY;u=k.clientY,!(c===0&&(j<=0||!m()))&&(S.cancelable&&S.preventDefault(),x(j))},I=S=>{c>0&&b(S.type==="touchend")};return l.addEventListener("wheel",h,{passive:!1}),l.addEventListener("touchstart",y,{passive:!0}),l.addEventListener("touchmove",v,{passive:!1}),l.addEventListener("touchend",I),l.addEventListener("touchcancel",I),()=>{clearTimeout(g),l.removeEventListener("wheel",h),l.removeEventListener("touchstart",y),l.removeEventListener("touchmove",v),l.removeEventListener("touchend",I),l.removeEventListener("touchcancel",I)}},[e]),{pull:r,dragging:a,armed:r>=Kl}}function $N(e){const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"})}const zN={idle:"下载",downloading:"下载中…",ready:"安装",installing:"安装中…"};function WN({version:e}){const t=xn(o=>o.status),r=xn(o=>o.progress);p.useEffect(()=>{DN()},[e]);const n=()=>{if(t!=="ready")return void Xy(e);LN(e)},a=t==="downloading"&&r?`下载中 ${_N(r)}`:zN[t];return s.jsx("button",{type:"button",disabled:t==="downloading"||t==="installing",onClick:n,className:"whitespace-nowrap rounded-xl bg-blue-500 px-3 py-2 text-sm font-medium text-white tabular-nums sm:px-4 transition hover:bg-blue-600 disabled:cursor-default disabled:opacity-70 disabled:hover:bg-blue-500",children:a})}function HN(){const e=er(k=>k.releases),t=er(k=>k.hasMore),r=er(k=>k.ignoredVersion),n=er(k=>k.checkError),[a,o]=p.useState(!1),[i,l]=p.useState(""),c=p.useRef(-1),u=()=>Fa(!1);Kr(!0,u),Lr(!0,Bo);const f=e[0],d=async k=>{o(!0),l("");try{await k()}catch(j){l(j instanceof Error?j.message:String(j))}finally{o(!1)}},g=()=>{a||!t||(c.current=e.length,d(()=>B5()))},{pull:m,dragging:x,armed:b}=FN(Bo,g);p.useEffect(()=>{er.getState().releases.length||d(()=>Tc())},[]),p.useEffect(()=>{const k=c.current;if(k<0||k>=e.length)return;c.current=-1;const j=Bo.current,A=j==null?void 0:j.querySelector(`[data-release-index="${k}"]`);j&&A&&j.scrollTo({top:A.offsetTop-12,behavior:"smooth"})},[e.length]);const h=!!(f&&Cs(f.version,"0.8.4")>0),y=De&&h,v=e.length?h?{label:"有新版本可用",text:"font-medium text-blue-600 dark:text-blue-400",dot:"bg-blue-500 ring-blue-500/20"}:n?{label:`检查失败:${n}`,text:"text-red-600 dark:text-red-400",dot:"bg-red-500 ring-red-500/20"}:{label:"当前已是最新版本",text:"text-gray-500 dark:text-gray-400",dot:"bg-emerald-500 ring-emerald-500/20"}:!a&&(i||n)?{label:"检查失败",text:"text-red-600 dark:text-red-400",dot:"bg-red-500 ring-red-500/20"}:{label:"当前版本",text:"text-gray-500 dark:text-gray-400",dot:"bg-gray-300 ring-gray-300/25 dark:bg-gray-600 dark:ring-gray-600/30"},I=a?"正在加载…":t?b?"松开加载更早的版本":"继续上滑加载更早的版本":"没有更早的版本了",S=a?0:Math.min(m/Kl,1);return lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[100] flex items-center justify-center p-4",onClick:u,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 flex h-[85vh] max-h-[720px] w-full max-w-2xl flex-col overflow-hidden rounded-3xl border border-white/50 bg-white/95 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10",onClick:k=>k.stopPropagation(),children:[s.jsxs("div",{className:"flex shrink-0 items-start gap-3 border-b border-gray-100 px-5 py-4 dark:border-white/[0.08]",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h3",{className:"text-base font-bold text-gray-800 dark:text-gray-100",children:"版本更新"}),De&&s.jsxs("button",{type:"button",onClick:()=>void Gg((f==null?void 0:f.url)??Ac),className:"flex items-center gap-1 text-xs text-gray-400 transition-colors hover:text-blue-500 dark:text-gray-500 dark:hover:text-blue-400",children:[s.jsx(Sg,{className:"h-3.5 w-3.5"}),"在 GitHub 打开"]})]}),s.jsxs("div",{className:`mt-1.5 flex min-w-0 items-center gap-2 text-xs ${v.text}`,children:[s.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ring-[3px] ${v.dot}`}),s.jsx("span",{title:v.label,className:"min-w-0 truncate",children:v.label}),s.jsx("span",{"data-selectable-text":!0,className:"shrink-0 font-mono text-gray-400 dark:text-gray-500",children:h?`v0.8.4 → ${f==null?void 0:f.tag}`:"v0.8.4"})]})]}),s.jsx("button",{type:"button",onClick:u,className:"-mr-1 shrink-0 rounded-full p-1 text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/[0.06] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})})]}),s.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:s.jsx("div",{ref:Bo,className:`custom-scrollbar relative h-full overflow-y-auto overscroll-contain px-5 py-4 ${x?"":"transition-transform duration-200 ease-out"}`,style:{transform:m?`translateY(${-m}px)`:void 0},children:e.length===0?s.jsx("div",{className:"flex h-full flex-col items-center justify-center gap-3 text-sm text-gray-500 dark:text-gray-400",children:a?"正在获取版本信息…":i?s.jsxs(s.Fragment,{children:[s.jsxs("span",{children:["获取版本信息失败:",i]}),s.jsx("button",{type:"button",onClick:()=>void d(()=>Tc(Xb)),className:"text-blue-500 hover:underline",children:"重试"})]}):"暂无版本信息"}):s.jsxs("div",{className:"space-y-4",children:[e.map((k,j)=>{const A=Cs(k.version,"0.8.4");return s.jsxs("section",{"data-release-index":j,className:`rounded-2xl p-4 ${A>0?"bg-blue-50/80 ring-1 ring-blue-100 dark:bg-blue-500/[0.08] dark:ring-blue-400/15":"bg-black/[0.03] dark:bg-white/[0.04]"}`,children:[s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[s.jsx("h4",{className:"text-[15px] font-bold text-gray-800 dark:text-gray-100",children:k.tag}),j===0&&A>0&&s.jsx("span",{className:"text-xs font-medium text-blue-500 dark:text-blue-400",children:"最新"}),A===0&&s.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"当前版本"}),s.jsx("span",{className:"ml-auto text-xs text-gray-400 dark:text-gray-500",children:$N(k.publishedAt)})]}),s.jsx("div",{"data-selectable-text":!0,className:"text-sm leading-relaxed text-gray-700 dark:text-gray-200",children:s.jsx(Ai,{content:L5(k.body,k.version).trim()||"暂无更新说明。"})})]},k.tag)}),s.jsx("div",{className:`flex items-center justify-center gap-2 pb-2 text-xs transition-colors ${b&&t&&!a?"text-blue-500 dark:text-blue-400":"text-gray-400 dark:text-gray-500"}`,children:i&&!a?s.jsxs(s.Fragment,{children:[s.jsxs("span",{children:["加载失败:",i]}),s.jsx("button",{type:"button",onClick:g,className:"text-blue-500 hover:underline",children:"重试"})]}):s.jsxs(s.Fragment,{children:[(a||t)&&s.jsx("span",{className:`inline-flex ${x?"":"transition-transform duration-200 ease-out"}`,style:{transform:`rotate(${S*360}deg)`},children:s.jsxs("svg",{className:`h-3.5 w-3.5 ${a?"animate-spin":""}`,fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),s.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",pathLength:100,strokeDasharray:`${a?25:10+S*65} 100`,transform:"rotate(-90 12 12)"})]})}),s.jsx("span",{children:I})]})})]})})}),s.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-t border-gray-100 p-3 dark:border-white/[0.08] sm:p-4",children:[f&&Zb(f,"0.8.4",r)&&s.jsx("button",{type:"button",onClick:()=>{U5(f.version),u()},className:"whitespace-nowrap rounded-xl px-2 py-2 text-xs text-gray-500 transition sm:px-3 sm:text-sm hover:bg-black/[0.05] hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/[0.06] dark:hover:text-gray-200",children:"忽略当前最新版本"}),s.jsxs("div",{className:"ml-auto flex min-w-0 items-center gap-1.5 sm:gap-2",children:[s.jsx("button",{type:"button",onClick:u,className:"whitespace-nowrap rounded-xl border border-transparent bg-black/[0.04] px-3 py-2 text-sm text-gray-600 sm:px-4 transition hover:bg-black/[0.07] dark:bg-white/[0.06] dark:text-gray-400 dark:hover:bg-white/[0.1]",children:"关闭"}),!De&&s.jsx("button",{type:"button",onClick:()=>void Gg((f==null?void 0:f.url)??Ac),className:"whitespace-nowrap rounded-xl bg-blue-500 px-3 py-2 text-sm font-medium text-white sm:px-4 transition hover:bg-blue-600",children:"前往 GitHub 查看"}),y&&f&&s.jsx(WN,{version:f.version})]})]})]})]}),document.body)}function YN(){return er(t=>t.modalOpen)?s.jsx(HN,{}):null}function qy(e){return e.split(/(`[^`]+`|「[^」]+」|\*\*[^*]+\*\*)/g).map((t,r)=>t.startsWith("`")&&t.endsWith("`")?s.jsx("code",{className:"rounded bg-gray-100 px-1 py-0.5 text-[0.85em] text-gray-700 dark:bg-white/[0.06] dark:text-gray-200",children:t.slice(1,-1)},r):t.startsWith("「")&&t.endsWith("」")?s.jsx("strong",{className:"font-semibold text-gray-700 dark:text-gray-200",children:t},r):t.startsWith("**")&&t.endsWith("**")?s.jsx("strong",{className:"font-semibold text-gray-700 dark:text-gray-200",children:t.slice(2,-2)},r):t)}function vh(e="primary"){return e==="secondary"?"border border-transparent bg-black/[0.04] text-gray-600 hover:bg-black/[0.07] dark:bg-white/[0.06] dark:text-gray-400 dark:hover:bg-white/[0.1]":e==="warning"?"bg-orange-500 text-white hover:bg-orange-600":e==="danger"?"bg-red-500 text-white hover:bg-red-600":"bg-blue-500 text-white hover:bg-blue-600"}function VN(){var y;const e=w(v=>v.confirmDialog),t=w(v=>v.setConfirmDialog),[r,n]=p.useState(!0),[a,o]=p.useState(!1),[i,l]=p.useState(!1),c=p.useRef(null);p.useEffect(()=>{const v=(e==null?void 0:e.minConfirmDelayMs)??0;if(!e||v<=0){n(!0);return}n(!1);const I=window.setTimeout(()=>n(!0),v);return()=>window.clearTimeout(I)},[e]),p.useEffect(()=>{var v;o(((v=e==null?void 0:e.checkbox)==null?void 0:v.defaultChecked)??!1)},[e]);const u=()=>{!r||i||t(null)},f=()=>{var v;(v=e==null?void 0:e.cancelAction)==null||v.call(e,a),u()};if(Kr(!!e&&r,u),Lr(!!e,c),!e)return null;const d=e.title.includes("删除")||e.title.includes("清空"),g=e.tone??(d?"danger":void 0),m=vh(g==="danger"||g==="warning"?g:"primary"),x=e.confirmText??(d?"确认删除":"确认"),b=e.cancelText??"取消",h=((y=e.buttons)==null?void 0:y.filter(v=>v.label.trim()))??[];return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[110] flex items-center justify-center p-4",onClick:u,children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{ref:c,className:`relative bg-white/90 dark:bg-gray-900/90 backdrop-blur-xl border border-white/50 dark:border-white/[0.08] rounded-3xl shadow-[0_8px_40px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] ${e.content?"max-w-md":"max-w-sm"} w-full max-h-full flex flex-col p-6 z-10 ring-1 ring-black/5 dark:ring-white/10 animate-confirm-in`,onClick:v=>v.stopPropagation(),children:[s.jsxs("h3",{className:"mb-2 flex items-center gap-2 text-base font-bold text-gray-800 dark:text-gray-100",children:[e.icon==="info"&&s.jsxs("svg",{className:"h-5 w-5 shrink-0 text-blue-500",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",viewBox:"0 0 24 24",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]}),e.icon==="copy"&&s.jsx(zr,{className:"h-5 w-5 shrink-0 text-blue-500"}),e.title]}),s.jsx("div",{className:`space-y-2 text-sm text-gray-500 dark:text-gray-400 ${e.content?"mb-3":e.checkbox?"mb-4":"mb-6"} leading-relaxed whitespace-pre-line text-pretty ${e.messageAlign==="center"?"text-center":""}`,children:e.message.split(/\n{2,}/).map((v,I)=>s.jsx("p",{children:qy(v)},I))}),e.content&&s.jsx("div",{className:`custom-scrollbar -mx-2 max-h-[min(60vh,32rem)] min-h-0 overflow-y-auto overscroll-contain px-2 ${e.checkbox?"mb-4":"mb-6"}`,children:e.content}),e.checkbox&&s.jsx(en,{checked:a,onChange:o,label:e.checkbox.label,tone:e.checkbox.tone,disabled:e.checkbox.disabled,className:"mb-6"}),h.length>0?s.jsx("div",{className:"flex gap-2",children:h.map(v=>s.jsx("button",{onClick:()=>{r&&(v.action(a),t(null))},disabled:!r,className:`flex-1 py-2 rounded-xl text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60 ${vh(v.tone)}`,children:v.label},v.label))}):s.jsxs("div",{className:"flex gap-2",children:[e.showCancel!==!1&&s.jsx("button",{onClick:f,disabled:i,className:"flex-1 py-2 rounded-xl border border-transparent bg-black/[0.04] dark:bg-white/[0.06] text-sm text-gray-600 dark:text-gray-400 hover:bg-black/[0.07] dark:hover:bg-white/[0.1] transition disabled:cursor-not-allowed disabled:opacity-60",children:b}),s.jsx("button",{onClick:()=>{var v;if(!(!r||i)){if(!e.awaitAction){(v=e.action)==null||v.call(e,a),t(null);return}l(!0),(async()=>{var I;try{await((I=e.action)==null?void 0:I.call(e,a))!==!1&&t(null)}finally{l(!1)}})()}},disabled:!r||i,className:`flex-1 py-2 rounded-xl text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60 ${m}`,children:i&&e.busyText?e.busyText:x})]})]})]})}const KN={image:"张图片",file:"个文件"};function XN(){const e=ws(c=>c.progress),t=e!==null,[r,n]=p.useState(!1),[a,o]=p.useState(!1);if(p.useEffect(()=>{if(o(!1),!t){n(!1);return}const c=window.setTimeout(()=>n(!0),300);return()=>window.clearTimeout(c)},[t]),!e||!r)return null;const i=e.total>0?Math.min(100,Math.round(e.done/e.total*100)):null,l=!e.unit||!e.total?"":e.unit==="byte"?`${Zs(e.done)} / ${Zs(e.total)}`:`已处理 ${e.done} / ${e.total} ${KN[e.unit]}`;return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[105] flex items-center justify-center p-4",children:[s.jsx("div",{className:"absolute inset-0 bg-black/20 dark:bg-black/40 backdrop-blur-md animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 w-full max-w-sm rounded-3xl border border-white/50 bg-white/90 p-6 shadow-[0_8px_40px_rgb(0,0,0,0.12)] ring-1 ring-black/5 backdrop-blur-xl animate-confirm-in dark:border-white/[0.08] dark:bg-gray-900/90 dark:shadow-[0_8px_40px_rgb(0,0,0,0.4)] dark:ring-white/10",children:[s.jsx("h3",{className:"mb-2 text-base font-bold text-gray-800 dark:text-gray-100",children:e.mode==="export"?"正在导出数据":"正在导入数据"}),s.jsxs("div",{className:"mb-3 flex items-baseline justify-between gap-3 text-sm text-gray-500 dark:text-gray-400",children:[s.jsx("span",{className:"min-w-0",children:e.stage}),i!==null&&s.jsxs("span",{className:"shrink-0 tabular-nums",children:[i,"%"]})]}),s.jsx("div",{role:"progressbar","aria-label":e.stage,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":i??void 0,className:"h-1.5 overflow-hidden rounded-full bg-black/[0.06] dark:bg-white/[0.08]",children:i!==null?s.jsx("div",{className:"h-full rounded-full bg-blue-500",style:{width:`${i}%`}}):s.jsx("div",{className:"h-full w-2/5 rounded-full bg-blue-500 animate-progress-indeterminate"})}),s.jsx("p",{className:"mt-2 min-h-[1rem] text-xs tabular-nums text-gray-400 dark:text-gray-500",children:l}),e.mode==="import"&&!e.cancelable&&s.jsxs("p",{className:"mt-3 text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:["正在写入,请勿关闭",De?"应用":"页面","。"]}),e.cancelable&&s.jsx("button",{onClick:()=>{o(!0),JC()},disabled:a,className:"mt-5 w-full rounded-xl border border-transparent bg-black/[0.04] py-2 text-sm text-gray-600 transition hover:bg-black/[0.07] disabled:cursor-not-allowed disabled:opacity-60 dark:bg-white/[0.06] dark:text-gray-400 dark:hover:bg-white/[0.1]",children:a?"正在取消…":"取消"})]})]})}function qN(){const e=w(r=>r.toast);if(!e)return null;const t=()=>{switch(e.type){case"success":return s.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-green-100 dark:bg-green-900/50 text-green-600 dark:text-green-400",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M5 13l4 4L19 7"})})});case"error":return s.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-red-100 dark:bg-red-900/50 text-red-600 dark:text-red-400",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M6 18L18 6M6 6l12 12"})})});default:return s.jsx("div",{className:"flex items-center justify-center w-5 h-5 rounded-full bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-400",children:s.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})})}};return s.jsx("div",{className:"fixed bottom-24 left-[calc((100%-var(--page-scrollbar-width))/2)] z-[120] pointer-events-none toast-enter",children:s.jsxs("div",{className:"flex items-center gap-2.5 w-max max-w-[calc(100vw-32px)] sm:max-w-[min(44rem,80vw)] px-5 py-3.5 bg-white/95 dark:bg-gray-900/95 backdrop-blur-xl border border-gray-200/60 dark:border-white/[0.08] rounded-full shadow-[0_8px_30px_rgb(0,0,0,0.12)] dark:shadow-[0_8px_30px_rgb(0,0,0,0.3)] ring-1 ring-black/5 dark:ring-white/10 text-sm font-medium text-gray-700 dark:text-gray-300",children:[s.jsx("span",{className:"flex-shrink-0",children:t()}),s.jsx("span",{className:"leading-5 whitespace-pre-line text-center",children:e.message})]})})}function JN(){return p.useSyncExternalStore(nk,rk)?s.jsx("div",{className:"fixed top-4 left-1/2 -translate-x-1/2 z-[130]",role:"alert",children:s.jsxs("div",{className:"flex items-center gap-2 sm:gap-2.5 w-max max-w-[calc(100vw-32px)] px-4 sm:px-5 py-3 bg-amber-50/95 dark:bg-amber-950/90 backdrop-blur-xl border border-amber-200 dark:border-amber-500/30 rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.12)] text-[13px] sm:text-sm font-medium text-amber-800 dark:text-amber-200",children:[s.jsx("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"})}),s.jsx("span",{className:"leading-5 text-balance",children:"请关闭或刷新本应用的其他标签页以完成升级"})]})}):null}const GN=1920,ZN=16;function wh(e,t){return Math.max(t,Math.floor(e/t)*t)}function QN(e,t,r=GN,n=ZN){const a=Math.max(e,t);if(a<=r)return{width:e,height:t,scale:1,wasResized:!1};const o=r/a;return{width:wh(e*o,n),height:wh(t*o,n),scale:o,wasResized:!0}}async function eA(e){const t=await On(e),r=QN(t.naturalWidth,t.naturalHeight),n=/^data:image\/png(?:[;,]|$)/i.test(e);if(!r.wasResized&&n)return{...r,dataUrl:e,originalWidth:t.naturalWidth,originalHeight:t.naturalHeight,wasConvertedToPng:!1};const a=document.createElement("canvas");a.width=r.width,a.height=r.height;const o=a.getContext("2d");if(!o)throw new Error("当前浏览器不支持 Canvas");o.drawImage(t,0,0,r.width,r.height);const i=await td(a,"image/png");return{...r,dataUrl:await oa(i),originalWidth:t.naturalWidth,originalHeight:t.naturalHeight,wasConvertedToPng:!0}}function tA(e,t,r){const n=[];let a=!1;for(const o of e){if(o.id===t){a||(n.push(r),a=!0);continue}if(o.id===r.id){a||(n.push(r),a=!0);continue}n.push(o)}return a?n:[r,...n]}const sa=1,Pg=8;function $a(e,t,r){return Math.min(r,Math.max(t,e))}function Tg(e,t,r){const n=$a(e.scale,sa,Pg);if(n===sa)return{scale:n,x:0,y:0};const a=r??{x:0,y:0,...t},o=(i,l,c,u)=>{const f=l*n;return f>u?$a(i,c+u-f,c):$a(i,c,c+u-f)};return{scale:n,x:o(e.x,t.width,a.x,a.width),y:o(e.y,t.height,a.y,a.height)}}function Jy(e,t,r,n,a){const o={x:(t.x-e.x)/e.scale,y:(t.y-e.y)/e.scale},i=$a(r,sa,Pg);return Tg({scale:i,x:t.x-o.x*i,y:t.y-o.y*i},n,a)}function rA(e){const t={x:(e.startCentroid.x-e.startTransform.x)/e.startTransform.scale,y:(e.startCentroid.y-e.startTransform.y)/e.startTransform.scale},r=e.startDistance>0?e.nextDistance/e.startDistance:1,n=$a(e.startTransform.scale*r,sa,Pg);return Tg({scale:n,x:e.nextCentroid.x-t.x*n,y:e.nextCentroid.y-t.y*n},e.viewportSize,e.bounds)}function nA(e,t,r){return{x:(t.x-e.left)/e.width*r.width,y:(t.y-e.top)/e.height*r.height}}function sA(e,t,r){if(!r||e.width<=0||e.height<=0)return{scale:sa,x:0,y:0};const n=t.height*.42,a=$a(n/e.height,sa,3);return Jy({scale:sa,x:0,y:0},{x:e.width/2,y:e.height/2},a,e)}const gu={scale:1,x:0,y:0};function Gy(e,t,r){const n=p.useRef(gu),a=p.useRef(new Map),o=p.useRef(null),i=p.useRef(null),[l,c]=p.useState(gu),[u,f]=p.useState(!1),[d,g]=p.useState(!1),[m,x]=p.useState(0);function b(){const N=e.current.getBoundingClientRect(),C=t.current.getBoundingClientRect();return{x:C.left-N.left,y:C.top-N.top,width:C.width,height:C.height}}function h(){const N=e.current;return{width:N.clientWidth,height:N.clientHeight}}function y(N=gu){const C=Tg(N,h(),b());n.current=C,c(C)}function v(N){const C=e.current.getBoundingClientRect();return{x:N.x-C.left,y:N.y-C.top}}function I(){const[N,C]=Array.from(a.current.values());o.current={startTransform:n.current,startCentroid:v({x:(N.x+C.x)/2,y:(N.y+C.y)/2}),startDistance:Math.hypot(N.x-C.x,N.y-C.y)}}p.useEffect(()=>{if(!r)return;const N=R=>{R.altKey&&f(!0)},C=R=>{R.key==="Alt"&&f(!1)},T=()=>f(!1);return window.addEventListener("keydown",N),window.addEventListener("keyup",C),window.addEventListener("blur",T),()=>{window.removeEventListener("keydown",N),window.removeEventListener("keyup",C),window.removeEventListener("blur",T)}},[r]),p.useLayoutEffect(()=>{if(!r)return;const N=e.current,C=t.current,T=U=>{!U.altKey&&!U.ctrlKey||(U.preventDefault(),y(Jy(n.current,v({x:U.clientX,y:U.clientY}),n.current.scale*Math.exp(-U.deltaY*.002),h(),b())))},R=new ResizeObserver(()=>{x(N.clientWidth),y(n.current)});return x(N.clientWidth),C.addEventListener("wheel",T,{passive:!1}),R.observe(N),R.observe(C),()=>{C.removeEventListener("wheel",T),R.disconnect()}},[r]);const S=N=>N.altKey&&N.pointerType!=="touch"?(i.current={pointerId:N.pointerId,startPoint:{x:N.clientX,y:N.clientY},startTransform:n.current},g(!0),"pan"):(a.current.set(N.pointerId,{x:N.clientX,y:N.clientY}),a.current.size<2?null:(I(),"pinch")),k=N=>{const C=i.current;if((C==null?void 0:C.pointerId)===N.pointerId)return y({scale:C.startTransform.scale,x:C.startTransform.x+N.clientX-C.startPoint.x,y:C.startTransform.y+N.clientY-C.startPoint.y}),!0;a.current.has(N.pointerId)&&a.current.set(N.pointerId,{x:N.clientX,y:N.clientY});const T=o.current;if(!T||a.current.size<2)return!!T;const[R,U]=Array.from(a.current.values());return y(rA({startTransform:T.startTransform,startCentroid:T.startCentroid,nextCentroid:v({x:(R.x+U.x)/2,y:(R.y+U.y)/2}),startDistance:T.startDistance,nextDistance:Math.hypot(R.x-U.x,R.y-U.y),viewportSize:h(),bounds:b()})),!0},j=N=>{var C;a.current.delete(N.pointerId),o.current&&(a.current.size>=2?I():a.current.size===0&&(o.current=null)),((C=i.current)==null?void 0:C.pointerId)===N.pointerId&&(i.current=null,g(!1))},A=l.scale>1.01||Math.abs(l.x)>1||Math.abs(l.y)>1;return{transform:l,transformRef:n,isZoomed:A,isAltPressed:u,isPanning:d,frameWidth:m,isPinching:()=>o.current!=null,getVisibleCenter:N=>{const C=b(),T=n.current;return{x:(C.x+C.width/2-T.x)/(T.scale*N),y:(C.y+C.height/2-T.y)/(T.scale*N)}},commit:y,pointerDown:S,pointerMove:k,pointerUp:j}}function kh(e,t){return nA(e.getBoundingClientRect(),{x:t.clientX,y:t.clientY},{width:e.width,height:e.height})}function mu(e){const t=e.getContext("2d",{willReadFrequently:!0});if(!t)throw new Error("当前浏览器不支持 Canvas");t.globalCompositeOperation="source-over",t.clearRect(0,0,e.width,e.height),t.fillStyle="#fff",t.fillRect(0,0,e.width,e.height)}function aA(e,t){const r=e.naturalWidth/e.naturalHeight,n=t.width/t.height;if(Math.abs(r-n)>.001)throw new Error("遮罩尺寸与当前图片不一致");const a=t.getContext("2d",{willReadFrequently:!0});if(!a)throw new Error("当前浏览器不支持 Canvas");a.clearRect(0,0,t.width,t.height),a.imageSmoothingEnabled=!0,a.imageSmoothingQuality="high",a.drawImage(e,0,0,t.width,t.height)}function oA(){const e=w(t=>t.maskEditorImageId);return e?s.jsx(iA,{imageId:e},e):null}function iA({imageId:e}){const t=w(Z=>Z.setMaskEditorImageId),r=w(Z=>Z.maskDraft),n=w(Z=>Z.setMaskDraft),a=w(Z=>Z.clearMaskDraft),o=w(Z=>Z.setConfirmDialog),i=w(Z=>Z.showToast),l=p.useRef(null),c=p.useRef(null),u=p.useRef(null),f=p.useRef(null),d=p.useRef(null),g=p.useRef(null),m=p.useRef(null),x=p.useRef(null),b=p.useRef([]),h=p.useRef([]),y=p.useRef(null),v=p.useRef(0),[I,S]=p.useState(""),[k,j]=p.useState(null),[A,N]=p.useState("brush"),[C,T]=p.useState(64),[R,U]=p.useState(!1),[W,F]=p.useState(!1),[_,O]=p.useState({undo:0,redo:0}),[J,H]=p.useState(null),[K,te]=p.useState(!1),P=Gy(d,g,!!k),B=Ot(),$=()=>{W||t(null)};Kr(!0,$),Lr(!0);const Q=()=>{o({title:"移除遮罩",message:"确定要撤销对这张图片的所有涂抹并移除遮罩吗?",tone:"danger",action:()=>{a(),t(null),i("已移除遮罩","success")}})};function L(){const Z=d.current,de=f.current;P.commit(sA({width:Z.clientWidth,height:Z.clientHeight},{width:de.clientWidth,height:de.clientHeight},window.matchMedia("(max-width: 1023px)").matches))}function G(){O({undo:b.current.length,redo:h.current.length})}function se(){const Z=u.current,de=c.current;if(!Z||!de)return;const he=de.getContext("2d");he&&(y.current=null,he.save(),he.clearRect(0,0,de.width,de.height),he.globalCompositeOperation="source-over",he.fillStyle="rgba(59, 130, 246, 0.58)",he.fillRect(0,0,de.width,de.height),he.globalCompositeOperation="destination-out",he.drawImage(Z,0,0),he.restore())}function Y(){y.current==null&&(y.current=window.requestAnimationFrame(se))}function le(){const Z=u.current,de=Z==null?void 0:Z.getContext("2d",{willReadFrequently:!0});!Z||!de||(b.current.push(de.getImageData(0,0,Z.width,Z.height)),b.current.length>40&&b.current.shift(),h.current=[],G())}function ie(Z){const de=u.current,he=de==null?void 0:de.getContext("2d",{willReadFrequently:!0});!de||!he||(he.putImageData(Z,0,0),Y())}function D(){if(m.current==null)return;const Z=b.current.pop();Z&&ie(Z),m.current=null,x.current=null,G()}function ue(Z){const de=u.current,he=de==null?void 0:de.getContext("2d");!de||!he||(he.save(),he.globalCompositeOperation=A==="brush"?"destination-out":"source-over",he.fillStyle="#fff",he.beginPath(),he.arc(Z.x,Z.y,C/2,0,Math.PI*2),he.fill(),he.restore(),Y())}function ke(Z,de){const he=u.current,pe=he==null?void 0:he.getContext("2d");!he||!pe||(pe.save(),pe.globalCompositeOperation=A==="brush"?"destination-out":"source-over",pe.strokeStyle="#fff",pe.lineWidth=C,pe.lineCap="round",pe.lineJoin="round",pe.beginPath(),pe.moveTo(Z.x,Z.y),pe.lineTo(de.x,de.y),pe.stroke(),pe.restore(),Y())}p.useEffect(()=>()=>{v.current++},[]),p.useEffect(()=>{let Z=!1;U(!0),S(""),j(null),b.current=[],h.current=[],G();async function de(){try{const he=await kt(e);if(Z)return;if(!he){i("图片已不存在,无法编辑遮罩","error"),t(null);return}const pe=await eA(he),Be=await On(pe.dataUrl);if(Z)return;const Oe={width:pe.width,height:pe.height},Ue=l.current,lt=c.current,ut=u.current;if(!Ue||!lt||!ut)return;for(const He of[Ue,lt,ut])He.width=Oe.width,He.height=Oe.height;const Ve=Ue.getContext("2d");if(!Ve)throw new Error("当前浏览器不支持 Canvas");if(Ve.clearRect(0,0,Ue.width,Ue.height),Ve.drawImage(Be,0,0),mu(ut),(r==null?void 0:r.targetImageId)===e)try{const He=await On(r.maskDataUrl);if(Z)return;aA(He,ut)}catch(He){mu(ut),i(`遮罩草稿加载失败,已重置为空白遮罩:${He instanceof Error?He.message:String(He)}`,"error")}Y(),S(pe.dataUrl),j(Oe),pe.wasResized&&i(`已为遮罩编辑按官方要求调整图片尺寸:
|
|
192
|
+
${pe.originalWidth}×${pe.originalHeight} → ${pe.width}×${pe.height}`,"info"),requestAnimationFrame(()=>{Z||L()})}catch(he){Z||(i(he instanceof Error?he.message:String(he),"error"),t(null))}finally{Z||U(!1)}}return de(),()=>{Z=!0,y.current!=null&&(window.cancelAnimationFrame(y.current),y.current=null),m.current=null,x.current=null}},[e,r,t,i]);const we=!!(I&&k&&!R),We=_.undo>0&&we&&!W,Ne=_.redo>0&&we&&!W,Fe=(r==null?void 0:r.targetImageId)===e,Ee=k?P.frameWidth/k.width*P.transform.scale:0,Ge=Z=>{const de=u.current;if(!de||!we||W||Z.pointerType!=="touch"&&Z.button!==0)return;Z.preventDefault(),Z.currentTarget.setPointerCapture(Z.pointerId);const he=P.pointerDown(Z);if(he==="pan")return;if(he==="pinch"){D();return}if(P.isPinching()||m.current!=null)return;m.current=Z.pointerId,le();const pe=kh(de,Z);x.current=pe,ue(pe)},Xe=Z=>{const de=u.current;if(!de)return;const he=kh(de,Z);if(Z.pointerType!=="touch"&&H(he),P.pointerMove(Z)){Z.preventDefault();return}m.current!==Z.pointerId||!x.current||!we||W||(Z.preventDefault(),ke(x.current,he),x.current=he)},ht=Z=>{Z.currentTarget.hasPointerCapture(Z.pointerId)&&Z.currentTarget.releasePointerCapture(Z.pointerId),P.pointerUp(Z),m.current===Z.pointerId&&(m.current=null,x.current=null)},Pe=()=>{const Z=u.current,de=Z==null?void 0:Z.getContext("2d",{willReadFrequently:!0}),he=b.current.pop();!Z||!de||!he||(h.current.push(de.getImageData(0,0,Z.width,Z.height)),ie(he),G())},ne=()=>{const Z=u.current,de=Z==null?void 0:Z.getContext("2d",{willReadFrequently:!0}),he=h.current.pop();!Z||!de||!he||(b.current.push(de.getImageData(0,0,Z.width,Z.height)),ie(he),G())},ge=()=>{const Z=u.current;!Z||!we||W||(le(),mu(Z),Y())},xe=async()=>{const Z=u.current;if(!Z||!I||!we||W)return;const de=++v.current;try{F(!0);const he=await td(Z,"image/png"),pe=await oa(he),Be=await Qn(I,"upload");if(v.current!==de)return;const Oe=w.getState();Oe.setInputImages(tA(Oe.inputImages,e,{id:Be,dataUrl:I}),{equivalentImageIds:{[e]:Be}}),n({targetImageId:Be,maskDataUrl:pe,updatedAt:Date.now()}),t(null),i("遮罩已保存","success")}catch(he){if(v.current!==de)return;i(he instanceof Error?he.message:String(he),"error")}finally{v.current===de&&F(!1)}},fe=!k||P.isAltPressed?null:K?J??P.getVisibleCenter(P.frameWidth/k.width):J,be=P.isPanning?"grabbing":P.isAltPressed?"grab":fe?"none":"crosshair";return s.jsxs(Dy,{onBackdropClick:$,children:[s.jsx(Ly,{left:s.jsx(Ke,{tooltip:"取消",className:hs,disabled:W,onClick:$,children:s.jsx(qt,{className:"h-5 w-5"})}),center:s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:"画笔",className:fs(A==="brush"),disabled:!we||W,onClick:()=>N("brush"),children:s.jsx(Fy,{})}),s.jsx(Ke,{tooltip:"橡皮擦",className:fs(A==="eraser"),disabled:!we||W,onClick:()=>N("eraser"),children:s.jsx($y,{})})]}),right:s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:"撤销",className:hs,disabled:!We,onClick:Pe,children:s.jsx(zy,{})}),s.jsx(Ke,{tooltip:"重做",className:hs,disabled:!Ne,onClick:ne,children:s.jsx(Wy,{})}),s.jsx(Ke,{tooltip:"清空遮罩",wrapperClassName:"relative hidden sm:inline-flex",className:hs,disabled:!we||W,onClick:ge,children:s.jsx(Hy,{})})]})}),s.jsxs("div",{ref:f,className:"relative min-h-0 flex-1 bg-gray-100/70 dark:bg-black/25",children:[s.jsx("div",{ref:g,className:"absolute inset-0 flex touch-none select-none items-center justify-center overflow-hidden py-4 pl-16 pr-4 sm:px-20 sm:py-6",style:{containerType:"size",cursor:be},onPointerDown:Ge,onPointerMove:Xe,onPointerUp:ht,onPointerCancel:ht,onLostPointerCapture:ht,onPointerLeave:()=>H(null),children:s.jsxs("div",{ref:d,className:"relative max-h-full max-w-full",style:{aspectRatio:k?`${k.width} / ${k.height}`:"1 / 1",width:k?`min(100%, 100cqh * ${k.width/k.height})`:"520px",visibility:k?"visible":"hidden"},children:[s.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-lg shadow-sm ring-1 ring-black/5 will-change-transform dark:ring-white/10",style:{transform:`matrix(${P.transform.scale}, 0, 0, ${P.transform.scale}, ${P.transform.x}, ${P.transform.y})`,transformOrigin:"0 0"},children:[s.jsx("canvas",{ref:l,className:"absolute inset-0 h-full w-full"}),s.jsx("canvas",{ref:c,className:"absolute inset-0 h-full w-full"}),s.jsx("canvas",{ref:u,className:"absolute inset-0 h-full w-full opacity-0"})]}),fe&&s.jsx(Uy,{x:fe.x*Ee+P.transform.x,y:fe.y*Ee+P.transform.y,size:C*Ee})]})}),R&&s.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center text-sm text-gray-500 dark:text-gray-400",children:"正在载入图片..."}),s.jsx(Oy,{value:C,min:8,max:220,label:"笔刷大小",disabled:!we||W,onChange:T,onAdjustStart:()=>te(!0),onAdjustEnd:()=>te(!1)}),P.isZoomed&&s.jsx(By,{onClick:L})]}),s.jsxs("div",{className:"flex flex-none items-center justify-between gap-3 px-3 py-3 sm:px-4",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 pl-1",children:[s.jsx("span",{className:"text-sm font-semibold text-gray-800 dark:text-gray-200",children:"编辑遮罩"}),s.jsxs("span",{className:"relative inline-flex",...B.handlers,children:[s.jsx("button",{type:"button",className:"flex h-7 w-7 items-center justify-center rounded-full text-gray-400 transition hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-white/[0.08] dark:hover:text-gray-300","aria-label":"遮罩编辑说明",onClick:B.show,children:s.jsx("svg",{className:"h-4 w-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}),s.jsxs(pt,{visible:B.visible,className:"w-64 leading-5",children:[s.jsx("p",{children:"根据官方文档说明,此功能仅基于提示词,无法完全控制模型编辑区域。"}),s.jsx("p",{className:"mt-1.5",children:"建议附加类似“只编辑遮罩区域”的提示词以提升模型指令遵循程度。"})]})]})]}),s.jsxs("div",{className:"flex flex-none items-center gap-2",children:[Fe&&s.jsx("button",{onClick:Q,disabled:W,className:"flex h-10 items-center rounded-xl bg-gray-100 px-4 text-sm font-medium text-gray-700 transition hover:bg-red-500/[0.1] hover:text-red-600 disabled:opacity-50 dark:bg-white/[0.08] dark:text-gray-300 dark:hover:bg-red-500/20 dark:hover:text-red-400",children:"移除遮罩"}),s.jsxs("button",{onClick:xe,disabled:!we||W,className:"flex h-10 items-center gap-1.5 rounded-xl bg-blue-500 px-4 text-sm font-medium text-white shadow-sm transition hover:bg-blue-600 active:bg-blue-700 disabled:opacity-50",children:[s.jsx(Ad,{}),W?"保存中...":"保存"]})]})]})]})}function Zo(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}const lA=["line","arrow","rect","ellipse","triangle","diamond","star","heart"],Ih=["nw","n","ne","e","se","s","sw","w"],Mg='system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif',Qo=1.25,Zy=2,Qy=160;function Da(e){return Math.round(16+e*4)}function cA(e){return Math.round((e-16)/4)}function sf(e){const t=e.map(o=>o.x),r=e.map(o=>o.y),n=Math.min(...t),a=Math.min(...r);return{x:n,y:a,width:Math.max(...t)-n,height:Math.max(...r)-a}}function Eg(e){const{start:t,end:r}=e;if(e.shape==="line")return[[t,r]];if(e.shape==="arrow"){const l=Math.atan2(r.y-t.y,r.x-t.x),c=Math.hypot(r.x-t.x,r.y-t.y),u=Math.min(c*.4,Math.max(16,e.width*3.5)),f=d=>({x:r.x-u*Math.cos(d),y:r.y-u*Math.sin(d)});return[[t,r],[f(l-Math.PI/6),r,f(l+Math.PI/6)]]}const n=sf([t,r]),a=n.x+n.width/2,o=n.y+n.height/2,i=(l,c)=>({x:n.x+n.width*l,y:n.y+n.height*c});switch(e.shape){case"rect":return[[i(0,0),i(1,0),i(1,1),i(0,1),i(0,0)]];case"triangle":return[[i(.5,0),i(1,1),i(0,1),i(.5,0)]];case"diamond":return[[i(.5,0),i(1,.5),i(.5,1),i(0,.5),i(.5,0)]];case"ellipse":return[Array.from({length:73},(l,c)=>{const u=c/72*Math.PI*2;return{x:a+n.width/2*Math.cos(u),y:o+n.height/2*Math.sin(u)}})];case"star":return[Array.from({length:11},(l,c)=>{const u=-Math.PI/2+c*Math.PI/5,f=c%2===0?1:.382;return i((f*Math.cos(u)+.951)/1.902,(f*Math.sin(u)+1)/1.809)})];case"heart":return[Array.from({length:97},(l,c)=>{const u=c/96*Math.PI*2,f=16*Math.sin(u)**3,d=-(13*Math.cos(u)-5*Math.cos(2*u)-2*Math.cos(3*u)-Math.cos(4*u));return{x:a+f/32*n.width,y:n.y+(d+12)/29*n.height}})]}}function ev(e,t){e.save(),e.font=`${t.fontSize}px ${Mg}`;const r=t.text.split(`
|
|
193
|
+
`),n=Math.max(t.fontSize*.5,...r.map(a=>e.measureText(a).width));return e.restore(),{width:n,height:r.length*t.fontSize*Qo}}function Ti(e,t){if(e.type==="text"){const a=ev(t,e);return{x:e.x,y:e.y,...a}}const r=e.type==="path"?sf(e.points):sf(Eg(e).flat()),n=e.width/2;return{x:r.x-n,y:r.y-n,width:r.width+n*2,height:r.height+n*2}}function dA(e,t,r){const n=r.x-t.x,a=r.y-t.y,o=n*n+a*a,i=o===0?0:Math.max(0,Math.min(1,((e.x-t.x)*n+(e.y-t.y)*a)/o));return Math.hypot(e.x-(t.x+i*n),e.y-(t.y+i*a))}function Ch(e,t){if(t.length===1)return Math.hypot(e.x-t[0].x,e.y-t[0].y);let r=1/0;for(let n=1;n<t.length;n++)r=Math.min(r,dA(e,t[n-1],t[n]));return r}function jh(e,t,r=0){return t.x>=e.x-r&&t.x<=e.x+e.width+r&&t.y>=e.y-r&&t.y<=e.y+e.height+r}function tv(e,t,r,n,a){if(e.type==="text")return jh(Ti(e,n),t,r);const o=e.width/2+r;return e.type==="path"?Ch(t,e.points)<=o:Eg(e).some(l=>Ch(t,l)<=o)?!0:a==="select"&&e.shape!=="line"&&e.shape!=="arrow"&&jh(Ti(e,n),t)}function Ml(e,t,r,n){for(let a=e.length-1;a>=0;a--)if(tv(e[a],t,r,n,"select"))return e[a];return null}function El(e,t){const r=t.includes("w")?0:t.includes("e")?1:.5,n=t.includes("n")?0:t.includes("s")?1:.5;return{x:e.x+e.width*r,y:e.y+e.height*n}}function uA(e,t,r,n=8,a){let o=e.x,i=e.y,l=e.x+e.width,c=e.y+e.height;if(t.includes("w")&&(o=Math.min(r.x,l-n)),t.includes("e")&&(l=Math.max(r.x,o+n)),t.includes("n")&&(i=Math.min(r.y,c-n)),t.includes("s")&&(c=Math.max(r.y,i+n)),!a||!Number.isFinite(a))return{x:o,y:i,width:l-o,height:c-i};const u=t.length===2,f=t==="e"||t==="w";let d=l-o,g=c-i;return(u?d/g>a:f)?g=d/a:d=g*a,{x:t.includes("w")?l-d:o,y:t.includes("n")?c-g:i,width:d,height:g}}function Sh(e,t){const r=Math.PI/4,n=Math.round(Math.atan2(t.y-e.y,t.x-e.x)/r)*r,a=Math.hypot(t.x-e.x,t.y-e.y);return{x:e.x+a*Math.cos(n),y:e.y+a*Math.sin(n)}}function hu(e){return e.type==="shape"&&(e.shape==="line"||e.shape==="arrow")}function af(e,t,r=1){var n;return(n=e.erase)==null?void 0:n.map(a=>({width:a.width*r,points:a.points.map(t)}))}function fA(e,t,r){const n=o=>({x:o.x+t,y:o.y+r}),a=af(e,n);return e.type==="text"?{...e,erase:a,x:e.x+t,y:e.y+r}:e.type==="path"?{...e,erase:a,points:e.points.map(n)}:{...e,erase:a,start:n(e.start),end:n(e.end)}}function gA(e,t,r,n){if(e.type==="text"){const l=n==="e"||n==="w"?r.width/Math.max(1,t.width):r.height/Math.max(1,t.height),c=Da(Zy)/e.fontSize,u=Da(Qy)/e.fontSize,f=Math.min(u,Math.max(c,l)),d=n.includes("w")?t.x+t.width*(1-f):t.x,g=n.includes("n")?t.y+t.height*(1-f):t.y;return{...e,erase:af(e,x=>({x:d+(x.x-t.x)*f,y:g+(x.y-t.y)*f}),f),x:d,y:g,fontSize:e.fontSize*f}}const a=i=>({x:t.width<1?i.x+r.x-t.x:r.x+(i.x-t.x)/t.width*r.width,y:t.height<1?i.y+r.y-t.y:r.y+(i.y-t.y)/t.height*r.height}),o=af(e,a);return e.type==="path"?{...e,erase:o,points:e.points.map(a)}:{...e,erase:o,start:a(e.start),end:a(e.end)}}function mA(e,t){const r=Ti(e,t);if(e.type==="text")return r;const n=e.width/2;return{x:r.x+n,y:r.y+n,width:r.width-n*2,height:r.height-n*2}}function Rg(e,t){if(e.save(),e.strokeStyle=t.color,e.fillStyle=t.color,e.lineWidth=t.width,e.lineCap="round",e.lineJoin="round",t.type==="text"){e.font=`${t.fontSize}px ${Mg}`;const r=t.fontSize*Qo,n=e.measureText(t.text),a=n.fontBoundingBoxAscent,o=(r-a-n.fontBoundingBoxDescent)/2+a;t.text.split(`
|
|
194
|
+
`).forEach((i,l)=>e.fillText(i,t.x,t.y+o+l*r)),e.restore();return}if(t.type==="path"){const r=t.points;if(r.length===1){e.beginPath(),e.arc(r[0].x,r[0].y,t.width/2,0,Math.PI*2),e.fill(),e.restore();return}e.beginPath(),e.moveTo(r[0].x,r[0].y);for(let a=1;a<r.length-1;a++){const o={x:(r[a].x+r[a+1].x)/2,y:(r[a].y+r[a+1].y)/2};e.quadraticCurveTo(r[a].x,r[a].y,o.x,o.y)}const n=r[r.length-1];e.lineTo(n.x,n.y),e.stroke(),e.restore();return}for(const r of Eg(t)){e.beginPath(),e.moveTo(r[0].x,r[0].y);for(const n of r.slice(1))e.lineTo(n.x,n.y);e.stroke()}e.restore()}const rv=1536;function hA(e,t=rv){const r=/^\s*(\d+)\s*[xX×]\s*(\d+)\s*$/.exec(e),n=r?Number(r[1]):1,a=r?Number(r[2]):1;return!n||!a?{width:t,height:t}:n>=a?{width:t,height:Math.round(t*a/n)}:{width:Math.round(t*n/a),height:t}}function nv(e,t){e.save(),e.globalCompositeOperation="destination-out",Rg(e,{type:"path",color:"#000",width:t.width,points:t.points}),e.restore()}function sv(e,t){const r=t.getContext("2d"),n=Ti(e,r),a=Math.floor(n.x)-2,o=Math.floor(n.y)-2;t.width=Math.max(1,Math.ceil(n.width)+4),t.height=Math.max(1,Math.ceil(n.height)+4),r.setTransform(1,0,0,1,-a,-o),Rg(r,e);for(const i of e.erase??[])nv(r,i);return r.setTransform(1,0,0,1,0,0),{x:a,y:o}}function pA(e,t,r){var a;if(!((a=t.erase)!=null&&a.length)){Rg(e,t);return}const n=sv(t,r);e.drawImage(r,n.x,n.y)}function xA(e,t){const r=t.getContext("2d",{willReadFrequently:!0});sv(e,t);const n=r.getImageData(0,0,t.width,t.height).data;for(let a=3;a<n.length;a+=4)if(n[a]>8)return!0;return!1}function bA(e,t){const[r]=p.useState(()=>{const j=w.getState(),A=e?j.inputImages.findIndex(N=>N.id===e):-1;return A>=0?Ya(j.prompt,A):[]}),[n,a]=p.useState(()=>r.map(j=>({...j,id:Zo()}))),[o,i]=p.useState(null),l=p.useRef(null),c=p.useRef(null),u=n.filter(j=>j.text.trim()).map(j=>({x:j.x,y:j.y,text:j.text.trim()})),f=JSON.stringify(u)!==JSON.stringify(r),d=(j,A)=>{a(N=>N.map(C=>C.id===j?{...C,...A}:C))},g=j=>{const A=l.current;l.current=null,a(j),A&&JSON.stringify(A)!==JSON.stringify(j)&&t(A)},m=j=>n.flatMap(A=>A.id!==o||A.id===j?[A]:A.text.trim()?[{...A,text:A.text.trim()}]:[]);return{comments:n,activeCommentId:o,commentData:u,commentsChanged:f,updateComment:d,createComment:(j,A)=>{const N=Zo();l.current=n,a([...n,{id:N,x:j,y:A,text:""}]),i(N)},finishComment:()=>{g(m()),i(null)},openComment:j=>{const A=m(j);g(A),l.current=A,i(j)},removeComment:j=>{l.current||(l.current=n),g(n.filter(A=>A.id!==j)),i(null)},moveComment:(j,A,N)=>{c.current||(c.current=n),d(j,{x:A,y:N})},finishMove:()=>{const j=c.current;c.current=null,j&&!l.current&&JSON.stringify(j)!==JSON.stringify(n)&&t(j)},restoreComments:j=>{l.current=null,c.current=null,a(j),i(null)},saveComments:(j,A=!1)=>{var U;const N=w.getState(),C=A?[...Ya(N.prompt,j),...u]:u,T=((U=N.promptSelection)==null?void 0:U.prompt)===N.prompt?N.promptSelection:{start:1/0,end:1/0},R=Zw(N.prompt,j,C,T.start,T.end);N.setPrompt(R.prompt),R.cursor!=null&&N.setPromptSelection({start:R.cursor,end:R.cursor})}}}const yA=280,$o=44,Rl=8;function vA(e,t,r){const n=Math.min(yA,r.right-r.left),a=f=>Math.min(Math.max(f,r.top),r.bottom-$o),o=a(t-Gs/2-$o/2),i=e+Gs+Rl;if(i+n<=r.right)return{left:i,top:o,width:n};const l=e-Rl-n;if(l>=r.left)return{left:l,top:o,width:n};const c=Math.min(Math.max(e+Gs/2-n/2,r.left),r.right-n),u=t+Rl;return{left:c,top:a(u+$o<=r.bottom?u:t-Gs-Rl-$o),width:n}}function wA({comments:e,activeId:t,docSize:r,viewScale:n,offset:a,bounds:o,interactive:i,canOpen:l,toDocPoint:c,onMove:u,onMoveEnd:f,onOpen:d,onChangeText:g,onFinish:m,onDelete:x}){const b=p.useRef(null),h=(N,C)=>{if(N.pointerType!=="touch"&&N.button!==0)return;N.stopPropagation(),N.currentTarget.setPointerCapture(N.pointerId);const T=N.currentTarget.getBoundingClientRect();b.current={id:C,startX:N.clientX,startY:N.clientY,offsetX:N.clientX-T.left,offsetY:N.clientY-T.bottom,moved:!1}},y=N=>{const C=b.current;if(!C||!N.currentTarget.hasPointerCapture(N.pointerId)||(N.stopPropagation(),!C.moved&&Math.hypot(N.clientX-C.startX,N.clientY-C.startY)<4))return;C.moved=!0;const T=c({clientX:N.clientX-C.offsetX,clientY:N.clientY-C.offsetY});u(C.id,Math.min(1,Math.max(0,T.x/r.width)),Math.min(1,Math.max(0,T.y/r.height)))},v=N=>{const C=b.current;C&&(N.stopPropagation(),b.current=null,N.currentTarget.hasPointerCapture(N.pointerId)&&N.currentTarget.releasePointerCapture(N.pointerId),C.moved?f():l&&d(C.id))},I=e.findIndex(N=>N.id===t),S=e[I],k=N=>({x:N.x*r.width*n+a.x,y:N.y*r.height*n+a.y}),j=S&&k(S),A=j&&o?vA(j.x,j.y,o):null;return s.jsxs(s.Fragment,{children:[e.map((N,C)=>{const{x:T,y:R}=k(N);return s.jsx(ky,{index:C,active:N.id===t,className:`absolute z-10 touch-none ${i?"":"pointer-events-none"}`,style:{left:T,top:R-Gs,cursor:l?"pointer":"grab"},onPointerDown:U=>h(U,N.id),onPointerMove:y,onPointerUp:v,onPointerCancel:v},N.id)}),S&&A&&s.jsxs("div",{className:"absolute z-20 flex items-center gap-1 rounded-2xl border border-gray-200/80 bg-white/95 p-1.5 shadow-xl backdrop-blur-md animate-fade-in dark:border-white/[0.08] dark:bg-gray-800/95",style:{...A,height:$o},onPointerDown:N=>N.stopPropagation(),onMouseDown:N=>{N.target instanceof HTMLInputElement||N.preventDefault()},children:[s.jsx(Ke,{tooltip:"删除评论",wrapperClassName:"relative inline-flex flex-none",className:"flex h-8 w-8 items-center justify-center rounded-xl text-gray-400 transition hover:bg-red-500/[0.1] hover:text-red-600 dark:hover:bg-red-500/[0.16]",onClick:()=>x(S.id),children:s.jsx(_r,{className:"h-4 w-4"})}),s.jsx("input",{autoFocus:!0,value:S.text,placeholder:"添加评论…","aria-label":`评论 ${I+1}`,onChange:N=>g(S.id,N.target.value),onBlur:m,onKeyDown:N=>{N.key==="Enter"&&!N.nativeEvent.isComposing&&N.currentTarget.blur()},className:"min-w-0 flex-1 bg-transparent px-1.5 text-sm text-gray-800 outline-none placeholder:text-gray-400 dark:text-gray-100 dark:placeholder:text-gray-500"}),s.jsx(Ke,{tooltip:"完成",wrapperClassName:"relative inline-flex flex-none",className:"flex h-8 w-8 items-center justify-center rounded-xl bg-blue-500 text-white shadow-sm transition hover:bg-blue-600",onClick:m,children:s.jsx(Ad,{})})]})]})}const Nh=[{value:"#6b7280",label:"灰色"},{value:"#92400e",label:"棕色"},{value:"#dc2626",label:"红色"},{value:"#f97316",label:"橙色"},{value:"#f59e0b",label:"琥珀色"},{value:"#16a34a",label:"绿色"},{value:"#0d9488",label:"青绿色"},{value:"#06b6d4",label:"青色"},{value:"#2563eb",label:"蓝色"},{value:"#4f46e5",label:"靛蓝色"},{value:"#9333ea",label:"紫色"},{value:"#db2777",label:"粉色"}],kA=100,IA={nw:"nwse-resize",se:"nwse-resize",ne:"nesw-resize",sw:"nesw-resize",n:"ns-resize",s:"ns-resize",e:"ew-resize",w:"ew-resize"},Ah={line:"直线",arrow:"箭头",rect:"矩形",ellipse:"椭圆",triangle:"三角形",diamond:"菱形",star:"星形",heart:"心形"};function Ph({shape:e}){return s.jsxs("svg",{className:"h-5 w-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",children:[e==="line"&&s.jsx("path",{d:"M5 19 19 5"}),e==="arrow"&&s.jsx("path",{d:"M5 19 19 5M10 5h9v9"}),e==="rect"&&s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"1.5"}),e==="ellipse"&&s.jsx("circle",{cx:"12",cy:"12",r:"8"}),e==="triangle"&&s.jsx("path",{d:"M12 4.5 20 19H4z"}),e==="diamond"&&s.jsx("path",{d:"m12 3 9 9-9 9-9-9z"}),e==="star"&&s.jsx("path",{d:"m12 3 2.6 5.6 6.1.7-4.5 4.2 1.2 6L12 16.6l-5.4 2.9 1.2-6-4.5-4.2 6.1-.7z"}),e==="heart"&&s.jsx("path",{d:"M12 20s-7.5-4.6-7.5-10.2A4.2 4.2 0 0 1 12 7.3a4.2 4.2 0 0 1 7.5 2.5C19.5 15.4 12 20 12 20z"})]})}function CA(){const e=w(t=>t.sketchBoard);return e?s.jsx(jA,{baseImageSrc:e.baseImageSrc,replaceImageId:e.replaceImageId}):null}function jA({baseImageSrc:e,replaceImageId:t}){const r=w(z=>z.setSketchBoard),n=w(z=>z.setConfirmDialog),a=w(z=>z.showToast),o=p.useRef(null),i=p.useRef(null),l=p.useRef(null),c=p.useRef(null),u=p.useRef(null),f=p.useRef(null),d=p.useRef(null),g=p.useRef(null),m=p.useRef([]),x=p.useRef([]),b=p.useRef(null),h=p.useRef(null),y=p.useRef(null),v=p.useRef(null),[I]=p.useState(()=>document.createElement("canvas")),[S]=p.useState(()=>document.createElement("canvas")),[k]=p.useState(()=>document.createElement("canvas")),j=S.getContext("2d"),[A]=p.useState(()=>document.documentElement.classList.contains("dark")),N=A?"#ffffff":"#18181b",C=A?"#232326":"#ffffff",[T,R]=p.useState(()=>e?null:hA(w.getState().params.size)),[U,W]=p.useState(null),[F,_]=p.useState([]),[O,J]=p.useState(null),[H,K]=p.useState(null),[,te]=p.useState(0),[P,B]=p.useState("pen"),[$,Q]=p.useState("rect"),[L,G]=p.useState(N),[se,Y]=p.useState(null),[le,ie]=p.useState(12),[D,ue]=p.useState(null),[ke,we]=p.useState(null),[We,Ne]=p.useState(!1),[Fe,Ee]=p.useState(null),[Ge,Xe]=p.useState("default"),[ht,Pe]=p.useState(!1),[ne,ge]=p.useState(!1),{comments:xe,activeCommentId:fe,commentData:be,commentsChanged:Z,updateComment:de,createComment:he,finishComment:pe,openComment:Be,removeComment:Oe,moveComment:Ue,finishMove:lt,restoreComments:ut,saveComments:Ve}=bA(t,z=>Pt(F,z)),He=Gy(l,c,!!T),vt=Ot();b.current=ke;const ct=T?He.frameWidth/T.width:0,rt=ct*He.transform.scale,V=!!T,X=F.find(z=>z.id===D)??null,me=m.current.length>0&&!ne,ve=x.current.length>0&&!ne,ae=F.length>0||Z||!!U&&!t,_e=()=>r(null),Ye=()=>{var z;if(!ne){if(b.current){(z=u.current)==null||z.blur();return}if(fe){pe();return}if(We){Ne(!1);return}if(F.length===0&&!Z){_e();return}n({title:"关闭画板",message:"当前草图尚未保存,确定要放弃吗?",confirmText:"放弃",tone:"danger",action:_e})}};Kr(!0,Ye),Lr(!0,f),p.useEffect(()=>{if(!e)return;let z=!1;return On(e).then(ee=>{if(z)return;const re=rv/Math.max(ee.naturalWidth,ee.naturalHeight);W(ee),R({width:Math.round(ee.naturalWidth*re),height:Math.round(ee.naturalHeight*re)})}).catch(ee=>{z||(a(`底图加载失败:${ee instanceof Error?ee.message:String(ee)}`,"error"),r(null))}),()=>{z=!0}},[e,r,a]),p.useEffect(()=>{if(!We)return;const z=ee=>{var re;(re=d.current)!=null&&re.contains(ee.target)||Ne(!1)};return document.addEventListener("pointerdown",z,!0),()=>document.removeEventListener("pointerdown",z,!0)},[We]);function wt(z,ee,re){const Ae=T;(I.width!==Ae.width||I.height!==Ae.height)&&(I.width=Ae.width,I.height=Ae.height);const $e=I.getContext("2d");$e.clearRect(0,0,Ae.width,Ae.height);for(const dt of ee)pA($e,dt,S);re&&nv($e,re),z.clearRect(0,0,Ae.width,Ae.height),z.fillStyle=C,z.fillRect(0,0,Ae.width,Ae.height),U&&z.drawImage(U,0,0,Ae.width,Ae.height),z.drawImage(I,0,0)}function xt(z){const ee=Ti(z,j),re=6/rt;return{x:ee.x-re,y:ee.y-re,width:ee.width+re*2,height:ee.height+re*2}}function qe(z,ee){const re=10/rt,Ae=dt=>Math.abs(dt.x-ee.x)<=re&&Math.abs(dt.y-ee.y)<=re;if(hu(z))return Ae(z.end)?"end":Ae(z.start)?"start":null;const $e=xt(z);return Ih.find(dt=>Ae(El($e,dt)))??null}p.useEffect(()=>{if(!T)return;const z=o.current.getContext("2d"),ee=F.filter(re=>re.id!==(ke==null?void 0:ke.id));wt(z,O?[...ee,O]:ee,H)},[F,O,H,ke,U,T]),p.useEffect(()=>{if(!T)return;const z=i.current.getContext("2d");if(z.clearRect(0,0,T.width,T.height),!X||ke)return;const ee=1/rt,re=9*ee;if(z.save(),z.strokeStyle="#3b82f6",z.fillStyle="#ffffff",z.lineWidth=1.5*ee,hu(X)){for(const $e of[X.start,X.end])z.beginPath(),z.arc($e.x,$e.y,re/1.6,0,Math.PI*2),z.fill(),z.stroke();z.restore();return}const Ae=xt(X);z.setLineDash([6*ee,4*ee]),z.strokeRect(Ae.x,Ae.y,Ae.width,Ae.height),z.setLineDash([]);for(const $e of Ih){const dt=El(Ae,$e);z.fillRect(dt.x-re/2,dt.y-re/2,re,re),z.strokeRect(dt.x-re/2,dt.y-re/2,re,re)}z.restore()},[X,ke,rt,T]);function tt(){te(z=>z+1)}function Pt(z,ee=xe){m.current.push({elements:z,comments:ee}),m.current.length>kA&&m.current.shift(),x.current=[],tt()}function Ct(z){Pt(F),_(z)}function Ht(){Jt();const z=m.current.pop();z&&(x.current.push({elements:F,comments:xe}),_(z.elements),ut(z.comments),ue(null),tt())}function Dt(){Jt();const z=x.current.pop();z&&(m.current.push({elements:F,comments:xe}),_(z.elements),ut(z.comments),ue(null),tt())}function Tt(){F.length!==0&&(Ct([]),ue(null))}p.useEffect(()=>{const z=ee=>{if(ee.target instanceof Element&&ee.target.closest('input:not([type="color"]), textarea, [contenteditable="true"]')||ne||h.current||w.getState().confirmDialog)return;const re=ee.ctrlKey||ee.metaKey,Ae=ee.key.toLowerCase();if(re&&Ae==="z"){ee.preventDefault(),ee.shiftKey?Dt():Ht();return}if(re&&Ae==="y"){ee.preventDefault(),Dt();return}(ee.key==="Delete"||ee.key==="Backspace")&&D&&(ee.preventDefault(),Ct(F.filter($e=>$e.id!==D)),ue(null))};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[F,xe,D,ne]);function Ce(z){const ee=o.current.getBoundingClientRect();return{x:(z.clientX-ee.left)/ee.width*T.width,y:(z.clientY-ee.top)/ee.height*T.height}}function Or(z){ue((z==null?void 0:z.id)??null),z&&(G(z.color),z.color!==N&&!Nh.some(ee=>ee.value===z.color)&&Y(z.color),ie(z.type==="text"?cA(z.fontSize):z.width))}function nt(z){ue(null),lr.flushSync(()=>we(z));const ee=u.current;ee&&(ee.focus(),ee.setSelectionRange(ee.value.length,ee.value.length))}function tr(){const z=b.current;if(!z)return;b.current=null,we(null);const ee=z.text.replace(/\s+$/,""),re=F.find($e=>$e.id===z.id);if(!ee.trim()){re&&Ct(F.filter($e=>$e.id!==z.id));return}const Ae={...z,text:ee};if(!re){Ct([...F,Ae]);return}re.type==="text"&&re.text===ee&&re.fontSize===Ae.fontSize&&re.color===Ae.color||Ct(F.map($e=>$e.id===Ae.id?Ae:$e))}function Le(){const z=g.current;g.current=null,J(null),K(null),z&&"before"in z&&_(z.before)}function gt(z){let ee=!1;const re=[];for(const Ae of F){if(!z.points.some(Je=>tv(Ae,Je,z.width/2,j,"erase"))){re.push(Ae);continue}ee=!0;const dt={...Ae,erase:[...Ae.erase??[],z]};xA(dt,k)&&re.push(dt)}ee&&Ct(re)}const Ut=z=>{var It;if(!T||ne||z.pointerType!=="touch"&&z.button!==0||z.target===u.current)return;if(b.current){(It=u.current)==null||It.blur();return}z.currentTarget.setPointerCapture(z.pointerId);const ee=He.pointerDown(z);if(ee==="pan")return;if(ee==="pinch"){Le();return}if(He.isPinching()||g.current)return;if(fe){pe();return}Ne(!1);const re=Ce(z),Ae=z.pointerId,$e=6/rt;if(P==="text"){if(re.x<0||re.y<0||re.x>T.width||re.y>T.height)return;const it=Ml(F.filter(ft=>ft.type==="text"),re,$e,j);if((it==null?void 0:it.type)==="text"){Or(it),nt(it);return}const Yt=Da(le);nt({id:Zo(),type:"text",color:L,width:le,x:re.x,y:re.y-Yt*Qo/2,text:"",fontSize:Yt});return}if(P==="comment"){if(re.x<0||re.y<0||re.x>T.width||re.y>T.height)return;g.current={kind:"comment",pointerId:Ae,point:re};return}if(P==="pen"){const it={id:Zo(),type:"path",color:L,width:le,points:[re]};g.current={kind:"draw",pointerId:Ae,el:it},J(it);return}if(P==="shape"){const it={id:Zo(),type:"shape",shape:$,color:L,width:le,start:re,end:re};g.current={kind:"shape",pointerId:Ae,el:it},J(it);return}if(P==="eraser"){const it={width:le,points:[re]};g.current={kind:"erase",pointerId:Ae,stroke:it},K(it);return}const dt=X?qe(X,re):null;if(X&&dt){if(dt==="start"||dt==="end"){hu(X)&&(g.current={kind:"endpoint",pointerId:Ae,before:F,target:X,handle:dt});return}const it=xt(X),Yt=mA(X,j),ft=El(it,dt),At=El(Yt,dt);g.current={kind:"resize",pointerId:Ae,before:F,target:X,handle:dt,from:Yt,offset:{x:ft.x-At.x,y:ft.y-At.y}};return}const Je=Ml(F,re,$e,j);Or(Je),Je&&(g.current={kind:"move",pointerId:Ae,before:F,start:re,targetId:Je.id})},jr=z=>{if(!T||He.pointerMove(z))return;const ee=Ce(z);z.pointerType!=="touch"&&Ee(ee);const re=g.current;if(!re){if(P!=="select")return;const Je=X?qe(X,ee):null,It=Je==="start"||Je==="end"?"crosshair":Je?IA[Je]:null;Xe(It??(Ml(F,ee,6/rt,j)?"move":"default"));return}if(re.pointerId!==z.pointerId)return;if(re.kind==="draw"){const Je=re.el.points[re.el.points.length-1];if(Math.hypot(ee.x-Je.x,ee.y-Je.y)<1)return;re.el={...re.el,points:[...re.el.points,ee]},J(re.el);return}if(re.kind==="erase"){const Je=re.stroke.points,It=Je[Je.length-1],it=Math.ceil(Math.hypot(ee.x-It.x,ee.y-It.y)/Math.max(1,re.stroke.width/3)),Yt=Array.from({length:it},(ft,At)=>({x:It.x+(ee.x-It.x)*(At+1)/it,y:It.y+(ee.y-It.y)*(At+1)/it}));re.stroke={...re.stroke,points:[...Je,...Yt]},K(re.stroke);return}if(re.kind==="shape"){const Je=re.el,It=ee.x-Je.start.x,it=ee.y-Je.start.y,Yt=Math.max(Math.abs(It),Math.abs(it)),ft=z.shiftKey?Je.shape==="line"||Je.shape==="arrow"?Sh(Je.start,ee):{x:Je.start.x+Math.sign(It||1)*Yt,y:Je.start.y+Math.sign(it||1)*Yt}:ee;re.el={...Je,end:ft},J(re.el);return}if(re.kind==="comment")return;if(re.changed=!0,re.kind==="move"){const Je=ee.x-re.start.x,It=ee.y-re.start.y;_(re.before.map(it=>it.id===re.targetId?fA(it,Je,It):it));return}if(re.kind==="endpoint"){const Je=re.target,It=re.handle==="start"?Je.end:Je.start,it=z.shiftKey?Sh(It,ee):ee,Yt=re.handle==="start"?{...Je,start:it}:{...Je,end:it};_(re.before.map(ft=>ft.id===Je.id?Yt:ft));return}const Ae=re.target,$e=!z.shiftKey||Ae.type==="text"?void 0:Ae.type==="shape"?1:re.from.width/re.from.height,dt=uA(re.from,re.handle,{x:ee.x-re.offset.x,y:ee.y-re.offset.y},8,$e);_(re.before.map(Je=>Je.id===Ae.id?gA(Ae,re.from,dt,re.handle):Je))},rr=z=>{He.pointerUp(z),z.currentTarget.hasPointerCapture(z.pointerId)&&z.currentTarget.releasePointerCapture(z.pointerId);const ee=g.current;if(!(!ee||ee.pointerId!==z.pointerId)){if(g.current=null,ee.kind==="comment"){if(z.type!=="pointerup")return;lr.flushSync(()=>he(ee.point.x/T.width,ee.point.y/T.height));return}if(ee.kind==="draw"){Ct([...F,ee.el]),J(null);return}if(ee.kind==="erase"){gt(ee.stroke),K(null);return}if(ee.kind==="shape"){J(null);const re=ee.el;if(Math.hypot(re.end.x-re.start.x,re.end.y-re.start.y)<4/rt)return;Ct([...F,re]),B("select"),ue(re.id);return}ee.changed&&Pt(ee.before)}},Ft=z=>{if(!T||P!=="select")return;const ee=Ml(F,Ce(z),6/rt,j);(ee==null?void 0:ee.type)==="text"&&nt(ee)},Sr=z=>{Y(z),G(z);const ee=b.current;if(ee){we({...ee,color:z});return}X&&(y.current||(y.current=F),_(re=>re.map(Ae=>Ae.id===X.id?{...Ae,color:z}:Ae)))},Jt=()=>{const z=y.current;y.current=null,z&&Pt(z)},cr=p.useRef(Jt);cr.current=Jt,p.useEffect(()=>{const z=v.current,ee=()=>cr.current();return z.addEventListener("change",ee),()=>z.removeEventListener("change",ee)},[]);const jn=z=>{G(z);const ee=b.current;if(ee){we({...ee,color:z});return}X&&X.color!==z&&Ct(F.map(re=>re.id===X.id?{...re,color:z}:re))},Xr=z=>{if(z===le)return;ie(z);const ee=b.current;if(ee){we({...ee,width:z,fontSize:Da(z)});return}X&&_(re=>re.map(Ae=>Ae.id!==X.id?Ae:Ae.type==="text"?{...Ae,width:z,fontSize:Da(z)}:{...Ae,width:z}))},Mt=z=>{var ee;b.current&&((ee=u.current)==null||ee.blur()),B(z),Ne(!1),z!=="select"&&ue(null)},os=async()=>{if(!T||!ae||ne)return;const z=w.getState(),ee=t?z.inputImages.findIndex(re=>re.id===t):-1;if(ee<0&&z.inputImages.length>=yr){a(`参考图数量已达上限(${yr} 张),无法继续添加`,"error");return}if(ee>=0&&F.length===0){Ve(ee),a("评论已更新","success"),_e();return}try{ge(!0);const re=document.createElement("canvas");re.width=T.width,re.height=T.height,wt(re.getContext("2d"),F);const Ae=await oa(await td(re,"image/png")),$e=await Qn(Ae,"upload");Xt($e,Ae);const dt=w.getState().inputImages.findIndex(Je=>Je.id===$e);if(dt>=0&&dt!==ee){be.length&&Ve(dt,!0),a(be.length?`参考图中已有相同的图片,评论已合并到图${dt+1}`:"参考图中已有相同的图片","info"),_e();return}ee>=0?(w.getState().replaceInputImage(ee,{id:$e,dataUrl:Ae}),a("参考图已更新","success")):(w.getState().addInputImage({id:$e,dataUrl:Ae}),a("草图已添加到参考图","success")),Z&&Ve(w.getState().inputImages.findIndex(Je=>Je.id===$e)),_e()}catch(re){console.error(re),a(`草图保存失败:${re instanceof Error?re.message:String(re)}`,"error"),ge(!1)}},Ar=!(P==="pen"||P==="eraser"||P==="shape")||!T||He.isAltPressed?null:ht?Fe??He.getVisibleCenter(ct):P==="shape"?null:Fe,an=He.isPanning?"grabbing":He.isAltPressed?"grab":P==="select"?Ge:P==="text"?"text":Ar?"none":"crosshair",oe=ke?ev(j,ke):null,Te=()=>{const z=c.current,ee=z.getBoundingClientRect(),re=l.current.getBoundingClientRect(),Ae=getComputedStyle(z);return{left:ee.left+parseFloat(Ae.paddingLeft)-re.left,right:ee.right-parseFloat(Ae.paddingRight)-re.left,top:ee.top-re.top,bottom:ee.bottom-re.top}},Qe=z=>`h-7 w-7 flex-none rounded-full transition-transform hover:scale-110 ${z?"ring-2 ring-blue-500 ring-offset-2 ring-offset-white dark:ring-offset-gray-900":"ring-1 ring-inset ring-black/10 dark:ring-white/15"}`;return s.jsxs(Dy,{onBackdropClick:Ye,children:[s.jsx(Ly,{left:s.jsx(Ke,{tooltip:"关闭",className:hs,disabled:ne,onClick:Ye,children:s.jsx(qt,{className:"h-5 w-5"})}),center:s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:"选择",className:fs(P==="select"),disabled:!V,onClick:()=>Mt("select"),children:s.jsx("svg",{className:"h-5 w-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M5 4.5 19 11l-6.2 1.8L10 19z"})})}),s.jsx(Ke,{tooltip:"画笔",className:fs(P==="pen"),disabled:!V,onClick:()=>Mt("pen"),children:s.jsx(Fy,{})}),s.jsx(Ke,{tooltip:"文字",className:fs(P==="text"),disabled:!V,onClick:()=>Mt("text"),children:s.jsx("svg",{className:"h-5 w-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M5 7V4.5h14V7M12 4.5v15M9 19.5h6"})})}),s.jsxs("div",{ref:d,className:"relative inline-flex",children:[s.jsx(Ke,{tooltip:`图形:${Ah[$]}`,className:fs(P==="shape"),disabled:!V,onClick:()=>{var z;b.current&&((z=u.current)==null||z.blur()),Ne(ee=>!ee)},children:P==="shape"?s.jsx(Ph,{shape:$}):s.jsxs("svg",{className:"h-5 w-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M8.3 10a.7.7 0 0 1-.63-1.08L11.4 3a.7.7 0 0 1 1.2-.04L16.3 8.9a.7.7 0 0 1-.57 1.1z"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("circle",{cx:"17.5",cy:"17.5",r:"3.5"})]})}),We&&s.jsx("div",{className:"absolute left-1/2 top-full z-30 mt-2 grid w-max -translate-x-1/2 grid-cols-4 gap-1 rounded-2xl border border-gray-200/80 bg-white/95 p-1.5 shadow-xl backdrop-blur-md animate-fade-in dark:border-white/[0.08] dark:bg-gray-800/95",children:lA.map(z=>s.jsx(Ke,{tooltip:Ah[z],className:`flex h-9 w-9 items-center justify-center rounded-xl transition ${P==="shape"&&$===z?"bg-blue-50 text-blue-500 dark:bg-blue-500/15 dark:text-blue-400":"text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-white/[0.08]"}`,onClick:()=>{Q(z),Mt("shape")},children:s.jsx(Ph,{shape:z})},z))})]}),s.jsx(Ke,{tooltip:"橡皮擦",className:fs(P==="eraser"),disabled:!V,onClick:()=>Mt("eraser"),children:s.jsx($y,{})}),s.jsx(Ke,{tooltip:"评论",className:fs(P==="comment"),disabled:!V,onClick:()=>Mt("comment"),children:s.jsx("svg",{className:"h-5 w-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.8,strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M5.5 5h13A1.5 1.5 0 0 1 20 6.5v8.5a1.5 1.5 0 0 1-1.5 1.5H12l-4.5 3.5v-3.5h-2A1.5 1.5 0 0 1 4 15V6.5A1.5 1.5 0 0 1 5.5 5zM8.5 9.5h7M8.5 12.5h4"})})})]}),right:s.jsxs(s.Fragment,{children:[s.jsx(Ke,{tooltip:"撤销",className:hs,disabled:!me,onClick:Ht,children:s.jsx(zy,{})}),s.jsx(Ke,{tooltip:"重做",className:hs,disabled:!ve,onClick:Dt,children:s.jsx(Wy,{})}),s.jsx(Ke,{tooltip:"清空画布",wrapperClassName:"relative hidden sm:inline-flex",className:hs,disabled:F.length===0||ne,onClick:Tt,children:s.jsx(Hy,{})})]})}),s.jsxs("div",{className:"relative min-h-0 flex-1 bg-gray-100/70 dark:bg-black/25",children:[s.jsx("div",{ref:c,className:"absolute inset-0 flex touch-none select-none items-center justify-center overflow-hidden py-4 pl-16 pr-4 sm:px-20 sm:py-6",style:{containerType:"size",cursor:an},onMouseDown:z=>{z.target instanceof HTMLTextAreaElement||z.target instanceof HTMLInputElement||z.preventDefault()},onPointerDown:Ut,onPointerMove:jr,onPointerUp:rr,onPointerCancel:rr,onLostPointerCapture:rr,onPointerLeave:()=>Ee(null),onDoubleClick:Ft,children:T&&s.jsxs("div",{ref:l,className:"relative max-h-full max-w-full",style:{aspectRatio:`${T.width} / ${T.height}`,width:`min(100%, 100cqh * ${T.width/T.height})`},children:[s.jsxs("div",{className:"absolute inset-0 will-change-transform",style:{transform:`matrix(${He.transform.scale}, 0, 0, ${He.transform.scale}, ${He.transform.x}, ${He.transform.y})`,transformOrigin:"0 0"},children:[s.jsxs("div",{className:"absolute inset-0 overflow-hidden rounded-lg shadow-sm ring-1 ring-black/5 dark:ring-white/10",style:{background:C},children:[s.jsx("canvas",{ref:o,width:T.width,height:T.height,className:"absolute inset-0 h-full w-full"}),s.jsx("canvas",{ref:i,width:T.width,height:T.height,className:"pointer-events-none absolute inset-0 h-full w-full"})]}),ke&&s.jsx("textarea",{ref:u,value:ke.text,onChange:z=>we({...ke,text:z.target.value}),onBlur:tr,onKeyDown:z=>{z.key==="Enter"&&(z.ctrlKey||z.metaKey)&&z.currentTarget.blur()},spellCheck:!1,wrap:"off",className:"absolute resize-none overflow-hidden whitespace-pre border-0 bg-transparent p-0 outline-dashed outline-[1.5px] outline-offset-[6px] outline-blue-500",style:{left:ke.x*ct,top:ke.y*ct,width:(((oe==null?void 0:oe.width)??0)+ke.fontSize)*ct,height:((oe==null?void 0:oe.height)??ke.fontSize*Qo)*ct,fontSize:ke.fontSize*ct,lineHeight:Qo,fontFamily:Mg,color:ke.color,caretColor:ke.color}})]}),Ar&&s.jsx(Uy,{x:Ar.x*rt+He.transform.x,y:Ar.y*rt+He.transform.y,size:le*rt}),s.jsx(wA,{comments:xe,activeId:fe,docSize:T,viewScale:rt,offset:He.transform,bounds:fe?Te():null,interactive:P==="comment"||P==="select",canOpen:P==="comment",toDocPoint:Ce,onMove:Ue,onMoveEnd:lt,onOpen:Be,onChangeText:(z,ee)=>de(z,{text:ee}),onFinish:pe,onDelete:Oe})]})}),!V&&s.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center text-sm text-gray-500 dark:text-gray-400",children:"正在载入底图..."}),s.jsx(Oy,{value:le,min:Zy,max:Qy,label:P==="text"?"字号":"粗细",displayValue:P==="text"?Da(le):le,disabled:!V,onChange:Xr,onAdjustStart:()=>{h.current=F,Pe(!0)},onAdjustEnd:()=>{Pe(!1);const z=h.current;h.current=null,z&&z!==F&&Pt(z)}}),He.isZoomed&&s.jsx(By,{onClick:()=>He.commit()})]}),s.jsxs("div",{className:"flex flex-none items-center gap-3 px-3 py-3 sm:px-4",children:[s.jsxs("div",{ref:f,onMouseDown:z=>z.preventDefault(),className:"flex min-w-0 flex-1 items-center gap-2.5 overflow-x-auto px-2 py-1.5 sm:justify-center [scrollbar-width:none]",children:[s.jsxs("span",{className:"relative inline-flex flex-none",...vt.handlers,onClick:()=>{vt.dismiss(),se&&jn(se)},children:[s.jsxs("label",{className:`${Qe(se!==null&&L===se)} relative cursor-pointer overflow-hidden`,style:{background:"conic-gradient(from 90deg, #ef4444, #f59e0b, #eab308, #22c55e, #06b6d4, #3b82f6, #8b5cf6, #ec4899, #ef4444)"},children:[se&&s.jsx("span",{className:"absolute inset-[5px] rounded-full ring-2 ring-white",style:{background:se}}),s.jsx("input",{ref:v,type:"color",value:se??(/^#[0-9a-f]{6}$/i.test(L)?L:"#000000"),onChange:z=>Sr(z.target.value),onBlur:Jt,className:"absolute inset-0 cursor-pointer opacity-0","aria-label":"自定义颜色"})]}),s.jsx(pt,{visible:vt.visible,className:"whitespace-nowrap",children:"自定义颜色"})]}),[{value:N,label:A?"白色":"黑色"},...Nh].map(z=>s.jsx(Ke,{tooltip:z.label,wrapperClassName:"relative inline-flex flex-none",className:Qe(L===z.value),onClick:()=>jn(z.value),children:s.jsx("span",{className:"block h-full w-full rounded-full ring-1 ring-inset ring-black/10 dark:ring-white/15",style:{background:z.value}})},z.value))]}),s.jsxs("button",{onClick:os,disabled:!ae||ne,className:"flex h-10 flex-none items-center gap-1.5 rounded-xl bg-blue-500 px-4 text-sm font-medium text-white shadow-sm transition hover:bg-blue-600 active:bg-blue-700 disabled:opacity-50",children:[s.jsx(Ad,{}),ne?"保存中...":"完成"]})]})]})}const pu="flex h-full w-[46px] items-center justify-center text-gray-500 transition-colors dark:text-gray-400";function SA(){const[e,t]=p.useState(!1);p.useEffect(()=>{const n=_o(),a=()=>n.isMaximized().then(t).catch(l=>console.warn("无法读取窗口状态:",l));a();let o=0;const i=n.onResized(()=>{cancelAnimationFrame(o),o=requestAnimationFrame(()=>void a())});return()=>{cancelAnimationFrame(o),i.then(l=>l())}},[]);const r=(n,a)=>a().catch(o=>console.error(`${n}失败:`,o));return s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-x-0 top-0 z-[130] flex select-none",style:{height:cf},children:[s.jsx("div",{"data-tauri-drag-region":!0,className:"flex-1"}),s.jsx("button",{type:"button","aria-label":"最小化",className:`${pu} hover:bg-black/[0.06] dark:hover:bg-white/[0.08]`,onClick:()=>r("最小化窗口",()=>_o().minimize()),children:s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:s.jsx("path",{d:"M0 5h10",stroke:"currentColor"})})}),s.jsx("button",{type:"button","aria-label":e?"向下还原":"最大化",className:`${pu} hover:bg-black/[0.06] dark:hover:bg-white/[0.08]`,onClick:()=>r("切换最大化",()=>_o().toggleMaximize()),children:e?s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 2.5V.5h7v7h-2M.5 2.5h7v7h-7z"})}):s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor","aria-hidden":"true",children:s.jsx("path",{d:"M.5.5h9v9h-9z"})})}),s.jsx("button",{type:"button","aria-label":"关闭",className:`${pu} hover:bg-[#c42b1c] hover:text-white dark:hover:text-white`,onClick:()=>r("关闭窗口",()=>_o().close()),children:s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:s.jsx("path",{d:"M0 0l10 10M10 0L0 10",stroke:"currentColor"})})})]})}function NA(){const[e,t]=p.useState(null),r=w(I=>I.showToast),n=w(I=>I.inputImages),a=w(I=>I.setDetailTaskId),o=w(I=>I.setLightboxImageId),i=w(I=>I.setMaskEditorImageId),l=p.useRef(null);if(p.useEffect(()=>{if(AA())return;const I=S=>{var j;const k=S.target;if(k&&k.tagName==="IMG"){const A=k;if(!A.src)return;const N=/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,C=window.matchMedia("(pointer: coarse)").matches;if(N&&C)return;const T=vy();if(!T&&A.classList.contains("object-contain"))return;S.preventDefault(),t({src:A.src,imageId:A.dataset.imageId,outputImageIds:((j=A.dataset.outputImageIds)==null?void 0:j.split(",").filter(Boolean))??[],canCopyImage:T,x:S.clientX,y:S.clientY})}};return window.addEventListener("contextmenu",I),()=>{window.removeEventListener("contextmenu",I)}},[]),p.useEffect(()=>{if(!e)return;const I=S=>{l.current&&S.target instanceof Node&&l.current.contains(S.target)||(S.target instanceof Element&&S.target.closest("[data-lightbox-root]")&&window.dispatchEvent(new Event("image-context-menu-dismiss-lightbox-click")),(S.type==="mousedown"||S.type==="touchstart")&&Rc(),t(null))};return window.addEventListener("mousedown",I,{capture:!0}),window.addEventListener("touchstart",I,{capture:!0}),window.addEventListener("wheel",I,{capture:!0}),window.addEventListener("scroll",I,{capture:!0}),window.addEventListener("resize",I),()=>{window.removeEventListener("mousedown",I,{capture:!0}),window.removeEventListener("touchstart",I,{capture:!0}),window.removeEventListener("wheel",I,{capture:!0}),window.removeEventListener("scroll",I,{capture:!0}),window.removeEventListener("resize",I)}},[e]),!e)return null;const c=async()=>e.imageId?await kt(e.imageId)??e.src:e.src,u=async I=>{I.stopPropagation(),t(null);try{await yy(c()),r("图片已复制","success")}catch(S){console.error(S),r($r("复制失败",S),"error")}},f=async I=>{I.stopPropagation();const S=e.imageId,k=e.src;t(null);try{let j="";if(S){const C=w.getState().tasks.find(T=>{var R;return(R=T.outputImages)==null?void 0:R.includes(S)});C?j=`task-${C.id}`:j=`image-${S}`}else j=`image-${di(new Date)}`;const A=await Xn([S||k],j);if(A.canceled)return;A.successCount===0?r(Zt(A.error),"error"):r(Kn("下载成功",A.location),"success")}catch(j){console.error(j),r(Zt(j),"error")}},d=async I=>{I.stopPropagation();const S=e.outputImageIds;if(t(null),!(S.length<=1))try{let k="";if(S[0]){const C=w.getState().tasks.find(T=>{var R;return(R=T.outputImages)==null?void 0:R.includes(S[0])});C&&(k=`task-${C.id}`)}k||(k=`batch-${di(new Date)}`);const A=w.getState().settings.zipDownloadRoutes.includes("image-context-menu-all")?await so(Ni(S,k),k):await Xn(S,k);if(A.canceled)return;A.successCount===0?r(Zt(A.error),"error"):A.failCount>0?r(`部分下载失败:成功 ${A.successCount},失败 ${A.failCount}`,"error"):r(Kn(A.successCount>1?`下载成功:${A.successCount} 张图片`:"下载成功",A.location),"success")}catch(k){console.error(k),r(Zt(k),"error")}},g=async I=>{if(I.stopPropagation(),t(null),n.length>=yr){r(`参考图数量已达上限(${yr} 张),无法继续添加`,"error");return}try{const S=await c();await Lb(S),a(null),o(null),i(null),r("已加入参考图","success")}catch(S){console.error(S),r(`加入参考图失败:${S instanceof Error?S.message:String(S)}`,"error")}};let m=e.x,x=e.y;const b=120,h=e.outputImageIds.length>1,v=((e.canCopyImage?1:0)+1+(h?1:0)+1)*32+32;return m+b>window.innerWidth&&(m-=b),x+v>window.innerHeight&&(x-=v),s.jsxs("div",{ref:l,className:"fixed z-[9999] bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-100 dark:border-gray-700 py-1 w-[120px] overflow-hidden animate-fade-in",style:{left:m,top:x},onContextMenu:I=>I.preventDefault(),children:[e.canCopyImage&&s.jsxs("button",{onClick:u,className:"w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",children:[s.jsx(zr,{className:"w-4 h-4 flex-shrink-0"}),"复制"]}),s.jsxs("button",{onClick:f,className:"w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",children:[s.jsx(qs,{className:"w-4 h-4 flex-shrink-0"}),"下载"]}),h&&s.jsxs("button",{onClick:d,className:"w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",children:[s.jsx(qs,{className:"w-4 h-4 flex-shrink-0"}),"下载全部"]}),s.jsxs("button",{onClick:g,className:"w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 flex items-center gap-2 transition-colors",children:[s.jsx(Hr,{className:"w-4 h-4 flex-shrink-0"}),"编辑"]})]})}function AA(){try{return window.self!==window.top}catch{return!0}}function PA(){const e=w(d=>d.supportPromptOpen),t=w(d=>d.dismissSupportPrompt),r=w(d=>d.confirmDialog),n=w(d=>d.detailTaskId),a=w(d=>d.lightboxImageId),o=w(d=>d.showSettings),i=w(d=>d.maskEditorImageId),l=w(d=>d.sketchBoard),u=!!(w(d=>!!d.privacyMode)||r||n||a||o||i||l),f=e&&!u;return Kr(f,t),Lr(f),f?lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",onClick:t,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 w-full max-w-sm rounded-[2rem] border border-white/50 bg-white/95 p-6 pb-7 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10 flex flex-col",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"absolute right-4 top-4",children:s.jsx("button",{type:"button",onClick:t,className:"rounded-full p-2 text-gray-400 transition-colors hover:bg-gray-200 hover:text-gray-600 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})})}),s.jsx("div",{className:"mb-5 mt-4 flex justify-center",children:s.jsx("div",{className:"flex h-20 w-20 items-center justify-center rounded-[1.5rem] bg-[#f4f0ff] text-[#946ce6] dark:bg-[#946ce6]/10 dark:text-[#bba3f2]",children:s.jsx("svg",{className:"h-10 w-10",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2.5,d:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"})})})}),s.jsx("h3",{className:"mb-3 text-center text-xl font-bold text-gray-800 dark:text-gray-100",children:"感谢使用 🎉"}),s.jsxs("p",{className:"mb-8 px-2 text-center text-[15px] leading-relaxed text-gray-500 dark:text-gray-400",children:["你已经成功生成了超过 ",s.jsx("strong",{className:"font-semibold text-gray-800 dark:text-gray-200",children:"50"})," 张图片!",s.jsx("br",{}),"如果这个工具对你有所帮助,",s.jsx("br",{}),"欢迎赞助作者,或反馈分享你的建议。"]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:[s.jsxs("a",{href:"https://www.ifdian.net/a/cooksleep",target:"_blank",rel:"noopener noreferrer",onClick:t,className:"flex w-full sm:w-auto flex-1 items-center justify-center gap-2 rounded-2xl bg-[#946ce6] px-5 py-3.5 text-[15px] font-semibold text-white transition-all hover:bg-[#8358dc] active:scale-[0.98] dark:bg-[#946ce6] dark:hover:bg-[#a885ee]",children:[s.jsx("svg",{className:"h-4 w-4",fill:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{d:"M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"})}),"赞助作者"]}),s.jsxs("a",{href:"https://github.com/CookSleep/gpt_image_playground/issues",target:"_blank",rel:"noopener noreferrer",onClick:t,className:"flex w-full sm:w-auto flex-1 items-center justify-center gap-2 rounded-2xl bg-[#f4f4f5] px-5 py-3.5 text-[15px] font-semibold text-gray-600 transition-all hover:bg-gray-200 active:scale-[0.98] dark:bg-[#27272a] dark:text-gray-300 dark:hover:bg-[#3f3f46]",children:[s.jsx("svg",{className:"h-[18px] w-[18px] opacity-70",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"})}),"反馈问题"]})]})]})]}),document.body):null}const Th="dismissed-announcements",Mh=new URL("./",window.location.href).href;function TA(){var r;const e=navigator,t=w.getState().tasks;return{platform:De?"client":"web",os:oy(e.userAgent,(r=e.userAgentData)==null?void 0:r.platform,e.maxTouchPoints),language:e.language,version:"0.8.4",imageCount:to(t),taskCount:t.filter(n=>!vn(n)).length,standalone:!De&&(window.matchMedia("(display-mode: standalone)").matches||e.standalone===!0),now:new Date().toISOString()}}let Eh=!1;function MA(e){const[t,r]=p.useState([]),[n,a]=p.useState(()=>G5(Qi(Th)));return p.useEffect(()=>{!e||Eh||(Eh=!0,(async()=>{try{const l=await fetch(`${Mh}announcements.json`,{cache:"no-store"});if(!l.ok)throw new Error(`HTTP ${l.status}`);r(J5(q5(await l.json(),Mh),TA(),n))}catch(l){console.warn("读取公告失败:",l)}})())},[e]),{pending:t.filter(l=>!n.includes(l.id)),dismiss:l=>{const c=[...n,...l];el(Th,JSON.stringify(c)),a(c)}}}function EA({ready:e}){const{pending:t,dismiss:r}=MA(e),n=t[0],a=p.useRef(null),o=w(x=>!!(x.privacyMode||x.confirmDialog||x.supportPromptOpen||x.showSettings||x.detailTaskId||x.lightboxImageId||x.maskEditorImageId||x.sketchBoard||x.isManageCollectionsModalOpen||x.favoritePickerTaskIds)),i=er(x=>x.modalOpen),l=x5(),c=!!n&&!o&&!i,u=()=>r(t.map(x=>x.id)),f=()=>r([n.id]);if(Kr(c,u),Lr(c,a),!c||!n)return null;const d=n.media,g=(d==null?void 0:d.type)==="html"?new URL(d.src):null;g==null||g.searchParams.set("theme",l?"dark":"light");const m=/\n\s*\n|^\s*([-*+]|\d+\.)\s/m.test(n.content.trim());return lr.createPortal(s.jsxs("div",{"data-no-drag-select":!0,className:"fixed inset-0 z-[70] flex items-center justify-center p-4",onClick:u,children:[s.jsx("div",{className:"absolute inset-0 bg-black/30 backdrop-blur-sm animate-overlay-in"}),s.jsxs("div",{className:"relative z-10 flex max-h-[85vh] w-full max-w-md flex-col overflow-hidden rounded-3xl border border-white/50 bg-white/95 shadow-2xl ring-1 ring-black/5 animate-modal-in dark:border-white/[0.08] dark:bg-gray-900/95 dark:ring-white/10",onClick:x=>x.stopPropagation(),children:[s.jsx("button",{type:"button",onClick:u,className:"absolute right-3 top-3 z-10 rounded-full bg-white/70 p-1 text-gray-400 backdrop-blur transition hover:bg-gray-100 hover:text-gray-600 dark:bg-gray-900/60 dark:hover:bg-white/[0.08] dark:hover:text-gray-200","aria-label":"关闭",children:s.jsx(qt,{className:"h-5 w-5"})}),s.jsxs("div",{ref:a,className:"custom-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pt-5 pb-3 text-center",children:[d&&s.jsx("div",{className:"mb-5 overflow-hidden rounded-2xl bg-black/[0.03] ring-1 ring-black/5 dark:bg-white/[0.04] dark:ring-white/[0.08]",style:{aspectRatio:d.aspectRatio},children:d.type==="html"?s.jsx("iframe",{src:g==null?void 0:g.href,title:n.title,sandbox:"allow-scripts",referrerPolicy:"no-referrer",tabIndex:-1,"aria-hidden":"true",className:"pointer-events-none block h-full w-full border-0"}):s.jsx("img",{src:d.src,alt:"",className:"block h-full w-full object-cover"})}),s.jsx("h3",{className:`text-lg font-bold text-gray-800 dark:text-gray-100 ${d?"":"px-6"}`,children:n.title}),s.jsx("div",{"data-selectable-text":!0,className:`mt-2 text-[15px] leading-relaxed text-gray-600 dark:text-gray-300 ${m?"text-left":""}`,children:s.jsx(Ai,{content:n.content})}),n.note&&s.jsx("p",{"data-selectable-text":!0,className:"mt-3 whitespace-pre-line text-xs leading-relaxed text-gray-400 dark:text-gray-500",children:n.note})]},n.id),s.jsxs("div",{className:"flex shrink-0 items-center justify-center gap-2 px-5 pt-2 pb-5",children:[s.jsx("button",{type:"button",onClick:f,className:"whitespace-nowrap rounded-xl border border-transparent px-4 py-2 text-sm text-gray-600 transition hover:bg-black/[0.07] dark:bg-white/[0.06] dark:text-gray-400 dark:hover:bg-white/[0.1]",children:t.length>1?"下一条":"知道了"}),n.action&&s.jsx("a",{href:n.action.url,target:"_blank",rel:"noopener noreferrer",onClick:f,className:"whitespace-nowrap rounded-xl bg-blue-500 px-4 py-2 text-sm font-medium text-white transition hover:bg-blue-600",children:n.action.label})]})]})]}),document.body)}function Rh({paths:e=[],details:t=[]}){return s.jsxs(s.Fragment,{children:[e.length>0&&s.jsx(Pi,{rows:e}),t.map((r,n)=>s.jsx("p",{"data-selectable-text":!0,className:"break-all text-xs leading-relaxed text-gray-500 dark:text-gray-400",children:qy(r)},n))]})}function RA(e){var a,o;if(!e.length)return;const[t,...r]=e,n=!!((a=t.paths)!=null&&a.length||(o=t.details)!=null&&o.length||r.length);w.getState().setConfirmDialog({title:t.title,message:t.message,content:n?s.jsxs("div",{className:"space-y-3",children:[s.jsx(Rh,{paths:t.paths,details:t.details}),r.map((i,l)=>s.jsxs("div",{className:"space-y-3 border-t border-black/[0.06] pt-3 dark:border-white/[0.08]",children:[s.jsx("div",{className:"text-sm font-medium text-gray-700 dark:text-gray-200",children:i.title}),s.jsx("p",{className:"text-sm leading-relaxed text-gray-600 dark:text-gray-300",children:i.message}),s.jsx(Rh,{paths:i.paths,details:i.details})]},l))]}):void 0,confirmText:"我知道了",showCancel:!1,tone:"warning"})}const av=["providerOrder","clearInputAfterSubmit","persistInputOnRestart","reuseTaskApiProfileTemporarily","alwaysShowRetryButton","saveTasksToActiveFavoriteCollection","retryMode","allowPromptRewrite","taskCompletionNotification","autoCheckUpdate","writeLogFile","enterSubmit","privacyModeShortcut","colorMode","uiFont","uiFontName","monoFont","monoFontName","showBatchPrompt","batchPromptEnabled","batchPromptMode","batchPromptConcurrencyLimited","batchPromptConcurrency","referenceImageEditAction","zipDownloadRoutes","saveLocationMode","agentScrollToBottomAfterSubmit","agentMaxToolRounds","agentWebSearch","agentMathFormattingPrompt","agentApiConfigMode","agentTextProfileId","agentImageProfileId"],_A=new Set(["name","provider","baseUrl","apiKey","model","selectedModel","imageGenerationModel","timeout","apiMode","reasoningEffort","codexCli","apiProxy","responseFormatB64Json","streamImages","streamPartialImages","transparentBackgroundMethod"]),_h=["auto","low","medium","high","xhigh","max"],Dh=["png","jpeg","webp"],_g=e=>({text:e,data:{message:e}}),Pd=e=>({text:JSON.stringify(e,null,2),data:e});function za(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function As(){return Me(w.getState().settings)}function rl(e){return w.getState().setSettings(Py(e)),As()}function ov(e,t){const{apiKey:r,providerDrafts:n,...a}=t;return{...a,apiKeySet:!!r.trim(),models:ca(t.model),active:t.id===e.activeProfileId,preset:Bn().has(t.id),locked:zc(t.id)}}function iv(e){const t={};if(e.size!==void 0){if(typeof e.size!="string"||!e.size.trim())throw new Error("size 必须是非空字符串");t.size=e.size.trim()}if(e.quality!==void 0){if(typeof e.quality!="string"||!_h.includes(e.quality))throw new Error(`quality 只能是 ${_h.join("、")}`);t.quality=e.quality}if(e.output_format!==void 0){if(typeof e.output_format!="string"||!Dh.includes(e.output_format))throw new Error(`output_format 只能是 ${Dh.join("、")}`);t.output_format=e.output_format}if(e.moderation!==void 0){if(e.moderation!=="auto"&&e.moderation!=="low")throw new Error("moderation 只能是 auto、low");t.moderation=e.moderation}if(e.output_compression!==void 0){const n=e.output_compression;if(n!==null&&(typeof n!="number"||!Number.isInteger(n)||n<0||n>100))throw new Error("output_compression 必须是 0–100 的整数或 null");t.output_compression=n}if(e.n!==void 0){if(typeof e.n!="number"||!Number.isInteger(e.n)||e.n<1)throw new Error("n 必须是正整数");t.n=e.n}if(e.transparent_output!==void 0){if(typeof e.transparent_output!="boolean")throw new Error("transparent_output 必须是 true 或 false");t.transparent_output=e.transparent_output}const r=t.output_format??w.getState().params.output_format;if(t.transparent_output&&r!=="png"&&r!=="webp")throw new Error("透明背景只支持 png 或 webp 格式");return t}async function Dg(e,t){return(await Nt("image_paths",{ids:e})).flatMap((n,a)=>{if(!n)return[];const o=e.length>1?`-${String(a+1).padStart(2,"0")}`:"";return[{path:n,name:`${t}${o}${n.slice(n.lastIndexOf("."))}`}]})}async function DA(e,t){var g,m;const r=(Array.isArray(t.prompts)?t.prompts:[t.prompt]).filter(x=>typeof x=="string").map(x=>x.trim()).filter(Boolean);if(!r.length)throw new Error("提示词不能为空");const n=ti(zt(As()));if(n)throw new Error(`应用启用的 API 配置不完整:${n}`);if(w.getState().batchProgress)throw new Error("应用正在批量提交任务,请等它完成后再试");const a=Array.isArray(t.reference_images)?t.reference_images:[];if(a.length>yr)throw new Error(`参考图最多 ${yr} 张`);const o=[];for(const x of a){if(typeof x!="string")throw new Error("参考图中有无法识别的项");if(x.startsWith("data:")){const h=await(await fetch(x)).blob(),y=await kg(new File([h],"image",{type:h.type}));if(!y)throw new Error("参考图中有无法识别的图片");o.push(y);continue}const b=await kt(x);if(!b)throw new Error(`找不到参考图中的图片 ID:${x}`);o.push({id:x,dataUrl:b})}const i=iv(t);Object.keys(i).length&&w.getState().setParams(i);const l=await ji({input:{prompts:r,inputImages:o}});if(!l.length)throw new Error("应用没有创建任务,原因见应用中的提示");await Nt("cli_progress",{id:e,text:`已提交任务:${l.join("、")}`}),await Promise.all(l.map(x=>Nb(x,()=>!1)));const c=l.map(x=>w.getState().tasks.find(b=>b.id===x)),u=[],f=[],d=[];for(const[x,b]of c.entries()){const h=c.length>1?`[${x+1}] `:"";if(!b){f.push(`${h}任务 ${l[x]} 在完成前被删除`),d.push({task_id:l[x],status:"deleted"});continue}if(b.status==="error"||!b.outputImages.length){const I=b.error||"没有返回图片";f.push(`${h}任务 ${b.id} 失败:${I}`),d.push({task_id:b.id,status:"error",error:I});continue}const y=await Dg(b.outputImages,`task-${b.id}`);u.push(...y);const v=(g=b.outputErrors)!=null&&g.length?`;另有 ${b.outputErrors.length} 张失败`:"";f.push(`${h}任务 ${b.id} 完成${v},图片:`,...y.map(I=>` ${I.path}`)),d.push({task_id:b.id,status:"done",image_ids:b.outputImages,files:y.map(I=>I.path),failed_images:((m=b.outputErrors)==null?void 0:m.length)??0})}if(l.length<r.length&&f.push(`批量提交被停止,只开始了 ${l.length} / ${r.length} 条`),!u.length)throw new Error(f.join(`
|
|
195
|
+
`));return{text:f.join(`
|
|
196
|
+
`),data:{tasks:d,submitted:l.length,requested:r.length,files:u.map(x=>x.path)},files:u}}async function LA(e){const t=Math.min(50,Math.max(1,Math.floor(Number(e.limit)||10))),r=Math.max(0,Math.floor(Number(e.offset)||0)),n=Array.isArray(e.task_ids)?e.task_ids.map(String):null,a=w.getState().tasks,o=n?a.filter(l=>n.includes(l.id)):a.slice(r,r+t),i=(n==null?void 0:n.filter(l=>!a.some(c=>c.id===l)))??[];return Pd({total:a.length,...i.length?{missing:i}:{},tasks:await Promise.all(o.map(async l=>({task_id:l.id,status:l.status,prompt:l.prompt,params:l.params,profile:l.apiProfileName,model:l.apiModel,created_at:new Date(l.createdAt).toISOString(),reference_image_ids:l.inputImageIds,image_ids:l.outputImages,files:(await Dg(l.outputImages,`task-${l.id}`)).map(c=>c.path),error:l.error})))})}async function OA(e){const t=typeof e.image_id=="string"?e.image_id.trim():"",r=typeof e.task_id=="string"?e.task_id.trim():"",n=w.getState().tasks,a=t?n.find(l=>l.outputImages.includes(t)):n.find(l=>l.id===r),o=t?[t]:(a==null?void 0:a.outputImages)??[],i=await Dg(o,a?`task-${a.id}`:`image-${t.slice(0,12)}`);if(!i.length)throw new Error(t||!r?"找不到这张图片":"找不到这个任务,或它没有图片");return{text:i.map(l=>l.path).join(`
|
|
197
|
+
`),data:{image_ids:o,files:i.map(l=>l.path)},files:i}}async function lv(){const e=As();return{settings:Object.fromEntries(av.map(t=>[t,e[t]??null])),params:w.getState().params,active_profile_id:e.activeProfileId,profiles:e.profiles.map(t=>ov(e,t)),custom_providers:e.customProviders,proxy:await df(),preset_config_only:Cn()}}async function BA(e){const t=As(),r=za(e.settings)?e.settings:{},n=Object.keys(r).filter(l=>!av.includes(l));if(n.length)throw new Error(`没有这些设置项,或不能在这里修改:${n.join("、")}`);const a=typeof e.active_profile_id=="string"?e.active_profile_id:void 0;if(a!==void 0){if(!t.profiles.some(l=>l.id===a))throw new Error(`找不到 API 配置:${a}`);if(Cn()&&!Bn().has(a))throw new Error("应用只允许使用预置的 API 配置")}if(r.taskCompletionNotification===!0&&!t.taskCompletionNotification&&!(await bx()).ok)throw new Error("系统没有允许通知,无法开启任务完成通知");const o=za(e.params)?iv(e.params):{};if(za(e.proxy)){const l={...await df(),...e.proxy};if(l.mode!=="system"&&l.mode!=="none"&&l.mode!=="custom")throw new Error("proxy.mode 只能是 system、none、custom");if(typeof l.url!="string")throw new Error("proxy.url 必须是字符串");await $h({mode:l.mode,url:l.url})}(Object.keys(r).length||a!==void 0)&&(a!==void 0&&w.getState().setReusedTaskApiProfile(null),rl({...t,...r,...a!==void 0?{activeProfileId:a}:{}})),Object.keys(o).length&&w.getState().setParams(o);const i=await lv();return Pd({settings:Object.fromEntries(Object.keys(r).map(l=>[l,i.settings[l]])),params:i.params,active_profile_id:i.active_profile_id,proxy:i.proxy})}function UA(e){if(!za(e.profile))throw new Error("profile 必须是对象");const t=e.profile,r=Object.keys(t).filter(x=>!_A.has(x));if(r.length)throw new Error(`API 配置没有这些字段,或不能修改:${r.join("、")}`);const n=As(),a=typeof e.id=="string"?e.id:"",o=n.profiles.find(x=>x.id===a);if(a&&!o)throw new Error(`找不到 API 配置:${a}`);if(!o&&Cn())throw new Error("应用只允许使用预置的 API 配置,不能新建");if(o&&zc(o.id)&&Object.keys(t).some(x=>x!=="apiKey"&&x!=="selectedModel"))throw new Error("这个预置的 API 配置已锁定,只能修改 apiKey 和 selectedModel");const i=o??In({id:_c("openai"),name:"新配置"}),l=typeof t.provider=="string"?t.provider:i.provider,c=Rn(n,l);if(!["openai","sb2api-async","fal"].includes(l)&&!c)throw new Error(`没有这个服务商:${l}`);const f={...l===i.provider?i:ec(i,l,c??void 0),...t,provider:l};if(t.selectedModel!==void 0&&!ca(f.model).includes(String(t.selectedModel)))throw new Error(`selectedModel 必须是这个配置的模型之一:${ca(f.model).join("、")}`);const d=e.activate===!0||!o&&e.activate!==!1;d&&w.getState().setReusedTaskApiProfile(null);const g=rl({...n,profiles:o?n.profiles.map(x=>x.id===f.id?f:x):[...n.profiles,f],activeProfileId:d?f.id:n.activeProfileId}),m=g.profiles.find(x=>x.id===f.id);if(!m)throw new Error("应用没有保存这个 API 配置");return Pd(ov(g,m))}function FA(e){const t=String(e.id??""),r=As(),n=Ty(r,t);if(n)throw new Error(n);const a=w.getState();t===a.reusedTaskApiProfileId&&a.setReusedTaskApiProfile(null),Bn().has(t)&&a.dismissPresetProfile(t);const o=rl(My(r,t));return _g(`已删除 API 配置,当前启用:${zt(o).name}(${o.activeProfileId})`)}function $A(e){if(!za(e.provider))throw new Error("provider 必须是对象");const t=As(),r=typeof e.id=="string"?e.id:null;if(r&&!t.customProviders.some(a=>a.id===r))throw new Error(`找不到自定义服务商:${r}`);if(Cn()||r&&_l(r))throw new Error("预置的服务商不能修改");const n=_y(e.provider,t.customProviders,r);return r||w.getState().restorePresetProvider(n.id),rl({...t,customProviders:r?t.customProviders.map(a=>a.id===r?n:a):[...t.customProviders,n]}),_g(`已保存自定义服务商「${n.name}」,id:${n.id}`)}function zA(e){const t=String(e.id??""),r=As(),n=Ey(r,t);if(n)throw new Error(n);return $c(t)&&w.getState().dismissPresetProvider(t),rl(Ry(r,t)),_g("已删除自定义服务商,使用它的 API 配置已切回 OpenAI 兼容接口")}async function WA(e){const t=za(e.arguments)?e.arguments:{};switch(e.tool){case"generate_image":return DA(e.id,t);case"list_history":return LA(t);case"get_image":return OA(t);case"get_settings":return Pd(await lv());case"update_settings":return BA(t);case"save_api_profile":return UA(t);case"delete_api_profile":return FA(t);case"save_custom_provider":return $A(t);case"delete_custom_provider":return zA(t);default:throw new Error(`未知命令:${e.tool}`)}}function HA(){const e=Fh("cli-request",({payload:t})=>{WA(t).then(r=>Nt("cli_respond",{id:t.id,result:r}),r=>Nt("cli_respond",{id:t.id,error:r instanceof Error?r.message:String(r)})).catch(r=>console.error("回传命令行结果失败:",r))});return e.then(()=>Nt("cli_ready",{ready:!0})).catch(t=>console.error("注册命令行请求监听失败:",t)),()=>{e.then(t=>t())}}let Lh=!1;function YA(){const e=w(f=>f.appMode),t=w(f=>f.filterFavorite),r=w(f=>f.activeFavoriteCollectionId),n=w(f=>f.settings.writeLogFile),a=w(f=>f.settings.saveLocationMode),o=w(f=>f.settings.autoCheckUpdate),i=w(f=>f.privacyModeEpoch),l=w(f=>f.settingsModalEpoch),[c,u]=p.useState(!1);return f5(),g5(),h5(),N4(),b5(),z5(),F5(o),W5(),E5(c),p.useEffect(()=>{if(De)return HA()},[]),p.useEffect(()=>{De&&Gv().catch(f=>(console.error("读取数据目录提示失败:",f),{notices:[],custom:!1})).then(({notices:f,custom:d})=>{const g=w.getState(),m=f.find(h=>h.kind==="success");m&&g.showToast(m.message,"success");const x=[],b=Qv();if(b){const h=b.code==="unavailable",y=h?b.message.includes("不可写")?d?"请在「设置 → 数据管理」中把数据目录改到有写权限的位置。":"可能装在了需要管理员权限的位置,比如 C:\\Program Files。可以重新安装到其他位置,或在「设置 → 数据管理」中更改数据目录。":b.message.includes("高于当前客户端")?"数据目录由更新版本的客户端创建,请升级到最新版本的客户端后再打开。":"数据库可能被其他程序占用或已损坏,关闭相关程序后重启再尝试。":"读取设置时数据库出错,可能已损坏。可以先在「设置 → 数据管理」中尝试导出备份,再反馈问题。";x.push({title:"无法保存数据",message:h?"数据目录无法使用,这次的改动不会被保存。":"读取设置失败,当前是默认设置,这次的改动不会被保存。",details:[`原因:${b.message}`,y]})}x.push(...f.filter(h=>h.kind==="warning")),RA(x)})},[]),p.useEffect(()=>{De&&Zv(n)},[n]),p.useEffect(()=>{cb(De&&a==="default")},[a]),p.useEffect(()=>{if(Lh)return;Lh=!0;const f=new URLSearchParams(window.location.search),d=$b(f)?new URLSearchParams(f):null;if(d){o5(f);const b=f.toString();window.history.replaceState(null,"",`${window.location.pathname}${b?`?${b}`:""}${window.location.hash}`)}const g=l5(),m=Wb(),x=()=>m?Promise.resolve().then(()=>c5()):u5(g);Ej().then(async()=>{var j;const b=m||g?await x():Cw()?{customProviders:[],profiles:[{...In(),isDefault:!0}]}:null;um(b);const h=w.getState();b?await h.setPresetImportedSettings(b):h.previousPresetConfig&&await h.setPresetImportedSettings({customProviders:[],profiles:[]});const y=w.getState();b||(w.setState({dismissedPresetProfileIds:[],dismissedPresetProviderIds:[]}),y.settings.profiles.some(A=>A.isDefault)&&y.setSettings({profiles:y.settings.profiles.map(A=>A.isDefault?{...A,isDefault:void 0}:A)}));const v=w.getState(),I=Bn(),S=Fc(),k=Cn()?Me({...v.settings,activeProfileId:I.has(v.settings.activeProfileId)?v.settings.activeProfileId:S??[...I][0],agentTextProfileId:v.settings.agentTextProfileId&&I.has(v.settings.agentTextProfileId)?v.settings.agentTextProfileId:((j=v.settings.profiles.find(A=>I.has(A.id)&&Oa(A)))==null?void 0:j.id)??null,agentImageProfileId:v.settings.agentImageProfileId&&I.has(v.settings.agentImageProfileId)?v.settings.agentImageProfileId:S??[...I][0]}):v.settings;v.setSettings(k)}).catch(b=>{console.warn("Failed to import preset config:",b),um(null)}).finally(()=>{u(!0),d&&Wl(d,!0)})},[]),p.useEffect(()=>{const f=d=>{var g;(g=d.target)!=null&&g.closest("img")&&d.preventDefault()};return document.addEventListener("dragstart",f),()=>document.removeEventListener("dragstart",f)},[]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{"data-page-scroll":!0,children:[s.jsx(OS,{}),e==="agent"?s.jsx(S4,{}):s.jsx("main",{"data-home-main":!0,"data-drag-select-surface":!0,className:"pb-48",children:s.jsxs("div",{className:"safe-area-x max-w-7xl mx-auto",children:[s.jsx(FS,{}),t&&!r?s.jsx(ES,{}):s.jsx(YS,{})]})})]}),s.jsx(K4,{},`input-${i}`),s.jsx(X4,{},`detail-${i}`),s.jsx(J4,{},`lightbox-${i}`),s.jsx(TN,{},`settings-${l}`),s.jsx(YN,{}),s.jsx(XN,{}),s.jsx(VN,{}),s.jsx(PA,{}),s.jsx(EA,{ready:c}),s.jsx(RS,{}),s.jsx(_S,{}),s.jsx(qN,{}),s.jsx(JN,{}),s.jsx(oA,{},`mask-${i}`),s.jsx(CA,{},`sketch-${i}`),s.jsx(NA,{},`menu-${i}`),cf>0&&s.jsx(SA,{})]})}const XA=Object.freeze(Object.defineProperty({__proto__:null,default:YA},Symbol.toStringTag,{value:"Module"}));export{XA as A,lr as r};
|