@pageops/sdk 0.1.28 → 0.1.29
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/dist/pageops-sdk.es.js +9 -18
- package/dist/pageops-sdk.umd.cjs +672 -34
- package/dist/types.d.ts +3 -3
- package/package.json +1 -1
package/dist/pageops-sdk.es.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var W = Object.defineProperty;
|
|
2
2
|
var H = (a, e, t) => e in a ? W(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
|
|
3
3
|
var i = (a, e, t) => H(a, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
-
const
|
|
4
|
+
const UPLOAD_MAX_BYTES = 500 * 1024 * 1024;
|
|
5
5
|
class K {
|
|
6
6
|
constructor(e) {
|
|
7
7
|
this.options = e;
|
|
@@ -20,7 +20,7 @@ class K {
|
|
|
20
20
|
tenant_id: e.tenantId,
|
|
21
21
|
user_role: e.userRole,
|
|
22
22
|
build_version: e.buildVersion,
|
|
23
|
-
source_snapshot_id:
|
|
23
|
+
source_snapshot_id: e.sourceSnapshotId == null ? void 0 : e.sourceSnapshotId
|
|
24
24
|
})
|
|
25
25
|
});
|
|
26
26
|
}
|
|
@@ -48,21 +48,10 @@ class K {
|
|
|
48
48
|
return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
|
|
49
49
|
}
|
|
50
50
|
uploadSource(e, t) {
|
|
51
|
-
if (e.size && e.size >
|
|
51
|
+
if (e.size && e.size > UPLOAD_MAX_BYTES) throw new Error("源码包超过 500M,请压缩后重新上传。");
|
|
52
52
|
const s = new FormData();
|
|
53
53
|
return s.append("file", e), t.tag && s.append("tag", t.tag), t.branch && s.append("branch", t.branch), t.remark && s.append("remark", t.remark), s.append("uploader", t.uploader || "未知用户"), this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: s, headers: {} }).then((r) => (t.onProgress && t.onProgress({ loaded: e.size || 0, total: e.size || 0, percent: 100, chunkIndex: 1, totalChunks: 1 }), r));
|
|
54
54
|
}
|
|
55
|
-
async uploadSourceInChunks(e, t) {
|
|
56
|
-
const s = `${Date.now()}-${Math.random().toString(36).slice(2)}`, r = Math.max(1, Math.ceil(e.size / UPLOAD_CHUNK_BYTES));
|
|
57
|
-
let n;
|
|
58
|
-
t.onProgress && t.onProgress({ loaded: 0, total: e.size || 0, percent: 0, chunkIndex: 0, totalChunks: r });
|
|
59
|
-
for (let c = 0; c < r; c += 1) {
|
|
60
|
-
const p = new FormData(), m = c * UPLOAD_CHUNK_BYTES, g = Math.min(e.size, m + UPLOAD_CHUNK_BYTES);
|
|
61
|
-
p.append("file", e.slice(m, g), e.name || "source.archive"), p.append("upload_id", s), p.append("chunk_index", String(c)), p.append("total_chunks", String(r)), p.append("total_size", String(e.size || 0)), p.append("filename", e.name || "source.archive"), t.tag && p.append("tag", t.tag), t.branch && p.append("branch", t.branch), t.remark && p.append("remark", t.remark), p.append("uploader", t.uploader || "未知用户"), n = await this.request(`/sources/upload/chunk?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: p, headers: {} });
|
|
62
|
-
t.onProgress && t.onProgress({ loaded: g, total: e.size || 0, percent: Math.round(g / (e.size || g || 1) * 100), chunkIndex: c + 1, totalChunks: r });
|
|
63
|
-
}
|
|
64
|
-
return n;
|
|
65
|
-
}
|
|
66
55
|
streamQuestion(e, t, s, r) {
|
|
67
56
|
return fetch(`${this.base()}/question/stream`, {
|
|
68
57
|
method: "POST",
|
|
@@ -255,10 +244,11 @@ class V {
|
|
|
255
244
|
}
|
|
256
245
|
getPageContext() {
|
|
257
246
|
var e, t, s;
|
|
247
|
+
const r = this.selectedSourceSnapshot(), n = this.selectedSourceSnapshotId != null ? this.selectedSourceSnapshotId : r ? this.sourceSnapshotValue(r) : null;
|
|
258
248
|
return {
|
|
259
249
|
...(s = (t = (e = this.options) == null ? void 0 : e.getPageContext) == null ? void 0 : t.call(e)) != null ? s : {},
|
|
260
250
|
userRole: this.answerAudience,
|
|
261
|
-
sourceSnapshotId:
|
|
251
|
+
sourceSnapshotId: n == null ? void 0 : n
|
|
262
252
|
};
|
|
263
253
|
}
|
|
264
254
|
answerAudienceStorageKey(e) {
|
|
@@ -297,7 +287,7 @@ class V {
|
|
|
297
287
|
}
|
|
298
288
|
selectSourceSnapshot(e) {
|
|
299
289
|
if (this.asking) return;
|
|
300
|
-
const
|
|
290
|
+
const s = e === "" ? null : e;
|
|
301
291
|
if ((this.selectedSourceSnapshotId == null ? "" : String(this.selectedSourceSnapshotId)) === (s == null ? "" : String(s))) return;
|
|
302
292
|
this.selectedSourceSnapshotId = s, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1, this.renderPanel();
|
|
303
293
|
}
|
|
@@ -313,7 +303,8 @@ class V {
|
|
|
313
303
|
async loadSources() {
|
|
314
304
|
if (this.client) {
|
|
315
305
|
try {
|
|
316
|
-
|
|
306
|
+
const e = await this.client.listSources(), t = e[0], s = t ? this.sourceSnapshotValue(t) : null, r = this.context && this.context.source_snapshot_id != null ? String(this.context.source_snapshot_id) : null, n = this.selectedSourceSnapshotId == null && s != null && r !== s && (this.context != null || this.currentThread != null);
|
|
307
|
+
this.sourceSnapshots = e, this.sourceLoadError = "", n && (this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1);
|
|
317
308
|
} catch (e) {
|
|
318
309
|
this.sourceLoadError = "源码包状态加载失败,连接恢复后将自动重试。";
|
|
319
310
|
}
|
|
@@ -684,7 +675,7 @@ function l(a) {
|
|
|
684
675
|
function M(a) {
|
|
685
676
|
var t;
|
|
686
677
|
const e = (t = a.metadata_json) == null ? void 0 : t.agent_run_id;
|
|
687
|
-
return typeof e == "string" ? e : "";
|
|
678
|
+
return typeof e == "number" ? String(e) : typeof e == "string" ? e : "";
|
|
688
679
|
}
|
|
689
680
|
function O(a) {
|
|
690
681
|
return new Intl.DateTimeFormat("zh-CN", {
|
package/dist/pageops-sdk.umd.cjs
CHANGED
|
@@ -1,39 +1,563 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
|
|
3
|
-
`))}</code></pre>`);continue}const n=H(e,s);if(n){t.push(n.html),s=n.next-1;continue}r.startsWith("### ")?t.push(`<h4>${S(r.slice(4))}</h4>`):r.startsWith("## ")?t.push(`<h3>${S(r.slice(3))}</h3>`):r.startsWith("# ")?t.push(`<h2>${S(r.slice(2))}</h2>`):r.startsWith("- ")?t.push(`<li>${S(r.slice(2))}</li>`):r.trim()?t.push(`<p>${S(r)}</p>`):t.push("<br>")}return t.join("")}async function z(a,e){var n;const t=a.getReader(),s=new TextDecoder;let r="";for(;;){const{done:c,value:p}=await t.read();if(c){r+=s.decode();break}r+=s.decode(p,{stream:!0});const f=r.split(/\r?\n\r?\n/);r=(n=f.pop())!=null?n:"";for(const g of f)q(g,e)}r.trim()&&q(r,e)}function q(a,e){var r,n;const t=(r=a.match(/^event:\s*(.+)$/m))==null?void 0:r[1],s=(n=a.match(/^data:\s*(.+)$/m))==null?void 0:n[1];t&&s&&e(t,JSON.parse(s))}class N{constructor(e,t=16){i(this,"queue",[]);i(this,"timer",null);i(this,"drainWaiters",[]);this.onChunk=e,this.interval=t}enqueue(e){this.queue.push(...Array.from(e)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(e=>this.drainWaiters.push(e))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const e=Math.max(1,Math.ceil(this.queue.length/90)),t=this.queue.splice(0,e).join("");if(t&&this.onChunk(t),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const e of this.drainWaiters.splice(0))e()}}const I=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class J{constructor(){i(this,"client",null);i(this,"options",null);i(this,"root",null);i(this,"panel",null);i(this,"context",null);i(this,"contextKey","");i(this,"selectedPageKey","");i(this,"currentThread",null);i(this,"conversations",[]);i(this,"messages",[]);i(this,"steps",[]);i(this,"selectedAgentRunId","");i(this,"runLoading",!1);i(this,"runLoadError","");i(this,"copiedAgentRunId","");i(this,"copyFeedbackTimer",null);i(this,"sourceSnapshots",[]);i(this,"selectedSourceSnapshotId",null);i(this,"sourceUploadStatus","");i(this,"sourceUploadProgress",null);i(this,"sourceUploadError","");i(this,"sourceLoadError","");i(this,"sourceUploading",!1);i(this,"sourceRefreshTimer",null);i(this,"streaming","");i(this,"asking",!1);i(this,"waitingForFirstContent",!1);i(this,"abortController",null);i(this,"activeRunId",0);i(this,"stoppedRunId",-1);i(this,"answerStopped",!1);i(this,"answerError","");i(this,"conversationError","");i(this,"deletingThreadId","");i(this,"streamFailure","");i(this,"streamDone",null);i(this,"answerAudience","business");i(this,"typewriter",new N(e=>{this.streaming+=e,this.updateStreamingMessage()}))}mount(e){var t;this.unmount(),this.options=e,this.client=new m(e),this.answerAudience=this.loadAnswerAudience(e.appId),this.root=document.createElement("div"),this.root.className="pageops-sdk",((t=e.container)!=null?t:document.body).appendChild(this.root),this.renderClosed()}unmount(){var e;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(e=this.root)==null||e.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoading=!1,this.runLoadError="",this.clearCopyFeedback(),this.sourceSnapshots=[],this.selectedSourceSnapshotId=null,this.sourceUploadStatus="",this.sourceUploadProgress=null,this.sourceUploadError="",this.sourceLoadError="",this.sourceUploading=!1,this.answerAudience="business"}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.renderClosed()}updateContext(e){if(!this.options)return;const t=this.options.appId;this.options={...this.options,...e},this.client=new m(this.options),this.options.appId!==t&&(this.answerAudience=this.loadAnswerAudience(this.options.appId),this.selectedSourceSnapshotId=null,this.currentThread=null,this.selectedPageKey="",this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError=""),this.context=null,this.contextKey="",this.renderPanel()}renderClosed(){var e;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(e=this.root.querySelector("button"))==null||e.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const e=this.getPageContext(),t=this.getPageContextKey(e);return this.context&&this.contextKey===t?this.context:(this.context=await this.client.createContext(e),this.contextKey=t,this.context)}getPageContext(){var e,t,s;return{...(s=(t=(e=this.options)==null?void 0:e.getPageContext)==null?void 0:t.call(e))!=null?s:{},userRole:this.answerAudience,sourceSnapshotId:this.selectedSourceSnapshotId}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return I.some(s=>s.value===t)?t:"business"}catch(t){return"business"}}saveAnswerAudience(){if(this.options)try{localStorage.setItem(this.answerAudienceStorageKey(this.options.appId),this.answerAudience)}catch(e){}}changeAnswerAudience(e){var s;if(this.asking)return;const t=(s=I.find(r=>r.value===e))==null?void 0:s.value;!t||t===this.answerAudience||(this.answerAudience=t,this.saveAnswerAudience(),this.renderPanel())}getPageContextKey(e){var t,s,r,n;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(r=e.title)!=null?r:document.title,(n=e.menuPath)!=null?n:[],e.sourceSnapshotId==null?"":String(e.sourceSnapshotId)])}selectSourceSnapshot(e){if(this.asking)return;const t=e?Number(e):null,s=t==null||Number.isNaN(t)?null:t;if((this.selectedSourceSnapshotId==null?"":String(this.selectedSourceSnapshotId))===(s==null?"":String(s)))return;this.selectedSourceSnapshotId=s,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel()}sourceSnapshotValue(e){var t,s;return String((s=(t=e.id)!=null?t:e.source_snapshot_id)!=null?s:"")}selectedSourceSnapshot(){if(this.selectedSourceSnapshotId==null)return this.sourceSnapshots[0];const e=String(this.selectedSourceSnapshotId);return this.sourceSnapshots.find(t=>this.sourceSnapshotValue(t)===e)}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceLoadError=""}catch(e){this.sourceLoadError="源码包状态加载失败,连接恢复后将自动重试。"}this.scheduleSourceRefresh(),this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const e=await this.ensureContext(),t=(s=e.menu_path)!=null&&s.length?e.menu_path.join(" / "):e.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(e.id,t),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel()}async selectThread(e){if(!this.client)return;this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel();const t=[...this.messages].reverse().map(L).find(Boolean);t&&await this.loadAgentRun(t)}async deleteConversation(e){var t;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)){this.deletingThreadId=e.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(e.id),this.conversations=this.conversations.filter(s=>s.id!==e.id),((t=this.currentThread)==null?void 0:t.id)===e.id){this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1;const s=this.conversations[0];s&&await this.selectThread(s)}}catch(s){this.conversationError=s instanceof Error?s.message:"删除问答会话失败"}finally{this.deletingThreadId="",this.renderPanel()}}}async uploadSource(e,t){var s;if(this.client){this.sourceUploading=!0,this.sourceUploadProgress=0,this.sourceUploadStatus="上传中 0%",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e,{...t,uploader:(s=this.options)==null?void 0:s.uploader,onProgress:r=>{this.sourceUploadProgress=Math.max(0,Math.min(100,Math.round(r.percent))),this.sourceUploadStatus=`上传中 ${this.sourceUploadProgress}%`,this.renderPanel()}}),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(r){this.sourceUploadError=r instanceof Error?r.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.sourceUploadProgress=null,this.renderPanel()}}}async ask(e){if(!this.client||this.asking)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,r=new AbortController;this.abortController=r,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const n=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==n&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.renderPanel();const c=await this.client.streamQuestion(this.currentThread.id,e,this.answerAudience,r.signal);if(!c.ok)throw new Error(await b(c,"服务暂时无法回答,请稍后重试。"));if(!c.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await z(c.body,(p,f)=>this.handleStreamEvent(p,f)),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");if(this.streamFailure)throw new Error(this.streamFailure);if(!this.streamDone)throw new Error("服务响应意外中断,请稍后重试。");if(await this.typewriter.drain(),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");await this.selectThread(this.currentThread)}catch(n){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=n instanceof Error?n.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",summary:this.answerError}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===r&&(this.abortController=null),this.renderPanel(!0)}}cancelActiveAnswer(e){var t;if(!(!this.asking&&!this.abortController)){if(e){this.stoppedRunId=this.activeRunId,this.answerStopped=!0;const s=this.steps.map(r=>r.status==="running"?{...r,status:"cancelled"}:r);this.steps=s.some(r=>r.status==="cancelled")?s:[...s,{id:"stopped",title:"已停止",status:"cancelled"}]}else this.activeRunId+=1,this.asking=!1;this.typewriter.clear(),this.waitingForFirstContent=!1,(t=this.abortController)==null||t.abort(),this.abortController=null,e&&this.renderPanel()}}handleStreamEvent(e,t){var s,r;if(e==="step"){this.upsertStep(t),this.renderExecutionSteps(!0);return}if(e==="delta"){const n=String((s=t.content)!=null?s:"");if(!n)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(n);return}e==="done"&&(this.streamDone=t),e==="error"&&(this.streamFailure=String((r=t.message)!=null?r:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,r;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=k(this.streaming);const t=(r=this.panel)==null?void 0:r.querySelector(".po-messages");t&&(t.scrollTop=t.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(e){const t=this.steps.findIndex(s=>s.id===e.id);this.steps=t===-1?[...this.steps,e]:this.steps.map(s=>s.id===e.id?{...s,...e}:s)}async loadAgentRun(e){if(!(!this.client||!e)){this.selectedAgentRunId=e,this.runLoading=!0,this.runLoadError="",this.renderPanel();try{const t=await this.client.getAgentRun(e);if(this.selectedAgentRunId!==e)return;this.steps=t.steps}catch(t){if(this.selectedAgentRunId!==e)return;this.steps=[],this.runLoadError=t instanceof Error?t.message:"执行过程加载失败"}finally{this.selectedAgentRunId===e&&(this.runLoading=!1,this.renderPanel())}}}async copyAgentRunId(e){var t;if(e){try{if((t=navigator.clipboard)!=null&&t.writeText)await navigator.clipboard.writeText(e);else{const s=document.createElement("textarea");if(s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select(),!document.execCommand("copy"))throw new Error("copy_not_supported");s.remove()}this.copiedAgentRunId=e}catch(s){this.copiedAgentRunId=`error:${e}`}this.clearCopyFeedback(!1),this.copyFeedbackTimer=setTimeout(()=>{this.copiedAgentRunId="",this.copyFeedbackTimer=null,this.updateCopyFeedback()},1800),this.updateCopyFeedback()}}updateCopyFeedback(){var e;(e=this.panel)==null||e.querySelectorAll("[data-copy-run]").forEach(t=>{var r;const s=(r=t.dataset.copyRun)!=null?r:"";t.textContent=this.copiedAgentRunId===s?"已复制":this.copiedAgentRunId===`error:${s}`?"复制失败":"复制流水号"})}clearCopyFeedback(e=!0){this.copyFeedbackTimer&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null,e&&(this.copiedAgentRunId="")}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.selectedSourceSnapshot())==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceLoadError&&!this.sourceSnapshots.length?"暂时无法读取项目共享代码包,请检查 PageOps 服务连接。":this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),!(!this.sourceLoadError&&!this.isProjectMemoryUpdating())&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(e=this.asking,t=!1){var g;if(!this.panel)return;const s=(g=this.panel.querySelector(".po-messages"))==null?void 0:g.scrollTop,r=this.questionUnavailableReason(),n=r||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),c=!!(r||this.asking),p=r?'<button type="submit" disabled>暂不可提问</button>':this.asking?'<button class="po-stop" type="button" data-action="stop-answer" aria-label="停止输出" title="停止输出"><span aria-hidden="true"></span></button>':'<button type="submit">发送</button>',f=I.map(o=>`
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
(function(g,f){typeof exports==='object'&&typeof module!=='undefined'?f(exports):typeof define==='function'&&define.amd?define(['exports'],f):(g=typeof globalThis!=='undefined'?globalThis:g||self,f(g.PageOpsSDK={}));})(this,(function(exports){'use strict';var W = Object.defineProperty;
|
|
2
|
+
var H = (a, e, t) => e in a ? W(a, e, { enumerable: true, configurable: true, writable: true, value: t }) : a[e] = t;
|
|
3
|
+
var i = (a, e, t) => H(a, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
const UPLOAD_MAX_BYTES = 500 * 1024 * 1024;
|
|
5
|
+
class K {
|
|
6
|
+
constructor(e) {
|
|
7
|
+
this.options = e;
|
|
8
|
+
}
|
|
9
|
+
async createContext(e = ((r) => (r = ((t) => ((s) => (s = (t = this.options).getPageContext) == null ? void 0 : s.call(t))())()) != null ? r : {})()) {
|
|
10
|
+
var n, c, p;
|
|
11
|
+
return this.request("/context/session", {
|
|
12
|
+
method: "POST",
|
|
13
|
+
body: JSON.stringify({
|
|
14
|
+
app_id: this.options.appId,
|
|
15
|
+
env: this.options.env,
|
|
16
|
+
route: e.route,
|
|
17
|
+
url: (n = e.url) != null ? n : location.href,
|
|
18
|
+
title: (c = e.title) != null ? c : document.title,
|
|
19
|
+
menu_path: (p = e.menuPath) != null ? p : [],
|
|
20
|
+
tenant_id: e.tenantId,
|
|
21
|
+
user_role: e.userRole,
|
|
22
|
+
build_version: e.buildVersion,
|
|
23
|
+
source_snapshot_id: e.sourceSnapshotId == null ? void 0 : e.sourceSnapshotId
|
|
24
|
+
})
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
async listConversations() {
|
|
28
|
+
return (await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations;
|
|
29
|
+
}
|
|
30
|
+
async createConversation(e, t) {
|
|
31
|
+
return this.request("/conversations", {
|
|
32
|
+
method: "POST",
|
|
33
|
+
body: JSON.stringify({ app_id: this.options.appId, context_session_id: e, title: t })
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
async deleteConversation(e) {
|
|
37
|
+
return this.request(`/conversations/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`, {
|
|
38
|
+
method: "DELETE"
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async listMessages(e) {
|
|
42
|
+
return (await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages;
|
|
43
|
+
}
|
|
44
|
+
async getAgentRun(e) {
|
|
45
|
+
return this.request(`/question/runs/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`);
|
|
46
|
+
}
|
|
47
|
+
async listSources() {
|
|
48
|
+
return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
|
|
49
|
+
}
|
|
50
|
+
uploadSource(e, t) {
|
|
51
|
+
if (e.size && e.size > UPLOAD_MAX_BYTES) throw new Error("源码包超过 500M,请压缩后重新上传。");
|
|
52
|
+
const s = new FormData();
|
|
53
|
+
return s.append("file", e), t.tag && s.append("tag", t.tag), t.branch && s.append("branch", t.branch), t.remark && s.append("remark", t.remark), s.append("uploader", t.uploader || "未知用户"), this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: s, headers: {} }).then((r) => (t.onProgress && t.onProgress({ loaded: e.size || 0, total: e.size || 0, percent: 100, chunkIndex: 1, totalChunks: 1 }), r));
|
|
54
|
+
}
|
|
55
|
+
streamQuestion(e, t, s, r) {
|
|
56
|
+
return fetch(`${this.base()}/question/stream`, {
|
|
57
|
+
method: "POST",
|
|
58
|
+
headers: { "content-type": "application/json" },
|
|
59
|
+
body: JSON.stringify({ app_id: this.options.appId, thread_id: e, question: t, user_role: s }),
|
|
60
|
+
signal: r
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
async request(e, t) {
|
|
64
|
+
var c, p;
|
|
65
|
+
const s = (t == null ? void 0 : t.body) instanceof FormData ? t.headers : { "content-type": "application/json", ...(c = t == null ? void 0 : t.headers) != null ? c : {} }, r = await fetch(`${this.base()}${e}`, { ...t, headers: s });
|
|
66
|
+
if (r.status === 204) return;
|
|
67
|
+
const n = await r.json().catch(() => null);
|
|
68
|
+
if (!r.ok) throw new Error((p = n == null ? void 0 : n.message) != null ? p : r.status === 413 ? "源码包超过网关上传大小限制,请压缩代码包或联系管理员调整上传限制。" : "PageOps 请求失败");
|
|
69
|
+
return n;
|
|
70
|
+
}
|
|
71
|
+
base() {
|
|
72
|
+
const e = this.options.apiBase.replace(/\/$/, "");
|
|
73
|
+
return e.endsWith("/api") || e.endsWith("/dc/ai") ? e : `${e}/dc/ai`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function z(a, e) {
|
|
77
|
+
const t = await a.json().catch(() => null);
|
|
78
|
+
return typeof (t == null ? void 0 : t.message) == "string" && t.message.trim() ? t.message : e;
|
|
79
|
+
}
|
|
80
|
+
function D(a) {
|
|
81
|
+
return String(a == null ? "" : a).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
82
|
+
}
|
|
83
|
+
function v(a) {
|
|
84
|
+
return D(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
85
|
+
}
|
|
86
|
+
function N(a, e) {
|
|
87
|
+
const t = a[e], s = a[e + 1];
|
|
88
|
+
if (!(t != null && t.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
|
|
89
|
+
const r = [];
|
|
90
|
+
let n = e;
|
|
91
|
+
for (; n < a.length && a[n].includes("|") && a[n].trim(); )
|
|
92
|
+
r.push(a[n]), n += 1;
|
|
93
|
+
const c = (g) => g.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((o) => v(o.trim())), p = c(r[0]).map((g) => `<th>${g}</th>`).join(""), m = r.slice(2).map((g) => `<tr>${c(g).map((o) => `<td>${o}</td>`).join("")}</tr>`).join("");
|
|
94
|
+
return { html: `<table><thead><tr>${p}</tr></thead><tbody>${m}</tbody></table>`, next: n };
|
|
95
|
+
}
|
|
96
|
+
function R(a) {
|
|
97
|
+
const e = a.split(`
|
|
98
|
+
`), t = [];
|
|
99
|
+
for (let s = 0; s < e.length; s += 1) {
|
|
100
|
+
const r = e[s];
|
|
101
|
+
if (r.trim().startsWith("```")) {
|
|
102
|
+
const c = [];
|
|
103
|
+
for (s += 1; s < e.length && !e[s].trim().startsWith("```"); )
|
|
104
|
+
c.push(e[s]), s += 1;
|
|
105
|
+
t.push(`<pre><code>${D(c.join(`
|
|
106
|
+
`))}</code></pre>`);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
const n = N(e, s);
|
|
110
|
+
if (n) {
|
|
111
|
+
t.push(n.html), s = n.next - 1;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
r.startsWith("### ") ? t.push(`<h4>${v(r.slice(4))}</h4>`) : r.startsWith("## ") ? t.push(`<h3>${v(r.slice(3))}</h3>`) : r.startsWith("# ") ? t.push(`<h2>${v(r.slice(2))}</h2>`) : r.startsWith("- ") ? t.push(`<li>${v(r.slice(2))}</li>`) : r.trim() ? t.push(`<p>${v(r)}</p>`) : t.push("<br>");
|
|
115
|
+
}
|
|
116
|
+
return t.join("");
|
|
117
|
+
}
|
|
118
|
+
async function J(a, e) {
|
|
119
|
+
var n;
|
|
120
|
+
const t = a.getReader(), s = new TextDecoder();
|
|
121
|
+
let r = "";
|
|
122
|
+
for (; ; ) {
|
|
123
|
+
const { done: c, value: p } = await t.read();
|
|
124
|
+
if (c) {
|
|
125
|
+
r += s.decode();
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
r += s.decode(p, { stream: true });
|
|
129
|
+
const m = r.split(/\r?\n\r?\n/);
|
|
130
|
+
r = (n = m.pop()) != null ? n : "";
|
|
131
|
+
for (const g of m) j(g, e);
|
|
132
|
+
}
|
|
133
|
+
r.trim() && j(r, e);
|
|
134
|
+
}
|
|
135
|
+
function j(a, e) {
|
|
136
|
+
var r, n;
|
|
137
|
+
const t = (r = a.match(/^event:\s*(.+)$/m)) == null ? void 0 : r[1], s = (n = a.match(/^data:\s*(.+)$/m)) == null ? void 0 : n[1];
|
|
138
|
+
t && s && e(t, JSON.parse(s));
|
|
139
|
+
}
|
|
140
|
+
class Q {
|
|
141
|
+
constructor(e, t = 16) {
|
|
142
|
+
i(this, "queue", []);
|
|
143
|
+
i(this, "timer", null);
|
|
144
|
+
i(this, "drainWaiters", []);
|
|
145
|
+
this.onChunk = e, this.interval = t;
|
|
146
|
+
}
|
|
147
|
+
enqueue(e) {
|
|
148
|
+
this.queue.push(...Array.from(e)), this.timer || this.tick();
|
|
149
|
+
}
|
|
150
|
+
async drain() {
|
|
151
|
+
!this.timer && !this.queue.length || await new Promise((e) => this.drainWaiters.push(e));
|
|
152
|
+
}
|
|
153
|
+
clear() {
|
|
154
|
+
this.timer && clearTimeout(this.timer), this.timer = null, this.queue = [], this.resolveDrainWaiters();
|
|
155
|
+
}
|
|
156
|
+
tick() {
|
|
157
|
+
const e = Math.max(1, Math.ceil(this.queue.length / 90)), t = this.queue.splice(0, e).join("");
|
|
158
|
+
if (t && this.onChunk(t), !this.queue.length) {
|
|
159
|
+
this.timer = null, this.resolveDrainWaiters();
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
this.timer = setTimeout(() => this.tick(), this.interval);
|
|
163
|
+
}
|
|
164
|
+
resolveDrainWaiters() {
|
|
165
|
+
for (const e of this.drainWaiters.splice(0)) e();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const C = [
|
|
169
|
+
{ value: "product", label: "产品" },
|
|
170
|
+
{ value: "business", label: "业务" },
|
|
171
|
+
{ value: "developer", label: "研发" },
|
|
172
|
+
{ value: "tester", label: "测试" }
|
|
173
|
+
];
|
|
174
|
+
class V {
|
|
175
|
+
constructor() {
|
|
176
|
+
i(this, "client", null);
|
|
177
|
+
i(this, "options", null);
|
|
178
|
+
i(this, "root", null);
|
|
179
|
+
i(this, "panel", null);
|
|
180
|
+
i(this, "context", null);
|
|
181
|
+
i(this, "contextKey", "");
|
|
182
|
+
i(this, "selectedPageKey", "");
|
|
183
|
+
i(this, "currentThread", null);
|
|
184
|
+
i(this, "conversations", []);
|
|
185
|
+
i(this, "messages", []);
|
|
186
|
+
i(this, "steps", []);
|
|
187
|
+
i(this, "selectedAgentRunId", "");
|
|
188
|
+
i(this, "runLoading", false);
|
|
189
|
+
i(this, "runLoadError", "");
|
|
190
|
+
i(this, "copiedAgentRunId", "");
|
|
191
|
+
i(this, "copyFeedbackTimer", null);
|
|
192
|
+
i(this, "sourceSnapshots", []);
|
|
193
|
+
i(this, "selectedSourceSnapshotId", null);
|
|
194
|
+
i(this, "sourceUploadStatus", "");
|
|
195
|
+
i(this, "sourceUploadProgress", null);
|
|
196
|
+
i(this, "sourceUploadError", "");
|
|
197
|
+
i(this, "sourceLoadError", "");
|
|
198
|
+
i(this, "sourceUploading", false);
|
|
199
|
+
i(this, "sourceRefreshTimer", null);
|
|
200
|
+
i(this, "streaming", "");
|
|
201
|
+
i(this, "asking", false);
|
|
202
|
+
i(this, "waitingForFirstContent", false);
|
|
203
|
+
i(this, "abortController", null);
|
|
204
|
+
i(this, "activeRunId", 0);
|
|
205
|
+
i(this, "stoppedRunId", -1);
|
|
206
|
+
i(this, "answerStopped", false);
|
|
207
|
+
i(this, "answerError", "");
|
|
208
|
+
i(this, "conversationError", "");
|
|
209
|
+
i(this, "deletingThreadId", "");
|
|
210
|
+
i(this, "streamFailure", "");
|
|
211
|
+
i(this, "streamDone", null);
|
|
212
|
+
i(this, "answerAudience", "business");
|
|
213
|
+
i(this, "typewriter", new Q((e) => {
|
|
214
|
+
this.streaming += e, this.updateStreamingMessage();
|
|
215
|
+
}));
|
|
216
|
+
}
|
|
217
|
+
mount(e) {
|
|
218
|
+
var t;
|
|
219
|
+
this.unmount(), this.options = e, this.client = new K(e), this.answerAudience = this.loadAnswerAudience(e.appId), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((t = e.container) != null ? t : document.body).appendChild(this.root), this.renderClosed();
|
|
220
|
+
}
|
|
221
|
+
unmount() {
|
|
222
|
+
var e;
|
|
223
|
+
this.stopSourceRefresh(), this.cancelActiveAnswer(false), this.resetAnswerState(), (e = this.root) == null || e.remove(), this.root = null, this.panel = null, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoading = false, this.runLoadError = "", this.clearCopyFeedback(), this.sourceSnapshots = [], this.selectedSourceSnapshotId = null, this.sourceUploadStatus = "", this.sourceUploadProgress = null, this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = false, this.answerAudience = "business";
|
|
224
|
+
}
|
|
225
|
+
open() {
|
|
226
|
+
this.root && (this.root.innerHTML = "", this.panel = document.createElement("div"), this.panel.className = "po-panel", this.root.appendChild(this.panel), this.loadSources(), this.loadConversations(), this.renderPanel());
|
|
227
|
+
}
|
|
228
|
+
close() {
|
|
229
|
+
this.stopSourceRefresh(), this.cancelActiveAnswer(false), this.renderClosed();
|
|
230
|
+
}
|
|
231
|
+
updateContext(e) {
|
|
232
|
+
if (!this.options) return;
|
|
233
|
+
const t = this.options.appId;
|
|
234
|
+
this.options = { ...this.options, ...e }, this.client = new K(this.options), this.options.appId !== t && (this.answerAudience = this.loadAnswerAudience(this.options.appId), this.selectedSourceSnapshotId = null, this.currentThread = null, this.selectedPageKey = "", this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = ""), this.context = null, this.contextKey = "", this.renderPanel();
|
|
235
|
+
}
|
|
236
|
+
renderClosed() {
|
|
237
|
+
var e;
|
|
238
|
+
this.root && (this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', (e = this.root.querySelector("button")) == null || e.addEventListener("click", () => this.open()));
|
|
239
|
+
}
|
|
240
|
+
async ensureContext() {
|
|
241
|
+
if (!this.client || !this.options) throw new Error("PageOps SDK 未初始化");
|
|
242
|
+
const e = this.getPageContext(), t = this.getPageContextKey(e);
|
|
243
|
+
return this.context && this.contextKey === t ? this.context : (this.context = await this.client.createContext(e), this.contextKey = t, this.context);
|
|
244
|
+
}
|
|
245
|
+
getPageContext() {
|
|
246
|
+
var e, t, s;
|
|
247
|
+
const r = this.selectedSourceSnapshot(), n = this.selectedSourceSnapshotId != null ? this.selectedSourceSnapshotId : r ? this.sourceSnapshotValue(r) : null;
|
|
248
|
+
return {
|
|
249
|
+
...(s = (t = (e = this.options) == null ? void 0 : e.getPageContext) == null ? void 0 : t.call(e)) != null ? s : {},
|
|
250
|
+
userRole: this.answerAudience,
|
|
251
|
+
sourceSnapshotId: n == null ? void 0 : n
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
answerAudienceStorageKey(e) {
|
|
255
|
+
return `pageops:answer-audience:${e}`;
|
|
256
|
+
}
|
|
257
|
+
loadAnswerAudience(e) {
|
|
258
|
+
try {
|
|
259
|
+
const t = localStorage.getItem(this.answerAudienceStorageKey(e));
|
|
260
|
+
return C.some((s) => s.value === t) ? t : "business";
|
|
261
|
+
} catch (t) {
|
|
262
|
+
return "business";
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
saveAnswerAudience() {
|
|
266
|
+
if (this.options)
|
|
267
|
+
try {
|
|
268
|
+
localStorage.setItem(this.answerAudienceStorageKey(this.options.appId), this.answerAudience);
|
|
269
|
+
} catch (e) {
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
changeAnswerAudience(e) {
|
|
273
|
+
var s;
|
|
274
|
+
if (this.asking) return;
|
|
275
|
+
const t = (s = C.find((r) => r.value === e)) == null ? void 0 : s.value;
|
|
276
|
+
!t || t === this.answerAudience || (this.answerAudience = t, this.saveAnswerAudience(), this.renderPanel());
|
|
277
|
+
}
|
|
278
|
+
getPageContextKey(e) {
|
|
279
|
+
var t, s, r, n;
|
|
280
|
+
return JSON.stringify([
|
|
281
|
+
(t = e.route) != null ? t : "",
|
|
282
|
+
(s = e.url) != null ? s : location.href,
|
|
283
|
+
(r = e.title) != null ? r : document.title,
|
|
284
|
+
(n = e.menuPath) != null ? n : [],
|
|
285
|
+
e.sourceSnapshotId == null ? "" : String(e.sourceSnapshotId)
|
|
286
|
+
]);
|
|
287
|
+
}
|
|
288
|
+
selectSourceSnapshot(e) {
|
|
289
|
+
if (this.asking) return;
|
|
290
|
+
const s = e === "" ? null : e;
|
|
291
|
+
if ((this.selectedSourceSnapshotId == null ? "" : String(this.selectedSourceSnapshotId)) === (s == null ? "" : String(s))) return;
|
|
292
|
+
this.selectedSourceSnapshotId = s, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = false, this.renderPanel();
|
|
293
|
+
}
|
|
294
|
+
sourceSnapshotValue(e) {
|
|
295
|
+
var t, s;
|
|
296
|
+
return String((s = (t = e.id) != null ? t : e.source_snapshot_id) != null ? s : "");
|
|
297
|
+
}
|
|
298
|
+
selectedSourceSnapshot() {
|
|
299
|
+
if (this.selectedSourceSnapshotId == null) return this.sourceSnapshots[0];
|
|
300
|
+
const e = String(this.selectedSourceSnapshotId);
|
|
301
|
+
return this.sourceSnapshots.find((t) => this.sourceSnapshotValue(t) === e);
|
|
302
|
+
}
|
|
303
|
+
async loadSources() {
|
|
304
|
+
if (this.client) {
|
|
305
|
+
try {
|
|
306
|
+
const e = await this.client.listSources(), t = e[0], s = t ? this.sourceSnapshotValue(t) : null, r = this.context && this.context.source_snapshot_id != null ? String(this.context.source_snapshot_id) : null, n = this.selectedSourceSnapshotId == null && s != null && r !== s && (this.context != null || this.currentThread != null);
|
|
307
|
+
this.sourceSnapshots = e, this.sourceLoadError = "", n && (this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1);
|
|
308
|
+
} catch (e) {
|
|
309
|
+
this.sourceLoadError = "源码包状态加载失败,连接恢复后将自动重试。";
|
|
310
|
+
}
|
|
311
|
+
this.scheduleSourceRefresh(), this.renderPanel();
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
async loadConversations() {
|
|
315
|
+
this.client && (this.conversations = await this.client.listConversations(), this.renderPanel());
|
|
316
|
+
}
|
|
317
|
+
async newConversation() {
|
|
318
|
+
var s;
|
|
319
|
+
if (!this.client) return;
|
|
320
|
+
const e = await this.ensureContext(), t = (s = e.menu_path) != null && s.length ? e.menu_path.join(" / ") : e.route || document.title || "新的问答";
|
|
321
|
+
this.currentThread = await this.client.createConversation(e.id, t), this.selectedPageKey = this.contextKey, this.conversations = [this.currentThread, ...this.conversations], this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = false, this.renderPanel();
|
|
322
|
+
}
|
|
323
|
+
async selectThread(e) {
|
|
324
|
+
if (!this.client) return;
|
|
325
|
+
this.currentThread = e, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(e.id), this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = false, this.renderPanel();
|
|
326
|
+
const t = [...this.messages].reverse().map(M).find(Boolean);
|
|
327
|
+
t && await this.loadAgentRun(t);
|
|
328
|
+
}
|
|
329
|
+
async deleteConversation(e) {
|
|
330
|
+
var t;
|
|
331
|
+
if (!(!this.client || this.asking || this.deletingThreadId) && window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)) {
|
|
332
|
+
this.deletingThreadId = e.id, this.conversationError = "", this.renderPanel();
|
|
333
|
+
try {
|
|
334
|
+
if (await this.client.deleteConversation(e.id), this.conversations = this.conversations.filter((s) => s.id !== e.id), ((t = this.currentThread) == null ? void 0 : t.id) === e.id) {
|
|
335
|
+
this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1;
|
|
336
|
+
const s = this.conversations[0];
|
|
337
|
+
s && await this.selectThread(s);
|
|
338
|
+
}
|
|
339
|
+
} catch (s) {
|
|
340
|
+
this.conversationError = s instanceof Error ? s.message : "删除问答会话失败";
|
|
341
|
+
} finally {
|
|
342
|
+
this.deletingThreadId = "", this.renderPanel();
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
async uploadSource(e, t) {
|
|
347
|
+
var s;
|
|
348
|
+
if (this.client) {
|
|
349
|
+
this.sourceUploading = true, this.sourceUploadProgress = 0, this.sourceUploadStatus = "上传中 0%", this.sourceUploadError = "", this.renderPanel();
|
|
350
|
+
try {
|
|
351
|
+
await this.client.uploadSource(e, { ...t, uploader: (s = this.options) == null ? void 0 : s.uploader, onProgress: (r) => {
|
|
352
|
+
this.sourceUploadProgress = Math.max(0, Math.min(100, Math.round(r.percent))), this.sourceUploadStatus = `上传中 ${this.sourceUploadProgress}%`, this.renderPanel();
|
|
353
|
+
} }), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = this.isProjectMemoryUpdating() ? "源码上传完成,项目记忆更新中..." : "上传完成", this.scheduleSourceRefresh();
|
|
354
|
+
} catch (r) {
|
|
355
|
+
this.sourceUploadError = r instanceof Error ? r.message : "源码包上传失败", this.sourceUploadStatus = "";
|
|
356
|
+
} finally {
|
|
357
|
+
this.sourceUploading = false, this.sourceUploadProgress = null, this.renderPanel();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
async ask(e) {
|
|
362
|
+
if (!this.client || this.asking) return;
|
|
363
|
+
const t = this.questionUnavailableReason();
|
|
364
|
+
if (t) {
|
|
365
|
+
this.sourceUploadError = t, this.renderPanel();
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
this.resetAnswerState();
|
|
369
|
+
const s = ++this.activeRunId, r = new AbortController();
|
|
370
|
+
this.abortController = r, this.stoppedRunId = -1, this.asking = true, this.waitingForFirstContent = true, this.renderPanel();
|
|
371
|
+
try {
|
|
372
|
+
const n = this.getPageContextKey(this.getPageContext());
|
|
373
|
+
if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== n && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
|
|
374
|
+
this.messages.push({ id: `local-${Date.now()}`, role: "user", content: e, metadata_json: {} }), this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.renderPanel();
|
|
375
|
+
const c = await this.client.streamQuestion(this.currentThread.id, e, this.answerAudience, r.signal);
|
|
376
|
+
if (!c.ok) throw new Error(await z(c, "服务暂时无法回答,请稍后重试。"));
|
|
377
|
+
if (!c.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
|
|
378
|
+
if (await J(c.body, (p, m) => this.handleStreamEvent(p, m)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
379
|
+
if (this.streamFailure) throw new Error(this.streamFailure);
|
|
380
|
+
if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
|
|
381
|
+
if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
382
|
+
await this.selectThread(this.currentThread);
|
|
383
|
+
} catch (n) {
|
|
384
|
+
if (s !== this.activeRunId) return;
|
|
385
|
+
this.typewriter.clear(), this.waitingForFirstContent = false, s === this.stoppedRunId ? this.answerStopped = true : (this.answerError = n instanceof Error ? n.message : "服务异常,请稍后重试。", this.upsertStep({ id: "error", title: "执行失败", status: "failed", summary: this.answerError }));
|
|
386
|
+
} finally {
|
|
387
|
+
if (s !== this.activeRunId) return;
|
|
388
|
+
this.asking = false, this.waitingForFirstContent = false, this.abortController === r && (this.abortController = null), this.renderPanel(true);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
cancelActiveAnswer(e) {
|
|
392
|
+
var t;
|
|
393
|
+
if (!(!this.asking && !this.abortController)) {
|
|
394
|
+
if (e) {
|
|
395
|
+
this.stoppedRunId = this.activeRunId, this.answerStopped = true;
|
|
396
|
+
const s = this.steps.map((r) => r.status === "running" ? { ...r, status: "cancelled" } : r);
|
|
397
|
+
this.steps = s.some((r) => r.status === "cancelled") ? s : [...s, { id: "stopped", title: "已停止", status: "cancelled" }];
|
|
398
|
+
} else
|
|
399
|
+
this.activeRunId += 1, this.asking = false;
|
|
400
|
+
this.typewriter.clear(), this.waitingForFirstContent = false, (t = this.abortController) == null || t.abort(), this.abortController = null, e && this.renderPanel();
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
handleStreamEvent(e, t) {
|
|
404
|
+
var s, r;
|
|
405
|
+
if (e === "step") {
|
|
406
|
+
this.upsertStep(t), this.renderExecutionSteps(true);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
if (e === "delta") {
|
|
410
|
+
const n = String((s = t.content) != null ? s : "");
|
|
411
|
+
if (!n) return;
|
|
412
|
+
this.waitingForFirstContent = false, this.typewriter.enqueue(n);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
e === "done" && (this.streamDone = t), e === "error" && (this.streamFailure = String((r = t.message) != null ? r : "服务异常,请稍后重试。"));
|
|
416
|
+
}
|
|
417
|
+
updateStreamingMessage() {
|
|
418
|
+
var s, r;
|
|
419
|
+
const e = (s = this.panel) == null ? void 0 : s.querySelector("[data-streaming-content]");
|
|
420
|
+
if (!e) {
|
|
421
|
+
this.renderPanel();
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
e.innerHTML = R(this.streaming);
|
|
425
|
+
const t = (r = this.panel) == null ? void 0 : r.querySelector(".po-messages");
|
|
426
|
+
t && (t.scrollTop = t.scrollHeight);
|
|
427
|
+
}
|
|
428
|
+
resetAnswerState() {
|
|
429
|
+
this.typewriter.clear(), this.asking = false, this.waitingForFirstContent = false, this.answerError = "", this.answerStopped = false, this.streamFailure = "", this.streamDone = null, this.streaming = "";
|
|
430
|
+
}
|
|
431
|
+
upsertStep(e) {
|
|
432
|
+
const t = this.steps.findIndex((s) => s.id === e.id);
|
|
433
|
+
this.steps = t === -1 ? [...this.steps, e] : this.steps.map((s) => s.id === e.id ? { ...s, ...e } : s);
|
|
434
|
+
}
|
|
435
|
+
async loadAgentRun(e) {
|
|
436
|
+
if (!(!this.client || !e)) {
|
|
437
|
+
this.selectedAgentRunId = e, this.runLoading = true, this.runLoadError = "", this.renderPanel();
|
|
438
|
+
try {
|
|
439
|
+
const t = await this.client.getAgentRun(e);
|
|
440
|
+
if (this.selectedAgentRunId !== e) return;
|
|
441
|
+
this.steps = t.steps;
|
|
442
|
+
} catch (t) {
|
|
443
|
+
if (this.selectedAgentRunId !== e) return;
|
|
444
|
+
this.steps = [], this.runLoadError = t instanceof Error ? t.message : "执行过程加载失败";
|
|
445
|
+
} finally {
|
|
446
|
+
this.selectedAgentRunId === e && (this.runLoading = false, this.renderPanel());
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
async copyAgentRunId(e) {
|
|
451
|
+
var t;
|
|
452
|
+
if (e) {
|
|
453
|
+
try {
|
|
454
|
+
if ((t = navigator.clipboard) != null && t.writeText)
|
|
455
|
+
await navigator.clipboard.writeText(e);
|
|
456
|
+
else {
|
|
457
|
+
const s = document.createElement("textarea");
|
|
458
|
+
if (s.value = e, s.style.position = "fixed", s.style.opacity = "0", document.body.appendChild(s), s.select(), !document.execCommand("copy")) throw new Error("copy_not_supported");
|
|
459
|
+
s.remove();
|
|
460
|
+
}
|
|
461
|
+
this.copiedAgentRunId = e;
|
|
462
|
+
} catch (s) {
|
|
463
|
+
this.copiedAgentRunId = `error:${e}`;
|
|
464
|
+
}
|
|
465
|
+
this.clearCopyFeedback(false), this.copyFeedbackTimer = setTimeout(() => {
|
|
466
|
+
this.copiedAgentRunId = "", this.copyFeedbackTimer = null, this.updateCopyFeedback();
|
|
467
|
+
}, 1800), this.updateCopyFeedback();
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
updateCopyFeedback() {
|
|
471
|
+
var e;
|
|
472
|
+
(e = this.panel) == null || e.querySelectorAll("[data-copy-run]").forEach((t) => {
|
|
473
|
+
var r;
|
|
474
|
+
const s = (r = t.dataset.copyRun) != null ? r : "";
|
|
475
|
+
t.textContent = this.copiedAgentRunId === s ? "已复制" : this.copiedAgentRunId === `error:${s}` ? "复制失败" : "复制流水号";
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
clearCopyFeedback(e = true) {
|
|
479
|
+
this.copyFeedbackTimer && clearTimeout(this.copyFeedbackTimer), this.copyFeedbackTimer = null, e && (this.copiedAgentRunId = "");
|
|
480
|
+
}
|
|
481
|
+
latestAnalysisStatus() {
|
|
482
|
+
var e, t, s;
|
|
483
|
+
return String((s = (t = (e = this.selectedSourceSnapshot()) == null ? void 0 : e.metadata) == null ? void 0 : t.analysis_status) != null ? s : "");
|
|
484
|
+
}
|
|
485
|
+
isProjectMemoryUpdating() {
|
|
486
|
+
return ["pending", "running"].includes(this.latestAnalysisStatus());
|
|
487
|
+
}
|
|
488
|
+
questionUnavailableReason() {
|
|
489
|
+
return this.sourceLoadError && !this.sourceSnapshots.length ? "暂时无法读取项目共享代码包,请检查 PageOps 服务连接。" : this.sourceSnapshots.length ? this.isProjectMemoryUpdating() ? "项目记忆正在更新,完成前暂不能问答。" : this.latestAnalysisStatus() === "failed" ? "项目记忆更新失败,请重新上传或重新索引。" : "" : "请先上传代码包后再提问。";
|
|
490
|
+
}
|
|
491
|
+
scheduleSourceRefresh() {
|
|
492
|
+
this.stopSourceRefresh(), !(!this.sourceLoadError && !this.isProjectMemoryUpdating()) && (this.sourceRefreshTimer = setTimeout(() => void this.loadSources(), 1500));
|
|
493
|
+
}
|
|
494
|
+
stopSourceRefresh() {
|
|
495
|
+
this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
|
|
496
|
+
}
|
|
497
|
+
renderPanel(e = this.asking, t = false) {
|
|
498
|
+
var g;
|
|
499
|
+
if (!this.panel) return;
|
|
500
|
+
const s = (g = this.panel.querySelector(".po-messages")) == null ? void 0 : g.scrollTop, r = this.questionUnavailableReason(), n = r || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), c = !!(r || this.asking), p = r ? '<button type="submit" disabled>暂不可提问</button>' : this.asking ? '<button class="po-stop" type="button" data-action="stop-answer" aria-label="停止输出" title="停止输出"><span aria-hidden="true"></span></button>' : '<button type="submit">发送</button>', m = C.map((o) => `
|
|
501
|
+
<button type="button" data-audience="${o.value}" aria-pressed="${o.value === this.answerAudience}" ${this.asking ? "disabled" : ""}>${o.label}</button>
|
|
502
|
+
`).join("");
|
|
503
|
+
if (this.panel.innerHTML = `
|
|
6
504
|
<aside class="po-sidebar">
|
|
7
505
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
8
|
-
<button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
|
|
506
|
+
<button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
|
|
9
507
|
<input class="po-search" placeholder="搜索问答" />
|
|
10
|
-
${this.conversationError
|
|
11
|
-
<div class="po-thread-list">${this.conversations.map(o=>{
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
508
|
+
${this.conversationError ? `<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>` : ""}
|
|
509
|
+
<div class="po-thread-list">${this.conversations.map((o) => {
|
|
510
|
+
var y;
|
|
511
|
+
return `
|
|
512
|
+
<div class="po-thread-row ${o.id === ((y = this.currentThread) == null ? void 0 : y.id) ? "active" : ""}">
|
|
513
|
+
<button class="po-thread" data-thread="${l(o.id)}" ${this.asking ? "disabled" : ""}>
|
|
514
|
+
<strong>${l(o.title)}</strong><span>${O(o.created_at)}</span>
|
|
15
515
|
</button>
|
|
16
|
-
<button class="po-thread-delete" type="button" data-delete-thread="${l(o.id)}" aria-label="删除会话:${l(o.title)}" title="删除会话" ${this.asking||this.deletingThreadId===o.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
17
|
-
</div
|
|
516
|
+
<button class="po-thread-delete" type="button" data-delete-thread="${l(o.id)}" aria-label="删除会话:${l(o.title)}" title="删除会话" ${this.asking || this.deletingThreadId === o.id ? "disabled" : ""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
517
|
+
</div>`;
|
|
518
|
+
}).join("")}</div>
|
|
18
519
|
</aside>
|
|
19
520
|
<main class="po-chat">
|
|
20
|
-
<header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread?l(this.currentThread.title):"未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${
|
|
521
|
+
<header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread ? l(this.currentThread.title) : "未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${m}</div></div></header>
|
|
21
522
|
<section class="po-messages">
|
|
22
|
-
${this.messages.map(o=>this.renderMessage(o)).join("")}
|
|
523
|
+
${this.messages.map((o) => this.renderMessage(o)).join("")}
|
|
23
524
|
${this.renderAnswerState()}
|
|
24
525
|
</section>
|
|
25
|
-
<form class="po-composer"><textarea ${c?"disabled":""} placeholder="${l(n)}"></textarea>${p}</form>
|
|
526
|
+
<form class="po-composer"><textarea ${c ? "disabled" : ""} placeholder="${l(n)}"></textarea>${p}</form>
|
|
26
527
|
</main>
|
|
27
528
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}<div class="po-steps">${this.renderSteps()}</div></section></aside>
|
|
28
|
-
`,this.bindPanelEvents(),
|
|
529
|
+
`, this.bindPanelEvents(), e) {
|
|
530
|
+
const o = this.panel.querySelector(".po-messages");
|
|
531
|
+
o && (o.scrollTop = o.scrollHeight);
|
|
532
|
+
} else if (s !== void 0) {
|
|
533
|
+
const o = this.panel.querySelector(".po-messages");
|
|
534
|
+
o && (o.scrollTop = s);
|
|
535
|
+
}
|
|
536
|
+
if (t) {
|
|
537
|
+
const o = this.panel.querySelector(".po-trace > section");
|
|
538
|
+
o && (o.scrollTop = o.scrollHeight);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
renderAnswerState() {
|
|
542
|
+
const e = this.asking && this.waitingForFirstContent ? '<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>' : "", t = this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${R(this.streaming)}</span>${this.asking ? '<span class="po-typing-cursor" aria-hidden="true"></span>' : ""}</div></article>` : "", s = this.answerError ? `<article class="po-message assistant answer-error" role="alert"><b>PageOps 分析</b><strong>本次回答失败</strong><div>${l(this.answerError)}</div></article>` : "", r = this.answerStopped ? '<div class="po-stream-stopped" role="status">已停止输出</div>' : "";
|
|
543
|
+
return `${e}${t}${r}${s}`;
|
|
544
|
+
}
|
|
545
|
+
renderMessage(e) {
|
|
546
|
+
const t = M(e), s = t && t === this.selectedAgentRunId, r = this.copiedAgentRunId === t, n = this.copiedAgentRunId === `error:${t}`, c = e.role === "assistant" && t ? `<footer class="po-answer-meta ${s ? "selected" : ""}">
|
|
29
547
|
<span class="po-run-id" title="${l(t)}">问答流水号 <code>${l(t)}</code></span>
|
|
30
|
-
<button type="button" data-copy-run="${l(t)}">${r?"已复制":n?"复制失败":"复制流水号"}</button>
|
|
31
|
-
<button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s?"正在查看":"查看执行过程"}</button>
|
|
32
|
-
</footer
|
|
33
|
-
|
|
34
|
-
<
|
|
548
|
+
<button type="button" data-copy-run="${l(t)}">${r ? "已复制" : n ? "复制失败" : "复制流水号"}</button>
|
|
549
|
+
<button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s ? "正在查看" : "查看执行过程"}</button>
|
|
550
|
+
</footer>` : "";
|
|
551
|
+
return `<article class="po-message ${e.role} ${s ? "run-selected" : ""}" data-message="${l(e.id)}">
|
|
552
|
+
<b>${e.role === "user" ? "你" : "PageOps 分析"}</b>
|
|
553
|
+
<div>${e.role === "assistant" ? R(e.content) : l(e.content)}</div>
|
|
35
554
|
${c}
|
|
36
|
-
</article
|
|
555
|
+
</article>`;
|
|
556
|
+
}
|
|
557
|
+
renderSourceUploader() {
|
|
558
|
+
const e = this.sourceLoadError ? "暂时无法读取项目共享代码包,连接恢复后将自动重试。" : "当前项目暂无代码包,请先上传后再提问。";
|
|
559
|
+
const t = typeof this.sourceUploadProgress == "number" ? Math.max(0, Math.min(100, Math.round(this.sourceUploadProgress))) : 0;
|
|
560
|
+
return `
|
|
37
561
|
<div class="po-source-uploader">
|
|
38
562
|
<strong>源码包</strong>
|
|
39
563
|
<p>同一项目的所有回答角色共享代码包。上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
|
|
@@ -44,20 +568,134 @@
|
|
|
44
568
|
<input class="po-source-reference-value" type="text" maxlength="128" placeholder="请输入 Branch 名称" />
|
|
45
569
|
<textarea class="po-source-remark" maxlength="500" placeholder="备注(选填)"></textarea>
|
|
46
570
|
<label class="po-upload-button">
|
|
47
|
-
<span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
|
|
48
|
-
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
|
|
571
|
+
<span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
|
|
572
|
+
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
|
|
49
573
|
</label>
|
|
50
|
-
${this.sourceUploadStatus
|
|
51
|
-
${this.sourceUploading
|
|
52
|
-
${this.sourceSnapshots.length
|
|
53
|
-
${this.sourceLoadError
|
|
54
|
-
${this.sourceUploadError
|
|
574
|
+
${this.sourceUploadStatus ? `<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>` : ""}
|
|
575
|
+
${this.sourceUploading ? `<div class="po-upload-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${t}"><span style="width:${t}%"></span></div>` : ""}
|
|
576
|
+
${this.sourceSnapshots.length ? `<label class="po-source-selector"><span>问答代码包</span><select data-action="select-source" ${this.asking ? "disabled" : ""}><option value="" ${this.selectedSourceSnapshotId == null ? "selected" : ""}>最新 ready 代码包(默认)</option>${this.sourceSnapshots.map((s) => this.renderSourceOption(s)).join("")}</select></label><div class="po-source-list">${this.sourceSnapshots.map((s) => this.renderSourceItem(s)).join("")}</div>` : `<p class="po-upload-empty">${e}</p>`}
|
|
577
|
+
${this.sourceLoadError ? `<p class="po-upload-error">${l(this.sourceLoadError)}</p>` : ""}
|
|
578
|
+
${this.sourceUploadError ? `<p class="po-upload-error">${l(this.sourceUploadError)}</p>` : ""}
|
|
55
579
|
</div>
|
|
56
|
-
|
|
580
|
+
`;
|
|
581
|
+
}
|
|
582
|
+
renderSourceOption(e) {
|
|
583
|
+
var n, c, p;
|
|
584
|
+
const t = this.sourceSnapshotValue(e), s = e.filename || `代码包 ${t}`, r = String((p = (c = (n = e.metadata) == null ? void 0 : n.analysis_status) != null ? c : e.status) != null ? p : "unknown");
|
|
585
|
+
return `<option value="${l(t)}" ${this.selectedSourceSnapshotId != null && String(this.selectedSourceSnapshotId) === t ? "selected" : ""}>${l(s)} · ${l(r)}</option>`;
|
|
586
|
+
}
|
|
587
|
+
renderSourceItem(e) {
|
|
588
|
+
var w, b, S, $, E, A, T;
|
|
589
|
+
const t = e.filename || "未命名代码包", s = e.created_at ? O(e.created_at) : "刚刚上传", r = G(e.archive_bytes || e.total_bytes || 0), n = String((b = (w = e.metadata) == null ? void 0 : w.analysis_status) != null ? b : "unknown"), c = typeof ((S = e.metadata) == null ? void 0 : S.tag) == "string" ? e.metadata.tag : "", p = typeof (($ = e.metadata) == null ? void 0 : $.branch) == "string" ? e.metadata.branch : "", m = c ? `Tag: ${c}` : p ? `Branch: ${p}` : "未记录代码引用", g = typeof ((E = e.metadata) == null ? void 0 : E.remark) == "string" && e.metadata.remark ? e.metadata.remark : "无备注", o = typeof ((A = e.metadata) == null ? void 0 : A.uploader) == "string" ? e.metadata.uploader : "未知用户", y = (T = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? T : "项目记忆状态未知";
|
|
590
|
+
return `<article class="po-source-item ${this.selectedSourceSnapshotId != null && this.sourceSnapshotValue(e) === String(this.selectedSourceSnapshotId) || this.selectedSourceSnapshotId == null && e === this.sourceSnapshots[0] ? "selected" : ""}"><strong>${l(t)}</strong><span>${l(m)}</span><span>备注:${l(g)}</span><span>上传人:${l(o)} · ${l(s)} · ${l(r)}</span><span>${l(y)} · 当前问答${this.selectedSourceSnapshotId == null && e === this.sourceSnapshots[0] ? "默认" : ""}引用</span></article>`;
|
|
591
|
+
}
|
|
592
|
+
renderSteps() {
|
|
593
|
+
return this.runLoading ? '<div class="po-trace-state"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在恢复本次执行过程</span></div>' : this.runLoadError ? `<div class="po-trace-state failed" role="alert">${l(this.runLoadError)}</div>` : (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", summary: "发送问题后,这里会展示完整分析过程。" }]).map((t) => {
|
|
594
|
+
var c, p, m;
|
|
595
|
+
const s = (c = t.metrics) != null && c.length ? `<div class="po-step-metrics">${t.metrics.map((g) => `<span>${l(g)}</span>`).join("")}</div>` : "", r = (p = t.details) != null && p.length ? `<div class="po-step-details">${t.details.map((g) => `<div><span>${l(g.label)}</span><p>${l(g.value)}</p></div>`).join("")}</div>` : "", n = !!(s || r);
|
|
596
|
+
return `<details class="po-step ${t.status}" ${t.status === "running" || t.status === "failed" ? "open" : ""} ${n ? "" : "data-static"}>
|
|
57
597
|
<summary>
|
|
58
598
|
<span class="po-step-dot" aria-hidden="true"></span>
|
|
59
|
-
<span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((
|
|
60
|
-
<span class="po-step-status">${
|
|
599
|
+
<span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((m = t.summary) != null ? m : "")}</small>${s}</span>
|
|
600
|
+
<span class="po-step-status">${Z(t.status)}</span>
|
|
61
601
|
</summary>
|
|
62
602
|
${r}
|
|
63
|
-
</details
|
|
603
|
+
</details>`;
|
|
604
|
+
}).join("");
|
|
605
|
+
}
|
|
606
|
+
renderExecutionSteps(e = false) {
|
|
607
|
+
var s, r;
|
|
608
|
+
const t = (s = this.panel) == null ? void 0 : s.querySelector(".po-steps");
|
|
609
|
+
if (t && (t.innerHTML = this.renderSteps(), e)) {
|
|
610
|
+
const n = (r = this.panel) == null ? void 0 : r.querySelector(".po-trace > section");
|
|
611
|
+
n && (n.scrollTop = n.scrollHeight);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
bindPanelEvents() {
|
|
615
|
+
var e, t, s, r, n, c, p, m, g, o, y, w, b, S, $, E, A, T, h, d;
|
|
616
|
+
(t = (e = this.panel) == null ? void 0 : e.querySelector('[data-action="new"]')) == null || t.addEventListener("click", () => void this.newConversation()), (r = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || r.addEventListener("click", () => this.close()), (c = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="stop-answer"]')) == null || c.addEventListener("click", () => this.cancelActiveAnswer(true)), (p = this.panel) == null || p.querySelectorAll("[data-audience]").forEach((h) => {
|
|
617
|
+
h.addEventListener("click", () => {
|
|
618
|
+
var d;
|
|
619
|
+
return this.changeAnswerAudience((d = h.dataset.audience) != null ? d : "");
|
|
620
|
+
});
|
|
621
|
+
}), (g = (m = this.panel) == null ? void 0 : m.querySelector('[data-action="upload-source"]')) == null || g.addEventListener("change", (h) => {
|
|
622
|
+
var k, P, I, x, q, L, F, U, _;
|
|
623
|
+
const d = (k = h.target.files) == null ? void 0 : k[0];
|
|
624
|
+
if (!d) return;
|
|
625
|
+
const u = (I = (P = this.panel) == null ? void 0 : P.querySelector('[name="source-reference"]:checked')) == null ? void 0 : I.value, f = (L = (q = (x = this.panel) == null ? void 0 : x.querySelector(".po-source-reference-value")) == null ? void 0 : q.value.trim()) != null ? L : "", B = (_ = (U = (F = this.panel) == null ? void 0 : F.querySelector(".po-source-remark")) == null ? void 0 : U.value.trim()) != null ? _ : "";
|
|
626
|
+
if (!f || u !== "tag" && u !== "branch") {
|
|
627
|
+
this.sourceUploadError = "请选择 Tag 或 Branch,并填写对应名称。", this.renderPanel();
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
this.uploadSource(d, { [u]: f, remark: B });
|
|
631
|
+
}), (o = this.panel) == null || o.querySelectorAll('[name="source-reference"]').forEach((h) => {
|
|
632
|
+
h.addEventListener("change", () => {
|
|
633
|
+
var u;
|
|
634
|
+
const d = (u = this.panel) == null ? void 0 : u.querySelector(".po-source-reference-value");
|
|
635
|
+
d && (d.placeholder = `请输入 ${h.value === "tag" ? "Tag" : "Branch"} 名称`);
|
|
636
|
+
});
|
|
637
|
+
}), (d = (h = this.panel) == null ? void 0 : h.querySelector('[data-action="select-source"]')) == null || d.addEventListener("change", (u) => {
|
|
638
|
+
this.selectSourceSnapshot(u.target.value);
|
|
639
|
+
}), (y = this.panel) == null || y.querySelectorAll("[data-thread]").forEach((h) => {
|
|
640
|
+
h.addEventListener("click", () => {
|
|
641
|
+
const d = this.conversations.find((u) => u.id === h.dataset.thread);
|
|
642
|
+
d && this.selectThread(d);
|
|
643
|
+
});
|
|
644
|
+
}), (w = this.panel) == null || w.querySelectorAll("[data-delete-thread]").forEach((h) => {
|
|
645
|
+
h.addEventListener("click", (d) => {
|
|
646
|
+
d.stopPropagation();
|
|
647
|
+
const u = this.conversations.find((f) => f.id === h.dataset.deleteThread);
|
|
648
|
+
u && this.deleteConversation(u);
|
|
649
|
+
});
|
|
650
|
+
}), (b = this.panel) == null || b.querySelectorAll("[data-view-run]").forEach((h) => {
|
|
651
|
+
h.addEventListener("click", (d) => {
|
|
652
|
+
var u;
|
|
653
|
+
d.stopPropagation(), this.loadAgentRun((u = h.dataset.viewRun) != null ? u : "");
|
|
654
|
+
});
|
|
655
|
+
}), (S = this.panel) == null || S.querySelectorAll("[data-copy-run]").forEach((h) => {
|
|
656
|
+
h.addEventListener("click", (d) => {
|
|
657
|
+
var u;
|
|
658
|
+
d.stopPropagation(), this.copyAgentRunId((u = h.dataset.copyRun) != null ? u : "");
|
|
659
|
+
});
|
|
660
|
+
}), (E = ($ = this.panel) == null ? void 0 : $.querySelector("form")) == null || E.addEventListener("submit", (h) => {
|
|
661
|
+
var f;
|
|
662
|
+
h.preventDefault();
|
|
663
|
+
const d = (f = this.panel) == null ? void 0 : f.querySelector("textarea"), u = d == null ? void 0 : d.value.trim();
|
|
664
|
+
u && (d.value = "", this.ask(u));
|
|
665
|
+
}), (T = (A = this.panel) == null ? void 0 : A.querySelector("textarea")) == null || T.addEventListener("keydown", (h) => {
|
|
666
|
+
var u, f;
|
|
667
|
+
const d = h;
|
|
668
|
+
d.key === "Enter" && !d.shiftKey && (d.preventDefault(), (f = (u = this.panel) == null ? void 0 : u.querySelector("form")) == null || f.requestSubmit());
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
function l(a) {
|
|
673
|
+
return String(a == null ? "" : a).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
674
|
+
}
|
|
675
|
+
function M(a) {
|
|
676
|
+
var t;
|
|
677
|
+
const e = (t = a.metadata_json) == null ? void 0 : t.agent_run_id;
|
|
678
|
+
return typeof e == "number" ? String(e) : typeof e == "string" ? e : "";
|
|
679
|
+
}
|
|
680
|
+
function O(a) {
|
|
681
|
+
return new Intl.DateTimeFormat("zh-CN", {
|
|
682
|
+
timeZone: "Asia/Shanghai",
|
|
683
|
+
month: "2-digit",
|
|
684
|
+
day: "2-digit",
|
|
685
|
+
hour: "2-digit",
|
|
686
|
+
minute: "2-digit",
|
|
687
|
+
hourCycle: "h23"
|
|
688
|
+
}).format(new Date(a));
|
|
689
|
+
}
|
|
690
|
+
function G(a) {
|
|
691
|
+
if (!a) return "0 B";
|
|
692
|
+
const e = ["B", "KB", "MB", "GB"];
|
|
693
|
+
let t = a, s = 0;
|
|
694
|
+
for (; t >= 1024 && s < e.length - 1; )
|
|
695
|
+
t /= 1024, s += 1;
|
|
696
|
+
return `${t >= 10 || s === 0 ? t.toFixed(0) : t.toFixed(1)} ${e[s]}`;
|
|
697
|
+
}
|
|
698
|
+
function Z(a) {
|
|
699
|
+
return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[a];
|
|
700
|
+
}
|
|
701
|
+
const Y = new V();exports.PageOpsSDK=Y;}));
|
package/dist/types.d.ts
CHANGED
|
@@ -27,7 +27,7 @@ export interface ContextSession {
|
|
|
27
27
|
tenant_id?: string;
|
|
28
28
|
user_role?: string;
|
|
29
29
|
build_version?: string;
|
|
30
|
-
source_snapshot_id?: number | null;
|
|
30
|
+
source_snapshot_id?: number | string | null;
|
|
31
31
|
}
|
|
32
32
|
export interface ConversationThread {
|
|
33
33
|
id: string;
|
|
@@ -65,8 +65,8 @@ export interface AgentRunHistory {
|
|
|
65
65
|
steps: ExecutionStep[];
|
|
66
66
|
}
|
|
67
67
|
export interface SourceSnapshot {
|
|
68
|
-
id?: string;
|
|
69
|
-
source_snapshot_id?: string | null;
|
|
68
|
+
id?: number | string;
|
|
69
|
+
source_snapshot_id?: number | string | null;
|
|
70
70
|
project_id?: string;
|
|
71
71
|
filename?: string | null;
|
|
72
72
|
archive_bytes?: number;
|