dsh-remote-plugin 0.8.8 → 0.9.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.
Files changed (60) hide show
  1. package/README.en.md +16 -5
  2. package/README.md +15 -4
  3. package/apk/dsh-remote.apk +0 -0
  4. package/gateway.cjs +527 -78
  5. package/index.mjs +1 -0
  6. package/package.json +8 -3
  7. package/public/activity.js +53 -4
  8. package/public/admin.html +34 -33
  9. package/public/admin.js +10 -2
  10. package/public/app.js +1204 -174
  11. package/public/bc-integration.css +81 -0
  12. package/public/build.json +2 -2
  13. package/public/composer-tools.css +184 -0
  14. package/public/composer-tools.js +888 -0
  15. package/public/desktop/desktop.html +92 -73
  16. package/public/desktop/desktop.js +631 -77
  17. package/public/file-inbox.js +77 -18
  18. package/public/genui.css +10 -0
  19. package/public/genui.js +22 -4
  20. package/public/host-queue.js +232 -0
  21. package/public/host-schedule.js +301 -0
  22. package/public/host-state.css +19 -0
  23. package/public/index.html +330 -140
  24. package/public/md.js +21 -1
  25. package/public/network.js +33 -1
  26. package/public/onboarding.js +3 -3
  27. package/public/operations.js +4 -3
  28. package/public/plan-review.css +297 -0
  29. package/public/plan-review.js +621 -0
  30. package/public/plugin.html +29 -28
  31. package/public/relay-autopair.js +25 -10
  32. package/public/relay-settings.css +11 -0
  33. package/public/relay-settings.js +350 -28
  34. package/public/session-management.css +61 -0
  35. package/public/session-management.js +742 -0
  36. package/public/session-search.css +137 -0
  37. package/public/session-search.js +977 -0
  38. package/public/skins/blue-fish/preview.html +3 -3
  39. package/public/skins/bocchi/preview.html +5 -5
  40. package/public/skins/kita/preview.html +6 -6
  41. package/public/skins/miku/SOURCES.json +10 -0
  42. package/public/skins/miku/chibi.png +0 -0
  43. package/public/skins/miku/preview.html +33 -0
  44. package/public/skins/miku/skin.css +82 -0
  45. package/public/skins/nijika/preview.html +6 -6
  46. package/public/skins/penguin/preview.html +3 -3
  47. package/public/skins/ryo/preview.html +6 -6
  48. package/public/slash-suggestions.js +15 -3
  49. package/public/sponsor-entry.js +11 -3
  50. package/public/styles.css +141 -21
  51. package/public/subagents.css +5 -0
  52. package/public/subagents.js +52 -0
  53. package/public/theme-vars.css +65 -1
  54. package/public/theme.js +4 -3
  55. package/public/turn-diff.css +323 -0
  56. package/public/turn-diff.js +778 -0
  57. package/public/update.json +8 -8
  58. package/public/version.json +1 -1
  59. package/public/workflow.css +305 -34
  60. package/public/workflow.js +141 -41
