@leiyi-works/dsh-feature-tweaks 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -1,35 +1,380 @@
1
1
  /**
2
- * Client half of dsh-feature-tweaks.
2
+ * Client half of @leiyi-works/dsh-feature-tweaks (0.5.0, merged with Menu Folders).
3
3
  *
4
- * Contributes one configurable "Reload page" shortcut (F5 on desktop,
5
- * Ctrl+Shift+R in a browser), moved here from
6
- * @leiyi-works/dsh-sidebar-folders 0.13.4 so functional tweaks live in one
7
- * bundle. The core shortcut service rejects overlapping default combinations,
8
- * so the key exists in exactly one plugin.
4
+ * One bundle now owns both halves:
9
5
  *
10
- * The key reloads through this bundle's Host probe (`reload-safe`): when any
11
- * Client bundle was rebuilt after the app started, a reload would fail the
12
- * Desktop boot audit, so the key explains the restart instead of reloading.
13
- * A failed probe falls back to a plain reload.
6
+ * 一、功能微调(原 dsh-feature-tweaks + dsh-ui-tweaks)
7
+ * 1) 隐藏会话头部右上角的右侧栏展开按钮。选择器只用 ui-sidebar-right 写在
8
+ * ExpandButton 上的稳定属性 `data-sidebar-right-expand`,不会误伤别的按钮。
9
+ * 2) 会话标题栏「⋯」导出菜单(session-log-export)可按开关隐藏。
10
+ * 3) 左侧会话列表默认展开全部会话:核心每个工作区只显示前 5 条,其余折叠成
11
+ * 「展开其余 N 个会话」按钮;这里在列表渲染后自动点开,用户手动「收起」的
12
+ * 分组会被记住。
13
+ * 4) 「刷新页面」快捷键(桌面端 F5 / 网页端 Ctrl+Shift+R),刷新前先问 Host
14
+ * `/__dsh-feature-tweaks/reload-safe`,Client bundle 重建过时只提示不刷新。
15
+ * 5) 桌面端退出忽略定时任务确认(Host 侧实现,见 index.js)。
16
+ * 6) 新会话默认开启团队协作(Host 侧实现,见 index.js)。
17
+ *
18
+ * 二、菜单文件夹(原 dsh-menu-folders 0.16.0)
19
+ * · 左侧菜单:每个用户文件夹一行(`sidebar.panellist`),点一下在左侧下拉展开
20
+ * 收纳的入口;已收纳入口从「更多」菜单移走。
21
+ * · 会话标题栏右上角的文件夹入口与「更多」按钮同一行对齐。
22
+ * · 管理页从「设置 → 菜单文件夹」搬进本插件左侧入口的「菜单文件夹」标签页。
23
+ *
24
+ * 入口(左侧菜单只有一个「功能微调」图标):`sidebar.panellist` 行 + `main` 页面,
25
+ * 页面内分「功能微调 / 菜单文件夹」两个标签页,各自是独立设置页。功能微调的开关
26
+ * 写 Host 的 settings 服务(profile 的 cordis.patch.yml),保存后立即生效。
27
+ *
28
+ * 配置通过 SSE(`/__dsh-feature-tweaks/events`)热更新,SSE 不可用时退回慢轮询
29
+ * (`/__dsh-feature-tweaks/config`)。上游若改了属性名,按钮会保持可见并在控制台
30
+ * 提示用 `extraSelectors` 兜底,不必改插件代码。
14
31
  */
