File size: 12,091 Bytes
9bdc593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5e756a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc826a1
e5e756a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc826a1
e5e756a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9bdc593
 
 
 
 
 
 
 
 
 
e5e756a
 
 
 
 
9bdc593
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
window.PluginUI = (() => {
  async function request(path, options = {}) {
    const response = await fetch(path, options);
    const contentType = response.headers.get("content-type") || "";
    const payload = contentType.includes("application/json")
      ? await response.json()
      : await response.text();

    if (!response.ok) {
      const detail = typeof payload === "object" ? payload.detail || payload.message : payload;
      throw new Error(detail || `请求失败:${response.status}`);
    }

    return payload;
  }

  async function requestBlob(path, options = {}) {
    const response = await fetch(path, options);
    if (!response.ok) {
      let detail = "";
      try {
        const payload = await response.json();
        detail = payload.detail || payload.message || "";
      } catch {
        detail = await response.text();
      }
      throw new Error(detail || `请求失败:${response.status}`);
    }
    return response.blob();
  }

  function showMessage(id, text, type = "success") {
    const el = document.getElementById(id);
    if (!el) return;
    el.textContent = text;
    el.className = `plugin-message show ${type}`;
  }

  function clearMessage(id) {
    const el = document.getElementById(id);
    if (!el) return;
    el.textContent = "";
    el.className = "plugin-message";
  }

  function setText(id, value) {
    const el = document.getElementById(id);
    if (el) el.textContent = value == null ? "" : String(value);
  }

  function setJson(id, value) {
    setText(id, typeof value === "string" ? value : JSON.stringify(value, null, 2));
  }

  function downloadBlob(blob, filename) {
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);
  }

  function fileSize(bytes) {
    if (!Number.isFinite(bytes)) return "-";
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
  }

  async function copyText(text) {
    await navigator.clipboard.writeText(text);
  }

  // ============================================================
  // Run Log 组件 — 从后端 run/log API 轮询真实事件
  // ============================================================

  /** 时间格式化辅助 */
  function _formatTs(ts) {
    try {
      const d = new Date(ts);
      const pad = (n) => String(n).padStart(2, "0");
      return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    } catch {
      return ts || "";
    }
  }

  /** 事件级别对应的 CSS class */
  function _levelClass(level) {
    if (level === "error") return "run-log-entry--error";
    if (level === "warning") return "run-log-entry--warn";
    return "";
  }

  /** 事件级别对应的中文标签 */
  function _levelLabel(level) {
    if (level === "error") return "错误";
    if (level === "warning") return "警告";
    if (level === "debug") return "调试";
    return "信息";
  }

  /**
   * 创建 run 日志容器,返回日志 DOM 元素。
   * 调用方应将其插入到期望的位置。
   *
   * @param {Object} [options]
   * @param {string} [options.title] - 面板标题,默认"运行日志"
   * @returns {HTMLElement} 日志容器 DOM
   */
  function createRunLog(options = {}) {
    const title = options.title || "运行日志";

    const panel = document.createElement("div");
    panel.className = "plugin-panel run-log-panel";

    const titleEl = document.createElement("h3");
    titleEl.className = "plugin-panel-title";
    titleEl.textContent = title;
    panel.appendChild(titleEl);

    // 运行状态指示器
    const statusBar = document.createElement("div");
    statusBar.className = "run-log-status";
    statusBar.innerHTML = `<span class="run-log-status-dot"></span><span class="run-log-status-text">等待运行...</span>`;
    panel.appendChild(statusBar);

    // 日志列表
    const logList = document.createElement("div");
    logList.className = "run-log-list";
    panel.appendChild(logList);

    // 存储内部状态(不在 DOM 中暴露)
    panel._runLogState = {
      seenSeq: new Set(),
      pollingTimer: null,
      apiBase: "",
      runId: "",
      statusBar,
      logList,
    };

    return panel;
  }

  /**
   * 渲染单条事件到日志列表。
   *
   * @param {HTMLElement} logPanel - createRunLog 返回的面板
   * @param {Object} event - 事件对象 {seq, ts, stage, level, message, detail, artifact_id}
   */
  function _renderEvent(logPanel, event) {
    const state = logPanel._runLogState;
    if (!state) return;

    // 去重
    if (state.seenSeq.has(event.seq)) return;
    state.seenSeq.add(event.seq);

    const entry = document.createElement("div");
    entry.className = `run-log-entry ${_levelClass(event.level)}`;

    // 事件头部:时间 + 阶段 + 级别
    const header = document.createElement("div");
    header.className = "run-log-entry-header";

    const ts = document.createElement("span");
    ts.className = "run-log-entry-ts";
    ts.textContent = _formatTs(event.ts);

    const stage = document.createElement("span");
    stage.className = "run-log-entry-stage";
    stage.textContent = event.stage || "";

    const level = document.createElement("span");
    level.className = `run-log-entry-level run-log-level--${event.level || "info"}`;
    level.textContent = _levelLabel(event.level);

    header.appendChild(ts);
    header.appendChild(stage);
    header.appendChild(level);
    entry.appendChild(header);

    // 消息
    const msg = document.createElement("div");
    msg.className = "run-log-entry-message";
    msg.textContent = event.message || "";
    entry.appendChild(msg);

    // 详情(折叠显示)
    if (event.detail) {
      const detail = document.createElement("details");
      detail.className = "run-log-entry-detail";
      const summary = document.createElement("summary");
      summary.textContent = "详情";
      detail.appendChild(summary);
      const pre = document.createElement("pre");
      pre.textContent = event.detail;
      detail.appendChild(pre);
      entry.appendChild(detail);
    }

    // artifact 链接
    if (event.artifact_id) {
      const artifactLink = document.createElement("div");
      artifactLink.className = "run-log-entry-artifact";
      artifactLink.innerHTML = `<span class="run-log-artifact-icon">📎</span>产物: <code>${event.artifact_id}</code>`;
      entry.appendChild(artifactLink);
    }

    state.logList.appendChild(entry);
    // 自动滚动到底部
    state.logList.scrollTop = state.logList.scrollHeight;
  }

  /**
   * 开始轮询后端 run events API,自动追加事件到日志面板。
   *
   * @param {string} pluginName - 插件名(如 "audio"),用于拼真后端路径 /api/plugins/{pluginName}/runs/{runId}
   * @param {string} runId - 运行 ID
   * @param {HTMLElement} logPanel - createRunLog 返回的面板
   * @param {Object} [options]
   * @param {number} [options.interval] - 轮询间隔(毫秒),默认 1500
   * @param {Function} [options.onRunComplete] - run 完成回调,参数 (run)
   * @param {Function} [options.onError] - 轮询失败回调,参数 (error)
   */
  function pollRunEvents(pluginName, runId, logPanel, options = {}) {
    const state = logPanel._runLogState;
    if (!state) return;

    // 清理旧轮询
    if (state.pollingTimer) {
      clearInterval(state.pollingTimer);
      state.pollingTimer = null;
    }

    state.pluginName = pluginName;
    state.runId = runId;

    const interval = options.interval || 1500;

    // 更新状态指示器
    state.statusBar.querySelector(".run-log-status-text").textContent = "运行中...";
    state.statusBar.querySelector(".run-log-status-dot").className =
      "run-log-status-dot run-log-status-dot--running";

    // 真后端 run 日志路径由 app/api/plugin_runs.py 提供,前缀 /api/plugins/{pluginName}/runs/{runId}
    const runBase = `/api/plugins/${pluginName}/runs/${runId}`;

    const poll = async () => {
      try {
        // 获取 run 状态
        const runResp = await request(runBase);
        const runStatus = runResp.status;

        // 获取事件列表
        const eventsResp = await request(`${runBase}/events`);
        const events = eventsResp.events || [];

        for (const event of events) {
          _renderEvent(logPanel, event);
        }

        // 检查是否完成
        if (runStatus === "succeeded" || runStatus === "failed") {
          clearInterval(state.pollingTimer);
          state.pollingTimer = null;

          const dot = state.statusBar.querySelector(".run-log-status-dot");
          const text = state.statusBar.querySelector(".run-log-status-text");

          if (runStatus === "succeeded") {
            dot.className = "run-log-status-dot run-log-status-dot--done";
            text.textContent = "运行完成";
          } else {
            dot.className = "run-log-status-dot run-log-status-dot--error";
            text.textContent = runResp.error
              ? `运行失败: ${runResp.error}`
              : "运行失败";
          }

          if (options.onRunComplete) {
            options.onRunComplete(runResp);
          }
        }
      } catch (err) {
        // 轮询失败不清空已有日志,仅在状态栏显示错误
        state.statusBar.querySelector(".run-log-status-dot").className =
          "run-log-status-dot run-log-status-dot--error";
        state.statusBar.querySelector(".run-log-status-text").textContent =
          `轮询错误: ${err.message}`;

        if (options.onError) {
          options.onError(err);
        }
      }
    };

    // 立即执行一次
    poll();
    // 定时轮询
    state.pollingTimer = setInterval(poll, interval);
  }

  /**
   * 停止当前日志面板的轮询。
   *
   * @param {HTMLElement} logPanel - createRunLog 返回的面板
   */
  function stopPolling(logPanel) {
    const state = logPanel._runLogState;
    if (state && state.pollingTimer) {
      clearInterval(state.pollingTimer);
      state.pollingTimer = null;
    }
  }

  /**
   * 渲染 artifact 下载链接。
   *
   * @param {Object} artifact - artifact 元数据 {artifact_id, filename, media_type, size}
   * @param {HTMLElement} container - 容器元素
   * @param {string} pluginName - 插件名(如 "audio")
   * @param {string} runId - 运行 ID
   * @returns {HTMLElement} artifact 项 DOM
   */
  function renderArtifactLink(artifact, container, pluginName, runId) {
    const item = document.createElement("div");
    item.className = "plugin-item";

    const info = document.createElement("div");
    info.innerHTML = `
      <strong>${escapeHtml(artifact.filename)}</strong>
      <div class="plugin-muted" style="font-size:12px">${fileSize(artifact.size)} · ${escapeHtml(artifact.media_type)}</div>
    `;
    item.appendChild(info);

    const btn = document.createElement("button");
    btn.className = "plugin-button secondary";
    btn.textContent = "下载";
    btn.addEventListener("click", async () => {
      try {
        const blob = await requestBlob(
          `/api/plugins/${pluginName}/runs/${runId}/artifacts/${artifact.artifact_id}/download`
        );
        downloadBlob(blob, artifact.filename);
      } catch (err) {
        alert(`下载失败: ${err.message}`);
      }
    });
    item.appendChild(btn);

    container.appendChild(item);
    return item;
  }

  /** HTML 转义辅助 */
  function escapeHtml(str) {
    if (!str) return "";
    const el = document.createElement("span");
    el.textContent = str;
    return el.innerHTML;
  }

  return {
    request,
    requestBlob,
    showMessage,
    clearMessage,
    setText,
    setJson,
    downloadBlob,
    fileSize,
    copyText,
    createRunLog,
    pollRunEvents,
    stopPolling,
    renderArtifactLink,
    escapeHtml,
  };
})();