@@ -0,0 +1,301 @@
1
+ ;(function (root) {
2
+ 'use strict'
3
+ const tr = (zh, en) => root.I18N?.lang === 'en' ? en : zh
4
+ const esc = value => String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char])
5
+ const kinds = { at: ['指定时间', 'At a date and time'], after: ['延时一次', 'One-time delay'], every: ['固定间隔', 'Fixed interval'], daily: ['每天', 'Daily'], weekly: ['每周', 'Weekly'], cron: ['Cron', 'Cron'], rrule: ['RRULE', 'RRULE'] }
6
+ const destinations = { session: ['复用现有会话', 'Reuse an existing session'], new_once: ['首次新建,之后复用', 'Create once, then reuse'], new: ['每次新建会话', 'Create a session each time'] }
7
+ const timeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
8
+ const stateLabels = { active: ['启用', 'Active'], paused: ['已暂停', 'Paused'], ended: ['已结束', 'Ended'], inactive: ['未启用', 'Inactive'] }
9
+ const executionLabels = { pending: ['已投递 · 仍在收件箱', 'Delivered · still in inbox'], running: ['执行中', 'Running'], completed: ['执行完成', 'Turn completed'], aborted: ['执行中止', 'Turn aborted'], failed: ['执行失败或未完成', 'Turn failed or did not complete'], unverified: ['已投递 · 执行状态未证实', 'Delivered · execution unverified'] }
10
+ const field = (values, name) => String(values[name] ?? '').trim()
11
+ const localTime = value => /^\d\d:\d\d$/.test(value) ? value + ':00' : value
12
+
13
+ function timing(values) {
14
+ const kind = values.kind, value = field(values, 'timingValue'), zone = field(values, 'zone')
15
+ if (!value) throw new Error(tr('请填写触发时间或重复规则。', 'Enter a trigger time or repeat rule.'))
16
+ if (kind === 'after' || kind === 'every') {
17
+ const seconds = Number(value)
18
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(seconds) || seconds < (kind === 'after' ? 1 : 60)) throw new Error(tr('请输入合法的秒数(固定间隔至少 60 秒)。', 'Enter valid seconds (at least 60 for a fixed interval).'))
19
+ return { kind, [kind + '_seconds']: seconds }
20
+ }
21
+ if (kind === 'rrule') return { kind, rrule: value.replace(/\r\n/g, '\n') }
22
+ if (kind === 'at' && /T.*(?:Z|[+-]\d\d:\d\d)$/i.test(value)) return { kind, at: value }
23
+ if (!zone) throw new Error(tr('请填写 IANA 时区。', 'Enter an IANA time zone.'))
24
+ try { new Intl.DateTimeFormat('en', { timeZone: zone }) } catch { throw new Error(tr('无法识别此 IANA 时区。', 'Unrecognized IANA time zone.')) }
25
+ if (kind === 'at') {
26
+ const match = /^(\d{4}-\d\d-\d\d)[T ](\d\d:\d\d(?::\d\d(?:\.\d{1,3})?)?)$/.exec(value)
27
+ if (!match) throw new Error(tr('请输入「年-月-日 时:分」或带偏移的 RFC 3339 时间。', 'Use YYYY-MM-DD HH:mm or an RFC 3339 timestamp with an offset.'))
28
+ return { kind, at: { date: match[1], time: localTime(match[2]), time_zone: zone } }
29
+ }
30
+ if (kind === 'cron') return { kind, cron: { expression: value, time_zone: zone } }
31
+ if (kind === 'daily') return { kind, daily: { time: localTime(value), time_zone: zone } }
32
+ if (kind === 'weekly') {
33
+ const weekdays = field(values, 'weekdays').split(/[,,\s]+/).filter(Boolean).map(Number)
34
+ if (!weekdays.length || weekdays.some(day => !Number.isInteger(day) || day < 1 || day > 7) || new Set(weekdays).size !== weekdays.length) throw new Error(tr('请输入不重复的星期编号 1–7(周一至周日)。', 'Enter distinct weekday numbers 1–7 (Monday through Sunday).'))
35
+ return { kind, weekly: { time: localTime(value), time_zone: zone, weekdays: weekdays.sort((left, right) => left - right) } }
36
+ }
37
+ throw new Error(tr('主机规则类型不可编辑。', 'This Host rule type is not editable.'))
38
+ }
39
+
40
+ function initial(task) {
41
+ const kind = task?.kind || 'at'
42
+ return { title: task?.title || '', prompt: task?.prompt || '', kind, zone: task?.timeZone || timeZone(),
43
+ timingValue: String(({ at: task?.scheduledAt, after: task?.afterSeconds, every: task?.everySeconds, daily: task?.time, weekly: task?.time, cron: task?.expression, rrule: task?.rrule })[kind] ?? ''),
44
+ weekdays: task?.weekdays?.join(',') || '', destination: task?.target?.kind || 'new_once',
45
+ sessionId: task?.target?.sessionId || '', cwd: task?.target?.create?.cwd || '' }
46
+ }
47
+
48
+ function changes(values, before, task) {
49
+ const patch = {}
50
+ for (const name of ['title', 'prompt']) {
51
+ if (!field(values, name)) throw new Error(tr('请填写名称和任务内容。', 'Enter a name and task instructions.'))
52
+ if (!task || field(values, name) !== before[name]) patch[name] = field(values, name)
53
+ }
54
+ if (!task || ['kind', 'zone', 'timingValue', 'weekdays'].some(name => values[name] !== before[name])) patch.timing = timing(values)
55
+ const targetChanged = values.destination !== before.destination || (values.destination === 'session' ? values.sessionId !== before.sessionId : values.cwd !== before.cwd)
56
+ if (!task || targetChanged) {
57
+ const kind = values.destination
58
+ if (kind === 'session') {
59
+ if (!values.sessionId) throw new Error(tr('请选择要复用的会话。', 'Choose a session to reuse.'))
60
+ patch.target = { kind, sessionId: values.sessionId }
61
+ } else if (kind === 'new' || kind === 'new_once') {
62
+ const agentPreset = task?.target?.create?.agentPreset
63
+ patch.target = { kind, create: { ...(values.cwd ? { cwd: values.cwd } : {}), ...(agentPreset ? { agentPreset } : {}) } }
64
+ } else throw new Error(tr('请选择投递目标。', 'Choose a delivery target.'))
65
+ }
66
+ return patch
67
+ }
68
+
69
+ function create(config) {
70
+ const limit = 30, historyLimit = 10
71
+ let connection, read = 0, offset = 0, rows = [], total = 0, writable = false, loaded = false
72
+ let loading = false, error = '', feedback = '', writing = null, dialog, history = null
73
+ const box = config.box
74
+ const active = () => !!box() && !box().classList.contains('hidden')
75
+ const valid = entry => entry && entry === connection && entry.valid() && active()
76
+ const taskLabel = task => tr(...(stateLabels[task.status] || [task.status || '未知', task.status || 'Unknown']))
77
+ const formatTime = (value, zone = timeZone()) => {
78
+ if (!value || !Number.isFinite(Date.parse(value))) return '—'
79
+ try { return new Intl.DateTimeFormat(root.I18N?.lang === 'en' ? 'en' : 'zh-CN', { timeZone: zone, dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value)) + ' · ' + zone }
80
+ catch { return String(value) }
81
+ }
82
+ function explain(err) {
83
+ if (root.DshHostQueue.denied(err)) return tr('此设备无权执行此操作。', 'This device cannot perform this operation.')
84
+ switch (err?.code) {
85
+ case 'schedule/unsupported': return tr('此主机未启用或不支持所需的 Schedule 接口。请在主机更新或启用 Schedule。', 'This Host does not expose the required Schedule API. Update the Host or enable Schedule there.')
86
+ case 'schedule_conflict': return tr('任务已被其他客户端修改,请刷新后重新编辑。', 'Another client changed this task. Refresh and reopen the editor.')
87
+ case 'schedule_not_found': return tr('任务已不存在。', 'This task no longer exists.')
88
+ case 'delivery_cursor_not_found': return tr('历史已变化,请重新读取该任务的投递记录。', 'History changed. Reload the task’s deliveries.')
89
+ case 'schedule_execution_pending': return tr('已有一次投递正在等待或执行,或仍在主机限制间隔内。', 'A delivery is pending, in progress, or within the Host delivery interval.')
90
+ case 'schedule/input-invalid': return tr('主机未接受任务设置,请核对时间、时区、重复规则和目标。', 'The Host rejected these settings. Check the time, time zone, repeat rule and target.')
91
+ case 'schedule/target-archived': return tr('目标会话已归档,请更换目标或在主机恢复会话。', 'The target session is archived. Change the target or restore it on the Host.')
92
+ default: return err?.message || tr('无法读取主机自动化。', 'Could not read Host automations.')
93
+ }
94
+ }
95
+
96
+ async function refresh(reloadHistory = false) {
97
+ if (!active()) return
98
+ if (!connection?.valid()) {
99
+ connection = config.capture()
100
+ offset = 0; rows = []; total = 0; history = null; writable = false; feedback = ''; loaded = false
101
+ dialog?.close()
102
+ }
103
+ const entry = connection, revision = ++read
104
+ loading = true; error = ''
105
+ render()
106
+ try {
107
+ if (!entry.token) throw new Error(tr('请先连接主机。', 'Connect to a Host first.'))
108
+ const [page, access] = await Promise.all([config.rpc('schedule.list', { limit, offset }), config.access(entry)])
109
+ if (!valid(entry) || revision !== read) return
110
+ if (!Array.isArray(page?.items) || !Number.isSafeInteger(page.total)) throw new Error(tr('网关或主机未提供兼容的自动化列表。', 'The Gateway or Host does not provide a compatible automation list.'))
111
+ if (offset && !page.items.length) { offset = Math.max(0, Math.floor((page.total - 1) / limit) * limit); return await refresh(reloadHistory) }
112
+ rows = page.items; total = page.total; writable = access; loaded = true
113
+ if (reloadHistory && history) void readHistory(history.task, undefined)
114
+ } catch (err) {
115
+ if (!valid(entry) || revision !== read) return
116
+ writable = false; loaded = false; error = explain(err)
117
+ } finally {
118
+ if (valid(entry) && revision === read) { loading = false; render() }
119
+ }
120
+ }
121
+
122
+ async function write(method, payload, task) {
123
+ const entry = connection
124
+ if (!valid(entry) || writing || loading || !loaded || !writable) return false
125
+ writing = entry; feedback = ''
126
+ render()
127
+ let attempted = false, succeeded = false
128
+ try {
129
+ if (!await config.access(entry) || !valid(entry)) throw new Error('host-state/access-denied')
130
+ if (task) {
131
+ const fresh = await config.rpc('schedule.view', { id: task.id })
132
+ if (fresh?.code || fresh?.id !== task.id) throw Object.assign(new Error(), { code: fresh?.code || 'schedule_not_found' })
133
+ if ((fresh.updatedAt ?? null) !== (task.updatedAt ?? null)) throw Object.assign(new Error(), { code: 'schedule_conflict' })
134
+ }
135
+ if (!valid(entry)) return false
136
+ attempted = true
137
+ const result = await config.rpc(method, payload)
138
+ if (result?.code) throw Object.assign(new Error(), { code: result.code })
139
+ if (!result?.id || (payload.action === 'delete' && result.deleted !== true)) throw new Error()
140
+ succeeded = true
141
+ if (valid(entry)) {
142
+ if (payload.action === 'delete' && history?.task.id === payload.id) history = null
143
+ feedback = method === 'schedule.run' ? tr('主机已确认投递;这不是执行完成。', 'The Host confirmed delivery, not completion.') : tr('主机已保存更改。', 'The Host saved the change.')
144
+ }
145
+ } catch (err) {
146
+ if (valid(entry)) feedback = !attempted || root.DshHostQueue.knownRejection(err) ? explain(err)
147
+ : tr('写入结果未确认。不会重发;请核对主机最新列表和记录。', 'Write unconfirmed. It was not retried; check the refreshed Host list and records.')
148
+ } finally {
149
+ if (valid(entry)) await refresh(true)
150
+ writing = null
151
+ if (active()) render()
152
+ }
153
+ return succeeded && valid(entry)
154
+ }
155
+
156
+ async function readHistory(task, before) {
157
+ const entry = connection
158
+ if (!valid(entry)) return
159
+ if (!before) history = { task, records: [], execution: new Map() }
160
+ if (history?.task.id !== task.id || history.busy) return
161
+ const current = history
162
+ current.busy = true; current.error = ''
163
+ render()
164
+ try {
165
+ const page = await config.rpc('schedule.history', { id: task.id, limit: historyLimit, ...(before ? { before } : {}) })
166
+ if (!valid(entry) || current !== history) return
167
+ if (page?.code) throw Object.assign(new Error(tr('该记录已不可用,请刷新。', 'History is no longer available; refresh to try again.')), { code: page.code })
168
+ if (!Array.isArray(page?.records)) throw new Error(tr('主机未返回有效的投递记录。', 'The Host returned no valid delivery records.'))
169
+ const prior = new Set(current.records.map(record => record.messageId))
170
+ current.records.push(...page.records.filter(record => !prior.has(record.messageId)))
171
+ current.next = page.nextBefore
172
+ current.partial = page.earlierRecordsUnavailable || page.earlierRecordsPruned
173
+ if (!before && current.records[0]) void checkExecution(current.records[0])
174
+ } catch (err) { if (valid(entry) && current === history) current.error = explain(err) }
175
+ finally { if (valid(entry) && current === history) { current.busy = false; render() } }
176
+ }
177
+
178
+ async function checkExecution(record) {
179
+ const entry = connection, current = history
180
+ if (!valid(entry) || !current || current.execution.get(record.messageId) === 'checking') return
181
+ current.execution.set(record.messageId, 'checking'); render()
182
+ try {
183
+ const value = await config.rpc('session.deliveryStatus', { sessionId: record.targetSessionId, messageId: record.messageId })
184
+ if (valid(entry) && history === current) current.execution.set(record.messageId, Object.hasOwn(executionLabels, value?.status) ? value.status : 'unverified')
185
+ } catch { if (valid(entry) && history === current) current.execution.set(record.messageId, 'unverified') }
186
+ finally { if (valid(entry) && history === current) render() }
187
+ }
188
+
189
+ function form(task) {
190
+ if (writing || loading || !writable || !loaded) return
191
+ const entry = connection, before = initial(task)
192
+ if (!dialog) {
193
+ dialog = root.document.createElement('dialog')
194
+ dialog.className = 'host-state-dialog'
195
+ dialog.setAttribute('aria-labelledby', 'host-schedule-editor-title')
196
+ root.document.body.append(dialog)
197
+ }
198
+ const options = (values, selected) => values.map(([value, label]) => `<option value="${esc(value)}" ${selected === value ? 'selected' : ''}>${esc(label)}</option>`).join('')
199
+ const workspaceChoices = config.workspaces().filter(row => row.path).map(row => [row.path, row.title || row.name || row.path])
200
+ const sessionChoices = config.sessions().map(row => [row.id, row.label])
201
+ if (before.cwd && !workspaceChoices.some(([path]) => path === before.cwd)) workspaceChoices.unshift([before.cwd, before.cwd])
202
+ if (before.sessionId && task?.target?.kind === 'session' && !sessionChoices.some(([id]) => id === before.sessionId)) sessionChoices.unshift([before.sessionId, before.sessionId])
203
+ dialog.innerHTML = `<form method="dialog">
204
+ <h2 id="host-schedule-editor-title">${task ? tr('编辑自动化', 'Edit automation') : tr('新建自动化', 'New automation')}</h2>
205
+ <label>${tr('名称', 'Name')}<input name="title" maxlength="120" required value="${esc(before.title)}"></label>
206
+ <label>${tr('任务内容', 'Instructions')}<textarea name="prompt" rows="4" required>${esc(before.prompt)}</textarea></label>
207
+ <label>${tr('触发规则', 'Trigger rule')}<select name="kind">${options(Object.entries({ ...(!Object.hasOwn(kinds, before.kind) ? { [before.kind]: [before.kind, before.kind] } : {}), ...kinds }).map(([kind, label]) => [kind, tr(...label)]), before.kind)}</select></label>
208
+ <label><span data-timing-label></span><textarea name="timingValue" rows="2">${esc(before.timingValue)}</textarea></label>
209
+ <label data-zone>${tr('时区(IANA)', 'IANA time zone')}<input name="zone" value="${esc(before.zone)}" placeholder="Asia/Shanghai"></label>
210
+ <label data-weekdays>${tr('星期(1=周一,7=周日)', 'Weekdays (1 Mon, 7 Sun)')}<input name="weekdays" value="${esc(before.weekdays)}" placeholder="1,3,5"></label>
211
+ <small>${tr('时间由主机校验。夏令时切换时,一次性任务可用显式 UTC 偏移消除歧义;重复规则按所选时区或 RRULE 的 TZID 执行。', 'The Host validates times. For a one-time trigger during a DST change, use an explicit UTC offset. Recurrences use the selected zone or the RRULE TZID.')}</small>
212
+ <label>${tr('投递至', 'Deliver to')}<select name="destination">${options(Object.entries(destinations).map(([kind, label]) => [kind, tr(...label)]), before.destination)}</select></label>
213
+ <label data-session>${tr('现有会话', 'Existing session')}<select name="sessionId">${options([['', tr('选择会话', 'Choose a session')], ...sessionChoices], before.sessionId)}</select></label>
214
+ <label data-workspace>${tr('工作区', 'Workspace')}<select name="cwd">${options([['', tr('主机默认工作区', 'Host default workspace')], ...workspaceChoices], before.cwd)}</select></label>
215
+ <p data-editor-status role="status"></p><div class="host-state-actions"><button value="cancel" formnovalidate>${tr('取消', 'Cancel')}</button><button value="save">${tr('保存到主机', 'Save to Host')}</button></div>
216
+ </form>`
217
+ const editor = dialog.querySelector('form'), fields = editor.elements, status = editor.querySelector('[data-editor-status]')
218
+ const update = () => {
219
+ const kind = fields.kind.value
220
+ editor.querySelector('[data-zone]').hidden = !['at', 'daily', 'weekly', 'cron'].includes(kind)
221
+ editor.querySelector('[data-weekdays]').hidden = kind !== 'weekly'
222
+ editor.querySelector('[data-session]').hidden = fields.destination.value !== 'session'
223
+ editor.querySelector('[data-workspace]').hidden = fields.destination.value === 'session'
224
+ editor.querySelector('[data-timing-label]').textContent = ({ at: tr('时间(本地日期时间或带偏移的 RFC 3339)', 'Date and time (local or RFC 3339 with offset)'), after: tr('延迟秒数', 'Delay in seconds'), every: tr('间隔秒数', 'Interval in seconds'), cron: tr('五字段 Cron 表达式', 'Five-field Cron expression'), rrule: 'DTSTART + RRULE' })[kind] || tr('本地时间(时:分)', 'Local time (HH:mm)')
225
+ }
226
+ editor.onchange = update; update()
227
+ const baseline = Object.fromEntries(new root.FormData(editor))
228
+ editor.onsubmit = async event => {
229
+ if (event.submitter?.value !== 'save') return
230
+ event.preventDefault()
231
+ if (!valid(entry) || writing) return
232
+ try {
233
+ const patch = changes(Object.fromEntries(new root.FormData(editor)), baseline, task)
234
+ if (!Object.keys(patch).length) { dialog.close(); return }
235
+ event.submitter.disabled = true
236
+ const saved = task ? await write('schedule.edit', { id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt ?? null, patch }, task) : await write('schedule.create', patch)
237
+ if (!valid(entry) || !dialog.open || editor !== dialog.querySelector('form')) return
238
+ if (saved) dialog.close()
239
+ else { status.textContent = feedback; event.submitter.disabled = !writable || !loaded }
240
+ } catch (err) { status.textContent = explain(err) }
241
+ }
242
+ dialog.showModal()
243
+ }
244
+
245
+ function render() {
246
+ if (!active()) return
247
+ const panel = box(), disabled = loading || !writable || !loaded || !!writing
248
+ const btn = (action, label, locked = false) => `<button type="button" data-auto="${action}" ${locked ? 'disabled' : ''}>${esc(label)}</button>`
249
+ const current = history
250
+ const historyHtml = current ? `<section class="host-state-card" aria-label="${tr('投递历史', 'Delivery history')}"><div class="host-state-actions"><h2>${tr('投递历史', 'Delivery history')} · ${esc(current.task.title)}</h2>${btn('history-close', tr('关闭', 'Close'))}</div>
251
+ <small>${tr('投递只代表主机写入会话收件箱。执行结果按消息 ID 匹配对应轮次;未找到证据时不判定结果。', 'Delivery only confirms a Host inbox write. Execution is matched by message ID to its turn and stays unverified without evidence.')}</small>
252
+ ${current.error ? `<p role="alert">${esc(current.error)}</p>` : ''}${current.partial ? `<p>${tr('更早的记录已被清理或不可用。', 'Earlier records were pruned or are unavailable.')}</p>` : ''}
253
+ ${current.records.map(record => {
254
+ const status = current.execution.get(record.messageId)
255
+ return `<article class="host-state-card" data-delivery="${esc(record.messageId)}"><strong>${status === 'checking' ? tr('已投递 · 核对执行中', 'Delivered · checking execution') : tr(...(executionLabels[status] || executionLabels.unverified))}</strong><p>${tr('计划', 'Scheduled')}:${esc(formatTime(record.scheduledAt))}<br>${tr('已投递', 'Delivered')}:${esc(formatTime(record.deliveredAt))}</p>
256
+ ${typeof record.prompt === 'string' ? `<details><summary>${tr('查看当次任务内容', 'View delivered instructions')}</summary><div class="host-state-pre">${esc(record.prompt)}</div></details>` : ''}
257
+ <div class="host-state-actions">${btn('execution', tr('核对执行状态', 'Check execution'), status === 'checking')}${btn('session', tr('打开会话', 'Open session'), !record.targetSessionId)}</div></article>`
258
+ }).join('')}
259
+ ${!current.busy && !current.records.length && !current.error ? `<p>${tr('没有已保存的投递记录。', 'No saved deliveries.')}</p>` : ''}${current.busy ? `<p role="status">${tr('正在读取历史…', 'Loading history…')}</p>` : ''}${current.next ? btn('history-more', tr('加载更早记录', 'Load earlier records'), current.busy) : ''}</section>` : ''
260
+ panel.innerHTML = `<div class="host-schedule"><div class="host-state-actions"><h1>${tr('自动化', 'Automations')}</h1>${btn('refresh', tr('刷新主机', 'Refresh Host'), loading || !!writing)}${btn('create', tr('新建任务', 'New task'), disabled)}</div>
261
+ <p>${tr('这些任务由 DSH 主机调度。关闭 Remote 不会停止调度;DSH 主机必须保持运行。', 'DSH schedules these tasks. Closing Remote does not stop scheduling; the DSH Host must remain running.')}</p>
262
+ ${!writable && loaded ? `<p>${tr('此设备仅可查看,不能变更任务。', 'This device can view but not change tasks.')}</p>` : ''}
263
+ ${feedback ? `<p role="status">${esc(feedback)}</p>` : ''}${error ? `<p role="alert">${esc(error)}</p>` : ''}${loading ? `<p role="status">${tr('正在读取主机…', 'Reading Host state…')}</p>` : ''}
264
+ ${historyHtml}
265
+ ${loaded && !rows.length ? `<p>${tr('主机没有自动化任务。', 'The Host has no automation tasks.')}</p>` : ''}
266
+ ${rows.map(task => `<article class="host-state-card" data-task="${esc(task.id)}"><h2>${esc(task.title)}</h2><p>${esc(taskLabel(task))} · ${esc(tr(...(kinds[task.kind] || [task.kind, task.kind])))}${task.status === 'active' ? ` · ${esc(formatTime(task.scheduledAt, task.timeZone))}` : ''}</p>
267
+ <details><summary>${tr('任务内容与目标', 'Instructions and target')}</summary><div class="host-state-pre">${esc(task.prompt)}</div><p>${esc(tr(...(destinations[task.target?.kind] || ['目标未知', 'Unknown target'])))} · ${esc(task.target?.create?.cwd || config.sessions().find(session => session.id === task.target?.sessionId)?.label || task.target?.sessionId || tr('主机默认工作区', 'Host default workspace'))}</p></details>
268
+ <div class="host-state-actions">${btn('history', tr('投递历史', 'Delivery history'), !loaded)}${btn('edit', tr('编辑', 'Edit'), disabled)}${btn('run', tr('立即运行', 'Run now'), disabled || task.executionActive === true)}${task.status === 'active' || task.status === 'paused' ? btn('toggle', task.status === 'active' ? tr('暂停', 'Pause') : tr('恢复', 'Resume'), disabled) : ''}${btn('delete', tr('删除', 'Delete'), disabled)}</div></article>`).join('')}
269
+ <div class="host-state-actions">${offset ? btn('prev', tr('上一页', 'Previous'), loading || !!writing) : ''}${offset + rows.length < total ? btn('next', tr('下一页', 'Next'), loading || !!writing) : ''}</div></div>`
270
+ panel.onclick = event => {
271
+ const trigger = event.target.closest('[data-auto]')
272
+ if (!trigger || trigger.disabled) return
273
+ const action = trigger.dataset.auto
274
+ if (action === 'refresh') return void refresh(true)
275
+ if (action === 'create') return form()
276
+ if (action === 'prev' || action === 'next') { offset += action === 'prev' ? -limit : limit; return void refresh() }
277
+ if (action === 'history-close') { history = null; return render() }
278
+ if (action === 'history-more' && current?.next) return void readHistory(current.task, current.next)
279
+ if (action === 'execution' || action === 'session') {
280
+ const record = current?.records.find(item => item.messageId === trigger.closest('[data-delivery]')?.dataset.delivery)
281
+ if (!record) return
282
+ if (action === 'execution') return void checkExecution(record)
283
+ return void config.openSession(record.targetSessionId)
284
+ }
285
+ const task = rows.find(item => item.id === trigger.closest('[data-task]')?.dataset.task)
286
+ if (!task) return
287
+ if (action === 'history') return void readHistory(task)
288
+ if (action === 'edit') return form(task)
289
+ if (action === 'run') return void write('schedule.run', { id: task.id }, task)
290
+ const expectedUpdatedAt = task.updatedAt ?? null
291
+ if (action === 'toggle') return void write('schedule.edit', { id: task.id, action: 'update', patch: { active: task.status === 'paused' }, expectedUpdatedAt }, task)
292
+ if (action === 'delete' && root.confirm(tr('删除任务和它的已保存投递记录?已投递的消息不会删除。', 'Delete the task and saved delivery history? Already delivered messages will remain.'))) return void write('schedule.edit', { id: task.id, action: 'delete', expectedUpdatedAt }, task)
293
+ }
294
+ }
295
+ return { refresh, leave() { read++; dialog?.close(); connection = undefined; loading = false } }
296
+ }
297
+
298
+ const api = { create, timing, initial, changes }
299
+ if (typeof module !== 'undefined' && module.exports) module.exports = api
300
+ else root.DshHostSchedule = api
301
+ })(globalThis)
@@ -0,0 +1,19 @@
1
+ .host-schedule { max-width: 60rem; margin: 0 auto; padding: 1rem; }
2
+ .ds-view#view-schedule { overflow-y: auto; }
3
+ .host-schedule h1, .host-schedule h2, .host-state-dialog h2 { margin: .15em 0; }
4
+ .host-schedule h2, .host-state-dialog h2 { font-size: 1.1rem; }
5
+ .host-state-card, .host-queue-rows > details { padding: .65rem; border: 1px solid var(--dsr-accent-line, #8886); border-radius: .65rem; margin: .5rem 0; }
6
+ .host-state-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem; margin: .25rem 0; }
7
+ .host-state-actions button { min-height: 2.15rem; padding: .35rem .6rem; border: 1px solid var(--dsr-accent-line, #8886); border-radius: .5rem; background: var(--dsr-bg-2, transparent); color: inherit; cursor: pointer; }
8
+ .host-state-actions button:disabled { opacity: .5; cursor: default; }
9
+ .host-state-pre { white-space: pre-wrap; overflow-wrap: anywhere; padding: .5rem 0; }
10
+ #queue-dock > .host-state-actions, #queue-dock > p, #queue-dock > small { margin-inline: .65rem; }
11
+ .host-queue-rows { max-height: min(45vh, 22rem); overflow: auto; padding-inline: .65rem; }
12
+ .host-queue-rows summary, .host-schedule summary { cursor: pointer; overflow-wrap: anywhere; }
13
+ .host-state-results { max-height: 9rem; overflow: auto; margin: .4rem 0; padding-inline-start: 1.5rem; overflow-wrap: anywhere; }
14
+ .host-state-dialog { width: min(36rem, calc(100vw - 2rem)); max-height: 90dvh; padding: 1rem; border: 1px solid var(--dsr-accent-line, #8886); border-radius: .8rem; color: var(--dsr-text, CanvasText); background: var(--dsr-bg-2, Canvas); }
15
+ .host-state-dialog::backdrop { background: #0008; }
16
+ .host-state-dialog form { display: grid; gap: .6rem; }
17
+ .host-state-dialog label { display: grid; gap: .25rem; }
18
+ .host-state-dialog label[hidden] { display: none; }
19
+ .host-state-dialog :is(input, textarea, select) { width: 100%; min-height: 2.25rem; padding: .4rem; border: 1px solid var(--dsr-accent-line, #8886); border-radius: .4rem; color: inherit; background: var(--dsr-bg, Canvas); font: inherit; }