dsh-cothread-mcp 0.1.8 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -63,10 +63,10 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
63
63
  };
64
64
  }
65
65
  function ActionIcon({ name, size = 16 }) {
66
- const names = { reuse: 'IconRefreshOutlineRegular', new: 'IconNewChatOutlineRegular', down: 'IconChevronDownOutlineRegular', check: 'IconCheckOutlineRegular', external: 'IconRightUpOutlineRegular', trash: 'IconTrashOutlineRegular', plus: 'IconPlusOutlineRegular', save: 'IconSaveOutlineRegular', session: 'IconChatOutlineRegular', chevron: 'IconChevronRightOutlineRegular', settings: 'IconSettingsOutlineMedium' };
66
+ const names = { reuse: 'IconRefreshOutlineRegular', new: 'IconNewChatOutlineRegular', down: 'IconChevronDownOutlineRegular', check: 'IconCheckOutlineRegular', external: 'IconRightUpOutlineRegular', trash: 'IconTrashOutlineRegular', plus: 'IconPlusOutlineRegular', save: 'IconSaveOutlineRegular', session: 'IconChatOutlineRegular', chevron: 'IconChevronRightOutlineRegular', settings: 'IconSettingsOutlineMedium', paperPlane: 'IconPaperPlaneOutlineRegular' };
67
67
  const SharedIcon = sharedIcons[names[name]];
68
68
  if (SharedIcon) return h(SharedIcon, { size });
69
- const paths = { notify: 'M8 2a4 4 0 0 0-4 4v2.5L2.5 11h11L12 8.5V6a4 4 0 0 0-4-4ZM6.5 13a1.5 1.5 0 0 0 3 0', reuse: 'M13 5a5 5 0 0 0-8.5-1L3 5.5M3 2.5v3h3M3 11a5 5 0 0 0 8.5 1l1.5-1.5M13 13.5v-3h-3', new: 'M3 3h10v7H8l-3 3v-3H3V3ZM8 5v3M6.5 6.5h3', down: 'm4 6 4 4 4-4', check: 'm3 8 3 3 7-7', external: 'M9 2h5v5M14 2 7 9M12 9v3a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3', trash: 'M2.5 4h11M6 4V2.5h4V4M4 4l.6 9a1 1 0 0 0 1 .9h4.8a1 1 0 0 0 1-.9l.6-9M6.5 7v4M9.5 7v4', plus: 'M8 3v10M3 8h10', save: 'M3 2.5h7.5L13 5v8.5H3zM5.5 2.5v3.5h5V2.5M5 13.5v-4h6v4', session: 'M2.5 3.5h11v7h-4.5l-3 3v-3h-3.5z', chevron: 'm6 3.5 4.5 4.5L6 12.5', settings: 'M6.6 2.2h2.8l.3 1.7 1.4.8 1.6-.7 1.4 2.4-1.3 1.2v1.6l1.3 1.2-1.4 2.4-1.6-.7-1.4.8-.3 1.7H6.6l-.3-1.7-1.4-.8-1.6.7-1.4-2.4 1.3-1.2V7.6L2.5 6.4l1.4-2.4 1.6.7 1.4-.8.3-1.7Z' };
69
+ const paths = { notify: 'M8 2a4 4 0 0 0-4 4v2.5L2.5 11h11L12 8.5V6a4 4 0 0 0-4-4ZM6.5 13a1.5 1.5 0 0 0 3 0', reuse: 'M13 5a5 5 0 0 0-8.5-1L3 5.5M3 2.5v3h3M3 11a5 5 0 0 0 8.5 1l1.5-1.5M13 13.5v-3h-3', new: 'M3 3h10v7H8l-3 3v-3H3V3ZM8 5v3M6.5 6.5h3', down: 'm4 6 4 4 4-4', check: 'm3 8 3 3 7-7', external: 'M9 2h5v5M14 2 7 9M12 9v3a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3', trash: 'M2.5 4h11M6 4V2.5h4V4M4 4l.6 9a1 1 0 0 0 1 .9h4.8a1 1 0 0 0 1-.9l.6-9M6.5 7v4M9.5 7v4', plus: 'M8 3v10M3 8h10', save: 'M3 2.5h7.5L13 5v8.5H3zM5.5 2.5v3.5h5V2.5M5 13.5v-4h6v4', session: 'M2.5 3.5h11v7h-4.5l-3 3v-3h-3.5z', chevron: 'm6 3.5 4.5 4.5L6 12.5', settings: 'M6.6 2.2h2.8l.3 1.7 1.4.8 1.6-.7 1.4 2.4-1.3 1.2v1.6l1.3 1.2-1.4 2.4-1.6-.7-1.4.8-.3 1.7H6.6l-.3-1.7-1.4-.8-1.6.7-1.4-2.4 1.3-1.2V7.6L2.5 6.4l1.4-2.4 1.6.7 1.4-.8.3-1.7Z', paperPlane: 'M14 2 2 7l5 2 2 5 5-12ZM7 9l5-5' };
70
70
  return h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true', style: { flex: 'none' } }, h('path', { d: paths[name] }));
71
71
  }
72
72
  function ChoicePicker({ items, selectedId, onPick, label, placeholder, missingLabel, emptyLabel, disabled = false, menuWidth = 320, invalid = false, displayItem, keepOpenOnPick = false, onOpen }) {
@@ -113,7 +113,15 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
113
113
  return h(ChoicePicker, { items, selectedId: action, menuWidth: 260, label, placeholder: '请选择动作', missingLabel: '请选择动作', onPick: id => onPick(id) });
114
114
  }
