@leiyi-works/dsh-feature-tweaks 0.4.0 → 0.6.0

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