dsh-cothread-mcp 0.1.0 → 0.1.3

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,732 @@
1
+ window.__ModuleLoader__.load({ id: 'dsh-cothread-mcp', factory: require => {
2
+ const React = require('react'), { useEffect, useState } = React, h = React.createElement;
3
+ const ns = 'cothread-mcp';
4
+ let sharedIcons = {}; try { sharedIcons = require('@deepseek-ai/dsh-client-ui-primitives') } catch {}
5
+ let ReactDOM = {}; try { ReactDOM = require('react-dom') } catch {}
6
+ /** 把弹层挂到 body 上:留在侧边栏里会继承它的毛玻璃与裁剪,菜单会又透又错位。 */
7
+ function portal(node, container) {
8
+ if (ReactDOM.createPortal && container) return ReactDOM.createPortal(node, container)
9
+ return node
10
+ }
11
+ async function call(method, args) {
12
+ const endpoint = 'cothread/' + method;
13
+ const res = await fetch('/api/' + endpoint, { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ type: 'client-request', rpcId: crypto.randomUUID(), method: endpoint, payload: { args: args || {} } }) });
14
+ if (!res.ok) throw new Error('请求失败(HTTP ' + res.status + ')');
15
+ const data = await res.json();
16
+ if (!data.result?.ok) throw new Error(data.result?.error?.message || '请求失败');
17
+ return data.result.value;
18
+ }
19
+ const styles = {
20
+ page: { maxWidth: 1280, display: 'grid', gap: 16, color: 'var(--dsw-alias-label-primary)' },
21
+ section: { display: 'grid', gap: 12, padding: '0 0 20px', borderBottom: '1px solid var(--dsw-alias-border-l4)' },
22
+ label: { display: 'grid', gap: 6, fontSize: 13 },
23
+ input: { height: 36, width: '100%', boxSizing: 'border-box', color: 'inherit', background: 'var(--dsw-alias-bg-layer-1)', border: '1px solid var(--dsw-alias-border-l2)', borderRadius: 8, padding: '0 10px' },
24
+ button: { cursor: 'pointer', height: 30, boxSizing: 'border-box', padding: '0 10px', fontSize: 13, lineHeight: '20px', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)', color: 'inherit', background: 'var(--dsw-alias-bg-layer-1)' },
25
+ };
26
+ function configuredRows(value) {
27
+ if (Array.isArray(value?.workspaces) && value.workspaces.length) return value.workspaces.map(row => ({ ...row }));
28
+ return value?.projectId ? [{ environment: value.environment || 'production', projectId: value.projectId, workspace: value.workspace || '', receiveMessages: value.receiveMessages === true, mentionAction: 'restate', taskAction: 'restate' }] : [];
29
+ }
30
+ /**
31
+ * 这次保存算不算换环境。
32
+ *
33
+ * 要跟「已保存的环境」比:草案改了环境之后,草案和已保存值会一起变,
34
+ * 只看草案就看不出切换发生了。换环境前必须先退出登录,这个判断要准。
35
+ */
36
+ /** 环境名归一化:自定义环境已下线,残留的 'custom' 一律按正式环境算。 */
37
+ function normalizeEnvironment(name) {
38
+ const key = String(name || 'production');
39
+ return key === 'custom' ? 'production' : key;
40
+ }
41
+ function switchesEnvironment(saved, draft) {
42
+ if (!saved) return false;
43
+ // 自定义环境已经下线。老配置里残留的 'custom' 要按正式环境算,
44
+ // 否则它跟 'production' 会被判成换了环境,白白要求用户先退出登录。
45
+ const savedEnv = normalizeEnvironment(saved.environment);
46
+ const targetEnv = normalizeEnvironment((draft && draft.environment) || savedEnv);
47
+ return targetEnv !== savedEnv;
48
+ }
49
+ /** 一行项目的身份:同一环境里的同一个项目只能有一行。 */
50
+ function rowIdentity(row) {
51
+ return `${row?.environment || 'production'}|${row?.projectId || ''}`;
52
+ }
53
+ /** 送给插件后端的行数据。 */
54
+ function rowPayload(row) {
55
+ return {
56
+ environment: row.environment || 'production',
57
+ projectId: row.projectId || '',
58
+ workspaceId: row.workspaceId || '',
59
+ workspace: row.workspace || '',
60
+ mentionAction: normalizeAction(row.mentionAction || row.action),
61
+ taskAction: normalizeAction(row.taskAction || row.action),
62
+ receiveMessages: true,
63
+ };
64
+ }
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' };
67
+ const SharedIcon = sharedIcons[names[name]];
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' };
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
+ }
72
+ function ChoicePicker({ items, selectedId, onPick, label, placeholder, missingLabel, emptyLabel, disabled = false, menuWidth = 320, invalid = false, displayItem, keepOpenOnPick = false, onOpen }) {
73
+ const [open, setOpen] = useState(false), [, reposition] = useState(0);
74
+ const root = React.useRef(null), anchor = React.useRef(null), menu = React.useRef(null);
75
+ const selected = displayItem || items?.find(item => item.id === selectedId);
76
+ const text = selected?.title || (selectedId ? missingLabel : placeholder);
77
+ useEffect(() => {
78
+ if (!open) return;
79
+ const dismiss = event => { if (!root.current?.contains(event.target)) setOpen(false) };
80
+ const onKey = event => { if (event.key === 'Escape') { setOpen(false); anchor.current?.focus() } };
81
+ const move = () => reposition(n => n + 1);
82
+ document.addEventListener('pointerdown', dismiss, true); document.addEventListener('keydown', onKey, true);
83
+ window.addEventListener('resize', move); window.addEventListener('scroll', move, true);
84
+ return () => { document.removeEventListener('pointerdown', dismiss, true); document.removeEventListener('keydown', onKey, true); window.removeEventListener('resize', move); window.removeEventListener('scroll', move, true) };
85
+ }, [open]);
86
+ const rect = open ? anchor.current?.getBoundingClientRect() : null;
87
+ const width = rect ? Math.min(Math.max(rect.width, menuWidth), 360, window.innerWidth - 24) : 0;
88
+ const left = rect ? Math.max(12, Math.min(rect.right - width, window.innerWidth - width - 12)) : 0;
89
+ const below = rect ? window.innerHeight - rect.bottom - 12 : 0;
90
+ const above = rect ? rect.top - 12 : 0;
91
+ const upwards = below < 180 && above > below;
92
+ const maxHeight = Math.max(80, Math.min(300, upwards ? above : below));
93
+ function moveFocus(event) {
94
+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
95
+ const choices = [...(menu.current?.querySelectorAll('[role="option"]') || [])];
96
+ if (!choices.length) return;
97
+ event.preventDefault();
98
+ const index = choices.indexOf(document.activeElement);
99
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? choices.length - 1 : event.key === 'ArrowDown' ? (index + 1) % choices.length : (index <= 0 ? choices.length - 1 : index - 1);
100
+ choices[next].focus();
101
+ }
102
+ return h('div', { ref: root, style: { position: 'relative', minWidth: 0 } },
103
+ h('style', null, '[data-cothread-workspace-option]:hover, [data-cothread-workspace-option]:focus-visible { background: var(--dsw-alias-interactive-bg-hover, #8882) !important; outline: none; }'),
104
+ h('button', { ref: anchor, type: 'button', disabled: !items || disabled, 'aria-label': `${label}:${text}`, 'aria-haspopup': 'listbox', 'aria-expanded': open, 'aria-invalid': invalid || undefined, onClick: () => { if (!open) onOpen?.(); setOpen(!open) }, onKeyDown: event => { if (event.key === 'ArrowDown' && items?.length) { event.preventDefault(); setOpen(true); requestAnimationFrame(() => menu.current?.querySelector('[role="option"]')?.focus()) } }, style: { ...styles.input, border: invalid ? '1px solid #d14949' : '0.5px solid var(--dsw-alias-border-l2)', color: invalid ? '#d14949' : 'inherit', borderRadius: 'var(--dsw-radius-md, 12px)', font: 'inherit', fontSize: 13, cursor: items && !disabled ? 'pointer' : 'default', textAlign: 'left', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 6 } }, h('span', { style: { display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 } }, selected?.icon ? h(ActionIcon, { name: selected.icon }) : null, h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, text)), h(ActionIcon, { name: 'down', size: 14 })),
105
+ open && rect ? h('div', { ref: menu, role: 'listbox', 'aria-label': `${label}列表`, 'data-menu-material': '', onKeyDown: moveFocus, style: { position: 'fixed', zIndex: 1100, left, width, ...(upwards ? { bottom: window.innerHeight - rect.top + 4 } : { top: rect.bottom + 4 }), maxHeight, overflowY: 'auto', padding: 4, boxSizing: 'border-box', border: 0, borderRadius: 'var(--dsw-radius-lg, 16px)', background: 'var(--dsw-specific-menu, var(--dsw-alias-bg-layer-2))', backdropFilter: 'var(--dsw-menu-backdrop-filter, blur(40px) saturate(150%))', WebkitBackdropFilter: 'var(--dsw-menu-backdrop-filter, blur(40px) saturate(150%))', boxShadow: 'var(--dsw-elevation-prominent, var(--dsw-elevation-panel))', '--dsw-elevation-stroke-color': 'var(--dsw-alias-border-l1)' } },
106
+ ...(items.length ? items.map(item => h('button', { key: item.id, type: 'button', role: 'option', 'data-cothread-workspace-option': '', 'aria-selected': item.id === selectedId, onClick: () => { onPick(item.id); if (!keepOpenOnPick) { setOpen(false); anchor.current?.focus() } }, style: { display: 'flex', alignItems: 'center', gap: 6, width: '100%', minWidth: 0, minHeight: 34, textAlign: 'left', padding: '6px 8px', border: 0, borderRadius: 'var(--dsw-radius-md, 12px)', cursor: 'pointer', font: 'inherit', fontSize: 13, lineHeight: '20px', color: 'var(--dsw-alias-label-primary)', background: 'transparent' } }, item.icon ? h(ActionIcon, { name: item.icon, size: 14 }) : null, h('span', { style: { display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0, flex: '1 1 auto' } }, h('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, item.title), item.path ? h('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 12, lineHeight: '18px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: item.path }, item.path) : null), item.id === selectedId ? h(ActionIcon, { name: 'check' }) : null)) : [h('div', { key: 'empty', style: { padding: 12, color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, emptyLabel)])) : null);
107
+ }
108
+ function ActionPicker({ action, label, onPick }) {
109
+ const items = [
110
+ { id: 'restate', title: '复述', path: '只复述内容,提醒你关注' },
111
+ { id: 'analyze', title: '思路', path: '先分析,再回复或处理' },
112
+ ];
113
+ return h(ChoicePicker, { items, selectedId: action, menuWidth: 260, label, placeholder: '请选择动作', missingLabel: '请选择动作', onPick: id => onPick(id) });
114
+ }
115
+ /** 旧配置里的动作值折算成现在的动作。 */
116
+ function normalizeAction(value) {
117
+ const raw = String(value || '').trim();
118
+ return raw === 'analyze' || raw === 'reuse' || raw === 'new' ? 'analyze' : 'restate';
119
+ }
120
+ /** 找到某个项目对应的自动化任务。 */
121
+ function automationOf(status, row) {
122
+ return (status.automations || []).find(item => item.projectId === row.projectId && item.workspaceId === row.workspaceId) || null;
123
+ }
124
+ const environmentChoices = [{ id: 'production', title: '正式环境', path: 'https://cothread.z2l.top/' }, { id: 'local', title: '本地环境', path: 'http://127.0.0.1:3100/' }];
125
+ function useStatus() {
126
+ const [status, setStatus] = useState({});
127
+ 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) } }, []);
128
+ return status;
129
+ }
130
+ /** 删除前的二次确认弹窗:把会结束的自动化任务与会话摊开给用户看。 */
131
+ function ConfirmDialog({ title, lines, confirmLabel, busy, onConfirm, onCancel }) {
132
+ return h('div', { style: { position: 'fixed', inset: 0, zIndex: 1200, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0, 0, 0, .45)', padding: 16 }, onClick: event => { if (event.target === event.currentTarget && !busy) onCancel() } },
133
+ h('div', { role: 'dialog', 'aria-modal': 'true', 'aria-label': title, style: { width: 'min(460px, 100%)', background: 'var(--dsw-alias-bg-layer-2)', borderRadius: 'var(--dsw-radius-lg, 16px)', padding: 20, display: 'grid', gap: 12, boxShadow: 'var(--dsw-elevation-prominent, var(--dsw-elevation-panel))', '--dsw-elevation-stroke-color': 'var(--dsw-alias-border-l1)' } },
134
+ h('strong', { style: { fontSize: 15 } }, title),
135
+ h('div', { style: { display: 'grid', gap: 6, fontSize: 13, lineHeight: '20px', color: 'var(--dsw-alias-label-secondary)' } }, ...(lines || []).map((line, index) => h('div', { key: index, style: { overflowWrap: 'anywhere' } }, line))),
136
+ h('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8 } },
137
+ h('button', { type: 'button', style: styles.button, disabled: busy, onClick: onCancel }, '取消'),
138
+ h('button', { type: 'button', style: { ...styles.button, background: '#d14949', borderColor: '#d14949', color: '#fff', opacity: busy ? 0.5 : 1 }, disabled: busy, onClick: onConfirm }, confirmLabel))));
139
+ }
140
+ function Settings({ form, remote, view, openSession }) {
141
+ 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);
143
+ 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
+ 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
+ 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
+ if (view === 'summary') return h('span', null, '共序登录和工作空间');
147
+ const state = form?.state || loaded, value = draft || state?.value;
148
+ const persistedRows = savedRows !== null ? savedRows : (Array.isArray(state?.value?.workspaces) ? state.value.workspaces : []);
149
+ /** 这一行是不是已经保存过:保存过的项目不能再改,只能删除。 */
150
+ function lockedFor(row) {
151
+ if (!row.projectId) return false;
152
+ if (state?.value?.projectId && state.value.projectId === row.projectId) return true;
153
+ return persistedRows.some(item => rowIdentity(item) === rowIdentity(row));
154
+ }
155
+ /** 写入配置:环境、项目行,并清掉旧版的单项目字段。 */
156
+ async function writeSettings(rows) {
157
+ // 换环境前必须先退出登录:凭据是按环境分开存的,没退出就换会让两个环境同时登录着。
158
+ // 要跟「已保存的环境」比,而不是跟草案比——草案改了之后两者会相等,就看不出切换了。
159
+ if (switchesEnvironment(state && state.value, draft)) {
160
+ const plan = await call('planEnvironmentSwitch')
161
+ if (!plan?.ok) throw Error(plan?.message || '无法读取当前环境状态')
162
+ if (plan.authenticated) throw Error('当前环境还处于登录状态,请先退出登录再切换环境')
163
+ }
164
+ const ops = [
165
+ { op: 'set', path: ['environment'], value: env },
166
+ { op: 'set', path: ['workspaces'], value: rows },
167
+ { op: 'set', path: ['projectId'], value: '' },
168
+ { op: 'set', path: ['workspace'], value: '' },
169
+ { op: 'set', path: ['receiveMessages'], value: false },
170
+ ];
171
+ const result = form ? await form.mutate(ops, state.revision) : await remote.settings.mutate(ns, ops, state.revision);
172
+ if (result === false || result?.ok === false) throw Error('设置保存失败');
173
+ if (!form && result?.value?.value) setLoaded(result.value);
174
+ return result;
175
+ }
176
+ /** 只保存环境设置:授权登录前先把环境定下来。 */
177
+ async function persistEnv() {
178
+ if (!value || !state) return false;
179
+ setBusy(true);
180
+ try { await writeSettings(persistedRows); return true; }
181
+ catch (error) { setMessage(error.message || '设置保存失败'); return false; }
182
+ finally { setBusy(false) }
183
+ }
184
+ /** 保存一行项目:配置只落这一行,自动化任务没有就新建、有就更新。 */
185
+ async function saveRow(row) {
186
+ if (!row.projectId) { setMessage('请先选择项目'); return }
187
+ if (!row.workspaceId) { setMessage('请先选择关联工作区'); return }
188
+ const payload = rowPayload(row);
189
+ const identity = rowIdentity(payload);
190
+ const index = persistedRows.findIndex(item => rowIdentity(item) === identity);
191
+ if (persistedRows.some((item, i) => i !== index && rowIdentity(item) === identity)) { setMessage('同一环境中的项目不能重复添加'); return }
192
+ setBusy(true);
193
+ try {
194
+ const next = index >= 0 ? persistedRows.map((item, i) => i === index ? { ...item, ...payload } : item) : [...persistedRows, payload];
195
+ await writeSettings(next);
196
+ setSavedRows(next);
197
+ setDraft(draft ? { ...draft, workspaces: (draft.workspaces || []).map(item => rowIdentity(item) === identity ? { ...item, ...payload } : item) } : null);
198
+ const result = await call('saveRow', { row: payload });
199
+ if (!result?.ok) { setMessage(`配置已保存,但自动化任务没有更新:${result?.message || '请重试'}`); return }
200
+ setMessage(result.created ? '已保存:自动化任务已新建' : '已保存:自动化任务已更新');
201
+ } catch (error) { setMessage(error.message || '保存失败'); }
202
+ finally { setBusy(false) }
203
+ }
204
+ /** 删除之前先看清楚会牵动哪些自动化任务与会话。 */
205
+ async function askRemove(row) {
206
+ setBusy(true);
207
+ try {
208
+ const plan = await call('planRemoval', { row: rowPayload(row) });
209
+ if (!plan?.ok) { setMessage(plan?.message || '无法检查自动化任务'); return }
210
+ setPendingRemoval({ row, plan });
211
+ } catch (error) { setMessage(error.message || '无法检查自动化任务'); }
212
+ finally { setBusy(false) }
213
+ }
214
+ /**
215
+ * 切换环境。
216
+ *
217
+ * 每个环境的凭据是分开的:当前环境还登录着时,必须先退出登录,
218
+ * 否则两个环境的凭据会同时留着,自动化任务也会认错环境。
219
+ */
220
+ async function pickEnvironment(next) {
221
+ if (next === env) return;
222
+ setBusy(true);
223
+ try {
224
+ const plan = await call('planEnvironmentSwitch');
225
+ if (!plan?.ok) { setMessage(plan?.message || '无法读取当前环境状态'); return }
226
+ if (plan.authenticated) {
227
+ setMessage('当前环境还处于登录状态,请先退出登录再切换环境');
228
+ return;
229
+ }
230
+ setDraft({ ...value, environment: next, workspaces: rows, projectId: '' });
231
+ setMessage('环境已切换,请点击授权登录');
232
+ } catch (error) { setMessage(error.message || '无法读取当前环境状态'); }
233
+ finally { setBusy(false) }
234
+ }
235
+ /** 退出登录前先看当前环境还有没有项目:有项目就不能退。 */
236
+ async function askLogout() {
237
+ setBusy(true);
238
+ try {
239
+ const plan = await call('planDisconnect');
240
+ if (!plan?.ok) { setMessage(plan?.message || '无法检查项目配置'); return }
241
+ // 没有项目就直接退出;有项目才弹窗拦下来。
242
+ if (plan.hasProjects) { setPendingLogout(plan); return }
243
+ const result = await call('disconnect')
244
+ setMessage(result?.ok ? '已退出本机授权' : (result?.message || '退出失败'));
245
+ } catch (error) { setMessage(error.message || '无法检查项目配置'); }
246
+ finally { setBusy(false) }
247
+ }
248
+ /** 弹窗上的「知道了」:关掉提示,提醒先删项目。 */
249
+ function dismissLogout() {
250
+ setPendingLogout(null);
251
+ setMessage('请先删除全部项目,再退出登录');
252
+ }
253
+ /** 确认后:结束自动化任务、归档自动化会话,再移除这一行配置。 */
254
+ async function confirmRemoval() {
255
+ const pending = pendingRemoval;
256
+ if (!pending) return;
257
+ setBusy(true);
258
+ try {
259
+ const result = await call('removeRow', { row: rowPayload(pending.row), sessionId: pending.plan.sessionId || '' });
260
+ if (!result?.ok) { setMessage(result?.message || '删除失败'); return }
261
+ const identity = rowIdentity(rowPayload(pending.row));
262
+ const next = persistedRows.filter(item => rowIdentity(item) !== identity);
263
+ await writeSettings(next);
264
+ setSavedRows(next);
265
+ setDraft(draft ? { ...draft, workspaces: (draft.workspaces || []).filter(item => rowIdentity(item) !== identity) } : null);
266
+ setPendingRemoval(null);
267
+ const parts = [];
268
+ if (result.deleted) parts.push('自动化任务已结束');
269
+ if (result.archived) parts.push('自动化会话已归档');
270
+ if (result.archiveMissing) parts.push('自动化会话还没建立,无需归档');
271
+ if (result.archiveError) parts.push(`自动化会话归档失败:${result.archiveError}`);
272
+ setMessage(parts.length ? `已删除:${parts.join(',')}` : '已删除这个项目的配置');
273
+ } catch (error) { setMessage(error.message || '删除失败'); }
274
+ finally { setBusy(false) }
275
+ }
276
+ /** 取消进行中的授权:浏览器授权页被关掉时,靠这个按钮脱身。 */
277
+ async function cancelLogin() {
278
+ setBusy(true);
279
+ try {
280
+ const result = await call('cancelAuthorization');
281
+ setMessage(result?.message || '已取消授权');
282
+ } catch (error) { setMessage(error.message || '取消失败'); }
283
+ finally { setBusy(false) }
284
+ }
285
+ async function login() { if (!await persistEnv()) return; if (!sameEnvironment) { setMessage('环境已保存,请再次点击授权登录'); return } try { const result = await call('authorize'); if (!result.ok) throw Error(result.message); window.open(result.url, '_blank', 'noopener,noreferrer'); setMessage('请在共序页面完成授权'); } catch (e) { setMessage(e.message || '无法发起授权') } }
286
+ if (!value) return h('p', null, message || '正在加载共序设置…');
287
+ const env = value.environment || 'production';
288
+ const rows = Array.isArray(value.workspaces) && (value.workspaces.length || !value.projectId) ? value.workspaces : configuredRows(value);
289
+ const activeOrigin = environmentChoices.find(item => item.id === env)?.path.replace(/\/$/, '');
290
+ const sameEnvironment = status.environment === env && status.origin === activeOrigin;
291
+ // 当前环境还登录着时,环境下拉置灰:得先退出登录。
292
+ // status 说的是已保存环境的授权状态,正是「正在离开的那个环境」。
293
+ const envLocked = Boolean(status.authenticated);
294
+ const authState = status.pending && sameEnvironment ? '等待浏览器授权' : !sameEnvironment ? '环境尚未切换,请保存设置' : status.authenticated ? '已授权' : '未授权';
295
+ const authColor = status.pending && sameEnvironment || !sameEnvironment ? '#b7791f' : status.authenticated ? '#27834a' : '#d14949';
296
+ const visibleRows = rows.map((row, index) => ({ ...row, index })).filter(row => row.environment === env);
297
+ function editRow(index, changes) { setDraft({ ...value, workspaces: rows.map((row, i) => i === index ? { ...row, ...changes } : row) }) }
298
+ return h('div', { style: styles.page, 'data-cothread-page': '' },
299
+ h('style', null, `[data-cothread-page] button { transition: box-shadow 140ms ease, transform 100ms ease, opacity 140ms ease; }
300
+ @media (hover: hover) { [data-cothread-page] button:not(:disabled):hover { box-shadow: inset 0 0 0 999px color-mix(in srgb, currentColor 8%, transparent); } }
301
+ [data-cothread-page] button:not(:disabled):active { transform: scale(.97); box-shadow: inset 0 0 0 999px color-mix(in srgb, currentColor 14%, transparent); }
302
+ [data-cothread-page] button:focus-visible { outline: 2px solid var(--dsw-alias-label-secondary, #718096); outline-offset: 2px; }
303
+ [data-cothread-page] button:disabled { cursor: not-allowed !important; opacity: .45; }
304
+ @media (prefers-reduced-motion: reduce) { [data-cothread-page] button { transition: none; } [data-cothread-page] button:not(:disabled):active { transform: none; } }`),
305
+ h('h2', null, '共序自动化'),
306
+ h('section', { style: styles.section }, h('strong', null, '授权登录'),
307
+ h('div', { style: { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 8 } },
308
+ h('div', { style: { flex: '0 0 160px', maxWidth: '100%' } }, h(ChoicePicker, { items: environmentChoices, selectedId: env, menuWidth: 220, label: '环境', placeholder: '请选择环境', missingLabel: '未知环境', disabled: envLocked, onPick: next => pickEnvironment(next) })),
309
+ h('button', { style: { ...styles.button, display: 'inline-flex', alignItems: 'center', gap: 5, color: '#27834a', borderColor: '#27834a' }, disabled: busy || status.pending, onClick: login }, h(ActionIcon, { name: 'external', size: 14 }), status.authenticated && sameEnvironment ? '重新授权' : '授权登录'),
310
+ status.pending ? h('button', { style: { ...styles.button, color: '#b7791f', borderColor: '#b7791f' }, disabled: busy, onClick: cancelLogin }, '取消授权') : null,
311
+ status.authenticated && sameEnvironment ? h('button', { style: { ...styles.button, color: '#d14949', borderColor: '#d14949', opacity: busy ? 0.45 : 1 }, disabled: busy, onClick: () => askLogout() }, '退出登录') : null,
312
+ h('span', { role: 'status', style: { flex: '0 0 100%', fontSize: 13, color: authColor } }, `${environmentChoices.find(item => item.id === env)?.title || '当前环境'}:${authState}`))),
313
+ 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
+ workspaceError ? h('p', { role: 'alert' }, workspaceError) : null,
315
+ ...visibleRows.map((row, ordinal) => {
316
+ const locked = lockedFor(row);
317
+ const automation = automationOf(status, row);
318
+ return h('div', { key: row.index, style: { display: 'flex', flexWrap: 'wrap', alignItems: 'end', gap: 8, padding: 0 } },
319
+ h('div', { style: { ...styles.label, flex: '1 1 170px', minWidth: 130 } }, ordinal === 0 ? '项目' : null, h(ChoicePicker, { items: projects.filter(p => p.id === row.projectId || !visibleRows.some(other => other.index !== row.index && other.projectId === p.id)).map(p => ({ id: p.id, title: p.name })), selectedId: row.projectId || '', menuWidth: 220, label: `项目 ${ordinal + 1}`, placeholder: '请选择项目', missingLabel: projectListOrigin === activeOrigin && sameEnvironment ? '项目已不在列表中' : '已选项目(暂不可用)', invalid: Boolean(row.projectId && sameEnvironment && projectListOrigin === activeOrigin && !projects.some(p => p.id === row.projectId)), emptyLabel: status.authenticated ? '暂无未选择的项目' : '请先授权登录', disabled: !sameEnvironment || locked, onPick: id => editRow(row.index, { projectId: id }) }), row.projectId && sameEnvironment && projectListOrigin === activeOrigin && !projects.some(p => p.id === row.projectId) ? h('span', { style: { color: '#d14949', fontSize: 12 } }, '项目已不在最新列表中,请重新选择或删除') : null),
320
+ h('div', { style: { ...styles.label, flex: '1 1 170px', minWidth: 130 } }, ordinal === 0 ? '关联工作区' : null, h(ChoicePicker, { items: localWorkspaces?.map(item => ({ ...item, title: item.title === 'default-workspace' ? '默认工作区' : item.title })) || null, selectedId: row.workspaceId || (row.workspace && localWorkspaces?.find(item => item.path === row.workspace)?.id) || '', label: `项目 ${ordinal + 1} 的关联工作区`, placeholder: row.workspace ? '旧路径未匹配,请重新选择' : localWorkspaces ? '请选择工作区' : '正在读取工作区…', missingLabel: '工作区已移除,请重新选择', emptyLabel: '尚无工作区,请先在 DSH 添加工作区', disabled: locked, onPick: id => editRow(row.index, { workspaceId: id, workspace: '' }) })),
321
+ ...[{ 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
+ h(ActionPicker, { action: normalizeAction(row[field] || row.action), label: `项目 ${ordinal + 1} ${title}`, onPick: choice => editRow(row.index, { [field]: choice, receiveMessages: true }) }))),
323
+ 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' })),
325
+ 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
+ }),
327
+ visibleRows.length ? h('small', { style: { color: 'var(--dsw-alias-label-secondary)' } }, '每个项目单独保存:保存后生成一个名为「共序-{项目名}」的自动化任务,关联所选工作区,新建会话并复用;任务会检查有没有被 @ 或待处理的任务,没有就保持沉默。保存过的项目不能再改,只能删除。') : null,
328
+ h('div', null,
329
+ 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
+ h(NotificationPermission),
331
+ status.error || status.sessionError || status.pollError || message ? h('p', { role: 'status' }, status.error || status.sessionError || status.pollError || message) : null,
332
+ pendingLogout && pendingLogout.projects && pendingLogout.projects.length ? h(ConfirmDialog, {
333
+ title: '不能退出登录',
334
+ lines: [
335
+ `当前环境(${environmentChoices.find(item => item.id === env)?.title || '当前环境'})还有 ${pendingLogout.projects.length} 个项目:`,
336
+ ...(pendingLogout.projects || []).map(item => `· ${item.name || item.projectId}`),
337
+ '这些项目还挂着自动化任务和自动化会话。请先删除全部项目,再退出登录。',
338
+ ],
339
+ confirmLabel: '知道了',
340
+ busy: false,
341
+ onConfirm: () => dismissLogout(),
342
+ onCancel: () => setPendingLogout(null),
343
+ }) : null,
344
+ pendingRemoval ? h(ConfirmDialog, {
345
+ title: '删除这个项目?',
346
+ lines: [
347
+ `项目:${projects.find(item => item.id === pendingRemoval.row.projectId)?.name || pendingRemoval.row.projectId}`,
348
+ `自动化任务:${pendingRemoval.plan.hasTask ? `${pendingRemoval.plan.taskTitle}(${pendingRemoval.plan.taskId})` : '没有对应的自动化任务'}`,
349
+ `自动化会话:${pendingRemoval.plan.sessionId ? `${pendingRemoval.plan.sessionId}${pendingRemoval.plan.sessionArchived ? '(已经归档)' : ''}` : '没有自动化会话'}`,
350
+ '确认后会结束上面的自动化任务、归档上面的自动化会话,并移除这个项目的配置。',
351
+ ],
352
+ confirmLabel: '确认删除',
353
+ busy,
354
+ onConfirm: () => void confirmRemoval(),
355
+ onCancel: () => setPendingRemoval(null),
356
+ }) : null);
357
+ }
358
+ /** 共序 logo:与插件图标一致。 */
359
+ function CothreadLogo({ size = 20 }) {
360
+ return h('svg', { width: size, height: size, viewBox: '0 0 64 64', fill: 'none', 'aria-hidden': 'true', style: { flex: 'none' } },
361
+ h('rect', { width: 64, height: 64, rx: 18, fill: '#395D40' }),
362
+ h('path', { d: 'M44 19H29C20.7 19 14 25.7 14 34s6.7 15 15 15h15', stroke: '#F3F6EC', strokeWidth: 6, strokeLinecap: 'round' }),
363
+ h('path', { d: 'M22 15v17c0 7.2 5.8 13 13 13s13-5.8 13-13V22', stroke: '#B7D295', strokeWidth: 6, strokeLinecap: 'round' }),
364
+ h('path', { d: 'M18.5 23.3A15 15 0 0 1 29 19h8', stroke: '#F3F6EC', strokeWidth: 6, strokeLinecap: 'round' }),
365
+ h('circle', { cx: 48, cy: 16, r: 3, fill: '#B7D295' }));
366
+ }
367
+
368
+ /** 菜单图标:面板(打开共序自动化)。 */
369
+ function PanelGlyph() {
370
+ return h('svg', { width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true' },
371
+ h('rect', { x: 2, y: 2.5, width: 12, height: 11, rx: 2 }),
372
+ h('path', { d: 'M2 6.5h12M6 6.5v7' }));
373
+ }
374
+
375
+ /** 菜单图标:退出登录。照 DSH 原生 LogoutIcon 的形状简化。 */
376
+ function LogoutGlyph() {
377
+ return h('svg', { width: 14, height: 14, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true' },
378
+ h('path', { d: 'M6 2.5H4.5A1.5 1.5 0 0 0 3 4v8a1.5 1.5 0 0 0 1.5 1.5H6' }),
379
+ h('path', { d: 'M10 5.5 13.5 8 10 10.5M13 8H6.5' }));
380
+ }
381
+
382
+ /** 取元素的 display 值;取不到就当它不是 flex 容器。 */
383
+ function displayOf(element) {
384
+ try {
385
+ if (typeof getComputedStyle === 'function') return getComputedStyle(element).display
386
+ } catch { /* 忽略 */ }
387
+ return element?.style?.display || ''
388
+ }
389
+
390
+ /**
391
+ * 侧边栏底部的共序登录入口。
392
+ *
393
+ * 未授权:显示共序 logo 与「未授权」,点开是环境选择器,选一个就去浏览器授权。
394
+ * 已授权:显示账号头像与昵称,后面跟着当前环境;点开是原生样式的菜单,
395
+ * 里面是「共序自动化」(切到侧边栏上的那个面板)和「退出登录」。
396
+ */
397
+ function CothreadAccount({ wide, remote, ctx }) {
398
+ const status = useStatus();
399
+ const [account, setAccount] = useState(null);
400
+ const [open, setOpen] = useState(false);
401
+ const [busy, setBusy] = useState(false);
402
+ const [note, setNote] = useState('');
403
+ const rootRef = React.useRef(null);
404
+ const containerRef = React.useRef(null);
405
+ const menuRef = React.useRef(null);
406
+ const [anchor, setAnchor] = useState(null);
407
+
408
+ const environment = status.environment || 'production';
409
+ const environmentTitle = (environmentChoices.find(item => item.id === environment) || {}).title || '当前环境';
410
+ const signedIn = Boolean(status.authenticated);
411
+
412
+ // 账号信息只在登录状态或环境变化时去取,不跟着 3 秒一次的状态轮询跑。
413
+ useEffect(() => {
414
+ let live = true;
415
+ if (!signedIn) { setAccount(null); return () => { live = false } }
416
+ call('account').then(result => { if (live) setAccount(result?.account || null) }).catch(() => { if (live) setAccount(null) });
417
+ return () => { live = false };
418
+ }, [signedIn, environment]);
419
+
420
+ // 独占一行:这一排 footer action 默认不换行,多个注册项会并排成一行。
421
+ // 这里让容器换行,这一项占满整行,停在 DSH 账号行的上方而不是把旁边的项挤没。
422
+ //
423
+ // 插槽锚点是 display:contents,它的父元素并不是那排 flex 容器,
424
+ // 得往上找到真正 display:flex 的那一层——改错元素的话换行不会生效,
425
+ // 这一项的整行宽度就会把同排的其它项压成零宽。
426
+ useEffect(() => {
427
+ const start = containerRef.current
428
+ if (!start) return
429
+ let container = start.parentElement
430
+ while (container) {
431
+ const display = displayOf(container)
432
+ if (display === 'flex') break
433
+ container = container.parentElement
434
+ }
435
+ if (!container) return
436
+ const previous = container.style.flexWrap
437
+ if (previous === 'wrap') return
438
+ container.style.flexWrap = 'wrap'
439
+ return () => { container.style.flexWrap = previous }
440
+ }, []);
441
+
442
+ // 弹层贴着按钮摆:侧边栏会裁掉溢出,所以用固定定位。
443
+ useEffect(() => {
444
+ if (!open) return;
445
+ const place = () => {
446
+ const rect = rootRef.current?.getBoundingClientRect();
447
+ if (rect) setAnchor({ left: rect.left, bottom: window.innerHeight - rect.top + 8 });
448
+ };
449
+ place();
450
+ window.addEventListener('resize', place);
451
+ return () => window.removeEventListener('resize', place);
452
+ }, [open]);
453
+
454
+ useEffect(() => {
455
+ if (!open) return;
456
+ // 菜单是 portal 到 body 的,不在 rootRef 里面,
457
+ // 所以要连菜单一起判断,否则点菜单项会被当成外部点击,菜单当场关掉、点击也就没了。
458
+ const dismiss = event => {
459
+ const target = event.target
460
+ if (rootRef.current?.contains(target)) return
461
+ if (menuRef.current?.contains(target)) return
462
+ setOpen(false)
463
+ };
464
+ document.addEventListener('pointerdown', dismiss, true);
465
+ return () => document.removeEventListener('pointerdown', dismiss, true);
466
+ }, [open]);
467
+
468
+ /** 读一次设置,拿当前版本号,写配置时不跟别人打架。 */
469
+ async function settingsRevision() {
470
+ try {
471
+ const found = await remote?.settings?.describe?.();
472
+ const payload = found?.ok ? found.value : found;
473
+ const rows = Array.isArray(payload) ? payload : payload?.namespaces;
474
+ const row = Array.isArray(rows) ? rows.find(x => x?.ns === ns) : rows?.[ns];
475
+ return row?.revision ?? undefined;
476
+ } catch { return undefined }
477
+ }
478
+
479
+ /** 选一个环境:先切过去,再发起浏览器授权。 */
480
+ async function authorizeIn(target) {
481
+ setBusy(true);
482
+ setNote('');
483
+ try {
484
+ if (target !== environment) {
485
+ const ops = [
486
+ { op: 'set', path: ['environment'], value: target },
487
+ ];
488
+ const result = await remote.settings.mutate(ns, ops, await settingsRevision());
489
+ if (result === false || result?.ok === false) throw Error('切换环境失败');
490
+ }
491
+ const granted = await call('authorize');
492
+ if (!granted?.ok) throw Error(granted?.message || '无法发起授权');
493
+ window.open(granted.url, '_blank', 'noopener,noreferrer');
494
+ setOpen(false);
495
+ } catch (error) { setNote(error.message || '无法发起授权'); }
496
+ finally { setBusy(false) }
497
+ }
498
+
499
+ /** 退出登录:当前环境还有项目时会被拦下来,这里把原因说清楚。 */
500
+ async function logout() {
501
+ setBusy(true);
502
+ setNote('');
503
+ try {
504
+ const result = await call('disconnect');
505
+ if (!result?.ok) { setNote(result?.message || '退出登录失败'); return }
506
+ setAccount(null);
507
+ setOpen(false);
508
+ } catch (error) { setNote(error.message || '退出登录失败'); }
509
+ finally { setBusy(false) }
510
+ }
511
+
512
+ /** 打开侧边栏上的「共序自动化」面板:等同于点侧边栏那一项。 */
513
+ function openAutomation() {
514
+ // 先执行、成功了再关菜单。反过来的话,出错信息写进 note 时菜单已经没了,
515
+ // 用户只看到「点了没反应」,什么提示都看不到。
516
+ try {
517
+ const layout = ctx?.get?.('layout')
518
+ if (!layout?.selectPanel) { setNote('当前环境无法切换到共序自动化面板'); return }
519
+ layout.selectPanel('cothread')
520
+ setOpen(false)
521
+ } catch (error) { setNote(error?.message || '无法切换到共序自动化面板') }
522
+ }
523
+
524
+ // 尺寸照抄原生账号行(dsh-client-ui-settings-account 的 AccountMenu):
525
+ // 行高 44px、头像 24px 圆形、图文间距 8px、正文 14px;收起态收成 36×36 的图标块。
526
+ const trigger = h('button', {
527
+ type: 'button', ref: rootRef, 'aria-label': signedIn ? `共序账号 ${account?.name || environmentTitle}` : '共序未授权,点击授权登录',
528
+ 'aria-haspopup': 'menu', 'aria-expanded': open,
529
+ onClick: () => { setNote(''); setOpen(!open) },
530
+ style: {
531
+ display: 'flex', alignItems: 'center', gap: 8, width: '100%', height: 44, boxSizing: 'border-box',
532
+ // 左右内边距都是 8px,跟原生账号行一致(那边是 2px 的 margin-inline 加 6px 的 padding)。
533
+ // 用 padding 补而不是 margin:margin 会把整行收窄,右侧内容看着就短了。
534
+ padding: wide ? '6px 8px 6px 8px' : 0,
535
+ border: 0, borderRadius: 'var(--dsw-radius-md)',
536
+ // 用 font 简写继承字重:全局正文是 500,只写 fontFamily 的话
537
+ // 按钮会退回浏览器默认的 400,笔画更细,看着像颜色浅了一档。
538
+ // 字号放在 font 之后,别被简写重置。
539
+ background: 'transparent', color: 'var(--dsw-alias-label-primary)', font: 'inherit', fontSize: 14,
540
+ cursor: 'pointer', textAlign: 'left', minWidth: 0,
541
+ ...(wide ? {} : { width: 36, height: 36, justifyContent: 'center', gap: 0 }),
542
+ },
543
+ onMouseEnter: event => { if (wide) event.currentTarget.style.backgroundColor = 'var(--dsw-alias-interactive-bg-hover)' },
544
+ onMouseLeave: event => { event.currentTarget.style.backgroundColor = 'transparent' },
545
+ },
546
+ signedIn && account?.avatar
547
+ ? h('span', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none', width: 24, height: 24, borderRadius: '50%', cornerShape: 'round', background: 'var(--dsw-alias-bg-skeleton)' } },
548
+ // 圆形由图片自己负责:原生 AccountAvatar 就是这么做的
549
+ // (border-radius:50% + object-fit:cover),容器只管尺寸和底色。
550
+ h('img', { src: account.avatar, alt: '', style: { display: 'block', width: '100%', height: '100%', borderRadius: '50%', cornerShape: 'round', objectFit: 'cover' } }))
551
+ : h('span', { style: { display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none', width: 24, height: 24, borderRadius: '50%', cornerShape: 'round', background: 'var(--dsw-alias-bg-skeleton)' } },
552
+ h(CothreadLogo, { size: 16 })),
553
+ // 登录后的这一行:左边头像,中间昵称和「共序·环境」,右边留白。
554
+ // 字号照 MiniMax 用量数据那一行——名称 14px、右侧数值 12px;
555
+ // 这里昵称和环境名都用 12px,两段都不抢眼。
556
+ // 左边是账号昵称,保持账号行本来的 14px;
557
+ // 右边是「共序 · 环境」,用 MiniMax 用量数据那种 12px 的次级字号。
558
+ wide ? h('span', { style: { display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 0, flex: '1 1 auto' } },
559
+ signedIn
560
+ ? h('span', { style: { fontSize: 14, color: 'var(--dsw-alias-label-primary)', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, account?.name || '共序')
561
+ : h('span', { style: { fontSize: 14, color: 'var(--dsw-alias-label-primary)' } }, '未授权'),
562
+ signedIn ? h('span', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', marginLeft: 'auto', flex: 'none', whiteSpace: 'nowrap' } }, `共序 · ${environmentTitle}`) : null) : null);
563
+
564
+ // 菜单卡片与菜单项:照 DSH 原生 Menu 的规格(dsh-client-ui-primitives 的 Menu)。
565
+ // 玻璃态照抄原生 Menu:半透明底 + 40px 模糊。
566
+ // 描边不单独画——原生是由 elevation 阴影自带的 0.5px 描边,
567
+ // 再单独加一条 border 会和它叠成双线,边框看着比原生重得多。
568
+ const cardStyle = {
569
+ boxSizing: 'border-box', padding: 4, display: 'flex', flexDirection: 'column', gap: 0,
570
+ background: 'var(--dsw-specific-menu, var(--dsw-alias-bg-layer-2))',
571
+ backdropFilter: 'var(--dsw-menu-backdrop-filter, blur(40px) saturate(150%))',
572
+ WebkitBackdropFilter: 'var(--dsw-menu-backdrop-filter, blur(40px) saturate(150%))',
573
+ borderRadius: 'var(--dsw-radius-lg, 16px)',
574
+ border: 0,
575
+ boxShadow: 'var(--dsw-elevation-prominent, var(--dsw-elevation-panel))',
576
+ '--dsw-elevation-stroke-color': 'var(--dsw-alias-border-l1)',
577
+ color: 'var(--dsw-alias-label-primary)',
578
+ };
579
+ // 菜单项照原生通用 Menu 的 .item(dsh-client-ui-primitives):
580
+ // 行高 34px、内边距 6px 8px、字号 13px、行高 20px、图文间距 6px、图标 14px。
581
+ //
582
+ // 原生账号菜单登录后走的是通用 .item,只有未登录菜单才用更大的 .signedOutMenu,
583
+ // 这里要跟登录后的观感一致,所以用通用那一套。
584
+ //
585
+ // 注意别用 `font: inherit` 这个简写:它会重置 font-size 和 line-height,
586
+ // 写在后面就把上面设的字号和行高顶回继承值,菜单项会显得又高又大。
587
+ const itemStyle = {
588
+ display: 'flex', alignItems: 'center', gap: 6, width: '100%', minHeight: 34, padding: '6px 8px',
589
+ border: 'none', borderRadius: 'var(--dsw-radius-md)', background: 'transparent', cursor: 'pointer',
590
+ font: 'inherit', fontSize: 13, lineHeight: '20px',
591
+ color: 'var(--dsw-alias-label-primary)', textAlign: 'left',
592
+ };
593
+ const iconStyle = { display: 'inline-flex', flex: 'none', width: 14, height: 14, alignItems: 'center', justifyContent: 'center', color: 'var(--dsw-alias-menu-icon)' };
594
+
595
+ function menuItem(icon, label, onClick, extra) {
596
+ return h('button', {
597
+ type: 'button', role: 'menuitem', disabled: busy, onClick,
598
+ style: itemStyle,
599
+ onMouseEnter: event => { event.currentTarget.style.backgroundColor = 'var(--dsw-alias-interactive-bg-hover)' },
600
+ onMouseLeave: event => { event.currentTarget.style.backgroundColor = 'transparent' },
601
+ }, h('span', { style: iconStyle }, icon), h('span', { style: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, label), extra || null);
602
+ }
603
+
604
+ const panel = anchor
605
+ ? portal(h('div', {
606
+ ref: menuRef, role: 'menu', 'aria-label': '共序账号', 'data-menu-material': '',
607
+ onClick: event => { event.stopPropagation() },
608
+ style: { ...cardStyle, position: 'fixed', zIndex: 1100, left: anchor.left, bottom: anchor.bottom, width: 'max-content', minWidth: 180, maxWidth: 'min(360px, calc(100vw - 24px))' },
609
+ }, signedIn
610
+ ? [
611
+ menuItem(h(ActionIcon, { name: 'settings', size: 14 }), '自动化设置', () => openAutomation()),
612
+ menuItem(h(LogoutGlyph), '退出登录', () => { void logout() }),
613
+ ]
614
+ : [
615
+ ...environmentChoices.map(item => menuItem(h(PanelGlyph), item.title, () => { void authorizeIn(item.id) })),
616
+ ],
617
+ note ? h('p', { role: 'alert', style: { margin: 0, padding: '4px 8px 6px', fontSize: 12, color: '#d14949' } }, note) : null),
618
+ typeof document !== 'undefined' ? document.body : null)
619
+ : null;
620
+
621
+ // 根容器照 Cordis 的 footer action 写法:flex:none + width:100% 让这一项占满整行,
622
+ // 不被同排的其它项挤扁;收起态不占宽度,交给底部的居中排布。
623
+ // 根容器不额外加外边距:MiniMax 那一行是 margin:0,原生账号行的 .root 也没有,
624
+ // 只有我多了一段 8px 上边距,三行的行距就对不齐了。
625
+ return h('div', {
626
+ ref: containerRef,
627
+ style: {
628
+ position: 'relative', minWidth: 0, flex: 'none', order: 1,
629
+ display: 'flex', alignItems: 'center',
630
+ ...(wide ? { width: '100%' } : {}),
631
+ },
632
+ }, trigger, open ? panel : null);
633
+ }
634
+
635
+ function NotificationMonitor() {
636
+ const status = useStatus(), last = React.useRef(null);
637
+ useEffect(() => {
638
+ const notices = status.notices || [];
639
+ if (notices.length === 0) return;
640
+ const newest = notices.reduce((max, notice) => Math.max(max, Number(notice.seq) || 0), 0);
641
+ if (last.current === null) { last.current = newest; return }
642
+ for (const notice of notices) {
643
+ if (notice.seq <= last.current) continue;
644
+ last.current = notice.seq;
645
+ const api = webNotification();
646
+ if (api && api.permission === 'granted') new api('共序有新消息', { body: notice.body || '请打开共序查看项目消息' });
647
+ }
648
+ }, [status.notices]);
649
+ return null;
650
+ }
651
+ /**
652
+ * 只有真正的浏览器通知 API 才可用。
653
+ * Electron 的主进程 Notification 没有 requestPermission / addEventListener,
654
+ * 直接调用会抛错并让整页渲染失败,所以这里先做特性检测。
655
+ */
656
+ function webNotification() {
657
+ if (typeof window === 'undefined') return null;
658
+ const api = window.Notification;
659
+ if (!api || typeof api.requestPermission !== 'function' || typeof api.addEventListener !== 'function') return null;
660
+ return api;
661
+ }
662
+ /** Show the browser notification permission state and let the user grant it. */
663
+ function NotificationPermission() {
664
+ const api = webNotification();
665
+ const [permission, setPermission] = useState(api ? api.permission : 'unsupported');
666
+ useEffect(() => {
667
+ if (!api) return;
668
+ const changed = () => setPermission(api.permission);
669
+ api.addEventListener('permissionchange', changed);
670
+ return () => api.removeEventListener('permissionchange', changed);
671
+ }, [api]);
672
+ if (permission === 'granted') return null;
673
+ 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)) } }, '开启系统通知'));
676
+ }
677
+ /** 渲染出错时显示提示,而不是留下一个空白页面。 */
678
+ class PanelBoundary extends React.Component {
679
+ constructor(props) { super(props); this.state = { error: null } }
680
+ static getDerivedStateFromError(error) { return { error } }
681
+ componentDidCatch(error) { this.props.onError?.(error) }
682
+ render() {
683
+ if (!this.state.error) return this.props.children
684
+ return h('div', { style: styles.page },
685
+ h('p', { role: 'alert' }, `页面渲染失败:${this.state.error.message || this.state.error}`),
686
+ h('button', { type: 'button', style: styles.button, onClick: () => this.setState({ error: null }) }, '重试'))
687
+ }
688
+ }
689
+ /** 包一层错误边界后再渲染页面。 */
690
+ function Safe({ children }) {
691
+ return h(PanelBoundary, null, children)
692
+ }
693
+ /**
694
+ * 侧边栏顶部面板项的图标。
695
+ *
696
+ * 照原生那一套来:「插件」是 IconPluginPinwheelOutlineRegular、「自动化任务」是
697
+ * IconClockOutlineRegular,都是单色描边的功能图标,尺寸用侧边栏给的 size
698
+ * (宽态 16、收起态 18),不写死。用原生图标,描边粗细和内在留白自然一致,
699
+ * 不会像满框的彩色方块那样顶到边上、比旁边的图标靠左约 1px。
700
+ *
701
+ * 也不能包一层 span:包了就成了行内盒子的基线,把图标抬到文字基线之上。
702
+ * 原生 TaskManagerIcon 的注释写的就是这件事。
703
+ *
704
+ * 共序的品牌标识留在侧边栏底部那一行(彩色 logo),这里用工作区树表示
705
+ * 「工作区 / 项目 / 任务」这串层级。
706
+ */
707
+ function PanelIcon({ size = 16 }) {
708
+ const Shared = sharedIcons.IconWorkspaceTreeOutlineMedium
709
+ if (Shared) return h(Shared, { size })
710
+ // primitives 取不到时的兜底:同样是一棵工作区树。
711
+ return h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': 'true', style: { flex: 'none' } },
712
+ h('circle', { cx: 8, cy: 3, r: 1.3 }),
713
+ h('circle', { cx: 4, cy: 8, r: 1.3 }),
714
+ h('circle', { cx: 12, cy: 8, r: 1.3 }),
715
+ h('circle', { cx: 4, cy: 13, r: 1.3 }),
716
+ h('circle', { cx: 12, cy: 13, r: 1.3 }),
717
+ h('path', { d: 'M8 4.3v1.4M8 5.7H4v1M8 5.7h4v1M4 9.3v2.4M12 9.3v2.4' }));
718
+ }
719
+ function apply(ctx) {
720
+ const openSession = id => { const workspace = ctx.get('uiWorkspace'); if (!workspace?.openSession) throw new Error('当前 DSH 无法打开会话'); workspace.openSession(id) };
721
+ const page = props => h(Safe, null, h(Settings, { ...props, remote: ctx.remote, openSession }));
722
+ const main = () => h(Safe, null, h('div', { style: { height: '100%', overflow: 'auto', boxSizing: 'border-box', padding: '32px clamp(24px, 5vw, 72px)' } }, h(Settings, { remote: ctx.remote, openSession })));
723
+ ctx.slots.inject('settings.section', () => ctx.slots.register({ name: 'settings.section', id: 'cothread', order: 28, label: () => '共序自动化', inject: () => ({ remote: ctx.remote }) }, page));
724
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: 'cothread', order: 30, label: () => '共序自动化' }, PanelIcon));
725
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: 'cothread' }, main));
726
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({ name: 'sidebar.footer.action', id: 'cothread-notifications' }, NotificationMonitor));
727
+ // 侧边栏底部的共序登录入口:位置在 DSH 账号上方。
728
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({ name: 'sidebar.footer.action', id: 'cothread-account' }, props => h(CothreadAccount, { ...props, remote: ctx.remote, ctx })));
729
+ }
730
+ return { name: 'dsh-cothread-mcp', inject: ['slots', 'remote', 'remote.settings'], apply };
731
+ }});
732
+