dsh-config-manager 0.5.0 → 0.6.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 (42) hide show
  1. package/lib/client.d.ts +3 -0
  2. package/lib/client.js +709 -602
  3. package/lib/core/messages.d.ts +4 -0
  4. package/lib/core/messages.js +8 -0
  5. package/lib/core/migration-history.d.ts +40 -0
  6. package/lib/core/migration-history.js +55 -0
  7. package/lib/core/plugin-cli.d.ts +5 -0
  8. package/lib/core/plugin-cli.js +11 -3
  9. package/lib/index.d.ts +5 -1
  10. package/lib/index.js +13 -14
  11. package/lib/profiles/dsh-profile-manager.d.ts +1 -1
  12. package/lib/profiles/dsh-profile-manager.js +26 -7
  13. package/lib/profiles/dsh-profile-shared.d.ts +3 -1
  14. package/lib/ui/sync-repository-picker.d.ts +21 -0
  15. package/lib/ui/sync-repository-picker.js +18 -0
  16. package/lib/utils/remove-tree.d.ts +7 -0
  17. package/lib/utils/remove-tree.js +265 -0
  18. package/package.json +1 -1
  19. package/src/client/config-manager.module.css +21 -1
  20. package/src/client/environment/EnvironmentPanel.tsx +2 -2
  21. package/src/client/locales/profiles.ts +2 -0
  22. package/src/client/sync/ChannelConfigDialog.tsx +32 -1
  23. package/src/client/sync/SyncPanel.tsx +11 -30
  24. package/src/client/sync/SyncRepositoryPicker.tsx +34 -13
  25. package/src/client/sync/SyncSettingsView.test.ts +32 -0
  26. package/src/client/sync/config-save-state.test.ts +99 -0
  27. package/src/client/sync/config-save-state.ts +69 -0
  28. package/src/client/sync/sync-locales.ts +4 -0
  29. package/src/core/engine-locale.test.ts +4 -0
  30. package/src/core/messages.ts +8 -0
  31. package/src/core/migration-history.test.ts +65 -0
  32. package/src/core/migration-history.ts +70 -0
  33. package/src/core/plugin-cli.fs.test.ts +30 -3
  34. package/src/core/plugin-cli.ts +11 -3
  35. package/src/index.ts +12 -14
  36. package/src/profiles/dsh-profile-manager.test.ts +20 -0
  37. package/src/profiles/dsh-profile-manager.ts +25 -7
  38. package/src/profiles/dsh-profile-shared.ts +2 -0
  39. package/src/ui/sync-repository-picker.test.ts +34 -1
  40. package/src/ui/sync-repository-picker.ts +24 -0
  41. package/src/utils/remove-tree.test.ts +120 -0
  42. package/src/utils/remove-tree.ts +239 -0