115
115
  /** 旧配置里的动作值折算成现在的动作。 */
116
- function normalizeAction(value) {
116
+ /** 上次巡检的时间标签:让人看出插件还在跑,而不是任务停了就什么都不动。 */
117
+ function pollTimeLabel(iso) {
118
+ if (!iso) return '尚未巡检'
119
+ const at = new Date(iso)
120
+ if (Number.isNaN(at.getTime())) return '尚未巡检'
121
+ const pad = value => String(value).padStart(2, '0')
122
+ return pad(at.getHours()) + ':' + pad(at.getMinutes()) + ':' + pad(at.getSeconds())
123
+ }
124
+ function normalizeAction(value) {
117
125
  const raw = String(value || '').trim();
118
126
  return raw === 'analyze' || raw === 'reuse' || raw === 'new' ? 'analyze' : 'restate';
119
127
  }
@@ -121,7 +129,7 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
121
129
  function automationOf(status, row) {
122
130
  return (status.automations || []).find(item => item.projectId === row.projectId && item.workspaceId === row.workspaceId) || null;
123
131
  }
124
- const environmentChoices = [{ id: 'production', title: '正式环境', path: 'https://cothread.z2l.top/' }, { id: 'local', title: '本地环境', path: 'http://127.0.0.1:3100/' }];
132
+ const environmentChoices = [{ id: 'production', title: '正式环境', path: 'https://cothread.hnstaoxiang.cn/' }, { id: 'local', title: '本地环境', path: 'http://127.0.0.1:3100/' }];
125
133
  function useStatus() {
126
134
  const [status, setStatus] = useState({});
127
135
  useEffect(() => { let live = true; const load = () => call('status').then(x => { if (live) setStatus(x) }).catch(() => { if (live) setStatus({ error: '服务不可用' }) }); void load(); const timer = setInterval(load, 3000); return () => { live = false; clearInterval(timer) } }, []);
@@ -139,21 +147,26 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
139
147
  }
140
148
  function Settings({ form, remote, view, openSession }) {
141
149
  const status = useStatus();
142
- const [loaded, setLoaded] = useState(null), [draft, setDraft] = useState(null), [message, setMessage] = useState(''), [projects, setProjects] = useState([]), [projectListOrigin, setProjectListOrigin] = useState(null), [localWorkspaces, setLocalWorkspaces] = useState(null), [workspaceError, setWorkspaceError] = useState(''), [refreshing, setRefreshing] = useState(false), [busy, setBusy] = useState(false), [savedRows, setSavedRows] = useState(null), [pendingRemoval, setPendingRemoval] = useState(null), [pendingLogout, setPendingLogout] = useState(null);
150
+ const [loaded, setLoaded] = useState(null), [draft, setDraft] = useState(null), [message, setMessage] = useState(''), [projects, setProjects] = useState([]), [projectListOrigin, setProjectListOrigin] = useState(null), [localWorkspaces, setLocalWorkspaces] = useState(null), [workspaceError, setWorkspaceError] = useState(''), [refreshing, setRefreshing] = useState(false), [busy, setBusy] = useState(false), [savedRows, setSavedRows] = useState(null), [pendingRemoval, setPendingRemoval] = useState(null), [pendingLogout, setPendingLogout] = useState(null), [cronDraft, setCronDraft] = useState(null), [cronInfo, setCronInfo] = useState(null);
143
151
  useEffect(() => { if (form?.state?.value || view === 'summary') return; let live = true; remote?.settings?.describe?.().then(found => { const payload = found?.ok ? found.value : found; const rows = Array.isArray(payload) ? payload : payload?.namespaces; const row = Array.isArray(rows) ? rows.find(x => x?.ns === ns) : rows?.[ns]; if (live && row) setLoaded({ value: row.value || row, revision: row.revision ?? 0 }) }).catch(() => { if (live) setMessage('无法读取设置') }); return () => { live = false } }, [form, remote, view, status.environment]);
144
152
  useEffect(() => { setProjectListOrigin(null); if (!status.authenticated) { setProjects([]); return } let live = true; call('projects').then(x => { if (!live) return; if (x.ok) { setProjects(x.projects); setProjectListOrigin(x.cached ? status.origin : null) } else setMessage(x.message || '无法获取项目列表') }).catch(() => { if (live) setMessage('无法获取项目列表') }); return () => { live = false } }, [status.authenticated, status.environment, status.origin, status.projectRevision]);
145
153
  useEffect(() => { let live = true; const load = () => call('localWorkspaces').then(x => { if (!live) return; if (x.ok) { setLocalWorkspaces(x.workspaces); setWorkspaceError('') } else { setLocalWorkspaces(null); setWorkspaceError(x.message || '无法读取 DSH 工作区') } }).catch(() => { if (live) { setLocalWorkspaces(null); setWorkspaceError('无法读取 DSH 工作区') } }); void load(); window.addEventListener('focus', load); return () => { live = false; window.removeEventListener('focus', load) } }, []);
146
154
  if (view === 'summary') return h('span', null, '共序登录和工作空间');
147
155
  const state = form?.state || loaded, value = draft || state?.value;
148
156
  const persistedRows = savedRows !== null ? savedRows : (Array.isArray(state?.value?.workspaces) ? state.value.workspaces : []);
149
- /** 这一行是不是已经保存过:保存过的项目不能再改,只能删除。 */
157
+ /** 这一行是不是已经保存过:保存过之后项目和关联工作区就不能再改了,只有动作还能改。 */
150
158
  function lockedFor(row) {
151
159
  if (!row.projectId) return false;
152
160
  if (state?.value?.projectId && state.value.projectId === row.projectId) return true;
153
161
  return persistedRows.some(item => rowIdentity(item) === rowIdentity(row));
154
162
  }
163
+ function canRunRow(row) {
164
+ const saved = persistedRows.find(item => rowIdentity(item) === rowIdentity(row) && item.workspaceId === row.workspaceId);
165
+ return Boolean(saved && normalizeAction(saved.mentionAction || saved.action) === normalizeAction(row.mentionAction || row.action)
166
+ && normalizeAction(saved.taskAction || saved.action) === normalizeAction(row.taskAction || row.action));
167
+ }
155
168
  /** 写入配置:环境、项目行,并清掉旧版的单项目字段。 */
156
- async function writeSettings(rows) {
169
+ async function writeSettings(rows, extraOps) {
157
170
  // 换环境前必须先退出登录:凭据是按环境分开存的,没退出就换会让两个环境同时登录着。
158
171
  // 要跟「已保存的环境」比,而不是跟草案比——草案改了之后两者会相等,就看不出切换了。
159
172
  if (switchesEnvironment(state && state.value, draft)) {
@@ -167,6 +180,7 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
167
180
  { op: 'set', path: ['projectId'], value: '' },
168
181
  { op: 'set', path: ['workspace'], value: '' },
169
182
  { op: 'set', path: ['receiveMessages'], value: false },
183
+ ...(extraOps || []),
170
184
  ];
171
185
  const result = form ? await form.mutate(ops, state.revision) : await remote.settings.mutate(ns, ops, state.revision);
172
186
  if (result === false || result?.ok === false) throw Error('设置保存失败');
@@ -196,11 +210,24 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
196
210
  setSavedRows(next);
197
211
  setDraft(draft ? { ...draft, workspaces: (draft.workspaces || []).map(item => rowIdentity(item) === identity ? { ...item, ...payload } : item) } : null);
198
212
  const result = await call('saveRow', { row: payload });
199
- if (!result?.ok) { setMessage(`配置已保存,但自动化任务没有更新:${result?.message || '请重试'}`); return }
213
+ if (!result?.ok) { setMessage(`${result?.automationReady ? '配置和自动化任务已保存,但本次未执行' : '配置已保存,但自动化任务没有更新'}:${result?.message || '请重试'}`); return }
200
214
  setMessage(result.created ? '已保存:自动化任务已新建' : '已保存:自动化任务已更新');
201
215
  } catch (error) { setMessage(error.message || '保存失败'); }
202
216
  finally { setBusy(false) }
203
217
  }
218
+ /** 立即执行一行:巡检一次并触发一次,让用户马上看到当前状态。 */
219
+ async function runRow(row) {
220
+ if (!row.projectId) { setMessage('请先选择项目'); return }
221
+ if (!row.workspaceId) { setMessage('请先选择关联工作区'); return }
222
+ if (!canRunRow(row)) { setMessage('请先保存项目及当前修改,再立即执行'); return }
223
+ setBusy(true);
224
+ try {
225
+ const result = await call('runRow', { row: rowPayload(row) });
226
+ if (!result?.ok) { setMessage(result?.message || '执行失败'); return }
227
+ setMessage(result.message || '已提交执行');
228
+ } catch (error) { setMessage(error.message || '执行失败'); }
229
+ finally { setBusy(false) }
230
+ }
204
231
  /** 删除之前先看清楚会牵动哪些自动化任务与会话。 */
205
232
  async function askRemove(row) {
206
233
  setBusy(true);
@@ -232,6 +259,38 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
232
259
  } catch (error) { setMessage(error.message || '无法读取当前环境状态'); }
233
260
  finally { setBusy(false) }
234
261
  }
262
+ /**
263
+ * 保存定时规则。
264
+ *
265
+ * 先让服务端校验一遍表达式:合法才写进配置,写完再把已有任务的
266
+ * 排程刷新一次,让新规则立刻生效。
267
+ */
268
+ async function saveCron() {
269
+ setBusy(true);
270
+ try {
271
+ const expression = String(cronDraft === null ? '' : cronDraft).trim();
272
+ const preview = await call('cronPreview', { expression: expression });
273
+ setCronInfo(preview);
274
+ if (!preview?.ok) { setMessage(preview?.message || 'cron 表达式不合法'); return }
275
+ await writeSettings(persistedRows, [
276
+ { op: 'set', path: ['cron'], value: preview.expression },
277
+ ]);
278
+ setCronDraft(preview.expression);
279
+ setDraft(draft ? { ...draft, cron: preview.expression } : null);
280
+ await call('syncAutomations', {});
281
+ setMessage('定时规则已保存:' + (preview.description || preview.expression));
282
+ } catch (error) { setMessage(error.message || '保存失败'); }
283
+ finally { setBusy(false) }
284
+ }
285
+
286
+ /** 边输入边看这个写法对不对、到底是什么时候跑。 */
287
+ async function checkCron(expression) {
288
+ setCronDraft(expression);
289
+ try {
290
+ const preview = await call('cronPreview', { expression: expression });
291
+ setCronInfo(preview);
292
+ } catch { setCronInfo(null); }
293
+ }
235
294
  /** 退出登录前先看当前环境还有没有项目:有项目就不能退。 */
236
295
  async function askLogout() {
237
296
  setBusy(true);
@@ -250,19 +309,19 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
250
309
  setPendingLogout(null);
251
310
  setMessage('请先删除全部项目,再退出登录');
252
311
  }
253
- /** 确认后:结束自动化任务、归档自动化会话,再移除这一行配置。 */
312
+ /** 先移除配置,防止后台同步重建任务;宿主确认删除后才关闭确认框。 */
254
313
  async function confirmRemoval() {
255
314
  const pending = pendingRemoval;
256
315
  if (!pending) return;
257
316
  setBusy(true);
258
317
  try {
259
- const result = await call('removeRow', { row: rowPayload(pending.row), sessionId: pending.plan.sessionId || '' });
260
- if (!result?.ok) { setMessage(result?.message || '删除失败'); return }
261
318
  const identity = rowIdentity(rowPayload(pending.row));
262
319
  const next = persistedRows.filter(item => rowIdentity(item) !== identity);
263
320
  await writeSettings(next);
264
321
  setSavedRows(next);
265
322
  setDraft(draft ? { ...draft, workspaces: (draft.workspaces || []).filter(item => rowIdentity(item) !== identity) } : null);
323
+ const result = await call('removeRow', { row: rowPayload(pending.row), sessionId: pending.plan.sessionId || '' });
324
+ if (!result?.ok) { setMessage('项目配置已移除,但自动化任务清理失败:' + (result?.message || '请重试删除')); return }
266
325
  setPendingRemoval(null);
267
326
  const parts = [];
268
327
  if (result.deleted) parts.push('自动化任务已结束');
@@ -310,6 +369,25 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
310
369
  status.pending ? h('button', { style: { ...styles.button, color: '#b7791f', borderColor: '#b7791f' }, disabled: busy, onClick: cancelLogin }, '取消授权') : null,
311
370
  status.authenticated && sameEnvironment ? h('button', { style: { ...styles.button, color: '#d14949', borderColor: '#d14949', opacity: busy ? 0.45 : 1 }, disabled: busy, onClick: () => askLogout() }, '退出登录') : null,
312
371
  h('span', { role: 'status', style: { flex: '0 0 100%', fontSize: 13, color: authColor } }, `${environmentChoices.find(item => item.id === env)?.title || '当前环境'}:${authState}`))),
372
+ h('section', { style: styles.section }, h('strong', null, '定时规则'),
373
+ h('div', { style: { display: 'flex', alignItems: 'flex-end', flexWrap: 'wrap', gap: 8 } },
374
+ h('div', { style: { ...styles.label, flex: '0 1 220px', minWidth: 180 } }, 'cron 表达式',
375
+ h('input', {
376
+ style: styles.input,
377
+ value: cronDraft === null ? String(value.cron || '*/5 * * * *') : cronDraft,
378
+ placeholder: '*/5 * * * *',
379
+ spellCheck: false,
380
+ onChange: event => { void checkCron(event.target.value); },
381
+ })),
382
+ h('button', { type: 'button', style: styles.button, disabled: busy, onClick: saveCron }, '保存定时规则'),
383
+ ),
384
+ h('small', { style: { color: 'var(--dsw-alias-label-secondary)' } }, '五段 cron:分 时 日 月 周。例如 */5 * * * * 表示每 5 分钟,0 9 * * 1 表示每周一 09:00。默认每 5 分钟,按中国标准时间计算。'),
385
+ cronInfo
386
+ ? cronInfo.ok
387
+ ? h('small', { style: { color: 'var(--dsw-alias-label-secondary)' } }, '当前规则:' + (cronInfo.description || cronInfo.expression) + '(' + (cronInfo.expression || '') + ')')
388
+ : h('small', { role: 'alert', style: { color: '#d14949' } }, '写法不对:' + (cronInfo.message || '请检查表达式'))
389
+ : null,
390
+ ),
313
391
  h('section', { style: { ...styles.section, borderBottom: 0 } }, h('div', { style: { display: 'flex', alignItems: 'center', gap: 12 } }, h('strong', null, '工作空间'), h('button', { type: 'button', style: styles.button, disabled: !status.authenticated || !sameEnvironment || refreshing, onClick: async () => { setRefreshing(true); try { const result = await call('refreshProjects'); if (!result.ok) throw Error(result.message); setProjects(result.projects); setProjectListOrigin(status.origin); setMessage('项目列表已更新') } catch (error) { setMessage(error.message || '获取项目列表失败') } finally { setRefreshing(false) } } }, refreshing ? '获取中…' : '获取项目列表')),
314
392
  workspaceError ? h('p', { role: 'alert' }, workspaceError) : null,
315
393
  ...visibleRows.map((row, ordinal) => {
@@ -321,14 +399,15 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
321
399
  ...[{ field: 'mentionAction', title: '被 @ 时' }, { field: 'taskAction', title: '任务待处理时' }].map(({ field, title }) => h('div', { key: field, style: { ...styles.label, flex: '1 1 150px', minWidth: 130 } }, ordinal === 0 ? title : null,
322
400
  h(ActionPicker, { action: normalizeAction(row[field] || row.action), label: `项目 ${ordinal + 1} ${title}`, onPick: choice => editRow(row.index, { [field]: choice, receiveMessages: true }) }))),
323
401
  automation ? h('button', { type: 'button', 'aria-label': '打开自动化会话', style: { ...styles.button, height: 36, padding: '0 8px 0 10px', display: 'inline-flex', alignItems: 'center', gap: 6, flex: 'none', maxWidth: 220 }, disabled: !automation.sessionId, title: automation.sessionId ? '打开自动化会话' : '保存这一行后就会建立自动化会话', onClick: () => { try { if (!automation.sessionId || !openSession) throw Error(); openSession(automation.sessionId) } catch { setMessage('当前 DSH 无法打开自动化会话') } } }, h('span', { style: { fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 170 } }, automation.sessionId ? (automation.sessionName || automation.title || '自动化会话') : '自动化会话'), h(ActionIcon, { name: 'chevron' })) : null,
324
- h('button', { type: 'button', 'aria-label': `保存项目 ${ordinal + 1}`, title: '保存这一行', style: { ...styles.button, width: 36, height: 36, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#395D40', borderColor: '#395D40', flex: 'none' }, disabled: busy || !row.projectId || !row.workspaceId, onClick: () => void saveRow(row) }, h(ActionIcon, { name: 'save' })),
402
+ h('button', { type: 'button', 'aria-label': `保存项目 ${ordinal + 1}`, title: '保存这一行', style: { ...styles.button, width: 36, height: 36, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#395D40', borderColor: '#395D40', flex: 'none' }, disabled: busy || !row.projectId || !row.workspaceId, onClick: () => void saveRow(row) }, h(ActionIcon, { name: 'save' })),h('button', { type: 'button', 'aria-label': `立即执行项目 ${ordinal + 1}`, title: canRunRow(row) ? '立即执行一次' : '请先保存项目及当前修改', style: { ...styles.button, width: 36, height: 36, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#395D40', borderColor: '#395D40', flex: 'none' }, disabled: busy || !row.projectId || !row.workspaceId || !sameEnvironment || !canRunRow(row), onClick: () => void runRow(row) }, h(ActionIcon, { name: 'paperPlane' })),
325
403
  h('button', { type: 'button', 'aria-label': `删除项目 ${ordinal + 1}`, title: '删除项目', style: { ...styles.button, width: 36, height: 36, padding: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: '#d14949', borderColor: '#d14949', flex: 'none' }, disabled: busy, onClick: () => void askRemove(row) }, h(ActionIcon, { name: 'trash' })));
326
404
  }),
327
- visibleRows.length ? h('small', { style: { color: 'var(--dsw-alias-label-secondary)' } }, '每个项目单独保存:保存后生成一个名为「共序-{项目名}」的自动化任务,关联所选工作区,新建会话并复用;任务会检查有没有被 @ 或待处理的任务,没有就保持沉默。保存过的项目不能再改,只能删除。') : null,
405
+ visibleRows.length ? h('small', { style: { color: 'var(--dsw-alias-label-secondary)' } }, '每个项目单独保存:建立「共序-{项目名}」任务与关联会话,并尝试执行一次。后台每 15 秒检查,按定时规则投递新内容;原生任务显示已暂停是正常状态。未保存的修改不能立即执行;宿主暂缓时会记录并重试。保存过的项目只能改动作,更换项目或工作区请先删除再添加。') : null,
328
406
  h('div', null,
329
407
  h('button', { type: 'button', style: { ...styles.button, display: 'inline-flex', alignItems: 'center', gap: 5 }, onClick: () => setDraft({ ...value, workspaces: [...rows, { environment: env, projectId: '', workspaceId: '', workspace: '', action: 'restate', mentionAction: 'restate', taskAction: 'restate', receiveMessages: true }], projectId: '' }) }, h(ActionIcon, { name: 'plus', size: 14 }), '添加项目'))),
330
408
  h(NotificationPermission),
331
409
  status.error || status.sessionError || status.pollError || message ? h('p', { role: 'status' }, status.error || status.sessionError || status.pollError || message) : null,
410
+ h('small', { style: { color: 'var(--dsw-alias-label-secondary)', display: 'block' } }, '上次巡检:' + pollTimeLabel(status.lastPollAt)),
332
411
  pendingLogout && pendingLogout.projects && pendingLogout.projects.length ? h(ConfirmDialog, {
333
412
  title: '不能退出登录',
334
413
  lines: [
@@ -643,36 +722,48 @@ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
643
722
  if (notice.seq <= last.current) continue;
644
723
  last.current = notice.seq;
645
724
  const api = webNotification();
646
- if (api && api.permission === 'granted') new api('共序有新消息', { body: notice.body || '请打开共序查看项目消息' });
725
+ // 桌面端自带通知能力,权限已经是 granted,直接弹;浏览器里没授权就不弹。
726
+ if (notificationReady(api)) new api('共序有新消息', { body: notice.body || '请打开共序查看项目消息' });
647
727
  }
648
728
  }, [status.notices]);
649
729
  return null;
650
730
  }
651
731
  /**
652
- * 只有真正的浏览器通知 API 才可用。
653
- * Electron 的主进程 Notification 没有 requestPermission / addEventListener,
654
- * 直接调用会抛错并让整页渲染失败,所以这里先做特性检测。
732
+ * 页面能不能弹系统通知。
733
+ *
734
+ * DSH 桌面端(dsh-app://)自带通知能力:window.Notification 存在、权限已经是 granted,
735
+ * 只是没有 addEventListener。检测只认「能不能构造通知」,别把权限变化监听当成硬要求,
736
+ * 否则会把本来好用的桌面端误判成「不支持」。
655
737
  */
656
738
  function webNotification() {
657
739
  if (typeof window === 'undefined') return null;
658
740
  const api = window.Notification;
659
- if (!api || typeof api.requestPermission !== 'function' || typeof api.addEventListener !== 'function') return null;
741
+ // 只看它存不存在:构造器是 function,实例是 object,两种都认。
742
+ if (!api || (typeof api !== 'function' && typeof api !== 'object')) return null;
660
743
  return api;
661
744
  }
745
+
746
+ /** 通知是不是已经获准直接弹。 */
747
+ function notificationReady(api) {
748
+ if (!api) return false;
749
+ if (api.permission === 'granted') return true;
750
+ return typeof api.requestPermission !== 'function'
751
+ }
662
752
  /** Show the browser notification permission state and let the user grant it. */
663
753
  function NotificationPermission() {
664
754
  const api = webNotification();
665
755
  const [permission, setPermission] = useState(api ? api.permission : 'unsupported');
666
756
  useEffect(() => {
667
- if (!api) return;
757
+ if (!api || typeof api.addEventListener !== 'function') return;
668
758
  const changed = () => setPermission(api.permission);
669
759
  api.addEventListener('permissionchange', changed);
670
760
  return () => api.removeEventListener('permissionchange', changed);
671
761
  }, [api]);
672
- if (permission === 'granted') return null;
762
+ // 已经获准:什么都不用说,也不用显示任何按钮。
763
+ if (notificationReady(api)) return null;
673
764
  return h('div', { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', paddingBottom: 12 } },
674
- h('span', { style: { fontSize: 13, color: 'var(--dsw-alias-label-secondary)' } }, permission === 'unsupported' ? '当前环境不支持系统通知。' : '系统通知未授权:收到共序消息时不会弹出桌面通知。'),
675
- permission === 'unsupported' || !api ? null : h('button', { type: 'button', style: styles.button, onClick: () => { void api.requestPermission().then(granted => setPermission(granted)).catch(() => setPermission(api.permission)) } }, '开启系统通知'));
765
+ h('span', { style: { fontSize: 13, color: 'var(--dsw-alias-label-secondary)' } }, '系统通知未授权:收到共序消息时不会弹出桌面通知。'),
766
+ api && typeof api.requestPermission === 'function' ? h('button', { type: 'button', style: styles.button, onClick: () => { void api.requestPermission().then(granted => setPermission(granted)).catch(() => setPermission(api.permission)) } }, '开启系统通知') : null);
676
767
  }
677
768
  /** 渲染出错时显示提示,而不是留下一个空白页面。 */
678
769
  class PanelBoundary extends React.Component {
package/package.json CHANGED
@@ -1,23 +1,22 @@
1
1
  {
2
2
  "name": "dsh-cothread-mcp",
3
- "version": "0.1.8",
3
+ "version": "0.1.11",
4
4
  "description": "连接共序 CoThread MCP,支持浏览器授权、项目设置及消息提醒。",
5
- "license": "MIT",
5
+ "license": "UNLICENSED",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://github.com/NingYuanLee/dsh-cothread-mcp.git"
9
9
  },
10
10
  "type": "module",
11
- "main": "src/index.js",
11
+ "main": "dist/index.js",
12
12
  "exports": {
13
- ".": "./src/index.js",
13
+ ".": "./dist/index.js",
14
14
  "./client": "./lib/client.js",
15
15
  "./package.json": "./package.json"
16
16
  },
17
17
  "files": [
18
- "src",
18
+ "dist",
19
19
  "lib/client.js",
20
- "scripts/build.mjs",
21
20
  "cordis.patch.yml",
22
21
  "icon.svg",
23
22
  "LICENSE",
@@ -26,8 +25,9 @@
26
25
  ],
27
26
  "scripts": {
28
27
  "test": "node --test test/*.test.js",
29
- "check": "node --check src/index.js && node --check src/authorization.js && node --check src/device.js && node --check src/version.js && node --check src/environments.js && node --check src/service.js && node --check src/events.js && node --check src/automation.js && node --check src/state.js && node --check lib/client.js",
30
- "build": "node scripts/build.mjs"
28
+ "check": "node --check src/index.js && node --check src/authorization.js && node --check src/device.js && node --check src/version.js && node --check src/environments.js && node --check src/service.js && node --check src/events.js && node --check src/automation.js && node --check src/state.js && node --check src/cron.js && node --check lib/client.js",
29
+ "build": "node scripts/build.mjs",
30
+ "pretest": "node scripts/build.mjs"
31
31
  },
32
32
  "engines": {
33
33
  "node": ">=22.19.0",
@@ -57,11 +57,15 @@
57
57
  "platform": "web"
58
58
  }
59
59
  },
60
+ "devDependencies": {
61
+ "esbuild": "^0.28.2"
62
+ },
60
63
  "peerDependencies": {
61
64
  "@deepseek-ai/cordis": ">=4.0.4 <5.0.0",
62
65
  "@deepseek-ai/dsh-credentials": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
63
66
  "@deepseek-ai/dsh-mcp-client": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
64
- "@deepseek-ai/schemastery": ">=3.18.4 <4.0.0",
65
- "@deepseek-ai/dsh-session": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0"
67
+ "@deepseek-ai/dsh-scope": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
68
+ "@deepseek-ai/dsh-session": ">=0.2.1-0 <0.3.0-0 || >=0.2.2-0 <0.3.0-0",
69
+ "@deepseek-ai/schemastery": ">=3.18.4 <4.0.0"
66
70
  }
67
71
  }
package/scripts/build.mjs DELETED
@@ -1,61 +0,0 @@
1
- /**
2
- * 发布前的构建期校验。
3
- *
4
- * 这个仓库没有编译产物:lib/client.js 是手写的浏览器 bundle,
5
- * 源码直接就是发布内容。所以 build 做的是「发布物完整性」检查:
6
- * 每个源文件都能被解析,package.json 的 files 覆盖了实际要发的文件,
7
- * 并且版本号在 CHANGELOG 里有对应条目——漏掉任何一样都会在发布时才暴露。
8
- */
9
- import { readFile, readdir, stat } from 'node:fs/promises'
10
- import { dirname, join, resolve } from 'node:path'
11
- import { fileURLToPath } from 'node:url'
12
- import { execFile } from 'node:child_process'
13
- import { promisify } from 'node:util'
14
-
15
- const run = promisify(execFile)
16
- const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
17
-
18
- async function listSources(dir) {
19
- const found = []
20
- for (const entry of await readdir(dir, { withFileTypes: true })) {
21
- const full = join(dir, entry.name)
22
- if (entry.isDirectory()) { found.push(...await listSources(full)); continue }
23
- if (entry.name.endsWith('.js') || entry.name.endsWith('.mjs')) found.push(full)
24
- }
25
- return found
26
- }
27
-
28
- const problems = []
29
-
30
- // 1) 每个源文件都要能被解析
31
- for (const dir of ['src', 'lib', 'scripts', 'test']) {
32
- let files = []
33
- try { files = await listSources(join(root, dir)) } catch { continue }
34
- for (const file of files) {
35
- try { await run(process.execPath, ['--check', file]) }
36
- catch (error) { problems.push(`语法错误:${file.replace(root + '\\', '')}\n${String(error.stderr || error.message).split('\n').slice(0, 4).join('\n')}`) }
37
- }
38
- }
39
-
40
- // 2) package.json 的 files 必须覆盖实际要发的文件
41
- const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
42
- // package.json、README、LICENSE 由 npm 自动附带,不必列进 files
43
- for (const required of ['src', 'lib/client.js', 'scripts/build.mjs', 'CHANGELOG.md', 'icon.svg']) {
44
- if (!Array.isArray(pkg.files) || !pkg.files.includes(required)) problems.push(`package.json 的 files 里少了 ${required}`)
45
- }
46
- if (!pkg.version) problems.push('package.json 缺少 version')
47
- if (!pkg.exports?.['.'] || !pkg.exports?.['./client']) problems.push('package.json 缺少主入口或 client 入口')
48
-
49
- // 3) CHANGELOG 要有当前版本的条目
50
- const changelog = await readFile(join(root, 'CHANGELOG.md'), 'utf8')
51
- if (!changelog.includes(`## ${pkg.version}`)) problems.push(`CHANGELOG.md 里没有 ${pkg.version} 的条目`)
52
-
53
- // 4) 图标得在
54
- try { await stat(join(root, 'icon.svg')) } catch { problems.push('缺少 icon.svg') }
55
-
56
- if (problems.length) {
57
- console.error('构建校验未通过:')
58
- for (const problem of problems) console.error(' - ' + problem)
59
- process.exit(1)
60
- }
61
- console.log(`构建校验通过:版本 ${pkg.version}`)
@@ -1,144 +0,0 @@
1
- import { createServer } from 'node:http'
2
- import { randomUUID } from 'node:crypto'
3
- import os from 'node:os'
4
-
5
- /** 问一次服务端「这次授权怎么样了」的间隔。 */
6
- const DEFAULT_POLL_INTERVAL_MS = 3000
7
- /** 服务端已拍板、但凭据还没回传时的宽限时间。 */
8
- const DEFAULT_DELIVERY_GRACE_MS = 20000
9
-
10
- /**
11
- * 发起一次 Agent 插件授权。
12
- *
13
- * @param {string} endpoint 服务根地址
14
- * @param {object} options
15
- * @param {Function} options.fetchImpl 便于测试
16
- * @param {number} options.timeoutMs 整体超时
17
- * @param {string} options.deviceId 本机稳定的设备身份;不传就临时生成一个
18
- * @param {string} options.version 插件版本号
19
- * @param {number} options.pollIntervalMs 轮询间隔
20
- * @param {number} options.deliveryGraceMs 凭据回传的宽限时间
21
- */
22
- export async function startAuthorization(endpoint, {
23
- fetchImpl = fetch,
24
- timeoutMs = 600000,
25
- deviceId,
26
- version = '0.0.0',
27
- pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
28
- deliveryGraceMs = DEFAULT_DELIVERY_GRACE_MS,
29
- } = {}) {
30
- const origin = new URL(endpoint).origin
31
- // 设备身份必须稳定:服务端按 device_id 认设备,每次都换新 ID 会被当成新设备——
32
- // 旧连接器被撤销、新记录重建,而「一个成员只能有一条 active 绑定」的唯一索引
33
- // 会让这次授权直接撞上冲突,浏览器点「确认授权」只会看到「记录已存在」。
34
- const localDeviceId = typeof deviceId === 'string' && deviceId.trim() ? deviceId.trim() : randomUUID()
35
- const response = await fetchImpl(new URL('/api/local-executor/v2/authorizations', origin), {
36
- method: 'POST', headers: { 'content-type': 'application/json' },
37
- body: JSON.stringify({ name: `DSH · ${os.hostname()}`, deviceId: localDeviceId, platform: process.platform, version }),
38
- signal: AbortSignal.timeout(10000),
39
- })
40
- if (!response.ok) throw new Error(`创建授权请求失败(HTTP ${response.status})`)
41
- const request = await response.json()
42
- if (!request.id || !request.pollToken || !request.verificationUrl) throw new Error('授权响应不完整')
43
- let verificationUrl = new URL(request.verificationUrl)
44
- // The current CoThread server always returns APP_ORIGIN, including in local development.
45
- // Rebase only its known authorization URL; never follow an arbitrary foreign origin.
46
- if (origin === 'http://127.0.0.1:3100' && verificationUrl.origin === 'https://cothread.z2l.top' && verificationUrl.pathname === '/' && verificationUrl.searchParams.get('localExecutorAuthorization') === request.id) {
47
- verificationUrl = new URL(verificationUrl.pathname + verificationUrl.search, origin)
48
- }
49
- if (verificationUrl.origin !== origin) throw new Error('授权页面与服务地址不一致')
50
- let timer
51
- let pollTimer
52
- let graceTimer
53
- let settled = false
54
- let resolveResult
55
- let rejectResult
56
- const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject })
57
- // A rejected result may arrive before callers attach their handler.
58
- result.catch(() => {})
59
- function finish() { clearTimeout(timer); clearInterval(pollTimer); clearTimeout(graceTimer); server.close() }
60
- function succeed(payload) { if (settled) return; settled = true; finish(); resolveResult(payload) }
61
- function fail(error) { if (settled) return; settled = true; finish(); rejectResult(error) }
62
- const server = createServer((req, res) => {
63
- if (req.headers.origin !== origin || req.url !== '/local-executor-authorization') { res.writeHead(403).end(); return }
64
- res.setHeader('Access-Control-Allow-Origin', origin)
65
- res.setHeader('Vary', 'Origin')
66
- res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
67
- res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
68
- res.setHeader('Access-Control-Private-Network', 'true')
69
- if (req.method === 'OPTIONS') { res.writeHead(204).end(); return }
70
- if (req.method !== 'POST') { res.writeHead(405).end(); return }
71
- let body = ''
72
- req.setEncoding('utf8')
73
- req.on('data', chunk => { body += chunk; if (body.length > 8192) req.destroy() })
74
- req.on('end', () => {
75
- let data
76
- try { data = JSON.parse(body) } catch { res.writeHead(400).end(); return }
77
- if (data.authorizationId !== request.id || data.callbackSecret !== request.pollToken) { res.writeHead(403).end(); return }
78
- if (data.status === 'approved' && typeof data.token === 'string' && data.token.startsWith('ctc_')) {
79
- res.writeHead(200).end()
80
- // deviceId 是我们发出去的身份(服务端按它认设备);data.id 是服务端那条连接器记录的 id,只用于排查。
81
- succeed({ deviceId: localDeviceId, executorId: typeof data.id === 'string' ? data.id : '', token: data.token })
82
- } else if (data.status === 'denied') {
83
- res.writeHead(200).end(); fail(new Error('用户已拒绝授权'))
84
- } else res.writeHead(400).end()
85
- })
86
- })
87
- await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })
88
- verificationUrl.searchParams.set('localExecutorCallbackPort', String(server.address().port))
89
- verificationUrl.searchParams.set('localExecutorClient', 'dsh')
90
- const hash = new URLSearchParams(verificationUrl.hash.slice(1))
91
- hash.set('connectorCallbackSecret', request.pollToken)
92
- verificationUrl.hash = hash.toString()
93
- timer = setTimeout(() => fail(new Error('授权已超时,请重新发起')), Math.min(timeoutMs, Number(request.expiresIn || 600) * 1000))
94
- timer.unref?.()
95
-
96
- /**
97
- * 问一次服务端这次授权怎么样了。
98
- *
99
- * 浏览器那边点「拒绝」或者关掉弹窗时,回环回调可能永远不来(回调是浏览器页面发的,
100
- * 页面关了就没了),插件就只能干等到超时。这里轮询服务端已有的 poll 接口,
101
- * 让「用户拒绝」能立刻结束。
102
- */
103
- async function pollOnce() {
104
- if (settled) return
105
- let response
106
- try {
107
- response = await fetchImpl(new URL(`/api/local-executor/v2/authorizations/${request.id}/poll`, origin), {
108
- method: 'POST', headers: { 'content-type': 'application/json' },
109
- body: JSON.stringify({ pollToken: request.pollToken }),
110
- signal: AbortSignal.timeout(10000),
111
- })
112
- } catch { return }
113
- if (settled) return
114
- if (response.status === 403) { fail(new Error('用户已拒绝授权')); return }
115
- if (response.status === 410) { fail(new Error('网页登录授权已过期,请重新发起')); return }
116
- if (response.status === 409) {
117
- // 授权结果已经被领取:浏览器已经拍板,凭据正在回传的路上(也可能没传回来)。
118
- // 这是正常终态,不再轮询;但留一点时间等回环回调,等到还没消息就明确报错。
119
- clearInterval(pollTimer); pollTimer = undefined
120
- graceTimer = setTimeout(() => fail(new Error('浏览器已确认授权,但凭据没有回传到本机,请重新授权')), deliveryGraceMs)
121
- graceTimer.unref?.()
122
- return
123
- }
124
- if (!response.ok) return
125
- let data
126
- try { data = await response.json() } catch { return }
127
- if (data && data.status === 'approved' && typeof data.token === 'string' && data.token.startsWith('ctc_')) {
128
- succeed({ deviceId: localDeviceId, executorId: typeof data.id === 'string' ? data.id : '', token: data.token })
129
- }
130
- }
131
- pollTimer = setInterval(() => { void pollOnce() }, pollIntervalMs)
132
- pollTimer.unref?.()
133
- return { url: verificationUrl.href, result, cancel() { fail(new Error('授权已取消')) } }
134
- }
135
-
136
- export async function getMcpCredential(endpoint, deviceToken, fetchImpl = fetch) {
137
- const response = await fetchImpl(new URL('/api/local-executor/mcp-credential', endpoint), {
138
- method: 'POST', headers: { authorization: `Bearer ${deviceToken}` }, signal: AbortSignal.timeout(10000),
139
- })
140
- if (!response.ok) throw new Error(`获取 MCP 凭据失败(HTTP ${response.status})`)
141
- const data = await response.json()
142
- if (typeof data.token !== 'string' || !data.token) throw new Error('MCP 凭据响应不完整')
143
- return data
144
- }