dsh-automations 0.0.0-stage → 0.2.0

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/lib/client.js ADDED
@@ -0,0 +1,961 @@
1
+ /**
2
+ * dsh-automations — browser half.
3
+ *
4
+ * Two registrations:
5
+ * - `sidebar.panellist` / id `automations` — the glyph in the left rail;
6
+ * - `main` / key `automations` — the page that rail entry opens.
7
+ *
8
+ * No build step: the module loader hands us React and we create elements
9
+ * directly. All data comes from the host half's JSON API, polled while the page
10
+ * is visible; the panel owns no durable state of its own.
11
+ *
12
+ * @module dsh-automations/client
13
+ */
14
+
15
+ window.__ModuleLoader__.load({
16
+ id: "dsh-automations",
17
+ factory: (require) => {
18
+ var module = { exports: {} };
19
+ var exports = module.exports;
20
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
21
+
22
+ const React = require("react");
23
+ const h = React.createElement;
24
+ const { useCallback, useEffect, useMemo, useRef, useState } = React;
25
+
26
+ /** Sidebar cell id === main-panel key. */
27
+ const PANEL_ID = "automations";
28
+ /** Host API prefix. */
29
+ const API = "/api/dsh-automations";
30
+ /** Poll interval while the page is visible. */
31
+ const POLL_MS = 4000;
32
+
33
+ //#region labels
34
+ /** Browser-level fallback; the host locale service overrides it when present. */
35
+ const FALLBACK_LANG = (typeof navigator !== "undefined" ? navigator.language : "") || (typeof document !== "undefined" ? document.documentElement.lang : "") || "en";
36
+ /** Active language flag; the panel updates it from `locale` and re-renders. */
37
+ let ZH = /^zh/i.test(FALLBACK_LANG);
38
+
39
+ /**
40
+ * @param {string} id - locale id.
41
+ * @returns {boolean} whether the flag changed.
42
+ */
43
+ function applyLocaleId(id) {
44
+ const next = /^zh/i.test(String(id ?? "")) || (String(id ?? "") === "" && /^zh/i.test(FALLBACK_LANG));
45
+ const changed = next !== ZH;
46
+ ZH = next;
47
+ return changed;
48
+ }
49
+
50
+ /** Bilingual literal. */
51
+ const T = (zh, en) => (ZH ? zh : en);
52
+
53
+ const STATUS_LABEL = {
54
+ ok: () => T("成功", "ok"),
55
+ error: () => T("失败", "failed"),
56
+ timeout: () => T("超时", "timeout"),
57
+ skipped: () => T("跳过", "skipped"),
58
+ };
59
+
60
+ /** Localised catalog label with an English fallback. */
61
+ function catalogLabel(entry) {
62
+ if (entry === undefined) return "";
63
+ return ZH ? entry.label : entry.labelEn ?? entry.label;
64
+ }
65
+
66
+ /** Localised catalog hint. */
67
+ function catalogHint(entry) {
68
+ if (entry === undefined) return "";
69
+ return ZH ? entry.hint : entry.hintEn ?? entry.hint;
70
+ }
71
+
72
+ /** Localised field label. */
73
+ function fieldLabel(field) {
74
+ return ZH ? field.label : field.labelEn ?? field.label;
75
+ }
76
+
77
+ /** Localised option label. */
78
+ function optionLabel(option) {
79
+ return ZH ? option.label : option.labelEn ?? option.label;
80
+ }
81
+ //#endregion
82
+
83
+ //#region styles
84
+ const CSS = [
85
+ ".dsha_root{height:100%;box-sizing:border-box;overflow:auto;padding:22px 26px 64px;font-family:inherit;font-size:13px;line-height:1.55;color:var(--dsw-alias-label-primary,#e6e8ee)}",
86
+ ".dsha_inner{max-width:920px;margin:0 auto}",
87
+ ".dsha_head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:16px}",
88
+ ".dsha_h1{margin:0 0 3px;font-size:19px;font-weight:600;letter-spacing:.01em}",
89
+ ".dsha_sub{margin:0;font-size:12.5px;color:var(--dsw-alias-label-secondary,#8a8f98)}",
90
+ ".dsha_btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.28));border-radius:6px;background:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.08));color:inherit;font:inherit;font-size:12.5px;line-height:18px;padding:5px 11px;cursor:pointer;white-space:nowrap;transition:background .15s ease,border-color .15s ease,opacity .15s ease}",
91
+ ".dsha_btn:hover{background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.16))}",
92
+ ".dsha_btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5b8def);outline-offset:1px}",
93
+ ".dsha_btn[disabled]{opacity:.5;cursor:not-allowed}",
94
+ ".dsha_btn.primary{background:var(--dsw-alias-brand-primary,#5b8def);border-color:transparent;color:#fff}",
95
+ ".dsha_btn.primary:hover{filter:brightness(1.06)}",
96
+ ".dsha_btn.ghost{background:transparent;border-color:transparent;color:var(--dsw-alias-label-secondary,#8a8f98)}",
97
+ ".dsha_btn.ghost:hover{background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.16));color:var(--dsw-alias-label-primary,#e6e8ee)}",
98
+ ".dsha_btn.danger:hover{color:var(--dsw-alias-state-error-primary,#e5534b)}",
99
+ ".dsha_stats{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:20px}",
100
+ ".dsha_stat{flex:1 1 150px;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22));border-radius:8px;padding:9px 12px;background:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.05))}",
101
+ ".dsha_stat b{display:block;font-size:17px;font-weight:600;line-height:1.35}",
102
+ ".dsha_stat span{font-size:11.5px;color:var(--dsw-alias-label-secondary,#8a8f98)}",
103
+ ".dsha_section{margin-top:22px}",
104
+ ".dsha_h2{display:flex;align-items:center;gap:8px;margin:0 0 10px;font-size:12.5px;font-weight:600;color:var(--dsw-alias-label-secondary,#8a8f98);text-transform:none}",
105
+ ".dsha_tabs{display:flex;gap:4px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22));margin:0 0 16px}",
106
+ ".dsha_tab{appearance:none;display:inline-flex;align-items:center;gap:6px;border:none;border-bottom:2px solid transparent;background:transparent;color:var(--dsw-alias-label-secondary,#8a8f98);font:inherit;font-size:13px;padding:7px 10px;margin-bottom:-1px;cursor:pointer}",
107
+ ".dsha_tab:hover{color:var(--dsw-alias-label-primary,#e6e8ee)}",
108
+ ".dsha_tab:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5b8def);outline-offset:-2px}",
109
+ ".dsha_tab[aria-selected=true]{color:var(--dsw-alias-label-primary,#e6e8ee);border-bottom-color:var(--dsw-alias-brand-primary,#5b8def)}",
110
+ ".dsha_tab .dsha_badge{font-size:10px;padding:0 6px}",
111
+ ".dsha_runrow .dsha_badge{flex:none;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
112
+ ".dsha_runmeta{padding:6px 11px;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18));font-size:11.5px;color:var(--dsw-alias-label-secondary,#8a8f98);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
113
+ ".dsha_runbox .dsha_pre{border-top:none}",
114
+ ".dsha_card{display:flex;align-items:flex-start;gap:12px;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22));border-radius:10px;background:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.05));padding:12px 14px;margin-bottom:8px}",
115
+ ".dsha_card[data-off=true]{opacity:.55}",
116
+ ".dsha_glyph{flex:none;width:30px;height:30px;border-radius:8px;display:flex;align-items:center;justify-content:center;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.14));color:var(--dsw-alias-brand-primary,#5b8def)}",
117
+ ".dsha_cardmain{flex:1 1 auto;min-width:0}",
118
+ ".dsha_cardtitle{display:flex;align-items:center;gap:8px;font-weight:600;font-size:13.5px}",
119
+ ".dsha_badge{flex:none;font-size:10.5px;font-weight:500;padding:1px 7px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.28));color:var(--dsw-alias-label-secondary,#8a8f98);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.1))}",
120
+ ".dsha_cardline{margin-top:3px;font-size:12px;color:var(--dsw-alias-label-secondary,#8a8f98);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
121
+ ".dsha_cardmeta{margin-top:2px;font-size:11px;color:var(--dsw-alias-label-secondary,#8a8f98);opacity:.85}",
122
+ ".dsha_cardactions{flex:none;display:flex;align-items:center;gap:6px}",
123
+ ".dsha_dot{width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-state-idle-primary,#8a8f98);flex:none}",
124
+ ".dsha_dot[data-status=ok]{background:var(--dsw-alias-state-success-primary,#34a853)}",
125
+ ".dsha_dot[data-status=error]{background:var(--dsw-alias-state-error-primary,#e5534b)}",
126
+ ".dsha_dot[data-status=timeout]{background:var(--dsw-alias-state-warn-primary,#e0a03a)}",
127
+ ".dsha_switch{position:relative;flex:none;width:32px;height:18px;border-radius:999px;border:none;padding:0;cursor:pointer;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.28));transition:background .15s ease}",
128
+ ".dsha_switch::after{content:\"\";position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:#fff;transition:transform .15s ease}",
129
+ ".dsha_switch[aria-checked=true]{background:var(--dsw-alias-brand-primary,#5b8def)}",
130
+ ".dsha_switch[aria-checked=true]::after{transform:translateX(14px)}",
131
+ ".dsha_empty{border:1px dashed var(--dsw-alias-border-l2,rgba(127,127,127,.35));border-radius:10px;padding:18px;text-align:center;color:var(--dsw-alias-label-secondary,#8a8f98);font-size:12.5px}",
132
+ ".dsha_tpls{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;margin-top:12px}",
133
+ ".dsha_tpl{box-sizing:border-box;text-align:left;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22));border-radius:9px;background:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.05));padding:11px 12px;cursor:pointer;color:inherit;font:inherit;transition:border-color .15s ease,background .15s ease}",
134
+ ".dsha_tpl:hover{border-color:var(--dsw-alias-brand-primary,#5b8def);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.1))}",
135
+ ".dsha_tpl b{display:block;font-size:12.5px;margin-bottom:3px}",
136
+ ".dsha_tpl span{font-size:11.5px;color:var(--dsw-alias-label-secondary,#8a8f98)}",
137
+ ".dsha_runs{display:flex;flex-direction:column;gap:6px}",
138
+ ".dsha_runbox{border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18));border-radius:8px;background:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.04));overflow:hidden}",
139
+ ".dsha_runrow{display:flex;align-items:center;gap:10px;padding:7px 11px;font-size:12px;cursor:pointer}",
140
+ ".dsha_runrow:hover{background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08))}",
141
+ ".dsha_runat{flex:none;width:112px;color:var(--dsw-alias-label-secondary,#8a8f98);font-variant-numeric:tabular-nums}",
142
+ ".dsha_runname{flex:0 1 auto;max-width:45%;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
143
+ ".dsha_runstatus{flex:none;width:56px;font-size:11.5px}",
144
+ ".dsha_runstatus[data-status=ok]{color:var(--dsw-alias-state-success-primary,#34a853)}",
145
+ ".dsha_runstatus[data-status=error]{color:var(--dsw-alias-state-error-primary,#e5534b)}",
146
+ ".dsha_runstatus[data-status=timeout]{color:var(--dsw-alias-state-warn-primary,#e0a03a)}",
147
+ ".dsha_rundur{flex:none;width:64px;text-align:right;color:var(--dsw-alias-label-secondary,#8a8f98);font-variant-numeric:tabular-nums}",
148
+ ".dsha_pre{margin:0;padding:9px 11px;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.18));font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:11.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word;max-height:260px;overflow:auto;color:var(--dsw-alias-label-secondary,#b9bec8)}",
149
+ ".dsha_backdrop{position:fixed;inset:0;z-index:2147482000;display:flex;align-items:center;justify-content:center;padding:26px;background:rgba(0,0,0,.45)}",
150
+ ".dsha_modal{box-sizing:border-box;width:min(760px,100%);max-height:90vh;overflow:auto;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.4));border-radius:12px;background:var(--dsw-alias-bg-overlay,#1f2430);box-shadow:0 18px 60px rgba(0,0,0,.45);padding:18px 20px 16px}",
151
+ ".dsha_modaltitle{margin:0 0 2px;font-size:15px;font-weight:600}",
152
+ ".dsha_modalsub{margin:0 0 14px;font-size:11.5px;color:var(--dsw-alias-label-secondary,#8a8f98)}",
153
+ ".dsha_grid{display:grid;grid-template-columns:1fr 1fr;gap:11px 14px}",
154
+ ".dsha_field{display:flex;flex-direction:column;gap:4px;min-width:0}",
155
+ ".dsha_field.wide{grid-column:1/-1}",
156
+ ".dsha_label{font-size:11.5px;color:var(--dsw-alias-label-secondary,#8a8f98)}",
157
+ ".dsha_input,.dsha_select,.dsha_textarea{box-sizing:border-box;width:100%;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.3));border-radius:6px;background:var(--dsw-alias-bg-base,rgba(0,0,0,.16));color:inherit;font:inherit;font-size:12.5px;padding:6px 8px}",
158
+ ".dsha_input:focus,.dsha_select:focus,.dsha_textarea:focus{outline:none;border-color:var(--dsw-alias-brand-primary,#5b8def)}",
159
+ ".dsha_textarea{resize:vertical;min-height:62px;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12px;line-height:1.5}",
160
+ ".dsha_hint{font-size:11px;color:var(--dsw-alias-label-secondary,#8a8f98);opacity:.85}",
161
+ ".dsha_days{display:flex;gap:5px;flex-wrap:wrap}",
162
+ ".dsha_day{border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.3));background:transparent;color:inherit;border-radius:5px;font:inherit;font-size:11.5px;padding:3px 8px;cursor:pointer}",
163
+ ".dsha_day[aria-pressed=true]{background:var(--dsw-alias-brand-primary,#5b8def);border-color:transparent;color:#fff}",
164
+ ".dsha_footer{display:flex;align-items:center;gap:8px;margin-top:16px;padding-top:12px;border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.2))}",
165
+ ".dsha_grow{flex:1 1 auto}",
166
+ ".dsha_err{margin-top:10px;font-size:12px;color:var(--dsw-alias-state-error-primary,#e5534b);white-space:pre-wrap}",
167
+ ".dsha_testres{margin-top:10px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.25));border-radius:8px;overflow:hidden}",
168
+ ".dsha_testhead{display:flex;gap:8px;align-items:center;padding:6px 10px;font-size:12px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.1))}",
169
+ ".dsha_toast{position:fixed;left:50%;bottom:26px;transform:translateX(-50%);z-index:2147483000;max-width:min(560px,90vw);padding:8px 14px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.4));background:var(--dsw-alias-bg-overlay,#1f2430);color:var(--dsw-alias-label-primary,#e6e8ee);box-shadow:0 10px 30px rgba(0,0,0,.4);font-size:12.5px}",
170
+ ".dsha_toast[data-kind=error]{border-color:var(--dsw-alias-state-error-primary,#e5534b)}",
171
+ ".dsha_loading{padding:40px 0;text-align:center;color:var(--dsw-alias-label-secondary,#8a8f98);font-size:12.5px}",
172
+ ].join("\n");
173
+ const CSS_ID = "dsh-automations/panel.css";
174
+ if (typeof document !== "undefined" && document.querySelector(`style[data-plugin-css=${JSON.stringify(CSS_ID)}]`) === null) {
175
+ const tag = document.createElement("style");
176
+ tag.dataset.plugin = "dsh-automations";
177
+ tag.dataset.pluginCss = CSS_ID;
178
+ tag.textContent = CSS;
179
+ document.head.appendChild(tag);
180
+ }
181
+ //#endregion
182
+
183
+ //#region api
184
+ /**
185
+ * Read one JSON endpoint.
186
+ *
187
+ * @param {string} path - suffix under /api/dsh-automations.
188
+ * @returns {Promise<any>}
189
+ */
190
+ async function apiGet(path) {
191
+ const response = await fetch(API + path, { headers: { accept: "application/json" } });
192
+ const body = await response.json().catch(() => null);
193
+ if (!response.ok || body === null || body.ok !== true) {
194
+ throw new Error(body?.error?.message ?? `HTTP ${response.status}`);
195
+ }
196
+ return body.value;
197
+ }
198
+
199
+ /**
200
+ * Post one JSON body.
201
+ *
202
+ * @param {string} path - suffix under /api/dsh-automations.
203
+ * @param {object} payload - JSON body.
204
+ * @returns {Promise<any>}
205
+ */
206
+ async function apiPost(path, payload) {
207
+ const response = await fetch(API + path, {
208
+ method: "POST",
209
+ headers: { "content-type": "application/json", accept: "application/json" },
210
+ body: JSON.stringify(payload ?? {}),
211
+ });
212
+ const body = await response.json().catch(() => null);
213
+ if (!response.ok || body === null || body.ok !== true) {
214
+ throw new Error(body?.error?.message ?? `HTTP ${response.status}`);
215
+ }
216
+ return body.value;
217
+ }
218
+ //#endregion
219
+
220
+ //#region formatting
221
+ /**
222
+ * @param {string} iso - instant.
223
+ * @returns {string} local clock/date.
224
+ */
225
+ function fmtClock(iso) {
226
+ const date = new Date(iso);
227
+ if (Number.isNaN(date.getTime())) return "";
228
+ const now = new Date();
229
+ const sameDay = date.toDateString() === now.toDateString();
230
+ return sameDay
231
+ ? date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
232
+ : date.toLocaleString([], { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
233
+ }
234
+
235
+ /**
236
+ * @param {string} iso - instant.
237
+ * @returns {string} relative time.
238
+ */
239
+ function fmtRelative(iso) {
240
+ const at = Date.parse(iso ?? "");
241
+ if (!Number.isFinite(at)) return "";
242
+ const diff = Date.now() - at;
243
+ if (diff < 0) return T("即将", "soon");
244
+ if (diff < 60_000) return T("刚刚", "just now");
245
+ if (diff < 3_600_000) return T(`${Math.floor(diff / 60_000)} 分钟前`, `${Math.floor(diff / 60_000)}m ago`);
246
+ if (diff < 86_400_000) return T(`${Math.floor(diff / 3_600_000)} 小时前`, `${Math.floor(diff / 3_600_000)}h ago`);
247
+ return T(`${Math.floor(diff / 86_400_000)} 天前`, `${Math.floor(diff / 86_400_000)}d ago`);
248
+ }
249
+
250
+ /**
251
+ * @param {number} ms - duration.
252
+ * @returns {string} compact duration.
253
+ */
254
+ function fmtDuration(ms) {
255
+ const value = Math.max(0, Number(ms) || 0);
256
+ if (value < 1000) return `${Math.round(value)}ms`;
257
+ if (value < 60_000) return `${(value / 1000).toFixed(1)}s`;
258
+ return `${Math.floor(value / 60_000)}m${String(Math.round((value % 60_000) / 1000)).padStart(2, "0")}s`;
259
+ }
260
+
261
+ /**
262
+ * @param {string} status - run status.
263
+ * @returns {string} localised label.
264
+ */
265
+ function statusLabel(status) {
266
+ return (STATUS_LABEL[status] ?? (() => status))();
267
+ }
268
+ //#endregion
269
+
270
+ //#region icons
271
+ /** The sidebar glyph (lightning bolt). */
272
+ function AutomationIcon(props) {
273
+ const size = typeof props?.size === "number" ? props.size : 18;
274
+ return h(
275
+ "svg",
276
+ { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" },
277
+ h("path", { d: "M13 2 4 14h6l-1 8 10-12h-6l1-8Z" }),
278
+ );
279
+ }
280
+
281
+ /** Per-trigger glyph. */
282
+ function TriggerGlyph({ type, size = 16 }) {
283
+ const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" };
284
+ switch (type) {
285
+ case "session-start":
286
+ return h("svg", common, h("path", { d: "M8 5v14l11-7L8 5Z" }));
287
+ case "session-idle":
288
+ return h("svg", common, h("path", { d: "M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z" }));
289
+ case "session-end":
290
+ return h("svg", common, h("path", { d: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" }), h("path", { d: "m16 17 5-5-5-5" }), h("path", { d: "M21 12H9" }));
291
+ case "user-message":
292
+ return h("svg", common, h("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2Z" }));
293
+ case "tool-after":
294
+ return h("svg", common, h("path", { d: "M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.6 2.6-2-2 2.6-2.6Z" }));
295
+ case "daily":
296
+ case "interval":
297
+ return h("svg", common, h("circle", { cx: 12, cy: 12, r: 9 }), h("path", { d: "M12 7v5l3 2" }));
298
+ case "manual":
299
+ return h("svg", common, h("path", { d: "M9 11V5a2 2 0 1 1 4 0v6" }), h("path", { d: "M13 11V7a2 2 0 1 1 4 0v7a6 6 0 0 1-6 6h-1a6 6 0 0 1-4.6-2.1L3 14.5a2 2 0 0 1 3-2.6L8 14" }));
300
+ default:
301
+ return h("svg", common, h("path", { d: "M13 2 4 14h6l-1 8 10-12h-6l1-8Z" }));
302
+ }
303
+ }
304
+
305
+ /** Small action glyph. */
306
+ function PlayGlyph({ size = 14 }) {
307
+ return h("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "currentColor", "aria-hidden": "true" }, h("path", { d: "M8 5v14l11-7L8 5Z" }));
308
+ }
309
+
310
+ /** Trash glyph. */
311
+ function TrashGlyph({ size = 14 }) {
312
+ return h("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" }, h("path", { d: "M3 6h18" }), h("path", { d: "M8 6V4h8v2" }), h("path", { d: "M19 6l-1 14H6L5 6" }));
313
+ }
314
+ //#endregion
315
+
316
+ //#region draft
317
+ /**
318
+ * @returns {object} a blank editor draft.
319
+ */
320
+ function emptyDraft() {
321
+ return {
322
+ id: "",
323
+ name: "",
324
+ enabled: true,
325
+ cooldownSeconds: 0,
326
+ triggerType: "startup",
327
+ trigger: { delayMs: 1500, source: "any", idleSeconds: 600, mode: "any", match: "", tool: "*", when: "always", time: "08:30", weekdays: [], minutes: 60 },
328
+ actionType: "shell",
329
+ action: { command: "", cwd: "", shell: "auto", timeoutMs: 60000, url: "", method: "GET", headers: "{}", body: "", message: "" },
330
+ };
331
+ }
332
+
333
+ /**
334
+ * @param {object} rule - stored rule.
335
+ * @returns {object} an editor draft bound to that rule.
336
+ */
337
+ function draftFromRule(rule) {
338
+ const base = emptyDraft();
339
+ return {
340
+ ...base,
341
+ id: rule.id,
342
+ name: rule.name,
343
+ enabled: rule.enabled !== false,
344
+ cooldownSeconds: rule.cooldownSeconds ?? 0,
345
+ triggerType: rule.trigger.type,
346
+ trigger: { ...base.trigger, ...rule.trigger },
347
+ actionType: rule.action.type,
348
+ action: { ...base.action, ...rule.action },
349
+ };
350
+ }
351
+
352
+ /**
353
+ * Build the server payload from a draft.
354
+ *
355
+ * @param {object} draft - editor draft.
356
+ * @returns {object}
357
+ */
358
+ function payloadFromDraft(draft) {
359
+ return {
360
+ id: draft.id === "" ? undefined : draft.id,
361
+ name: draft.name,
362
+ enabled: draft.enabled,
363
+ cooldownSeconds: Number(draft.cooldownSeconds) || 0,
364
+ trigger: { ...draft.trigger, type: draft.triggerType },
365
+ action: { ...draft.action, type: draft.actionType },
366
+ };
367
+ }
368
+ //#endregion
369
+
370
+ //#region form pieces
371
+ /**
372
+ * One labelled form control.
373
+ *
374
+ * @param {{field: object, value: unknown, onChange: (value: unknown) => void}} props
375
+ */
376
+ function FieldControl({ field, value, onChange }) {
377
+ const id = `dsha-${field.key}`;
378
+ if (field.type === "select") {
379
+ return h(
380
+ "select",
381
+ { id, className: "dsha_select", value: String(value ?? ""), onChange: (event) => onChange(event.target.value) },
382
+ (field.options ?? []).map((option) => h("option", { key: option.value, value: option.value }, optionLabel(option))),
383
+ );
384
+ }
385
+ if (field.type === "textarea") {
386
+ return h("textarea", { id, className: "dsha_textarea", value: String(value ?? ""), placeholder: field.placeholder ?? "", spellCheck: false, onChange: (event) => onChange(event.target.value) });
387
+ }
388
+ if (field.type === "int") {
389
+ return h("input", { id, className: "dsha_input", type: "number", min: field.min, max: field.max, value: String(value ?? ""), onChange: (event) => onChange(event.target.value === "" ? "" : Number(event.target.value)) });
390
+ }
391
+ if (field.type === "time") {
392
+ return h("input", { id, className: "dsha_input", type: "time", value: String(value ?? ""), onChange: (event) => onChange(event.target.value) });
393
+ }
394
+ if (field.type === "weekdays") {
395
+ const selected = Array.isArray(value) ? value : [];
396
+ const names = [T("一", "Mo"), T("二", "Tu"), T("三", "We"), T("四", "Th"), T("五", "Fr"), T("六", "Sa"), T("日", "Su")];
397
+ return h(
398
+ "div",
399
+ { className: "dsha_days" },
400
+ names.map((name, index) => {
401
+ const day = index + 1;
402
+ return h(
403
+ "button",
404
+ {
405
+ key: day,
406
+ type: "button",
407
+ className: "dsha_day",
408
+ "aria-pressed": selected.includes(day),
409
+ onClick: () => onChange(selected.includes(day) ? selected.filter((entry) => entry !== day) : [...selected, day].sort((a, b) => a - b)),
410
+ },
411
+ name,
412
+ );
413
+ }),
414
+ );
415
+ }
416
+ return h("input", { id, className: "dsha_input", type: "text", value: String(value ?? ""), placeholder: field.placeholder ?? "", onChange: (event) => onChange(event.target.value) });
417
+ }
418
+
419
+ /**
420
+ * A field row (label + control + hint).
421
+ *
422
+ * @param {{field: object, value: unknown, onChange: (value: unknown) => void, wide?: boolean}} props
423
+ */
424
+ function FieldRow({ field, value, onChange, wide }) {
425
+ return h(
426
+ "div",
427
+ { className: `dsha_field${wide === true ? " wide" : ""}` },
428
+ h("label", { className: "dsha_label", htmlFor: `dsha-${field.key}` }, fieldLabel(field)),
429
+ h(FieldControl, { field, value, onChange }),
430
+ field.hint ? h("span", { className: "dsha_hint" }, field.hint) : null,
431
+ );
432
+ }
433
+
434
+ /** Section heading inside the editor. */
435
+ function FormGroup({ title, children }) {
436
+ return h("div", { className: "dsha_field wide", style: { gap: "8px" } }, h("span", { className: "dsha_label", style: { fontWeight: 600, color: "inherit" } }, title), children);
437
+ }
438
+ //#endregion
439
+
440
+ //#region editor
441
+ /**
442
+ * The rule editor modal.
443
+ *
444
+ * @param {{draft: object, setDraft: Function, catalog: object, saving: boolean, testResult: object|null, error: string, onClose: Function, onSave: Function, onTest: Function}} props
445
+ */
446
+ function Editor(props) {
447
+ const { draft, setDraft, catalog, saving, testResult, error, onClose, onSave, onTest } = props;
448
+ const triggerSpec = useMemo(() => (catalog?.triggers ?? []).find((entry) => entry.type === draft.triggerType), [catalog, draft.triggerType]);
449
+ const actionSpec = useMemo(() => (catalog?.actions ?? []).find((entry) => entry.type === draft.actionType), [catalog, draft.actionType]);
450
+
451
+ useEffect(() => {
452
+ const onKey = (event) => {
453
+ if (event.key === "Escape") onClose();
454
+ };
455
+ window.addEventListener("keydown", onKey);
456
+ return () => window.removeEventListener("keydown", onKey);
457
+ }, [onClose]);
458
+
459
+ const patch = (changes) => setDraft({ ...draft, ...changes });
460
+ const patchTrigger = (key, value) => setDraft({ ...draft, trigger: { ...draft.trigger, [key]: value } });
461
+ const patchAction = (key, value) => setDraft({ ...draft, action: { ...draft.action, [key]: value } });
462
+ const canSave = String(draft.name ?? "").trim() !== "";
463
+
464
+ return h(
465
+ "div",
466
+ {
467
+ className: "dsha_backdrop",
468
+ role: "presentation",
469
+ onMouseDown: (event) => {
470
+ if (event.target === event.currentTarget) onClose();
471
+ },
472
+ },
473
+ h(
474
+ "div",
475
+ { className: "dsha_modal", role: "dialog", "aria-modal": "true", "aria-label": T("编辑自动化规则", "Edit automation rule") },
476
+ h("h3", { className: "dsha_modaltitle" }, draft.id === "" ? T("新建自动化规则", "New automation") : T("编辑自动化规则", "Edit automation")),
477
+ h("p", { className: "dsha_modalsub" }, T("选一个时机,再选它要做的事。命令在宿主进程里以非交互方式运行。", "Pick a moment, then what it should do. Commands run non-interactively in the host process.")),
478
+
479
+ h(
480
+ "div",
481
+ { className: "dsha_grid" },
482
+ h(FieldRow, { wide: true, field: { key: "name", label: "名称", labelEn: "Name", type: "text", placeholder: T("例如:开机预热本地模型", "e.g. Warm up the local model on boot") }, value: draft.name, onChange: (value) => patch({ name: value }) }),
483
+
484
+ h(
485
+ "div",
486
+ { className: "dsha_field" },
487
+ h("label", { className: "dsha_label" }, T("触发时机", "Trigger")),
488
+ h("select", { className: "dsha_select", value: draft.triggerType, onChange: (event) => patch({ triggerType: event.target.value }) }, (catalog?.triggers ?? []).map((entry) => h("option", { key: entry.type, value: entry.type }, catalogLabel(entry)))),
489
+ triggerSpec ? h("span", { className: "dsha_hint" }, catalogHint(triggerSpec)) : null,
490
+ ),
491
+ h(
492
+ "div",
493
+ { className: "dsha_field" },
494
+ h("label", { className: "dsha_label" }, T("动作", "Action")),
495
+ h("select", { className: "dsha_select", value: draft.actionType, onChange: (event) => patch({ actionType: event.target.value }) }, (catalog?.actions ?? []).map((entry) => h("option", { key: entry.type, value: entry.type }, catalogLabel(entry)))),
496
+ actionSpec ? h("span", { className: "dsha_hint" }, catalogHint(actionSpec)) : null,
497
+ ),
498
+
499
+ (triggerSpec?.fields ?? []).map((field) => h(FieldRow, { key: `t-${field.key}`, field, value: draft.trigger[field.key], onChange: (value) => patchTrigger(field.key, value), wide: field.type === "weekdays" })),
500
+ h("div", { className: "dsha_field wide", style: { height: 1, background: "var(--dsw-alias-border-l1, rgba(127,127,127,.22))" } }),
501
+ (actionSpec?.fields ?? []).map((field) => h(FieldRow, {
502
+ key: `a-${field.key}`,
503
+ field,
504
+ value: draft.action[field.key],
505
+ onChange: (value) => patchAction(field.key, value),
506
+ wide: field.type === "textarea",
507
+ })),
508
+
509
+ h(
510
+ "div",
511
+ { className: "dsha_field" },
512
+ h("label", { className: "dsha_label" }, T("冷却时间(秒)", "Cooldown (seconds)")),
513
+ h("input", { className: "dsha_input", type: "number", min: 0, max: 86400, value: String(draft.cooldownSeconds ?? 0), onChange: (event) => patch({ cooldownSeconds: Number(event.target.value) || 0 }) }),
514
+ h("span", { className: "dsha_hint" }, T("两次运行的最小间隔;0 表示不限制", "Minimum gap between runs; 0 means none")),
515
+ ),
516
+ h(
517
+ "div",
518
+ { className: "dsha_field" },
519
+ h("label", { className: "dsha_label" }, T("启用", "Enabled")),
520
+ h("label", { style: { display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, cursor: "pointer" } },
521
+ h("input", { type: "checkbox", checked: draft.enabled !== false, onChange: (event) => patch({ enabled: event.target.checked }) }),
522
+ T("保存后立即生效", "Active as soon as it is saved"),
523
+ ),
524
+ ),
525
+ ),
526
+
527
+ error ? h("div", { className: "dsha_err", role: "alert" }, error) : null,
528
+
529
+ testResult
530
+ ? h(
531
+ "div",
532
+ { className: "dsha_testres" },
533
+ h("div", { className: "dsha_testhead" },
534
+ h("span", { className: "dsha_dot", "data-status": testResult.status }),
535
+ h("b", null, T("试运行", "Test run")),
536
+ h("span", { style: { color: "var(--dsw-alias-label-secondary)" } }, `${statusLabel(testResult.status)} · ${fmtDuration(testResult.durationMs)} · ${T("退出码", "exit")} ${testResult.exitCode ?? "-"}`),
537
+ ),
538
+ h("pre", { className: "dsha_pre" }, testResult.output || testResult.error || T("(无输出)", "(no output)")),
539
+ )
540
+ : null,
541
+
542
+ h(
543
+ "div",
544
+ { className: "dsha_footer" },
545
+ h("button", { type: "button", className: "dsha_btn ghost", onClick: onClose, disabled: saving }, T("取消", "Cancel")),
546
+ h("button", { type: "button", className: "dsha_btn", onClick: onTest, disabled: saving || !canSave }, T("试运行", "Test")),
547
+ h("span", { className: "dsha_grow" }),
548
+ h("button", { type: "button", className: "dsha_btn primary", onClick: onSave, disabled: saving || !canSave }, saving ? T("保存中…", "Saving…") : T("保存", "Save")),
549
+ ),
550
+ ),
551
+ );
552
+ }
553
+ //#endregion
554
+
555
+ //#region rules list
556
+ /**
557
+ * One rule card.
558
+ *
559
+ * @param {{rule: object, catalog: object, busyId: string, onRun: Function, onEdit: Function, onDelete: Function, onToggle: Function}} props
560
+ */
561
+ function RuleCard({ rule, catalog, busyId, onRun, onEdit, onDelete, onToggle }) {
562
+ const spec = (catalog?.triggers ?? []).find((entry) => entry.type === rule.trigger.type);
563
+ const last = rule.lastRun;
564
+ return h(
565
+ "div",
566
+ { className: "dsha_card", "data-off": rule.enabled === false ? "true" : "false", "data-rule-id": rule.id },
567
+ h("div", { className: "dsha_glyph" }, h(TriggerGlyph, { type: rule.trigger.type })),
568
+ h(
569
+ "div",
570
+ { className: "dsha_cardmain" },
571
+ h("div", { className: "dsha_cardtitle" },
572
+ h("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, rule.name),
573
+ h("span", { className: "dsha_badge" }, catalogLabel(spec)),
574
+ ),
575
+ h("div", { className: "dsha_cardline", title: rule.actionSummary }, ZH ? rule.triggerSummary : rule.triggerSummaryEn, h("span", { style: { opacity: 0.5 } }, " · "), ZH ? rule.actionSummary : rule.actionSummaryEn),
576
+ h(
577
+ "div",
578
+ { className: "dsha_cardmeta" },
579
+ last
580
+ ? h(React.Fragment, null,
581
+ h("span", { className: "dsha_dot", "data-status": last.status, style: { display: "inline-block", marginRight: 6, verticalAlign: "middle" } }),
582
+ `${statusLabel(last.status)} · ${fmtRelative(last.at)} · ${T("累计", "total")} ${rule.runCount ?? 0}`,
583
+ )
584
+ : T("尚未运行", "Never ran"),
585
+ ),
586
+ ),
587
+ h(
588
+ "div",
589
+ { className: "dsha_cardactions" },
590
+ h("button", { type: "button", className: "dsha_switch", role: "switch", "aria-checked": rule.enabled !== false, "aria-label": T("启用或停用", "Enable or disable"), onClick: () => onToggle(rule) }),
591
+ h("button", { type: "button", className: "dsha_btn ghost", title: T("立即运行", "Run now"), disabled: busyId === rule.id, onClick: () => onRun(rule) }, busyId === rule.id ? T("运行中…", "Running…") : h(React.Fragment, null, h(PlayGlyph), T("运行", "Run"))),
592
+ h("button", { type: "button", className: "dsha_btn ghost", title: T("编辑", "Edit"), onClick: () => onEdit(rule) }, T("编辑", "Edit")),
593
+ h("button", { type: "button", className: "dsha_btn ghost danger", title: T("删除", "Delete"), onClick: () => onDelete(rule) }, h(TrashGlyph)),
594
+ ),
595
+ );
596
+ }
597
+ //#endregion
598
+
599
+ //#region panel
600
+ /** @param {object | undefined} locale - client locale service. @returns {string} active locale id. */
601
+ function readActiveLocale(locale) {
602
+ try {
603
+ return String(locale?.getSnapshot?.()?.active ?? locale?.getLocale?.()?.active ?? "");
604
+ } catch {
605
+ return "";
606
+ }
607
+ }
608
+
609
+ /** Sidebar-selected page. */
610
+ function Panel(props) {
611
+ const locale = props?.locale;
612
+ const [view, setView] = useState(null);
613
+ const [localeId, setLocaleId] = useState(() => readActiveLocale(locale) || FALLBACK_LANG);
614
+
615
+ useEffect(() => {
616
+ const sync = () => {
617
+ const next = readActiveLocale(locale) || FALLBACK_LANG;
618
+ applyLocaleId(next);
619
+ setLocaleId(next);
620
+ };
621
+ sync();
622
+ const off = typeof locale?.subscribe === "function" ? locale.subscribe(sync) : null;
623
+ return () => {
624
+ if (typeof off === "function") off();
625
+ };
626
+ }, [locale]);
627
+ const [loadError, setLoadError] = useState("");
628
+ const [draft, setDraft] = useState(null);
629
+ const [saving, setSaving] = useState(false);
630
+ const [modalError, setModalError] = useState("");
631
+ const [testResult, setTestResult] = useState(null);
632
+ const [busyId, setBusyId] = useState("");
633
+ const [toast, setToast] = useState(null);
634
+ const [openRun, setOpenRun] = useState("");
635
+ const [tab, setTab] = useState(() => {
636
+ try {
637
+ return window.localStorage.getItem("dsha.tab") === "runs" ? "runs" : "rules";
638
+ } catch {
639
+ return "rules";
640
+ }
641
+ });
642
+ const toastTimer = useRef(null);
643
+
644
+ /** @param {"rules"|"runs"} next - tab to activate. */
645
+ const switchTab = useCallback((next) => {
646
+ setTab(next);
647
+ try {
648
+ window.localStorage.setItem("dsha.tab", next);
649
+ } catch {
650
+ /* storage may be unavailable */
651
+ }
652
+ }, []);
653
+
654
+ /** @param {string} message - toast text. @param {string} [kind] - error|info. */
655
+ const notify = useCallback((message, kind = "info") => {
656
+ setToast({ message, kind });
657
+ if (toastTimer.current !== null) window.clearTimeout(toastTimer.current);
658
+ toastTimer.current = window.setTimeout(() => setToast(null), 2600);
659
+ }, []);
660
+
661
+ useEffect(() => () => {
662
+ if (toastTimer.current !== null) window.clearTimeout(toastTimer.current);
663
+ }, []);
664
+
665
+ const refresh = useCallback(async (silent) => {
666
+ try {
667
+ const next = await apiGet("/state");
668
+ setView(next);
669
+ setLoadError("");
670
+ } catch (error) {
671
+ if (silent !== true) setLoadError(error instanceof Error ? error.message : String(error));
672
+ }
673
+ }, []);
674
+
675
+ useEffect(() => {
676
+ void refresh(false);
677
+ const timer = window.setInterval(() => {
678
+ if (document.hidden !== true) void refresh(true);
679
+ }, POLL_MS);
680
+ return () => window.clearInterval(timer);
681
+ }, [refresh]);
682
+
683
+ const defaultCwd = typeof view?.defaultCwd === "string" ? view.defaultCwd : "";
684
+
685
+ const openEditor = useCallback((rule) => {
686
+ let next;
687
+ if (rule === null || rule === undefined) {
688
+ next = emptyDraft();
689
+ if (defaultCwd !== "") next = { ...next, action: { ...next.action, cwd: defaultCwd } };
690
+ } else {
691
+ next = draftFromRule(rule);
692
+ }
693
+ setDraft(next);
694
+ setModalError("");
695
+ setTestResult(null);
696
+ }, [defaultCwd]);
697
+
698
+ const saveDraft = useCallback(async () => {
699
+ if (draft === null) return;
700
+ setSaving(true);
701
+ setModalError("");
702
+ try {
703
+ const result = await apiPost("/rules", { rule: payloadFromDraft(draft) });
704
+ setView(result.state);
705
+ setDraft(null);
706
+ notify(T("规则已保存", "Rule saved"));
707
+ } catch (error) {
708
+ setModalError(error instanceof Error ? error.message : String(error));
709
+ } finally {
710
+ setSaving(false);
711
+ }
712
+ }, [draft, notify]);
713
+
714
+ const testDraft = useCallback(async () => {
715
+ if (draft === null) return;
716
+ setSaving(true);
717
+ setModalError("");
718
+ try {
719
+ const result = await apiPost("/test", { rule: payloadFromDraft(draft) });
720
+ setTestResult(result.run);
721
+ } catch (error) {
722
+ setModalError(error instanceof Error ? error.message : String(error));
723
+ } finally {
724
+ setSaving(false);
725
+ }
726
+ }, [draft]);
727
+
728
+ const toggleRule = useCallback(async (rule) => {
729
+ try {
730
+ const result = await apiPost("/rules/toggle", { id: rule.id, enabled: rule.enabled === false });
731
+ setView(result.state);
732
+ } catch (error) {
733
+ notify(error instanceof Error ? error.message : String(error), "error");
734
+ }
735
+ }, [notify]);
736
+
737
+ const runRule = useCallback(async (rule) => {
738
+ setBusyId(rule.id);
739
+ try {
740
+ const result = await apiPost("/run", { id: rule.id });
741
+ setView(result.state);
742
+ const run = result.run;
743
+ notify(`${rule.name}:${statusLabel(run.status)} · ${fmtDuration(run.durationMs)}`, run.status === "ok" ? "info" : "error");
744
+ setOpenRun(run.id);
745
+ } catch (error) {
746
+ notify(error instanceof Error ? error.message : String(error), "error");
747
+ } finally {
748
+ setBusyId("");
749
+ }
750
+ }, [notify]);
751
+
752
+ const deleteRule = useCallback(async (rule) => {
753
+ const ok = window.confirm(T(`删除「${rule.name}」?`, `Delete "${rule.name}"?`));
754
+ if (!ok) return;
755
+ try {
756
+ const result = await apiPost("/rules/delete", { id: rule.id });
757
+ setView(result.state);
758
+ notify(T("已删除", "Deleted"));
759
+ } catch (error) {
760
+ notify(error instanceof Error ? error.message : String(error), "error");
761
+ }
762
+ }, [notify]);
763
+
764
+ const rules = view?.rules ?? [];
765
+ const runs = view?.runs ?? [];
766
+ const stats = view?.stats ?? { total: 0, enabled: 0, runsToday: 0, lastRunAt: null, busy: 0 };
767
+ const catalog = view?.catalog ?? { triggers: [], actions: [] };
768
+ /** @param {string} type - trigger type. @returns {string} localised trigger name. */
769
+ const triggerNameOf = (type) => {
770
+ const spec = (catalog.triggers ?? []).find((entry) => entry.type === type);
771
+ return spec ? catalogLabel(spec) : String(type ?? "");
772
+ };
773
+
774
+ const templates = useMemo(() => [
775
+ {
776
+ key: "startup-log",
777
+ title: T("DSH 启动时记录", "Log on DSH startup"),
778
+ desc: T("往 ~\\dsh-boot.log 追加一行启动时间", "Append the boot time to ~\\dsh-boot.log"),
779
+ build: () => ({
780
+ ...emptyDraft(),
781
+ name: T("DSH 启动记录", "DSH boot log"),
782
+ triggerType: "startup",
783
+ trigger: { ...emptyDraft().trigger, delayMs: 2000 },
784
+ actionType: "shell",
785
+ action: { ...emptyDraft().action, command: 'Write-Output "DSH started $(Get-Date -Format o)" | Out-File -Append -Encoding utf8 "$env:USERPROFILE\\dsh-boot.log"', shell: "powershell", timeoutMs: 15000 },
786
+ }),
787
+ },
788
+ {
789
+ key: "daily-health",
790
+ title: T("每天 08:30 健康检查", "Daily 08:30 health check"),
791
+ desc: T("GET 一个本地服务地址(改成你自己的)", "GET a local service URL (edit it)"),
792
+ build: () => ({
793
+ ...emptyDraft(),
794
+ name: T("本地服务探活", "Local service health"),
795
+ triggerType: "daily",
796
+ trigger: { ...emptyDraft().trigger, time: "08:30", weekdays: [] },
797
+ actionType: "http",
798
+ action: { ...emptyDraft().action, url: "http://127.0.0.1:8080/health", method: "GET", timeoutMs: 10000 },
799
+ }),
800
+ },
801
+ {
802
+ key: "idle-log",
803
+ title: T("会话空闲 10 分钟", "Session idle for 10 min"),
804
+ desc: T("空闲时写一条运行记录,验证时机是否命中", "Write a run-log entry to verify the timing"),
805
+ build: () => ({
806
+ ...emptyDraft(),
807
+ name: T("空闲记录", "Idle marker"),
808
+ triggerType: "session-idle",
809
+ trigger: { ...emptyDraft().trigger, idleSeconds: 600 },
810
+ actionType: "log",
811
+ action: { ...emptyDraft().action, message: T("会话已空闲 10 分钟", "Session idle for 10 minutes") },
812
+ }),
813
+ },
814
+ ], [localeId]);
815
+
816
+ if (view === null) {
817
+ return h("div", { className: "dsha_root" }, h("div", { className: "dsha_inner" },
818
+ loadError
819
+ ? h("div", { className: "dsha_empty", role: "alert" }, T("无法连接自动化服务:", "Cannot reach the automation service: ") + loadError)
820
+ : h("div", { className: "dsha_loading" }, T("正在加载自动化规则…", "Loading automations…")),
821
+ ));
822
+ }
823
+
824
+ return h(
825
+ "div",
826
+ { className: "dsha_root", "data-panel": PANEL_ID },
827
+ h(
828
+ "div",
829
+ { className: "dsha_inner" },
830
+ h(
831
+ "div",
832
+ { className: "dsha_head" },
833
+ h("div", null,
834
+ h("h1", { className: "dsha_h1" }, T("生命周期自动化", "Automations")),
835
+ h("p", { className: "dsha_sub" }, T("在 DSH 生命周期与时机点自动执行命令、HTTP 请求或记录。", "Run a command, HTTP request or log line at DSH lifecycle moments.")),
836
+ ),
837
+ h("button", { type: "button", className: "dsha_btn primary", onClick: () => { switchTab("rules"); openEditor(null); } }, T("+ 新建规则", "+ New rule")),
838
+ ),
839
+ loadError ? h("div", { className: "dsha_err", role: "alert" }, loadError) : null,
840
+
841
+ h(
842
+ "div",
843
+ { className: "dsha_stats" },
844
+ h("div", { className: "dsha_stat" }, h("b", null, String(stats.total)), h("span", null, T("规则总数", "Rules"))),
845
+ h("div", { className: "dsha_stat" }, h("b", null, String(stats.enabled)), h("span", null, T("已启用", "Enabled"))),
846
+ h("div", { className: "dsha_stat" }, h("b", null, String(stats.runsToday)), h("span", null, T("今日运行", "Runs today"))),
847
+ h("div", { className: "dsha_stat" }, h("b", null, stats.lastRunAt ? fmtClock(stats.lastRunAt) : "—"), h("span", null, stats.lastRunAt ? fmtRelative(stats.lastRunAt) : T("最近运行", "Last run"))),
848
+ ),
849
+
850
+ h(
851
+ "div",
852
+ { className: "dsha_tabs", role: "tablist" },
853
+ h("button", { type: "button", className: "dsha_tab", role: "tab", "aria-selected": tab === "rules", onClick: () => switchTab("rules") },
854
+ T("规则", "Rules"), h("span", { className: "dsha_badge" }, String(rules.length))),
855
+ h("button", { type: "button", className: "dsha_tab", role: "tab", "aria-selected": tab === "runs", onClick: () => switchTab("runs") },
856
+ T("运行", "Runs"), h("span", { className: "dsha_badge" }, String(runs.length))),
857
+ ),
858
+
859
+ tab === "rules"
860
+ ? h(
861
+ "div",
862
+ { className: "dsha_section", role: "tabpanel" },
863
+ rules.length === 0
864
+ ? h("div", { className: "dsha_empty" },
865
+ h("div", null, T("还没有自动化规则。从一个模板开始:", "No automations yet. Start from a template:")),
866
+ h("div", { className: "dsha_tpls" },
867
+ templates.map((template) => h("button", { key: template.key, type: "button", className: "dsha_tpl", onClick: () => setDraft(template.build()) },
868
+ h("b", null, template.title),
869
+ h("span", null, template.desc),
870
+ )),
871
+ ),
872
+ )
873
+ : rules.map((rule) => h(RuleCard, { key: rule.id, rule, catalog, busyId, onRun: runRule, onEdit: openEditor, onDelete: deleteRule, onToggle: toggleRule })),
874
+ )
875
+ : h(
876
+ "div",
877
+ { className: "dsha_section", role: "tabpanel" },
878
+ runs.length === 0
879
+ ? h("div", { className: "dsha_empty" }, T("还没有运行记录。去「规则」页点一次「运行」试试。", "No runs yet. Use “Run” on a rule to try one."))
880
+ : h("div", { className: "dsha_runs" },
881
+ runs.map((run) => h(
882
+ "div",
883
+ { key: run.id, className: "dsha_runbox" },
884
+ h("div", { className: "dsha_runrow", role: "button", tabIndex: 0, onClick: () => setOpenRun(openRun === run.id ? "" : run.id), onKeyDown: (event) => { if (event.key === "Enter") setOpenRun(openRun === run.id ? "" : run.id); } },
885
+ h("span", { className: "dsha_runat" }, fmtClock(run.at)),
886
+ h("span", { className: "dsha_runname", title: run.ruleName }, run.ruleName),
887
+ h("span", { className: "dsha_badge" }, triggerNameOf(run.trigger)),
888
+ h("span", { className: "dsha_grow" }),
889
+ h("span", { className: "dsha_runstatus", "data-status": run.status }, statusLabel(run.status)),
890
+ h("span", { className: "dsha_rundur" }, fmtDuration(run.durationMs)),
891
+ ),
892
+ openRun === run.id
893
+ ? h(React.Fragment, null,
894
+ h("div", { className: "dsha_runmeta" },
895
+ T("触发:", "Trigger: ") + triggerNameOf(run.trigger)
896
+ + T(" · 退出码 ", " · exit ") + (run.exitCode ?? "-")
897
+ + (run.error ? " · " + run.error : ""),
898
+ ),
899
+ h("pre", { className: "dsha_pre" }, run.output || T("(无输出)", "(no output)")),
900
+ )
901
+ : null,
902
+ )),
903
+ ),
904
+ ),
905
+
906
+ h("p", { className: "dsha_sub", style: { marginTop: 22, fontSize: 11.5 } },
907
+ T("规则保存在 ", "Rules live in ") + (view.stateDir ?? "") + T(";宿主启动于 ", "; host booted ") + fmtClock(view.bootedAt) + T("。", "."),
908
+ ),
909
+ ),
910
+
911
+ draft !== null
912
+ ? h(Editor, {
913
+ draft,
914
+ setDraft,
915
+ catalog,
916
+ saving,
917
+ testResult,
918
+ error: modalError,
919
+ onClose: () => { setDraft(null); setTestResult(null); setModalError(""); },
920
+ onSave: saveDraft,
921
+ onTest: testDraft,
922
+ })
923
+ : null,
924
+
925
+ toast !== null
926
+ ? h("div", { className: "dsha_toast", "data-kind": toast.kind, role: "status" }, toast.message)
927
+ : null,
928
+ );
929
+ }
930
+ //#endregion
931
+
932
+ //#region apply
933
+ const inject = ["slots", "locale"];
934
+
935
+ /**
936
+ * Register the rail entry and the page it opens.
937
+ *
938
+ * @param {object} ctx - client root context.
939
+ */
940
+ function apply(ctx) {
941
+ const locale = ctx.locale;
942
+ applyLocaleId(readActiveLocale(locale) || FALLBACK_LANG);
943
+ ctx.slots.inject("main", () => ctx.slots.register(
944
+ { name: "main", key: PANEL_ID, inject: () => ({ locale }) },
945
+ Panel,
946
+ ));
947
+ ctx.slots.inject("sidebar.panellist", () => ctx.slots.register(
948
+ { name: "sidebar.panellist", id: PANEL_ID, order: 30, label: () => T("生命周期自动化", "Automations") },
949
+ AutomationIcon,
950
+ ));
951
+ }
952
+ //#endregion
953
+
954
+ exports.apply = apply;
955
+ exports.inject = inject;
956
+ /** Test seam for the bundle self-check. */
957
+ exports.__test__ = { PANEL_ID, API, emptyDraft, draftFromRule, payloadFromDraft, T };
958
+
959
+ return module.exports;
960
+ },
961
+ });