@@ -0,0 +1,265 @@
1
+ /**
2
+ * 严格递归删除 —— 覆盖 `fs.rm(dir, { recursive: true, force: true })` 的**静默失效**。
3
+ *
4
+ * 实测(Node 24 / Windows,本仓 0.5.0):目录里只要有一个**悬空链接**(junction / 符号链接的
5
+ * 重指向目标已被删掉),`fs.rmSync(dir, { recursive: true, force: true })` 既不抛错、也不删任何东西
6
+ * —— 1 ms 内返回,目录原样留在磁盘上。用户点「删除档案」,插件回「已删除档案 X」,磁盘上一点没动。
7
+ *
8
+ * 悬空链接不是畸形数据,而是 DSH 自己会造出来的形态:档案的 `node_modules/<pkg>` 是指向
9
+ * `.dsh-module-fallback/node_modules/<pkg>` 的 junction,fallback 目录随宿主升级/重建消失后,
10
+ * 这些链接就全部悬空(实测某档案 20 个)。所以删除必须走通这种树,且**删完必须复核**。
11
+ *
12
+ * 本模块的语义:
13
+ * - 不用 rm 的目录遍历:自己 readdir + lstat 逐条走;**链接只删链接本身**,绝不跟随进 pnpm store;
14
+ * - 列表里有、lstat 读不到的条目(并发删除 / 悬空链接在个别平台上的形态)→ 直接尝试 unlink;
15
+ * - 只读文件 / 只读目录 / 被杀软或索引占用的条目 → 改权限 + 有界退避重试;
16
+ * - 结束后**复核目标不存在**,还在就抛错 —— 绝不把「什么都没删」当成成功。
17
+ */
18
+ import { chmodSync, existsSync, lstatSync, readdirSync, rmdirSync, unlinkSync } from 'node:fs';
19
+ import { chmod, lstat, readdir, rmdir, unlink } from 'node:fs/promises';
20
+ import { join } from 'node:path';
21
+ /** 单个条目的删除重试次数(Windows 上半途的 AV 扫描 / 索引句柄会让 unlink 短暂 EBUSY)。 */
22
+ const MAX_ATTEMPTS = 4;
23
+ /** 首次退避毫秒(之后每次翻倍)。 */
24
+ const BASE_DELAY_MS = 20;
25
+ /** 值得重试的错误码:只读属性 / 被占用 / 目录已被别人删空一半。 */
26
+ const RETRYABLE = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY', 'EMFILE']);
27
+ function errorCode(error) {
28
+ return error?.code;
29
+ }
30
+ /** 同步退避:用 Atomics.wait 而不是忙等自旋(与 utils/atomic-write.ts 同做法)。 */
31
+ function busyWait(ms) {
32
+ const ia = new Int32Array(new SharedArrayBuffer(4));
33
+ try {
34
+ Atomics.wait(ia, 0, 0, ms);
35
+ }
36
+ catch {
37
+ /* SharedArrayBuffer 不可用:退化为不等待(少见) */
38
+ }
39
+ }
40
+ function sleep(ms) {
41
+ return new Promise((resolve) => { setTimeout(resolve, ms); });
42
+ }
43
+ /** lstat:ENOENT 返回 null(真的没了),其它错误照抛(读不到 ≠ 不存在)。 */
44
+ function lstatSyncOrNull(path) {
45
+ try {
46
+ return lstatSync(path);
47
+ }
48
+ catch (error) {
49
+ if (errorCode(error) === 'ENOENT')
50
+ return null;
51
+ throw error;
52
+ }
53
+ }
54
+ async function lstatOrNull(path) {
55
+ try {
56
+ return await lstat(path);
57
+ }
58
+ catch (error) {
59
+ if (errorCode(error) === 'ENOENT')
60
+ return null;
61
+ throw error;
62
+ }
63
+ }
64
+ /** 删一个**非目录**条目(文件 / 符号链接 / junction);悬空链接只能走这条路。 */
65
+ function unlinkSyncOrRetry(path) {
66
+ let delay = BASE_DELAY_MS;
67
+ for (let attempt = 0;; attempt++) {
68
+ try {
69
+ unlinkSync(path);
70
+ return;
71
+ }
72
+ catch (error) {
73
+ const code = errorCode(error);
74
+ if (code === 'ENOENT')
75
+ return;
76
+ if (attempt >= MAX_ATTEMPTS || code === undefined || !RETRYABLE.has(code))
77
+ throw error;
78
+ // EPERM 在 Windows 上多为「只读属性」:先摘掉只读再重试
79
+ if (code === 'EPERM' || code === 'EACCES') {
80
+ try {
81
+ chmodSync(path, 0o666);
82
+ }
83
+ catch { /* 目标已消失 / 无权限:交给下一轮重试 */ }
84
+ }
85
+ busyWait(delay);
86
+ delay *= 2;
87
+ }
88
+ }
89
+ }
90
+ async function unlinkOrRetry(path) {
91
+ let delay = BASE_DELAY_MS;
92
+ for (let attempt = 0;; attempt++) {
93
+ try {
94
+ await unlink(path);
95
+ return;
96
+ }
97
+ catch (error) {
98
+ const code = errorCode(error);
99
+ if (code === 'ENOENT')
100
+ return;
101
+ if (attempt >= MAX_ATTEMPTS || code === undefined || !RETRYABLE.has(code))
102
+ throw error;
103
+ if (code === 'EPERM' || code === 'EACCES') {
104
+ try {
105
+ await chmod(path, 0o666);
106
+ }
107
+ catch { /* 同上 */ }
108
+ }
109
+ await sleep(delay);
110
+ delay *= 2;
111
+ }
112
+ }
113
+ }
114
+ /** 删空目录(调用前子项已删净);ENOTEMPTY 说明有人在并发写入 → 有界重试。 */
115
+ function rmdirSyncOrRetry(path) {
116
+ let delay = BASE_DELAY_MS;
117
+ for (let attempt = 0;; attempt++) {
118
+ try {
119
+ rmdirSync(path);
120
+ return;
121
+ }
122
+ catch (error) {
123
+ const code = errorCode(error);
124
+ if (code === 'ENOENT')
125
+ return;
126
+ if (attempt >= MAX_ATTEMPTS || code === undefined || !RETRYABLE.has(code))
127
+ throw error;
128
+ if (code === 'EPERM' || code === 'EACCES') {
129
+ try {
130
+ chmodSync(path, 0o777);
131
+ }
132
+ catch { /* 同上 */ }
133
+ }
134
+ busyWait(delay);
135
+ delay *= 2;
136
+ }
137
+ }
138
+ }
139
+ async function rmdirOrRetry(path) {
140
+ let delay = BASE_DELAY_MS;
141
+ for (let attempt = 0;; attempt++) {
142
+ try {
143
+ await rmdir(path);
144
+ return;
145
+ }
146
+ catch (error) {
147
+ const code = errorCode(error);
148
+ if (code === 'ENOENT')
149
+ return;
150
+ if (attempt >= MAX_ATTEMPTS || code === undefined || !RETRYABLE.has(code))
151
+ throw error;
152
+ if (code === 'EPERM' || code === 'EACCES') {
153
+ try {
154
+ await chmod(path, 0o777);
155
+ }
156
+ catch { /* 同上 */ }
157
+ }
158
+ await sleep(delay);
159
+ delay *= 2;
160
+ }
161
+ }
162
+ }
163
+ /** 目录在遍历途中消失 → 返回空(随后 rmdir 得到 ENOENT 并被吞掉)。 */
164
+ function readdirSafe(dir) {
165
+ try {
166
+ return readdirSync(dir, { withFileTypes: true });
167
+ }
168
+ catch (error) {
169
+ if (errorCode(error) === 'ENOENT')
170
+ return [];
171
+ throw error;
172
+ }
173
+ }
174
+ async function readdirSafeAsync(dir) {
175
+ try {
176
+ return await readdir(dir, { withFileTypes: true });
177
+ }
178
+ catch (error) {
179
+ if (errorCode(error) === 'ENOENT')
180
+ return [];
181
+ throw error;
182
+ }
183
+ }
184
+ /** 无异常版本的「还在不在」:任何 stat 错误都当作还在,交给最终复核报错。 */
185
+ function stillExists(path) {
186
+ try {
187
+ lstatSync(path);
188
+ return true;
189
+ }
190
+ catch {
191
+ return existsSync(path);
192
+ }
193
+ }
194
+ /**
195
+ * 删掉一个节点(文件 / 链接 / 目录,目录连自身一起删)。
196
+ * 判据用 lstat:junction 在 Windows 上 isSymbolicLink()=true → 走 unlink,绝不跟进目标。
197
+ */
198
+ function removeNodeSync(target) {
199
+ const stat = lstatSyncOrNull(target);
200
+ if (stat === null)
201
+ return;
202
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
203
+ unlinkSyncOrRetry(target);
204
+ return;
205
+ }
206
+ for (const entry of readdirSafe(target))
207
+ removeChildSync(target, entry);
208
+ rmdirSyncOrRetry(target);
209
+ }
210
+ async function removeNode(target) {
211
+ const stat = await lstatOrNull(target);
212
+ if (stat === null)
213
+ return;
214
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
215
+ await unlinkOrRetry(target);
216
+ return;
217
+ }
218
+ for (const entry of await readdirSafeAsync(target))
219
+ await removeChild(target, entry);
220
+ await rmdirOrRetry(target);
221
+ }
222
+ function removeChildSync(dir, entry) {
223
+ const child = join(dir, entry.name);
224
+ try {
225
+ // dirent 对悬空链接的 isDirectory() 各平台不一致:类型只认 lstat
226
+ lstatSync(child);
227
+ }
228
+ catch (error) {
229
+ if (errorCode(error) === 'ENOENT')
230
+ return;
231
+ // 读不到类型(锁 / 权限):按「非目录」尝试删;删不掉就把真实错误抛出去
232
+ unlinkSyncOrRetry(child);
233
+ return;
234
+ }
235
+ removeNodeSync(child);
236
+ }
237
+ async function removeChild(dir, entry) {
238
+ const child = join(dir, entry.name);
239
+ try {
240
+ await lstat(child);
241
+ }
242
+ catch (error) {
243
+ if (errorCode(error) === 'ENOENT')
244
+ return;
245
+ await unlinkOrRetry(child);
246
+ return;
247
+ }
248
+ await removeNode(child);
249
+ }
250
+ /**
251
+ * 同步严格删除:目标不存在算成功;链接只删链接本身;删不掉抛底层错误;
252
+ * 结束时目标**仍然存在**也抛错(rm 静默失效的兜底判据)。
253
+ */
254
+ export function removeTreeSync(target) {
255
+ removeNodeSync(target);
256
+ if (stillExists(target))
257
+ throw new Error(`removeTreeSync: target still exists after removal: ${target}`);
258
+ }
259
+ /** 异步版本(大批量目录不阻塞事件循环);语义与 removeTreeSync 完全一致。 */
260
+ export async function removeTree(target) {
261
+ await removeNode(target);
262
+ if (stillExists(target))
263
+ throw new Error(`removeTree: target still exists after removal: ${target}`);
264
+ }
265
+ //# sourceMappingURL=remove-tree.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-manager",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "license": "MIT",
5
5
  "description": "Backup, restore, export, import, migrate and sync your DeepSeek Harness (DSH) configuration: settings, plugins, MCP servers, skills, agent presets and workspaces. One-click migration to another machine. DSH 配置一键备份、恢复、导出、导入、迁移与同步插件。",
