@pageops/sdk 0.1.14 → 0.1.15
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/client.d.ts +3 -3
- package/dist/index.d.ts +0 -1
- package/dist/pageops-sdk.css +1 -1
- package/dist/pageops-sdk.es.js +196 -184
- package/dist/pageops-sdk.umd.cjs +33 -27
- package/dist/types.d.ts +7 -0
- package/package.json +1 -1
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AgentRunHistory, ContextSession, ConversationMessage, ConversationThread, PageOpsContext, PageOpsMountOptions, SourceSnapshot } from './types';
|
|
1
|
+
import type { AgentRunHistory, ContextSession, ConversationMessage, ConversationThread, PageOpsContext, PageOpsMountOptions, SourceSnapshot, SourceUploadMetadata } from './types';
|
|
2
2
|
export declare class PageOpsClient {
|
|
3
3
|
private options;
|
|
4
4
|
constructor(options: PageOpsMountOptions);
|
|
@@ -9,8 +9,8 @@ export declare class PageOpsClient {
|
|
|
9
9
|
listMessages(threadId: string): Promise<ConversationMessage[]>;
|
|
10
10
|
getAgentRun(runId: string): Promise<AgentRunHistory>;
|
|
11
11
|
listSources(): Promise<SourceSnapshot[]>;
|
|
12
|
-
uploadSource(file: File): Promise<SourceSnapshot>;
|
|
13
|
-
streamQuestion(threadId: string, question: string, signal?: AbortSignal): Promise<Response>;
|
|
12
|
+
uploadSource(file: File, metadata: SourceUploadMetadata): Promise<SourceSnapshot>;
|
|
13
|
+
streamQuestion(threadId: string, question: string, userRole: string, signal?: AbortSignal): Promise<Response>;
|
|
14
14
|
private request;
|
|
15
15
|
private base;
|
|
16
16
|
}
|
package/dist/index.d.ts
CHANGED
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: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.run-selected{border-color:#93c5fd;box-shadow:0 0 0 2px #3b82f614}.po-answer-meta{display:flex;min-width:0;align-items:center;flex-wrap:wrap;gap:6px 10px;border-top:1px solid var(--po-soft-border);margin-top:5px;padding-top:8px;color:var(--po-muted);font-size:11px}.po-answer-meta.selected{color:#1d4ed8}.po-run-id{display:flex;min-width:0;max-width:100%;align-items:center;gap:5px}.po-run-id code{display:block;max-width:148px;overflow:hidden;background:transparent;color:inherit;padding:0;text-overflow:ellipsis;white-space:nowrap}.po-answer-meta button{border:0;background:transparent;color:var(--po-primary-dark);padding:2px 0;font-size:11px;font-weight:700}.po-answer-meta button:hover{text-decoration:underline}.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:8px;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:grid;grid-template-columns:9px minmax(0,1fr) auto;align-items:start;gap:9px;cursor:pointer}.po-step summary::marker{display:none;content:""}.po-step[data-static] summary{cursor:default}.po-step-dot{width:8px;height:8px;margin-top:5px;border:2px solid #94a3b8;border-radius:50%;background:#fff}.po-step.running .po-step-dot{border-color:#2563eb;animation:po-step-pulse 1.2s ease-in-out infinite}.po-step.completed .po-step-dot{border-color:#16a34a;background:#16a34a}.po-step.failed .po-step-dot{border-color:#dc2626;background:#dc2626}.po-step-copy{display:grid;min-width:0;gap:4px}.po-step-copy strong{font-size:13px}.po-step-copy small{color:var(--po-muted);font-size:12px;font-weight:500;line-height:1.45}.po-step-status{color:var(--po-muted);font-size:11px;white-space:nowrap}.po-step-metrics{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0 0 18px}.po-step-metrics span{border:1px solid #dbeafe;border-radius:4px;background:#f8fbff;color:#475569;padding:2px 6px;font-size:11px}.po-step-details{display:grid;gap:8px;margin:10px 0 0 18px;border-top:1px solid var(--po-soft-border);padding-top:9px}.po-step-details div{display:grid;gap:3px}.po-step-details span{color:var(--po-muted);font-size:11px}.po-step-details p{overflow-wrap:anywhere;margin:0;color:#334155;font-size:12px;line-height:1.5;white-space:pre-wrap}.po-trace-state{display:flex;align-items:center;gap:8px;border:1px solid var(--po-soft-border);border-radius:8px;background:#fff;color:var(--po-muted);padding:12px;font-size:12px}.po-trace-state.failed{border-color:#fecaca;color:#b91c1c}@keyframes po-step-pulse{50%{opacity:.35}}@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-step-dot,.po-typing-cursor{animation:none}}
|
|
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.run-selected{border-color:#93c5fd;box-shadow:0 0 0 2px #3b82f614}.po-answer-meta{display:flex;min-width:0;align-items:center;flex-wrap:wrap;gap:6px 10px;border-top:1px solid var(--po-soft-border);margin-top:5px;padding-top:8px;color:var(--po-muted);font-size:11px}.po-answer-meta.selected{color:#1d4ed8}.po-run-id{display:flex;min-width:0;max-width:100%;align-items:center;gap:5px}.po-run-id code{display:block;max-width:148px;overflow:hidden;background:transparent;color:inherit;padding:0;text-overflow:ellipsis;white-space:nowrap}.po-answer-meta button{border:0;background:transparent;color:var(--po-primary-dark);padding:2px 0;font-size:11px;font-weight:700}.po-answer-meta button:hover{text-decoration:underline}.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;padding-bottom:4px}.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:6px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-source-reference{display:grid;grid-template-columns:1fr 1fr;overflow:hidden;border:1px solid #cbd5e1;border-radius:6px;background:#fff}.po-source-reference label{display:flex;align-items:center;justify-content:center;gap:6px;min-height:32px;color:#475569;font-size:12px;font-weight:700;cursor:pointer}.po-source-reference label+label{border-left:1px solid #cbd5e1}.po-source-reference label:has(input:checked){background:#eef2ff;color:var(--po-primary-dark)}.po-source-reference input{accent-color:var(--po-primary)}.po-source-reference-value,.po-source-remark{box-sizing:border-box;width:100%;border:1px solid #cbd5e1;border-radius:6px;background:#fff;color:var(--po-text);padding:8px 9px;font:inherit;font-size:12px;outline:none}.po-source-reference-value:focus,.po-source-remark:focus{border-color:var(--po-primary);box-shadow:0 0 0 2px #4f46e51f}.po-source-remark{min-height:54px;resize:vertical}.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:6px;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:8px;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:grid;grid-template-columns:9px minmax(0,1fr) auto;align-items:start;gap:9px;cursor:pointer}.po-step summary::marker{display:none;content:""}.po-step[data-static] summary{cursor:default}.po-step-dot{width:8px;height:8px;margin-top:5px;border:2px solid #94a3b8;border-radius:50%;background:#fff}.po-step.running .po-step-dot{border-color:#2563eb;animation:po-step-pulse 1.2s ease-in-out infinite}.po-step.completed .po-step-dot{border-color:#16a34a;background:#16a34a}.po-step.failed .po-step-dot{border-color:#dc2626;background:#dc2626}.po-step-copy{display:grid;min-width:0;gap:4px}.po-step-copy strong{font-size:13px}.po-step-copy small{color:var(--po-muted);font-size:12px;font-weight:500;line-height:1.45}.po-step-status{color:var(--po-muted);font-size:11px;white-space:nowrap}.po-step-metrics{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0 0 18px}.po-step-metrics span{border:1px solid #dbeafe;border-radius:4px;background:#f8fbff;color:#475569;padding:2px 6px;font-size:11px}.po-step-details{display:grid;gap:8px;margin:10px 0 0 18px;border-top:1px solid var(--po-soft-border);padding-top:9px}.po-step-details div{display:grid;gap:3px}.po-step-details span{color:var(--po-muted);font-size:11px}.po-step-details p{overflow-wrap:anywhere;margin:0;color:#334155;font-size:12px;line-height:1.5;white-space:pre-wrap}.po-trace-state{display:flex;align-items:center;gap:8px;border:1px solid var(--po-soft-border);border-radius:8px;background:#fff;color:var(--po-muted);padding:12px;font-size:12px}.po-trace-state.failed{border-color:#fecaca;color:#b91c1c}@keyframes po-step-pulse{50%{opacity:.35}}@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-step-dot,.po-typing-cursor{animation:none}}
|
package/dist/pageops-sdk.es.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
4
|
-
class
|
|
1
|
+
var W = Object.defineProperty;
|
|
2
|
+
var z = (a, e, t) => e in a ? W(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
|
|
3
|
+
var i = (a, e, t) => z(a, typeof e != "symbol" ? e + "" : e, t);
|
|
4
|
+
class K {
|
|
5
5
|
constructor(e) {
|
|
6
6
|
this.options = e;
|
|
7
7
|
}
|
|
8
|
-
async createContext(e = ((
|
|
9
|
-
var n,
|
|
8
|
+
async createContext(e = ((r) => (r = ((t) => ((s) => (s = (t = this.options).getPageContext) == null ? void 0 : s.call(t))())()) != null ? r : {})()) {
|
|
9
|
+
var n, l, p;
|
|
10
10
|
return this.request("/context/session", {
|
|
11
11
|
method: "POST",
|
|
12
12
|
body: JSON.stringify({
|
|
@@ -14,8 +14,8 @@ class R {
|
|
|
14
14
|
env: this.options.env,
|
|
15
15
|
route: e.route,
|
|
16
16
|
url: (n = e.url) != null ? n : location.href,
|
|
17
|
-
title: (
|
|
18
|
-
menu_path: (
|
|
17
|
+
title: (l = e.title) != null ? l : document.title,
|
|
18
|
+
menu_path: (p = e.menuPath) != null ? p : [],
|
|
19
19
|
tenant_id: e.tenantId,
|
|
20
20
|
user_role: e.userRole,
|
|
21
21
|
build_version: e.buildVersion
|
|
@@ -45,24 +45,24 @@ class R {
|
|
|
45
45
|
async listSources() {
|
|
46
46
|
return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
|
|
47
47
|
}
|
|
48
|
-
uploadSource(e) {
|
|
49
|
-
const
|
|
50
|
-
return
|
|
48
|
+
uploadSource(e, t) {
|
|
49
|
+
const s = new FormData();
|
|
50
|
+
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: {} });
|
|
51
51
|
}
|
|
52
|
-
streamQuestion(e, t, s) {
|
|
52
|
+
streamQuestion(e, t, s, r) {
|
|
53
53
|
return fetch(`${this.base()}/question/stream`, {
|
|
54
54
|
method: "POST",
|
|
55
55
|
headers: { "content-type": "application/json" },
|
|
56
|
-
body: JSON.stringify({ app_id: this.options.appId, thread_id: e, question: t }),
|
|
57
|
-
signal:
|
|
56
|
+
body: JSON.stringify({ app_id: this.options.appId, thread_id: e, question: t, user_role: s }),
|
|
57
|
+
signal: r
|
|
58
58
|
});
|
|
59
59
|
}
|
|
60
60
|
async request(e, t) {
|
|
61
|
-
var
|
|
62
|
-
const s = (t == null ? void 0 : t.body) instanceof FormData ? t.headers : { "content-type": "application/json", ...(
|
|
63
|
-
if (
|
|
64
|
-
const n = await
|
|
65
|
-
if (!
|
|
61
|
+
var l, p;
|
|
62
|
+
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 : {} }, r = await fetch(`${this.base()}${e}`, { ...t, headers: s });
|
|
63
|
+
if (r.status === 204) return;
|
|
64
|
+
const n = await r.json();
|
|
65
|
+
if (!r.ok) throw new Error((p = n.message) != null ? p : "PageOps 请求失败");
|
|
66
66
|
return n;
|
|
67
67
|
}
|
|
68
68
|
base() {
|
|
@@ -70,75 +70,75 @@ class R {
|
|
|
70
70
|
return e.endsWith("/api") ? e : `${e}/api`;
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
|
-
async function
|
|
73
|
+
async function H(a, e) {
|
|
74
74
|
const t = await a.json().catch(() => null);
|
|
75
75
|
return typeof (t == null ? void 0 : t.message) == "string" && t.message.trim() ? t.message : e;
|
|
76
76
|
}
|
|
77
|
-
function
|
|
77
|
+
function M(a) {
|
|
78
78
|
return a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
79
79
|
}
|
|
80
80
|
function v(a) {
|
|
81
|
-
return
|
|
81
|
+
return M(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
82
82
|
}
|
|
83
|
-
function
|
|
83
|
+
function N(a, e) {
|
|
84
84
|
const t = a[e], s = a[e + 1];
|
|
85
85
|
if (!(t != null && t.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
|
|
86
|
-
const
|
|
86
|
+
const r = [];
|
|
87
87
|
let n = e;
|
|
88
88
|
for (; n < a.length && a[n].includes("|") && a[n].trim(); )
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
return { html: `<table><thead><tr>${
|
|
89
|
+
r.push(a[n]), n += 1;
|
|
90
|
+
const l = (g) => g.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((f) => v(f.trim())), p = l(r[0]).map((g) => `<th>${g}</th>`).join(""), o = r.slice(2).map((g) => `<tr>${l(g).map((f) => `<td>${f}</td>`).join("")}</tr>`).join("");
|
|
91
|
+
return { html: `<table><thead><tr>${p}</tr></thead><tbody>${o}</tbody></table>`, next: n };
|
|
92
92
|
}
|
|
93
|
-
function
|
|
93
|
+
function R(a) {
|
|
94
94
|
const e = a.split(`
|
|
95
95
|
`), t = [];
|
|
96
96
|
for (let s = 0; s < e.length; s += 1) {
|
|
97
|
-
const
|
|
98
|
-
if (
|
|
99
|
-
const
|
|
97
|
+
const r = e[s];
|
|
98
|
+
if (r.trim().startsWith("```")) {
|
|
99
|
+
const l = [];
|
|
100
100
|
for (s += 1; s < e.length && !e[s].trim().startsWith("```"); )
|
|
101
|
-
|
|
102
|
-
t.push(`<pre><code>${
|
|
101
|
+
l.push(e[s]), s += 1;
|
|
102
|
+
t.push(`<pre><code>${M(l.join(`
|
|
103
103
|
`))}</code></pre>`);
|
|
104
104
|
continue;
|
|
105
105
|
}
|
|
106
|
-
const n =
|
|
106
|
+
const n = N(e, s);
|
|
107
107
|
if (n) {
|
|
108
108
|
t.push(n.html), s = n.next - 1;
|
|
109
109
|
continue;
|
|
110
110
|
}
|
|
111
|
-
|
|
111
|
+
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>");
|
|
112
112
|
}
|
|
113
113
|
return t.join("");
|
|
114
114
|
}
|
|
115
|
-
async function
|
|
115
|
+
async function J(a, e) {
|
|
116
116
|
var n;
|
|
117
117
|
const t = a.getReader(), s = new TextDecoder();
|
|
118
|
-
let
|
|
118
|
+
let r = "";
|
|
119
119
|
for (; ; ) {
|
|
120
|
-
const { done:
|
|
121
|
-
if (
|
|
122
|
-
|
|
120
|
+
const { done: l, value: p } = await t.read();
|
|
121
|
+
if (l) {
|
|
122
|
+
r += s.decode();
|
|
123
123
|
break;
|
|
124
124
|
}
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
for (const g of
|
|
125
|
+
r += s.decode(p, { stream: !0 });
|
|
126
|
+
const o = r.split(/\r?\n\r?\n/);
|
|
127
|
+
r = (n = o.pop()) != null ? n : "";
|
|
128
|
+
for (const g of o) j(g, e);
|
|
129
129
|
}
|
|
130
|
-
|
|
130
|
+
r.trim() && j(r, e);
|
|
131
131
|
}
|
|
132
|
-
function
|
|
133
|
-
var
|
|
134
|
-
const t = (
|
|
132
|
+
function j(a, e) {
|
|
133
|
+
var r, n;
|
|
134
|
+
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];
|
|
135
135
|
t && s && e(t, JSON.parse(s));
|
|
136
136
|
}
|
|
137
|
-
class
|
|
137
|
+
class Q {
|
|
138
138
|
constructor(e, t = 16) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
139
|
+
i(this, "queue", []);
|
|
140
|
+
i(this, "timer", null);
|
|
141
|
+
i(this, "drainWaiters", []);
|
|
142
142
|
this.onChunk = e, this.interval = t;
|
|
143
143
|
}
|
|
144
144
|
enqueue(e) {
|
|
@@ -162,61 +162,60 @@ class K {
|
|
|
162
162
|
for (const e of this.drainWaiters.splice(0)) e();
|
|
163
163
|
}
|
|
164
164
|
}
|
|
165
|
-
const
|
|
165
|
+
const T = [
|
|
166
166
|
{ value: "product", label: "产品" },
|
|
167
167
|
{ value: "business", label: "业务" },
|
|
168
168
|
{ value: "developer", label: "研发" },
|
|
169
169
|
{ value: "tester", label: "测试" }
|
|
170
170
|
];
|
|
171
|
-
class
|
|
171
|
+
class V {
|
|
172
172
|
constructor() {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
r(this, "typewriter", new K((e) => {
|
|
173
|
+
i(this, "client", null);
|
|
174
|
+
i(this, "options", null);
|
|
175
|
+
i(this, "root", null);
|
|
176
|
+
i(this, "panel", null);
|
|
177
|
+
i(this, "context", null);
|
|
178
|
+
i(this, "contextKey", "");
|
|
179
|
+
i(this, "selectedPageKey", "");
|
|
180
|
+
i(this, "currentThread", null);
|
|
181
|
+
i(this, "conversations", []);
|
|
182
|
+
i(this, "messages", []);
|
|
183
|
+
i(this, "steps", []);
|
|
184
|
+
i(this, "selectedAgentRunId", "");
|
|
185
|
+
i(this, "runLoading", !1);
|
|
186
|
+
i(this, "runLoadError", "");
|
|
187
|
+
i(this, "copiedAgentRunId", "");
|
|
188
|
+
i(this, "copyFeedbackTimer", null);
|
|
189
|
+
i(this, "sourceSnapshots", []);
|
|
190
|
+
i(this, "sourceUploadStatus", "");
|
|
191
|
+
i(this, "sourceUploadError", "");
|
|
192
|
+
i(this, "sourceLoadError", "");
|
|
193
|
+
i(this, "sourceUploading", !1);
|
|
194
|
+
i(this, "sourceRefreshTimer", null);
|
|
195
|
+
i(this, "streaming", "");
|
|
196
|
+
i(this, "asking", !1);
|
|
197
|
+
i(this, "waitingForFirstContent", !1);
|
|
198
|
+
i(this, "abortController", null);
|
|
199
|
+
i(this, "activeRunId", 0);
|
|
200
|
+
i(this, "stoppedRunId", -1);
|
|
201
|
+
i(this, "answerStopped", !1);
|
|
202
|
+
i(this, "answerError", "");
|
|
203
|
+
i(this, "conversationError", "");
|
|
204
|
+
i(this, "deletingThreadId", "");
|
|
205
|
+
i(this, "streamFailure", "");
|
|
206
|
+
i(this, "streamDone", null);
|
|
207
|
+
i(this, "answerAudience", "business");
|
|
208
|
+
i(this, "typewriter", new Q((e) => {
|
|
210
209
|
this.streaming += e, this.updateStreamingMessage();
|
|
211
210
|
}));
|
|
212
211
|
}
|
|
213
212
|
mount(e) {
|
|
214
213
|
var t;
|
|
215
|
-
this.unmount(), this.options = e, this.client = new
|
|
214
|
+
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();
|
|
216
215
|
}
|
|
217
216
|
unmount() {
|
|
218
217
|
var e;
|
|
219
|
-
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.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = !1, this.answerAudience = "business"
|
|
218
|
+
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.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = !1, this.answerAudience = "business";
|
|
220
219
|
}
|
|
221
220
|
open() {
|
|
222
221
|
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,7 +226,7 @@ class j {
|
|
|
227
226
|
updateContext(e) {
|
|
228
227
|
if (!this.options) return;
|
|
229
228
|
const t = this.options.appId;
|
|
230
|
-
this.options = { ...this.options, ...e }, this.client = new
|
|
229
|
+
this.options = { ...this.options, ...e }, this.client = new K(this.options), this.options.appId !== t && (this.answerAudience = this.loadAnswerAudience(this.options.appId), this.currentThread = null, this.selectedPageKey = "", this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = ""), this.context = null, this.contextKey = "", this.renderPanel();
|
|
231
230
|
}
|
|
232
231
|
renderClosed() {
|
|
233
232
|
var e;
|
|
@@ -251,7 +250,7 @@ class j {
|
|
|
251
250
|
loadAnswerAudience(e) {
|
|
252
251
|
try {
|
|
253
252
|
const t = localStorage.getItem(this.answerAudienceStorageKey(e));
|
|
254
|
-
return
|
|
253
|
+
return T.some((s) => s.value === t) ? t : "business";
|
|
255
254
|
} catch (t) {
|
|
256
255
|
return "business";
|
|
257
256
|
}
|
|
@@ -263,29 +262,19 @@ class j {
|
|
|
263
262
|
} catch (e) {
|
|
264
263
|
}
|
|
265
264
|
}
|
|
266
|
-
|
|
265
|
+
changeAnswerAudience(e) {
|
|
267
266
|
var s;
|
|
268
|
-
if (this.asking
|
|
269
|
-
const t = (s =
|
|
270
|
-
|
|
271
|
-
this.answerAudience = t, this.saveAnswerAudience(), this.audienceChanging = !0, 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.conversationError = "", this.renderPanel();
|
|
272
|
-
try {
|
|
273
|
-
await this.newConversation();
|
|
274
|
-
} catch (i) {
|
|
275
|
-
this.conversationError = i instanceof Error ? i.message : "切换回答角色失败,请稍后重试。";
|
|
276
|
-
} finally {
|
|
277
|
-
this.audienceChanging = !1, this.renderPanel();
|
|
278
|
-
}
|
|
279
|
-
}
|
|
267
|
+
if (this.asking) return;
|
|
268
|
+
const t = (s = T.find((r) => r.value === e)) == null ? void 0 : s.value;
|
|
269
|
+
!t || t === this.answerAudience || (this.answerAudience = t, this.saveAnswerAudience(), this.renderPanel());
|
|
280
270
|
}
|
|
281
271
|
getPageContextKey(e) {
|
|
282
|
-
var t, s,
|
|
272
|
+
var t, s, r, n;
|
|
283
273
|
return JSON.stringify([
|
|
284
274
|
(t = e.route) != null ? t : "",
|
|
285
275
|
(s = e.url) != null ? s : location.href,
|
|
286
|
-
(
|
|
287
|
-
(n = e.menuPath) != null ? n : []
|
|
288
|
-
(c = e.userRole) != null ? c : ""
|
|
276
|
+
(r = e.title) != null ? r : document.title,
|
|
277
|
+
(n = e.menuPath) != null ? n : []
|
|
289
278
|
]);
|
|
290
279
|
}
|
|
291
280
|
async loadSources() {
|
|
@@ -310,7 +299,7 @@ class j {
|
|
|
310
299
|
async selectThread(e) {
|
|
311
300
|
if (!this.client) return;
|
|
312
301
|
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();
|
|
313
|
-
const t = [...this.messages].reverse().map(
|
|
302
|
+
const t = [...this.messages].reverse().map(O).find(Boolean);
|
|
314
303
|
t && await this.loadAgentRun(t);
|
|
315
304
|
}
|
|
316
305
|
async deleteConversation(e) {
|
|
@@ -330,13 +319,14 @@ class j {
|
|
|
330
319
|
}
|
|
331
320
|
}
|
|
332
321
|
}
|
|
333
|
-
async uploadSource(e) {
|
|
322
|
+
async uploadSource(e, t) {
|
|
323
|
+
var s;
|
|
334
324
|
if (this.client) {
|
|
335
325
|
this.sourceUploading = !0, this.sourceUploadStatus = "上传中...", this.sourceUploadError = "", this.renderPanel();
|
|
336
326
|
try {
|
|
337
|
-
await this.client.uploadSource(e), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = this.isProjectMemoryUpdating() ? "源码上传完成,项目记忆更新中..." : "上传完成", this.scheduleSourceRefresh();
|
|
338
|
-
} catch (
|
|
339
|
-
this.sourceUploadError =
|
|
327
|
+
await this.client.uploadSource(e, { ...t, uploader: (s = this.options) == null ? void 0 : s.uploader }), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = this.isProjectMemoryUpdating() ? "源码上传完成,项目记忆更新中..." : "上传完成", this.scheduleSourceRefresh();
|
|
328
|
+
} catch (r) {
|
|
329
|
+
this.sourceUploadError = r instanceof Error ? r.message : "源码包上传失败", this.sourceUploadStatus = "";
|
|
340
330
|
} finally {
|
|
341
331
|
this.sourceUploading = !1, this.renderPanel();
|
|
342
332
|
}
|
|
@@ -350,16 +340,16 @@ class j {
|
|
|
350
340
|
return;
|
|
351
341
|
}
|
|
352
342
|
this.resetAnswerState();
|
|
353
|
-
const s = ++this.activeRunId,
|
|
354
|
-
this.abortController =
|
|
343
|
+
const s = ++this.activeRunId, r = new AbortController();
|
|
344
|
+
this.abortController = r, this.stoppedRunId = -1, this.asking = !0, this.waitingForFirstContent = !0, this.renderPanel();
|
|
355
345
|
try {
|
|
356
346
|
const n = this.getPageContextKey(this.getPageContext());
|
|
357
347
|
if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== n && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
|
|
358
348
|
this.messages.push({ id: `local-${Date.now()}`, role: "user", content: e, metadata_json: {} }), this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.renderPanel();
|
|
359
|
-
const
|
|
360
|
-
if (!
|
|
361
|
-
if (!
|
|
362
|
-
if (await
|
|
349
|
+
const l = await this.client.streamQuestion(this.currentThread.id, e, this.answerAudience, r.signal);
|
|
350
|
+
if (!l.ok) throw new Error(await H(l, "服务暂时无法回答,请稍后重试。"));
|
|
351
|
+
if (!l.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
|
|
352
|
+
if (await J(l.body, (p, o) => this.handleStreamEvent(p, o)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
363
353
|
if (this.streamFailure) throw new Error(this.streamFailure);
|
|
364
354
|
if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
|
|
365
355
|
if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
@@ -369,7 +359,7 @@ class j {
|
|
|
369
359
|
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 }));
|
|
370
360
|
} finally {
|
|
371
361
|
if (s !== this.activeRunId) return;
|
|
372
|
-
this.asking = !1, this.waitingForFirstContent = !1, this.abortController ===
|
|
362
|
+
this.asking = !1, this.waitingForFirstContent = !1, this.abortController === r && (this.abortController = null), this.renderPanel(!0);
|
|
373
363
|
}
|
|
374
364
|
}
|
|
375
365
|
cancelActiveAnswer(e) {
|
|
@@ -377,17 +367,17 @@ class j {
|
|
|
377
367
|
if (!(!this.asking && !this.abortController)) {
|
|
378
368
|
if (e) {
|
|
379
369
|
this.stoppedRunId = this.activeRunId, this.answerStopped = !0;
|
|
380
|
-
const s = this.steps.map((
|
|
381
|
-
this.steps = s.some((
|
|
370
|
+
const s = this.steps.map((r) => r.status === "running" ? { ...r, status: "cancelled" } : r);
|
|
371
|
+
this.steps = s.some((r) => r.status === "cancelled") ? s : [...s, { id: "stopped", title: "已停止", status: "cancelled" }];
|
|
382
372
|
} else
|
|
383
373
|
this.activeRunId += 1, this.asking = !1;
|
|
384
374
|
this.typewriter.clear(), this.waitingForFirstContent = !1, (t = this.abortController) == null || t.abort(), this.abortController = null, e && this.renderPanel();
|
|
385
375
|
}
|
|
386
376
|
}
|
|
387
377
|
handleStreamEvent(e, t) {
|
|
388
|
-
var s,
|
|
378
|
+
var s, r;
|
|
389
379
|
if (e === "step") {
|
|
390
|
-
this.upsertStep(t), this.renderPanel();
|
|
380
|
+
this.upsertStep(t), this.renderPanel(!1, !0);
|
|
391
381
|
return;
|
|
392
382
|
}
|
|
393
383
|
if (e === "delta") {
|
|
@@ -396,17 +386,17 @@ class j {
|
|
|
396
386
|
this.waitingForFirstContent = !1, this.typewriter.enqueue(n);
|
|
397
387
|
return;
|
|
398
388
|
}
|
|
399
|
-
e === "done" && (this.streamDone = t), e === "error" && (this.streamFailure = String((
|
|
389
|
+
e === "done" && (this.streamDone = t), e === "error" && (this.streamFailure = String((r = t.message) != null ? r : "服务异常,请稍后重试。"));
|
|
400
390
|
}
|
|
401
391
|
updateStreamingMessage() {
|
|
402
|
-
var s,
|
|
392
|
+
var s, r;
|
|
403
393
|
const e = (s = this.panel) == null ? void 0 : s.querySelector("[data-streaming-content]");
|
|
404
394
|
if (!e) {
|
|
405
395
|
this.renderPanel();
|
|
406
396
|
return;
|
|
407
397
|
}
|
|
408
|
-
e.innerHTML =
|
|
409
|
-
const t = (
|
|
398
|
+
e.innerHTML = R(this.streaming);
|
|
399
|
+
const t = (r = this.panel) == null ? void 0 : r.querySelector(".po-messages");
|
|
410
400
|
t && (t.scrollTop = t.scrollHeight);
|
|
411
401
|
}
|
|
412
402
|
resetAnswerState() {
|
|
@@ -470,56 +460,60 @@ class j {
|
|
|
470
460
|
stopSourceRefresh() {
|
|
471
461
|
this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
|
|
472
462
|
}
|
|
473
|
-
renderPanel(e = this.asking) {
|
|
463
|
+
renderPanel(e = this.asking, t = !1) {
|
|
474
464
|
if (!this.panel) return;
|
|
475
|
-
const
|
|
476
|
-
<button type="button" data-audience="${o.value}" aria-pressed="${o.value === this.answerAudience}" ${this.asking
|
|
465
|
+
const s = this.questionUnavailableReason(), r = s || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), n = !!(s || this.asking), l = s ? '<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>', p = T.map((o) => `
|
|
466
|
+
<button type="button" data-audience="${o.value}" aria-pressed="${o.value === this.answerAudience}" ${this.asking ? "disabled" : ""}>${o.label}</button>
|
|
477
467
|
`).join("");
|
|
478
468
|
if (this.panel.innerHTML = `
|
|
479
469
|
<aside class="po-sidebar">
|
|
480
470
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
481
471
|
<button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
|
|
482
472
|
<input class="po-search" placeholder="搜索问答" />
|
|
483
|
-
${this.conversationError ? `<p class="po-conversation-error" role="alert">${
|
|
473
|
+
${this.conversationError ? `<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>` : ""}
|
|
484
474
|
<div class="po-thread-list">${this.conversations.map((o) => {
|
|
485
|
-
var
|
|
475
|
+
var g;
|
|
486
476
|
return `
|
|
487
|
-
<div class="po-thread-row ${o.id === ((
|
|
488
|
-
<button class="po-thread" data-thread="${
|
|
489
|
-
<strong>${
|
|
477
|
+
<div class="po-thread-row ${o.id === ((g = this.currentThread) == null ? void 0 : g.id) ? "active" : ""}">
|
|
478
|
+
<button class="po-thread" data-thread="${c(o.id)}" ${this.asking ? "disabled" : ""}>
|
|
479
|
+
<strong>${c(o.title)}</strong><span>${D(o.created_at)}</span>
|
|
490
480
|
</button>
|
|
491
|
-
<button class="po-thread-delete" type="button" data-delete-thread="${
|
|
481
|
+
<button class="po-thread-delete" type="button" data-delete-thread="${c(o.id)}" aria-label="删除会话:${c(o.title)}" title="删除会话" ${this.asking || this.deletingThreadId === o.id ? "disabled" : ""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
492
482
|
</div>`;
|
|
493
483
|
}).join("")}</div>
|
|
494
484
|
</aside>
|
|
495
485
|
<main class="po-chat">
|
|
496
|
-
<header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread ?
|
|
486
|
+
<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="回答角色">${p}</div></div></header>
|
|
497
487
|
<section class="po-messages">
|
|
498
488
|
${this.messages.map((o) => this.renderMessage(o)).join("")}
|
|
499
489
|
${this.renderAnswerState()}
|
|
500
490
|
</section>
|
|
501
|
-
<form class="po-composer"><textarea ${
|
|
491
|
+
<form class="po-composer"><textarea ${n ? "disabled" : ""} placeholder="${c(r)}"></textarea>${l}</form>
|
|
502
492
|
</main>
|
|
503
493
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
504
494
|
`, this.bindPanelEvents(), e) {
|
|
505
495
|
const o = this.panel.querySelector(".po-messages");
|
|
506
496
|
o && (o.scrollTop = o.scrollHeight);
|
|
507
497
|
}
|
|
498
|
+
if (t) {
|
|
499
|
+
const o = this.panel.querySelector(".po-trace > section");
|
|
500
|
+
o && (o.scrollTop = o.scrollHeight);
|
|
501
|
+
}
|
|
508
502
|
}
|
|
509
503
|
renderAnswerState() {
|
|
510
|
-
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>${
|
|
511
|
-
return `${e}${t}${
|
|
504
|
+
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>${c(this.answerError)}</div></article>` : "", r = this.answerStopped ? '<div class="po-stream-stopped" role="status">已停止输出</div>' : "";
|
|
505
|
+
return `${e}${t}${r}${s}`;
|
|
512
506
|
}
|
|
513
507
|
renderMessage(e) {
|
|
514
|
-
const t =
|
|
515
|
-
<span class="po-run-id" title="${
|
|
516
|
-
<button type="button" data-copy-run="${
|
|
517
|
-
<button type="button" data-view-run="${
|
|
508
|
+
const t = O(e), s = t && t === this.selectedAgentRunId, r = this.copiedAgentRunId === t, n = this.copiedAgentRunId === `error:${t}`, l = e.role === "assistant" && t ? `<footer class="po-answer-meta ${s ? "selected" : ""}">
|
|
509
|
+
<span class="po-run-id" title="${c(t)}">问答流水号 <code>${c(t)}</code></span>
|
|
510
|
+
<button type="button" data-copy-run="${c(t)}">${r ? "已复制" : n ? "复制失败" : "复制流水号"}</button>
|
|
511
|
+
<button type="button" data-view-run="${c(t)}" aria-pressed="${s}">${s ? "正在查看" : "查看执行过程"}</button>
|
|
518
512
|
</footer>` : "";
|
|
519
|
-
return `<article class="po-message ${e.role} ${s ? "run-selected" : ""}" data-message="${
|
|
513
|
+
return `<article class="po-message ${e.role} ${s ? "run-selected" : ""}" data-message="${c(e.id)}">
|
|
520
514
|
<b>${e.role === "user" ? "你" : "PageOps 分析"}</b>
|
|
521
|
-
<div>${e.role === "assistant" ?
|
|
522
|
-
${
|
|
515
|
+
<div>${e.role === "assistant" ? R(e.content) : c(e.content)}</div>
|
|
516
|
+
${l}
|
|
523
517
|
</article>`;
|
|
524
518
|
}
|
|
525
519
|
renderSourceUploader() {
|
|
@@ -528,89 +522,107 @@ class j {
|
|
|
528
522
|
<div class="po-source-uploader">
|
|
529
523
|
<strong>源码包</strong>
|
|
530
524
|
<p>同一项目的所有回答角色共享代码包。上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
|
|
525
|
+
<div class="po-source-reference" role="group" aria-label="代码引用类型">
|
|
526
|
+
<label><input type="radio" name="source-reference" value="branch" checked />Branch</label>
|
|
527
|
+
<label><input type="radio" name="source-reference" value="tag" />Tag</label>
|
|
528
|
+
</div>
|
|
529
|
+
<input class="po-source-reference-value" type="text" maxlength="128" placeholder="请输入 Branch 名称" />
|
|
530
|
+
<textarea class="po-source-remark" maxlength="500" placeholder="备注(选填)"></textarea>
|
|
531
531
|
<label class="po-upload-button">
|
|
532
532
|
<span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
|
|
533
533
|
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
|
|
534
534
|
</label>
|
|
535
|
-
${this.sourceUploadStatus ? `<p class="po-upload-status">${
|
|
535
|
+
${this.sourceUploadStatus ? `<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>` : ""}
|
|
536
536
|
${this.sourceSnapshots.length ? `<div class="po-source-list">${this.sourceSnapshots.map((t) => this.renderSourceItem(t)).join("")}</div>` : `<p class="po-upload-empty">${e}</p>`}
|
|
537
|
-
${this.sourceLoadError ? `<p class="po-upload-error">${
|
|
538
|
-
${this.sourceUploadError ? `<p class="po-upload-error">${
|
|
537
|
+
${this.sourceLoadError ? `<p class="po-upload-error">${c(this.sourceLoadError)}</p>` : ""}
|
|
538
|
+
${this.sourceUploadError ? `<p class="po-upload-error">${c(this.sourceUploadError)}</p>` : ""}
|
|
539
539
|
</div>
|
|
540
540
|
`;
|
|
541
541
|
}
|
|
542
542
|
renderSourceItem(e) {
|
|
543
|
-
var
|
|
544
|
-
const t = e.filename || "未命名代码包", s = e.created_at ?
|
|
545
|
-
return `<article class="po-source-item"><strong>${
|
|
543
|
+
var y, w, b, $, S, E, A;
|
|
544
|
+
const t = e.filename || "未命名代码包", s = e.created_at ? D(e.created_at) : "刚刚上传", r = G(e.archive_bytes || e.total_bytes || 0), n = String((w = (y = e.metadata) == null ? void 0 : y.analysis_status) != null ? w : "unknown"), l = typeof ((b = e.metadata) == null ? void 0 : b.tag) == "string" ? e.metadata.tag : "", p = typeof (($ = e.metadata) == null ? void 0 : $.branch) == "string" ? e.metadata.branch : "", o = l ? `Tag: ${l}` : p ? `Branch: ${p}` : "未记录代码引用", g = typeof ((S = e.metadata) == null ? void 0 : S.remark) == "string" && e.metadata.remark ? e.metadata.remark : "无备注", f = typeof ((E = e.metadata) == null ? void 0 : E.uploader) == "string" ? e.metadata.uploader : "未知用户", P = (A = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? A : "项目记忆状态未知";
|
|
545
|
+
return `<article class="po-source-item"><strong>${c(t)}</strong><span>${c(o)}</span><span>备注:${c(g)}</span><span>上传人:${c(f)} · ${c(s)} · ${c(r)}</span><span>${c(P)}</span></article>`;
|
|
546
546
|
}
|
|
547
547
|
renderSteps() {
|
|
548
|
-
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">${
|
|
549
|
-
var
|
|
550
|
-
const s = (
|
|
548
|
+
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">${c(this.runLoadError)}</div>` : (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", summary: "发送问题后,这里会展示完整分析过程。" }]).map((t) => {
|
|
549
|
+
var l, p, o;
|
|
550
|
+
const s = (l = t.metrics) != null && l.length ? `<div class="po-step-metrics">${t.metrics.map((g) => `<span>${c(g)}</span>`).join("")}</div>` : "", r = (p = t.details) != null && p.length ? `<div class="po-step-details">${t.details.map((g) => `<div><span>${c(g.label)}</span><p>${c(g.value)}</p></div>`).join("")}</div>` : "", n = !!(s || r);
|
|
551
551
|
return `<details class="po-step ${t.status}" ${t.status === "running" || t.status === "failed" ? "open" : ""} ${n ? "" : "data-static"}>
|
|
552
552
|
<summary>
|
|
553
553
|
<span class="po-step-dot" aria-hidden="true"></span>
|
|
554
|
-
<span class="po-step-copy"><strong>${
|
|
555
|
-
<span class="po-step-status">${
|
|
554
|
+
<span class="po-step-copy"><strong>${c(t.title)}</strong><small>${c((o = t.summary) != null ? o : "")}</small></span>
|
|
555
|
+
<span class="po-step-status">${Z(t.status)}</span>
|
|
556
556
|
</summary>
|
|
557
|
-
${s}${
|
|
557
|
+
${s}${r}
|
|
558
558
|
</details>`;
|
|
559
559
|
}).join("");
|
|
560
560
|
}
|
|
561
561
|
bindPanelEvents() {
|
|
562
|
-
var e, t, s,
|
|
563
|
-
(t = (e = this.panel) == null ? void 0 : e.querySelector('[data-action="new"]')) == null || t.addEventListener("click", () => void this.newConversation()), (
|
|
562
|
+
var e, t, s, r, n, l, p, o, g, f, P, y, w, b, $, S, E, A;
|
|
563
|
+
(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()), (l = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="stop-answer"]')) == null || l.addEventListener("click", () => this.cancelActiveAnswer(!0)), (p = this.panel) == null || p.querySelectorAll("[data-audience]").forEach((d) => {
|
|
564
564
|
d.addEventListener("click", () => {
|
|
565
565
|
var h;
|
|
566
|
-
return
|
|
566
|
+
return this.changeAnswerAudience((h = d.dataset.audience) != null ? h : "");
|
|
567
|
+
});
|
|
568
|
+
}), (g = (o = this.panel) == null ? void 0 : o.querySelector('[data-action="upload-source"]')) == null || g.addEventListener("change", (d) => {
|
|
569
|
+
var C, k, I, x, q, L, U, F, _;
|
|
570
|
+
const h = (C = d.target.files) == null ? void 0 : C[0];
|
|
571
|
+
if (!h) return;
|
|
572
|
+
const u = (I = (k = this.panel) == null ? void 0 : k.querySelector('[name="source-reference"]:checked')) == null ? void 0 : I.value, m = (L = (q = (x = this.panel) == null ? void 0 : x.querySelector(".po-source-reference-value")) == null ? void 0 : q.value.trim()) != null ? L : "", B = (_ = (F = (U = this.panel) == null ? void 0 : U.querySelector(".po-source-remark")) == null ? void 0 : F.value.trim()) != null ? _ : "";
|
|
573
|
+
if (!m || u !== "tag" && u !== "branch") {
|
|
574
|
+
this.sourceUploadError = "请选择 Tag 或 Branch,并填写对应名称。", this.renderPanel();
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
this.uploadSource(h, { [u]: m, remark: B });
|
|
578
|
+
}), (f = this.panel) == null || f.querySelectorAll('[name="source-reference"]').forEach((d) => {
|
|
579
|
+
d.addEventListener("change", () => {
|
|
580
|
+
var u;
|
|
581
|
+
const h = (u = this.panel) == null ? void 0 : u.querySelector(".po-source-reference-value");
|
|
582
|
+
h && (h.placeholder = `请输入 ${d.value === "tag" ? "Tag" : "Branch"} 名称`);
|
|
567
583
|
});
|
|
568
|
-
}), (
|
|
569
|
-
var u;
|
|
570
|
-
const h = (u = d.target.files) == null ? void 0 : u[0];
|
|
571
|
-
h && this.uploadSource(h);
|
|
572
|
-
}), (f = this.panel) == null || f.querySelectorAll("[data-thread]").forEach((d) => {
|
|
584
|
+
}), (P = this.panel) == null || P.querySelectorAll("[data-thread]").forEach((d) => {
|
|
573
585
|
d.addEventListener("click", () => {
|
|
574
586
|
const h = this.conversations.find((u) => u.id === d.dataset.thread);
|
|
575
587
|
h && this.selectThread(h);
|
|
576
588
|
});
|
|
577
|
-
}), (
|
|
589
|
+
}), (y = this.panel) == null || y.querySelectorAll("[data-delete-thread]").forEach((d) => {
|
|
578
590
|
d.addEventListener("click", (h) => {
|
|
579
591
|
h.stopPropagation();
|
|
580
592
|
const u = this.conversations.find((m) => m.id === d.dataset.deleteThread);
|
|
581
593
|
u && this.deleteConversation(u);
|
|
582
594
|
});
|
|
583
|
-
}), (
|
|
595
|
+
}), (w = this.panel) == null || w.querySelectorAll("[data-view-run]").forEach((d) => {
|
|
584
596
|
d.addEventListener("click", (h) => {
|
|
585
597
|
var u;
|
|
586
598
|
h.stopPropagation(), this.loadAgentRun((u = d.dataset.viewRun) != null ? u : "");
|
|
587
599
|
});
|
|
588
|
-
}), (
|
|
600
|
+
}), (b = this.panel) == null || b.querySelectorAll("[data-copy-run]").forEach((d) => {
|
|
589
601
|
d.addEventListener("click", (h) => {
|
|
590
602
|
var u;
|
|
591
603
|
h.stopPropagation(), this.copyAgentRunId((u = d.dataset.copyRun) != null ? u : "");
|
|
592
604
|
});
|
|
593
|
-
}), (
|
|
605
|
+
}), (S = ($ = this.panel) == null ? void 0 : $.querySelector("form")) == null || S.addEventListener("submit", (d) => {
|
|
594
606
|
var m;
|
|
595
607
|
d.preventDefault();
|
|
596
608
|
const h = (m = this.panel) == null ? void 0 : m.querySelector("textarea"), u = h == null ? void 0 : h.value.trim();
|
|
597
609
|
u && (h.value = "", this.ask(u));
|
|
598
|
-
}), (
|
|
610
|
+
}), (A = (E = this.panel) == null ? void 0 : E.querySelector("textarea")) == null || A.addEventListener("keydown", (d) => {
|
|
599
611
|
var u, m;
|
|
600
612
|
const h = d;
|
|
601
613
|
h.key === "Enter" && !h.shiftKey && (h.preventDefault(), (m = (u = this.panel) == null ? void 0 : u.querySelector("form")) == null || m.requestSubmit());
|
|
602
614
|
});
|
|
603
615
|
}
|
|
604
616
|
}
|
|
605
|
-
function
|
|
617
|
+
function c(a) {
|
|
606
618
|
return a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
607
619
|
}
|
|
608
|
-
function
|
|
620
|
+
function O(a) {
|
|
609
621
|
var t;
|
|
610
622
|
const e = (t = a.metadata_json) == null ? void 0 : t.agent_run_id;
|
|
611
623
|
return typeof e == "string" ? e : "";
|
|
612
624
|
}
|
|
613
|
-
function
|
|
625
|
+
function D(a) {
|
|
614
626
|
return new Intl.DateTimeFormat("zh-CN", {
|
|
615
627
|
timeZone: "Asia/Shanghai",
|
|
616
628
|
month: "2-digit",
|
|
@@ -620,7 +632,7 @@ function k(a) {
|
|
|
620
632
|
hourCycle: "h23"
|
|
621
633
|
}).format(new Date(a));
|
|
622
634
|
}
|
|
623
|
-
function
|
|
635
|
+
function G(a) {
|
|
624
636
|
if (!a) return "0 B";
|
|
625
637
|
const e = ["B", "KB", "MB", "GB"];
|
|
626
638
|
let t = a, s = 0;
|
|
@@ -628,10 +640,10 @@ function O(a) {
|
|
|
628
640
|
t /= 1024, s += 1;
|
|
629
641
|
return `${t >= 10 || s === 0 ? t.toFixed(0) : t.toFixed(1)} ${e[s]}`;
|
|
630
642
|
}
|
|
631
|
-
function
|
|
643
|
+
function Z(a) {
|
|
632
644
|
return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[a];
|
|
633
645
|
}
|
|
634
|
-
const
|
|
646
|
+
const Y = new V();
|
|
635
647
|
export {
|
|
636
|
-
|
|
648
|
+
Y as PageOpsSDK
|
|
637
649
|
};
|
package/dist/pageops-sdk.umd.cjs
CHANGED
|
@@ -1,56 +1,62 @@
|
|
|
1
|
-
(function(f,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(f=typeof globalThis!="undefined"?globalThis:f||self,m(f.PageOpsSDK={}))})(this,(function(f){"use strict";var
|
|
2
|
-
`),t=[];for(let s=0;s<e.length;s+=1){const
|
|
3
|
-
`))}</code></pre>`);continue}const i=U(e,s);if(i){t.push(i.html),s=i.next-1;continue}n.startsWith("### ")?t.push(`<h4>${w(n.slice(4))}</h4>`):n.startsWith("## ")?t.push(`<h3>${w(n.slice(3))}</h3>`):n.startsWith("# ")?t.push(`<h2>${w(n.slice(2))}</h2>`):n.startsWith("- ")?t.push(`<li>${w(n.slice(2))}</li>`):n.trim()?t.push(`<p>${w(n)}</p>`):t.push("<br>")}return t.join("")}async function F(o,e){var i;const t=o.getReader(),s=new TextDecoder;let n="";for(;;){const{done:c,value:a}=await t.read();if(c){n+=s.decode();break}n+=s.decode(a,{stream:!0});const p=n.split(/\r?\n\r?\n/);n=(i=p.pop())!=null?i:"";for(const g of p)A(g,e)}n.trim()&&A(n,e)}function A(o,e){var n,i;const t=(n=o.match(/^event:\s*(.+)$/m))==null?void 0:n[1],s=(i=o.match(/^data:\s*(.+)$/m))==null?void 0:i[1];t&&s&&e(t,JSON.parse(s))}class K{constructor(e,t=16){r(this,"queue",[]);r(this,"timer",null);r(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 S=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class _{constructor(){r(this,"client",null);r(this,"options",null);r(this,"root",null);r(this,"panel",null);r(this,"context",null);r(this,"contextKey","");r(this,"selectedPageKey","");r(this,"currentThread",null);r(this,"conversations",[]);r(this,"messages",[]);r(this,"steps",[]);r(this,"selectedAgentRunId","");r(this,"runLoading",!1);r(this,"runLoadError","");r(this,"copiedAgentRunId","");r(this,"copyFeedbackTimer",null);r(this,"sourceSnapshots",[]);r(this,"sourceUploadStatus","");r(this,"sourceUploadError","");r(this,"sourceLoadError","");r(this,"sourceUploading",!1);r(this,"sourceRefreshTimer",null);r(this,"streaming","");r(this,"asking",!1);r(this,"waitingForFirstContent",!1);r(this,"abortController",null);r(this,"activeRunId",0);r(this,"stoppedRunId",-1);r(this,"answerStopped",!1);r(this,"answerError","");r(this,"conversationError","");r(this,"deletingThreadId","");r(this,"streamFailure","");r(this,"streamDone",null);r(this,"answerAudience","business");r(this,"audienceChanging",!1);r(this,"typewriter",new K(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.sourceUploadStatus="",this.sourceUploadError="",this.sourceLoadError="",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 m(this.options),this.options.appId!==t&&(this.answerAudience=this.loadAnswerAudience(this.options.appId),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}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return S.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=S.find(n=>n.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.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.conversationError="",this.renderPanel();try{await this.newConversation()}catch(n){this.conversationError=n instanceof Error?n.message:"切换回答角色失败,请稍后重试。"}finally{this.audienceChanging=!1,this.renderPanel()}}}getPageContextKey(e){var t,s,n,i,c;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(n=e.title)!=null?n:document.title,(i=e.menuPath)!=null?i:[],(c=e.userRole)!=null?c:""])}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(P).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){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,n=new AbortController;this.abortController=n,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const i=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==i&&(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,n.signal);if(!c.ok)throw new Error(await y(c,"服务暂时无法回答,请稍后重试。"));if(!c.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await F(c.body,(a,p)=>this.handleStreamEvent(a,p)),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(i){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=i instanceof Error?i.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===n&&(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(n=>n.status==="running"?{...n,status:"cancelled"}:n);this.steps=s.some(n=>n.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,n;if(e==="step"){this.upsertStep(t),this.renderPanel();return}if(e==="delta"){const i=String((s=t.content)!=null?s:"");if(!i)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(i);return}e==="done"&&(this.streamDone=t),e==="error"&&(this.streamFailure=String((n=t.message)!=null?n:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,n;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=$(this.streaming);const t=(n=this.panel)==null?void 0:n.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.renderPanel()},1800),this.renderPanel()}}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.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.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){if(!this.panel)return;const t=this.questionUnavailableReason(),s=t||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),n=!!(t||this.asking),i=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>',c=S.map(a=>`
|
|
4
|
-
<button type="button" data-audience="${a.value}" aria-pressed="${a.value===this.answerAudience}" ${this.asking
|
|
1
|
+
(function(f,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(f=typeof globalThis!="undefined"?globalThis:f||self,m(f.PageOpsSDK={}))})(this,(function(f){"use strict";var X=Object.defineProperty;var Y=(f,m,w)=>m in f?X(f,m,{enumerable:!0,configurable:!0,writable:!0,value:w}):f[m]=w;var i=(f,m,w)=>Y(f,typeof m!="symbol"?m+"":m,w);class m{constructor(e){this.options=e}async createContext(e=(r=>(r=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?r:{})()){var n,l,p;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:(p=e.menuPath)!=null?p:[],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 getAgentRun(e){return this.request(`/question/runs/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`)}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(e,t){const s=new FormData;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:{}})}streamQuestion(e,t,s,r){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,user_role:s}),signal:r})}async request(e,t){var l,p;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:{}},r=await fetch(`${this.base()}${e}`,{...t,headers:s});if(r.status===204)return;const n=await r.json();if(!r.ok)throw new Error((p=n.message)!=null?p:"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 x(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function b(o){return x(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function z(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 r=[];let n=e;for(;n<o.length&&o[n].includes("|")&&o[n].trim();)r.push(o[n]),n+=1;const l=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(y=>b(y.trim())),p=l(r[0]).map(g=>`<th>${g}</th>`).join(""),a=r.slice(2).map(g=>`<tr>${l(g).map(y=>`<td>${y}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${p}</tr></thead><tbody>${a}</tbody></table>`,next:n}}function k(o){const e=o.split(`
|
|
2
|
+
`),t=[];for(let s=0;s<e.length;s+=1){const r=e[s];if(r.trim().startsWith("```")){const l=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)l.push(e[s]),s+=1;t.push(`<pre><code>${x(l.join(`
|
|
3
|
+
`))}</code></pre>`);continue}const n=z(e,s);if(n){t.push(n.html),s=n.next-1;continue}r.startsWith("### ")?t.push(`<h4>${b(r.slice(4))}</h4>`):r.startsWith("## ")?t.push(`<h3>${b(r.slice(3))}</h3>`):r.startsWith("# ")?t.push(`<h2>${b(r.slice(2))}</h2>`):r.startsWith("- ")?t.push(`<li>${b(r.slice(2))}</li>`):r.trim()?t.push(`<p>${b(r)}</p>`):t.push("<br>")}return t.join("")}async function H(o,e){var n;const t=o.getReader(),s=new TextDecoder;let r="";for(;;){const{done:l,value:p}=await t.read();if(l){r+=s.decode();break}r+=s.decode(p,{stream:!0});const a=r.split(/\r?\n\r?\n/);r=(n=a.pop())!=null?n:"";for(const g of a)q(g,e)}r.trim()&&q(r,e)}function q(o,e){var r,n;const t=(r=o.match(/^event:\s*(.+)$/m))==null?void 0:r[1],s=(n=o.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,"sourceUploadStatus","");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.sourceUploadStatus="",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.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}}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:[]])}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.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e,{...t,uploader:(s=this.options)==null?void 0:s.uploader}),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.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 l=await this.client.streamQuestion(this.currentThread.id,e,this.answerAudience,r.signal);if(!l.ok)throw new Error(await w(l,"服务暂时无法回答,请稍后重试。"));if(!l.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await H(l.body,(p,a)=>this.handleStreamEvent(p,a)),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.renderPanel(!1,!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.renderPanel()},1800),this.renderPanel()}}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.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.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){if(!this.panel)return;const s=this.questionUnavailableReason(),r=s||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),n=!!(s||this.asking),l=s?'<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>',p=I.map(a=>`
|
|
4
|
+
<button type="button" data-audience="${a.value}" aria-pressed="${a.value===this.answerAudience}" ${this.asking?"disabled":""}>${a.label}</button>
|
|
5
5
|
`).join("");if(this.panel.innerHTML=`
|
|
6
6
|
<aside class="po-sidebar">
|
|
7
7
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
8
8
|
<button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
|
|
9
9
|
<input class="po-search" placeholder="搜索问答" />
|
|
10
|
-
${this.conversationError?`<p class="po-conversation-error" role="alert">${
|
|
11
|
-
<div class="po-thread-list">${this.conversations.map(a=>{var
|
|
12
|
-
<div class="po-thread-row ${a.id===((
|
|
13
|
-
<button class="po-thread" data-thread="${
|
|
14
|
-
<strong>${
|
|
10
|
+
${this.conversationError?`<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>`:""}
|
|
11
|
+
<div class="po-thread-list">${this.conversations.map(a=>{var g;return`
|
|
12
|
+
<div class="po-thread-row ${a.id===((g=this.currentThread)==null?void 0:g.id)?"active":""}">
|
|
13
|
+
<button class="po-thread" data-thread="${c(a.id)}" ${this.asking?"disabled":""}>
|
|
14
|
+
<strong>${c(a.title)}</strong><span>${U(a.created_at)}</span>
|
|
15
15
|
</button>
|
|
16
|
-
<button class="po-thread-delete" type="button" data-delete-thread="${
|
|
16
|
+
<button class="po-thread-delete" type="button" data-delete-thread="${c(a.id)}" aria-label="删除会话:${c(a.title)}" title="删除会话" ${this.asking||this.deletingThreadId===a.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
17
17
|
</div>`}).join("")}</div>
|
|
18
18
|
</aside>
|
|
19
19
|
<main class="po-chat">
|
|
20
|
-
<header><div class="po-chat-title"><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="回答角色">${p}</div></div></header>
|
|
21
21
|
<section class="po-messages">
|
|
22
22
|
${this.messages.map(a=>this.renderMessage(a)).join("")}
|
|
23
23
|
${this.renderAnswerState()}
|
|
24
24
|
</section>
|
|
25
|
-
<form class="po-composer"><textarea ${n?"disabled":""} placeholder="${
|
|
25
|
+
<form class="po-composer"><textarea ${n?"disabled":""} placeholder="${c(r)}"></textarea>${l}</form>
|
|
26
26
|
</main>
|
|
27
27
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
28
|
-
`,this.bindPanelEvents(),e){const a=this.panel.querySelector(".po-messages");a&&(a.scrollTop=a.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>${
|
|
29
|
-
<span class="po-run-id" title="${
|
|
30
|
-
<button type="button" data-copy-run="${
|
|
31
|
-
<button type="button" data-view-run="${
|
|
32
|
-
</footer>`:"";return`<article class="po-message ${e.role} ${s?"run-selected":""}" data-message="${
|
|
28
|
+
`,this.bindPanelEvents(),e){const a=this.panel.querySelector(".po-messages");a&&(a.scrollTop=a.scrollHeight)}if(t){const a=this.panel.querySelector(".po-trace > section");a&&(a.scrollTop=a.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>${k(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>`:"",r=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${e}${t}${r}${s}`}renderMessage(e){const t=L(e),s=t&&t===this.selectedAgentRunId,r=this.copiedAgentRunId===t,n=this.copiedAgentRunId===`error:${t}`,l=e.role==="assistant"&&t?`<footer class="po-answer-meta ${s?"selected":""}">
|
|
29
|
+
<span class="po-run-id" title="${c(t)}">问答流水号 <code>${c(t)}</code></span>
|
|
30
|
+
<button type="button" data-copy-run="${c(t)}">${r?"已复制":n?"复制失败":"复制流水号"}</button>
|
|
31
|
+
<button type="button" data-view-run="${c(t)}" aria-pressed="${s}">${s?"正在查看":"查看执行过程"}</button>
|
|
32
|
+
</footer>`:"";return`<article class="po-message ${e.role} ${s?"run-selected":""}" data-message="${c(e.id)}">
|
|
33
33
|
<b>${e.role==="user"?"你":"PageOps 分析"}</b>
|
|
34
|
-
<div>${e.role==="assistant"
|
|
35
|
-
${
|
|
34
|
+
<div>${e.role==="assistant"?k(e.content):c(e.content)}</div>
|
|
35
|
+
${l}
|
|
36
36
|
</article>`}renderSourceUploader(){const e=this.sourceLoadError?"暂时无法读取项目共享代码包,连接恢复后将自动重试。":"当前项目暂无代码包,请先上传后再提问。";return`
|
|
37
37
|
<div class="po-source-uploader">
|
|
38
38
|
<strong>源码包</strong>
|
|
39
39
|
<p>同一项目的所有回答角色共享代码包。上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
|
|
40
|
+
<div class="po-source-reference" role="group" aria-label="代码引用类型">
|
|
41
|
+
<label><input type="radio" name="source-reference" value="branch" checked />Branch</label>
|
|
42
|
+
<label><input type="radio" name="source-reference" value="tag" />Tag</label>
|
|
43
|
+
</div>
|
|
44
|
+
<input class="po-source-reference-value" type="text" maxlength="128" placeholder="请输入 Branch 名称" />
|
|
45
|
+
<textarea class="po-source-remark" maxlength="500" placeholder="备注(选填)"></textarea>
|
|
40
46
|
<label class="po-upload-button">
|
|
41
47
|
<span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
|
|
42
48
|
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
|
|
43
49
|
</label>
|
|
44
|
-
${this.sourceUploadStatus?`<p class="po-upload-status">${
|
|
50
|
+
${this.sourceUploadStatus?`<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>`:""}
|
|
45
51
|
${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:`<p class="po-upload-empty">${e}</p>`}
|
|
46
|
-
${this.sourceLoadError?`<p class="po-upload-error">${
|
|
47
|
-
${this.sourceUploadError?`<p class="po-upload-error">${
|
|
52
|
+
${this.sourceLoadError?`<p class="po-upload-error">${c(this.sourceLoadError)}</p>`:""}
|
|
53
|
+
${this.sourceUploadError?`<p class="po-upload-error">${c(this.sourceUploadError)}</p>`:""}
|
|
48
54
|
</div>
|
|
49
|
-
`}renderSourceItem(e){var
|
|
55
|
+
`}renderSourceItem(e){var $,S,E,A,P,T,R;const t=e.filename||"未命名代码包",s=e.created_at?U(e.created_at):"刚刚上传",r=Q(e.archive_bytes||e.total_bytes||0),n=String((S=($=e.metadata)==null?void 0:$.analysis_status)!=null?S:"unknown"),l=typeof((E=e.metadata)==null?void 0:E.tag)=="string"?e.metadata.tag:"",p=typeof((A=e.metadata)==null?void 0:A.branch)=="string"?e.metadata.branch:"",a=l?`Tag: ${l}`:p?`Branch: ${p}`:"未记录代码引用",g=typeof((P=e.metadata)==null?void 0:P.remark)=="string"&&e.metadata.remark?e.metadata.remark:"无备注",y=typeof((T=e.metadata)==null?void 0:T.uploader)=="string"?e.metadata.uploader:"未知用户",C=(R={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?R:"项目记忆状态未知";return`<article class="po-source-item"><strong>${c(t)}</strong><span>${c(a)}</span><span>备注:${c(g)}</span><span>上传人:${c(y)} · ${c(s)} · ${c(r)}</span><span>${c(C)}</span></article>`}renderSteps(){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">${c(this.runLoadError)}</div>`:(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",summary:"发送问题后,这里会展示完整分析过程。"}]).map(t=>{var l,p,a;const s=(l=t.metrics)!=null&&l.length?`<div class="po-step-metrics">${t.metrics.map(g=>`<span>${c(g)}</span>`).join("")}</div>`:"",r=(p=t.details)!=null&&p.length?`<div class="po-step-details">${t.details.map(g=>`<div><span>${c(g.label)}</span><p>${c(g.value)}</p></div>`).join("")}</div>`:"",n=!!(s||r);return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""} ${n?"":"data-static"}>
|
|
50
56
|
<summary>
|
|
51
57
|
<span class="po-step-dot" aria-hidden="true"></span>
|
|
52
|
-
<span class="po-step-copy"><strong>${
|
|
53
|
-
<span class="po-step-status">${
|
|
58
|
+
<span class="po-step-copy"><strong>${c(t.title)}</strong><small>${c((a=t.summary)!=null?a:"")}</small></span>
|
|
59
|
+
<span class="po-step-status">${V(t.status)}</span>
|
|
54
60
|
</summary>
|
|
55
|
-
${s}${
|
|
56
|
-
</details>`}).join("")}bindPanelEvents(){var e,t,s,n,
|
|
61
|
+
${s}${r}
|
|
62
|
+
</details>`}).join("")}bindPanelEvents(){var e,t,s,r,n,l,p,a,g,y,C,$,S,E,A,P,T,R;(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()),(l=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||l.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(p=this.panel)==null||p.querySelectorAll("[data-audience]").forEach(h=>{h.addEventListener("click",()=>{var d;return this.changeAnswerAudience((d=h.dataset.audience)!=null?d:"")})}),(g=(a=this.panel)==null?void 0:a.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",h=>{var F,_,K,j,O,D,M,B,W;const d=(F=h.target.files)==null?void 0:F[0];if(!d)return;const u=(K=(_=this.panel)==null?void 0:_.querySelector('[name="source-reference"]:checked'))==null?void 0:K.value,v=(D=(O=(j=this.panel)==null?void 0:j.querySelector(".po-source-reference-value"))==null?void 0:O.value.trim())!=null?D:"",Z=(W=(B=(M=this.panel)==null?void 0:M.querySelector(".po-source-remark"))==null?void 0:B.value.trim())!=null?W:"";if(!v||u!=="tag"&&u!=="branch"){this.sourceUploadError="请选择 Tag 或 Branch,并填写对应名称。",this.renderPanel();return}this.uploadSource(d,{[u]:v,remark:Z})}),(y=this.panel)==null||y.querySelectorAll('[name="source-reference"]').forEach(h=>{h.addEventListener("change",()=>{var u;const d=(u=this.panel)==null?void 0:u.querySelector(".po-source-reference-value");d&&(d.placeholder=`请输入 ${h.value==="tag"?"Tag":"Branch"} 名称`)})}),(C=this.panel)==null||C.querySelectorAll("[data-thread]").forEach(h=>{h.addEventListener("click",()=>{const d=this.conversations.find(u=>u.id===h.dataset.thread);d&&this.selectThread(d)})}),($=this.panel)==null||$.querySelectorAll("[data-delete-thread]").forEach(h=>{h.addEventListener("click",d=>{d.stopPropagation();const u=this.conversations.find(v=>v.id===h.dataset.deleteThread);u&&this.deleteConversation(u)})}),(S=this.panel)==null||S.querySelectorAll("[data-view-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.loadAgentRun((u=h.dataset.viewRun)!=null?u:"")})}),(E=this.panel)==null||E.querySelectorAll("[data-copy-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.copyAgentRunId((u=h.dataset.copyRun)!=null?u:"")})}),(P=(A=this.panel)==null?void 0:A.querySelector("form"))==null||P.addEventListener("submit",h=>{var v;h.preventDefault();const d=(v=this.panel)==null?void 0:v.querySelector("textarea"),u=d==null?void 0:d.value.trim();u&&(d.value="",this.ask(u))}),(R=(T=this.panel)==null?void 0:T.querySelector("textarea"))==null||R.addEventListener("keydown",h=>{var u,v;const d=h;d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),(v=(u=this.panel)==null?void 0:u.querySelector("form"))==null||v.requestSubmit())})}}function c(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function L(o){var t;const e=(t=o.metadata_json)==null?void 0:t.agent_run_id;return typeof e=="string"?e:""}function U(o){return new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(new Date(o))}function Q(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 V(o){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[o]}const G=new J;f.PageOpsSDK=G,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
|
package/dist/types.d.ts
CHANGED
|
@@ -11,6 +11,7 @@ export interface PageOpsMountOptions {
|
|
|
11
11
|
apiBase: string;
|
|
12
12
|
appId: string;
|
|
13
13
|
env: string;
|
|
14
|
+
uploader?: string;
|
|
14
15
|
getPageContext?: () => PageOpsContext;
|
|
15
16
|
container?: HTMLElement;
|
|
16
17
|
}
|
|
@@ -77,6 +78,12 @@ export interface SourceSnapshot {
|
|
|
77
78
|
export interface SourceSnapshotListResponse {
|
|
78
79
|
sources: SourceSnapshot[];
|
|
79
80
|
}
|
|
81
|
+
export interface SourceUploadMetadata {
|
|
82
|
+
tag?: string;
|
|
83
|
+
branch?: string;
|
|
84
|
+
remark?: string;
|
|
85
|
+
uploader?: string;
|
|
86
|
+
}
|
|
80
87
|
export interface StreamDonePayload {
|
|
81
88
|
message_id: string;
|
|
82
89
|
answer: Record<string, unknown>;
|