15
32
  window.__ModuleLoader__.load({
16
33
  id: '@leiyi-works/dsh-feature-tweaks',
17
- factory() {
18
- /** Locale namespace owned by this bundle. */
34
+ factory(require) {
35
+ const React = require('react')
36
+ const h = React.createElement
37
+ // Portals keep the header folder row outside the conversation header's
38
+ // clipping context; the inline fallback still renders when react-dom is
39
+ // not shared with this bundle.
40
+ let ReactDOM = null
41
+ try { ReactDOM = require('react-dom') } catch { ReactDOM = null }
42
+
43
+ /** Bundle version reported in diagnostics (kept in step with package.json). */
44
+ const VERSION = '0.5.0'
45
+ /** Locale namespace of the feature half. */
19
46
  const NS = 'featureTweaks'
47
+ /** Locale namespace of the folder half. */
48
+ const NS_MENU = 'menuFolders'
20
49
  /** Host route prefix owned by the Host half. */
21
- const API_PREFIX = '__dsh-feature-tweaks/api/'
50
+ const API_PREFIX = '__dsh-feature-tweaks/'
51
+ /** Id of the single left-menu entry and the main page it opens. */
52
+ const HUB_PANEL_ID = 'feature-tweaks'
53
+ /** Id prefix of one top-menu folder row and of its main-page key. */
54
+ const FOLDER_PANEL_PREFIX = 'menu-folder-'
55
+ /** localStorage mirror of the folder state used until the Host route is reachable. */
56
+ const LOCAL_KEY = 'dsh.menu-folders.state'
57
+ /** localStorage mirror of the last ghost session ids, so a reload can hide their rows before the Host answers. */
58
+ const GHOST_CACHE_KEY = 'dsh.menu-folders.ghosts'
59
+ /** Mirrors left behind by the previous package name; read once for migration. */
60
+ const LEGACY_LOCAL_KEY = 'dsh.sidebar-folders.state'
61
+ const LEGACY_GHOST_CACHE_KEY = 'dsh.sidebar-folders.ghosts'
62
+ /** localStorage key remembering which tab the page was on. */
63
+ const TAB_KEY = 'dsh.feature-tweaks.tab'
64
+ /** Attribute marking one More-menu row this plugin hid. */
65
+ const HIDDEN_ROW_ATTR = 'data-sfb-more-hidden'
66
+ /** Attribute marking the buttons of a hidden row (restored with the row). */
67
+ const HIDDEN_BUTTON_ATTR = 'data-sfb-more-hidden-button'
68
+ /** Stylesheet tag that hides ghost session rows and an empty ungrouped header. */
69
+ const GHOST_CSS_TAG_ID = '@leiyi-works/dsh-feature-tweaks/hidden-ghosts'
70
+ /** Session id shape accepted from the Host. */
71
+ const GHOST_ID_RE = /^session-[0-9a-f][0-9a-f-]{8,}$/u
72
+ /** Style tag id, also the duplicate guard. */
73
+ const CSS_TAG_ID = '@leiyi-works/dsh-feature-tweaks/client.css'
74
+
75
+ /** Stable attribute written by ui-sidebar-right's ExpandButton. */
76
+ const DEFAULT_SELECTORS = ['button[data-sidebar-right-expand]']
77
+ /**
78
+ * 会话标题栏右侧「⋯」导出菜单(session-log-export)的隐藏选择器。
79
+ * CSS Module 类名会随 DSH 构建变化(不同构建里见过 K0RNnq_ / nL4_yW_ 前缀),
80
+ * 所以同时用 aria-label 兜底;aria-label 跟随界面语言变化,中英文都列上。
81
+ */
82
+ const EXPORT_MENU_SELECTORS = [
83
+ '[class*="K0RNnq_moreButton"]',
84
+ '[class*="nL4_yW_moreButton"]',
85
+ 'button[aria-label="更多操作"]',
86
+ 'button[aria-label="More actions"]',
87
+ ]
88
+ const FALLBACK_POLL_MS = 30000
89
+ const DIAGNOSTIC_DELAY_MS = 6000
90
+ /**
91
+ * 左侧会话列表里「展开其余 N 个会话」按钮的选择器:
92
+ * `data-row-key="overflow:<workspaceKey>"` 是 workspace 组件写的稳定锚点,
93
+ * class 里的 `sessionOverflowButton` 作为兜底(上游若改了 data 属性)。
94
+ */
95
+ const SESSION_OVERFLOW_SELECTOR = 'button[data-row-key^="overflow:"], button[class*="sessionOverflowButton"]'
96
+ /** 自动展开的最小重跑间隔(页面渲染很快,节流一下避免和流式输出抢帧)。 */
97
+ const EXPAND_MIN_INTERVAL_MS = 600
98
+ /** 单个 workspace 分组最多连续补点轮数(每轮 +5 条,足够覆盖极端数量)。 */
99
+ const EXPAND_MAX_ROUNDS = 12
100
+
101
+ const CSS = [
102
+ '.sfbRoot{height:100%;overflow:auto;overscroll-behavior:contain;box-sizing:border-box;padding:calc(var(--dsh-frame-top-clearance,0px) + 24px) 24px 40px;color:var(--dsw-alias-label-primary);font-size:14px;line-height:1.5}',
103
+ '.sfbInner{max-width:820px;margin:0 auto;display:flex;flex-direction:column;gap:22px}',
104
+ '.twhInner{max-width:860px;margin:0 auto;display:flex;flex-direction:column;gap:18px}',
105
+ '.sfbHeader{display:flex;flex-direction:column;gap:6px}',
106
+ '.sfbTitle{margin:0;font-size:22px;font-weight:600;letter-spacing:.01em}',
107
+ '.sfbHint{margin:0;color:var(--dsw-alias-label-secondary);font-size:13px}',
108
+ '.sfbSection{display:flex;flex-direction:column;gap:10px}',
109
+ '.sfbSectionHead{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-bottom:6px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22))}',
110
+ '.sfbSectionTitle{font-size:14px;font-weight:600}',
111
+ '.sfbBtn{appearance:none;cursor:pointer;border-radius:7px;padding:4px 10px;font-size:12px;line-height:18px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35));background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-primary)}',
112
+ '.sfbBtn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}',
113
+ '.sfbBtnPrimary{appearance:none;cursor:pointer;border-radius:7px;padding:5px 14px;font-size:13px;line-height:18px;border:1px solid transparent;background:var(--dsw-alias-state-business-primary,#3f7fd4);color:#fff}',
114
+ '.sfbBtnPrimary:hover{filter:brightness(1.06)}',
115
+ '.sfbBtnDanger{color:var(--dsw-alias-state-error-primary,#d14a4a)}',
116
+ '.sfbFolderCard{border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22));border-radius:10px;background:var(--dsw-alias-bg-layer-1,transparent);overflow:hidden}',
117
+ '.sfbFolderHead{display:flex;align-items:center;gap:8px;padding:9px 12px;background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.08));min-width:0}',
118
+ '.sfbFolderName{font-weight:600;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}',
119
+ '.sfbCount{flex:none;font-size:11px;line-height:16px;color:var(--dsw-alias-label-secondary);background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14));border-radius:8px;padding:0 7px}',
120
+ '.sfbSpacer{flex:1;min-width:0}',
121
+ '.sfbActions{display:flex;align-items:center;gap:6px;flex:none}',
122
+ '.sfbFolderBody{display:flex;flex-direction:column;padding:4px 6px 6px}',
123
+ '.sfbEntryRow{display:flex;align-items:center;gap:10px;padding:6px 8px;border-radius:7px;min-width:0}',
124
+ '.sfbEntryRow:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.10))}',
125
+ '.sfbEntryName{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:13px}',
126
+ '.sfbEntryButton{appearance:none;width:100%;border:none;background:transparent;display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:7px;cursor:pointer;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;text-align:left;min-width:0}',
127
+ '.sfbEntryButton:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}',
128
+ '.sfbEntryChevron{flex:none;display:inline-flex;color:var(--dsw-alias-label-secondary)}',
129
+ '.sfbSubTitle{margin:18px 0 6px;font-size:13px;font-weight:600;color:var(--dsw-alias-label-secondary)}',
130
+ '.sfbMuted{padding:8px 10px;color:var(--dsw-alias-label-secondary);font-size:12px}',
131
+ '.sfbErrorRow{padding:10px 12px;border:1px dashed var(--dsw-alias-border-l2,rgba(127,127,127,.4));border-radius:10px;color:var(--dsw-alias-state-error-primary,#d14a4a);font-size:12px;word-break:break-word}',
132
+ '.sfbNewRow{display:flex;align-items:center;gap:8px}',
133
+ '.sfbInput{flex:1;min-width:0;box-sizing:border-box;border-radius:7px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35));background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-primary);padding:6px 10px;font:inherit;font-size:13px;outline:none}',
134
+ '.sfbInput:focus{border-color:var(--dsw-alias-state-business-primary,#3f7fd4)}',
135
+ '.sfbSelect{flex:none;max-width:190px;border-radius:7px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35));background:var(--dsw-alias-bg-layer-1,transparent);color:var(--dsw-alias-label-primary);padding:4px 8px;font:inherit;font-size:12px;outline:none;cursor:pointer}',
136
+ '.sfbMenu{display:flex;flex-direction:column;gap:1px;min-width:220px}',
137
+ '.sfbMenuNote{padding:5px 8px 3px;font-size:11px;color:var(--dsw-alias-label-secondary);white-space:normal}',
138
+ '.sfbMenuRow{appearance:none;width:100%;min-width:0;display:flex;align-items:center;gap:8px;text-align:left;border:none;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:20px;padding:6px 8px;border-radius:6px;cursor:pointer}',
139
+ '.sfbMenuRow:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}',
140
+ '.sfbMenuLabel{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
141
+ '.sfbMenuIndent{padding-left:22px}',
142
+ '.sfbMenuCount{flex:none;font-size:11px;color:var(--dsw-alias-label-secondary)}',
143
+ '.sfbMenuSep{height:1px;background:var(--dsw-alias-border-l1,rgba(127,127,127,.22));margin:4px 6px}',
144
+ '.sfbChevron{flex:none;display:inline-flex;color:var(--dsw-alias-label-secondary);transition:transform .15s ease}',
145
+ '.sfbChevron[data-open=true]{transform:rotate(90deg)}',
146
+ '.sfbIcon{flex:none;display:inline-flex;color:var(--dsw-alias-label-secondary)}',
147
+ '.sfbRowGlyph{position:relative;display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;color:inherit}',
148
+ '.sfbRowIcon{display:inline-flex;align-items:center;justify-content:center}',
149
+ '.sfbDropdown{position:absolute;top:26px;left:-8px;z-index:70;width:208px;box-sizing:border-box;padding:5px;border-radius:10px;background:var(--dsw-alias-bg-overlay);border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.25));box-shadow:0 10px 28px rgba(0,0,0,.18);display:flex;flex-direction:column;gap:1px;cursor:default;text-align:left}',
150
+ '.sfbDropdown .sfbMenuRow{padding-left:26px}',
151
+ '.sfbDropdown .sfbMenuNote{padding-left:26px}',
152
+ '.sfbHeaderAnchor{display:inline-block;width:1px;height:24px;overflow:hidden;opacity:0;pointer-events:none}',
153
+ '.sfbHeaderBar{position:fixed;z-index:200;display:flex;flex-direction:row;align-items:center;justify-content:flex-end;gap:6px;max-width:62vw;overflow:hidden}',
154
+ '.sfbHeaderFolderWrap{display:inline-flex;align-items:center;flex:none}',
155
+ '.sfbHeaderFolder{appearance:none;display:inline-flex;align-items:center;gap:4px;height:24px;padding:0 7px;border-radius:var(--dsw-radius-sm,6px);border:.5px solid var(--dsw-alias-border-l4,rgba(127,127,127,.28));background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:11px;line-height:16px;cursor:pointer;max-width:150px}',
156
+ '.sfbHeaderFolder:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}',
157
+ '.sfbHeaderFolderName{max-width:104px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
158
+ '.sfbHeaderDropdown{position:fixed;z-index:210;min-width:190px;max-width:260px;box-sizing:border-box;padding:5px;border-radius:10px;background:var(--dsw-alias-bg-overlay);border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.25));box-shadow:0 10px 28px rgba(0,0,0,.18);display:flex;flex-direction:column;gap:1px;cursor:default;text-align:left}',
159
+ '.twhTabs{display:flex;flex-wrap:wrap;gap:6px;padding:2px 0 2px;border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22))}',
160
+ '.twhTab{appearance:none;cursor:pointer;border-radius:8px 8px 0 0;padding:7px 16px;font:inherit;font-size:13px;line-height:18px;border:1px solid transparent;border-bottom:none;background:transparent;color:var(--dsw-alias-label-secondary);margin-bottom:-1px}',
161
+ '.twhTab:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.10));color:var(--dsw-alias-label-primary)}',
162
+ '.twhTab[data-active=true]{background:var(--dsw-alias-bg-layer-1,transparent);border-color:var(--dsw-alias-border-l1,rgba(127,127,127,.22));color:var(--dsw-alias-label-primary);font-weight:600}',
163
+ '.twhPane{display:flex;flex-direction:column;gap:20px;padding-top:4px}',
164
+ '.twhFeatureList{display:flex;flex-direction:column;gap:8px}',
165
+ '.twhFeatureRow{display:flex;align-items:flex-start;gap:14px;padding:11px 14px;border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.22));border-radius:10px;background:var(--dsw-alias-bg-layer-1,transparent)}',
166
+ '.twhFeatureText{flex:1;min-width:0;display:flex;flex-direction:column;gap:3px}',
167
+ '.twhFeatureTitle{font-size:13px;font-weight:600;line-height:20px}',
168
+ '.twhFeatureDesc{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}',
169
+ '.twhSwitch{appearance:none;flex:none;cursor:pointer;position:relative;width:38px;height:22px;margin-top:1px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.35));background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.14));transition:background .15s ease,border-color .15s ease;padding:0}',
170
+ '.twhSwitch::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-label-primary,#fff);opacity:.85;transition:transform .15s ease,opacity .15s ease}',
171
+ '.twhSwitch[data-on=true]{background:var(--dsw-alias-state-business-primary,#3f7fd4);border-color:transparent}',
172
+ '.twhSwitch[data-on=true]::after{transform:translateX(16px);background:#fff;opacity:1}',
173
+ '.twhSwitch:hover{filter:brightness(1.05)}',
174
+ '.twhSwitch:disabled{cursor:default;opacity:.55}',
175
+ '.twhSwitch:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#3f7fd4);outline-offset:2px}',
176
+ '.twhFootnote{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}',
177
+ ].join('')
22
178
 
23
- /** Chinese dictionary. */
179
+ try {
180
+ if (typeof document !== 'undefined'
181
+ && document.querySelector('style[data-plugin-css=' + JSON.stringify(CSS_TAG_ID) + ']') === null) {
182
+ const tag = document.createElement('style')
183
+ tag.dataset.plugin = '@leiyi-works/dsh-feature-tweaks'
184
+ tag.dataset.pluginCss = CSS_TAG_ID
185
+ tag.textContent = CSS
186
+ document.head.appendChild(tag)
187
+ }
188
+ } catch {
189
+ // A missing stylesheet must not stop the plugin.
190
+ }
191
+
192
+ /** Simplified Chinese dictionary of the feature half (key-set source of truth). */
24
193
  const zh = {
194
+ 'page.title': '功能微调',
195
+ 'page.hint': 'DSH 跨版本的功能与界面微调。下面的开关保存后立即生效,写入本机 profile 并随云端同步;右侧「菜单文件夹」标签页管理左侧菜单文件夹。',
196
+ 'tab.features': '功能微调',
197
+ 'tab.folders': '菜单文件夹',
198
+ 'group.interface': '界面',
199
+ 'group.behavior': '操作与退出',
200
+ 'group.team': '智能体协作',
201
+ 'feature.hideRightSidebarToggle.title': '隐藏右侧栏展开按钮',
202
+ 'feature.hideRightSidebarToggle.desc': '隐藏会话头部右上角的「重新打开右侧栏」按钮;右栏本身、左栏入口和快捷键都不受影响。',
203
+ 'feature.hideSessionLogExportMenu.title': '隐藏「⋯」导出菜单',
204
+ 'feature.hideSessionLogExportMenu.desc': '隐藏会话标题栏右上角「⋯」菜单里的导出项(默认显示)。',
205
+ 'feature.expandWorkspaceSessions.title': '会话列表默认展开',
206
+ 'feature.expandWorkspaceSessions.desc': '每个工作区默认显示全部会话,不再折叠成「展开其余 N 个会话」;手动点「收起」的分组仍保持收起。',
207
+ 'feature.reloadShortcut.title': '刷新页面快捷键',
208
+ 'feature.reloadShortcut.desc': '桌面端 F5、网页端 Ctrl+Shift+R 刷新页面;刷新前会先检查,插件代码刚更新过时只提示、不刷新。',
209
+ 'feature.quitIgnoresScheduledTasks.title': '退出时不因定时任务确认',
210
+ 'feature.quitIgnoresScheduledTasks.desc': '桌面端退出时,只有已排期的定时任务不再弹确认(任务不会丢,下次打开补触发);确实有任务在运行仍会确认。',
211
+ 'feature.defaultTeamForNewSessions.title': '新会话默认开启团队协作',
212
+ 'feature.defaultTeamForNewSessions.desc': '新建根会话(含普通 fork)默认打开「智能体团队协作」;已有选择/恢复的会话不受影响,单个会话仍可随时关掉。注意团队模式会让上下文与工具更多,token 开销更高。',
213
+ 'footnote.saved': '设置保存在本机 profile 的 cordis.patch.yml,无需重启;换机时随云端同步带走。',
214
+ 'switch.on': '已开启',
215
+ 'switch.off': '已关闭',
216
+ 'save.failed': '保存失败:{message}',
25
217
  'reload.label': '刷新页面',
26
218
  'reload.blocked': '插件代码在本次启动后更新过({names}),现在刷新会弹启动报错。请完全退出 DSH 再打开一次。',
27
219
  }
28
220
  /** English dictionary, complete against the zh key set. */
29
221
  const en = {
222
+ 'page.title': 'Feature tweaks',
223
+ 'page.hint': 'Cross-version behaviour and UI tweaks for DSH. Each switch applies at once, is stored in this machine profile, and travels with cloud sync. The Menu folders tab manages the folders in the left menu.',
224
+ 'tab.features': 'Feature tweaks',
225
+ 'tab.folders': 'Menu folders',
226
+ 'group.interface': 'Interface',
227
+ 'group.behavior': 'Shortcuts and quitting',
228
+ 'group.team': 'Agent teams',
229
+ 'feature.hideRightSidebarToggle.title': 'Hide the right-sidebar expand button',
230
+ 'feature.hideRightSidebarToggle.desc': 'Hides the reopen-right-sidebar button at the top-right of the conversation header. The sidebar itself, its launchers and the shortcut keep working.',
231
+ 'feature.hideSessionLogExportMenu.title': 'Hide the more-actions export menu',
232
+ 'feature.hideSessionLogExportMenu.desc': 'Hides the export entry in the header more-actions menu; shown by default.',
233
+ 'feature.expandWorkspaceSessions.title': 'Expand session lists by default',
234
+ 'feature.expandWorkspaceSessions.desc': 'Shows every session in each workspace instead of collapsing them behind "Show N more sessions". A group you collapse by hand stays collapsed.',
235
+ 'feature.reloadShortcut.title': 'Reload page shortcut',
236
+ 'feature.reloadShortcut.desc': 'F5 on desktop, Ctrl+Shift+R on the web. The reload asks the Host first and only shows a notice instead of reloading when plugin code changed since this app started.',
237
+ 'feature.quitIgnoresScheduledTasks.title': 'Quit without scheduled-task confirmation',
238
+ 'feature.quitIgnoresScheduledTasks.desc': 'On desktop, armed scheduled tasks alone no longer ask for confirmation when quitting (nothing is lost; they run on the next start). Running work still asks.',
239
+ 'feature.defaultTeamForNewSessions.title': 'Start new sessions with Agent Teams',
240
+ 'feature.defaultTeamForNewSessions.desc': 'New root sessions (including ordinary forks) start with Agent Teams enabled. Later choices and resumed sessions are untouched, and one session can always switch it off. Team mode adds tools and guidance, so token cost is higher.',
241
+ 'footnote.saved': 'Settings are stored in this machine profile cordis.patch.yml; no restart is needed, and they travel with cloud sync.',
242
+ 'switch.on': 'On',
243
+ 'switch.off': 'Off',
244
+ 'save.failed': 'Could not save: {message}',
30
245
  'reload.label': 'Reload page',
31
246
  'reload.blocked': 'Plugin code changed after this app started ({names}); reloading now would fail with a startup error. Quit DSH completely and open it again.',
32
247
  }
248
+ /** Simplified Chinese dictionary of the folder half. */
249
+ const zhMenu = {
250
+ 'page.title': '菜单文件夹',
251
+ 'page.hint': '把左侧顶部菜单里的入口收进文件夹。文件夹会显示在左侧菜单「更多」的上方,点一下即可在左侧下拉查看收纳的入口;已收纳的入口在打开一次「更多」后会从顶部菜单移走。',
252
+ 'folders.section': '文件夹',
253
+ 'folders.new': '新建文件夹',
254
+ 'folders.placeholder': '文件夹名称',
255
+ 'folders.empty': '还没有文件夹。先新建一个,再把上面的菜单项收纳进去。',
256
+ 'folders.rename': '重命名',
257
+ 'folders.up': '上移',
258
+ 'folders.down': '下移',
259
+ 'folders.delete': '删除',
260
+ 'folders.noMembers': '这个文件夹还没有收纳任何入口。',
261
+ 'entries.section': '未收纳的菜单项',
262
+ 'entries.empty': '所有菜单项都已收纳进文件夹。',
263
+ 'entries.moveTo': '收纳到…',
264
+ 'entries.remove': '移出',
265
+ 'entries.up': '上移',
266
+ 'entries.down': '下移',
267
+ 'folderPage.empty': '这个文件夹还没有收纳任何入口,去「功能微调」入口的「菜单文件夹」标签页里收纳。',
268
+ 'folderPage.manage': '在左侧菜单「功能微调」入口的「菜单文件夹」标签页里管理文件夹和收纳项。',
269
+ 'more.note': '已收纳的入口不会列在本菜单里,请从左侧文件夹打开;在「功能微调 → 菜单文件夹」里管理。',
270
+ 'save.failed': '文件夹配置同步失败,修改暂存在本页。',
271
+ }
272
+ /** English dictionary, complete against the zhMenu key set. */
273
+ const enMenu = {
274
+ 'page.title': 'Menu folders',
275
+ 'page.hint': 'Collect entries of the left global menu into folders. Each folder appears in the left menu above More; click it to expand its collected entries inline. Collected entries leave the top menu once More has been opened.',
276
+ 'folders.section': 'Folders',
277
+ 'folders.new': 'New folder',
278
+ 'folders.placeholder': 'Folder name',
279
+ 'folders.empty': 'No folders yet. Create one, then collect menu entries from above.',
280
+ 'folders.rename': 'Rename',
281
+ 'folders.up': 'Up',
282
+ 'folders.down': 'Down',
283
+ 'folders.delete': 'Delete',
284
+ 'folders.noMembers': 'This folder holds no entries yet.',
285
+ 'entries.section': 'Uncollected entries',
286
+ 'entries.empty': 'Every menu entry is already collected.',
287
+ 'entries.moveTo': 'Collect into…',
288
+ 'entries.remove': 'Remove',
289
+ 'entries.up': 'Move up',
290
+ 'entries.down': 'Move down',
291
+ 'folderPage.empty': 'This folder holds no entries yet. Collect some in the Menu folders tab of the Feature tweaks entry.',
292
+ 'folderPage.manage': 'Manage folders and collected entries in the Menu folders tab of the Feature tweaks entry on the left menu.',
293
+ 'more.note': 'Collected entries are not listed in this menu; open them from their folder. Manage them in Feature tweaks → Menu folders.',
294
+ 'save.failed': 'Folder settings did not sync; changes stay on this page for now.',
295
+ }
296
+
297
+ /** Fallback translator used until the locale service hands over its bound one. */
298
+ function fallbackTranslator(dictionary, ns) {
299
+ return (key, vars) => {
300
+ const template = dictionary[key]
301
+ const text = template !== undefined ? template : key
302
+ if (vars === undefined) return text
303
+ return text.replace(/\{(\w+)\}/g, (match, name) => (vars[name] === undefined ? match : String(vars[name])))
304
+ }
305
+ }
306
+ /** Live feature translator (rebound to the locale service when it is ready). */
307
+ let t = fallbackTranslator(zh)
308
+ /** Live folder translator. */
309
+ let tMenu = fallbackTranslator(zhMenu)
310
+
311
+ // ------------------------------------------------------------------
312
+ // Shared helpers
313
+ // ------------------------------------------------------------------
314
+
315
+ /** Join truthy class names. */
316
+ function cx(...names) {
317
+ return names.filter(Boolean).join(' ')
318
+ }
319
+
320
+ /** Render one stroke icon. */
321
+ function icon(size, children, extra) {
322
+ return h('svg', Object.assign({
323
+ width: size,
324
+ height: size,
325
+ viewBox: '0 0 24 24',
326
+ fill: 'none',
327
+ stroke: 'currentColor',
328
+ strokeWidth: 1.7,
329
+ strokeLinecap: 'round',
330
+ strokeLinejoin: 'round',
331
+ 'aria-hidden': true,
332
+ focusable: 'false',
333
+ }, extra || {}), children)
334
+ }
335
+
336
+ const iconFolder = (size) => icon(size, [
337
+ h('path', { key: 'f', d: 'M3 8.6A2.6 2.6 0 0 1 5.6 6h3.1l1.9 2.1h7.8A2.6 2.6 0 0 1 21 10.7v5.7A2.6 2.6 0 0 1 18.4 19H5.6A2.6 2.6 0 0 1 3 16.4z' }),
338
+ ])
339
+ const iconChevron = (size) => icon(size, [h('path', { key: 'c', d: 'M9 6l6 6-6 6' })])
340
+
341
+ /** Left-menu glyph of this plugin: two sliders. */
342
+ function HubEntryIcon(props) {
343
+ const size = props !== null && props !== undefined && typeof props.size === 'number' && props.size > 0 ? props.size : 18
344
+ return h('svg', {
345
+ width: size,
346
+ height: size,
347
+ viewBox: '0 0 24 24',
348
+ fill: 'none',
349
+ 'aria-hidden': true,
350
+ style: { display: 'block' },
351
+ },
352
+ h('path', { key: 'a', d: 'M3 7h18', stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round' }),
353
+ h('circle', { key: 'b', cx: 15, cy: 7, r: 3.2, fill: 'currentColor' }),
354
+ h('path', { key: 'c', d: 'M3 17h18', stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round' }),
355
+ h('circle', { key: 'd', cx: 9, cy: 17, r: 3.2, fill: 'currentColor' }),
356
+ )
357
+ }
358
+
359
+ /** A tiny snapshot store usable with React.useSyncExternalStore. */
360
+ function createSnapshotStore(initial) {
361
+ let value = initial
362
+ const listeners = new Set()
363
+ return {
364
+ getSnapshot: () => value,
365
+ subscribe(fn) {
366
+ listeners.add(fn)
367
+ return () => { listeners.delete(fn) }
368
+ },
369
+ set(next) {
370
+ if (next === value) return
371
+ value = next
372
+ for (const fn of [...listeners]) {
373
+ try { fn() } catch { /* one subscriber must not break its peers */ }
374
+ }
375
+ },
376
+ }
377
+ }
33
378
 
34
379
  /** Page base that keeps requests on the page's own origin. */
35
380
  function pageBase() {
@@ -66,6 +411,262 @@ window.__ModuleLoader__.load({
66
411
  return String(error)
67
412
  }
68
413
 
414
+ /**
415
+ * Read a localStorage mirror, copying the value left under the previous
416
+ * package name to the current key so folders survive the rename.
417
+ * @param currentKey - key this bundle writes.
418
+ * @param legacyKey - key owned by the previous package name.
419
+ * @returns the stored text, or null when both keys are absent.
420
+ */
421
+ function readLocalMirror(currentKey, legacyKey) {
422
+ try {
423
+ const current = localStorage.getItem(currentKey)
424
+ if (current !== null) return current
425
+ const legacy = localStorage.getItem(legacyKey)
426
+ if (legacy !== null) localStorage.setItem(currentKey, legacy)
427
+ return legacy
428
+ } catch {
429
+ return null
430
+ }
431
+ }
432
+
433
+ /** Normalize an untrusted folder state document read back from the Host. */
434
+ function normalizeState(raw) {
435
+ const folders = []
436
+ const list = raw !== null && typeof raw === 'object' && Array.isArray(raw.folders) ? raw.folders : []
437
+ for (const item of list) {
438
+ if (item === null || typeof item !== 'object') continue
439
+ const id = typeof item.id === 'string' ? item.id.slice(0, 96) : ''
440
+ const name = typeof item.name === 'string' ? item.name.trim().slice(0, 40) : ''
441
+ if (id === '' || name === '') continue
442
+ if (folders.some((known) => known.id === id)) continue
443
+ const panelIds = []
444
+ if (Array.isArray(item.panelIds)) {
445
+ for (const value of item.panelIds) {
446
+ if (typeof value !== 'string' || value === '') continue
447
+ if (panelIds.includes(value)) continue
448
+ panelIds.push(value)
449
+ }
450
+ }
451
+ folders.push({ id, name, panelIds })
452
+ if (folders.length >= 64) break
453
+ }
454
+ return folders
455
+ }
456
+
457
+ // ------------------------------------------------------------------
458
+ // Feature half: DOM tweaks, config store, SSE, reload shortcut
459
+ // ------------------------------------------------------------------
460
+
461
+ /** Live config snapshot used by the DOM tweaks and by the settings page. */
462
+ const featureStore = createSnapshotStore({
463
+ hideRightSidebarToggle: true,
464
+ hideSessionLogExportMenu: false,
465
+ expandWorkspaceSessions: true,
466
+ reloadShortcut: true,
467
+ quitIgnoresScheduledTasks: true,
468
+ defaultTeamForNewSessions: true,
469
+ extraSelectors: [],
470
+ pollIntervalMs: FALLBACK_POLL_MS,
471
+ debug: false,
472
+ selectors: DEFAULT_SELECTORS.slice(),
473
+ })
474
+
475
+ /** Selectors of the hide rule (defaults + extraSelectors). */
476
+ let selectors = DEFAULT_SELECTORS.slice()
477
+ /** Whether the hide rule is active. */
478
+ let hidden = true
479
+ /** Export-menu hiding flag; shown unless explicitly enabled. */
480
+ let hideExportMenu = false
481
+ let debug = false
482
+ let diagnosticTimer = null
483
+ let diagnosed = false
484
+ let expandSessions = true
485
+ /** Reload shortcut flag (live). */
486
+ let reloadShortcutEnabled = true
487
+ /** 会话列表自动展开实例(配置热更新时可立即触发一次)。 */
488
+ let sessionExpander = null
489
+ /** Registered shortcuts service (for dynamic registration of the reload command). */
490
+ let shortcutsService = null
491
+ /** Disposer of the registered reload shortcut. */
492
+ let shortcutDispose = null
493
+ /** Whether apply is still mounted. */
494
+ let stopped = false
495
+ let reloading = false
496
+ /** Fallback polling handle. */
497
+ let pollHandle = null
498
+ let pollMs = 0
499
+
500
+ function log(...args) {
501
+ if (debug) console.info('[dsh-feature-tweaks]', ...args)
502
+ }
503
+
504
+ /** Build the CSS text for the current selector list. */
505
+ function buildCss() {
506
+ const list = hideExportMenu ? selectors.concat(EXPORT_MENU_SELECTORS) : selectors
507
+ return list.map((selector) => `${selector}{display:none !important}`).join('\n')
508
+ }
509
+
510
+ /** Insert or remove the hide rule. */
511
+ function ensureStyle() {
512
+ const existing = document.getElementById(CSS_TAG_ID + '-hide')
513
+ if (!hidden) {
514
+ if (existing !== null) existing.remove()
515
+ return
516
+ }
517
+ if (existing !== null) {
518
+ const css = buildCss()
519
+ if (existing.textContent !== css) existing.textContent = css
520
+ return
521
+ }
522
+ if (document.head === null) return
523
+ const style = document.createElement('style')
524
+ style.id = CSS_TAG_ID + '-hide'
525
+ style.setAttribute('data-dsh-feature-tweaks', 'hide-right-sidebar-toggle')
526
+ style.textContent = buildCss()
527
+ document.head.appendChild(style)
528
+ }
529
+
530
+ /** Warn once when the hide rule is active but nothing matches (upstream changed). */
531
+ function scheduleDiagnostic() {
532
+ if (diagnosticTimer !== null) clearTimeout(diagnosticTimer)
533
+ diagnosticTimer = null
534
+ if (!hidden || diagnosed) return
535
+ diagnosticTimer = setTimeout(() => {
536
+ diagnosticTimer = null
537
+ if (!hidden || diagnosed) return
538
+ let matched = false
539
+ for (const selector of selectors) {
540
+ try {
541
+ if (document.querySelector(selector) !== null) {
542
+ matched = true
543
+ break
544
+ }
545
+ } catch {
546
+ log('invalid selector', selector)
547
+ }
548
+ }
549
+ if (!matched) {
550
+ diagnosed = true
551
+ console.warn(
552
+ '[dsh-feature-tweaks] 隐藏已启用,但没有找到目标按钮。上游可能改了 data 属性名;' +
553
+ '可在插件 Config 的 extraSelectors 里追加新的选择器(无需改插件代码)。',
554
+ )
555
+ }
556
+ }, DIAGNOSTIC_DELAY_MS)
557
+ }
558
+
559
+ /**
560
+ * 会话列表「展开其余 N 个会话」兜底。
561
+ *
562
+ * DSH 核心每个 workspace 只渲染前 5 条会话(SESSION_WATERMARK_BASE),其余折叠在一个
563
+ * overflow 按钮后面。这里在列表渲染后自动点开该按钮,让列表默认显示全部会话;
564
+ * 用户手动点「收起」的分组会被记住,本次页面会话内不再自动展开。
565
+ *
566
+ * @returns 展开器(expandNow / dispose);环境不支持时返回 null。
567
+ */
568
+ function installSessionListExpander() {
569
+ if (typeof window === 'undefined' || typeof document === 'undefined') return null
570
+ if (typeof MutationObserver !== 'function') return null
571
+ const userCollapsed = new Set()
572
+ let disposed = false
573
+ let timer = null
574
+ let lastRun = 0
575
+ let rounds = 0
576
+ let observer = null
577
+
578
+ const overflowButtons = () => {
579
+ try {
580
+ return Array.from(document.querySelectorAll(SESSION_OVERFLOW_SELECTOR))
581
+ } catch {
582
+ return []
583
+ }
584
+ }
585
+ const groupKeyOf = (button) => {
586
+ const rowKey = button.getAttribute('data-row-key')
587
+ if (typeof rowKey === 'string' && rowKey.startsWith('overflow:')) return rowKey.slice(9)
588
+ return null
589
+ }
590
+ const isCollapsed = (button) => button.getAttribute('aria-expanded') === 'false'
591
+
592
+ const schedule = (delay) => {
593
+ if (disposed || timer !== null) return
594
+ timer = window.setTimeout(() => {
595
+ timer = null
596
+ run()
597
+ }, Math.max(0, delay))
598
+ }
599
+
600
+ const run = () => {
601
+ if (disposed || !expandSessions) return
602
+ const now = Date.now()
603
+ if (now - lastRun < EXPAND_MIN_INTERVAL_MS) {
604
+ schedule(EXPAND_MIN_INTERVAL_MS - (now - lastRun))
605
+ return
606
+ }
607
+ lastRun = now
608
+ if (rounds >= EXPAND_MAX_ROUNDS) return
609
+ let clicked = 0
610
+ for (const button of overflowButtons()) {
611
+ if (!isCollapsed(button)) continue
612
+ const key = groupKeyOf(button)
613
+ if (key !== null && userCollapsed.has(key)) continue
614
+ try {
615
+ button.click()
616
+ clicked += 1
617
+ } catch {
618
+ /* 忽略单次点击失败,下一轮再试 */
619
+ }
620
+ }
621
+ if (clicked > 0) {
622
+ rounds += 1
623
+ log('session list expanded', clicked)
624
+ schedule(160)
625
+ } else {
626
+ rounds = 0
627
+ }
628
+ }
629
+
630
+ // 尊重用户手动「收起」:按 workspace 分组记住,本次页面会话内不再自动展开该分组。
631
+ const onClick = (event) => {
632
+ if (event.isTrusted !== true) return
633
+ const target = event.target
634
+ if (!(target instanceof Element)) return
635
+ const button = target.closest(SESSION_OVERFLOW_SELECTOR)
636
+ if (button === null) return
637
+ const key = groupKeyOf(button)
638
+ if (key === null) return
639
+ if (button.getAttribute('aria-expanded') === 'true') userCollapsed.add(key)
640
+ else userCollapsed.delete(key)
641
+ }
642
+ document.addEventListener('click', onClick, true)
643
+
644
+ observer = new MutationObserver(() => {
645
+ schedule(EXPAND_MIN_INTERVAL_MS)
646
+ })
647
+ observer.observe(document.body, {
648
+ childList: true,
649
+ subtree: true,
650
+ attributes: true,
651
+ attributeFilter: ['aria-expanded'],
652
+ })
653
+ // 首屏布局可能晚于插件加载,先排一轮,后面的 MutationObserver 会继续兜底。
654
+ schedule(200)
655
+
656
+ return {
657
+ expandNow() {
658
+ rounds = 0
659
+ schedule(60)
660
+ },
661
+ dispose() {
662
+ disposed = true
663
+ document.removeEventListener('click', onClick, true)
664
+ if (observer !== null) observer.disconnect()
665
+ if (timer !== null) window.clearTimeout(timer)
666
+ },
667
+ }
668
+ }
669
+
69
670
  /** Transient toast for a reload that was refused on purpose. */
70
671
  function showNotice(text) {
71
672
  try {
@@ -99,82 +700,808 @@ window.__ModuleLoader__.load({
99
700
  .filter((id) => bootRevs.get(id) !== revs[id])
100
701
  }
101
702
 
102
- return {
103
- name: '@leiyi-works/dsh-feature-tweaks',
104
- inject: ['locale'],
105
- apply(ctx) {
106
- ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'feature-tweaks: dictionaries')
107
- const t = ctx.locale.bind(NS)
108
-
109
- let reloading = false
110
- /** Probe the Host, then reload only when no Client bundle is stale. */
111
- const scheduleReload = async () => {
112
- if (reloading) return
113
- reloading = true
114
- reportDiag('reload-shortcut-fired')
115
- let changed = null
703
+ /** Probe the Host, then reload only when no Client bundle is stale. */
704
+ async function scheduleReload() {
705
+ if (reloading) return
706
+ reloading = true
707
+ reportDiag('reload-shortcut-fired')
708
+ let changed = null
709
+ try {
710
+ const response = await fetch(apiUrl('reload-safe'), { cache: 'no-store' })
711
+ if (response.ok) {
712
+ const data = await response.json()
713
+ if (data !== null && typeof data === 'object'
714
+ && data.revs !== null && typeof data.revs === 'object') {
715
+ changed = changedSinceBoot(data.revs)
716
+ } else if (Array.isArray(data?.changed)) {
717
+ changed = data.changed
718
+ }
719
+ }
720
+ } catch {
721
+ // An unreachable probe falls back to a plain reload.
722
+ }
723
+ if (changed !== null && changed.length > 0) {
724
+ const names = changed.slice(0, 3).join('、') + (changed.length > 3 ? ' 等' : '')
725
+ showNotice(t('reload.blocked', { names }))
726
+ reportDiag('reload-shortcut-blocked changed=' + changed.join(','))
727
+ reloading = false
728
+ return
729
+ }
730
+ window.setTimeout(() => {
731
+ try { globalThis.location.reload() } catch { /* the page is going away anyway */ }
732
+ }, 120)
733
+ }
734
+
735
+ /** Register or unregister the reload shortcut to follow the live switch. */
736
+ function syncReloadShortcut() {
737
+ const want = reloadShortcutEnabled && stopped !== true
738
+ if (want && shortcutsService !== null && shortcutDispose === null) {
739
+ try {
740
+ shortcutDispose = shortcutsService.register({
741
+ id: 'feature-tweaks.reload',
742
+ label: () => t('reload.label'),
743
+ aliases: ['reload', 'refresh', '刷新'],
744
+ defaults: {
745
+ 'desktop:windows': { code: 'F5', modifiers: [] },
746
+ 'desktop:macos': { code: 'F5', modifiers: [] },
747
+ 'web:windows': { code: 'KeyR', modifiers: ['primary', 'shift'] },
748
+ 'web:macos': { code: 'KeyR', modifiers: ['primary', 'shift'] },
749
+ },
750
+ regions: ['page', 'editable', 'terminal'],
751
+ modals: [],
752
+ resolve: () => ({
753
+ status: 'handled',
754
+ run: () => { void scheduleReload() },
755
+ }),
756
+ })
757
+ reportDiag('reload-shortcut-ready')
758
+ } catch (error) {
759
+ reportDiag('reload-shortcut-failed: ' + errorText(error))
760
+ shortcutDispose = null
761
+ }
762
+ return
763
+ }
764
+ if (!want && shortcutDispose !== null) {
765
+ try { shortcutDispose() } catch { /* already gone */ }
766
+ shortcutDispose = null
767
+ reportDiag('reload-shortcut-removed')
768
+ }
769
+ }
770
+
771
+ /** Apply one config payload from the host. */
772
+ function applyConfig(data) {
773
+ if (data === null || typeof data !== 'object') return
774
+ hidden = data.hideRightSidebarToggle !== false
775
+ hideExportMenu = data.hideSessionLogExportMenu === true
776
+ expandSessions = data.expandWorkspaceSessions !== false
777
+ reloadShortcutEnabled = data.reloadShortcut !== false
778
+ debug = data.debug === true
779
+ const extra = Array.isArray(data.extraSelectors)
780
+ ? data.extraSelectors.filter((item) => typeof item === 'string' && item.trim() !== '')
781
+ : []
782
+ selectors = DEFAULT_SELECTORS.concat(extra)
783
+ const pollNext = typeof data.pollIntervalMs === 'number' && Number.isFinite(data.pollIntervalMs)
784
+ ? Math.max(2000, data.pollIntervalMs)
785
+ : FALLBACK_POLL_MS
786
+ featureStore.set({
787
+ hideRightSidebarToggle: hidden,
788
+ hideSessionLogExportMenu: hideExportMenu,
789
+ expandWorkspaceSessions: expandSessions,
790
+ reloadShortcut: reloadShortcutEnabled,
791
+ quitIgnoresScheduledTasks: data.quitIgnoresScheduledTasks !== false,
792
+ defaultTeamForNewSessions: data.defaultTeamForNewSessions !== false,
793
+ extraSelectors: extra,
794
+ pollIntervalMs: pollNext,
795
+ debug,
796
+ selectors: selectors.slice(),
797
+ })
798
+ log('config applied', { hidden, hideExportMenu, selectors, expandSessions, reloadShortcutEnabled })
799
+ ensureStyle()
800
+ scheduleDiagnostic()
801
+ if (expandSessions && sessionExpander !== null) sessionExpander.expandNow()
802
+ syncReloadShortcut()
803
+ startPolling(pollNext)
804
+ }
805
+
806
+ /** Read the config once over plain HTTP (fallback / startup). */
807
+ async function syncOnce() {
808
+ try {
809
+ const response = await fetch(apiUrl('config'), { headers: { accept: 'application/json' } })
810
+ if (!response.ok) return
811
+ const data = await response.json()
812
+ if (data !== null && typeof data === 'object') applyConfig(data)
813
+ } catch {
814
+ /* host not ready yet: keep the default */
815
+ }
816
+ }
817
+
818
+ /** (Re)start the fallback poll with the configured interval. */
819
+ function startPolling(nextMs) {
820
+ const ms = typeof nextMs === 'number' && nextMs > 0 ? nextMs : FALLBACK_POLL_MS
821
+ if (pollHandle !== null && ms === pollMs) return
822
+ if (pollHandle !== null) clearInterval(pollHandle)
823
+ pollMs = ms
824
+ pollHandle = setInterval(() => {
825
+ if (!stopped) void syncOnce()
826
+ }, ms)
827
+ }
828
+
829
+ /** Subscribe to host pushes; returns the EventSource or null when unsupported. */
830
+ function connectEvents() {
831
+ if (typeof EventSource !== 'function') return null
832
+ try {
833
+ const source = new EventSource(apiUrl('events'))
834
+ source.addEventListener('config', (event) => {
116
835
  try {
117
- const response = await fetch(apiUrl('reload-safe'), { cache: 'no-store' })
118
- if (response.ok) {
119
- const data = await response.json()
120
- if (data !== null && typeof data === 'object'
121
- && data.revs !== null && typeof data.revs === 'object') {
122
- changed = changedSinceBoot(data.revs)
123
- } else if (Array.isArray(data?.changed)) {
124
- changed = data.changed
836
+ applyConfig(JSON.parse(event.data))
837
+ } catch {
838
+ log('bad config payload')
839
+ }
840
+ })
841
+ source.addEventListener('open', () => log('SSE connected'))
842
+ source.addEventListener('error', () => log('SSE unavailable, relying on fallback polling'))
843
+ return source
844
+ } catch {
845
+ return null
846
+ }
847
+ }
848
+
849
+ // ------------------------------------------------------------------
850
+ // Folder half: state loading, ghost sessions, inline dropdowns
851
+ // ------------------------------------------------------------------
852
+
853
+ /**
854
+ * Session-row CSS for ghost sessions plus, when the DOM already proves it
855
+ * empty, the "Ungrouped" group header.
856
+ * @param ids - ghost session ids.
857
+ * @returns the rules to install.
858
+ */
859
+ function ghostRules(ids) {
860
+ const ghosts = new Set(ids.filter((id) => typeof id === 'string' && GHOST_ID_RE.test(id)))
861
+ const rules = [...ghosts].map((id) => `[data-row-key="session:${id}"]{display:none!important}`).join('')
862
+ if (ghosts.size === 0) return rules
863
+ try {
864
+ // The "Ungrouped" header outlives its rows: hide it when every row
865
+ // between it and the next workspace header belongs to a ghost.
866
+ const tree = document.querySelector('[role="tree"]')
867
+ const ungrouped = tree === null ? null : tree.querySelector('[data-row-key="workspace:"]')
868
+ if (ungrouped === null) return rules
869
+ let sibling = ungrouped.nextElementSibling
870
+ let visible = false
871
+ while (sibling !== null) {
872
+ const key = sibling.getAttribute === undefined ? '' : String(sibling.getAttribute('data-row-key') ?? '')
873
+ if (key.startsWith('workspace:')) break
874
+ if (key.startsWith('session:')) {
875
+ if (!ghosts.has(key.slice('session:'.length))) {
876
+ visible = true
877
+ break
878
+ }
879
+ } else if (key === '') {
880
+ for (const row of sibling.querySelectorAll('[data-row-key^="session:"]')) {
881
+ if (!ghosts.has(String(row.getAttribute('data-row-key') ?? '').slice('session:'.length))) {
882
+ visible = true
883
+ break
125
884
  }
126
885
  }
127
- } catch {
128
- // An unreachable probe falls back to a plain reload.
886
+ if (visible) break
887
+ } else {
888
+ visible = true
889
+ break
129
890
  }
130
- if (changed !== null && changed.length > 0) {
131
- const names = changed.slice(0, 3).join('、') + (changed.length > 3 ? ' 等' : '')
132
- showNotice(t('reload.blocked', { names }))
133
- reportDiag('reload-shortcut-blocked changed=' + changed.join(','))
134
- reloading = false
891
+ sibling = sibling.nextElementSibling
892
+ }
893
+ return visible ? rules : rules + '[role="tree"] [data-row-key="workspace:"]{display:none!important}'
894
+ } catch {
895
+ return rules
896
+ }
897
+ }
898
+
899
+ /** Install (or clear) the ghost-row rules without disturbing other styles. */
900
+ function writeGhostRules(rules) {
901
+ try {
902
+ let tag = document.querySelector('style[data-plugin-css=' + JSON.stringify(GHOST_CSS_TAG_ID) + ']')
903
+ if (rules === '') {
904
+ if (tag !== null) tag.textContent = ''
905
+ return
906
+ }
907
+ if (tag === null) {
908
+ tag = document.createElement('style')
909
+ tag.dataset.plugin = '@leiyi-works/dsh-feature-tweaks'
910
+ tag.dataset.pluginCss = GHOST_CSS_TAG_ID
911
+ document.head.appendChild(tag)
912
+ }
913
+ tag.textContent = rules
914
+ } catch {
915
+ // Hiding ghost rows is best effort.
916
+ }
917
+ }
918
+
919
+ // Hide ghost session rows from the previous page as early as the bundle is
920
+ // imported: the Host answer at activation only refines this list, so a
921
+ // reload no longer paints a deleted row for a few seconds first.
922
+ try {
923
+ if (typeof document !== 'undefined') {
924
+ const cached = JSON.parse(readLocalMirror(GHOST_CACHE_KEY, LEGACY_GHOST_CACHE_KEY) ?? 'null')
925
+ const ids = cached !== null && Array.isArray(cached.ids) ? cached.ids : []
926
+ if (ids.length > 0) writeGhostRules(ghostRules(ids))
927
+ }
928
+ } catch {
929
+ // The Host answer installs the rules at activation.
930
+ }
931
+
932
+ // ------------------------------------------------------------------
933
+ // Components
934
+ // ------------------------------------------------------------------
935
+
936
+ /** One small text button used across the folder page. */
937
+ function smallButton(key, label, onClick, extraClass) {
938
+ return h('button', {
939
+ key,
940
+ type: 'button',
941
+ className: cx('sfbBtn', extraClass),
942
+ onClick,
943
+ }, label)
944
+ }
945
+
946
+ /** One feature switch row: title, description, accessible toggle. */
947
+ function FeatureRow(props) {
948
+ const key = props.featureKey
949
+ const title = props.t('feature.' + key + '.title')
950
+ return h('div', { className: 'twhFeatureRow' },
951
+ h('div', { className: 'twhFeatureText' },
952
+ h('span', { className: 'twhFeatureTitle' }, title),
953
+ h('p', { className: 'twhFeatureDesc' }, props.t('feature.' + key + '.desc'))),
954
+ h('button', {
955
+ type: 'button',
956
+ role: 'switch',
957
+ 'aria-checked': props.checked === true ? 'true' : 'false',
958
+ 'aria-label': title + ':' + (props.checked ? props.t('switch.on') : props.t('switch.off')),
959
+ title: props.checked ? props.t('switch.on') : props.t('switch.off'),
960
+ className: 'twhSwitch',
961
+ 'data-on': props.checked === true ? 'true' : 'false',
962
+ // One save at a time: the Host rewrites the row's profile config, so a
963
+ // second concurrent write could race with the reload it triggers.
964
+ disabled: props.anyBusy === true,
965
+ onClick: () => props.onToggle(key),
966
+ }))
967
+ }
968
+
969
+ /** Feature groups, in page order. */
970
+ const FEATURE_GROUPS = [
971
+ { title: 'group.interface', keys: ['hideRightSidebarToggle', 'hideSessionLogExportMenu', 'expandWorkspaceSessions'] },
972
+ { title: 'group.behavior', keys: ['reloadShortcut', 'quitIgnoresScheduledTasks'] },
973
+ { title: 'group.team', keys: ['defaultTeamForNewSessions'] },
974
+ ]
975
+
976
+ /**
977
+ * 功能微调标签页:六项功能的开关。
978
+ * @param props - `feature` snapshot、`savingKey`、`onToggle` 与本地化 `t`。
979
+ */
980
+ function FeaturePane(props) {
981
+ const feature = props.feature
982
+ return h('div', { className: 'twhPane' },
983
+ FEATURE_GROUPS.map((group) => h('div', { key: group.title, className: 'sfbSection' },
984
+ h('div', { className: 'sfbSectionHead' },
985
+ h('span', { className: 'sfbSectionTitle' }, props.t(group.title))),
986
+ h('div', { className: 'twhFeatureList' },
987
+ group.keys.map((key) => h(FeatureRow, {
988
+ key,
989
+ featureKey: key,
990
+ checked: feature[key] === true,
991
+ anyBusy: props.savingKey !== null,
992
+ onToggle: props.onToggle,
993
+ t: props.t,
994
+ }))))),
995
+ h('p', { className: 'twhFootnote' }, props.t('footnote.saved')))
996
+ }
997
+
998
+ /**
999
+ * The hub page: one left-menu entry, two tabs.
1000
+ * @param props - owner props, injected `runtime`/`menuT`, locale `t`.
1001
+ */
1002
+ function HubPage(props) {
1003
+ const runtime = props.runtime
1004
+ const menuT = props.menuT
1005
+ const [tab, setTab] = React.useState(() => {
1006
+ try {
1007
+ const stored = localStorage.getItem(TAB_KEY)
1008
+ return stored === 'folders' ? 'folders' : 'features'
1009
+ } catch {
1010
+ return 'features'
1011
+ }
1012
+ })
1013
+ const feature = React.useSyncExternalStore(featureStore.subscribe, featureStore.getSnapshot, featureStore.getSnapshot)
1014
+ const [savingKey, setSavingKey] = React.useState(null)
1015
+ const [saveError, setSaveError] = React.useState('')
1016
+
1017
+ const chooseTab = (next) => {
1018
+ setTab(next)
1019
+ try { localStorage.setItem(TAB_KEY, next) } catch { /* private mode */ }
1020
+ }
1021
+
1022
+ const toggle = React.useCallback(async (key) => {
1023
+ const before = featureStore.getSnapshot()[key] === true
1024
+ const next = !before
1025
+ featureStore.set({ ...featureStore.getSnapshot(), [key]: next })
1026
+ setSavingKey(key)
1027
+ setSaveError('')
1028
+ try {
1029
+ const response = await fetch(apiUrl('feature'), {
1030
+ method: 'POST',
1031
+ headers: { 'content-type': 'application/json' },
1032
+ body: JSON.stringify({ key, value: next }),
1033
+ })
1034
+ let data = null
1035
+ try { data = await response.json() } catch { data = null }
1036
+ if (!response.ok || data === null || data.ok !== true) {
1037
+ throw new Error(data !== null && typeof data.error === 'string' ? data.error : 'HTTP ' + response.status)
1038
+ }
1039
+ if (data.config !== null && typeof data.config === 'object') applyConfig(data.config)
1040
+ } catch (error) {
1041
+ featureStore.set({ ...featureStore.getSnapshot(), [key]: before })
1042
+ setSaveError(String(error instanceof Error ? error.message : error))
1043
+ } finally {
1044
+ setSavingKey(null)
1045
+ }
1046
+ }, [feature])
1047
+
1048
+ const tabs = [
1049
+ { id: 'features', label: props.t('tab.features') },
1050
+ { id: 'folders', label: props.t('tab.folders') },
1051
+ ]
1052
+ return h('div', { className: 'sfbRoot' },
1053
+ h('div', { className: 'twhInner' },
1054
+ h('div', { className: 'sfbHeader' },
1055
+ h('h1', { className: 'sfbTitle' }, props.t('page.title')),
1056
+ h('p', { className: 'sfbHint' }, props.t('page.hint'))),
1057
+ h('div', { className: 'twhTabs', role: 'tablist' },
1058
+ tabs.map((item) => h('button', {
1059
+ key: item.id,
1060
+ type: 'button',
1061
+ role: 'tab',
1062
+ 'aria-selected': tab === item.id ? 'true' : 'false',
1063
+ className: 'twhTab',
1064
+ 'data-active': tab === item.id ? 'true' : 'false',
1065
+ onClick: () => chooseTab(item.id),
1066
+ }, item.label))),
1067
+ saveError === '' ? null : h('div', { className: 'sfbErrorRow' },
1068
+ props.t('save.failed', { message: saveError })),
1069
+ tab === 'features'
1070
+ ? h(FeaturePane, { feature, savingKey, onToggle: toggle, t: props.t })
1071
+ : h(FoldersPage, { runtime, t: menuT })))
1072
+ }
1073
+
1074
+ /**
1075
+ * One top-menu folder row: its glyph plus the inline dropdown listing the
1076
+ * entries collected in that folder.
1077
+ * @param props - injected `runtime`/`folderId`, owner `size`, locale `t`.
1078
+ */
1079
+ function FolderRowIcon(props) {
1080
+ const runtime = props.runtime
1081
+ const folderId = props.folderId
1082
+ const locale = (key) => (typeof props.t === 'function' ? props.t(key) : key)
1083
+ const size = typeof props.size === 'number' ? props.size : 16
1084
+ const snapshot = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
1085
+ const ui = React.useSyncExternalStore(runtime.uiSubscribe, runtime.uiGetSnapshot, runtime.uiGetSnapshot)
1086
+ const folder = snapshot.folders.find((item) => item.id === folderId)
1087
+ const open = ui.expandedFolderId === folderId
1088
+ const panels = snapshot.panels.filter((panel) => panel.id !== 'plugins' && !panel.id.startsWith(FOLDER_PANEL_PREFIX))
1089
+ const panelById = new Map(panels.map((panel) => [panel.id, panel]))
1090
+ const members = folder === undefined ? [] : folder.panelIds.map((id) => panelById.get(id) || { id, label: id })
1091
+ return h('span', {
1092
+ className: 'sfbRowGlyph',
1093
+ 'data-sfb-row': folderId,
1094
+ title: folder === undefined ? '' : folder.name,
1095
+ },
1096
+ h('span', { className: 'sfbRowIcon', 'aria-hidden': true }, iconFolder(size)),
1097
+ open
1098
+ ? h('span', {
1099
+ className: 'sfbDropdown',
1100
+ 'data-sfb-popover': '1',
1101
+ onClick: (event) => event.stopPropagation(),
1102
+ },
1103
+ members.length === 0
1104
+ ? h('span', { className: 'sfbMenuNote' }, locale('folders.noMembers'))
1105
+ : members.map((panel) => h('button', {
1106
+ key: 'member:' + panel.id,
1107
+ type: 'button',
1108
+ className: 'sfbMenuRow',
1109
+ onClick: (event) => {
1110
+ event.stopPropagation()
1111
+ runtime.closeFolder()
1112
+ runtime.openPanel(panel.id)
1113
+ },
1114
+ }, h('span', { className: 'sfbMenuLabel' }, panel.label))))
1115
+ : null)
1116
+ }
1117
+
1118
+ /**
1119
+ * The folder row in the conversation header's utility area (top-right).
1120
+ *
1121
+ * A zero-width anchor stays in the utilities flex row; the chips are laid
1122
+ * out as one row on the same line as the native buttons, vertically
1123
+ * centred with them (the More "..." menu) and ending just left of them.
1124
+ * Chips follow the folder list order, laid out left to right.
1125
+ * @param props - injected runtime plus locale t.
1126
+ */
1127
+ function HeaderFoldersBar(props) {
1128
+ const runtime = props.runtime
1129
+ const locale = (key) => (typeof props.t === 'function' ? props.t(key) : key)
1130
+ const snapshot = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
1131
+ const ui = React.useSyncExternalStore(runtime.uiSubscribe, runtime.uiGetSnapshot, runtime.uiGetSnapshot)
1132
+ const folders = snapshot.folders
1133
+ const panels = snapshot.panels.filter((panel) => panel.id !== 'plugins' && !panel.id.startsWith(FOLDER_PANEL_PREFIX))
1134
+ const panelById = new Map(panels.map((panel) => [panel.id, panel]))
1135
+ const anchorRef = React.useRef(null)
1136
+ const chipRefs = React.useRef(new Map())
1137
+ const [anchor, setAnchor] = React.useState(null)
1138
+ const [menu, setMenu] = React.useState(null)
1139
+ const measuresRef = React.useRef(0)
1140
+ React.useLayoutEffect(() => {
1141
+ let settleTimer
1142
+ let pending = false
1143
+ const update = () => {
1144
+ // 文件夹 chips 与「会话标题栏右上角的 utility 行」同一排显示。锚点行是
1145
+ // 稳定参照物:不依赖外壳是否渲染原生按钮(例如「在文件夹中打开」的分栏
1146
+ // 按钮只在 host 发现了可用应用时才出现)。以前按那个按钮定位,按钮一
1147
+ // 缺席就会发现不了位置、整排 chips 直接隐藏。
1148
+ const anchorNode = anchorRef.current
1149
+ const utilities = anchorNode !== null && anchorNode.isConnected
1150
+ ? anchorNode.closest('[class*="headerUtilities"]')
1151
+ : null
1152
+ if (utilities === null) {
1153
+ setAnchor((prev) => (prev === null ? prev : null))
1154
+ setMenu((prev) => (prev === null ? prev : null))
135
1155
  return
136
1156
  }
137
- window.setTimeout(() => {
138
- try { globalThis.location.reload() } catch { /* the page is going away anyway */ }
139
- }, 120)
1157
+ const utilitiesRect = utilities.getBoundingClientRect()
1158
+ // 文件预览页/非会话视图里头部工具行会被替换或隐藏:行尺寸为 0 时隐藏
1159
+ // 文件夹入口,避免它停在旧位置与其他按钮重叠。
1160
+ if (!(utilitiesRect.width > 0 && utilitiesRect.height > 1)) {
1161
+ setAnchor((prev) => (prev === null ? prev : null))
1162
+ setMenu((prev) => (prev === null ? prev : null))
1163
+ return
1164
+ }
1165
+ // Chips share the utilities row: vertically centred on the native
1166
+ // buttons (the More "..." menu) and ending just left of them, so the
1167
+ // folder row lines up with the header instead of dropping below it
1168
+ // on any viewport width (desktop and phone alike). The width is
1169
+ // capped to the space left of the utilities row so the chips never
1170
+ // cover the native buttons on a narrow screen.
1171
+ const top = Math.round(utilitiesRect.top + (utilitiesRect.height - 24) / 2)
1172
+ const right = Math.round(Math.max(8, window.innerWidth - utilitiesRect.left + 6))
1173
+ const maxWidth = Math.max(96, Math.round(utilitiesRect.left - 12))
1174
+ setAnchor((prev) => (prev !== null && prev.top === top && prev.right === right
1175
+ && prev.maxWidth === maxWidth ? prev : { top, right, maxWidth }))
1176
+ if (measuresRef.current < 3) {
1177
+ measuresRef.current += 1
1178
+ const portal = ReactDOM !== null && typeof ReactDOM.createPortal === 'function'
1179
+ const nativeButton = utilities.querySelector('[class*="mOxcpG_menuAnchor"]')
1180
+ reportDiag(`header-bar-measure row=${Math.round(utilitiesRect.left)},${Math.round(utilitiesRect.bottom)},${Math.round(utilitiesRect.width)}x${Math.round(utilitiesRect.height)} native=${nativeButton !== null} portal=${portal} inner=${window.innerWidth}`)
1181
+ }
1182
+ }
1183
+ // 同一个动画帧内只重排一次,避免流式输出期间的 DOM 变更风暴。
1184
+ const rerun = () => {
1185
+ if (pending) return
1186
+ pending = true
1187
+ window.requestAnimationFrame(() => {
1188
+ pending = false
1189
+ update()
1190
+ })
140
1191
  }
1192
+ update()
1193
+ // The shell can still be animating the sidebar/header in when the layout
1194
+ // effect runs; measure again after the animation settles.
1195
+ const settleFrame = window.requestAnimationFrame(update)
1196
+ settleTimer = window.setTimeout(update, 320)
1197
+ window.addEventListener('resize', update)
1198
+ window.addEventListener('scroll', update, true)
1199
+ // 切到文件预览/其他页签时,头部工具行会被替换但不会触发 resize;
1200
+ // 监听 DOM 变化和路由变化,重新测量;再用低频定时器兜底。
1201
+ const observer = typeof MutationObserver === 'function'
1202
+ ? new MutationObserver(rerun)
1203
+ : null
1204
+ if (observer !== null) observer.observe(document.body, { childList: true, subtree: true })
1205
+ const fallbackTimer = window.setInterval(rerun, 1000)
1206
+ window.addEventListener('hashchange', rerun)
1207
+ window.addEventListener('popstate', rerun)
1208
+ return () => {
1209
+ window.cancelAnimationFrame(settleFrame)
1210
+ window.clearTimeout(settleTimer)
1211
+ window.clearInterval(fallbackTimer)
1212
+ window.removeEventListener('resize', update)
1213
+ window.removeEventListener('scroll', update, true)
1214
+ window.removeEventListener('hashchange', rerun)
1215
+ window.removeEventListener('popstate', rerun)
1216
+ if (observer !== null) observer.disconnect()
1217
+ }
1218
+ }, [folders.length])
1219
+ React.useLayoutEffect(() => {
1220
+ const folderId = ui.headerFolderId
1221
+ if (folderId === null) {
1222
+ setMenu(null)
1223
+ return undefined
1224
+ }
1225
+ const chip = chipRefs.current.get(folderId)
1226
+ if (chip === undefined || chip === null || !chip.isConnected) {
1227
+ setMenu(null)
1228
+ return undefined
1229
+ }
1230
+ const rect = chip.getBoundingClientRect()
1231
+ setMenu({ folderId, top: Math.round(rect.bottom + 6), right: Math.round(Math.max(8, window.innerWidth - rect.right)) })
1232
+ return undefined
1233
+ }, [ui.headerFolderId, folders, anchor])
1234
+ if (folders.length === 0) return null
1235
+ const openFolder = menu === null ? undefined : folders.find((folder) => folder.id === menu.folderId)
1236
+ const members = openFolder === undefined ? [] : openFolder.panelIds.map((id) => panelById.get(id) || { id, label: id })
1237
+ const chips = folders.map((folder) => h('button', {
1238
+ key: 'chip:' + folder.id,
1239
+ ref: (node) => {
1240
+ if (node === null) chipRefs.current.delete(folder.id)
1241
+ else chipRefs.current.set(folder.id, node)
1242
+ },
1243
+ type: 'button',
1244
+ className: 'sfbHeaderFolder',
1245
+ 'data-sfb-header-folder': folder.id,
1246
+ title: folder.name,
1247
+ onClick: (event) => {
1248
+ event.stopPropagation()
1249
+ runtime.toggleHeaderFolder(folder.id)
1250
+ },
1251
+ },
1252
+ h('span', { className: 'sfbRowIcon', 'aria-hidden': true }, iconFolder(13)),
1253
+ h('span', { className: 'sfbHeaderFolderName' }, folder.name)))
1254
+ const barNode = anchor === null ? null : h('span', {
1255
+ className: 'sfbHeaderBar',
1256
+ style: { top: anchor.top + 'px', right: anchor.right + 'px', maxWidth: anchor.maxWidth + 'px' },
1257
+ },
1258
+ chips)
1259
+ const menuNode = menu === null ? null : h('span', {
1260
+ className: 'sfbHeaderDropdown',
1261
+ 'data-sfb-popover': '1',
1262
+ 'data-sfb-header-popover': '1',
1263
+ style: { top: menu.top + 'px', right: menu.right + 'px' },
1264
+ onClick: (event) => event.stopPropagation(),
1265
+ },
1266
+ members.length === 0
1267
+ ? h('span', { className: 'sfbMenuNote' }, locale('folders.noMembers'))
1268
+ : members.map((panel) => h('button', {
1269
+ key: 'member:' + panel.id,
1270
+ type: 'button',
1271
+ className: 'sfbMenuRow',
1272
+ onClick: (event) => {
1273
+ event.stopPropagation()
1274
+ runtime.closeHeaderFolder()
1275
+ runtime.openPanel(panel.id)
1276
+ },
1277
+ }, h('span', { className: 'sfbMenuLabel' }, panel.label))))
1278
+ const overlayContent = h(React.Fragment, null, barNode, menuNode)
1279
+ const overlay = anchor === null
1280
+ ? null
1281
+ : ReactDOM !== null && typeof ReactDOM.createPortal === 'function' && typeof document !== 'undefined'
1282
+ ? ReactDOM.createPortal(overlayContent, document.body)
1283
+ : overlayContent
1284
+ return h(React.Fragment, null,
1285
+ h('span', { className: 'sfbHeaderAnchor', ref: anchorRef, 'aria-hidden': true }),
1286
+ overlay)
1287
+ }
141
1288
 
142
- ctx.inject(['shortcuts'], (scope) => {
143
- scope.effect(() => {
144
- try {
145
- const dispose = scope.shortcuts.register({
146
- id: 'feature-tweaks.reload',
147
- label: () => t('reload.label'),
148
- aliases: ['reload', 'refresh', '刷新'],
149
- defaults: {
150
- 'desktop:windows': { code: 'F5', modifiers: [] },
151
- 'desktop:macos': { code: 'F5', modifiers: [] },
152
- 'web:windows': { code: 'KeyR', modifiers: ['primary', 'shift'] },
153
- 'web:macos': { code: 'KeyR', modifiers: ['primary', 'shift'] },
1289
+ /**
1290
+ * The folder manager page (rendered inside the 菜单文件夹 tab).
1291
+ * @param props - injected runtime plus locale `t`.
1292
+ */
1293
+ function FoldersPage(props) {
1294
+ const runtime = props.runtime
1295
+ const locale = (key) => (typeof props.t === 'function' ? props.t(key) : key)
1296
+ const snapshot = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
1297
+ const [newDraft, setNewDraft] = React.useState('')
1298
+ const [editingId, setEditingId] = React.useState(null)
1299
+ const [renameDraft, setRenameDraft] = React.useState('')
1300
+ const folders = snapshot.folders
1301
+ const panels = snapshot.panels.filter((panel) => panel.id !== 'plugins' && !panel.id.startsWith(FOLDER_PANEL_PREFIX))
1302
+ const assigned = new Set()
1303
+ for (const folder of folders) for (const id of folder.panelIds) assigned.add(id)
1304
+ const unassigned = panels.filter((panel) => !assigned.has(panel.id))
1305
+ const panelById = new Map(panels.map((panel) => [panel.id, panel]))
1306
+
1307
+ const createFolder = () => {
1308
+ const name = newDraft.trim()
1309
+ if (name === '') return
1310
+ runtime.createFolder(name)
1311
+ setNewDraft('')
1312
+ }
1313
+ const startRename = (folder) => {
1314
+ setEditingId(folder.id)
1315
+ setRenameDraft(folder.name)
1316
+ }
1317
+ const commitRename = () => {
1318
+ if (editingId === null) return
1319
+ runtime.renameFolder(editingId, renameDraft)
1320
+ setEditingId(null)
1321
+ setRenameDraft('')
1322
+ }
1323
+
1324
+ const folderCard = (folder) => {
1325
+ const members = folder.panelIds.map((id) => panelById.get(id) || { id, label: id })
1326
+ const renaming = editingId === folder.id
1327
+ const memberRow = (panel, index) => h('div', {
1328
+ key: 'member:' + panel.id,
1329
+ className: 'sfbEntryRow',
1330
+ },
1331
+ h('span', { className: 'sfbEntryName' }, panel.label),
1332
+ h('span', { className: 'sfbActions' },
1333
+ index > 0
1334
+ ? smallButton('up', locale('entries.up'), () => runtime.movePanel(folder.id, panel.id, -1))
1335
+ : null,
1336
+ index < members.length - 1
1337
+ ? smallButton('down', locale('entries.down'), () => runtime.movePanel(folder.id, panel.id, 1))
1338
+ : null,
1339
+ smallButton('remove', locale('entries.remove'), () => runtime.unassignPanel(panel.id))))
1340
+ return h('div', { key: 'folder:' + folder.id, className: 'sfbFolderCard' },
1341
+ h('div', { className: 'sfbFolderHead' },
1342
+ h('span', { className: 'sfbIcon' }, iconFolder(15)),
1343
+ renaming
1344
+ ? h('input', {
1345
+ className: 'sfbInput',
1346
+ style: { maxWidth: '240px' },
1347
+ autoFocus: true,
1348
+ value: renameDraft,
1349
+ onChange: (event) => setRenameDraft(event.target.value),
1350
+ onKeyDown: (event) => {
1351
+ if (event.key === 'Enter') { event.preventDefault(); commitRename() }
1352
+ else if (event.key === 'Escape') { event.preventDefault(); setEditingId(null) }
154
1353
  },
155
- regions: ['page', 'editable', 'terminal'],
156
- modals: [],
157
- resolve: () => ({
158
- status: 'handled',
159
- run: () => { void scheduleReload() },
160
- }),
1354
+ onBlur: commitRename,
161
1355
  })
162
- reportDiag('reload-shortcut-ready')
163
- return dispose
164
- } catch (error) {
165
- reportDiag('reload-shortcut-failed: ' + errorText(error))
166
- return () => {}
167
- }
168
- }, 'feature-tweaks: reload shortcut')
169
- })
1356
+ : h('span', { className: 'sfbFolderName' }, folder.name),
1357
+ h('span', { className: 'sfbCount' }, String(members.length)),
1358
+ h('span', { className: 'sfbSpacer' }),
1359
+ h('span', { className: 'sfbActions' },
1360
+ smallButton('up', locale('folders.up'), () => runtime.moveFolder(folder.id, -1)),
1361
+ smallButton('down', locale('folders.down'), () => runtime.moveFolder(folder.id, 1)),
1362
+ smallButton('rename', locale('folders.rename'), () => startRename(folder)),
1363
+ smallButton('delete', locale('folders.delete'), () => runtime.deleteFolder(folder.id), 'sfbBtnDanger'))),
1364
+ h('div', { className: 'sfbFolderBody' },
1365
+ members.length === 0
1366
+ ? h('div', { className: 'sfbMuted' }, locale('folders.noMembers'))
1367
+ : members.map((panel, index) => memberRow(panel, index))))
1368
+ }
1369
+
1370
+ const entryRow = (panel) => h('div', { key: 'entry:' + panel.id, className: 'sfbEntryRow' },
1371
+ h('span', { className: 'sfbEntryName' }, panel.label),
1372
+ h('select', {
1373
+ className: 'sfbSelect',
1374
+ value: '',
1375
+ 'aria-label': locale('entries.moveTo'),
1376
+ onChange: (event) => {
1377
+ const folderId = event.target.value
1378
+ if (folderId !== '') runtime.assignPanel(panel.id, folderId)
1379
+ },
1380
+ },
1381
+ h('option', { value: '' }, locale('entries.moveTo')),
1382
+ folders.map((folder) => h('option', { key: folder.id, value: folder.id }, folder.name))))
1383
+
1384
+ return h(React.Fragment, null,
1385
+ h('p', { className: 'sfbHint' }, locale('page.hint')),
1386
+ snapshot.loadError
1387
+ ? h('div', { className: 'sfbErrorRow' }, locale('save.failed'))
1388
+ : null,
1389
+ // Uncollected entries first, folders after: that is the order the left
1390
+ // menu shows them in (pinned entries above the folder rows).
1391
+ h('div', { className: 'sfbSection' },
1392
+ h('div', { className: 'sfbSectionHead' },
1393
+ h('span', { className: 'sfbSectionTitle' }, locale('entries.section')),
1394
+ h('span', { className: 'sfbCount' }, String(unassigned.length))),
1395
+ unassigned.length === 0
1396
+ ? h('div', { className: 'sfbMuted' }, locale('entries.empty'))
1397
+ : unassigned.map(entryRow)),
1398
+ h('div', { className: 'sfbSection' },
1399
+ h('div', { className: 'sfbSectionHead' },
1400
+ h('span', { className: 'sfbSectionTitle' }, locale('folders.section')),
1401
+ h('span', { className: 'sfbCount' }, String(folders.length))),
1402
+ folders.length === 0
1403
+ ? h('div', { className: 'sfbMuted' }, locale('folders.empty'))
1404
+ : folders.map(folderCard),
1405
+ h('div', { className: 'sfbNewRow' },
1406
+ h('input', {
1407
+ className: 'sfbInput',
1408
+ value: newDraft,
1409
+ placeholder: locale('folders.placeholder'),
1410
+ onChange: (event) => setNewDraft(event.target.value),
1411
+ onKeyDown: (event) => {
1412
+ if (event.key === 'Enter') { event.preventDefault(); createFolder() }
1413
+ },
1414
+ }),
1415
+ h('button', { type: 'button', className: 'sfbBtnPrimary', onClick: createFolder }, locale('folders.new')))))
1416
+ }
1417
+
1418
+ /**
1419
+ * The page one top-menu folder row opens: every entry collected in it.
1420
+ * @param props - injected `runtime` and `folderId`, plus locale `t`.
1421
+ */
1422
+ function FolderPage(props) {
1423
+ const runtime = props.runtime
1424
+ const folderId = props.folderId
1425
+ const locale = (key) => (typeof props.t === 'function' ? props.t(key) : key)
1426
+ const snapshot = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
1427
+ const folder = snapshot.folders.find((item) => item.id === folderId)
1428
+ const panels = snapshot.panels.filter((panel) => panel.id !== 'plugins' && !panel.id.startsWith(FOLDER_PANEL_PREFIX))
1429
+ const panelById = new Map(panels.map((panel) => [panel.id, panel]))
1430
+ const members = folder === undefined ? [] : folder.panelIds.map((id) => panelById.get(id) || { id, label: id })
1431
+ return h('div', { className: 'sfbRoot' },
1432
+ h('div', { className: 'sfbInner' },
1433
+ h('div', { className: 'sfbHeader' },
1434
+ h('h1', { className: 'sfbTitle' }, folder === undefined ? locale('page.title') : folder.name),
1435
+ h('p', { className: 'sfbHint' }, locale('folderPage.manage'))),
1436
+ members.length === 0
1437
+ ? h('div', { className: 'sfbMuted' }, locale('folderPage.empty'))
1438
+ : h('div', { className: 'sfbSection' }, members.map((panel) => h('button', {
1439
+ key: 'member:' + panel.id,
1440
+ type: 'button',
1441
+ className: 'sfbEntryButton',
1442
+ onClick: () => runtime.openPanel(panel.id),
1443
+ },
1444
+ h('span', { className: 'sfbEntryName' }, panel.label),
1445
+ h('span', { className: 'sfbEntryChevron' }, iconChevron(14)))))))
1446
+ }
1447
+
1448
+ /**
1449
+ * The row contributed to the panel list's More menu: it only syncs the
1450
+ * sidebar's own pin state so collected entries leave the top menu.
1451
+ * @param props - owner props (entries/onPinnedChange), injected runtime,
1452
+ * and locale `t`.
1453
+ */
1454
+ function MoreMenuContent(props) {
1455
+ const runtime = props.runtime
1456
+ const locale = (key) => (typeof props.t === 'function' ? props.t(key) : key)
1457
+ const snapshot = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
1458
+ const folders = snapshot.folders
1459
+ const entries = Array.isArray(props.entries) ? props.entries : []
1460
+ const onPinnedChange = props.onPinnedChange
1461
+
1462
+ React.useLayoutEffect(() => {
1463
+ const onDismiss = props.onDismiss
1464
+ if (typeof onPinnedChange === 'function') {
1465
+ const assigned = new Set()
1466
+ for (const folder of folders) for (const id of folder.panelIds) assigned.add(id)
1467
+ for (const entry of entries) {
1468
+ if (entry.id.startsWith(FOLDER_PANEL_PREFIX)) continue
1469
+ const desired = !assigned.has(entry.id)
1470
+ if (entry.pinned !== desired) onPinnedChange(entry.id, desired)
1471
+ }
1472
+ }
1473
+ // A hidden auto-sync pass closes the menu again before it is painted.
1474
+ if (typeof runtime.consumeAutoSync === 'function' && runtime.consumeAutoSync()) {
1475
+ if (typeof onDismiss === 'function') onDismiss()
1476
+ }
1477
+ }, [folders, entries, onPinnedChange])
1478
+
1479
+ return h('div', { className: 'sfbMenu' }, [
1480
+ h('div', {
1481
+ key: 'note',
1482
+ className: 'sfbMenuNote',
1483
+ 'data-sfb-more-note': '1',
1484
+ }, locale('more.note')),
1485
+ ])
1486
+ }
1487
+
1488
+ // ------------------------------------------------------------------
1489
+ // Plugin
1490
+ // ------------------------------------------------------------------
170
1491
 
171
- // Fallback for the desktop shell: its native shortcut bridge only
172
- // forwards a key once the shell has received this command's definition,
173
- // and that hand-off can lag a page load. A plain DOM listener reloads the
174
- // page anyway; when the bridge does forward the key, the shell consumes
175
- // it first and this listener never sees it, so reload never runs twice.
1492
+ /** Mount the feature half of the plugin (DOM tweaks, SSE, reload shortcut). */
1493
+ function applyFeatures(ctx) {
1494
+ // 界面侧:先注入隐藏规则(避免按钮闪一下),再装会话列表展开与配置订阅。
1495
+ ensureStyle()
1496
+ sessionExpander = installSessionListExpander()
1497
+ const source = connectEvents()
1498
+ void syncOnce()
1499
+
1500
+ // 快捷键:服务可用后按当前开关注册(配置热更新时动态注册/注销)。
1501
+ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
176
1502
  ctx.effect(() => {
177
1503
  const onKeyDown = (event) => {
1504
+ if (!reloadShortcutEnabled) return
178
1505
  if (event.key !== 'F5' || event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) return
179
1506
  if (event.defaultPrevented) return
180
1507
  event.preventDefault()
@@ -184,6 +1511,932 @@ window.__ModuleLoader__.load({
184
1511
  document.addEventListener('keydown', onKeyDown, true)
185
1512
  return () => document.removeEventListener('keydown', onKeyDown, true)
186
1513
  }, 'feature-tweaks: reload key fallback')
1514
+ }
1515
+
1516
+ try {
1517
+ ctx.inject(['shortcuts'], (scope) => {
1518
+ shortcutsService = scope.shortcuts
1519
+ syncReloadShortcut()
1520
+ scope.effect(() => () => {
1521
+ shortcutsService = null
1522
+ if (shortcutDispose !== null) {
1523
+ try { shortcutDispose() } catch { /* already gone */ }
1524
+ shortcutDispose = null
1525
+ }
1526
+ }, 'feature-tweaks: reload shortcut')
1527
+ })
1528
+ } catch (error) {
1529
+ reportDiag('shortcuts-inject-failed: ' + errorText(error))
1530
+ }
1531
+
1532
+ // Fallback poll interval follows the config (started when applyConfig lands).
1533
+ startPolling(FALLBACK_POLL_MS)
1534
+
1535
+ // Cleanup: timers, SSE, expander, style — unload must restore the page.
1536
+ ctx.effect(() => () => {
1537
+ stopped = true
1538
+ if (pollHandle !== null) {
1539
+ clearInterval(pollHandle)
1540
+ pollHandle = null
1541
+ }
1542
+ if (diagnosticTimer !== null) clearTimeout(diagnosticTimer)
1543
+ if (source !== null) source.close()
1544
+ if (sessionExpander !== null) {
1545
+ sessionExpander.dispose()
1546
+ sessionExpander = null
1547
+ }
1548
+ const style = document.getElementById(CSS_TAG_ID + '-hide')
1549
+ if (style !== null) style.remove()
1550
+ }, 'feature-tweaks: cleanup')
1551
+ }
1552
+
1553
+ /** Mount the folder half of the plugin plus the single left-menu hub entry. */
1554
+ function applyFolders(ctx) {
1555
+ reportDiag('apply-start v' + VERSION)
1556
+ const store = createSnapshotStore({ panels: [], folders: [], loadError: false })
1557
+ let saveTimer
1558
+ let saveFailed = false
1559
+
1560
+ const update = (patch) => {
1561
+ store.set({ ...store.getSnapshot(), ...patch })
1562
+ }
1563
+
1564
+ /** Rebuild the observable menu index from the live slot table. */
1565
+ const refreshPanels = () => {
1566
+ let entries = []
1567
+ try {
1568
+ entries = ctx.slots.entriesOfSlot('sidebar.panellist')
1569
+ } catch {
1570
+ entries = []
1571
+ }
1572
+ const panels = entries.map(({ options }) => {
1573
+ let label = options.label
1574
+ if (typeof label === 'function') {
1575
+ try { label = label() } catch { label = undefined }
1576
+ }
1577
+ return {
1578
+ id: options.id,
1579
+ label: typeof label === 'string' && label !== '' ? label : options.id,
1580
+ order: typeof options.order === 'number' ? options.order : 0,
1581
+ }
1582
+ }).sort((a, b) => (a.order - b.order) || a.id.localeCompare(b.id))
1583
+ const previous = store.getSnapshot()
1584
+ if (previous.panels.length === panels.length
1585
+ && previous.panels.every((panel, index) => {
1586
+ const candidate = panels[index]
1587
+ return panel.id === candidate.id && panel.label === candidate.label && panel.order === candidate.order
1588
+ })) {
1589
+ // The row set is unchanged, but a re-registration can still need the
1590
+ // pin correction (a page reload resets the sidebar's pin store).
1591
+ maybeSyncPins()
1592
+ return
1593
+ }
1594
+ update({ panels })
1595
+ maybeSyncPins()
1596
+ }
1597
+
1598
+ /** Persist the folder list through the Host route, mirroring to localStorage. */
1599
+ const persistNow = async () => {
1600
+ saveTimer = undefined
1601
+ const payload = { folders: store.getSnapshot().folders }
1602
+ try {
1603
+ localStorage.setItem(LOCAL_KEY, JSON.stringify(payload))
1604
+ } catch {
1605
+ // Private mode or quota: the Host copy still applies.
1606
+ }
1607
+ try {
1608
+ const response = await fetch(apiUrl('state'), {
1609
+ method: 'POST',
1610
+ headers: { 'content-type': 'application/json' },
1611
+ body: JSON.stringify(payload),
1612
+ })
1613
+ if (!response.ok) throw new Error('HTTP ' + response.status)
1614
+ if (saveFailed) {
1615
+ saveFailed = false
1616
+ update({ loadError: false })
1617
+ }
1618
+ } catch (error) {
1619
+ saveFailed = true
1620
+ update({ loadError: true })
1621
+ reportDiag('save-failed: ' + errorText(error))
1622
+ }
1623
+ }
1624
+
1625
+ const persist = () => {
1626
+ if (saveTimer !== undefined) window.clearTimeout(saveTimer)
1627
+ saveTimer = window.setTimeout(() => { void persistNow() }, 300)
1628
+ }
1629
+
1630
+ const commit = (folders) => {
1631
+ update({ folders })
1632
+ persist()
1633
+ }
1634
+
1635
+ // Which folder's inline dropdown is open in the left menu (view state
1636
+ // only; never persisted).
1637
+ const uiStore = createSnapshotStore({ expandedFolderId: null, headerFolderId: null })
1638
+
1639
+ // Collected entries must leave the top menu. The only supported switch
1640
+ // for that is the sidebar's own pin state, which is reachable solely from
1641
+ // rows mounted inside its More menu — so the plugin opens that menu
1642
+ // invisibly (same tick, closed again from a layout effect) whenever the
1643
+ // collected set changes.
1644
+ //
1645
+ // The sidebar's pin store is page-local (it resets to "everything pinned"
1646
+ // on every page load), so the correction must run at every load and after
1647
+ // any panellist row registers late — a reloaded or renamed plugin adds its
1648
+ // entry after the first sync. The signature therefore covers the live
1649
+ // panellist ids too, an unavailable trigger retries instead of latching,
1650
+ // and a DOM leak detector repairs a member that a later registration or a
1651
+ // manual pin puts back on the top menu.
1652
+ let autoSyncPending = false
1653
+ let pinSyncBusy = false
1654
+ let pinSyncTimer
1655
+ let pinSyncRetryTimer
1656
+ let pinSyncAttempts = 0
1657
+ let lastPinSignature = ''
1658
+ let pendingPinSignature = ''
1659
+
1660
+ /** Live panellist ids, sorted; the signature input for late registrations. */
1661
+ const livePanellistIds = () => {
1662
+ try {
1663
+ return ctx.slots.entriesOfSlot('sidebar.panellist')
1664
+ .map((entry) => (entry === null || entry === undefined || entry.options === null || entry.options === undefined ? undefined : entry.options.id))
1665
+ .filter((id) => typeof id === 'string')
1666
+ .sort()
1667
+ } catch {
1668
+ return []
1669
+ }
1670
+ }
1671
+
1672
+ /** Folder assignments plus live panellist ids: any change re-runs the sync. */
1673
+ const pinSignature = () => JSON.stringify({
1674
+ folders: store.getSnapshot().folders.map((folder) => [folder.id, folder.panelIds]),
1675
+ panels: livePanellistIds(),
1676
+ })
1677
+
1678
+ /** User-visible labels of every entry collected into a folder. */
1679
+ const folderMemberLabels = () => {
1680
+ const assigned = new Set()
1681
+ for (const folder of store.getSnapshot().folders) for (const id of folder.panelIds) assigned.add(id)
1682
+ const labels = []
1683
+ if (assigned.size === 0) return labels
1684
+ try {
1685
+ for (const entry of ctx.slots.entriesOfSlot('sidebar.panellist')) {
1686
+ const id = entry === null || entry === undefined || entry.options === null || entry.options === undefined ? undefined : entry.options.id
1687
+ if (!assigned.has(id)) continue
1688
+ let label = entry.options.label
1689
+ if (typeof label === 'function') {
1690
+ try { label = label() } catch { label = undefined }
1691
+ }
1692
+ if (typeof label === 'string' && label.trim() !== '') labels.push(label.trim())
1693
+ }
1694
+ } catch {
1695
+ return []
1696
+ }
1697
+ return labels
1698
+ }
1699
+
1700
+ /**
1701
+ * Whether a folder member still renders as a top-level sidebar row. The
1702
+ * folder rows themselves and the More launcher are skipped, as is the
1703
+ * inline folder dropdown (its members are supposed to show there).
1704
+ */
1705
+ const detectLeakedMember = () => {
1706
+ const labels = folderMemberLabels()
1707
+ if (labels.length === 0) return false
1708
+ const glyph = document.querySelector('[data-sfb-row]')
1709
+ const nav = glyph === null ? null : glyph.closest('nav')
1710
+ if (nav === null) return false
1711
+ const wanted = labels.map((label) => label.replace(/\s+/g, ''))
1712
+ for (const row of nav.querySelectorAll('button')) {
1713
+ if (row.getAttribute('aria-haspopup') === 'menu') continue
1714
+ if (row.closest('[data-sfb-popover="1"]') !== null) continue
1715
+ if (row.querySelector('[data-sfb-row]') !== null) continue
1716
+ const text = (row.textContent || '').replace(/\s+/g, '')
1717
+ if (text === '') continue
1718
+ for (const label of wanted) {
1719
+ if (text === label) return true
1720
+ if (text.startsWith(label) && text.length - label.length <= 8) return true
1721
+ }
1722
+ }
1723
+ return false
1724
+ }
1725
+
1726
+ /** One diagnostic line per page load once the pass has hidden rows. */
1727
+ let moreHideReported = false
1728
+
1729
+ /** Normalize visible row text so markup whitespace never splits a match. */
1730
+ const rowText = (element) => String(element.textContent ?? '').replace(/\s+/gu, '')
1731
+
1732
+ /** The sidebar's More menu, recognized by this plugin's own note row. */
1733
+ const moreMenuContainer = () => {
1734
+ const note = document.querySelector('[data-sfb-more-note]')
1735
+ if (note === null) return null
1736
+ // The note normally renders inside the menu element; when the owner
1737
+ // puts slot rows beside the menu instead, the popup body that also
1738
+ // holds menu items is the closest safe container.
1739
+ const menu = note.closest('[role="menu"]')
1740
+ if (menu !== null) return menu
1741
+ let cursor = note.parentElement
1742
+ while (cursor !== null && cursor !== document.body) {
1743
+ if (cursor.querySelector('[role="menuitem"]') !== null) return cursor
1744
+ cursor = cursor.parentElement
1745
+ }
1746
+ return null
1747
+ }
1748
+
1749
+ /** Undo a previous pass: an open menu (or a flipped setting) gets its rows back. */
1750
+ const restoreMoreRows = () => {
1751
+ for (const row of document.querySelectorAll('[' + HIDDEN_ROW_ATTR + ']')) {
1752
+ if (row instanceof HTMLElement) {
1753
+ row.style.removeProperty('display')
1754
+ row.removeAttribute(HIDDEN_ROW_ATTR)
1755
+ }
1756
+ for (const button of row.querySelectorAll('[' + HIDDEN_BUTTON_ATTR + ']')) {
1757
+ if (!(button instanceof HTMLElement)) continue
1758
+ button.removeAttribute(HIDDEN_BUTTON_ATTR)
1759
+ button.removeAttribute('disabled')
1760
+ button.removeAttribute('tabindex')
1761
+ }
1762
+ }
1763
+ }
1764
+
1765
+ /**
1766
+ * Remove rows of already-collected entries from the sidebar's More menu.
1767
+ *
1768
+ * DSH tracks launchers as pinned or unpinned and lists every unpinned one
1769
+ * in that menu, which is why a collected entry still appears there. The
1770
+ * menu is rendered by DSH, so the only reachable switch is its DOM: hide
1771
+ * the row whose visible text is exactly the collected label, and make its
1772
+ * buttons unreachable so keyboard focus never lands on a hidden row. The
1773
+ * menu is rebuilt on every open, so nothing has to be persisted here.
1774
+ */
1775
+ const hideCollectedInMoreMenu = () => {
1776
+ const snapshot = store.getSnapshot()
1777
+ if (snapshot.folders.length === 0) {
1778
+ restoreMoreRows()
1779
+ return
1780
+ }
1781
+ const labels = folderMemberLabels()
1782
+ if (labels.length === 0) {
1783
+ restoreMoreRows()
1784
+ return
1785
+ }
1786
+ const wanted = new Set(labels.map((label) => label.replace(/\s+/gu, '')))
1787
+ const menu = moreMenuContainer()
1788
+ if (menu === null) return
1789
+ const matches = []
1790
+ for (const element of menu.querySelectorAll('*')) {
1791
+ if (element.hasAttribute(HIDDEN_ROW_ATTR)) continue
1792
+ const text = rowText(element)
1793
+ if (text === '' || !wanted.has(text)) continue
1794
+ matches.push(element)
1795
+ }
1796
+ // Nested matches share one row: keep the outermost element of each.
1797
+ const rows = matches.filter((element) => !matches.some((other) => (
1798
+ other !== element && other.contains(element)
1799
+ )))
1800
+ let hidden = 0
1801
+ for (const row of rows) {
1802
+ if (!(row instanceof HTMLElement)) continue
1803
+ if (row.querySelector('[role="menuitem"]') === null) continue
1804
+ row.style.display = 'none'
1805
+ row.setAttribute(HIDDEN_ROW_ATTR, '1')
1806
+ hidden += 1
1807
+ for (const button of row.querySelectorAll('button')) {
1808
+ if (button.hasAttribute(HIDDEN_BUTTON_ATTR)) continue
1809
+ button.setAttribute(HIDDEN_BUTTON_ATTR, '1')
1810
+ button.setAttribute('disabled', '')
1811
+ button.tabIndex = -1
1812
+ }
1813
+ }
1814
+ // One line per page so a live run proves the pass found the rows.
1815
+ if (hidden > 0 && !moreHideReported) {
1816
+ moreHideReported = true
1817
+ reportDiag('more-hide rows=' + hidden)
1818
+ }
1819
+ }
1820
+
1821
+ /** Retry a sync whose sidebar DOM was not ready yet (bounded). */
1822
+ const schedulePinRetry = () => {
1823
+ if (pinSyncRetryTimer !== undefined) return
1824
+ if (pinSyncAttempts >= 40) return
1825
+ pinSyncAttempts += 1
1826
+ pinSyncRetryTimer = window.setTimeout(() => {
1827
+ pinSyncRetryTimer = undefined
1828
+ runPinSync()
1829
+ }, 250)
1830
+ }
1831
+
1832
+ const requestPinSync = (delay = 80) => {
1833
+ if (pinSyncTimer !== undefined) window.clearTimeout(pinSyncTimer)
1834
+ pinSyncTimer = window.setTimeout(() => {
1835
+ pinSyncTimer = undefined
1836
+ runPinSync()
1837
+ }, delay)
1838
+ }
1839
+
1840
+ const runPinSync = () => {
1841
+ if (pinSyncBusy) return
1842
+ if (store.getSnapshot().folders.length === 0) return
1843
+ const glyph = document.querySelector('[data-sfb-row]')
1844
+ const nav = glyph === null ? null : glyph.closest('nav')
1845
+ const trigger = nav === null ? null : nav.querySelector('button[aria-haspopup="menu"]')
1846
+ // The sidebar or a plugin row can still be mounting; retry instead of
1847
+ // dropping the correction (the old code returned here, and the latched
1848
+ // signature then suppressed every later attempt).
1849
+ if (trigger === null || document.querySelector('[role="menu"]') !== null) {
1850
+ schedulePinRetry()
1851
+ return
1852
+ }
1853
+ pinSyncBusy = true
1854
+ autoSyncPending = true
1855
+ const previousFocus = document.activeElement
1856
+ try {
1857
+ trigger.click()
1858
+ } catch (error) {
1859
+ autoSyncPending = false
1860
+ pinSyncBusy = false
1861
+ reportDiag('pin-sync-click-failed: ' + errorText(error))
1862
+ schedulePinRetry()
1863
+ return
1864
+ }
1865
+ window.setTimeout(() => {
1866
+ autoSyncPending = false
1867
+ pinSyncBusy = false
1868
+ pinSyncAttempts = 0
1869
+ lastPinSignature = pendingPinSignature
1870
+ if (previousFocus instanceof HTMLElement && document.contains(previousFocus)) {
1871
+ try { previousFocus.focus({ preventScroll: true }) } catch { /* the element may be gone */ }
1872
+ }
1873
+ // React may re-add a row right after the menu closes; one reconciliation
1874
+ // pass catches that without a permanent polling timer.
1875
+ window.setTimeout(() => {
1876
+ if (detectLeakedMember()) {
1877
+ pinSyncAttempts = 0
1878
+ requestPinSync(80)
1879
+ }
1880
+ }, 150)
1881
+ }, 0)
1882
+ }
1883
+
1884
+ const maybeSyncPins = () => {
1885
+ if (store.getSnapshot().folders.length === 0) return
1886
+ const signature = pinSignature()
1887
+ if (signature === lastPinSignature) return
1888
+ pendingPinSignature = signature
1889
+ pinSyncAttempts = 0
1890
+ requestPinSync()
1891
+ }
1892
+
1893
+ const runtime = {
1894
+ subscribe: store.subscribe,
1895
+ getSnapshot: store.getSnapshot,
1896
+ uiSubscribe: uiStore.subscribe,
1897
+ uiGetSnapshot: uiStore.getSnapshot,
1898
+ consumeAutoSync() {
1899
+ const pending = autoSyncPending
1900
+ autoSyncPending = false
1901
+ return pending
1902
+ },
1903
+ openPanel: (id) => ctx.layout.selectPanel(id),
1904
+ toggleFolder(folderId) {
1905
+ if (typeof folderId !== 'string' || folderId === '') return
1906
+ const current = uiStore.getSnapshot()
1907
+ uiStore.set({ ...current, expandedFolderId: current.expandedFolderId === folderId ? null : folderId })
1908
+ },
1909
+ closeFolder() {
1910
+ const current = uiStore.getSnapshot()
1911
+ if (current.expandedFolderId !== null) uiStore.set({ ...current, expandedFolderId: null })
1912
+ },
1913
+ toggleHeaderFolder(folderId) {
1914
+ if (typeof folderId !== 'string' || folderId === '') return
1915
+ const current = uiStore.getSnapshot()
1916
+ uiStore.set({ ...current, headerFolderId: current.headerFolderId === folderId ? null : folderId })
1917
+ },
1918
+ closeHeaderFolder() {
1919
+ const current = uiStore.getSnapshot()
1920
+ if (current.headerFolderId !== null) uiStore.set({ ...current, headerFolderId: null })
1921
+ },
1922
+ createFolder(name) {
1923
+ const base = typeof name === 'string' ? name.trim() : ''
1924
+ if (base === '') return
1925
+ const folder = {
1926
+ id: 'f' + Date.now().toString(36) + Math.random().toString(36).slice(2, 7),
1927
+ name: base.slice(0, 40),
1928
+ panelIds: [],
1929
+ }
1930
+ commit([...store.getSnapshot().folders, folder])
1931
+ },
1932
+ renameFolder(id, name) {
1933
+ const base = typeof name === 'string' ? name.trim() : ''
1934
+ if (base === '') return
1935
+ commit(store.getSnapshot().folders.map((folder) => (
1936
+ folder.id === id ? { ...folder, name: base.slice(0, 40) } : folder
1937
+ )))
1938
+ },
1939
+ deleteFolder(id) {
1940
+ const current = uiStore.getSnapshot()
1941
+ if (current.expandedFolderId === id || current.headerFolderId === id) {
1942
+ uiStore.set({
1943
+ ...current,
1944
+ expandedFolderId: current.expandedFolderId === id ? null : current.expandedFolderId,
1945
+ headerFolderId: current.headerFolderId === id ? null : current.headerFolderId,
1946
+ })
1947
+ }
1948
+ commit(store.getSnapshot().folders.filter((folder) => folder.id !== id))
1949
+ },
1950
+ moveFolder(id, delta) {
1951
+ const folders = [...store.getSnapshot().folders]
1952
+ const from = folders.findIndex((folder) => folder.id === id)
1953
+ const to = from + delta
1954
+ if (from < 0 || to < 0 || to >= folders.length) return
1955
+ const [moved] = folders.splice(from, 1)
1956
+ folders.splice(to, 0, moved)
1957
+ commit(folders)
1958
+ },
1959
+ movePanel(folderId, panelId, delta) {
1960
+ const folders = store.getSnapshot().folders.map((folder) => {
1961
+ if (folder.id !== folderId) return folder
1962
+ const ids = [...folder.panelIds]
1963
+ const from = ids.indexOf(panelId)
1964
+ const to = from + delta
1965
+ if (from < 0 || to < 0 || to >= ids.length) return folder
1966
+ ids.splice(from, 1)
1967
+ ids.splice(to, 0, panelId)
1968
+ return { ...folder, panelIds: ids }
1969
+ })
1970
+ commit(folders)
1971
+ },
1972
+ assignPanel(panelId, folderId) {
1973
+ const folders = store.getSnapshot().folders.map((folder) => (
1974
+ { ...folder, panelIds: folder.panelIds.filter((id) => id !== panelId) }
1975
+ ))
1976
+ const index = folders.findIndex((folder) => folder.id === folderId)
1977
+ if (index >= 0) folders[index] = { ...folders[index], panelIds: [...folders[index].panelIds, panelId] }
1978
+ commit(folders)
1979
+ },
1980
+ unassignPanel(panelId) {
1981
+ commit(store.getSnapshot().folders.map((folder) => (
1982
+ folder.panelIds.includes(panelId)
1983
+ ? { ...folder, panelIds: folder.panelIds.filter((id) => id !== panelId) }
1984
+ : folder
1985
+ )))
1986
+ },
1987
+ }
1988
+
1989
+ /** Translate a folder key through the live folder translator. */
1990
+ const menuT = (key, vars) => tMenu(key, vars)
1991
+
1992
+ ctx.effect(() => {
1993
+ refreshPanels()
1994
+ const offPanels = ctx.slots.subscribe('sidebar.panellist', refreshPanels)
1995
+ const offLocale = ctx.locale.subscribe(refreshPanels)
1996
+ return () => {
1997
+ offPanels()
1998
+ offLocale()
1999
+ }
2000
+ }, 'feature-tweaks: menu index')
2001
+
2002
+ // Deleted sessions the Host still holds live come back after every reload.
2003
+ // Their rows are suppressed with a stylesheet (the sidebar stamps every
2004
+ // session row with data-row-key="session:<id>"), together with the
2005
+ // "Ungrouped" header when nothing else is left under it. The Host is
2006
+ // polled fast right after activation and on every sidebar mutation, and
2007
+ // the answer is mirrored to localStorage so the next page load hides the
2008
+ // rows before the Host replies.
2009
+ ctx.effect(() => {
2010
+ let disposed = false
2011
+ let lastIds = []
2012
+ let lastRules = null
2013
+ let applyTimer
2014
+ const apply = () => {
2015
+ if (disposed) return
2016
+ const rules = ghostRules(lastIds)
2017
+ if (rules === lastRules) return
2018
+ lastRules = rules
2019
+ writeGhostRules(rules)
2020
+ }
2021
+ const scheduleApply = () => {
2022
+ if (applyTimer !== undefined) return
2023
+ applyTimer = window.setTimeout(() => {
2024
+ applyTimer = undefined
2025
+ apply()
2026
+ }, 80)
2027
+ }
2028
+ const poll = async () => {
2029
+ try {
2030
+ const response = await fetch(apiUrl('ghosts'), { cache: 'no-store' })
2031
+ const data = await response.json()
2032
+ const ids = Array.isArray(data?.ghosts)
2033
+ ? data.ghosts.filter((id) => typeof id === 'string' && GHOST_ID_RE.test(id))
2034
+ : []
2035
+ lastIds = ids
2036
+ try { localStorage.setItem(GHOST_CACHE_KEY, JSON.stringify({ ids, at: Date.now() })) } catch { /* private mode */ }
2037
+ apply()
2038
+ return true
2039
+ } catch {
2040
+ // Keep the previous ids when the Host is unreachable.
2041
+ return false
2042
+ }
2043
+ }
2044
+ // The first moments after activation are the ones that flash a stale
2045
+ // row, so retry quickly until the Host answers at least once.
2046
+ let warmupAttempts = 0
2047
+ const warmup = () => {
2048
+ if (disposed) return
2049
+ void poll().then((answered) => {
2050
+ if (answered || disposed) return
2051
+ warmupAttempts += 1
2052
+ if (warmupAttempts < 8) window.setTimeout(warmup, 350)
2053
+ })
2054
+ }
2055
+ warmup()
2056
+ const timer = window.setInterval(() => { void poll() }, 2000)
2057
+ const onFocus = () => { void poll() }
2058
+ window.addEventListener('focus', onFocus)
2059
+ // A rendered row or a fresh group header re-applies the cached rules
2060
+ // immediately instead of waiting for the next poll; a change inside the
2061
+ // session tree also re-asks the Host, so a deletion reaches the cache
2062
+ // before a reload could paint the row from it.
2063
+ let pollTimer
2064
+ const schedulePoll = () => {
2065
+ if (pollTimer !== undefined) return
2066
+ pollTimer = window.setTimeout(() => {
2067
+ pollTimer = undefined
2068
+ void poll()
2069
+ }, 250)
2070
+ }
2071
+ const observer = new MutationObserver((records) => {
2072
+ scheduleApply()
2073
+ const tree = document.querySelector('[role="tree"]')
2074
+ if (tree === null) return
2075
+ for (const record of records) {
2076
+ const target = record.target
2077
+ if (target instanceof Node && (target === tree || tree.contains(target))) {
2078
+ schedulePoll()
2079
+ break
2080
+ }
2081
+ }
2082
+ })
2083
+ try { observer.observe(document.body, { childList: true, subtree: true }) } catch { /* no observer */ }
2084
+ return () => {
2085
+ disposed = true
2086
+ window.clearInterval(timer)
2087
+ window.removeEventListener('focus', onFocus)
2088
+ if (applyTimer !== undefined) window.clearTimeout(applyTimer)
2089
+ if (pollTimer !== undefined) window.clearTimeout(pollTimer)
2090
+ try { observer.disconnect() } catch { /* no observer */ }
2091
+ try { writeGhostRules('') } catch { /* the page is going away */ }
2092
+ }
2093
+ }, 'feature-tweaks: hide ghost session rows')
2094
+
2095
+ // Inline dropdown behaviour: a click on a top-menu folder row expands
2096
+ // that folder's entries below it instead of selecting a main panel. The
2097
+ // shipped row is a button, so interception happens in the capture phase
2098
+ // before React's root listener receives the click.
2099
+ ctx.effect(() => {
2100
+ /** Find the folder marker inside the row that contains the target. */
2101
+ const folderMarkerFor = (target) => {
2102
+ if (!(target instanceof Element)) return null
2103
+ if (target.closest('[data-sfb-popover="1"]') !== null) return null
2104
+ const glyph = target.closest('[data-sfb-row]')
2105
+ if (glyph !== null) return glyph
2106
+ const rowButton = target.closest('button')
2107
+ if (rowButton === null) return null
2108
+ return rowButton.querySelector('[data-sfb-row]')
2109
+ }
2110
+ const onPointerDown = (event) => {
2111
+ const target = event.target
2112
+ if (!(target instanceof Element)) return
2113
+ if (target.closest('[data-sfb-popover="1"]') !== null) return
2114
+ if (target.closest('[data-sfb-header-folder]') !== null) {
2115
+ // The chip's own click toggles it; only the inline dropdown closes.
2116
+ runtime.closeFolder()
2117
+ return
2118
+ }
2119
+ const marker = folderMarkerFor(target)
2120
+ if (marker !== null) {
2121
+ event.preventDefault()
2122
+ event.stopPropagation()
2123
+ runtime.toggleFolder(marker.getAttribute('data-sfb-row'))
2124
+ return
2125
+ }
2126
+ runtime.closeFolder()
2127
+ runtime.closeHeaderFolder()
2128
+ }
2129
+ // A cancelled pointerdown does not reliably cancel the click Chrome
2130
+ // fires for a mouse button, so the same row is also filtered here:
2131
+ // the shipped row must never select a main panel for a folder row.
2132
+ const onClick = (event) => {
2133
+ const marker = folderMarkerFor(event.target)
2134
+ if (marker === null) return
2135
+ event.preventDefault()
2136
+ event.stopPropagation()
2137
+ if (event.detail === 0) runtime.toggleFolder(marker.getAttribute('data-sfb-row'))
2138
+ }
2139
+ const onKeyDown = (event) => {
2140
+ if (event.key === 'Escape') {
2141
+ runtime.closeFolder()
2142
+ runtime.closeHeaderFolder()
2143
+ }
2144
+ }
2145
+ document.addEventListener('pointerdown', onPointerDown, true)
2146
+ document.addEventListener('click', onClick, true)
2147
+ document.addEventListener('keydown', onKeyDown)
2148
+ return () => {
2149
+ document.removeEventListener('pointerdown', onPointerDown, true)
2150
+ document.removeEventListener('click', onClick, true)
2151
+ document.removeEventListener('keydown', onKeyDown)
2152
+ }
2153
+ }, 'feature-tweaks: inline folder dropdown')
2154
+
2155
+ ctx.effect(() => {
2156
+ let disposed = false
2157
+ const readLocal = () => {
2158
+ try {
2159
+ const raw = readLocalMirror(LOCAL_KEY, LEGACY_LOCAL_KEY)
2160
+ if (raw === null) return []
2161
+ return normalizeState(JSON.parse(raw))
2162
+ } catch {
2163
+ return []
2164
+ }
2165
+ }
2166
+ const load = async () => {
2167
+ let folders = []
2168
+ let migrate = false
2169
+ try {
2170
+ const response = await fetch(apiUrl('state'), { cache: 'no-store' })
2171
+ if (!response.ok) throw new Error('HTTP ' + response.status)
2172
+ const data = await response.json()
2173
+ folders = normalizeState(data)
2174
+ if (folders.length === 0) {
2175
+ const local = readLocal()
2176
+ if (local.length > 0) {
2177
+ folders = local
2178
+ migrate = true
2179
+ }
2180
+ }
2181
+ } catch (error) {
2182
+ reportDiag('state-fetch-failed: ' + errorText(error))
2183
+ folders = readLocal()
2184
+ }
2185
+ if (disposed) return
2186
+ update({ folders })
2187
+ if (migrate) persist()
2188
+ }
2189
+ void load()
2190
+ return () => {
2191
+ disposed = true
2192
+ if (saveTimer !== undefined) window.clearTimeout(saveTimer)
2193
+ }
2194
+ }, 'feature-tweaks: state load')
2195
+
2196
+ // Top-menu folder rows: one registration pair (the sidebar row plus the
2197
+ // main page it opens) per folder, rebuilt whenever ids or names change.
2198
+ const folderRegistrations = new Map()
2199
+ let folderSignature = ''
2200
+ const disposeFolderRegistrations = () => {
2201
+ for (const disposes of folderRegistrations.values()) {
2202
+ for (const dispose of disposes) {
2203
+ try { dispose() } catch (error) { reportDiag('dispose-failed: ' + errorText(error)) }
2204
+ }
2205
+ }
2206
+ folderRegistrations.clear()
2207
+ }
2208
+ // One header row for every folder (chips are ordered by the folder list).
2209
+ let headerBarDispose = null
2210
+ const disposeHeaderBar = () => {
2211
+ if (headerBarDispose === null) return
2212
+ const dispose = headerBarDispose
2213
+ headerBarDispose = null
2214
+ try { dispose() } catch (error) { reportDiag('header-bar-dispose-failed: ' + errorText(error)) }
2215
+ }
2216
+ const syncHeaderBar = (folders) => {
2217
+ if (folders.length === 0) {
2218
+ disposeHeaderBar()
2219
+ return
2220
+ }
2221
+ if (headerBarDispose !== null) return
2222
+ try {
2223
+ headerBarDispose = ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({
2224
+ name: 'conversation.session.header.utilities',
2225
+ id: 'menu-folders-header-bar',
2226
+ order: 100,
2227
+ locale: NS_MENU,
2228
+ inject: () => ({ runtime }),
2229
+ }, HeaderFoldersBar))
2230
+ } catch (error) {
2231
+ reportDiag('folder-header-failed: ' + errorText(error))
2232
+ }
2233
+ }
2234
+ const syncFolderMenus = () => {
2235
+ const folders = store.getSnapshot().folders
2236
+ const signature = folders.map((folder) => folder.id + '\u0000' + folder.name).join('\u0001')
2237
+ if (signature === folderSignature) return
2238
+ folderSignature = signature
2239
+ disposeFolderRegistrations()
2240
+ folders.forEach((folder, index) => {
2241
+ const panelId = FOLDER_PANEL_PREFIX + folder.id
2242
+ const disposes = []
2243
+ try {
2244
+ disposes.push(ctx.slots.register({
2245
+ name: 'sidebar.panellist',
2246
+ id: panelId,
2247
+ order: 100 + index,
2248
+ label: folder.name,
2249
+ locale: NS_MENU,
2250
+ inject: () => ({ runtime, folderId: folder.id }),
2251
+ }, FolderRowIcon))
2252
+ } catch (error) {
2253
+ reportDiag('folder-row-failed: ' + errorText(error))
2254
+ }
2255
+ try {
2256
+ disposes.push(ctx.slots.register({
2257
+ name: 'main',
2258
+ key: panelId,
2259
+ locale: NS_MENU,
2260
+ inject: () => ({ runtime, folderId: folder.id }),
2261
+ }, FolderPage))
2262
+ } catch (error) {
2263
+ reportDiag('folder-page-failed: ' + errorText(error))
2264
+ }
2265
+ folderRegistrations.set(folder.id, disposes)
2266
+ })
2267
+ syncHeaderBar(folders)
2268
+ }
2269
+ ctx.effect(() => {
2270
+ syncFolderMenus()
2271
+ maybeSyncPins()
2272
+ const off = store.subscribe(() => {
2273
+ syncFolderMenus()
2274
+ maybeSyncPins()
2275
+ })
2276
+ return () => {
2277
+ off()
2278
+ if (pinSyncTimer !== undefined) window.clearTimeout(pinSyncTimer)
2279
+ if (pinSyncRetryTimer !== undefined) window.clearTimeout(pinSyncRetryTimer)
2280
+ disposeHeaderBar()
2281
+ disposeFolderRegistrations()
2282
+ }
2283
+ }, 'feature-tweaks: top-menu folder rows')
2284
+
2285
+ // A folder member must never stay on the top menu: watch the sidebar DOM
2286
+ // and repair a leaked row even when its plugin registered (or was manually
2287
+ // pinned back) long after the signature-based sync.
2288
+ ctx.effect(() => {
2289
+ let disposed = false
2290
+ let reconcileTimer
2291
+ const reconcile = () => {
2292
+ reconcileTimer = undefined
2293
+ if (disposed) return
2294
+ if (store.getSnapshot().folders.length === 0) return
2295
+ if (pinSyncBusy) {
2296
+ scheduleReconcile()
2297
+ return
2298
+ }
2299
+ if (detectLeakedMember()) {
2300
+ pinSyncAttempts = 0
2301
+ requestPinSync()
2302
+ }
2303
+ }
2304
+ const scheduleReconcile = () => {
2305
+ if (disposed || reconcileTimer !== undefined) return
2306
+ reconcileTimer = window.setTimeout(reconcile, 250)
2307
+ }
2308
+ let observer = null
2309
+ try {
2310
+ observer = new MutationObserver(scheduleReconcile)
2311
+ observer.observe(document.body, { childList: true, subtree: true })
2312
+ } catch {
2313
+ observer = null
2314
+ }
2315
+ window.addEventListener('focus', scheduleReconcile)
2316
+ scheduleReconcile()
2317
+ return () => {
2318
+ disposed = true
2319
+ if (reconcileTimer !== undefined) window.clearTimeout(reconcileTimer)
2320
+ if (observer !== null) {
2321
+ try { observer.disconnect() } catch { /* already disconnected */ }
2322
+ }
2323
+ window.removeEventListener('focus', scheduleReconcile)
2324
+ }
2325
+ }, 'feature-tweaks: folder members stay out of the top menu')
2326
+
2327
+ // Collected entries leave the top menu by unpinning, and DSH lists every
2328
+ // unpinned entry inside the sidebar's More menu. This pass removes those
2329
+ // rows from that menu too, so a folder is the only launcher a collected
2330
+ // entry has. It runs synchronously from a microtask right after the menu
2331
+ // is rendered (before paint, so no row flashes) and again whenever the
2332
+ // folder set or the setting changes, which restores an already open menu.
2333
+ ctx.effect(() => {
2334
+ let disposed = false
2335
+ let queued = false
2336
+ const apply = () => {
2337
+ queued = false
2338
+ if (disposed) return
2339
+ try {
2340
+ hideCollectedInMoreMenu()
2341
+ } catch (error) {
2342
+ reportDiag('more-hide-failed: ' + errorText(error))
2343
+ }
2344
+ }
2345
+ const schedule = () => {
2346
+ if (disposed || queued) return
2347
+ queued = true
2348
+ void Promise.resolve().then(apply)
2349
+ }
2350
+ let observer = null
2351
+ try {
2352
+ observer = new MutationObserver(schedule)
2353
+ observer.observe(document.body, { childList: true, subtree: true })
2354
+ } catch {
2355
+ observer = null
2356
+ }
2357
+ const offStore = store.subscribe(schedule)
2358
+ window.addEventListener('focus', schedule)
2359
+ schedule()
2360
+ return () => {
2361
+ disposed = true
2362
+ offStore()
2363
+ window.removeEventListener('focus', schedule)
2364
+ if (observer !== null) {
2365
+ try { observer.disconnect() } catch { /* already disconnected */ }
2366
+ }
2367
+ }
2368
+ }, 'feature-tweaks: collected entries stay out of the More menu')
2369
+
2370
+ /** Register one contribution; a failure is reported and never thrown. */
2371
+ const contribute = (slot, label, build) => {
2372
+ try {
2373
+ ctx.effect(() => ctx.slots.inject(slot, () => {
2374
+ try {
2375
+ return build()
2376
+ } catch (error) {
2377
+ reportDiag('register-failed ' + slot + ': ' + errorText(error))
2378
+ return () => {}
2379
+ }
2380
+ }), 'feature-tweaks: ' + label)
2381
+ } catch (error) {
2382
+ reportDiag('inject-failed ' + slot + ': ' + errorText(error))
2383
+ }
2384
+ }
2385
+
2386
+ // The single left-menu entry: its icon row plus the main page with the two
2387
+ // tabs. The folder manager lives inside that page, not in Settings.
2388
+ contribute('sidebar.panellist', 'sidebar entry', () => ctx.slots.register({
2389
+ name: 'sidebar.panellist',
2390
+ id: HUB_PANEL_ID,
2391
+ order: 49,
2392
+ label: () => t('page.title'),
2393
+ locale: NS,
2394
+ }, HubEntryIcon))
2395
+
2396
+ contribute('main', 'hub page', () => ctx.slots.register({
2397
+ name: 'main',
2398
+ key: HUB_PANEL_ID,
2399
+ locale: NS,
2400
+ inject: () => ({ runtime, menuT }),
2401
+ }, HubPage))
2402
+
2403
+ contribute('sidebar.panellist.actions', 'more menu', () => ctx.slots.register({
2404
+ name: 'sidebar.panellist.actions',
2405
+ id: 'menu-folders-menu',
2406
+ order: -10,
2407
+ locale: NS_MENU,
2408
+ inject: () => ({ runtime }),
2409
+ }, MoreMenuContent))
2410
+
2411
+ reportDiag('apply-ok v' + VERSION)
2412
+ }
2413
+
2414
+ return {
2415
+ name: '@leiyi-works/dsh-feature-tweaks',
2416
+ inject: ['slots', 'layout', 'locale'],
2417
+ apply(ctx) {
2418
+ try {
2419
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'feature-tweaks: dictionaries')
2420
+ ctx.effect(() => ctx.locale.register(NS_MENU, { zh: zhMenu, en: enMenu }), 'feature-tweaks: folder dictionaries')
2421
+ } catch (error) {
2422
+ reportDiag('locale-register-failed: ' + errorText(error))
2423
+ }
2424
+ try {
2425
+ t = ctx.locale.bind(NS)
2426
+ tMenu = ctx.locale.bind(NS_MENU)
2427
+ } catch (error) {
2428
+ reportDiag('locale-bind-failed: ' + errorText(error))
2429
+ }
2430
+ try {
2431
+ applyFeatures(ctx)
2432
+ } catch (error) {
2433
+ reportDiag('feature-apply-crash: ' + errorText(error))
2434
+ }
2435
+ try {
2436
+ applyFolders(ctx)
2437
+ } catch (error) {
2438
+ reportDiag('folder-apply-crash: ' + errorText(error))
2439
+ }
187
2440
  },
188
2441
  }
189
2442
  },