6
6
  "icon": "./icon.svg",
@@ -1581,6 +1581,25 @@ body {
1581
1581
  align-items: center;
1582
1582
  }
1583
1583
 
1584
+ /* —— 静默自动保存的「已保存」回执(ChannelConfigDialog footer) ——
1585
+ 四通道共用的输入防抖自动保存成功后闪一次:入场 180ms 淡入 + 轻微上浮,2.4s 后由组件隐藏。
1586
+ 本类**只管动画**,盒模型完全由里面的 .badge 提供(不在此重复字号/间距,避免第二套徽章)。 */
1587
+ .savedTick {
1588
+ display: inline-flex;
1589
+ animation: savedTickIn var(--cm-motion-base) var(--cm-motion-ease-out);
1590
+ }
1591
+
1592
+ @keyframes savedTickIn {
1593
+ from {
1594
+ opacity: 0;
1595
+ transform: translateY(2px);
1596
+ }
1597
+ to {
1598
+ opacity: 1;
1599
+ transform: translateY(0);
1600
+ }
1601
+ }
1602
+
1584
1603
  /* —— 中性分类片(Chip,tech-debt #10 / 2026-11) ——
1585
1604
  职责划分:**Badge = 状态语义**(四态只由 src/ui/badge-tone.ts 的 BadgeKind 定义);
1586
1605
  **Chip = 中性分类**(来源 / 形态 / 适配器 / 分区数 —— 没有轻重缓急,也不该有颜色)。
@@ -5802,7 +5821,8 @@ button.profileRowMain:hover {
5802
5821
  .pickerOverlay,
5803
5822
  .pickerUnit,
5804
5823
  .banner,
5805
- .empty {
5824
+ .empty,
5825
+ .savedTick {
5806
5826
  animation: none;
5807
5827
  }
5808
5828
  .statusDot,
@@ -77,14 +77,14 @@ function selectProfilesSlice(): PanelState {
77
77
  }
78
78
 
79
79
  /** host 侧 engine 错误码 → 文案(未知错误回退到通用模板,不显示裸英文码)。 */
