@muou000/dsh-wsl 0.0.0-stage → 0.1.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/wsl.js ADDED
@@ -0,0 +1,691 @@
1
+ // Adapted from dsh-wsl-folder v1.1.1, MIT (copyright 2026 lvyuxin).
2
+ // Composed with the SSH workspace manager by scripts/build-client.mjs.
3
+ export function createWslClient(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const NS = 'dshSshWsl'
7
+ const ROUTE = 'api/dsh-ssh/wsl'
8
+ const HOLES = ['sidebar.workspaces.directoryFlow', 'conversation.hero.workspace.directoryFlow', 'workspace.picker.directoryFlow']
9
+ const RECENT_KEY = 'dsh-ssh.wsl.recent'
10
+ const DISTRO_KEY = 'dsh-ssh.wsl.distro'
11
+
12
+ const zh = {
13
+ title: '添加工作区',
14
+ chooseHint: '要添加的文件夹在哪里?',
15
+ windows: 'Windows 文件夹',
16
+ windowsDesc: '选择 Windows 主机上的目录',
17
+ newFolder: '新建文件夹',
18
+ folderName: '文件夹名称',
19
+ wsl: 'WSL 文件夹',
20
+ wslDesc: '浏览 WSL 发行版中的 Linux 目录',
21
+ recent: '最近的 WSL 位置',
22
+ wslTitle: '选择 WSL 目录',
23
+ distro: '发行版',
24
+ editPath: '编辑路径',
25
+ back: '返回',
26
+ showHidden: '显示隐藏文件',
27
+ loading: '加载中…',
28
+ empty: '没有子文件夹',
29
+ truncated: '文件夹过多,仅显示前 {count} 个。',
30
+ noDistro: '没有找到 WSL 发行版。请先在 Windows 中安装 WSL。',
31
+ cancel: '取消',
32
+ close: '关闭',
33
+ open: '打开',
34
+ adding: '正在添加…',
35
+ tipTitle: '使用提示',
36
+ tipTerminal: 'WSL 工作区里打开的侧栏终端会直接进入发行版,起始目录就是工作区。',
37
+ tipAgent: 'agent 通过 \\\\wsl.localhost 共享读写文件;需要 Linux 命令时让它调用 wsl.exe。',
38
+ browseHint: '点文件夹进入下一级,点铅笔可直接输入路径,选好后点「打开」。',
39
+ 'error.not-found': '目录不存在',
40
+ 'error.denied': '没有权限读取这个目录',
41
+ 'error.unreadable': '无法读取这个目录',
42
+ 'error.wsl-failed': '调用 wsl.exe 失败',
43
+ 'error.unsupported': 'Host 不是 Windows,无法使用 WSL',
44
+ 'error.network': '无法连接到插件的 Host 路由',
45
+ 'error.generic': '出错了',
46
+ }
47
+ const en = {
48
+ title: 'Add workspace',
49
+ chooseHint: 'Where is the folder you want to add?',
50
+ windows: 'Windows folder',
51
+ windowsDesc: 'Choose a directory on the Windows host',
52
+ newFolder: 'New folder',
53
+ folderName: 'Folder name',
54
+ wsl: 'WSL folder',
55
+ wslDesc: 'Browse Linux directories in a WSL distribution',
56
+ recent: 'Recent WSL locations',
57
+ wslTitle: 'Select WSL directory',
58
+ distro: 'Distribution',
59
+ editPath: 'Edit path',
60
+ back: 'Back',
61
+ showHidden: 'Show hidden files',
62
+ loading: 'Loading…',
63
+ empty: 'No subfolders',
64
+ truncated: 'Too many folders; only the first {count} are shown.',
65
+ noDistro: 'No WSL distribution found. Install WSL on Windows first.',
66
+ cancel: 'Cancel',
67
+ close: 'Close',
68
+ open: 'Open',
69
+ adding: 'Adding…',
70
+ tipTitle: 'Tips',
71
+ tipTerminal: 'Sidebar terminals in a WSL workspace open inside the distribution, starting in the workspace.',
72
+ tipAgent: 'The agent reads and writes files through the \\\\wsl.localhost share; ask it to call wsl.exe for Linux commands.',
73
+ browseHint: 'Click a folder to enter it, or the pencil to type a path, then click Open.',
74
+ 'error.not-found': 'The directory does not exist',
75
+ 'error.denied': 'Permission denied',
76
+ 'error.unreadable': 'The directory cannot be read',
77
+ 'error.wsl-failed': 'wsl.exe failed',
78
+ 'error.unsupported': 'The Host is not Windows; WSL is unavailable',
79
+ 'error.network': 'Cannot reach the plugin\'s Host routes',
80
+ 'error.generic': 'Something went wrong',
81
+ }
82
+
83
+ // Copied from DSH's Modal / Button / Menu primitives and its directory browser dialog.
84
+ const CSS = `
85
+ .dwf-root{pointer-events:auto;position:fixed;inset:0;z-index:1000;display:flex;align-items:center;justify-content:center;padding:max(24px,var(--dsh-frame-overlay-top,24px)) 24px}
86
+ .dwf-mask{position:absolute;inset:var(--dsh-frame-chrome-top,0px) 0 0;backdrop-filter:var(--dsw-mask-blur)}
87
+ .dwf-mask:after{content:"";position:absolute;inset:0;background:var(--dsw-alias-bg-mask-1);animation:dwf-enter var(--ds-transition-duration,.2s) var(--ds-ease-in-out,ease-in-out)}
88
+ .dwf-dialog{box-sizing:border-box;position:relative;z-index:1;display:flex;flex-direction:column;gap:0;width:min(380px,100%);padding:0;overflow:hidden;border:0;border-radius:var(--dsw-radius-panel);background:var(--dsw-alias-bg-layer-2);box-shadow:var(--dsw-elevation-prominent);animation:dwf-enter var(--ds-transition-duration,.2s) var(--ds-ease-in-out,ease-in-out)}
89
+ .dwf-dialog:focus{outline:none}
90
+ @keyframes dwf-enter{0%{opacity:0}to{opacity:1}}
91
+ @media(prefers-reduced-motion:reduce){.dwf-mask:after,.dwf-dialog{animation:none}}
92
+ .dwf-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:22px 14px 4px 24px}
93
+ .dwf-title{flex:1;min-width:0;margin:0;font-size:16px;line-height:24px;font-weight:510;color:var(--dsw-alias-label-primary)}
94
+ .dwf-iconbtn{flex:none;display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:none;border-radius:var(--dsw-radius-sm);background:transparent;cursor:pointer;color:var(--dsw-alias-label-secondary)}
95
+ .dwf-iconbtn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
96
+ .dwf-iconbtn:disabled{opacity:.4;cursor:not-allowed}
97
+ .dwf-iconbtn:focus-visible,.dwf-item:focus-visible,.dwf-row:focus-visible,.dwf-crumb:focus-visible,.dwf-btn:focus-visible,.dwf-select:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:-2px}
98
+ .dwf-desc{margin:0;padding:0 24px;font-size:14px;line-height:22px;color:var(--dsw-alias-label-secondary)}
99
+ .dwf-menu{display:flex;flex-direction:column;padding:12px 16px 12px}
100
+ .dwf-item{display:flex;align-items:center;gap:10px;width:100%;min-height:34px;padding:8px;border:none;border-radius:var(--dsw-radius-md);background:transparent;cursor:pointer;font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary);text-align:left}
101
+ .dwf-item:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
102
+ .dwf-item:disabled{opacity:.4;cursor:not-allowed}
103
+ .dwf-item-icon{display:inline-flex;flex:none;width:20px;height:20px;align-items:center;justify-content:center;color:var(--dsw-alias-menu-icon,var(--dsw-alias-label-secondary))}
104
+ .dwf-item-text{display:flex;flex-direction:column;min-width:0;flex:1}
105
+ .dwf-item-title{font-size:14px;line-height:22px;font-weight:500}
106
+ .dwf-item-sub,.dwf-item-mono{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
107
+ .dwf-item-mono{font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary)}
108
+ .dwf-item-tag{flex:none;font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary)}
109
+ .dwf-label{padding:6px 8px;margin-top:4px;font-size:11px;line-height:15px;color:var(--dsw-alias-label-tertiary)}
110
+ .dwf-sep{height:.5px;margin:3px 2px;background:var(--dsw-alias-border-l2)}
111
+ .dwf-tip{display:flex;gap:8px;margin:0 24px 20px;padding:10px 12px;border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px}
112
+ .dwf-tip-icon{flex:none;display:inline-flex;margin-top:1px;color:var(--dsw-alias-label-tertiary)}
113
+ .dwf-tip-body{display:flex;flex-direction:column;gap:2px;min-width:0}
114
+ .dwf-tip-title{font-weight:500;color:var(--dsw-alias-label-primary)}
115
+ .dwf-hint{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
116
+ .dwf-error{padding:4px 8px;font-size:12px;line-height:18px;color:var(--dsw-alias-state-error-primary);word-break:break-word}
117
+ .dwf-browser{width:min(680px,100%);height:min(500px,100dvh - 32px);--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2);--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2)}
118
+ .dwf-bhead{border-bottom:.5px solid var(--dsw-alias-border-l3);display:flex;flex-direction:column;flex:none;gap:8px;padding:16px 14px 8px 24px}
119
+ .dwf-titlerow{display:flex;align-items:center;gap:8px;min-height:28px}
120
+ .dwf-titlerow .dwf-iconbtn{margin-left:-8px}
121
+ .dwf-select{box-sizing:border-box;height:28px;max-width:220px;padding:0 8px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-sm);background:transparent;color:var(--dsw-alias-label-primary);font-size:12px;line-height:18px;cursor:pointer;outline:none}
122
+ .dwf-select option{background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}
123
+ .dwf-crumbbar{box-sizing:border-box;border-radius:var(--dsw-radius-sm);border:1px solid transparent;display:flex;align-items:center;gap:4px;min-height:24px;margin-left:-9px;padding:0 8px}
124
+ .dwf-crumbbar:has(.dwf-editzone:enabled:hover),.dwf-crumbbar:has(.dwf-editzone:focus-visible),.dwf-crumbbar:has(.dwf-pathinput){border-color:var(--dsw-alias-border-l2)}
125
+ .dwf-trail{scrollbar-width:none;flex:0 1 auto;display:flex;align-items:center;gap:4px;min-width:0;overflow-x:auto}
126
+ .dwf-crumbseat{flex:none;display:inline-flex;align-items:center;gap:4px;min-width:0}
127
+ .dwf-crumb{text-overflow:ellipsis;white-space:nowrap;max-width:160px;color:var(--dsw-alias-label-tertiary);cursor:pointer;background:none;border:none;padding:0;font-size:13px;font-weight:500;line-height:20px;overflow:hidden}
128
+ .dwf-crumb:hover{color:var(--dsw-alias-label-primary)}
129
+ .dwf-crumb-last{color:var(--dsw-alias-label-primary)}
130
+ .dwf-chev{color:var(--dsw-alias-label-tertiary);flex:none}
131
+ .dwf-editzone{cursor:text;background:none;border:none;outline:none;flex:1 0 34px;display:flex;justify-content:flex-end;align-items:center;min-width:34px;height:22px;padding:0;color:var(--dsw-alias-label-tertiary)}
132
+ .dwf-editzone:enabled:hover,.dwf-editzone:focus-visible{color:var(--dsw-alias-label-primary)}
133
+ .dwf-editzone:disabled{cursor:default;color:var(--dsw-alias-label-caption)}
134
+ .dwf-pathinput{box-sizing:border-box;flex:1 1 0;min-width:0;height:22px;padding:0;border:none;outline:none;background:none;color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px}
135
+ .dwf-content{display:flex;flex-direction:column;flex:1 1 0;min-height:0;padding:16px 16px 16px 24px;position:relative}
136
+ .dwf-column{display:flex;flex-direction:column;flex:1 1 0;gap:2px;min-height:0;padding-right:8px;overflow-y:auto}
137
+ .dwf-row{border-radius:var(--dsw-radius-sm);text-align:left;cursor:pointer;background:none;border:none;flex:none;display:flex;align-items:center;gap:4px;width:100%;height:28px;padding:4px}
138
+ .dwf-row:hover{background:var(--dsw-alias-interactive-bg-hover)}
139
+ .dwf-row:disabled{cursor:default}
140
+ .dwf-row-icon{color:var(--dsw-alias-label-secondary);flex:none}
141
+ .dwf-row-name{text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1 1 0;color:var(--dsw-alias-label-primary);font-size:13px;font-weight:500;line-height:20px;overflow:hidden}
142
+ .dwf-row-hidden .dwf-row-name{color:var(--dsw-alias-label-secondary)}
143
+ .dwf-status{padding:4px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
144
+ .dwf-content .dwf-error{padding:4px}
145
+ .dwf-float{position:absolute;bottom:8px;right:16px;padding:2px 8px;background:var(--dsw-alias-bg-layer-2);font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
146
+ .dwf-foot{border-top:.5px solid var(--dsw-alias-border-l3);flex:none;display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:16px 24px}
147
+ .dwf-toggle{display:inline-flex;align-items:center;gap:4px;padding:0;border:none;background:none;cursor:pointer;white-space:nowrap;color:var(--dsw-alias-label-secondary);font-size:13px;font-weight:500;line-height:20px}
148
+ .dwf-toggle:hover{color:var(--dsw-alias-label-primary)}
149
+ .dwf-toggle[aria-pressed=true]{color:var(--dsw-alias-label-primary)}
150
+ .dwf-gap{flex:1 1 0}
151
+ .dwf-unc{flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
152
+ .dwf-btn{box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;gap:4px;height:36px;min-width:72px;padding:0 14px;border:none;border-radius:var(--dsw-radius-md);cursor:pointer;font-size:14px;line-height:22px;color:var(--dsw-alias-label-primary);background:transparent}
153
+ .dwf-btn:disabled{cursor:not-allowed;opacity:.4}
154
+ .dwf-btn-primary{background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}
155
+ .dwf-btn-primary:hover:not(:disabled){background:var(--dsw-alias-button-primary-hover)}
156
+ .dwf-btn-outline{border:.5px solid var(--dsw-alias-border-l3)}
157
+ .dwf-btn-outline:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
158
+ `
159
+
160
+ // ── glyphs (original artwork, 16px grid, currentColor) ─────────────────────────
161
+ const svg = (size, ...children) => h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true }, ...children)
162
+ const stroke = { stroke: 'currentColor', strokeWidth: 1.2, strokeLinecap: 'round', strokeLinejoin: 'round' }
163
+ const IconFolder = (size = 16) => svg(size, h('path', { d: 'M2 4.5A1.5 1.5 0 0 1 3.5 3h2.8l1.4 1.5h4.8A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z', ...stroke }))
164
+ const IconTerminal = (size = 16) => svg(size, h('rect', { x: 1.75, y: 2.75, width: 12.5, height: 10.5, rx: 2, ...stroke }), h('path', { d: 'M4.5 6.5 6.5 8l-2 1.5M8.5 10h3', ...stroke }))
165
+ const IconWindows = (size = 16) => svg(size, h('path', { d: 'M2.5 3.8 7 3.2v4.3H2.5zM8.2 3 13.5 2.3v5.2H8.2zM2.5 8.5H7v4.3l-4.5-.6zM8.2 8.5h5.3v5.2L8.2 13z', fill: 'currentColor' }))
166
+ const IconChevron = (size = 14) => svg(size, h('path', { d: 'm6 4 4 4-4 4', ...stroke }))
167
+ const IconBack = (size = 16) => svg(size, h('path', { d: 'm10 4-4 4 4 4', ...stroke }))
168
+ const IconClose = (size = 16) => svg(size, h('path', { d: 'm4 4 8 8M12 4l-8 8', ...stroke }))
169
+ const IconEdit = (size = 14) => svg(size, h('path', { d: 'M10.5 3.2 12.8 5.5 6 12.3 3.3 12.7 3.7 10z', ...stroke }))
170
+ const IconCheck = (size = 14) => svg(size, h('path', { d: 'm3.5 8.5 3 3 6-7', ...stroke }))
171
+ const IconInfo = (size = 14) => svg(size, h('circle', { cx: 8, cy: 8, r: 6, ...stroke }), h('path', { d: 'M8 7.2v3.6M8 5.2v.1', ...stroke }))
172
+ const IconClock = (size = 16) => svg(size, h('circle', { cx: 8, cy: 8, r: 5.75, ...stroke }), h('path', { d: 'M8 5v3.2l2 1.3', ...stroke }))
173
+
174
+ // ── small helpers ──────────────────────────────────────────────────────────────
175
+ function createStore() {
176
+ let state = null
177
+ const listeners = new Set()
178
+ return {
179
+ get: () => state,
180
+ set(next) { state = next; for (const listener of [...listeners]) listener() },
181
+ subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener) } },
182
+ }
183
+ }
184
+
185
+ function readJson(key, fallback) {
186
+ try {
187
+ const raw = globalThis.localStorage?.getItem(key)
188
+ return raw ? JSON.parse(raw) : fallback
189
+ } catch { return fallback }
190
+ }
191
+ function writeJson(key, value) {
192
+ try { globalThis.localStorage?.setItem(key, JSON.stringify(value)) } catch { /* storage unavailable */ }
193
+ }
194
+ function rememberRecent(entry) {
195
+ const stored = readJson(RECENT_KEY, [])
196
+ const list = (Array.isArray(stored) ? stored : [])
197
+ .filter((item) => item && typeof item.distro === 'string' && typeof item.path === 'string')
198
+ .filter((item) => !(item.distro === entry.distro && item.path === entry.path))
199
+ list.unshift({ distro: entry.distro, path: entry.path })
200
+ writeJson(RECENT_KEY, list.slice(0, 5))
201
+ writeJson(DISTRO_KEY, entry.distro)
202
+ }
203
+
204
+ async function getJson(route, params, signal) {
205
+ const query = new URLSearchParams(params || {}).toString()
206
+ return requestJson(`${ROUTE}/${route}${query ? `?${query}` : ''}`, { headers: { accept: 'application/json' }, signal })
207
+ }
208
+
209
+ function postJson(route, body, signal) {
210
+ return requestJson(`${ROUTE}/${route}`, {
211
+ method: 'POST',
212
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
213
+ body: JSON.stringify(body), signal,
214
+ })
215
+ }
216
+
217
+ async function requestJson(url, init) {
218
+ let response
219
+ try {
220
+ const send = globalThis.__DSH_TRANSPORT__?.fetch ?? ((url, init) => globalThis.fetch(url, init))
221
+ response = await send(url, init)
222
+ } catch (error) {
223
+ if (error && error.name === 'AbortError') throw error
224
+ throw Object.assign(new Error(String((error && error.message) || error)), { code: 'network' })
225
+ }
226
+ let body = null
227
+ try { body = await response.json() } catch { /* not JSON */ }
228
+ if (body === null || (!response.ok && !body.error)) throw Object.assign(new Error(`HTTP ${response.status}`), { code: 'network' })
229
+ if (body.error) throw Object.assign(new Error(body.message || body.error), { code: body.error })
230
+ return body
231
+ }
232
+
233
+ // Page-lifetime caches: reopening the dialog or stepping back lands instantly, and every
234
+ // cached view is revalidated in the background.
235
+ const cache = { distros: null, homes: new Map(), lists: new Map() }
236
+ const listKey = (distro, path) => `${distro}\u0000${path}`
237
+ function fetchDistros(signal) {
238
+ return getJson('distros', {}, signal).then((r) => { signal?.throwIfAborted(); cache.distros = Array.isArray(r.distros) ? r.distros : []; return cache.distros })
239
+ }
240
+ function fetchHome(distro, signal) {
241
+ // Always revalidate: a distribution's default user (and so its home) can change between runs.
242
+ return getJson('home', { distro }, signal).then((r) => { signal?.throwIfAborted(); const home = r.home || '/'; cache.homes.set(distro, home); return home })
243
+ }
244
+ function fetchList(distro, path, signal) {
245
+ return getJson('list', { distro, path }, signal).then((r) => { signal?.throwIfAborted(); cache.lists.set(listKey(distro, r.path), r); return r })
246
+ }
247
+ function preferredDistro(list) {
248
+ const remembered = readJson(DISTRO_KEY, '')
249
+ return (list.find((d) => d.name === remembered) || list.find((d) => d.default) || list[0])?.name ?? ''
250
+ }
251
+ function describeError(t, error) {
252
+ if (!error) return ''
253
+ const key = `error.${error.code || 'generic'}`
254
+ const label = t(key)
255
+ const head = label === key ? t('error.generic') : label
256
+ return error.message && error.message !== head ? `${head} — ${error.message}` : head
257
+ }
258
+
259
+ /** Escape closes; Tab stays inside the dialog. */
260
+ function useDialogKeys(ref, onEscape) {
261
+ return (event) => {
262
+ if (event.key === 'Escape') { event.stopPropagation(); event.preventDefault(); onEscape(); return }
263
+ if (event.key !== 'Tab' || ref.current === null) return
264
+ const focusables = [...ref.current.querySelectorAll('button:not(:disabled),select:not(:disabled),input:not(:disabled),[tabindex="0"]')]
265
+ if (focusables.length === 0) return
266
+ const first = focusables[0]
267
+ const last = focusables[focusables.length - 1]
268
+ const active = ref.current.ownerDocument.activeElement
269
+ if (event.shiftKey && (active === first || active === ref.current)) { event.preventDefault(); last.focus() }
270
+ else if (!event.shiftKey && active === last) { event.preventDefault(); first.focus() }
271
+ }
272
+ }
273
+
274
+ function Frame({ className, label, onDismiss, children, cardRef, onKeyDown }) {
275
+ return h('div', { className: 'dwf-root' },
276
+ h('div', { className: 'dwf-mask', onMouseDown: onDismiss }),
277
+ h('div', {
278
+ ref: cardRef, className: `dwf-dialog ${className || ''}`, role: 'dialog', 'aria-modal': true,
279
+ 'aria-label': label, tabIndex: -1, onKeyDown,
280
+ }, children))
281
+ }
282
+
283
+ // ── hole occupant: bridges the owner's flow conversation into the store ─────────
284
+ let requestSeq = 0
285
+ function FlowBridge(props) {
286
+ const { open, busy, store, hole } = props
287
+ const latest = React.useRef(props)
288
+ latest.current = props
289
+ const token = React.useRef(null)
290
+
291
+ React.useEffect(() => {
292
+ if (!open) {
293
+ if (token.current !== null && store.get()?.token === token.current) store.set(null)
294
+ token.current = null
295
+ return
296
+ }
297
+ if (token.current !== null) return
298
+ const mine = ++requestSeq
299
+ token.current = mine
300
+ // If the independently switchable Host row was disabled, drop this occupant. DSH's
301
+ // ordinary picker receives the still-open request and handles it as usual.
302
+ props.recheck().then(enabled => {
303
+ if (enabled && token.current === mine) store.set({ token: mine, hole, busy: !!latest.current.busy, owner: latest })
304
+ })
305
+ }, [open])
306
+
307
+ React.useEffect(() => {
308
+ const current = store.get()
309
+ if (current !== null && current.token === token.current && current.busy !== !!busy) store.set({ ...current, busy: !!busy })
310
+ }, [busy])
311
+
312
+ React.useEffect(() => () => {
313
+ if (token.current !== null && store.get()?.token === token.current) store.set(null)
314
+ token.current = null
315
+ }, [])
316
+ return null
317
+ }
318
+
319
+ // ── overlay ────────────────────────────────────────────────────────────────────
320
+ function PickerOverlay(props) {
321
+ const request = React.useSyncExternalStore(props.store.subscribe, props.store.get, props.store.get)
322
+ if (request === null) return null
323
+ return h(React.Fragment, null,
324
+ h('style', null, CSS),
325
+ h(PickerFlow, { key: request.token, request, t: props.tf, picker: props.picker }))
326
+ }
327
+
328
+ function PickerFlow({ request, t, picker, initialView = 'choose' }) {
329
+ const [view, setView] = React.useState(initialView)
330
+ const [nativeError, setNativeError] = React.useState(null)
331
+ const [picking, setPicking] = React.useState(false)
332
+ const [pickError, setPickError] = React.useState(null)
333
+ const lifetime = React.useRef(null)
334
+ React.useEffect(() => {
335
+ const controller = new AbortController()
336
+ lifetime.current = controller
337
+ return () => controller.abort()
338
+ }, [])
339
+ const owner = request.owner
340
+ const busy = request.owner.current.busy || request.busy || picking
341
+
342
+ const cancel = () => { if (!busy) owner.current.onCancel() }
343
+ const pickWindows = () => {
344
+ if (picker.kind === 'browse') { setView('windows'); return }
345
+ const signal = lifetime.current.signal
346
+ setView('native')
347
+ setNativeError(null)
348
+ Promise.resolve().then(() => picker.pick()).then((path) => {
349
+ if (signal.aborted) return
350
+ if (path === null || path === undefined) owner.current.onCancel()
351
+ else owner.current.onPicked(path)
352
+ }, (reason) => {
353
+ if (signal.aborted) return
354
+ setView('choose')
355
+ setNativeError(reason instanceof Error ? reason.message : String(reason))
356
+ })
357
+ }
358
+ // The Host decides what to register: a \\wsl.localhost path, or the real Windows path of a
359
+ // folder on a Windows drive mounted into the distribution (/mnt/<drive>/...).
360
+ const pickWsl = (distro, path) => {
361
+ setPicking(true)
362
+ setPickError(null)
363
+ const signal = lifetime.current.signal
364
+ postJson('pick', { distro, path }, signal).then((result) => {
365
+ if (signal.aborted) return
366
+ rememberRecent({ distro, path })
367
+ setPicking(false)
368
+ owner.current.onPicked(result.target)
369
+ }, (reason) => {
370
+ if (signal.aborted) return
371
+ setPicking(false)
372
+ setPickError(reason)
373
+ })
374
+ }
375
+ const errorText = pickError ? describeError(t, pickError) : nativeError
376
+
377
+ // The native chooser is a separate window, exactly as with DSH's own button.
378
+ if (view === 'native') return null
379
+ if (view === 'windows') return h(WslBrowser, { t, busy, hostPicker: picker, onBack: () => setView('choose'), onCancel: cancel, onPick: (_, path) => owner.current.onPicked(path) })
380
+ if (view === 'wsl') return h(WslBrowser, { t, busy, pickError: pickError ? describeError(t, pickError) : null, onBack: initialView === 'wsl' ? owner.current.onBack : () => { setPickError(null); setView('choose') }, onCancel: cancel, onPick: pickWsl })
381
+ return h(ChooseDialog, { t, busy, nativeError: errorText, onWindows: pickWindows, onWsl: () => { setPickError(null); setView('wsl') }, onRecent: pickWsl, onCancel: cancel })
382
+ }
383
+
384
+ function WslProvider(props) {
385
+ const owner = React.useRef(props)
386
+ owner.current = props
387
+ const request = React.useMemo(() => ({ token: ++requestSeq, busy: false, owner }), [])
388
+ return h(React.Fragment, null, h('style', null, CSS), h(PickerFlow, { request, t: props.t, picker: { kind: 'browse' }, initialView: 'wsl' }))
389
+ }
390
+ WslProvider.selfFramed = true
391
+
392
+ function ChooseDialog({ t, busy, nativeError, onWindows, onWsl, onRecent, onCancel }) {
393
+ const cardRef = React.useRef(null)
394
+ const firstRef = React.useRef(null)
395
+ const recents = React.useMemo(() => {
396
+ const stored = readJson(RECENT_KEY, [])
397
+ return (Array.isArray(stored) ? stored : [])
398
+ .filter((item) => item && typeof item.distro === 'string' && typeof item.path === 'string')
399
+ }, [])
400
+ React.useEffect(() => { (firstRef.current || cardRef.current)?.focus() }, [])
401
+ const item = (key, icon, title, sub, onClick, ref) => h('button', {
402
+ key, ref, type: 'button', className: 'dwf-item', onClick, disabled: busy,
403
+ },
404
+ h('span', { className: 'dwf-item-icon' }, icon),
405
+ h('span', { className: 'dwf-item-text' },
406
+ h('span', { className: 'dwf-item-title' }, title),
407
+ h('span', { className: 'dwf-item-sub' }, sub)))
408
+ return h(Frame, {
409
+ cardRef, label: t('title'), onDismiss: onCancel, onKeyDown: useDialogKeys(cardRef, onCancel),
410
+ },
411
+ h('div', { className: 'dwf-head' },
412
+ h('h2', { className: 'dwf-title' }, t('title')),
413
+ h('button', { type: 'button', className: 'dwf-iconbtn', 'aria-label': t('close'), title: t('close'), onClick: onCancel, disabled: busy }, IconClose())),
414
+ h('p', { className: 'dwf-desc' }, busy ? t('adding') : t('chooseHint')),
415
+ h('div', { className: 'dwf-menu' },
416
+ item('windows', IconWindows(16), t('windows'), t('windowsDesc'), onWindows),
417
+ item('wsl', IconTerminal(18), t('wsl'), t('wslDesc'), onWsl, firstRef),
418
+ nativeError ? h('div', { className: 'dwf-error', role: 'alert' }, nativeError) : null,
419
+ recents.length > 0 ? h('div', { className: 'dwf-sep' }) : null,
420
+ recents.length > 0 ? h('div', { className: 'dwf-label' }, t('recent')) : null,
421
+ recents.map((entry) => h('button', {
422
+ key: `${entry.distro}:${entry.path}`, type: 'button', className: 'dwf-item', disabled: busy,
423
+ title: `${entry.distro}: ${entry.path}`, onClick: () => onRecent(entry.distro, entry.path),
424
+ },
425
+ h('span', { className: 'dwf-item-icon' }, IconClock(14)),
426
+ h('span', { className: 'dwf-item-mono' }, entry.path),
427
+ h('span', { className: 'dwf-item-tag' }, entry.distro)))),
428
+ h('div', { className: 'dwf-tip', role: 'note' },
429
+ h('span', { className: 'dwf-tip-icon' }, IconInfo(14)),
430
+ h('span', { className: 'dwf-tip-body' },
431
+ h('span', { className: 'dwf-tip-title' }, t('tipTitle')),
432
+ h('span', null, t('tipTerminal')),
433
+ h('span', null, t('tipAgent')))))
434
+ }
435
+
436
+ // A previous successful listing may stay visible while its replacement is pending or fails.
437
+ // Only confirmed rows can be adopted. Keeping drafts active across blur avoids a stale click.
438
+ function selectionToOpen({ listing, distro, busy, loading, error, editing, folderName }) {
439
+ return listing && listing.distro === distro && !busy && !loading && !error && editing === null && folderName === null
440
+ ? listing : null
441
+ }
442
+
443
+ function WslBrowser({ t, busy, pickError, onBack, onCancel, onPick, hostPicker }) {
444
+ const cardRef = React.useRef(null)
445
+ const listRef = React.useRef(null)
446
+ const [folderName, setFolderName] = React.useState(null)
447
+ const [distros, setDistros] = React.useState(hostPicker ? [{ name: 'Windows' }] : cache.distros)
448
+ const [distro, setDistro] = React.useState(() => (hostPicker ? 'Windows' : (cache.distros ? preferredDistro(cache.distros) : '')))
449
+ const [listing, setListing] = React.useState(() => {
450
+ if (hostPicker || !cache.distros) return null
451
+ const d = preferredDistro(cache.distros)
452
+ const home = cache.homes.get(d)
453
+ return home === undefined ? null : cache.lists.get(listKey(d, home)) ?? null
454
+ })
455
+ const [loading, setLoading] = React.useState(false)
456
+ const [error, setError] = React.useState(null)
457
+ const [showHidden, setShowHidden] = React.useState(false)
458
+ const [editing, setEditing] = React.useState(null) // draft path while the path editor is open
459
+ const inflight = React.useRef(null)
460
+
461
+ const begin = () => {
462
+ inflight.current?.abort()
463
+ const controller = new AbortController()
464
+ inflight.current = controller
465
+ setLoading(true)
466
+ setError(null)
467
+ return controller
468
+ }
469
+ const settle = (controller, reason) => {
470
+ if (controller.signal.aborted) return
471
+ setLoading(false)
472
+ if (reason !== undefined) setError(reason)
473
+ }
474
+
475
+ const navigate = (name, target) => {
476
+ if (!name) return
477
+ setEditing(null)
478
+ const cached = !hostPicker && cache.lists.get(listKey(name, target))
479
+ if (cached) { setListing(cached); listRef.current?.scrollTo?.(0, 0) }
480
+ const controller = begin()
481
+ const pending = hostPicker
482
+ ? hostPicker.list(target, controller.signal).then(result => ({ ...result, distro: name, target: result.path }))
483
+ : fetchList(name, target, controller.signal)
484
+ pending.then((result) => {
485
+ if (controller.signal.aborted) return
486
+ setListing(result)
487
+ if (!cached) listRef.current?.scrollTo?.(0, 0)
488
+ settle(controller)
489
+ }, (reason) => settle(controller, reason))
490
+ }
491
+ const goHome = (name) => {
492
+ const controller = begin()
493
+ fetchHome(name, controller.signal).then((home) => {
494
+ if (!controller.signal.aborted) navigate(name, home)
495
+ }, (reason) => { if (!controller.signal.aborted) navigate(name, '/'); else settle(controller, reason) })
496
+ }
497
+
498
+ React.useEffect(() => {
499
+ cardRef.current?.focus()
500
+ if (hostPicker) {
501
+ navigate('Windows', undefined)
502
+ return () => inflight.current?.abort()
503
+ }
504
+ const controller = begin()
505
+ fetchDistros(controller.signal).then((list) => {
506
+ if (controller.signal.aborted) return
507
+ setDistros(list)
508
+ if (list.length === 0) { settle(controller); return }
509
+ const initial = preferredDistro(list)
510
+ setDistro(initial)
511
+ if (listing !== null && listing.distro === initial) navigate(initial, listing.path)
512
+ else goHome(initial)
513
+ }, (reason) => { setDistros((current) => current ?? []); settle(controller, reason) })
514
+ return () => inflight.current?.abort()
515
+ }, [])
516
+
517
+ const changeDistro = (name) => {
518
+ setDistro(name)
519
+ setListing(null)
520
+ setEditing(null)
521
+ goHome(name)
522
+ }
523
+
524
+ const entries = listing ? listing.entries.filter((entry) => showHidden || !entry.hidden) : []
525
+ const current = listing !== null && listing.distro === distro ? listing : null
526
+ const selected = selectionToOpen({ listing, distro, busy, loading, error, editing, folderName })
527
+ const segments = current === null ? [] : current.path.split('/').filter(Boolean)
528
+
529
+ const submitPath = () => {
530
+ const target = (editing ?? '').trim()
531
+ setEditing(null)
532
+ if (target) navigate(distro, hostPicker || target.startsWith('/') ? target : `/${target}`)
533
+ }
534
+
535
+ const createFolder = async () => {
536
+ if (folderName === null || !folderName.trim() || !current || busy || loading) return
537
+ const controller = begin()
538
+ try {
539
+ const path = await hostPicker.create(current.path, folderName.trim())
540
+ if (!controller.signal.aborted) { setFolderName(null); navigate(distro, path) }
541
+ } catch (error) { settle(controller, error) }
542
+ }
543
+
544
+ let body
545
+ if (distros === null || (loading && current === null)) body = h('div', { className: 'dwf-status' }, t('loading'))
546
+ else if (distros.length === 0 && !error) body = h('div', { className: 'dwf-status' }, t('noDistro'))
547
+ else if (current === null) body = null
548
+ else if (entries.length === 0) body = h('div', { className: 'dwf-status' }, t('empty'))
549
+ else {
550
+ body = entries.map((entry) => h('button', {
551
+ key: entry.path, type: 'button', disabled: busy, title: entry.name,
552
+ className: `dwf-row${entry.hidden ? ' dwf-row-hidden' : ''}`,
553
+ onClick: () => navigate(distro, entry.path),
554
+ },
555
+ h('span', { className: 'dwf-row-icon' }, IconFolder(16)),
556
+ h('span', { className: 'dwf-row-name' }, entry.name),
557
+ h('span', { className: 'dwf-chev' }, IconChevron(14))))
558
+ }
559
+
560
+ const crumbEntries = current?.crumbs ?? [{ name: '/', path: '/' }, ...segments.map((name, i) => ({ name, path: `/${segments.slice(0, i + 1).join('/')}` }))]
561
+ const crumbs = current === null ? null : h('div', { className: 'dwf-trail' },
562
+ crumbEntries.map((crumb, i) => h('span', { key: crumb.path, className: 'dwf-crumbseat' },
563
+ i ? h('span', { className: 'dwf-chev' }, IconChevron(12)) : null,
564
+ h('button', { type: 'button', className: `dwf-crumb${i === crumbEntries.length - 1 ? ' dwf-crumb-last' : ''}`,
565
+ onClick: () => navigate(distro, crumb.path), disabled: busy }, crumb.name))))
566
+
567
+ const onKeyDown = useDialogKeys(cardRef, () => {
568
+ if (folderName !== null) { setFolderName(null); cardRef.current?.focus() }
569
+ else if (editing !== null) { setEditing(null); cardRef.current?.focus() } else onCancel()
570
+ })
571
+
572
+ return h(Frame, { className: 'dwf-browser', cardRef, label: t(hostPicker ? 'windows' : 'wslTitle'), onDismiss: onCancel, onKeyDown },
573
+ h('div', { className: 'dwf-bhead' },
574
+ h('div', { className: 'dwf-titlerow' },
575
+ h('button', { type: 'button', className: 'dwf-iconbtn', 'aria-label': t('back'), title: t('back'), onClick: onBack, disabled: busy }, IconBack()),
576
+ h('h2', { className: 'dwf-title' }, t(hostPicker ? 'windows' : 'wslTitle')),
577
+ hostPicker ? null : h('select', {
578
+ className: 'dwf-select', value: distro, 'aria-label': t('distro'), title: t('distro'),
579
+ disabled: busy || !distros || distros.length === 0,
580
+ onChange: (event) => changeDistro(event.target.value),
581
+ }, (distros || []).map((d) => h('option', { key: d.name, value: d.name }, d.name))),
582
+ h('button', { type: 'button', className: 'dwf-iconbtn', 'aria-label': t('close'), title: t('close'), onClick: onCancel, disabled: busy }, IconClose())),
583
+ h('div', { className: 'dwf-crumbbar' },
584
+ editing !== null
585
+ ? h('input', {
586
+ className: 'dwf-pathinput', value: editing, spellCheck: false, autoFocus: true, 'aria-label': t('editPath'),
587
+ onChange: (event) => setEditing(event.target.value),
588
+ onKeyDown: (event) => { if (event.key === 'Enter') { event.preventDefault(); submitPath() } },
589
+ })
590
+ : h(React.Fragment, null,
591
+ crumbs,
592
+ h('button', {
593
+ type: 'button', className: 'dwf-editzone', 'aria-label': t('editPath'), title: t('editPath'),
594
+ disabled: busy || !distro,
595
+ onClick: () => setEditing(hostPicker ? (current?.path ?? '') : (current === null || current.path === '/' ? '/' : `${current.path}/`)),
596
+ }, IconEdit(14)))),
597
+ h('p', { className: 'dwf-hint' }, t('browseHint'))),
598
+ h('div', { className: 'dwf-content' },
599
+ error ? h('div', { className: 'dwf-error', role: 'alert' }, describeError(t, error)) : null,
600
+ pickError ? h('div', { className: 'dwf-error', role: 'alert' }, pickError) : null,
601
+ h('div', { ref: listRef, className: 'dwf-column', role: 'list', 'aria-busy': loading }, body),
602
+ current && current.truncated ? h('div', { className: 'dwf-status' }, t('truncated', { count: current.entries.length })) : null,
603
+ loading && current !== null ? h('div', { className: 'dwf-float', role: 'status' }, t('loading')) : null),
604
+ h('div', { className: 'dwf-foot' },
605
+ h('button', {
606
+ type: 'button', className: 'dwf-toggle', 'aria-pressed': showHidden,
607
+ onClick: () => setShowHidden((value) => !value),
608
+ }, showHidden ? IconCheck(14) : null, t('showHidden')),
609
+ hostPicker && current ? (folderName === null
610
+ ? h('button', { type: 'button', className: 'dwf-btn dwf-btn-outline', disabled: busy || loading, onClick: () => setFolderName('') }, t('newFolder'))
611
+ : h('form', { onSubmit: event => { event.preventDefault(); createFolder() } },
612
+ h('input', { autoFocus: true, 'aria-label': t('folderName'), value: folderName, onChange: event => setFolderName(event.target.value) }),
613
+ h('button', { type: 'submit', className: 'dwf-btn dwf-btn-outline', disabled: busy || loading || !folderName.trim() }, t('newFolder')))) : null,
614
+ h('span', { className: 'dwf-gap' }),
615
+ current ? h('span', { className: 'dwf-unc', title: current.target ?? current.unc }, busy ? t('adding') : (current.target ?? current.unc)) : null,
616
+ h('button', { type: 'button', className: 'dwf-btn dwf-btn-outline', onClick: onCancel, disabled: busy }, t('cancel')),
617
+ h('button', {
618
+ type: 'button', className: 'dwf-btn dwf-btn-primary', disabled: !selected,
619
+ onClick: () => selected && onPick(selected.distro, selected.path),
620
+ }, t('open'))))
621
+ }
622
+
623
+ return {
624
+ selectionToOpen,
625
+ inject: ['locale', 'uiWorkspace', 'remoteAccess'],
626
+ apply(ctx, options = {}) {
627
+ const chooserService = options.workspaceChooser
628
+ const tf = ctx.locale.bind(NS)
629
+ ctx.effect(() => {
630
+ const zhDispose = ctx.locale.register(NS, 'zh', zh)
631
+ try {
632
+ const enDispose = ctx.locale.register(NS, 'en', en)
633
+ return () => { enDispose(); zhDispose() }
634
+ } catch (error) { zhDispose(); throw error }
635
+ }, 'dsh-ssh: WSL dictionaries')
636
+ const setup = () => {
637
+ const life = new AbortController()
638
+ let activeMode
639
+ let registration
640
+ let checking
641
+ const clear = () => {
642
+ registration?.()
643
+ registration = undefined
644
+ activeMode = undefined
645
+ cache.distros = null; cache.homes.clear(); cache.lists.clear()
646
+ }
647
+ const mount = kind => {
648
+ const chooser = chooserService || ctx.workspaceChooser
649
+ if (!chooser || typeof chooser.register !== 'function') return false
650
+ const render = props => h(WslProvider, { ...props, t: tf })
651
+ render.selfFramed = true
652
+ try {
653
+ registration = chooser.register({ id: 'wsl', label: () => tf('wsl'), icon: '▣', render, order: 10, selfFramed: true })
654
+ activeMode = kind
655
+ return true
656
+ } catch (error) {
657
+ ctx.logger?.warn?.('dsh-ssh: WSL chooser registration failed', error)
658
+ return false
659
+ }
660
+ }
661
+ // HTTP, Desktop and mounts behind a prefix use the same document-relative address.
662
+ // The Host may be Linux, disabled, an older version, or unavailable to this Peer.
663
+ const recheck = () => {
664
+ if (life.signal.aborted) return Promise.resolve(false)
665
+ if (checking) return checking
666
+ checking = getJson('capabilities', {}, AbortSignal.any([life.signal, AbortSignal.timeout(5000)])).then(value =>
667
+ value.wsl === true && ['native', 'browse'].includes(value.picker) ? value.picker : undefined,
668
+ () => undefined).then(mode => {
669
+ if (life.signal.aborted) return false
670
+ if (mode !== activeMode) {
671
+ clear()
672
+ if (mode) mount(mode)
673
+ }
674
+ return !!mode && activeMode === mode
675
+ }).finally(() => { checking = undefined })
676
+ return checking
677
+ }
678
+ const onFocus = () => { void recheck().catch(error => ctx.logger?.warn?.('dsh-ssh: WSL picker capability check failed', error)) }
679
+ const reset = ctx.on?.('connection/reset', onFocus) || (() => {})
680
+ if (typeof window !== 'undefined') window.addEventListener('focus', onFocus)
681
+ onFocus()
682
+ return () => {
683
+ life.abort(); reset(); if (typeof window !== 'undefined') window.removeEventListener('focus', onFocus); clear()
684
+ }
685
+ }
686
+ const guard = ctx.remoteAccess?.whenAccess
687
+ if (typeof guard === 'function') guard.call(ctx.remoteAccess, 'directoryPicker/pick', setup)
688
+ else ctx.effect?.(setup, 'dsh-ssh: WSL chooser lifetime')
689
+ },
690
+ }
691
+ }