@pageops/sdk 0.1.10 → 0.1.11
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/index.d.ts +6 -0
- package/dist/pageops-sdk.css +1 -1
- package/dist/pageops-sdk.es.js +250 -196
- package/dist/pageops-sdk.umd.cjs +19 -17
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -29,6 +29,8 @@ declare class PageOpsSDKController {
|
|
|
29
29
|
private deletingThreadId;
|
|
30
30
|
private streamFailure;
|
|
31
31
|
private streamDone;
|
|
32
|
+
private answerAudience;
|
|
33
|
+
private audienceChanging;
|
|
32
34
|
private typewriter;
|
|
33
35
|
mount(options: PageOpsMountOptions): void;
|
|
34
36
|
unmount(): void;
|
|
@@ -38,6 +40,10 @@ declare class PageOpsSDKController {
|
|
|
38
40
|
private renderClosed;
|
|
39
41
|
private ensureContext;
|
|
40
42
|
private getPageContext;
|
|
43
|
+
private answerAudienceStorageKey;
|
|
44
|
+
private loadAnswerAudience;
|
|
45
|
+
private saveAnswerAudience;
|
|
46
|
+
private changeAnswerAudience;
|
|
41
47
|
private getPageContextKey;
|
|
42
48
|
private loadSources;
|
|
43
49
|
private loadConversations;
|
package/dist/pageops-sdk.css
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
.pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread-row{position:relative;display:grid;grid-template-columns:minmax(0,1fr) 32px;align-items:center;border:1px solid transparent;border-radius:10px}.po-thread-row.active{border-color:#bfdbfe;background:#fff}.po-thread{display:grid;gap:4px;width:100%;border:0;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread-row.active .po-thread{color:var(--po-text)}.po-thread span{color:#94a3b8;font-size:12px}.po-thread-delete{display:grid;width:28px;height:28px;place-items:center;border:0;border-radius:6px;background:transparent;color:#94a3b8;opacity:0}.po-thread-row:hover .po-thread-delete,.po-thread-row:focus-within .po-thread-delete{opacity:1}.po-thread-delete:hover{background:#fee2e2;color:#b91c1c}.po-thread-delete:disabled{cursor:not-allowed;opacity:.35}.po-trash-icon{position:relative;width:11px;height:12px;border:1.5px solid currentcolor;border-top:0;border-radius:0 0 2px 2px}.po-trash-icon:before{position:absolute;top:-4px;left:-2px;width:13px;border-top:1.5px solid currentcolor;content:""}.po-trash-icon:after{position:absolute;top:-6px;left:3px;width:4px;height:2px;border:1.5px solid currentcolor;border-bottom:0;border-radius:2px 2px 0 0;content:""}.po-conversation-error{margin:0;color:#b91c1c;font-size:12px}.po-chat{display:flex;min-width:0;min-height:0;flex-direction:column;background:linear-gradient(180deg,#fff,var(--po-panel));padding:22px 26px}.po-chat header,.po-trace header{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--po-soft-border);padding-bottom:14px}.po-chat header p,.po-chat header h2,.po-trace header h2{margin:0}.po-chat header p,.po-chat header span{color:var(--po-muted);font-size:12px}.po-chat header h2,.po-trace header h2{font-size:20px;letter-spacing
|
|
1
|
+
.pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread-row{position:relative;display:grid;grid-template-columns:minmax(0,1fr) 32px;align-items:center;border:1px solid transparent;border-radius:10px}.po-thread-row.active{border-color:#bfdbfe;background:#fff}.po-thread{display:grid;gap:4px;width:100%;border:0;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread-row.active .po-thread{color:var(--po-text)}.po-thread span{color:#94a3b8;font-size:12px}.po-thread-delete{display:grid;width:28px;height:28px;place-items:center;border:0;border-radius:6px;background:transparent;color:#94a3b8;opacity:0}.po-thread-row:hover .po-thread-delete,.po-thread-row:focus-within .po-thread-delete{opacity:1}.po-thread-delete:hover{background:#fee2e2;color:#b91c1c}.po-thread-delete:disabled{cursor:not-allowed;opacity:.35}.po-trash-icon{position:relative;width:11px;height:12px;border:1.5px solid currentcolor;border-top:0;border-radius:0 0 2px 2px}.po-trash-icon:before{position:absolute;top:-4px;left:-2px;width:13px;border-top:1.5px solid currentcolor;content:""}.po-trash-icon:after{position:absolute;top:-6px;left:3px;width:4px;height:2px;border:1.5px solid currentcolor;border-bottom:0;border-radius:2px 2px 0 0;content:""}.po-conversation-error{margin:0;color:#b91c1c;font-size:12px}.po-chat{display:flex;min-width:0;min-height:0;flex-direction:column;background:linear-gradient(180deg,#fff,var(--po-panel));padding:22px 26px}.po-chat header,.po-trace header{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--po-soft-border);padding-bottom:14px}.po-chat header p,.po-chat header h2,.po-trace header h2{margin:0}.po-chat header p,.po-chat header span{color:var(--po-muted);font-size:12px}.po-chat header h2,.po-trace header h2{font-size:20px;letter-spacing:0}.po-chat-title{min-width:0}.po-chat-title h2{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-audience{display:flex;flex:0 0 auto;align-items:center;gap:8px}.po-audience>span{white-space:nowrap}.po-audience-options{display:grid;grid-template-columns:repeat(4,44px);height:32px;overflow:hidden;border:1px solid #cbd5e1;border-radius:6px;background:#f8fafc}.po-audience-options button{min-width:0;border:0;border-right:1px solid #e2e8f0;background:transparent;color:#475569;padding:0 8px;font-size:12px;font-weight:650}.po-audience-options button:last-child{border-right:0}.po-audience-options button[aria-pressed=true]{background:var(--po-primary);color:#fff}.po-audience-options button:disabled{cursor:not-allowed;opacity:.55}.po-messages{display:grid;align-content:start;gap:14px;min-height:0;flex:1;overflow:auto;padding:18px 4px 18px 0}.po-message{display:grid;max-width:82%;gap:6px;border:1px solid var(--po-soft-border);border-radius:14px;padding:11px 13px;line-height:1.55;white-space:pre-wrap;word-break:break-word}.po-message b{font-size:12px;opacity:.78}.po-message.user{justify-self:end;border-color:var(--po-primary);background:var(--po-primary);color:#fff}.po-message.assistant{justify-self:start;background:var(--po-soft)}.po-message.streaming{border-color:#bfdbfe;background:#eff6ff}.po-message.answer-error{border-color:#fecaca;background:#fff7f7;color:#991b1b}.po-message.answer-error>strong{color:#7f1d1d}.po-stream-stopped{justify-self:start;color:var(--po-muted);font-size:12px}.po-ai-waiting{display:inline-flex;align-items:center;gap:9px;min-height:24px;color:#475569}.po-ai-spinner{width:16px;height:16px;flex:0 0 auto;border:2px solid #bfdbfe;border-top-color:var(--po-primary);border-radius:50%;animation:po-ai-spin .7s linear infinite}.po-typing-cursor{display:inline-block;width:2px;height:1em;margin-left:3px;background:var(--po-primary);vertical-align:-.12em;animation:po-typing-cursor .8s steps(1,end) infinite}@keyframes po-ai-spin{to{transform:rotate(360deg)}}@keyframes po-typing-cursor{50%{opacity:0}}.po-message code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.po-message pre{max-width:100%;margin:8px 0;overflow:auto;border:1px solid var(--po-border);border-radius:6px;background:#f8fafc;padding:10px 12px;white-space:pre}.po-message pre code{border-radius:0;background:transparent;color:#1f2937;padding:0}.po-message h2,.po-message h3,.po-message h4,.po-message p{margin:8px 0}.po-message table{width:100%;margin:12px 0;border-collapse:collapse;border-radius:10px;font-size:14px}.po-message th,.po-message td{border:1px solid var(--po-border);padding:8px 10px;text-align:left;vertical-align:top}.po-message th{background:#eef5ff;color:#334155;font-weight:800}.po-composer{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px;border-top:1px solid var(--po-soft-border);padding-top:12px}.po-composer textarea{min-height:88px;resize:vertical;padding:10px}.po-composer button{min-height:44px;padding:0 16px}.po-composer .po-stop{display:grid;width:44px;height:44px;min-height:44px;place-items:center;border:1px solid #fecaca;background:#fff;color:#dc2626;padding:0}.po-stop span{width:12px;height:12px;border-radius:2px;background:currentcolor}.po-trace{display:flex;min-height:0;flex-direction:column;border-left:1px solid var(--po-soft-border);background:#fafbff}.po-trace header{padding:18px}.po-trace header button{width:32px;height:32px;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:#334155;font-size:20px;line-height:1}.po-trace section{display:grid;align-content:start;gap:12px;min-height:0;overflow:auto;padding:16px}.po-source-uploader{display:grid;gap:8px;border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-source-uploader p{margin:0;color:var(--po-muted);font-size:12px;line-height:1.5}.po-upload-button{display:inline-flex;justify-content:center;border:1px solid #bfdbfe;border-radius:10px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-empty{color:#92400e!important}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:10px;background:#f8fbff;padding:8px}.po-source-item strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-source-item span{color:var(--po-muted);font-size:12px}.po-composer textarea:disabled,.po-composer button:disabled{cursor:not-allowed;opacity:.62}.po-upload-error{color:#b91c1c!important}.po-step{border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-step.running{border-color:#bfdbfe;background:#eff6ff}.po-step.completed{border-color:#bbf7d0}.po-step.failed{border-color:#fecaca;background:#fff1f2}.po-step.cancelled{border-color:#cbd5e1;background:#f8fafc}.po-step summary{display:flex;justify-content:space-between;gap:8px;cursor:pointer}.po-step summary::marker{color:var(--po-muted)}.po-step pre{overflow:auto;margin:10px 0 0;border-radius:12px;background:#0f172a;color:#e2e8f0;padding:12px;font-size:12px;white-space:pre-wrap}@media(max-width:900px){.po-panel{inset:12px;grid-template-columns:1fr;overflow:auto}.po-sidebar,.po-trace{min-height:220px;border:0}.po-chat{min-height:520px}.po-chat header{align-items:flex-start;flex-wrap:wrap}.po-audience{width:100%;justify-content:space-between}.po-message{max-width:94%}}@media(prefers-reduced-motion:reduce){.po-ai-spinner,.po-typing-cursor{animation:none}}
|
package/dist/pageops-sdk.es.js
CHANGED
|
@@ -1,164 +1,170 @@
|
|
|
1
1
|
var x = Object.defineProperty;
|
|
2
|
-
var k = (a,
|
|
3
|
-
var o = (a,
|
|
4
|
-
class
|
|
5
|
-
constructor(
|
|
6
|
-
this.options =
|
|
7
|
-
}
|
|
8
|
-
async createContext(
|
|
9
|
-
var n,
|
|
2
|
+
var k = (a, e, t) => e in a ? x(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
|
|
3
|
+
var o = (a, e, t) => k(a, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
class P {
|
|
5
|
+
constructor(e) {
|
|
6
|
+
this.options = e;
|
|
7
|
+
}
|
|
8
|
+
async createContext(e = ((i) => (i = ((t) => ((s) => (s = (t = this.options).getPageContext) == null ? void 0 : s.call(t))())()) != null ? i : {})()) {
|
|
9
|
+
var n, l, r;
|
|
10
10
|
return this.request("/context/session", {
|
|
11
11
|
method: "POST",
|
|
12
12
|
body: JSON.stringify({
|
|
13
13
|
app_id: this.options.appId,
|
|
14
14
|
env: this.options.env,
|
|
15
|
-
route:
|
|
16
|
-
url: (n =
|
|
17
|
-
title: (
|
|
18
|
-
menu_path: (
|
|
19
|
-
tenant_id:
|
|
20
|
-
user_role:
|
|
21
|
-
build_version:
|
|
15
|
+
route: e.route,
|
|
16
|
+
url: (n = e.url) != null ? n : location.href,
|
|
17
|
+
title: (l = e.title) != null ? l : document.title,
|
|
18
|
+
menu_path: (r = e.menuPath) != null ? r : [],
|
|
19
|
+
tenant_id: e.tenantId,
|
|
20
|
+
user_role: e.userRole,
|
|
21
|
+
build_version: e.buildVersion
|
|
22
22
|
})
|
|
23
23
|
});
|
|
24
24
|
}
|
|
25
25
|
async listConversations() {
|
|
26
26
|
return (await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations;
|
|
27
27
|
}
|
|
28
|
-
async createConversation(
|
|
28
|
+
async createConversation(e, t) {
|
|
29
29
|
return this.request("/conversations", {
|
|
30
30
|
method: "POST",
|
|
31
|
-
body: JSON.stringify({ app_id: this.options.appId, context_session_id:
|
|
31
|
+
body: JSON.stringify({ app_id: this.options.appId, context_session_id: e, title: t })
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
|
-
async deleteConversation(
|
|
35
|
-
return this.request(`/conversations/${encodeURIComponent(
|
|
34
|
+
async deleteConversation(e) {
|
|
35
|
+
return this.request(`/conversations/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`, {
|
|
36
36
|
method: "DELETE"
|
|
37
37
|
});
|
|
38
38
|
}
|
|
39
|
-
async listMessages(
|
|
40
|
-
return (await this.request(`/conversations/${encodeURIComponent(
|
|
39
|
+
async listMessages(e) {
|
|
40
|
+
return (await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages;
|
|
41
41
|
}
|
|
42
42
|
async listSources() {
|
|
43
43
|
return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
|
|
44
44
|
}
|
|
45
|
-
uploadSource(
|
|
46
|
-
const
|
|
47
|
-
return
|
|
45
|
+
uploadSource(e) {
|
|
46
|
+
const t = new FormData();
|
|
47
|
+
return t.append("file", e), this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: t, headers: {} });
|
|
48
48
|
}
|
|
49
|
-
streamQuestion(
|
|
49
|
+
streamQuestion(e, t, s) {
|
|
50
50
|
return fetch(`${this.base()}/question/stream`, {
|
|
51
51
|
method: "POST",
|
|
52
52
|
headers: { "content-type": "application/json" },
|
|
53
|
-
body: JSON.stringify({ app_id: this.options.appId, thread_id:
|
|
53
|
+
body: JSON.stringify({ app_id: this.options.appId, thread_id: e, question: t }),
|
|
54
54
|
signal: s
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
|
-
async request(
|
|
58
|
-
var
|
|
59
|
-
const s = (
|
|
57
|
+
async request(e, t) {
|
|
58
|
+
var l, r;
|
|
59
|
+
const s = (t == null ? void 0 : t.body) instanceof FormData ? t.headers : { "content-type": "application/json", ...(l = t == null ? void 0 : t.headers) != null ? l : {} }, i = await fetch(`${this.base()}${e}`, { ...t, headers: s });
|
|
60
60
|
if (i.status === 204) return;
|
|
61
61
|
const n = await i.json();
|
|
62
|
-
if (!i.ok) throw new Error((
|
|
62
|
+
if (!i.ok) throw new Error((r = n.message) != null ? r : "PageOps 请求失败");
|
|
63
63
|
return n;
|
|
64
64
|
}
|
|
65
65
|
base() {
|
|
66
|
-
const
|
|
67
|
-
return
|
|
66
|
+
const e = this.options.apiBase.replace(/\/$/, "");
|
|
67
|
+
return e.endsWith("/api") ? e : `${e}/api`;
|
|
68
68
|
}
|
|
69
69
|
}
|
|
70
|
-
async function
|
|
71
|
-
const
|
|
72
|
-
return typeof (
|
|
70
|
+
async function R(a, e) {
|
|
71
|
+
const t = await a.json().catch(() => null);
|
|
72
|
+
return typeof (t == null ? void 0 : t.message) == "string" && t.message.trim() ? t.message : e;
|
|
73
73
|
}
|
|
74
|
-
function
|
|
74
|
+
function I(a) {
|
|
75
75
|
return a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
76
76
|
}
|
|
77
77
|
function v(a) {
|
|
78
|
-
return
|
|
78
|
+
return I(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
79
79
|
}
|
|
80
|
-
function
|
|
81
|
-
const
|
|
82
|
-
if (!(
|
|
80
|
+
function U(a, e) {
|
|
81
|
+
const t = a[e], s = a[e + 1];
|
|
82
|
+
if (!(t != null && t.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
|
|
83
83
|
const i = [];
|
|
84
|
-
let n =
|
|
84
|
+
let n = e;
|
|
85
85
|
for (; n < a.length && a[n].includes("|") && a[n].trim(); )
|
|
86
86
|
i.push(a[n]), n += 1;
|
|
87
|
-
const
|
|
88
|
-
return { html: `<table><thead><tr>${
|
|
87
|
+
const l = (p) => p.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((f) => v(f.trim())), r = l(i[0]).map((p) => `<th>${p}</th>`).join(""), d = i.slice(2).map((p) => `<tr>${l(p).map((f) => `<td>${f}</td>`).join("")}</tr>`).join("");
|
|
88
|
+
return { html: `<table><thead><tr>${r}</tr></thead><tbody>${d}</tbody></table>`, next: n };
|
|
89
89
|
}
|
|
90
90
|
function w(a) {
|
|
91
|
-
const
|
|
92
|
-
`),
|
|
93
|
-
for (let s = 0; s <
|
|
94
|
-
const i =
|
|
91
|
+
const e = a.split(`
|
|
92
|
+
`), t = [];
|
|
93
|
+
for (let s = 0; s < e.length; s += 1) {
|
|
94
|
+
const i = e[s];
|
|
95
95
|
if (i.trim().startsWith("```")) {
|
|
96
|
-
const
|
|
97
|
-
for (s += 1; s <
|
|
98
|
-
|
|
99
|
-
|
|
96
|
+
const l = [];
|
|
97
|
+
for (s += 1; s < e.length && !e[s].trim().startsWith("```"); )
|
|
98
|
+
l.push(e[s]), s += 1;
|
|
99
|
+
t.push(`<pre><code>${I(l.join(`
|
|
100
100
|
`))}</code></pre>`);
|
|
101
101
|
continue;
|
|
102
102
|
}
|
|
103
|
-
const n =
|
|
103
|
+
const n = U(e, s);
|
|
104
104
|
if (n) {
|
|
105
|
-
|
|
105
|
+
t.push(n.html), s = n.next - 1;
|
|
106
106
|
continue;
|
|
107
107
|
}
|
|
108
|
-
i.startsWith("### ") ?
|
|
108
|
+
i.startsWith("### ") ? t.push(`<h4>${v(i.slice(4))}</h4>`) : i.startsWith("## ") ? t.push(`<h3>${v(i.slice(3))}</h3>`) : i.startsWith("# ") ? t.push(`<h2>${v(i.slice(2))}</h2>`) : i.startsWith("- ") ? t.push(`<li>${v(i.slice(2))}</li>`) : i.trim() ? t.push(`<p>${v(i)}</p>`) : t.push("<br>");
|
|
109
109
|
}
|
|
110
|
-
return
|
|
110
|
+
return t.join("");
|
|
111
111
|
}
|
|
112
|
-
async function
|
|
112
|
+
async function q(a, e) {
|
|
113
113
|
var n;
|
|
114
|
-
const
|
|
114
|
+
const t = a.getReader(), s = new TextDecoder();
|
|
115
115
|
let i = "";
|
|
116
116
|
for (; ; ) {
|
|
117
|
-
const { done:
|
|
118
|
-
if (
|
|
117
|
+
const { done: l, value: r } = await t.read();
|
|
118
|
+
if (l) {
|
|
119
119
|
i += s.decode();
|
|
120
120
|
break;
|
|
121
121
|
}
|
|
122
|
-
i += s.decode(
|
|
123
|
-
const
|
|
124
|
-
i = (n =
|
|
125
|
-
for (const
|
|
122
|
+
i += s.decode(r, { stream: !0 });
|
|
123
|
+
const d = i.split(/\r?\n\r?\n/);
|
|
124
|
+
i = (n = d.pop()) != null ? n : "";
|
|
125
|
+
for (const p of d) T(p, e);
|
|
126
126
|
}
|
|
127
|
-
i.trim() &&
|
|
127
|
+
i.trim() && T(i, e);
|
|
128
128
|
}
|
|
129
|
-
function
|
|
129
|
+
function T(a, e) {
|
|
130
130
|
var i, n;
|
|
131
|
-
const
|
|
132
|
-
|
|
131
|
+
const t = (i = a.match(/^event:\s*(.+)$/m)) == null ? void 0 : i[1], s = (n = a.match(/^data:\s*(.+)$/m)) == null ? void 0 : n[1];
|
|
132
|
+
t && s && e(t, JSON.parse(s));
|
|
133
133
|
}
|
|
134
|
-
class
|
|
135
|
-
constructor(
|
|
134
|
+
class K {
|
|
135
|
+
constructor(e, t = 16) {
|
|
136
136
|
o(this, "queue", []);
|
|
137
137
|
o(this, "timer", null);
|
|
138
138
|
o(this, "drainWaiters", []);
|
|
139
|
-
this.onChunk =
|
|
139
|
+
this.onChunk = e, this.interval = t;
|
|
140
140
|
}
|
|
141
|
-
enqueue(
|
|
142
|
-
this.queue.push(...Array.from(
|
|
141
|
+
enqueue(e) {
|
|
142
|
+
this.queue.push(...Array.from(e)), this.timer || this.tick();
|
|
143
143
|
}
|
|
144
144
|
async drain() {
|
|
145
|
-
!this.timer && !this.queue.length || await new Promise((
|
|
145
|
+
!this.timer && !this.queue.length || await new Promise((e) => this.drainWaiters.push(e));
|
|
146
146
|
}
|
|
147
147
|
clear() {
|
|
148
148
|
this.timer && clearTimeout(this.timer), this.timer = null, this.queue = [], this.resolveDrainWaiters();
|
|
149
149
|
}
|
|
150
150
|
tick() {
|
|
151
|
-
const
|
|
152
|
-
if (
|
|
151
|
+
const e = Math.max(1, Math.ceil(this.queue.length / 90)), t = this.queue.splice(0, e).join("");
|
|
152
|
+
if (t && this.onChunk(t), !this.queue.length) {
|
|
153
153
|
this.timer = null, this.resolveDrainWaiters();
|
|
154
154
|
return;
|
|
155
155
|
}
|
|
156
156
|
this.timer = setTimeout(() => this.tick(), this.interval);
|
|
157
157
|
}
|
|
158
158
|
resolveDrainWaiters() {
|
|
159
|
-
for (const
|
|
159
|
+
for (const e of this.drainWaiters.splice(0)) e();
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
|
+
const y = [
|
|
163
|
+
{ value: "product", label: "产品" },
|
|
164
|
+
{ value: "business", label: "业务" },
|
|
165
|
+
{ value: "developer", label: "研发" },
|
|
166
|
+
{ value: "tester", label: "测试" }
|
|
167
|
+
];
|
|
162
168
|
class F {
|
|
163
169
|
constructor() {
|
|
164
170
|
o(this, "client", null);
|
|
@@ -189,17 +195,19 @@ class F {
|
|
|
189
195
|
o(this, "deletingThreadId", "");
|
|
190
196
|
o(this, "streamFailure", "");
|
|
191
197
|
o(this, "streamDone", null);
|
|
192
|
-
o(this, "
|
|
193
|
-
|
|
198
|
+
o(this, "answerAudience", "business");
|
|
199
|
+
o(this, "audienceChanging", !1);
|
|
200
|
+
o(this, "typewriter", new K((e) => {
|
|
201
|
+
this.streaming += e, this.updateStreamingMessage();
|
|
194
202
|
}));
|
|
195
203
|
}
|
|
196
|
-
mount(
|
|
197
|
-
var
|
|
198
|
-
this.unmount(), this.options =
|
|
204
|
+
mount(e) {
|
|
205
|
+
var t;
|
|
206
|
+
this.unmount(), this.options = e, this.client = new P(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();
|
|
199
207
|
}
|
|
200
208
|
unmount() {
|
|
201
|
-
var
|
|
202
|
-
this.stopSourceRefresh(), this.cancelActiveAnswer(!1), this.resetAnswerState(), (
|
|
209
|
+
var e;
|
|
210
|
+
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.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceUploading = !1, this.answerAudience = "business", this.audienceChanging = !1;
|
|
203
211
|
}
|
|
204
212
|
open() {
|
|
205
213
|
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());
|
|
@@ -207,37 +215,76 @@ class F {
|
|
|
207
215
|
close() {
|
|
208
216
|
this.stopSourceRefresh(), this.cancelActiveAnswer(!1), this.renderClosed();
|
|
209
217
|
}
|
|
210
|
-
updateContext(
|
|
211
|
-
|
|
218
|
+
updateContext(e) {
|
|
219
|
+
if (!this.options) return;
|
|
220
|
+
const t = this.options.appId;
|
|
221
|
+
this.options = { ...this.options, ...e }, this.client = new P(this.options), this.options.appId !== t && (this.answerAudience = this.loadAnswerAudience(this.options.appId), this.currentThread = null, this.selectedPageKey = "", this.messages = [], this.steps = []), this.context = null, this.contextKey = "", this.renderPanel();
|
|
212
222
|
}
|
|
213
223
|
renderClosed() {
|
|
214
|
-
var
|
|
215
|
-
this.root && (this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', (
|
|
224
|
+
var e;
|
|
225
|
+
this.root && (this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', (e = this.root.querySelector("button")) == null || e.addEventListener("click", () => this.open()));
|
|
216
226
|
}
|
|
217
227
|
async ensureContext() {
|
|
218
228
|
if (!this.client || !this.options) throw new Error("PageOps SDK 未初始化");
|
|
219
|
-
const
|
|
220
|
-
return this.context && this.contextKey ===
|
|
229
|
+
const e = this.getPageContext(), t = this.getPageContextKey(e);
|
|
230
|
+
return this.context && this.contextKey === t ? this.context : (this.context = await this.client.createContext(e), this.contextKey = t, this.context);
|
|
221
231
|
}
|
|
222
232
|
getPageContext() {
|
|
223
|
-
var
|
|
224
|
-
return
|
|
233
|
+
var e, t, s;
|
|
234
|
+
return {
|
|
235
|
+
...(s = (t = (e = this.options) == null ? void 0 : e.getPageContext) == null ? void 0 : t.call(e)) != null ? s : {},
|
|
236
|
+
userRole: this.answerAudience
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
answerAudienceStorageKey(e) {
|
|
240
|
+
return `pageops:answer-audience:${e}`;
|
|
241
|
+
}
|
|
242
|
+
loadAnswerAudience(e) {
|
|
243
|
+
try {
|
|
244
|
+
const t = localStorage.getItem(this.answerAudienceStorageKey(e));
|
|
245
|
+
return y.some((s) => s.value === t) ? t : "business";
|
|
246
|
+
} catch (t) {
|
|
247
|
+
return "business";
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
saveAnswerAudience() {
|
|
251
|
+
if (this.options)
|
|
252
|
+
try {
|
|
253
|
+
localStorage.setItem(this.answerAudienceStorageKey(this.options.appId), this.answerAudience);
|
|
254
|
+
} catch (e) {
|
|
255
|
+
}
|
|
225
256
|
}
|
|
226
|
-
|
|
227
|
-
var
|
|
257
|
+
async changeAnswerAudience(e) {
|
|
258
|
+
var s;
|
|
259
|
+
if (this.asking || this.audienceChanging) return;
|
|
260
|
+
const t = (s = y.find((i) => i.value === e)) == null ? void 0 : s.value;
|
|
261
|
+
if (!(!t || t === this.answerAudience)) {
|
|
262
|
+
this.answerAudience = t, this.saveAnswerAudience(), this.audienceChanging = !0, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1, this.conversationError = "", this.renderPanel();
|
|
263
|
+
try {
|
|
264
|
+
await this.newConversation();
|
|
265
|
+
} catch (i) {
|
|
266
|
+
this.conversationError = i instanceof Error ? i.message : "切换回答角色失败,请稍后重试。";
|
|
267
|
+
} finally {
|
|
268
|
+
this.audienceChanging = !1, this.renderPanel();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
getPageContextKey(e) {
|
|
273
|
+
var t, s, i, n, l;
|
|
228
274
|
return JSON.stringify([
|
|
229
|
-
(
|
|
230
|
-
(s =
|
|
231
|
-
(i =
|
|
232
|
-
(n =
|
|
275
|
+
(t = e.route) != null ? t : "",
|
|
276
|
+
(s = e.url) != null ? s : location.href,
|
|
277
|
+
(i = e.title) != null ? i : document.title,
|
|
278
|
+
(n = e.menuPath) != null ? n : [],
|
|
279
|
+
(l = e.userRole) != null ? l : ""
|
|
233
280
|
]);
|
|
234
281
|
}
|
|
235
282
|
async loadSources() {
|
|
236
283
|
if (this.client) {
|
|
237
284
|
try {
|
|
238
285
|
this.sourceSnapshots = await this.client.listSources(), this.sourceUploadError = "";
|
|
239
|
-
} catch (
|
|
240
|
-
this.sourceUploadError =
|
|
286
|
+
} catch (e) {
|
|
287
|
+
this.sourceUploadError = e instanceof Error ? e.message : "源码包状态加载失败";
|
|
241
288
|
}
|
|
242
289
|
this.scheduleSourceRefresh(), this.renderPanel();
|
|
243
290
|
}
|
|
@@ -248,18 +295,18 @@ class F {
|
|
|
248
295
|
async newConversation() {
|
|
249
296
|
var s;
|
|
250
297
|
if (!this.client) return;
|
|
251
|
-
const
|
|
252
|
-
this.currentThread = await this.client.createConversation(
|
|
298
|
+
const e = await this.ensureContext(), t = (s = e.menu_path) != null && s.length ? e.menu_path.join(" / ") : e.route || document.title || "新的问答";
|
|
299
|
+
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();
|
|
253
300
|
}
|
|
254
|
-
async selectThread(
|
|
255
|
-
this.client && (this.currentThread =
|
|
301
|
+
async selectThread(e) {
|
|
302
|
+
this.client && (this.currentThread = e, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(e.id), this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1, this.renderPanel());
|
|
256
303
|
}
|
|
257
|
-
async deleteConversation(
|
|
258
|
-
var
|
|
259
|
-
if (!(!this.client || this.asking || this.deletingThreadId) && window.confirm(`确定删除会话“${
|
|
260
|
-
this.deletingThreadId =
|
|
304
|
+
async deleteConversation(e) {
|
|
305
|
+
var t;
|
|
306
|
+
if (!(!this.client || this.asking || this.deletingThreadId) && window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)) {
|
|
307
|
+
this.deletingThreadId = e.id, this.conversationError = "", this.renderPanel();
|
|
261
308
|
try {
|
|
262
|
-
if (await this.client.deleteConversation(
|
|
309
|
+
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) {
|
|
263
310
|
this.currentThread = null, this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1;
|
|
264
311
|
const s = this.conversations[0];
|
|
265
312
|
s && await this.selectThread(s);
|
|
@@ -271,23 +318,23 @@ class F {
|
|
|
271
318
|
}
|
|
272
319
|
}
|
|
273
320
|
}
|
|
274
|
-
async uploadSource(
|
|
321
|
+
async uploadSource(e) {
|
|
275
322
|
if (this.client) {
|
|
276
323
|
this.sourceUploading = !0, this.sourceUploadStatus = "上传中...", this.sourceUploadError = "", this.renderPanel();
|
|
277
324
|
try {
|
|
278
|
-
await this.client.uploadSource(
|
|
279
|
-
} catch (
|
|
280
|
-
this.sourceUploadError =
|
|
325
|
+
await this.client.uploadSource(e), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = this.isProjectMemoryUpdating() ? "源码上传完成,项目记忆更新中..." : "上传完成", this.scheduleSourceRefresh();
|
|
326
|
+
} catch (t) {
|
|
327
|
+
this.sourceUploadError = t instanceof Error ? t.message : "源码包上传失败", this.sourceUploadStatus = "";
|
|
281
328
|
} finally {
|
|
282
329
|
this.sourceUploading = !1, this.renderPanel();
|
|
283
330
|
}
|
|
284
331
|
}
|
|
285
332
|
}
|
|
286
|
-
async ask(
|
|
333
|
+
async ask(e) {
|
|
287
334
|
if (!this.client || this.asking) return;
|
|
288
|
-
const
|
|
289
|
-
if (
|
|
290
|
-
this.sourceUploadError =
|
|
335
|
+
const t = this.questionUnavailableReason();
|
|
336
|
+
if (t) {
|
|
337
|
+
this.sourceUploadError = t, this.renderPanel();
|
|
291
338
|
return;
|
|
292
339
|
}
|
|
293
340
|
this.resetAnswerState();
|
|
@@ -296,11 +343,11 @@ class F {
|
|
|
296
343
|
try {
|
|
297
344
|
const n = this.getPageContextKey(this.getPageContext());
|
|
298
345
|
if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== n && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
|
|
299
|
-
this.messages.push({ id: `local-${Date.now()}`, role: "user", content:
|
|
300
|
-
const
|
|
301
|
-
if (!
|
|
302
|
-
if (!
|
|
303
|
-
if (await
|
|
346
|
+
this.messages.push({ id: `local-${Date.now()}`, role: "user", content: e, metadata_json: {} }), this.steps = [], this.renderPanel();
|
|
347
|
+
const l = await this.client.streamQuestion(this.currentThread.id, e, i.signal);
|
|
348
|
+
if (!l.ok) throw new Error(await R(l, "服务暂时无法回答,请稍后重试。"));
|
|
349
|
+
if (!l.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
|
|
350
|
+
if (await q(l.body, (r, d) => this.handleStreamEvent(r, d)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
304
351
|
if (this.streamFailure) throw new Error(this.streamFailure);
|
|
305
352
|
if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
|
|
306
353
|
if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
@@ -313,53 +360,53 @@ class F {
|
|
|
313
360
|
this.asking = !1, this.waitingForFirstContent = !1, this.abortController === i && (this.abortController = null), this.renderPanel(!0);
|
|
314
361
|
}
|
|
315
362
|
}
|
|
316
|
-
cancelActiveAnswer(
|
|
317
|
-
var
|
|
363
|
+
cancelActiveAnswer(e) {
|
|
364
|
+
var t;
|
|
318
365
|
if (!(!this.asking && !this.abortController)) {
|
|
319
|
-
if (
|
|
366
|
+
if (e) {
|
|
320
367
|
this.stoppedRunId = this.activeRunId, this.answerStopped = !0;
|
|
321
368
|
const s = this.steps.map((i) => i.status === "running" ? { ...i, status: "cancelled" } : i);
|
|
322
369
|
this.steps = s.some((i) => i.status === "cancelled") ? s : [...s, { id: "stopped", title: "已停止", status: "cancelled" }];
|
|
323
370
|
} else
|
|
324
371
|
this.activeRunId += 1, this.asking = !1;
|
|
325
|
-
this.typewriter.clear(), this.waitingForFirstContent = !1, (
|
|
372
|
+
this.typewriter.clear(), this.waitingForFirstContent = !1, (t = this.abortController) == null || t.abort(), this.abortController = null, e && this.renderPanel();
|
|
326
373
|
}
|
|
327
374
|
}
|
|
328
|
-
handleStreamEvent(
|
|
375
|
+
handleStreamEvent(e, t) {
|
|
329
376
|
var s, i;
|
|
330
|
-
if (
|
|
331
|
-
this.upsertStep(
|
|
377
|
+
if (e === "step") {
|
|
378
|
+
this.upsertStep(t), this.renderPanel();
|
|
332
379
|
return;
|
|
333
380
|
}
|
|
334
|
-
if (
|
|
335
|
-
const n = String((s =
|
|
381
|
+
if (e === "delta") {
|
|
382
|
+
const n = String((s = t.content) != null ? s : "");
|
|
336
383
|
if (!n) return;
|
|
337
384
|
this.waitingForFirstContent = !1, this.typewriter.enqueue(n);
|
|
338
385
|
return;
|
|
339
386
|
}
|
|
340
|
-
|
|
387
|
+
e === "done" && (this.streamDone = t), e === "error" && (this.streamFailure = String((i = t.message) != null ? i : "服务异常,请稍后重试。"));
|
|
341
388
|
}
|
|
342
389
|
updateStreamingMessage() {
|
|
343
390
|
var s, i;
|
|
344
|
-
const
|
|
345
|
-
if (!
|
|
391
|
+
const e = (s = this.panel) == null ? void 0 : s.querySelector("[data-streaming-content]");
|
|
392
|
+
if (!e) {
|
|
346
393
|
this.renderPanel();
|
|
347
394
|
return;
|
|
348
395
|
}
|
|
349
|
-
|
|
350
|
-
const
|
|
351
|
-
|
|
396
|
+
e.innerHTML = w(this.streaming);
|
|
397
|
+
const t = (i = this.panel) == null ? void 0 : i.querySelector(".po-messages");
|
|
398
|
+
t && (t.scrollTop = t.scrollHeight);
|
|
352
399
|
}
|
|
353
400
|
resetAnswerState() {
|
|
354
401
|
this.typewriter.clear(), this.asking = !1, this.waitingForFirstContent = !1, this.answerError = "", this.answerStopped = !1, this.streamFailure = "", this.streamDone = null, this.streaming = "";
|
|
355
402
|
}
|
|
356
|
-
upsertStep(
|
|
357
|
-
const
|
|
358
|
-
this.steps =
|
|
403
|
+
upsertStep(e) {
|
|
404
|
+
const t = this.steps.findIndex((s) => s.id === e.id);
|
|
405
|
+
this.steps = t === -1 ? [...this.steps, e] : this.steps.map((s) => s.id === e.id ? { ...s, ...e } : s);
|
|
359
406
|
}
|
|
360
407
|
latestAnalysisStatus() {
|
|
361
|
-
var
|
|
362
|
-
return String((s = (
|
|
408
|
+
var e, t, s;
|
|
409
|
+
return String((s = (t = (e = this.sourceSnapshots[0]) == null ? void 0 : e.metadata) == null ? void 0 : t.analysis_status) != null ? s : "");
|
|
363
410
|
}
|
|
364
411
|
isProjectMemoryUpdating() {
|
|
365
412
|
return ["pending", "running"].includes(this.latestAnalysisStatus());
|
|
@@ -373,43 +420,45 @@ class F {
|
|
|
373
420
|
stopSourceRefresh() {
|
|
374
421
|
this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
|
|
375
422
|
}
|
|
376
|
-
renderPanel(
|
|
423
|
+
renderPanel(e = this.asking) {
|
|
377
424
|
if (!this.panel) return;
|
|
378
|
-
const
|
|
425
|
+
const t = this.questionUnavailableReason(), s = t || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), i = !!(t || this.asking), n = t ? '<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>', l = y.map((r) => `
|
|
426
|
+
<button type="button" data-audience="${r.value}" aria-pressed="${r.value === this.answerAudience}" ${this.asking || this.audienceChanging ? "disabled" : ""}>${r.label}</button>
|
|
427
|
+
`).join("");
|
|
379
428
|
if (this.panel.innerHTML = `
|
|
380
429
|
<aside class="po-sidebar">
|
|
381
430
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
382
431
|
<button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
|
|
383
432
|
<input class="po-search" placeholder="搜索问答" />
|
|
384
|
-
${this.conversationError ? `<p class="po-conversation-error" role="alert">${
|
|
433
|
+
${this.conversationError ? `<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>` : ""}
|
|
385
434
|
<div class="po-thread-list">${this.conversations.map((r) => {
|
|
386
|
-
var
|
|
435
|
+
var d;
|
|
387
436
|
return `
|
|
388
|
-
<div class="po-thread-row ${r.id === ((
|
|
389
|
-
<button class="po-thread" data-thread="${
|
|
390
|
-
<strong>${
|
|
437
|
+
<div class="po-thread-row ${r.id === ((d = this.currentThread) == null ? void 0 : d.id) ? "active" : ""}">
|
|
438
|
+
<button class="po-thread" data-thread="${c(r.id)}" ${this.asking ? "disabled" : ""}>
|
|
439
|
+
<strong>${c(r.title)}</strong><span>${A(r.created_at)}</span>
|
|
391
440
|
</button>
|
|
392
|
-
<button class="po-thread-delete" type="button" data-delete-thread="${
|
|
441
|
+
<button class="po-thread-delete" type="button" data-delete-thread="${c(r.id)}" aria-label="删除会话:${c(r.title)}" title="删除会话" ${this.asking || this.deletingThreadId === r.id ? "disabled" : ""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
393
442
|
</div>`;
|
|
394
443
|
}).join("")}</div>
|
|
395
444
|
</aside>
|
|
396
445
|
<main class="po-chat">
|
|
397
|
-
<header><div><p>问数回答</p><h2>${this.currentThread ?
|
|
446
|
+
<header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread ? c(this.currentThread.title) : "未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${l}</div></div></header>
|
|
398
447
|
<section class="po-messages">
|
|
399
|
-
${this.messages.map((r) => `<article class="po-message ${r.role}"><b>${r.role === "user" ? "你" : "PageOps 分析"}</b><div>${r.role === "assistant" ? w(r.content) :
|
|
448
|
+
${this.messages.map((r) => `<article class="po-message ${r.role}"><b>${r.role === "user" ? "你" : "PageOps 分析"}</b><div>${r.role === "assistant" ? w(r.content) : c(r.content)}</div></article>`).join("")}
|
|
400
449
|
${this.renderAnswerState()}
|
|
401
450
|
</section>
|
|
402
|
-
<form class="po-composer"><textarea ${i ? "disabled" : ""} placeholder="${
|
|
451
|
+
<form class="po-composer"><textarea ${i ? "disabled" : ""} placeholder="${c(s)}"></textarea>${n}</form>
|
|
403
452
|
</main>
|
|
404
453
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
405
|
-
`, this.bindPanelEvents(),
|
|
454
|
+
`, this.bindPanelEvents(), e) {
|
|
406
455
|
const r = this.panel.querySelector(".po-messages");
|
|
407
456
|
r && (r.scrollTop = r.scrollHeight);
|
|
408
457
|
}
|
|
409
458
|
}
|
|
410
459
|
renderAnswerState() {
|
|
411
|
-
const
|
|
412
|
-
return `${
|
|
460
|
+
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>${w(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>${c(this.answerError)}</div></article>` : "", i = this.answerStopped ? '<div class="po-stream-stopped" role="status">已停止输出</div>' : "";
|
|
461
|
+
return `${e}${t}${i}${s}`;
|
|
413
462
|
}
|
|
414
463
|
renderSourceUploader() {
|
|
415
464
|
return `
|
|
@@ -420,70 +469,75 @@ class F {
|
|
|
420
469
|
<span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
|
|
421
470
|
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
|
|
422
471
|
</label>
|
|
423
|
-
${this.sourceUploadStatus ? `<p class="po-upload-status">${
|
|
424
|
-
${this.sourceSnapshots.length ? `<div class="po-source-list">${this.sourceSnapshots.map((
|
|
425
|
-
${this.sourceUploadError ? `<p class="po-upload-error">${
|
|
472
|
+
${this.sourceUploadStatus ? `<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>` : ""}
|
|
473
|
+
${this.sourceSnapshots.length ? `<div class="po-source-list">${this.sourceSnapshots.map((e) => this.renderSourceItem(e)).join("")}</div>` : '<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
|
|
474
|
+
${this.sourceUploadError ? `<p class="po-upload-error">${c(this.sourceUploadError)}</p>` : ""}
|
|
426
475
|
</div>
|
|
427
476
|
`;
|
|
428
477
|
}
|
|
429
|
-
renderSourceItem(
|
|
430
|
-
var
|
|
431
|
-
const
|
|
432
|
-
return `<article class="po-source-item"><strong>${
|
|
478
|
+
renderSourceItem(e) {
|
|
479
|
+
var r, d, p;
|
|
480
|
+
const t = e.filename || "未命名代码包", s = e.created_at ? A(e.created_at) : "刚刚上传", i = _(e.archive_bytes || e.total_bytes || 0), n = String((d = (r = e.metadata) == null ? void 0 : r.analysis_status) != null ? d : "unknown"), l = (p = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? p : "项目记忆状态未知";
|
|
481
|
+
return `<article class="po-source-item"><strong>${c(t)}</strong><span>${c(s)} · ${c(i)}</span><span>${c(l)}</span></article>`;
|
|
433
482
|
}
|
|
434
483
|
renderSteps() {
|
|
435
|
-
return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((
|
|
484
|
+
return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((t) => {
|
|
436
485
|
var s;
|
|
437
|
-
return `<details class="po-step ${
|
|
486
|
+
return `<details class="po-step ${t.status}" ${t.status === "running" || t.status === "failed" ? "open" : ""}><summary><strong>${c(t.title)}</strong><span>${O(t.status)}</span></summary><pre>${c(JSON.stringify((s = t.details) != null ? s : {}, null, 2))}</pre></details>`;
|
|
438
487
|
}).join("");
|
|
439
488
|
}
|
|
440
489
|
bindPanelEvents() {
|
|
441
|
-
var
|
|
442
|
-
(
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
}), (d = this.panel) == null || d.querySelectorAll("[data-thread]").forEach((g) => {
|
|
447
|
-
g.addEventListener("click", () => {
|
|
448
|
-
const c = this.conversations.find((u) => u.id === g.dataset.thread);
|
|
449
|
-
c && this.selectThread(c);
|
|
490
|
+
var e, t, s, i, n, l, r, d, p, f, b, S, $, E, C;
|
|
491
|
+
(t = (e = this.panel) == null ? void 0 : e.querySelector('[data-action="new"]')) == null || t.addEventListener("click", () => void this.newConversation()), (i = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || i.addEventListener("click", () => this.close()), (l = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="stop-answer"]')) == null || l.addEventListener("click", () => this.cancelActiveAnswer(!0)), (r = this.panel) == null || r.querySelectorAll("[data-audience]").forEach((u) => {
|
|
492
|
+
u.addEventListener("click", () => {
|
|
493
|
+
var h;
|
|
494
|
+
return void this.changeAnswerAudience((h = u.dataset.audience) != null ? h : "");
|
|
450
495
|
});
|
|
451
|
-
}), (
|
|
452
|
-
g
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
496
|
+
}), (p = (d = this.panel) == null ? void 0 : d.querySelector('[data-action="upload-source"]')) == null || p.addEventListener("change", (u) => {
|
|
497
|
+
var g;
|
|
498
|
+
const h = (g = u.target.files) == null ? void 0 : g[0];
|
|
499
|
+
h && this.uploadSource(h);
|
|
500
|
+
}), (f = this.panel) == null || f.querySelectorAll("[data-thread]").forEach((u) => {
|
|
501
|
+
u.addEventListener("click", () => {
|
|
502
|
+
const h = this.conversations.find((g) => g.id === u.dataset.thread);
|
|
503
|
+
h && this.selectThread(h);
|
|
456
504
|
});
|
|
457
|
-
}), (
|
|
505
|
+
}), (b = this.panel) == null || b.querySelectorAll("[data-delete-thread]").forEach((u) => {
|
|
506
|
+
u.addEventListener("click", (h) => {
|
|
507
|
+
h.stopPropagation();
|
|
508
|
+
const g = this.conversations.find((m) => m.id === u.dataset.deleteThread);
|
|
509
|
+
g && this.deleteConversation(g);
|
|
510
|
+
});
|
|
511
|
+
}), ($ = (S = this.panel) == null ? void 0 : S.querySelector("form")) == null || $.addEventListener("submit", (u) => {
|
|
458
512
|
var m;
|
|
459
|
-
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
}), (
|
|
463
|
-
var
|
|
464
|
-
const
|
|
465
|
-
|
|
513
|
+
u.preventDefault();
|
|
514
|
+
const h = (m = this.panel) == null ? void 0 : m.querySelector("textarea"), g = h == null ? void 0 : h.value.trim();
|
|
515
|
+
g && (h.value = "", this.ask(g));
|
|
516
|
+
}), (C = (E = this.panel) == null ? void 0 : E.querySelector("textarea")) == null || C.addEventListener("keydown", (u) => {
|
|
517
|
+
var g, m;
|
|
518
|
+
const h = u;
|
|
519
|
+
h.key === "Enter" && !h.shiftKey && (h.preventDefault(), (m = (g = this.panel) == null ? void 0 : g.querySelector("form")) == null || m.requestSubmit());
|
|
466
520
|
});
|
|
467
521
|
}
|
|
468
522
|
}
|
|
469
|
-
function
|
|
523
|
+
function c(a) {
|
|
470
524
|
return a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
471
525
|
}
|
|
472
|
-
function
|
|
526
|
+
function A(a) {
|
|
473
527
|
return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(a));
|
|
474
528
|
}
|
|
475
529
|
function _(a) {
|
|
476
530
|
if (!a) return "0 B";
|
|
477
|
-
const
|
|
478
|
-
let
|
|
479
|
-
for (;
|
|
480
|
-
|
|
481
|
-
return `${
|
|
531
|
+
const e = ["B", "KB", "MB", "GB"];
|
|
532
|
+
let t = a, s = 0;
|
|
533
|
+
for (; t >= 1024 && s < e.length - 1; )
|
|
534
|
+
t /= 1024, s += 1;
|
|
535
|
+
return `${t >= 10 || s === 0 ? t.toFixed(0) : t.toFixed(1)} ${e[s]}`;
|
|
482
536
|
}
|
|
483
|
-
function
|
|
537
|
+
function O(a) {
|
|
484
538
|
return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[a];
|
|
485
539
|
}
|
|
486
|
-
const
|
|
540
|
+
const D = new F();
|
|
487
541
|
export {
|
|
488
|
-
|
|
542
|
+
D as PageOpsSDK
|
|
489
543
|
};
|
package/dist/pageops-sdk.umd.cjs
CHANGED
|
@@ -1,29 +1,31 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`),
|
|
3
|
-
`))}</code></pre>`);continue}const n=I(t,s);if(n){e.push(n.html),s=n.next-1;continue}i.startsWith("### ")?e.push(`<h4>${y(i.slice(4))}</h4>`):i.startsWith("## ")?e.push(`<h3>${y(i.slice(3))}</h3>`):i.startsWith("# ")?e.push(`<h2>${y(i.slice(2))}</h2>`):i.startsWith("- ")?e.push(`<li>${y(i.slice(2))}</li>`):i.trim()?e.push(`<p>${y(i)}</p>`):e.push("<br>")}return e.join("")}async function R(o,t){var n;const e=o.getReader(),s=new TextDecoder;let i="";for(;;){const{done:r,value:l}=await e.read();if(r){i+=s.decode();break}i+=s.decode(l,{stream:!0});const f=i.split(/\r?\n\r?\n/);i=(n=f.pop())!=null?n:"";for(const u of f)E(u,t)}i.trim()&&E(i,t)}function E(o,t){var i,n;const e=(i=o.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(n=o.match(/^data:\s*(.+)$/m))==null?void 0:n[1];e&&s&&t(e,JSON.parse(s))}class U{constructor(t,e=16){a(this,"queue",[]);a(this,"timer",null);a(this,"drainWaiters",[]);this.onChunk=t,this.interval=e}enqueue(t){this.queue.push(...Array.from(t)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(t=>this.drainWaiters.push(t))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const t=Math.max(1,Math.ceil(this.queue.length/90)),e=this.queue.splice(0,t).join("");if(e&&this.onChunk(e),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const t of this.drainWaiters.splice(0))t()}}class q{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);a(this,"contextKey","");a(this,"selectedPageKey","");a(this,"currentThread",null);a(this,"conversations",[]);a(this,"messages",[]);a(this,"steps",[]);a(this,"sourceSnapshots",[]);a(this,"sourceUploadStatus","");a(this,"sourceUploadError","");a(this,"sourceUploading",!1);a(this,"sourceRefreshTimer",null);a(this,"streaming","");a(this,"asking",!1);a(this,"waitingForFirstContent",!1);a(this,"abortController",null);a(this,"activeRunId",0);a(this,"stoppedRunId",-1);a(this,"answerStopped",!1);a(this,"answerError","");a(this,"conversationError","");a(this,"deletingThreadId","");a(this,"streamFailure","");a(this,"streamDone",null);a(this,"typewriter",new U(t=>{this.streaming+=t,this.updateStreamingMessage()}))}mount(t){var e;this.unmount(),this.options=t,this.client=new d(t),this.root=document.createElement("div"),this.root.className="pageops-sdk",((e=t.container)!=null?e:document.body).appendChild(this.root),this.renderClosed()}unmount(){var t;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1}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(t){this.options&&(this.options={...this.options,...t},this.client=new d(this.options),this.context=null,this.contextKey="")}renderClosed(){var t;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(t=this.root.querySelector("button"))==null||t.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const t=this.getPageContext(),e=this.getPageContextKey(t);return this.context&&this.contextKey===e?this.context:(this.context=await this.client.createContext(t),this.contextKey=e,this.context)}getPageContext(){var t,e,s;return(s=(e=(t=this.options)==null?void 0:t.getPageContext)==null?void 0:e.call(t))!=null?s:{}}getPageContextKey(t){var e,s,i,n;return JSON.stringify([(e=t.route)!=null?e:"",(s=t.url)!=null?s:location.href,(i=t.title)!=null?i:document.title,(n=t.menuPath)!=null?n:[]])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包状态加载失败"}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 t=await this.ensureContext(),e=(s=t.menu_path)!=null&&s.length?t.menu_path.join(" / "):t.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(t.id,e),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(t){this.client&&(this.currentThread=t,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel())}async deleteConversation(t){var e;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${t.title}”吗?此操作无法撤销。`)){this.deletingThreadId=t.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(t.id),this.conversations=this.conversations.filter(s=>s.id!==t.id),((e=this.currentThread)==null?void 0:e.id)===t.id){this.currentThread=null,this.messages=[],this.steps=[],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(t){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(t),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(t){if(!this.client||this.asking)return;const e=this.questionUnavailableReason();if(e){this.sourceUploadError=e,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,i=new AbortController;this.abortController=i,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:t,metadata_json:{}}),this.steps=[],this.renderPanel();const r=await this.client.streamQuestion(this.currentThread.id,t,i.signal);if(!r.ok)throw new Error(await w(r,"服务暂时无法回答,请稍后重试。"));if(!r.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await R(r.body,(l,f)=>this.handleStreamEvent(l,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",details:{message:this.answerError}}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===i&&(this.abortController=null),this.renderPanel(!0)}}cancelActiveAnswer(t){var e;if(!(!this.asking&&!this.abortController)){if(t){this.stoppedRunId=this.activeRunId,this.answerStopped=!0;const s=this.steps.map(i=>i.status==="running"?{...i,status:"cancelled"}:i);this.steps=s.some(i=>i.status==="cancelled")?s:[...s,{id:"stopped",title:"已停止",status:"cancelled"}]}else this.activeRunId+=1,this.asking=!1;this.typewriter.clear(),this.waitingForFirstContent=!1,(e=this.abortController)==null||e.abort(),this.abortController=null,t&&this.renderPanel()}}handleStreamEvent(t,e){var s,i;if(t==="step"){this.upsertStep(e),this.renderPanel();return}if(t==="delta"){const n=String((s=e.content)!=null?s:"");if(!n)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(n);return}t==="done"&&(this.streamDone=e),t==="error"&&(this.streamFailure=String((i=e.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const t=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!t){this.renderPanel();return}t.innerHTML=b(this.streaming);const e=(i=this.panel)==null?void 0:i.querySelector(".po-messages");e&&(e.scrollTop=e.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(t){const e=this.steps.findIndex(s=>s.id===t.id);this.steps=e===-1?[...this.steps,t]:this.steps.map(s=>s.id===t.id?{...s,...t}:s)}latestAnalysisStatus(){var t,e,s;return String((s=(e=(t=this.sourceSnapshots[0])==null?void 0:t.metadata)==null?void 0:e.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),this.isProjectMemoryUpdating()&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(t=this.asking){if(!this.panel)return;const e=this.questionUnavailableReason(),s=e||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),i=!!(e||this.asking),n=e?'<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>';if(this.panel.innerHTML=`
|
|
1
|
+
(function(m,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(m=typeof globalThis!="undefined"?globalThis:m||self,u(m.PageOpsSDK={}))})(this,(function(m){"use strict";var _=Object.defineProperty;var D=(m,u,w)=>u in m?_(m,u,{enumerable:!0,configurable:!0,writable:!0,value:w}):m[u]=w;var a=(m,u,w)=>D(m,typeof u!="symbol"?u+"":u,w);class u{constructor(e){this.options=e}async createContext(e=(i=>(i=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?i:{})()){var n,l,r;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(n=e.url)!=null?n:location.href,title:(l=e.title)!=null?l:document.title,menu_path:(r=e.menuPath)!=null?r:[],tenant_id:e.tenantId,user_role:e.userRole,build_version:e.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(e,t){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:e,title:t})})}async deleteConversation(e){return this.request(`/conversations/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`,{method:"DELETE"})}async listMessages(e){return(await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(e){const t=new FormData;return t.append("file",e),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:t,headers:{}})}streamQuestion(e,t,s){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:e,question:t}),signal:s})}async request(e,t){var l,r;const s=(t==null?void 0:t.body)instanceof FormData?t.headers:{"content-type":"application/json",...(l=t==null?void 0:t.headers)!=null?l:{}},i=await fetch(`${this.base()}${e}`,{...t,headers:s});if(i.status===204)return;const n=await i.json();if(!i.ok)throw new Error((r=n.message)!=null?r:"PageOps 请求失败");return n}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")?e:`${e}/api`}}async function w(o,e){const t=await o.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function E(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function y(o){return E(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function R(o,e){const t=o[e],s=o[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const i=[];let n=e;for(;n<o.length&&o[n].includes("|")&&o[n].trim();)i.push(o[n]),n+=1;const l=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(b=>y(b.trim())),r=l(i[0]).map(g=>`<th>${g}</th>`).join(""),d=i.slice(2).map(g=>`<tr>${l(g).map(b=>`<td>${b}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${r}</tr></thead><tbody>${d}</tbody></table>`,next:n}}function S(o){const e=o.split(`
|
|
2
|
+
`),t=[];for(let s=0;s<e.length;s+=1){const i=e[s];if(i.trim().startsWith("```")){const l=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)l.push(e[s]),s+=1;t.push(`<pre><code>${E(l.join(`
|
|
3
|
+
`))}</code></pre>`);continue}const n=R(e,s);if(n){t.push(n.html),s=n.next-1;continue}i.startsWith("### ")?t.push(`<h4>${y(i.slice(4))}</h4>`):i.startsWith("## ")?t.push(`<h3>${y(i.slice(3))}</h3>`):i.startsWith("# ")?t.push(`<h2>${y(i.slice(2))}</h2>`):i.startsWith("- ")?t.push(`<li>${y(i.slice(2))}</li>`):i.trim()?t.push(`<p>${y(i)}</p>`):t.push("<br>")}return t.join("")}async function U(o,e){var n;const t=o.getReader(),s=new TextDecoder;let i="";for(;;){const{done:l,value:r}=await t.read();if(l){i+=s.decode();break}i+=s.decode(r,{stream:!0});const d=i.split(/\r?\n\r?\n/);i=(n=d.pop())!=null?n:"";for(const g of d)P(g,e)}i.trim()&&P(i,e)}function P(o,e){var i,n;const t=(i=o.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(n=o.match(/^data:\s*(.+)$/m))==null?void 0:n[1];t&&s&&e(t,JSON.parse(s))}class q{constructor(e,t=16){a(this,"queue",[]);a(this,"timer",null);a(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 $=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class K{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);a(this,"contextKey","");a(this,"selectedPageKey","");a(this,"currentThread",null);a(this,"conversations",[]);a(this,"messages",[]);a(this,"steps",[]);a(this,"sourceSnapshots",[]);a(this,"sourceUploadStatus","");a(this,"sourceUploadError","");a(this,"sourceUploading",!1);a(this,"sourceRefreshTimer",null);a(this,"streaming","");a(this,"asking",!1);a(this,"waitingForFirstContent",!1);a(this,"abortController",null);a(this,"activeRunId",0);a(this,"stoppedRunId",-1);a(this,"answerStopped",!1);a(this,"answerError","");a(this,"conversationError","");a(this,"deletingThreadId","");a(this,"streamFailure","");a(this,"streamDone",null);a(this,"answerAudience","business");a(this,"audienceChanging",!1);a(this,"typewriter",new q(e=>{this.streaming+=e,this.updateStreamingMessage()}))}mount(e){var t;this.unmount(),this.options=e,this.client=new u(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.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1,this.answerAudience="business",this.audienceChanging=!1}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 u(this.options),this.options.appId!==t&&(this.answerAudience=this.loadAnswerAudience(this.options.appId),this.currentThread=null,this.selectedPageKey="",this.messages=[],this.steps=[]),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}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return $.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){}}async changeAnswerAudience(e){var s;if(this.asking||this.audienceChanging)return;const t=(s=$.find(i=>i.value===e))==null?void 0:s.value;if(!(!t||t===this.answerAudience)){this.answerAudience=t,this.saveAnswerAudience(),this.audienceChanging=!0,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.conversationError="",this.renderPanel();try{await this.newConversation()}catch(i){this.conversationError=i instanceof Error?i.message:"切换回答角色失败,请稍后重试。"}finally{this.audienceChanging=!1,this.renderPanel()}}}getPageContextKey(e){var t,s,i,n,l;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(i=e.title)!=null?i:document.title,(n=e.menuPath)!=null?n:[],(l=e.userRole)!=null?l:""])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包状态加载失败"}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){this.client&&(this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel())}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.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){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,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,i=new AbortController;this.abortController=i,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.renderPanel();const l=await this.client.streamQuestion(this.currentThread.id,e,i.signal);if(!l.ok)throw new Error(await w(l,"服务暂时无法回答,请稍后重试。"));if(!l.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await U(l.body,(r,d)=>this.handleStreamEvent(r,d)),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",details:{message:this.answerError}}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===i&&(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(i=>i.status==="running"?{...i,status:"cancelled"}:i);this.steps=s.some(i=>i.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,i;if(e==="step"){this.upsertStep(t),this.renderPanel();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((i=t.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=S(this.streaming);const t=(i=this.panel)==null?void 0:i.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)}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.sourceSnapshots[0])==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),this.isProjectMemoryUpdating()&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(e=this.asking){if(!this.panel)return;const t=this.questionUnavailableReason(),s=t||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),i=!!(t||this.asking),n=t?'<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>',l=$.map(r=>`
|
|
4
|
+
<button type="button" data-audience="${r.value}" aria-pressed="${r.value===this.answerAudience}" ${this.asking||this.audienceChanging?"disabled":""}>${r.label}</button>
|
|
5
|
+
`).join("");if(this.panel.innerHTML=`
|
|
4
6
|
<aside class="po-sidebar">
|
|
5
7
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
6
8
|
<button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
|
|
7
9
|
<input class="po-search" placeholder="搜索问答" />
|
|
8
|
-
${this.conversationError?`<p class="po-conversation-error" role="alert">${
|
|
9
|
-
<div class="po-thread-list">${this.conversations.map(r=>{var
|
|
10
|
-
<div class="po-thread-row ${r.id===((
|
|
11
|
-
<button class="po-thread" data-thread="${
|
|
12
|
-
<strong>${
|
|
10
|
+
${this.conversationError?`<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>`:""}
|
|
11
|
+
<div class="po-thread-list">${this.conversations.map(r=>{var d;return`
|
|
12
|
+
<div class="po-thread-row ${r.id===((d=this.currentThread)==null?void 0:d.id)?"active":""}">
|
|
13
|
+
<button class="po-thread" data-thread="${c(r.id)}" ${this.asking?"disabled":""}>
|
|
14
|
+
<strong>${c(r.title)}</strong><span>${C(r.created_at)}</span>
|
|
13
15
|
</button>
|
|
14
|
-
<button class="po-thread-delete" type="button" data-delete-thread="${
|
|
16
|
+
<button class="po-thread-delete" type="button" data-delete-thread="${c(r.id)}" aria-label="删除会话:${c(r.title)}" title="删除会话" ${this.asking||this.deletingThreadId===r.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
15
17
|
</div>`}).join("")}</div>
|
|
16
18
|
</aside>
|
|
17
19
|
<main class="po-chat">
|
|
18
|
-
<header><div><p>问数回答</p><h2>${this.currentThread?
|
|
20
|
+
<header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread?c(this.currentThread.title):"未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${l}</div></div></header>
|
|
19
21
|
<section class="po-messages">
|
|
20
|
-
${this.messages.map(r=>`<article class="po-message ${r.role}"><b>${r.role==="user"?"你":"PageOps 分析"}</b><div>${r.role==="assistant"?
|
|
22
|
+
${this.messages.map(r=>`<article class="po-message ${r.role}"><b>${r.role==="user"?"你":"PageOps 分析"}</b><div>${r.role==="assistant"?S(r.content):c(r.content)}</div></article>`).join("")}
|
|
21
23
|
${this.renderAnswerState()}
|
|
22
24
|
</section>
|
|
23
|
-
<form class="po-composer"><textarea ${i?"disabled":""} placeholder="${
|
|
25
|
+
<form class="po-composer"><textarea ${i?"disabled":""} placeholder="${c(s)}"></textarea>${n}</form>
|
|
24
26
|
</main>
|
|
25
27
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
26
|
-
`,this.bindPanelEvents(),
|
|
28
|
+
`,this.bindPanelEvents(),e){const r=this.panel.querySelector(".po-messages");r&&(r.scrollTop=r.scrollHeight)}}renderAnswerState(){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>${S(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>${c(this.answerError)}</div></article>`:"",i=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${e}${t}${i}${s}`}renderSourceUploader(){return`
|
|
27
29
|
<div class="po-source-uploader">
|
|
28
30
|
<strong>源码包</strong>
|
|
29
31
|
<p>上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
|
|
@@ -31,8 +33,8 @@
|
|
|
31
33
|
<span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
|
|
32
34
|
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
|
|
33
35
|
</label>
|
|
34
|
-
${this.sourceUploadStatus?`<p class="po-upload-status">${
|
|
35
|
-
${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(
|
|
36
|
-
${this.sourceUploadError?`<p class="po-upload-error">${
|
|
36
|
+
${this.sourceUploadStatus?`<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>`:""}
|
|
37
|
+
${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(e=>this.renderSourceItem(e)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
|
|
38
|
+
${this.sourceUploadError?`<p class="po-upload-error">${c(this.sourceUploadError)}</p>`:""}
|
|
37
39
|
</div>
|
|
38
|
-
`}renderSourceItem(
|
|
40
|
+
`}renderSourceItem(e){var r,d,g;const t=e.filename||"未命名代码包",s=e.created_at?C(e.created_at):"刚刚上传",i=O(e.archive_bytes||e.total_bytes||0),n=String((d=(r=e.metadata)==null?void 0:r.analysis_status)!=null?d:"unknown"),l=(g={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?g:"项目记忆状态未知";return`<article class="po-source-item"><strong>${c(t)}</strong><span>${c(s)} · ${c(i)}</span><span>${c(l)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(t=>{var s;return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""}><summary><strong>${c(t.title)}</strong><span>${F(t.status)}</span></summary><pre>${c(JSON.stringify((s=t.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var e,t,s,i,n,l,r,d,g,b,T,A,I,x,k;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(i=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||i.addEventListener("click",()=>this.close()),(l=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||l.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(r=this.panel)==null||r.querySelectorAll("[data-audience]").forEach(p=>{p.addEventListener("click",()=>{var h;return void this.changeAnswerAudience((h=p.dataset.audience)!=null?h:"")})}),(g=(d=this.panel)==null?void 0:d.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",p=>{var f;const h=(f=p.target.files)==null?void 0:f[0];h&&this.uploadSource(h)}),(b=this.panel)==null||b.querySelectorAll("[data-thread]").forEach(p=>{p.addEventListener("click",()=>{const h=this.conversations.find(f=>f.id===p.dataset.thread);h&&this.selectThread(h)})}),(T=this.panel)==null||T.querySelectorAll("[data-delete-thread]").forEach(p=>{p.addEventListener("click",h=>{h.stopPropagation();const f=this.conversations.find(v=>v.id===p.dataset.deleteThread);f&&this.deleteConversation(f)})}),(I=(A=this.panel)==null?void 0:A.querySelector("form"))==null||I.addEventListener("submit",p=>{var v;p.preventDefault();const h=(v=this.panel)==null?void 0:v.querySelector("textarea"),f=h==null?void 0:h.value.trim();f&&(h.value="",this.ask(f))}),(k=(x=this.panel)==null?void 0:x.querySelector("textarea"))==null||k.addEventListener("keydown",p=>{var f,v;const h=p;h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),(v=(f=this.panel)==null?void 0:f.querySelector("form"))==null||v.requestSubmit())})}}function c(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function C(o){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(o))}function O(o){if(!o)return"0 B";const e=["B","KB","MB","GB"];let t=o,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;return`${t>=10||s===0?t.toFixed(0):t.toFixed(1)} ${e[s]}`}function F(o){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[o]}const j=new K;m.PageOpsSDK=j,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|