80
- const ERROR_CODES = ['notLaunchable', 'launcherUnavailable', 'launchFailed', 'alreadyRunning', 'notRunning', 'stopFailed', 'instanceRunning', 'exists', 'notFound', 'currentProfile', 'invalidName', 'reservedName', 'unknownTemplate', 'managedProfile'] as const
80
+ const ERROR_CODES = ['notLaunchable', 'launcherUnavailable', 'launchFailed', 'alreadyRunning', 'notRunning', 'stopFailed', 'instanceRunning', 'exists', 'notFound', 'currentProfile', 'invalidName', 'reservedName', 'unknownTemplate', 'managedProfile', 'deleteFailed'] as const
81
81
 
82
82
  function profileErrorText(t: TranslateNS<'config-manager'>, error: unknown): string {
83
83
  const message = error instanceof Error ? error.message : String(error)
84
84
  for (const code of ERROR_CODES) {
85
85
  if (message === code || message.includes(code)) {
86
86
  // launchFailed / stopFailed 的 message 形如 `<code>: <细节>`:细节是排障的唯一线索,不能吞掉
87
- if ((code === 'launchFailed' || code === 'stopFailed') && message.includes(': ')) {
87
+ if ((code === 'launchFailed' || code === 'stopFailed' || code === 'deleteFailed') && message.includes(': ')) {
88
88
  const tail = message.slice(message.indexOf(': ') + 2).trim()
89
89
  return tail === '' ? t(`profiles.error.${code}`) : `${t(`profiles.error.${code}`)} — ${redact(tail)}`
90
90
  }
@@ -130,6 +130,7 @@ export const zh = {
130
130
  'profiles.error.notRunning': '该档案没有正在运行的实例(可能已被手动关闭)',
131
131
  'profiles.error.stopFailed': '停止实例失败',
132
132
  'profiles.error.instanceRunning': '该档案的实例正在运行,请先停止再删除',
133
+ 'profiles.error.deleteFailed': '删除失败:档案目录被占用或权限不足,档案仍在磁盘上',
133
134
  'profiles.error.generic': '操作失败:{message}',
134
135
  } as const;
135
136
 
@@ -259,5 +260,6 @@ export const en: Record<keyof typeof zh, string> = {
259
260
  'profiles.error.notRunning': 'This profile has no running instance (it may have been closed manually)',
260
261
  'profiles.error.stopFailed': 'Stopping the instance failed',
261
262
  'profiles.error.instanceRunning': 'An instance of this profile is running — stop it before deleting',
263
+ 'profiles.error.deleteFailed': 'Delete failed: the profile directory is in use or access is denied — the profile is still on disk',
262
264
  'profiles.error.generic': 'Operation failed: {message}',
263
265
  };
@@ -4,6 +4,7 @@
4
4
  * 约定:只接收「渲染所需的数据 + 回调」;React 状态、副作用与网络调用仍由
5
5
  * SyncPanel 持有(单一状态源);可测纯逻辑在 src/ui/sync-settings-view.ts。
6
6
  */
7
+ import { useEffect, useRef, useState } from 'react'
7
8
  import type { ChangeEvent } from 'react'
8
9
  import type { TranslateNS } from '../client-types.ts'
9
10
  import type { UiT } from '../../ui/i18n.ts'
@@ -24,6 +25,12 @@ import { S3_PROVIDERS } from '../../ui/sync-settings-view.ts'
24
25
  import type { CloudFormIssue, SyncFormSnapshot } from '../../ui/sync-settings-view.ts'
25
26
  import css from '../config-manager.module.css'
26
27
 
28
+ /**
29
+ * 静默自动保存的「已保存」徽章在弹窗里停留多久(ms)。
30
+ * 入场 180ms 淡入(--cm-motion-base),2.4s 是「够看清、又不碍着继续输入」的停留长度。
31
+ */
32
+ const SAVED_TICK_MS = 2400
33
+
27
34
  /** 通道配置弹窗的表单字段补丁(onFormChange 入参:git/webdav + 云端点两组)。 */
28
35
  export type ChannelFormPatch = {
29
36
  repoUrl?: string
@@ -51,7 +58,7 @@ export type ChannelFormPatch = {
51
58
  * 拆出的职责单元只接收「渲染所需数据 + 回调」:`onFormChange` 由父组件实现为
52
59
  * 「patch 表单 + 防抖自动保存」—— 防抖定时器与卸载 flush 仍归父组件(单一状态源)。
53
60
  */
54
- export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIssues, busy, savingConfig, remoteReady, statusInfo, githubSignedIn, githubView, onFormChange, onGithubStart, onGithubCancel, onSave }: {
61
+ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIssues, busy, savingConfig, remoteReady, statusInfo, githubSignedIn, saveTick, githubView, onFormChange, onGithubStart, onGithubCancel, onSave }: {
55
62
  open: boolean
56
63
  onClose: () => void
57
64
  api: SyncApi
@@ -70,6 +77,12 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
70
77
  remoteReady: boolean
71
78
  statusInfo: SyncStatusResponse | null
72
79
  githubSignedIn: boolean | null
80
+ /**
81
+ * 静默自动保存的成功计数(父组件每次保存成功 +1)。
82
+ * 为什么用计数而不是布尔:连续改字段会连着保存多次,每次都要重新闪一次徽章;
83
+ * 布尔在「已经显示」的状态下无法区分第二次保存。
84
+ */
85
+ saveTick: number
73
86
  githubView: GithubLoginView
74
87
  onFormChange: (patch: ChannelFormPatch) => void
75
88
  onGithubStart: () => void
@@ -84,6 +97,21 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
84
97
  } = form
85
98
  /** 密钥槽位引用名(与宿主 cloudSecretRef 同构;只用于提示文案,值从不经过前端) */
86
99
  const cloudSecretRef = cloudSecretRefName(channel)
100
+
101
+ /**
102
+ * 静默自动保存的可见回执(四通道共用):每来一个新的 saveTick 就闪一次「已保存」,SAVED_TICK_MS 后隐藏。
103
+ * 用 ref 记住已消费的 tick —— 弹窗关着时到达的 tick 不会在下次打开时误闪,窗口内重复保存只重置计时。
104
+ */
105
+ const [savedVisible, setSavedVisible] = useState(false)
106
+ // 初始值取挂载瞬间的 tick:弹窗关着时到达的保存不会在下次打开时误闪
107
+ const consumedTickRef = useRef(saveTick)
108
+ useEffect(() => {
109
+ if (saveTick <= 0 || saveTick === consumedTickRef.current) return
110
+ consumedTickRef.current = saveTick
111
+ setSavedVisible(true)
112
+ const timer = setTimeout(() => { setSavedVisible(false) }, SAVED_TICK_MS)
113
+ return () => { clearTimeout(timer) }
114
+ }, [saveTick])
87
115
  return (
88
116
  <Modal
89
117
  open={open}
@@ -117,6 +145,7 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
117
145
  api={api}
118
146
  t={t}
119
147
  repoUrl={repoUrl}
148
+ signedIn={githubSignedIn}
120
149
  busy={busy}
121
150
  onPick={(cloneUrl) => { onFormChange({ repoUrl: cloneUrl }) }}
122
151
  />
@@ -450,6 +479,8 @@ export function ChannelConfigDialog({ open, onClose, api, t, uiT, form, cloudIss
450
479
  >
451
480
  {t('config.save')}
452
481
  </Button>
482
+ {/* 自动保存的可见回执:改动即存这件事此前完全静默,用户改完字段没有任何反馈 */}
483
+ {savedVisible && <span className={css.savedTick}><Badge kind="ok">{t('config.savedTick')}</Badge></span>}
453
484
  <InfoHint text={t('config.saveHint')} label={t('common.infoHint')} />
454
485
  </div>
455
486
  </Modal.Body>
@@ -61,6 +61,7 @@ import type {
61
61
  } from './sync-api.ts'
62
62
  import { resolveSmartSync } from './sync-entry.ts'
63
63
  import { reportPreviewFailure } from './preview-failure.ts'
64
+ import { savedConfigState } from './config-save-state.ts'
64
65
  import {
65
66
  channelMapOf, channelStateMap, computeGithubLoginView, computeSyncButtons, defaultChannelSyncState,
66
67
  githubPollMessage, isClientChannel, pushReportView, readStoredChannel,
@@ -320,6 +321,9 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
320
321
  const mountedRef = useRef(true)
321
322
  /** 通道配置弹窗开关(瞬态 UI:切 tab/刷新不持久化,弹窗不自动重开;DESIGN.md §8.12 约定) */
322
323
  const [channelOpen, setChannelOpen] = useState(false)
324
+ /** 静默自动保存的成功计数(不进 SyncUiState 契约):>0 时弹窗内闪一次「已保存」徽章 ——
325
+ * 四通道共用的输入防抖自动保存此前成功后完全静默,用户无从判断存没存上。 */
326
+ const [saveTick, setSaveTick] = useState(0)
323
327
  /** 待确认断开的通道(null = 未打开确认弹窗)——用户要求:配置过的通道必须能删掉 */
324
328
  const [clearTarget, setClearTarget] = useState<SyncChannel | null>(null)
325
329
  /**
@@ -647,38 +651,12 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
647
651
  // 基于 stateRef 计算(同步权威),经 commit 落库:即使保存完成时组件已卸载
648
652
  // (切走 tab),savingConfig 复位与凭据清空仍会镜像进 store,切回后一致
649
653
  const s = stateRef.current
650
- const next: SyncUiState = { ...s, savingConfig: false }
651
- // 只清空「本次已写入的」password/token:若保存期间用户已改输入则保留新值
652
- next.webdavPassword = s.webdavPassword !== '' && s.webdavPassword !== payloadToSave.password
653
- ? s.webdavPassword
654
- : ''
655
- next.token = s.token !== '' && s.token !== payloadToSave.token ? s.token : ''
656
- // 云端点密钥同一口径:只清「本次确实写出去的」那个;保存期间用户又改了输入则保留新值
657
- next.s3Secret = s.s3Secret !== '' && s.s3Secret !== payloadToSave.secret ? s.s3Secret : ''
658
- next.gistToken = s.gistToken !== '' && s.gistToken !== payloadToSave.secret ? s.gistToken : ''
659
- // 凭据徽章合并(响应只含布尔,无 secret 值)
660
- if (s.statusInfo !== null) {
661
- const info: SyncStatusResponse = {
662
- ...s.statusInfo,
663
- configured: true,
664
- credentialConfigured: saved.credentialConfigured,
665
- }
666
- if (saved.webdav !== undefined) {
667
- info.webdav = {
668
- url: s.statusInfo.webdav?.url,
669
- username: s.statusInfo.webdav?.username,
670
- usernameConfigured: saved.webdav.usernameConfigured,
671
- passwordConfigured: saved.webdav.passwordConfigured,
672
- }
673
- }
674
- // 云端点:响应只回非密视图 + secretStored 布尔(值永不回传),直接合并供徽章刷新
675
- if (saved.s3 !== undefined) info.s3 = saved.s3
676
- if (saved.gist !== undefined) info.gist = saved.gist
677
- next.statusInfo = info
678
- }
654
+ // 凭据清空 + 徽章合并的自包含演算下沉到 ./config-save-state.ts(本文件有行数棘轮)
655
+ const next: SyncUiState = { ...s, ...savedConfigState(s, saved, payloadToSave) }
679
656
  commit(next)
680
- // M-17:手动保存成功给出回执(自动保存静默,避免输入防抖刷屏)
657
+ // M-17:手动保存给出 toast 回执;自动保存不弹 toast(防抖会刷屏),改为计数 +1 → 弹窗内的「已保存」徽章
681
658
  if (announce) toast.ok(t('toast.configSaved'))
659
+ else setSaveTick((n) => n + 1)
682
660
  // 手动填入的 git token 保存成功 → 校验有效性(有效则隐藏 GitHub 登录块)。
683
661
  // 只有 git 通道用 SYNC_CREDENTIAL_REF:云端点通道的密钥走各自的槽位,与 GitHub 登录无关。
684
662
  if (payloadToSave.transport === 'git' && saved.credentialConfigured) {
@@ -809,6 +787,8 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
809
787
  if (poll.status === 'success') {
810
788
  // token 已由宿主写入 DSH credentials:标记已登录(隐藏登录块)+ 刷新状态/凭据徽章
811
789
  patch({ githubSignedIn: true, github: { ...stateRef.current.github, phase: 'success', error: null } })
790
+ // 登录成功必须当场可见(用户反馈:成功后界面无任何提示,只能靠猜);文案复用 githubPollMessage 的 success 分支
791
+ toast.ok(message)
812
792
  void loadStatus()
813
793
  } else {
814
794
  patchGithub({ phase: 'error', error: message })
@@ -1411,6 +1391,7 @@ export function SyncPanel({ api, t, cmT }: SyncPanelProps) {
1411
1391
  remoteReady={remoteReady}
1412
1392
  statusInfo={state.statusInfo}
1413
1393
  githubSignedIn={state.githubSignedIn}
1394
+ saveTick={saveTick}
1414
1395
  githubView={githubView}
1415
1396
  onClose={closeChannelDialog}
1416
1397
  onFormChange={(p) => { patch(p); scheduleConfigSave() }}
@@ -15,7 +15,7 @@
15
15
  * - 失败**绝不静默,也绝不把拒绝抛出去**(调用点在 void 上下文里):错误同时进 toast 与内联红字
16
16
  * (toast 会被后续提示挤掉,内联红字留在原地),宿主下发的文本一律先过 `redact()` 再渲染。
17
17
  */
18
- import { useCallback, useEffect, useState } from 'react'
18
+ import { useCallback, useEffect, useRef, useState } from 'react'
19
19
  import type { ChangeEvent } from 'react'
20
20
 
21
21
  import type { TranslateNS } from '../client-types.ts'
@@ -27,7 +27,7 @@ import { toast } from '../common/toast-store.ts'
27
27
  import type { SyncApi } from './sync-api.ts'
28
28
  import {
29
29
  formatRepoUpdatedAt, repoCreateBody, repoNameError, repoPickerOptions, repoPickerRepos,
30
- repoPickerValueFor, REPO_PICKER_CREATE_VALUE, type RepoNameError, type RepoPickerRepo,
30
+ repoPickerValueFor, shouldAutoLoadRepos, REPO_PICKER_CREATE_VALUE, type RepoNameError, type RepoPickerRepo,
31
31
  } from '../../ui/sync-repository-picker.ts'
32
32
  import css from '../config-manager.module.css'
33
33
 
@@ -39,6 +39,11 @@ export interface SyncRepositoryPickerProps {
39
39
  t: TranslateNS<'config-manager-sync'>
40
40
  /** 表单里当前的仓库地址(用于回显「当前选中的是哪一个」) */
41
41
  repoUrl: string
42
+ /**
43
+ * GitHub 登录态(null = 未知)。登录成功那一刻由父组件变 true ⇒ 本组件**自动**拉列表,
44
+ * 用户不必再点开下拉才知道列表出来了(2026-11-08 用户反馈)。
45
+ */
46
+ signedIn: boolean | null
42
47
  /** 表单繁忙(保存中 / 同步中)时禁用选择与新建 */
43
48
  busy: boolean
44
49
  /** 选中仓库(或新建成功)后把地址交回父组件 */
@@ -46,7 +51,7 @@ export interface SyncRepositoryPickerProps {
46
51
  }
47
52
 
48
53
  /** 打开下拉时才拉列表(Select 的 onOpen)—— 弹窗一打开就请求会白跑一次网络。 */
49
- export function SyncRepositoryPicker({ open, api, t, repoUrl, busy, onPick }: SyncRepositoryPickerProps) {
54
+ export function SyncRepositoryPicker({ open, api, t, repoUrl, signedIn, busy, onPick }: SyncRepositoryPickerProps) {
50
55
  const [repos, setRepos] = useState<RepoPickerRepo[]>([])
51
56
  const [loading, setLoading] = useState(false)
52
57
  const [loaded, setLoaded] = useState(false)
@@ -58,20 +63,26 @@ export function SyncRepositoryPicker({ open, api, t, repoUrl, busy, onPick }: Sy
58
63
  const [nameError, setNameError] = useState<RepoNameError>(null)
59
64
  const [createError, setCreateError] = useState<string | null>(null)
60
65
 
61
- /** 拉取仓库列表。**绝不抛出**(调用点在 void 上下文里,抛出的拒绝会变成 unhandled rejection)。 */
62
- const load = useCallback(async (): Promise<void> => {
66
+ /** 拉取仓库列表。**绝不抛出**(调用点在 void 上下文里,抛出的拒绝会变成 unhandled rejection)。
67
+ * announce:手动点「刷新列表」为 true —— 列表就在眼前,但用户需要知道那一次点击真的跑了;
68
+ * 自动加载(打开弹窗 / 登录成功)保持静默,否则一进弹窗就弹一条没人要求的通知。
69
+ * 失败**始终**进 toast(内联红字会随滚动离开视野,密码/token 相关的 401 尤其要当刻可见)。 */
70
+ const load = useCallback(async (announce = false): Promise<void> => {
63
71
  setLoading(true)
64
72
  setLoadError(null)
65
73
  try {
66
74
  const res = await api.githubListRepositories()
67
75
  setRepos(res.repos)
68
76
  setLoaded(true)
77
+ if (announce) toast.ok(t('repoPicker.refreshed', { count: repoPickerRepos(res.repos).length }))
69
78
  } catch (err) {
70
- setLoadError(err instanceof Error ? err.message : String(err))
79
+ const detail = err instanceof Error ? err.message : String(err)
80
+ setLoadError(detail)
81
+ toast.error(t('repoPicker.loadFailed') + t('common.labelSeparator') + redact(detail))
71
82
  } finally {
72
83
  setLoading(false)
73
84
  }
74
- }, [api])
85
+ }, [api, t])
75
86
 
76
87
  // 关闭时收起新建表单(下次打开从「选择」开始,不留上一次的半截输入)
77
88
  useEffect(() => {
@@ -83,13 +94,23 @@ export function SyncRepositoryPicker({ open, api, t, repoUrl, busy, onPick }: Sy
83
94
  setCreateError(null)
84
95
  }, [open])
85
96
 
86
- // 表单里已经有地址(例如上次选过)→ 进弹窗就把列表拉出来,让用户直接看到「当前选中的是哪一个」;
87
- // 空地址则等 onOpen 惰性加载。失败过就不自动重试(避免每开一次弹窗打一次必然失败的请求)。
97
+ // 自动加载的三个触发(弹窗打开 / 登录成功瞬间 / 表单里已有地址)由 ui 层的 shouldAutoLoadRepos 判定:
98
+ // 父组件在轮询到 success 时把 signedIn 变 true,这里就会**自动**把列表拉出来 —— 用户不再需要
99
+ // 自己去点开下拉(2026-11-08 用户反馈:登录成功后界面没有任何提示,看不出到底成了没有)。
100
+ // 失败过不自动重试(避免每开一次弹窗打一次必然失败的请求),重试走「刷新列表」或登录态复位。
88
101
  useEffect(() => {
89
- if (!open || loaded || loading || loadError !== null) return
90
- if (repoUrl.trim() === '') return
102
+ if (!shouldAutoLoadRepos({ open, signedIn, loaded, loading, failed: loadError !== null, repoUrl })) return
91
103
  void load()
92
- }, [open, loaded, loading, loadError, repoUrl, load])
104
+ }, [open, signedIn, loaded, loading, loadError, repoUrl, load])
105
+
106
+ // 登录状态由「未登录/未知」变「已登录」→ 清掉上一次的失败态(多半是未登录时的 401),让上面那条
107
+ // effect 立刻重试一次;否则用户登录完仍旧只看到「加载失败,可重试」。
108
+ const prevSignedInRef = useRef(signedIn)
109
+ useEffect(() => {
110
+ const prev = prevSignedInRef.current
111
+ prevSignedInRef.current = signedIn
112
+ if (prev !== true && signedIn === true && loadError !== null) setLoadError(null)
113
+ }, [signedIn, loadError])
93
114
 
94
115
  const pick = (value: string): void => {
95
116
  if (value === REPO_PICKER_CREATE_VALUE) {
@@ -159,7 +180,7 @@ export function SyncRepositoryPicker({ open, api, t, repoUrl, busy, onPick }: Sy
159
180
  onOpen={() => { if (!loaded && !loading) void load() }}
160
181
  onChange={pick}
161
182
  />
162
- <Button size="sm" loading={loading} disabled={busy} onClick={() => { void load() }}>
183
+ <Button size="sm" loading={loading} disabled={busy} onClick={() => { void load(true) }}>
163
184
  {t('repoPicker.refresh')}
164
185
  </Button>
165
186
  </div>
@@ -170,3 +170,35 @@ test('t42: 未新增硬编码颜色(DESIGN.md:颜色/阴影走 --dsw-* token
170
170
  assert.doesNotMatch(viewSource, /#[0-9a-fA-F]{3,8}\b/, '不得出现硬编码颜色值')
171
171
  assert.doesNotMatch(viewSource, /rgba?\(/, '不得出现硬编码 rgb/rgba 颜色')
172
172
  })
173
+
174
+ /* ------------------------------- 用户感知:登录回执 / 列表自动加载 / 自动保存回执 */
175
+
176
+ test('GitHub 登录成功必须立刻给出 toast(用户报告:成功后界面没有任何提示,只能靠猜)', () => {
177
+ // 成功分支原本只 patch 状态 + loadStatus:登录块在 githubSignedIn===true 时整块隐藏,
178
+ // 「成功」这件事在界面上完全消失,用户看不出到底成了没有。文案必须复用 githubPollMessage
179
+ // 的 success 分支(同一句话不在字典与 toast 里各写一遍)。
180
+ const start = viewSource.indexOf("if (poll.status === 'success')")
181
+ assert.ok(start > 0, 'success 分支必须存在')
182
+ const branch = viewSource.slice(start, start + 400)
183
+ assert.match(branch, /toast\.ok\(message\)/, '登录成功必须弹 toast(复用 githubPollMessage 的成功文案)')
184
+ })
185
+
186
+ test('仓库列表在登录成功那一刻自动加载,不必用户先点开下拉(2026-11-08 用户反馈)', () => {
187
+ // 判定收在 ui 纯逻辑里(可单测),组件只负责调用 —— 组件里不得再出现「地址为空就 return」这类内联规则。
188
+ const picker = readSource(fileURLToPath(new URL('./SyncRepositoryPicker.tsx', import.meta.url)))
189
+ assert.match(picker, /shouldAutoLoadRepos\(\{ open, signedIn, loaded, loading, failed: loadError !== null, repoUrl \}\)/, '自动加载必须经 ui/sync-repository-picker.ts 的 shouldAutoLoadRepos 判定')
190
+ assert.doesNotMatch(picker, /if \(repoUrl\.trim\(\) === ''\) return/, '旧的「地址为空就不加载」内联规则必须撤掉(登录成功也要能拉列表)')
191
+ assert.match(picker, /signedIn: boolean \| null/, '选择器必须接收登录态')
192
+ const dialog = readSource(fileURLToPath(new URL('./ChannelConfigDialog.tsx', import.meta.url)))
193
+ assert.match(dialog, /signedIn=\{githubSignedIn\}/, '弹窗必须把登录态传给仓库选择器(登录成功后翻 true ⇒ 自动加载)')
194
+ })
195
+
196
+ test('静默自动保存必须有可见回执(四通道共用:输入防抖保存此前成功后完全静默)', () => {
197
+ // 主文件:自动保存成功(announce=false)→ 计数 +1;弹窗据此闪一次「已保存」徽章。
198
+ assert.match(viewSource, /else setSaveTick\(\(n\) => n \+ 1\)/, '自动保存成功后必须递增 saveTick(不进 SyncUiState 契约)')
199
+ assert.match(viewSource, /<ChannelConfigDialog[\s\S]*?saveTick=\{saveTick\}/, 'saveTick 必须传给配置弹窗')
200
+ const dialog = readSource(fileURLToPath(new URL('./ChannelConfigDialog.tsx', import.meta.url)))
201
+ assert.match(dialog, /\{savedVisible && <span className=\{css\.savedTick\}>/, '弹窗必须渲染「已保存」回执')
202
+ assert.match(dialog, /t\('config\.savedTick'\)/, '回执文案必须走字典(i18n 禁硬编码)')
203
+ assert.match(dialog, /SAVED_TICK_MS = 2400/, '回执是瞬时提示(2.4s 后隐藏),不得常驻')
204
+ })