dsh-remote 1.1.1 → 1.2.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/lib/client.js CHANGED
@@ -27,7 +27,7 @@ window.__ModuleLoader__.load({
27
27
 
28
28
  const React = require('react')
29
29
  const name = 'dsh-remote'
30
- const CLIENT_VERSION = '1.1.1'
30
+ const CLIENT_VERSION = '1.2.0'
31
31
 
32
32
  // ── optional host primitives ────────────────────────────────────────────
33
33
  // Issue #74: a remote session's .md link must open over SFTP, NOT via the
@@ -153,6 +153,55 @@ window.__ModuleLoader__.load({
153
153
  'changes.partialDiff': "差异较大,当前仅显示部分内容。",
154
154
  'changes.chooseFile': "选择改动文件查看差异。",
155
155
 
156
+ 'ide.welcome': '欢迎',
157
+ 'ide.welcomeTitle': '远程开发工作区',
158
+ 'ide.welcomeHint': '从左侧打开文件,即可在这里开始编辑。',
159
+ 'ide.guideFiles': '浏览与搜索',
160
+ 'ide.guideFilesHint': '在左侧展开目录,或搜索远端文件、目录和内容。',
161
+ 'ide.guideEdit': '编辑与保存',
162
+ 'ide.guideEditHint': '文件直接打开为可编辑状态。使用 Ctrl / ⌘ + S 保存到远端。',
163
+ 'ide.guideAgent': '与 Agent 协作',
164
+ 'ide.guideAgentHint': '在右侧描述任务,运行构建并核对输出;点击诊断可跳转源码。',
165
+ 'ide.guideLayout': '调整工作空间',
166
+ 'ide.guideLayoutHint': '拖动分隔线调整栏宽;窄屏可切换文件、编辑器和会话。',
167
+ 'ide.documentation': '使用指南',
168
+ 'ide.tools': '会话工具', 'ide.toolsHint': '展开或收起会话附加工具与连接信息',
169
+ "local.explorer.tabTitle": "本地文件",
170
+ "local.workbench.openTerminal": "打开本地终端",
171
+ "local.workbench.terminalUnavailable": "本地终端尚不可用,请检查宿主终端插件。",
172
+ "local.workbench.filter": "搜索本地工作区",
173
+ "local.workbench.remote": "本地工作区",
174
+ "local.workbench.copyPath": "复制本地路径",
175
+ "local.workbench.saved": "已保存到本地",
176
+ "local.workbench.loadingFile": "正在读取本地文件…",
177
+ "local.file.readFail": "本地读取失败:{msg}",
178
+ "local.file.listFail": "本地目录读取失败:{msg}",
179
+ "local.file.conflictHelp": "本地文件已变化,草稿已保留。请重新读取并比较后合并修改。",
180
+ "local.file.discardReload": "舍弃草稿并重新读取",
181
+ "local.file.incompletePreview": "当前文件预览不完整,请在终端编辑完整文件。",
182
+ "local.explorer.connection.loading": "正在读取本地目录…",
183
+ "local.explorer.connection.interrupted": "本地访问失败 · 已保留文件列表",
184
+ "local.explorer.connection.ready": "本地目录已就绪",
185
+ "local.ide.welcomeTitle": "本地开发工作区",
186
+ "local.ide.guideFilesHint": "在左侧展开目录,或搜索项目文件、目录和内容。",
187
+ "local.ide.guideEditHint": "文件打开即可编辑。使用 Ctrl / ⌘ + S 保存到本地项目。",
188
+ "local.ide.guideAgentHint": "Agent 继续使用宿主原生文件与命令工具,在当前本地项目中工作。",
189
+ "local.ide.chooseFile": "从左侧选择项目文件,在这里编辑。",
190
+ "local.file.saveToRemote": "保存到本地",
191
+ "local.file.binary": "二进制文件({size}),请使用本机应用打开。",
192
+ "local.file.truncated": "… 内容已截断,请在本机应用中查看完整文件。",
193
+ "local.file.conflict": "本地文件已变化,请重新读取",
194
+ "local.changes.title": "本地 Git 改动",
195
+ "local.changes.failed": "无法读取本地 Git 状态",
196
+ "local.changes.noGit": "本机未安装 Git,安装后点击刷新。",
197
+ "local.changes.unavailable": "当前无法查看本地 Git 状态。",
198
+ "local.changes.readOnly": "查看本地仓库,不自动提交或更改暂存区。",
199
+ "local.changes.refreshing": "正在刷新本地状态…",
200
+ "local.changes.loading": "正在读取本地 Git 状态…",
201
+ "local.changes.diff": "本地文件差异",
202
+ "local.changes.openFile": "打开本地文件",
203
+ "workspace.files": "工作区文件",
204
+ "workspace.git": "Git 改动",
156
205
  'ide.enter': 'IDE 模式', 'ide.exit': '返回普通模式', 'ide.files': '文件',
157
206
  'ide.editor': '编辑器', 'ide.chat': '会话', 'ide.openEditor': '打开编辑区',
158
207
  'ide.chooseFile': '从左侧选择远程文件,在这里编辑。',
@@ -617,6 +666,7 @@ window.__ModuleLoader__.load({
617
666
  'file.saveToRemote': '保存到远程',
618
667
  'file.saving': '保存中…',
619
668
  'file.cancel': '取消',
669
+ 'file.discardChanges': '放弃更改',
620
670
  'file.edit': '编辑',
621
671
  'file.download': '下载',
622
672
  'file.loading': '加载中…',
@@ -629,6 +679,11 @@ window.__ModuleLoader__.load({
629
679
  'file.saveHint': 'Ctrl/⌘+S 保存',
630
680
  'file.downloaded': '已下载到本地镜像{local}',
631
681
  'file.downloadedAt': ': {path}',
682
+ 'file.localCopyMissing': '远端没有此文件,但本地镜像中有同名副本。',
683
+ 'file.localCopyHelp': '可先只读查看,确认后上传到远端。上传仅创建新文件,不覆盖已有文件。',
684
+ 'file.localCopyView': '查看本地副本',
685
+ 'file.localCopyPublish': '上传到远端并打开',
686
+ 'file.localCopySource': '本地镜像副本 · 只读,尚未上传到远端',
632
687
  'file.readFail': '远程读取失败: {msg}',
633
688
  'file.listFail': '远程目录读取失败: {msg}',
634
689
  // Issue #55: a file link in a remote Session cannot be mapped onto the
@@ -694,6 +749,55 @@ window.__ModuleLoader__.load({
694
749
  'changes.partialDiff': "This diff is large; showing partial content.",
695
750
  'changes.chooseFile': "Select a changed file to inspect its diff.",
696
751
 
752
+ 'ide.welcome': 'Welcome',
753
+ 'ide.welcomeTitle': 'Your remote development workspace',
754
+ 'ide.welcomeHint': 'Open a file on the left to start editing here.',
755
+ 'ide.guideFiles': 'Browse and search',
756
+ 'ide.guideFilesHint': 'Expand folders on the left, or search remote files, folders and contents.',
757
+ 'ide.guideEdit': 'Edit and save',
758
+ 'ide.guideEditHint': 'Files open ready to edit. Use Ctrl / ⌘ + S to save to the remote host.',
759
+ 'ide.guideAgent': 'Work with your agent',
760
+ 'ide.guideAgentHint': 'Describe a task on the right, build and review output. Click diagnostics to open source.',
761
+ 'ide.guideLayout': 'Arrange your workspace',
762
+ 'ide.guideLayoutHint': 'Drag separators to resize columns. Switch panes on narrow screens.',
763
+ 'ide.documentation': 'User guide',
764
+ 'ide.tools': 'Chat tools', 'ide.toolsHint': 'Show or hide extra conversation tools and connection details',
765
+ "local.explorer.tabTitle": "Local files",
766
+ "local.workbench.openTerminal": "Open local terminal",
767
+ "local.workbench.terminalUnavailable": "Local terminal unavailable. Check the host terminal plugin.",
768
+ "local.workbench.filter": "Search local workspace",
769
+ "local.workbench.remote": "Local workspace",
770
+ "local.workbench.copyPath": "Copy local path",
771
+ "local.workbench.saved": "Saved locally",
772
+ "local.workbench.loadingFile": "Reading local file…",
773
+ "local.file.readFail": "Local read failed: {msg}",
774
+ "local.file.listFail": "Local listing failed: {msg}",
775
+ "local.file.conflictHelp": "Local file changed. Your draft is retained; reload and compare before merging.",
776
+ "local.file.discardReload": "Discard draft and reload",
777
+ "local.file.incompletePreview": "Incomplete preview; edit the complete file in the terminal.",
778
+ "local.explorer.connection.loading": "Reading local directory…",
779
+ "local.explorer.connection.interrupted": "Local access failed · file list retained",
780
+ "local.explorer.connection.ready": "Local directory ready",
781
+ "local.ide.welcomeTitle": "Local development workspace",
782
+ "local.ide.guideFilesHint": "Expand folders on the left, or search project files, directories and contents.",
783
+ "local.ide.guideEditHint": "Files open ready to edit. Use Ctrl / ⌘ + S to save to the local project.",
784
+ "local.ide.guideAgentHint": "The Agent uses the host’s native file and command tools in this local project.",
785
+ "local.ide.chooseFile": "Select a project file on the left to edit here.",
786
+ "local.file.saveToRemote": "Save locally",
787
+ "local.file.binary": "Binary file ({size}); open it with a local application.",
788
+ "local.file.truncated": "… Preview truncated; open the complete file with a local application.",
789
+ "local.file.conflict": "Local file changed; reload before saving",
790
+ "local.changes.title": "Local Git changes",
791
+ "local.changes.failed": "Could not read local Git status",
792
+ "local.changes.noGit": "Git is unavailable on this host. Install it and refresh.",
793
+ "local.changes.unavailable": "Local Git status is unavailable.",
794
+ "local.changes.readOnly": "Inspect the local repository without changing commits or the index.",
795
+ "local.changes.refreshing": "Refreshing local status…",
796
+ "local.changes.loading": "Reading local Git status…",
797
+ "local.changes.diff": "Local file diff",
798
+ "local.changes.openFile": "Open local file",
799
+ "workspace.files": "Workspace files",
800
+ "workspace.git": "Git changes",
697
801
  'ide.enter': 'IDE mode', 'ide.exit': 'Return to standard mode', 'ide.files': 'Files',
698
802
  'ide.editor': 'Editor', 'ide.chat': 'Chat', 'ide.openEditor': 'Open editor area',
699
803
  'ide.chooseFile': 'Choose a remote file on the left to edit it here.',
@@ -1151,6 +1255,7 @@ window.__ModuleLoader__.load({
1151
1255
  'file.saveToRemote': 'Save to remote',
1152
1256
  'file.saving': 'Saving…',
1153
1257
  'file.cancel': 'Cancel',
1258
+ 'file.discardChanges': 'Discard changes',
1154
1259
  'file.edit': 'Edit',
1155
1260
  'file.download': 'Download',
1156
1261
  'file.loading': 'Loading…',
@@ -1163,6 +1268,11 @@ window.__ModuleLoader__.load({
1163
1268
  'file.saveHint': 'Ctrl/⌘+S to save',
1164
1269
  'file.downloaded': 'Downloaded to local mirror{local}',
1165
1270
  'file.downloadedAt': ': {path}',
1271
+ 'file.localCopyMissing': 'This file is missing remotely. A copy exists in the local mirror.',
1272
+ 'file.localCopyHelp': 'Preview the local copy, then upload it. Upload creates a new remote file and never replaces an existing file.',
1273
+ 'file.localCopyView': 'View local copy',
1274
+ 'file.localCopyPublish': 'Upload and open remotely',
1275
+ 'file.localCopySource': 'Local mirror copy · Read only, not uploaded',
1166
1276
  'file.readFail': 'Failed to read remote: {msg}',
1167
1277
  'file.listFail': 'Failed to list remote directory: {msg}',
1168
1278
  'file.markdown.copy': 'Copy',
@@ -1262,13 +1372,35 @@ window.__ModuleLoader__.load({
1262
1372
  // The official Electron shell serves the shared API over its private
1263
1373
  // dsh-app carrier. Legacy browser hosts keep their existing route prefix.
1264
1374
  // Choose before sending: never retry a mutating request on another route.
1375
+ //
1376
+ // A browser host may mount the harness UNDER A PATH PREFIX (the fnOS
1377
+ // console serves it at /app/<app>/dsh/, and any prefix-stripping reverse
1378
+ // proxy does the same). The routes are registered at the server ROOT, so a
1379
+ // ROOT-ABSOLUTE '/dsh-remote/...' request would leave the mount and hit
1380
+ // the gateway's own SPA — a 404 with an empty body, and the remote
1381
+ // workspace panel then shows no hosts at all.
1382
+ //
1383
+ // The page's <base href="./"> makes every relative resource resolve
1384
+ // against the mount DIRECTORY, so the route must resolve the same way:
1385
+ // drop the leading slash and let the base carry the prefix. Resolving
1386
+ // against the base's own directory ('.' against the base URL) is exactly
1387
+ // what the browser does for the plugin bundle URL, so the API and the
1388
+ // bundle can never disagree about where the mount lives.
1265
1389
  function apiPath(path) {
1266
- return window.location && window.location.protocol === 'dsh-app:'
1267
- ? '/api' + path : path
1390
+ if (window.location && window.location.protocol === 'dsh-app:') return '/api' + path
1391
+ const base = typeof document !== 'undefined' ? document.baseURI : ''
1392
+ if (!base) return path
1393
+ try {
1394
+ const baseUrl = new URL(base)
1395
+ if (baseUrl.protocol !== 'http:' && baseUrl.protocol !== 'https:') return path
1396
+ return new URL('.', baseUrl).pathname + path.replace(/^\/+/, '')
1397
+ } catch {
1398
+ return path
1399
+ }
1268
1400
  }
1269
1401
 
1270
1402
  function sessionQuery(sessionId) {
1271
- return sessionId ? 'sessionId=' + encodeURIComponent(sessionId) : ''
1403
+ return sessionId ? 'sessionId=' + encodeURIComponent(sessionId) + (localWorkspaceSession(sessionId) ? '&workspace=local' : '') : ''
1272
1404
  }
1273
1405
  function withSessionQuery(path, sessionId) {
1274
1406
  const q = sessionQuery(sessionId)
@@ -1277,7 +1409,7 @@ window.__ModuleLoader__.load({
1277
1409
  }
1278
1410
  function withSessionBody(body, sessionId) {
1279
1411
  if (!sessionId) return body
1280
- return Object.assign({}, body || {}, { sessionId })
1412
+ return Object.assign({}, body || {}, { sessionId }, localWorkspaceSession(sessionId) ? { workspace: 'local' } : {})
1281
1413
  }
1282
1414
 
1283
1415
  async function api(method, path, body, signal) {
@@ -1285,7 +1417,12 @@ window.__ModuleLoader__.load({
1285
1417
  if (body) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body) }
1286
1418
  const res = await fetch(apiPath(path), opts)
1287
1419
  const data = await res.json().catch(() => ({}))
1288
- if (!res.ok) throw new Error(trHostError((data && (data.error || data.message))) || 'HTTP ' + res.status)
1420
+ if (!res.ok) {
1421
+ const error = new Error(trHostError((data && (data.error || data.message))) || 'HTTP ' + res.status)
1422
+ error.code = data?.code
1423
+ error.localCopy = data?.localCopy
1424
+ throw error
1425
+ }
1289
1426
  return data
1290
1427
  }
1291
1428
 
@@ -3707,7 +3844,30 @@ window.__ModuleLoader__.load({
3707
3844
  return api('POST', EXPLORER_AUTO_OPEN_ROUTE, { enabled: on }).catch(() => null)
3708
3845
  }
3709
3846
 
3847
+ // A loaded registry plus the session's own cwd proves local vs remote.
3848
+ // Registry failure never turns an unrecognised mirror into a local project.
3849
+ function localWorkspaceSession(sessionId) {
3850
+ const cwd = sessionCwdFor(sessionId)
3851
+ return !!(cwd && MIRRORS.loaded && !MIRRORS.error && !mirrorForCwd(cwd, MIRRORS.list))
3852
+ }
3853
+ function workspaceText(key, sessionId, params) {
3854
+ return tr(localWorkspaceSession(sessionId) && L.en['local.' + key] ? 'local.' + key : key, params)
3855
+ }
3856
+ function workspaceSummary(sessionId) {
3857
+ const cwd = sessionCwdFor(sessionId)
3858
+ const remote = mirrorForCwd(cwd, MIRRORS.list)
3859
+ if (remote) return remote
3860
+ return localWorkspaceSession(sessionId) ? { local: true, remotePath: cwd, name: workspaceText('workbench.remote', sessionId) } : null
3861
+ }
3862
+ function workspaceMemoryKey(sessionId) {
3863
+ return localWorkspaceSession(sessionId) ? 'local:' + sessionCwdFor(sessionId) + ':' + sessionId : String(sessionId || '')
3864
+ }
3865
+ function fetchWorkspaceContext(sessionId) {
3866
+ return api('GET', '/dsh-remote/workspace-context?sessionId=' + encodeURIComponent(sessionId))
3867
+ }
3868
+
3710
3869
  function fetchRemoteStatus(sessionId) {
3870
+ if (localWorkspaceSession(sessionId)) return fetchWorkspaceContext(sessionId).then(value => ({ ...value, local: true, connected: true, workspace: value.root })).catch(() => null)
3711
3871
  return api('GET', withSessionQuery('/dsh-remote/status', sessionId)).catch(() => null)
3712
3872
  }
3713
3873
 
@@ -3990,14 +4150,16 @@ window.__ModuleLoader__.load({
3990
4150
  }
3991
4151
 
3992
4152
  function readRemoteFile(path, maxBytes, sessionId) {
3993
- return api('POST', '/dsh-remote/read', withSessionBody({ path, maxBytes }, sessionId)).catch((e) => {
3994
- throw new Error(tr('file.readFail', { msg: ((e && e.message) || e) }))
4153
+ return ensureMirrors().then(() => api('POST', '/dsh-remote/read', withSessionBody({ path, maxBytes }, sessionId))).catch((e) => {
4154
+ const error = new Error(workspaceText('file.readFail', sessionId, { msg: ((e && e.message) || e) }))
4155
+ error.code = e?.code; error.localCopy = e?.localCopy
4156
+ throw error
3995
4157
  })
3996
4158
  }
3997
4159
 
3998
4160
  function listRemoteDir(path, sessionId) {
3999
- return api('GET', withSessionQuery('/dsh-remote/ls?path=' + encodeURIComponent(path || ''), sessionId)).catch((e) => {
4000
- throw new Error(tr('file.listFail', { msg: ((e && e.message) || e) }))
4161
+ return ensureMirrors().then(() => api('GET', withSessionQuery('/dsh-remote/ls?path=' + encodeURIComponent(path || ''), sessionId))).catch((e) => {
4162
+ throw new Error(workspaceText('file.listFail', sessionId, { msg: ((e && e.message) || e) }))
4001
4163
  })
4002
4164
  }
4003
4165
 
@@ -4178,7 +4340,7 @@ window.__ModuleLoader__.load({
4178
4340
  // tab, which is where the resolved root becomes known.)
4179
4341
  const sharedKey = sharedExpanded.join('\u0000')
4180
4342
  React.useEffect(() => {
4181
- if (!evictShared) return
4343
+ if (!evictShared || localWorkspaceSession(props.scope?.sessionId)) return
4182
4344
  const stray = strayRemoteSharedPaths('', sharedKey ? sharedKey.split('\u0000') : [])
4183
4345
  for (const p of stray) evictShared(p)
4184
4346
  }, [sharedKey, evictShared])
@@ -4189,7 +4351,7 @@ window.__ModuleLoader__.load({
4189
4351
  return React.createElement(RemoteExplorerTab, {
4190
4352
  ...owned,
4191
4353
  evictStray: (root) => {
4192
- if (!evictShared || !sharedExpanded.length) return []
4354
+ if (!evictShared || !sharedExpanded.length || localWorkspaceSession(props.scope?.sessionId)) return []
4193
4355
  const stray = strayRemoteSharedPaths(root, sharedExpanded)
4194
4356
  for (const p of stray) evictShared(p)
4195
4357
  return stray
@@ -4222,12 +4384,17 @@ window.__ModuleLoader__.load({
4222
4384
  try {
4223
4385
  const right = SIDEBAR_RIGHT
4224
4386
  const terminals = WEB_TERMINALS
4225
- if (!right || !terminals || typeof terminals.launchShells !== 'function') throw new Error(tr('workbench.terminalUnavailable'))
4387
+ if (!right || !terminals || typeof terminals.launchShells !== 'function') throw new Error(workspaceText('workbench.terminalUnavailable', sessionId))
4226
4388
  const choices = await terminals.launchShells(sessionId, controller.signal)
4227
4389
  if (controller.signal.aborted) return
4228
4390
  if (right.mounted && typeof right.mounted.getSnapshot === 'function' && right.mounted.getSnapshot() !== sessionId) return
4229
- const shell = (choices.shells || []).find((s) => s.name === 'remote ssh' || /(^|[\\/])remote ssh(?:\.cmd)?$/i.test(s.path || ''))
4230
- if (!shell) throw new Error(tr('workbench.terminalUnavailable'))
4391
+ const shells = choices.shells || []
4392
+ const isRemote = s => s.name === 'remote ssh' || /(^|[\\/])remote ssh(?:\.cmd)?$/i.test(s.path || '')
4393
+ const local = localWorkspaceSession(sessionId)
4394
+ const shell = local
4395
+ ? shells.find(s => !isRemote(s) && (s.path === choices.selectedShell || s.name === choices.selectedShell)) || shells.find(s => !isRemote(s))
4396
+ : shells.find(isRemote)
4397
+ if (!shell) throw new Error(workspaceText('workbench.terminalUnavailable', sessionId))
4231
4398
  right.openTab('terminal', { params: { shellPath: shell.path } })
4232
4399
  } catch (e) { if (!controller.signal.aborted) setError(String(e.message || e)) }
4233
4400
  finally { if (lifetime.current === controller) { lifetime.current = null; setPending(false) } }
@@ -4340,8 +4507,9 @@ window.__ModuleLoader__.load({
4340
4507
  }
4341
4508
 
4342
4509
  function RemoteExplorerTab(props) {
4510
+ const tr = (key, params) => workspaceText(key, props.scope?.sessionId, params)
4343
4511
  const [status, setStatus] = React.useState(null)
4344
- const [root, setRoot] = React.useState('') // remote root path for this session
4512
+ const [root, setRoot] = React.useState('') // execution-world project root for this session
4345
4513
  const [data, setData] = React.useState({}) // dir -> { entries | error | loading }
4346
4514
  const dataRef = React.useRef(data)
4347
4515
  const [err, setErr] = React.useState('')
@@ -4386,7 +4554,7 @@ window.__ModuleLoader__.load({
4386
4554
  setData(dataRef.current)
4387
4555
  }
4388
4556
 
4389
- const viewKey = String(sessionId || '') + '\0' + String(scopeCwd || '')
4557
+ const viewKey = workspaceMemoryKey(sessionId) + '\0' + String(scopeCwd || '')
4390
4558
  const viewRef = React.useRef({ key: viewKey, requests: new Map() })
4391
4559
  if (viewRef.current.key !== viewKey) {
4392
4560
  viewRef.current = { key: viewKey, requests: new Map() }
@@ -4412,7 +4580,7 @@ window.__ModuleLoader__.load({
4412
4580
  const request = {}
4413
4581
  view.requests.set(dir, request)
4414
4582
  const current = () => viewRef.current === view && view.requests.get(dir) === request
4415
- storeLevel(dir, { ...existing, loading: true })
4583
+ if (!opts?.quiet || !existing?.entries) storeLevel(dir, { ...existing, loading: true })
4416
4584
  return listRemoteDir(dir, sessionId)
4417
4585
  .then((res) => {
4418
4586
  if (!current()) return
@@ -4475,7 +4643,10 @@ window.__ModuleLoader__.load({
4475
4643
 
4476
4644
  }
4477
4645
  }
4478
- const resolveRoot = () => {
4646
+ const resolveRoot = async () => {
4647
+ if (opts?.force) await refreshMirrors()
4648
+ else await ensureMirrors()
4649
+ if (localWorkspaceSession(sessionId)) return fetchWorkspaceContext(sessionId).then(value => value.root || '')
4479
4650
  if (scopeCwd) {
4480
4651
  return api('GET', '/dsh-remote/resolve-mirror?local=' + encodeURIComponent(scopeCwd))
4481
4652
  .then((r) => (r && r.remotePath) || '')
@@ -4544,7 +4715,7 @@ window.__ModuleLoader__.load({
4544
4715
  return d
4545
4716
  }
4546
4717
  box.appendChild(mkItem(menu.isDir ? tr('explorer.menuExpand') : tr('explorer.menuOpen'), false, () => runMenuAction('open', menu)))
4547
- box.appendChild(mkItem(tr('explorer.menuDownload'), false, () => runMenuAction('download', menu)))
4718
+ if (!localWorkspaceSession(sessionId)) box.appendChild(mkItem(tr('explorer.menuDownload'), false, () => runMenuAction('download', menu)))
4548
4719
  box.appendChild(mkItem(tr('explorer.menuCopyRel'), false, () => runMenuAction('copy-rel', menu)))
4549
4720
  box.appendChild(mkItem(tr('explorer.menuCopyAbs'), false, () => runMenuAction('copy-abs', menu)))
4550
4721
  box.appendChild(mkItem(tr('explorer.menuRename'), false, () => runMenuAction('rename', menu)))
@@ -4765,6 +4936,10 @@ window.__ModuleLoader__.load({
4765
4936
  const view = viewRef.current
4766
4937
  const timer = setInterval(() => {
4767
4938
  fetchRemoteStatus(sessionId).then((next) => { if (next && viewRef.current === view) setStatus(next) })
4939
+ if (localWorkspaceSession(sessionId)) {
4940
+ loadDir(root, { force: true, quiet: true })
4941
+ for (const dir of expandedRef.current) if (dir !== root) loadDir(dir, { force: true, quiet: true })
4942
+ }
4768
4943
  }, 5000)
4769
4944
  return () => clearInterval(timer)
4770
4945
  }, [root, sessionId, props.visible])
@@ -4836,7 +5011,7 @@ window.__ModuleLoader__.load({
4836
5011
  getAnchorRect: () => ({ left: menu.x, top: menu.y, right: menu.x, bottom: menu.y, width: 0, height: 0 }),
4837
5012
  items: [
4838
5013
  { id: 'open', label: menu.isDir ? tr('explorer.menuExpand') : tr('explorer.menuOpen') },
4839
- { id: 'download', label: tr('explorer.menuDownload') },
5014
+ ...(!localWorkspaceSession(sessionId) ? [{ id: 'download', label: tr('explorer.menuDownload') }] : []),
4840
5015
  { id: 'copy-rel', label: tr('explorer.menuCopyRel') },
4841
5016
  { id: 'copy-abs', label: tr('explorer.menuCopyAbs') },
4842
5017
  { id: 'rename', label: tr('explorer.menuRename') },
@@ -4935,7 +5110,7 @@ window.__ModuleLoader__.load({
4935
5110
  )
4936
5111
  }
4937
5112
 
4938
- // ── Remote file tab (opened by the explorer; live read + explicit edit) ──
5113
+ // ── Remote file tab (live read, editable text and conflict-aware saves) ──
4939
5114
  /**
4940
5115
  * The host's MarkdownText reads chrome strings off `labels` while rendering
4941
5116
  * fenced code blocks (`labels.code.*`) and footnotes (`labels.footnotes`),
@@ -4977,19 +5152,174 @@ window.__ModuleLoader__.load({
4977
5152
  return { text: text.slice(0, lineStart) + indented + text.slice(blockEnd), start: Math.max(lineStart, start + firstAdjustment), end: Math.max(lineStart, end + adjustment) }
4978
5153
  }
4979
5154
 
5155
+ // Keeps the native textarea as the editor: selection, IME, accessibility,
5156
+ // clipboard and the browser undo stack never depend on token DOM nodes.
5157
+ function HighlightedEditor(props) {
5158
+ const value = String(props.value ?? '')
5159
+ const lang = languageForPathFn ? languageForPathFn(props.path || '') : undefined
5160
+ const highlight = useCodeHighlighterFn ? useCodeHighlighterFn(lang) : null
5161
+ const lines = React.useMemo(() => value.split('\n'), [value])
5162
+ const large = value.length > 300000 || lines.length > 10000
5163
+ const tokenLines = React.useMemo(() => {
5164
+ if (!highlight || large) return null
5165
+ try {
5166
+ const result = highlight(value)
5167
+ if (!Array.isArray(result)) return null
5168
+ // Never hide native text behind stale, clipped or malformed tokens.
5169
+ if (!lines.every((line, index) => Array.isArray(result[index] || []) && (result[index] || []).every(token => token && typeof token.text === 'string') && (result[index] || []).map(token => token.text).join('') === line)) return null
5170
+ return result
5171
+ } catch { return null }
5172
+ }, [highlight, value, lines, large])
5173
+ const ownEditorRef = React.useRef(null)
5174
+ const paintRef = React.useRef(null)
5175
+ const gutterRef = React.useRef(null)
5176
+ const compositionRef = React.useRef(false)
5177
+ const publishedRef = React.useRef(0)
5178
+ const [composing, setComposing] = React.useState(false)
5179
+ const [metrics, setMetrics] = React.useState({ width: 0, gutterHeights: [] })
5180
+ const layoutEffect = React.useLayoutEffect || React.useEffect
5181
+ const lineHeight = 20
5182
+ const marked = new Set(props.matchingLines || [])
5183
+ const colored = !!tokenLines && !composing
5184
+ const paintText = !composing && !large
5185
+ const typography = {
5186
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', fontSize: 13,
5187
+ lineHeight: lineHeight + 'px', fontWeight: 400, fontStyle: 'normal', fontVariantLigatures: 'none',
5188
+ fontKerning: 'none', fontFeatureSettings: '"liga" 0, "calt" 0', letterSpacing: 0,
5189
+ tabSize: 2, textIndent: 0, textAlign: 'left', textTransform: 'none', direction: 'ltr',
5190
+ whiteSpace: props.wrap ? 'pre-wrap' : 'pre', overflowWrap: props.wrap ? 'anywhere' : 'normal', wordBreak: 'normal',
5191
+ }
5192
+ const syncScroll = node => {
5193
+ if (paintRef.current) paintRef.current.style.transform = 'translate(' + (-node.scrollLeft) + 'px,' + (-node.scrollTop) + 'px)'
5194
+ if (gutterRef.current) gutterRef.current.style.transform = 'translateY(' + (-node.scrollTop) + 'px)'
5195
+ }
5196
+ const publish = event => { publishedRef.current++; props.onChange?.(event) }
5197
+ const notifySelection = node => props.onSelect?.({ currentTarget: node, target: node })
5198
+ const measure = () => {
5199
+ const node = ownEditorRef.current, paint = paintRef.current
5200
+ if (!node || !paint) return
5201
+ const heights = Array.from(paint.children, row => row.getBoundingClientRect().height)
5202
+ setMetrics(previous => previous.width === node.clientWidth && previous.gutterHeights.length === heights.length && heights.every((height, index) => height === previous.gutterHeights[index])
5203
+ ? previous : { width: node.clientWidth, gutterHeights: heights })
5204
+ syncScroll(node)
5205
+ }
5206
+ layoutEffect(() => {
5207
+ const node = ownEditorRef.current
5208
+ measure()
5209
+ if (!node || typeof ResizeObserver !== 'function') return undefined
5210
+ const observer = new ResizeObserver(measure)
5211
+ observer.observe(node)
5212
+ if (paintRef.current) observer.observe(paintRef.current)
5213
+ return () => observer.disconnect()
5214
+ }, [])
5215
+ layoutEffect(measure, [value, props.wrap, tokenLines, metrics.width])
5216
+ const revealLine = (requested, select) => {
5217
+ const node = ownEditorRef.current, paint = paintRef.current
5218
+ if (!node || !paint || !Number.isFinite(Number(requested))) return
5219
+ const number = Math.max(1, Math.min(lines.length, Math.trunc(Number(requested))))
5220
+ const row = paint.children[number - 1]
5221
+ if (select) {
5222
+ const offset = lines.slice(0, number - 1).reduce((sum, line) => sum + line.length + 1, 0)
5223
+ try { node.focus({ preventScroll: true }) } catch { node.focus() }
5224
+ node.setSelectionRange(offset, offset)
5225
+ notifySelection(node)
5226
+ }
5227
+ node.scrollTop = Math.max(0, (row ? row.offsetTop : 10 + (number - 1) * lineHeight) - (node.clientHeight - (row ? row.offsetHeight : lineHeight)) / 2)
5228
+ if (select) node.scrollLeft = 0
5229
+ syncScroll(node)
5230
+ props.onScroll?.({ currentTarget: node, target: node })
5231
+ }
5232
+ layoutEffect(() => {
5233
+ const node = ownEditorRef.current
5234
+ if (!node) return undefined
5235
+ node.dshScrollToLine = line => revealLine(line, false)
5236
+ return () => { delete node.dshScrollToLine }
5237
+ }, [value, props.wrap])
5238
+ layoutEffect(() => {
5239
+ if (!props.jumpLine) return undefined
5240
+ const schedule = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : callback => setTimeout(callback, 0)
5241
+ const cancel = typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : clearTimeout
5242
+ const frame = schedule(() => revealLine(props.jumpLine, true))
5243
+ return () => cancel(frame)
5244
+ }, [props.path, props.jumpLine, props.jumpRevision])
5245
+ layoutEffect(() => { if (props.currentMatchLine) revealLine(props.currentMatchLine, false) }, [props.currentMatchLine])
5246
+ const indentSelection = (node, reverse) => {
5247
+ const transform = props.indent || indentRemoteDraft
5248
+ const result = transform(node.value, node.selectionStart, node.selectionEnd, reverse)
5249
+ if (result.text === node.value) return
5250
+ // Replace only the changed range. Native insertText records a genuine
5251
+ // editing transaction; assigning .value would discard browser undo.
5252
+ const before = node.value
5253
+ let from = 0, oldEnd = before.length, newEnd = result.text.length
5254
+ while (from < oldEnd && from < newEnd && before[from] === result.text[from]) from++
5255
+ while (oldEnd > from && newEnd > from && before[oldEnd - 1] === result.text[newEnd - 1]) { oldEnd--; newEnd-- }
5256
+ const published = publishedRef.current
5257
+ node.setSelectionRange(from, oldEnd)
5258
+ let inserted = false
5259
+ try { inserted = document.execCommand('insertText', false, result.text.slice(from, newEnd)) } catch { /* unsupported browser */ }
5260
+ if (!inserted || node.value !== result.text) node.setRangeText(result.text.slice(from, newEnd), from, oldEnd, 'end')
5261
+ // execCommand fires React's input event on supported browsers. The
5262
+ // fallback must publish explicitly, without emitting a duplicate edit.
5263
+ if (publishedRef.current === published) publish({ currentTarget: node, target: node })
5264
+ node.setSelectionRange(result.start, result.end)
5265
+ notifySelection(node)
5266
+ syncScroll(node)
5267
+ }
5268
+ return React.createElement('div', {
5269
+ 'data-rw-highlight-editor': '', 'data-rw-editor-highlighted': colored ? 'true' : 'false',
5270
+ style: { position: 'relative', flex: 1, minHeight: 0, minWidth: 0, display: 'flex', overflow: 'hidden', ...typography, background: 'transparent' },
5271
+ },
5272
+ React.createElement('style', {}, '[data-rw-editor-input]::selection{background:rgba(74,144,226,.32);color:inherit;-webkit-text-fill-color:inherit}'),
5273
+ React.createElement('div', { 'aria-hidden': true, 'data-rw-editor-gutter': '', style: { display: large ? 'none' : undefined, flex: '0 0 ' + (Math.max(3, String(lines.length).length) + 2) + 'ch', overflow: 'hidden', borderRight: '1px solid ' + T.border, color: T.muted, userSelect: 'none', ...typography } },
5274
+ React.createElement('div', { ref: gutterRef, style: { paddingTop: 10, paddingBottom: 10 } }, (large ? [] : lines).map((_, index) => React.createElement('div', { key: index, style: { height: metrics.gutterHeights[index] || lineHeight, textAlign: 'right', paddingRight: 10, boxSizing: 'border-box' } }, index + 1)))),
5275
+ React.createElement('div', { style: { position: 'relative', flex: 1, minWidth: 0, minHeight: 0, overflow: 'hidden' } },
5276
+ React.createElement('pre', { ref: paintRef, 'aria-hidden': true, 'data-rw-editor-paint': '', style: { ...typography, position: 'absolute', left: 0, top: 0, margin: 0, border: 0, padding: '10px 12px', boxSizing: 'border-box', width: metrics.width || '100%', pointerEvents: 'none', visibility: paintText ? 'visible' : 'hidden', color: T.label } },
5277
+ (large ? [] : lines).map((line, index) => React.createElement('span', {
5278
+ key: index + (Number(props.jumpLine) === index + 1 ? '-jump-' + String(props.jumpRevision || 0) : ''),
5279
+ 'data-line': index + 1, 'data-rw-editor-line': index + 1,
5280
+ className: [Number(props.jumpLine) === index + 1 ? 'dsh-rw-line-flash' : '', props.currentMatchLine === index + 1 ? 'dsh-rw-code-current' : marked.has(index + 1) ? 'dsh-rw-code-hit' : ''].filter(Boolean).join(' ') || undefined,
5281
+ style: { display: 'block', minHeight: lineHeight, ...typography },
5282
+ }, tokenLines && tokenLines[index]?.length
5283
+ ? tokenLines[index].map((token, tokenIndex) => React.createElement('span', { key: tokenIndex, 'data-rw-editor-token': '', style: { color: token.style?.color || T.label } }, token.text))
5284
+ : line || '\u200b'))),
5285
+ React.createElement('textarea', {
5286
+ ref: node => { ownEditorRef.current = node; if (typeof props.editorRef === 'function') props.editorRef(node); else if (props.editorRef) props.editorRef.current = node },
5287
+ 'data-rw-editor-input': '', 'aria-label': props['aria-label'], value, wrap: props.wrap ? 'soft' : 'off',
5288
+ spellCheck: false, autoCorrect: 'off', autoCapitalize: 'off', autoComplete: 'off',
5289
+ onChange: publish, onSelect: props.onSelect,
5290
+ onScroll: event => { syncScroll(event.currentTarget); props.onScroll?.(event) },
5291
+ onCompositionStart: () => { compositionRef.current = true; setComposing(true) },
5292
+ onCompositionEnd: event => { compositionRef.current = false; setComposing(false); publish(event) },
5293
+ onKeyDown: event => {
5294
+ if (compositionRef.current || event.isComposing || event.nativeEvent?.isComposing) return
5295
+ if (event.key === 'Tab') { event.preventDefault(); indentSelection(event.currentTarget, event.shiftKey); return }
5296
+ props.onKeyDown?.(event)
5297
+ },
5298
+ style: { ...typography, position: 'absolute', inset: 0, width: '100%', height: '100%', padding: '10px 12px', boxSizing: 'border-box', border: 0, outline: 'none', margin: 0, resize: 'none', background: 'transparent', color: paintText ? 'transparent' : T.label, WebkitTextFillColor: paintText ? 'transparent' : T.label, caretColor: T.label, overflow: 'auto' },
5299
+ }),
5300
+ ),
5301
+ )
5302
+ }
5303
+
4980
5304
  const remoteDrafts = new Map()
4981
5305
  const pendingFileSaves = new Map()
4982
5306
  function RemoteFileTab(props) {
5307
+ const tr = (key, params) => workspaceText(key, props.scope?.sessionId, params)
4983
5308
  const { tab, scope } = props
4984
5309
  const path = tab.path || ''
4985
5310
  const fileSessionId = scope && scope.sessionId
4986
- const [data, setData] = React.useState(() => fileViewMemory.get(String(fileSessionId || '') + '\0' + path)?.data || null)
5311
+ const [data, setData] = React.useState(() => fileViewMemory.get(workspaceMemoryKey(fileSessionId) + '\0' + path)?.data || null)
4987
5312
  const [err, setErr] = React.useState('')
4988
5313
  const [loading, setLoading] = React.useState(true)
5314
+ const [localCopy, setLocalCopy] = React.useState(null)
5315
+ const [localPreview, setLocalPreview] = React.useState(null)
5316
+ const [copyBusy, setCopyBusy] = React.useState(false)
5317
+ const copyRequestRef = React.useRef(null)
5318
+ const copyGenerationRef = React.useRef(0)
4989
5319
  const [edit, setEdit] = React.useState(false)
4990
5320
  const [draft, setDraft] = React.useState('')
4991
5321
  const [saving, setSaving] = React.useState(false)
4992
- const draftKey = String(fileSessionId || '') + '\0' + path
5322
+ const draftKey = workspaceMemoryKey(fileSessionId) + '\0' + path
4993
5323
  const draftRecord = remoteDrafts.get(draftKey)
4994
5324
  const fileViewRef = React.useRef(draftKey)
4995
5325
  fileViewRef.current = draftKey
@@ -5000,7 +5330,7 @@ window.__ModuleLoader__.load({
5000
5330
  const remoteTerminal = useRemoteTerminal(fileSessionId)
5001
5331
  const cachedView = fileViewMemory.get(draftKey)
5002
5332
  const [wrap, setWrap] = React.useState(() => !!cachedView?.wrap)
5003
- const [sourceMode, setSourceMode] = React.useState(() => !!cachedView?.sourceMode)
5333
+ const [sourceMode, setSourceMode] = React.useState(() => cachedView?.sourceMode !== false)
5004
5334
  const [findOpen, setFindOpen] = React.useState(false)
5005
5335
  const [findQuery, setFindQuery] = React.useState('')
5006
5336
  const [findIndex, setFindIndex] = React.useState(0)
@@ -5013,14 +5343,14 @@ window.__ModuleLoader__.load({
5013
5343
  React.useEffect(() => () => { if (copyTimerRef.current) clearTimeout(copyTimerRef.current) }, [])
5014
5344
  React.useEffect(() => {
5015
5345
  const view = fileViewMemory.get(draftKey)
5016
- setWrap(!!view?.wrap); setSourceMode(!!view?.sourceMode)
5346
+ setWrap(!!view?.wrap); setSourceMode(view?.sourceMode !== false)
5017
5347
  setFindOpen(false); setFindQuery(''); setFindIndex(0)
5018
5348
  rememberRemoteSelection(fileSessionId, path)
5019
5349
  }, [draftKey])
5020
5350
  React.useEffect(() => { if (findOpen) { findRef.current?.focus(); findRef.current?.select() } }, [findOpen])
5021
5351
  React.useEffect(() => {
5022
5352
  if (loading || props.jumpLine) return
5023
- const node = scrollRef.current
5353
+ const node = editorRef.current || scrollRef.current
5024
5354
  const view = fileViewMemory.get(draftKey)
5025
5355
  if (node && view) { node.scrollTop = view.scrollTop || 0; node.scrollLeft = view.scrollLeft || 0 }
5026
5356
  }, [loading, draftKey])
@@ -5039,7 +5369,13 @@ window.__ModuleLoader__.load({
5039
5369
  }
5040
5370
  const showExplorer = () => {
5041
5371
  rememberRemoteSelection(fileSessionId, path)
5042
- if (SIDEBAR_RIGHT?.openTab) SIDEBAR_RIGHT.openTab(NATIVE_EXPLORER)
5372
+ if (remoteIdeState.enabled && SIDEBAR_RIGHT?.mounted?.getSnapshot?.() === fileSessionId) {
5373
+ const rows = document.querySelectorAll?.('[data-rw-ide-tree] [data-rw-tree-row]') || []
5374
+ const row = Array.from(rows).find(node => node.getAttribute('data-rw-tree-row') === path) || rows[0]
5375
+ row?.focus(); return
5376
+ }
5377
+ if (SIDEBAR_RIGHT?.openTabIn) SIDEBAR_RIGHT.openTabIn(fileSessionId, NATIVE_EXPLORER)
5378
+ else if (SIDEBAR_RIGHT?.openTab) SIDEBAR_RIGHT.openTab(NATIVE_EXPLORER)
5043
5379
  }
5044
5380
  const updateCursor = (node) => {
5045
5381
  const before = node.value.slice(0, node.selectionStart)
@@ -5050,7 +5386,7 @@ window.__ModuleLoader__.load({
5050
5386
  const saveTokenRef = React.useRef(null)
5051
5387
  const discardDraft = async (reload) => {
5052
5388
  if (dirty && !(await discardConfirm.ask(tr('file.discardConfirm')))) return
5053
- remoteDrafts.delete(draftKey); setEdit(false); setErr(''); setSaveConflict(false)
5389
+ remoteDrafts.delete(draftKey); setDraft(originalText); setEdit(!!data && !data.binary && !data.image && !data.truncated); setErr(''); setSaveConflict(false)
5054
5390
  if (reload === true) load()
5055
5391
  }
5056
5392
  const changeDraft = (text) => {
@@ -5079,27 +5415,57 @@ window.__ModuleLoader__.load({
5079
5415
  footnotes: tr('file.markdown.footnotes'),
5080
5416
  }
5081
5417
 
5082
- const originalText = (data && data.content != null ? data.content : '').replace(/\n…\[truncated:.*$/, '')
5418
+ const originalText = (data && data.content != null ? data.content : '').replace(/\n…\[truncated:.*$/, '').replace(/\r\n/g, '\n')
5083
5419
  const dirty = edit && draft !== originalText
5084
5420
 
5085
5421
  const load = () => {
5422
+ if (props.visible === false) return
5086
5423
  if (!path) { setLoading(false); return }
5087
5424
  let cancelled = false
5088
- setLoading(true); setErr(''); setData(fileViewMemory.get(draftKey)?.data || null); setEdit(false); setSaveConflict(false)
5425
+ const cached = fileViewMemory.get(draftKey)?.data || null
5426
+ const generation = ++copyGenerationRef.current; copyRequestRef.current = null
5427
+ setLocalCopy(null); setLocalPreview(null); setCopyBusy(false)
5428
+ setLoading(true); setErr(''); setData(cached); setEdit(!!cached && !cached.binary && !cached.image && !cached.truncated); setSaveConflict(false)
5429
+ setDraft(remoteDrafts.get(draftKey)?.text ?? String(cached?.content || '').replace(/\r\n/g, '\n'))
5089
5430
  readRemoteFile(path, 256 * 1024, fileSessionId)
5090
- .then((d) => { if (!cancelled && fileViewRef.current === draftKey) {
5431
+ .then((d) => { if (!cancelled && fileViewRef.current === draftKey && copyGenerationRef.current === generation) {
5091
5432
  keepView({ data: d }); setData(d); setLoading(false)
5092
5433
  const saved = remoteDrafts.get(draftKey)
5093
5434
  if (saved) { setDraft(saved.text); setEdit(true); setSaveConflict(!!d.truncated || (saved.baseMtime != null && d.mtime !== saved.baseMtime) || (saved.baseRevision != null && saved.baseRevision !== d.revision)) }
5435
+ else { setDraft(String(d.content || '').replace(/\r\n/g, '\n')); setEdit(!d.binary && !d.image && !d.truncated && typeof d.content === 'string') }
5436
+ } })
5437
+ .catch((e) => { if (!cancelled && fileViewRef.current === draftKey && copyGenerationRef.current === generation) {
5438
+ if (e?.code === 'REMOTE_FILE_MISSING_LOCAL_COPY' && e.localCopy?.available) {
5439
+ setLocalCopy(e.localCopy); setData(null); setEdit(false); keepView({ data: null }); setErr('')
5440
+ } else setErr(String((e && e.message) || e))
5441
+ setLoading(false)
5094
5442
  } })
5095
- .catch((e) => { if (!cancelled && fileViewRef.current === draftKey) { setErr(String((e && e.message) || e)); setLoading(false) } })
5096
5443
  return () => { cancelled = true }
5097
5444
  }
5098
- React.useEffect(load, [path, fileSessionId, props.navigationRevision])
5445
+ React.useEffect(load, [path, fileSessionId, props.navigationRevision, props.visible])
5446
+
5447
+ const recoverLocalCopy = async (publish) => {
5448
+ if (!fileSessionId || copyRequestRef.current || (publish && !localPreview?.localRevision)) return
5449
+ const request = { key: draftKey, generation: copyGenerationRef.current }
5450
+ const isCurrent = () => fileViewRef.current === draftKey && copyRequestRef.current === request && copyGenerationRef.current === request.generation
5451
+ copyRequestRef.current = request
5452
+ setCopyBusy(true); setErr('')
5453
+ try {
5454
+ const result = await api('POST', '/dsh-remote/local-copy/' + (publish ? 'publish' : 'read'),
5455
+ withSessionBody({ path, ...(publish ? { expectedLocalRevision: localPreview.localRevision } : {}) }, fileSessionId))
5456
+ if (!isCurrent()) return
5457
+ if (publish) { setLocalCopy(null); setLocalPreview(null); load() }
5458
+ else setLocalPreview(result)
5459
+ } catch (error) {
5460
+ if (isCurrent()) setErr(String(error?.message || error))
5461
+ } finally {
5462
+ if (isCurrent()) { copyRequestRef.current = null; setCopyBusy(false) }
5463
+ }
5464
+ }
5099
5465
 
5100
5466
  const startEdit = () => {
5101
5467
  if (!data || data.binary || data.image || data.truncated) return
5102
- setDraft((data.content != null ? data.content : '').replace(/\n…\[truncated:.*$/, ''))
5468
+ setDraft((data.content != null ? data.content : '').replace(/\n…\[truncated:.*$/, '').replace(/\r\n/g, '\n'))
5103
5469
  setEdit(true); setErr(''); setSaveConflict(false)
5104
5470
  }
5105
5471
  const saveRemote = () => {
@@ -5127,7 +5493,7 @@ window.__ModuleLoader__.load({
5127
5493
  if (fileViewRef.current !== draftKey) return
5128
5494
  setCopyNote(tr(newerDraft ? 'workbench.savedWithDraft' : 'workbench.saved'))
5129
5495
  if (newerDraft) { setData(savedData); setDraft(latest.text); setEdit(true); setSaveConflict(false) }
5130
- else { setEdit(false); load() }
5496
+ else { setData(savedData); setDraft(submittedText); setEdit(true); setSaveConflict(false) }
5131
5497
  })
5132
5498
  .catch((e) => { if (fileViewRef.current === draftKey) setErr(String((e && e.message) || e)) })
5133
5499
  .finally(() => { if (pendingFileSaves.get(draftKey) === request) pendingFileSaves.delete(draftKey); if (saveTokenRef.current === draftKey) saveTokenRef.current = null; if (fileViewRef.current === draftKey) setSaving(false) })
@@ -5160,6 +5526,7 @@ window.__ModuleLoader__.load({
5160
5526
  if (!findOpen || !activeMatch) return
5161
5527
  if (edit && editorRef.current) {
5162
5528
  editorRef.current.setSelectionRange(activeMatch.start, activeMatch.end)
5529
+ editorRef.current.dshScrollToLine?.(activeMatch.line)
5163
5530
  } else {
5164
5531
  scrollRef.current?.querySelector('[data-line="' + activeMatch.line + '"]')?.scrollIntoView({ block: 'center' })
5165
5532
  }
@@ -5180,15 +5547,15 @@ window.__ModuleLoader__.load({
5180
5547
  React.createElement(WorkbenchAction, { icon: 'terminal', label: tr('workbench.openTerminal'), disabled: remoteTerminal.pending, onClick: remoteTerminal.open }),
5181
5548
  edit ? React.createElement(React.Fragment, null,
5182
5549
  React.createElement('button', { type: 'button', className: 'dsh-rw-btn dsh-rw-primary', style: { ...primaryBtnS, padding: '4px 10px', fontSize: 12 }, onClick: saveRemote, disabled: saving || !dirty || saveConflict, title: tr('file.saveHint') }, saving ? tr('file.saving') : tr('file.saveToRemote')),
5183
- React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '4px 8px', fontSize: 12 }, onClick: () => discardDraft(false) }, tr('file.cancel')))
5184
- : React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '4px 10px', fontSize: 12 }, onClick: startEdit, disabled: loading || !data || data.binary || data.image || data.truncated, title: data && data.truncated ? tr('file.incompletePreview') : tr('file.edit') }, tr('file.edit')),
5550
+ React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '4px 8px', fontSize: 12 }, onClick: () => discardDraft(false), disabled: !dirty || saving }, tr('file.discardChanges')))
5551
+ : React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '4px 10px', fontSize: 12 }, onClick: startEdit, disabled: loading || !!localCopy || !data || data.binary || data.image || data.truncated, title: data && data.truncated ? tr('file.incompletePreview') : tr('file.edit') }, tr('file.edit')),
5185
5552
  ),
5186
5553
  React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 6, padding: '4px 10px', borderBottom: '1px solid ' + T.border } },
5187
5554
  React.createElement(WorkbenchAction, { icon: 'folder', label: tr('workbench.backToFiles'), onClick: showExplorer }),
5188
5555
  React.createElement('span', { className: 'dsh-rw-path', style: { flex: 1 }, title: path }, path),
5189
5556
  React.createElement(WorkbenchAction, { icon: 'copy', label: tr('workbench.copyPath'), onClick: () => copy(path) }),
5190
- !edit ? React.createElement(WorkbenchAction, { icon: 'refresh', label: tr('explorer.refresh'), disabled: loading, onClick: load }) : null,
5191
- isMarkdown && !edit ? React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '3px 8px', fontSize: 11 }, onClick: () => { setSourceMode(!sourceMode); keepView({ sourceMode: !sourceMode }) } }, sourceMode ? tr('workbench.preview') : tr('workbench.source')) : null),
5557
+ React.createElement(WorkbenchAction, { icon: 'refresh', label: tr('explorer.refresh'), disabled: loading || saving, onClick: load }),
5558
+ isMarkdown ? React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, padding: '3px 8px', fontSize: 11 }, onClick: () => { setSourceMode(!sourceMode); keepView({ sourceMode: !sourceMode }) } }, sourceMode ? tr('workbench.preview') : tr('workbench.source')) : null),
5192
5559
  findOpen ? React.createElement('div', { style: { display: 'flex', gap: 4, alignItems: 'center', padding: '6px 10px', borderBottom: '1px solid ' + T.border, background: T.bg } },
5193
5560
  React.createElement('input', { ref: findRef, className: 'dsh-rw-input', 'aria-label': tr('workbench.find'), placeholder: tr('workbench.find'), value: findQuery, onChange: (e) => setFindQuery(e.target.value), onKeyDown: (e) => {
5194
5561
  if (e.isComposing) return
@@ -5203,36 +5570,41 @@ window.__ModuleLoader__.load({
5203
5570
  tr('file.conflictHelp'),
5204
5571
  React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, marginLeft: 8 }, onClick: () => copyToClipboard(draft) }, tr('file.copyDraft')),
5205
5572
  React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, marginLeft: 8 }, onClick: () => discardDraft(true) }, tr('file.discardReload'))) : null,
5573
+ localCopy ? React.createElement('div', { 'data-rw-local-copy-recovery': '', role: 'status', 'aria-busy': copyBusy, style: { padding: '12px', borderBottom: '1px solid ' + T.border, fontSize: 12, lineHeight: 1.6, background: T.bg } },
5574
+ React.createElement('strong', null, tr('file.localCopyMissing')),
5575
+ React.createElement('div', { style: { color: T.muted, marginTop: 4 } }, tr('file.localCopyHelp')),
5576
+ copyBusy ? React.createElement('div', { style: { marginTop: 4, color: T.muted } }, tr('file.loading')) : null,
5577
+ React.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 10 } },
5578
+ React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: buttonS, disabled: copyBusy, onClick: () => recoverLocalCopy(false) }, tr('file.localCopyView')),
5579
+ localPreview?.localRevision ? React.createElement('button', { type: 'button', className: 'dsh-rw-btn dsh-rw-primary', style: primaryBtnS, disabled: copyBusy, onClick: () => recoverLocalCopy(true) }, tr('file.localCopyPublish')) : null)) : null,
5206
5580
  discardConfirm.node,
5207
5581
  React.createElement('div', { ref: scrollRef, className: wrap ? 'dsh-rw-code-wrap' : '', onScroll: (e) => keepView({ scrollTop: e.currentTarget.scrollTop, scrollLeft: e.currentTarget.scrollLeft }), style: { flex: 1, overflow: 'auto', minHeight: 0, display: 'flex', flexDirection: 'column', position: 'relative' } },
5208
5582
  err ? React.createElement('div', { style: { color: T.danger, padding: '8px 12px', fontSize: 13, flexShrink: 0 } }, err, !edit ? React.createElement('button', { type: 'button', className: 'dsh-rw-btn', style: { ...buttonS, marginLeft: 8 }, onClick: load }, tr('project.retry')) : null) : null,
5209
- loading && !data ? React.createElement('div', { style: { opacity: 0.7, padding: 12, fontSize: 13 } }, tr('file.loading'))
5583
+ localPreview ? React.createElement('div', { 'data-rw-local-copy-preview': '', style: { padding: 12 } },
5584
+ React.createElement('div', { style: { color: T.warn, fontSize: 12, marginBottom: 12 } }, tr('file.localCopySource')),
5585
+ String(localPreview.content || '').length > 300000 || String(localPreview.content || '').split('\n', 10002).length > 10000
5586
+ ? React.createElement('pre', { 'data-rw-local-copy-large': '', tabIndex: 0, style: { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', fontSize: 13, lineHeight: 1.55, whiteSpace: wrap ? 'pre-wrap' : 'pre', margin: 0, tabSize: 2 } }, localPreview.content || '')
5587
+ : React.createElement(CodeView, { code: localPreview.content || '', path, wrap }))
5588
+ : loading && !data ? React.createElement('div', { style: { opacity: 0.7, padding: 12, fontSize: 13 } }, tr('file.loading'))
5210
5589
  : (data && data.binary
5211
5590
  ? React.createElement('div', { style: { padding: 12, fontSize: 13, color: T.warn } },
5212
5591
  tr('file.binary', { size: (data.size != null ? data.size + ' bytes' : tr('file.unknownSize')) }))
5213
5592
  : data && data.image
5214
5593
  ? React.createElement('div', { style: { flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 12, minHeight: 0 } },
5215
5594
  React.createElement('img', { src: `data:${data.mime};base64,${data.content}`, alt: baseName, style: { maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' } }))
5216
- : (edit
5217
- ? React.createElement('textarea', {
5218
- ref: editorRef, 'aria-label': tr('file.edit') + ' ' + baseName,
5219
- onSelect: (e) => updateCursor(e.currentTarget),
5220
- value: draft,
5221
- onChange: (e) => { changeDraft(e.target.value); updateCursor(e.target) },
5222
- onKeyDown: (e) => {
5223
- if (e.isComposing) return
5224
- if (e.key === 'Tab') {
5225
- e.preventDefault()
5226
- const node = e.currentTarget
5227
- const result = indentRemoteDraft(draft, node.selectionStart, node.selectionEnd, e.shiftKey)
5228
- changeDraft(result.text)
5229
- setTimeout(() => { node.setSelectionRange(result.start, result.end); updateCursor(node) }, 0)
5230
- }
5231
- if ((e.metaKey || e.ctrlKey) && e.key === 's') { e.preventDefault(); if (!e.isComposing && !saving && dirty && !saveConflict) saveRemote() }
5232
- if (e.key === 'Escape') { e.preventDefault(); e.currentTarget.blur() }
5595
+ : (edit && (!isMarkdown || sourceMode)
5596
+ ? React.createElement(HighlightedEditor, {
5597
+ editorRef, path, wrap, indent: indentRemoteDraft, 'aria-label': tr('file.edit') + ' ' + baseName,
5598
+ value: draft, jumpLine: props.jumpLine || null, jumpRevision: props.navigationRevision,
5599
+ matchingLines: findOpen ? matches.map(match => match.line) : [], currentMatchLine: findOpen && activeMatch ? activeMatch.line : null,
5600
+ onSelect: event => updateCursor(event.currentTarget),
5601
+ onChange: event => { changeDraft(event.target.value); updateCursor(event.target) },
5602
+ onScroll: event => keepView({ scrollTop: event.currentTarget.scrollTop, scrollLeft: event.currentTarget.scrollLeft }),
5603
+ onKeyDown: event => {
5604
+ if (event.isComposing || event.nativeEvent?.isComposing) return
5605
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') { event.preventDefault(); if (!saving && dirty && !saveConflict) saveRemote() }
5606
+ if (event.key === 'Escape') { event.preventDefault(); event.currentTarget.blur() }
5233
5607
  },
5234
- spellCheck: false,
5235
- style: { width: '100%', height: '100%', flex: 1, boxSizing: 'border-box', border: 'none', outline: 'none', resize: 'none', background: 'transparent', color: T.label, fontSize: 13, lineHeight: 1.55, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace', padding: '10px 12px', whiteSpace: wrap ? 'pre-wrap' : 'pre', overflowWrap: wrap ? 'anywhere' : 'normal' },
5236
5608
  })
5237
5609
  : (isMarkdown && !sourceMode && MarkdownText
5238
5610
  // Render remote markdown with the host renderer instead of a
@@ -5246,9 +5618,9 @@ window.__ModuleLoader__.load({
5246
5618
  fontSize: 13, lineHeight: 1.55, fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
5247
5619
  whiteSpace: 'pre-wrap', wordBreak: 'break-word', color: T.label,
5248
5620
  },
5249
- }, originalText),
5621
+ }, edit ? draft : originalText),
5250
5622
  },
5251
- React.createElement(MarkdownText, { text: originalText, variant: 'body', labels: markdownLabels })),
5623
+ React.createElement(MarkdownText, { text: edit ? draft : originalText, variant: 'body', labels: markdownLabels })),
5252
5624
  (data && data.truncated)
5253
5625
  ? React.createElement('div', { style: { color: T.warn, fontSize: 12, marginTop: 8 } }, tr('file.truncated'))
5254
5626
  : null)
@@ -5267,7 +5639,7 @@ window.__ModuleLoader__.load({
5267
5639
  React.createElement('span', {}, data && data.size != null ? humanSize(data.size) : ''),
5268
5640
  React.createElement('span', {}, baseName.includes('.') ? baseName.split('.').pop().toUpperCase() : 'TEXT'),
5269
5641
  data?.eol ? React.createElement('span', {}, data.eol === 'crlf' ? 'CRLF' : data.eol === 'mixed' ? tr('file.mixedEol') : 'LF') : null,
5270
- React.createElement('span', { style: { marginLeft: 'auto', color: copyNote ? T.ok : T.muted } }, copyNote || (loading && data ? tr('workbench.refreshing') : edit ? tr('file.editing') : tr('file.readonly')))),
5642
+ React.createElement('span', { style: { marginLeft: 'auto', color: copyNote ? T.ok : T.muted } }, copyNote || (localPreview ? tr('file.localCopySource') : loading && data ? tr('workbench.refreshing') : edit ? tr('file.editing') : tr('file.readonly')))),
5271
5643
  )
5272
5644
  }
5273
5645
 
@@ -5286,7 +5658,7 @@ window.__ModuleLoader__.load({
5286
5658
  try {
5287
5659
  disposers.push(bs.registerTab({
5288
5660
  id: SIDEBAR_EXPLORER_ID,
5289
- title: () => tr('explorer.tabTitle'),
5661
+ title: () => tr('workspace.files'),
5290
5662
  icon: (size) => React.createElement('span', { style: { fontSize: (size || 14), lineHeight: 1 } }, '🌐'),
5291
5663
  order: 55,
5292
5664
  single: true,
@@ -5345,6 +5717,7 @@ window.__ModuleLoader__.load({
5345
5717
  const NATIVE_EXPLORER = 'dsh-remote/explorer'
5346
5718
  const NATIVE_FILE = 'dsh-remote/file'
5347
5719
  const NATIVE_CHANGES = 'dsh-remote/changes'
5720
+ const NATIVE_WELCOME = 'dsh-remote/welcome'
5348
5721
  // Issue #55: the address the CORE emits for a file link, which is NOT the
5349
5722
  // one this plugin mints for its own explorer. A model-emitted
5350
5723
  // `[x](src/main.c)` (or a `@src/main.c` chip) is turned into
@@ -5457,6 +5830,28 @@ window.__ModuleLoader__.load({
5457
5830
  if (/^[A-Za-z]:/.test(relBody) || /^\//.test(relBody)) return toRemote(relBody)
5458
5831
  return remoteRoot + remoteSep + toRemote(relBody)
5459
5832
  }
5833
+ function localPathForCoreAddress(parsed, cwd) {
5834
+ if (!localWorkspaceSession(parsed.sessionId)) return null
5835
+ const root = String(cwd || '').replace(/[\\/]+$/, '') || '/'
5836
+ const win = /^(?:[a-z]:|\\\\)/i.test(root)
5837
+ const value = String(parsed.path || '')
5838
+ const absolute = /^(?:[a-z]:[\\/]|[\\/])/i.test(value) ? value : joinRemote(root, value)
5839
+ const canonical = text => {
5840
+ const parts = []
5841
+ for (const part of (win ? text.replace(/\\/g, '/') : text).split('/')) {
5842
+ if (part === '.') continue
5843
+ if (part === '..') { if (parts.length > 1) parts.pop() }
5844
+ else parts.push(part)
5845
+ }
5846
+ const result = parts.join('/').replace(/\/$/, '') || '/'
5847
+ return win ? result.toLowerCase() : result
5848
+ }
5849
+ const base = canonical(root), target = canonical(absolute)
5850
+ return target === base || target.startsWith(base === '/' ? '/' : base + '/') ? absolute : null
5851
+ }
5852
+ function workspacePathForCoreAddress(parsed, cwd) {
5853
+ return remotePathForCoreAddress(parsed, cwd) || (remoteIdeState.enabled ? localPathForCoreAddress(parsed, cwd) : null)
5854
+ }
5460
5855
  function NativeExplorer(props) {
5461
5856
  const info = props.useTabInfo()
5462
5857
  const [expanded, setExpanded] = React.useState(() => explorerMemory.get(props.sessionId)?.expanded || [])
@@ -5474,7 +5869,7 @@ window.__ModuleLoader__.load({
5474
5869
  function NativeFile(props) {
5475
5870
  const info = props.useTabInfo()
5476
5871
  const path = remoteFilePath(info.tab.navigation.address)
5477
- return React.createElement(RemoteFileTab, { key: path, tab: { path }, scope: { sessionId: props.sessionId }, jumpLine: Number.isSafeInteger(info.tab.navigation.params?.line) && info.tab.navigation.params.line > 0 ? info.tab.navigation.params.line : null, navigationRevision: info.tab.navigation.revision })
5872
+ return React.createElement(RemoteFileTab, { key: path, tab: { path }, scope: { sessionId: props.sessionId }, visible: info.tab.visible, jumpLine: Number.isSafeInteger(info.tab.navigation.params?.line) && info.tab.navigation.params.line > 0 ? info.tab.navigation.params.line : null, navigationRevision: info.tab.navigation.revision })
5478
5873
  }
5479
5874
  /**
5480
5875
  * The body for a CORE file link in a remote Session (issue #55).
@@ -5493,7 +5888,7 @@ window.__ModuleLoader__.load({
5493
5888
  // Resolve from the current navigation on every render. Keeping only an
5494
5889
  // initial path in state made same-tab navigation continue reading the old file.
5495
5890
  const [, invalidate] = React.useState(0)
5496
- const remotePath = parsed ? remotePathForCoreAddress(parsed, sessionCwdFor(sessionId)) : null
5891
+ const remotePath = parsed ? workspacePathForCoreAddress(parsed, sessionCwdFor(sessionId)) : null
5497
5892
  React.useEffect(() => {
5498
5893
  const changed = () => invalidate((version) => version + 1)
5499
5894
  mirrorWatchers.add(changed)
@@ -5524,7 +5919,7 @@ window.__ModuleLoader__.load({
5524
5919
  return React.createElement(RemoteFileTab, {
5525
5920
  key: remotePath,
5526
5921
  tab: { path: remotePath },
5527
- scope: { sessionId },
5922
+ scope: { sessionId }, visible: info.tab.visible,
5528
5923
  // Current hosts pass line numbers as navigation params; retain support
5529
5924
  // for older address-carried anchors. Invalid params must not mask them.
5530
5925
  jumpLine: (parsed && parsed.line) || paramsLine || null,
@@ -5542,8 +5937,9 @@ window.__ModuleLoader__.load({
5542
5937
  } catch { return '' }
5543
5938
  }
5544
5939
  // The shipped workspace-files command opens kind "files". Route that
5545
- // intent before navigation, using the captured session's binding; retain
5546
- // the host's original page for local sessions and every other kind.
5940
+ // intent before navigation, using the captured session's binding. Proven
5941
+ // local projects now share this explorer; unknown roots and other kinds
5942
+ // retain the host's original routing.
5547
5943
  function routeWorkspaceFiles(sidebar) {
5548
5944
  const originals = new Map(), pending = new Map()
5549
5945
  let disposed = false
@@ -5563,7 +5959,7 @@ window.__ModuleLoader__.load({
5563
5959
  if (sessionIndex == null && sidebar.mounted?.getSnapshot?.() !== sessionId) return
5564
5960
  const remote = mirrorForCwd(sessionCwdFor(sessionId), MIRRORS.list)
5565
5961
  const next = args.slice()
5566
- next[kindIndex] = remote ? NATIVE_EXPLORER : kind
5962
+ next[kindIndex] = remote || localWorkspaceSession(sessionId) ? NATIVE_EXPLORER : kind
5567
5963
  return Reflect.apply(original, owner, next)
5568
5964
  }
5569
5965
  if (MIRRORS.loaded) return open()
@@ -5625,8 +6021,8 @@ window.__ModuleLoader__.load({
5625
6021
  if (previous) { try { previous() } catch { /* already released */ } }
5626
6022
  disposeExplorer = tabs.register({
5627
6023
  id: NATIVE_EXPLORER, kind: NATIVE_EXPLORER,
5628
- title: () => tr('explorer.tabTitle'),
5629
- ...(withGuide ? { guide: [{ order: 55, title: () => tr('explorer.tabTitle') }] } : {}),
6024
+ title: () => tr('workspace.files'),
6025
+ ...(withGuide ? { guide: [{ order: 55, title: () => tr('workspace.files') }] } : {}),
5630
6026
  })
5631
6027
  guideListed = withGuide
5632
6028
  }
@@ -5653,9 +6049,10 @@ window.__ModuleLoader__.load({
5653
6049
  try { syncExplorerType() } catch (e) { console.warn('[dsh-remote] start-page card handover skipped:', e) }
5654
6050
  }, 'dsh-remote.start-card-owner')
5655
6051
  })
5656
- inner.effect(() => tabs.register({ id: NATIVE_CHANGES, kind: NATIVE_CHANGES, title: () => tr('changes.title') }), 'dsh-remote.native-changes-type')
6052
+ inner.effect(() => tabs.register({ id: NATIVE_WELCOME, kind: NATIVE_WELCOME, title: () => tr('ide.welcome') }), 'dsh-remote.native-welcome-type')
6053
+ inner.effect(() => tabs.register({ id: NATIVE_CHANGES, kind: NATIVE_CHANGES, title: () => tr('workspace.git') }), 'dsh-remote.native-changes-type')
5657
6054
  inner.effect(() => tabs.register({
5658
- id: NATIVE_FILE, kind: NATIVE_FILE,
6055
+ id: NATIVE_FILE, kind: NATIVE_FILE, keepMounted: true,
5659
6056
  patterns: ['dsh-resource://dsh-remote/**'],
5660
6057
  title: (address) => remoteFilePath(address).split(/[\\/]/).pop() || tr('explorer.tabTitle'),
5661
6058
  }), 'dsh-remote.native-file-type')
@@ -5665,10 +6062,9 @@ window.__ModuleLoader__.load({
5665
6062
  // `dsh-resource://file/**` in the `fallback` band and reads locally.
5666
6063
  // better-sidebar also registers an extension-band editor, so the more
5667
6064
  // specific session/** pattern below must win the pattern-length tie-break.
5668
- // `canOpen` is the safety guard: it must return true ONLY for a
5669
- // session whose cwd is PROVEN to be a remote mirror. Local sessions, and
5670
- // a page load before the mirror registry has arrived, fall through to the
5671
- // built-in preview and behave exactly as they did before.
6065
+ // `canOpen` guards execution-world selection. Proven remote links use
6066
+ // SFTP; in IDE mode, project-scoped local links share this editor. Other
6067
+ // local links and cold/unknown contexts retain the native host viewer.
5672
6068
  //
5673
6069
  // Registration is wrapped because the address-claiming half of this
5674
6070
  // contract (`patterns` + `canOpen`) is not something every DSH line
@@ -5679,7 +6075,7 @@ window.__ModuleLoader__.load({
5679
6075
  inner.effect(() => {
5680
6076
  try {
5681
6077
  const dispose = tabs.register({
5682
- id: NATIVE_LINK, kind: NATIVE_LINK,
6078
+ id: NATIVE_LINK, kind: NATIVE_LINK, keepMounted: true,
5683
6079
  // Specificity beats bundle order: the registry ranks longest-glob-first,
5684
6080
  // and ties fall to registration order (which we do not control). Another
5685
6081
  // extension claiming `dsh-resource://file/**` used to win those ties and
@@ -5695,12 +6091,12 @@ window.__ModuleLoader__.load({
5695
6091
  // file that was never synced dies with ENOENT and shows nothing at
5696
6092
  // all. This editor opens the file over SFTP and RENDERS it via the
5697
6093
  // host's MarkdownText (source only when the primitive is missing),
5698
- // so claiming is no longer a downgrade. Local sessions still fall
5699
- // through: their cwd is not a mirror, proven below.
6094
+ // so claiming is no longer a downgrade. Local project links also
6095
+ // share the editor when IDE mode is enabled, proven below.
5700
6096
  const cwd = sessionCwdFor(parsed.sessionId)
5701
6097
  // `MIRRORS.loaded` is checked so a cold start NEVER steals a local
5702
- // link: an empty registry cannot prove a mirror, and guessing would
5703
- // break the text preview for every local session.
6098
+ // link: only a successfully loaded registry can distinguish a
6099
+ // local project from a mirror.
5704
6100
  if (!cwd || !MIRRORS.loaded) return false
5705
6101
  // Ask the SAME resolver the body uses, not merely whether the cwd
5706
6102
  // is a mirror. A remote session can cite a LOCAL absolute path
@@ -5708,7 +6104,7 @@ window.__ModuleLoader__.load({
5708
6104
  // the old check claimed it here, then NativeRemoteLink rejected it
5709
6105
  // and showed file.linkUnresolved. Refusing it here hands the address
5710
6106
  // back to the built-in LOCAL editor, which is the correct owner.
5711
- return !!remotePathForCoreAddress(parsed, cwd)
6107
+ return !!workspacePathForCoreAddress(parsed, cwd)
5712
6108
  },
5713
6109
  title: (address) => {
5714
6110
  const parsed = parseCoreFileAddress(address)
@@ -5727,6 +6123,7 @@ window.__ModuleLoader__.load({
5727
6123
  slots.register({ name: 'sidebar.right.pane.tab', key: NATIVE_EXPLORER }, NativeExplorer),
5728
6124
  slots.register({ name: 'sidebar.right.pane.tab', key: NATIVE_FILE }, NativeFile),
5729
6125
  slots.register({ name: 'sidebar.right.pane.tab', key: NATIVE_CHANGES }, NativeChanges),
6126
+ slots.register({ name: 'sidebar.right.pane.tab', key: NATIVE_WELCOME }, RemoteIdeWelcome),
5730
6127
  ]
5731
6128
  // Only register the link body when its type was accepted: a body under a
5732
6129
  // kind nothing claims would never render, and on a build that rejected
@@ -5755,6 +6152,7 @@ window.__ModuleLoader__.load({
5755
6152
  }
5756
6153
 
5757
6154
  function RemoteGitTab(props) {
6155
+ const tr = (key, params) => workspaceText(key, props.sessionId, params)
5758
6156
  const key = String(props.sessionId || '')
5759
6157
  const initial = gitViewMemory.get(key)
5760
6158
  const [git, setGit] = React.useState({ key, data: null, error: '', busy: false, revision: 0 })
@@ -6087,7 +6485,7 @@ window.__ModuleLoader__.load({
6087
6485
  function RemoteIdeToggle(props) {
6088
6486
  const mirror = useSessionMirror(props.sessionId, props.useSessions)
6089
6487
  const state = useRemoteIdeState()
6090
- if (!mirror) return null
6488
+ if (!mirror && !localWorkspaceSession(props.sessionId)) return null
6091
6489
  const supported = !!remoteIdeController?.mounted?.getSnapshot && typeof remoteIdeController.openResourceIn === 'function'
6092
6490
  return React.createElement('button', {
6093
6491
  type: 'button', 'data-rw-ide-toggle': '', 'aria-pressed': state.enabled,
@@ -6121,12 +6519,38 @@ window.__ModuleLoader__.load({
6121
6519
  [data-rw-ide-navigation]{display:flex;gap:3px}
6122
6520
  [data-rw-ide-navigation] button[aria-pressed=true]{background:var(--dsw-alias-interactive-bg-hover,#eee);font-weight:600}
6123
6521
  @media(max-width:600px){[data-rw-ide-header]{gap:5px;padding:0 6px}[data-rw-ide-title]{display:none}[data-rw-ide-header] button{font-size:11px!important;padding:4px 6px!important}}
6522
+ /* Reversible IDE-only header adapter for DSH 0.2.1/0.2.2.
6523
+ * Uses published slot/DOM markers rather than compiled class names.
6524
+ * Removing data-rw-ide-chat restores all native host styles automatically. */
6525
+ [data-rw-ide-chat] header[data-window-drag]{display:flex!important;flex-direction:column!important;flex:none!important;gap:0!important;min-height:0!important;height:auto!important;padding:10px 12px 0!important;box-sizing:border-box!important;overflow:visible!important}
6526
+ [data-rw-ide-chat] header[data-window-drag] div:has(>[data-conversation-header-corner]){display:grid!important;grid-template-columns:minmax(0,1fr) auto!important;grid-template-rows:auto auto!important;align-items:start!important;gap:6px 4px!important;min-width:0!important;width:100%!important;padding:0!important;min-height:0!important;container-type:normal!important}
6527
+ [data-rw-ide-chat] header[data-window-drag] div:has(>nav){display:flex!important;flex-direction:column!important;align-items:stretch!important;gap:5px!important;grid-column:1!important;grid-row:1!important;min-width:0!important;max-width:100%!important;margin:0!important;padding:0!important;mask-image:none!important;overflow:visible!important}
6528
+ [data-rw-ide-chat] header[data-window-drag] nav{display:flex!important;min-width:0!important;max-width:100%!important;overflow:hidden!important}
6529
+ [data-rw-ide-chat] header[data-window-drag] nav>span{min-width:0!important;max-width:100%!important;flex-shrink:1!important}
6530
+ [data-rw-ide-chat] header[data-window-drag] nav>span>span:last-child{min-width:0!important;max-width:100%!important;overflow:hidden!important;text-overflow:ellipsis!important;white-space:nowrap!important}
6531
+ [data-rw-ide-chat] header[data-window-drag] div:has(>[data-slot="conversation.session.header.actions"]){display:flex!important;flex-wrap:wrap!important;gap:5px!important;align-items:center!important;min-width:0!important;max-width:100%!important;margin:0!important;padding:0!important}
6532
+ [data-rw-ide-chat] header[data-window-drag] div:has(>[data-slot="conversation.session.header.utilities"]){display:flex!important;flex-wrap:wrap!important;align-items:center!important;gap:5px!important;grid-column:1/-1!important;grid-row:2!important;min-width:0!important;max-width:100%!important;margin:0!important;padding:0!important}
6533
+ [data-rw-ide-chat] header[data-window-drag] [data-dsh-remote-chip]{max-width:100%!important;min-width:0!important;flex-shrink:1!important}
6534
+ [data-rw-ide-chat] [data-conversation-header-corner]{grid-column:2!important;grid-row:1!important;align-self:start!important;min-width:0!important;margin:0!important;padding:0!important}
6535
+ [data-rw-ide-chat] header[data-window-drag] div:has(>[data-conversation-tabs]){display:flex!important;flex-wrap:nowrap!important;align-items:flex-end!important;gap:8px!important;min-width:0!important;width:100%!important;margin:6px 0 0!important;padding:0!important;min-height:32px!important;position:relative!important}
6536
+ [data-rw-ide-chat] [data-conversation-tabs]{display:flex!important;flex-wrap:nowrap!important;align-items:stretch!important;gap:16px!important;flex:1!important;min-width:0!important;max-width:100%!important;overflow-x:auto!important;scrollbar-width:none!important}
6537
+ [data-rw-ide-chat] [data-conversation-tabs]>[role="tab"]{flex:none!important;min-height:32px!important;margin:0!important;padding:7px 2px 8px!important;box-sizing:border-box!important}
6538
+ [data-rw-ide-chat] header[data-window-drag] button{max-width:100%}
6539
+ /* The shell already has a persistent Return to standard mode action. */
6540
+ [data-rw-ide-chat] [data-rw-ide-toggle]{display:none!important}
6541
+
6542
+ /* Keep the default conversation header compact; preserve every extension
6543
+ * action behind the shell's explicit Chat tools disclosure. */
6544
+ [data-rw-ide-chat]:not([data-rw-ide-tools-expanded]) header[data-window-drag] div:has(>[data-slot="conversation.session.header.actions"]),
6545
+ [data-rw-ide-chat]:not([data-rw-ide-tools-expanded]) header[data-window-drag] div:has(>[data-slot="conversation.session.header.utilities"]){display:none!important}
6546
+ [data-rw-ide-chat]:not([data-rw-ide-tools-expanded]) header[data-window-drag] div:has(>[data-conversation-header-corner]){grid-template-rows:auto!important}
6547
+
6124
6548
  `
6125
6549
  // Returns a disposer that restores only the attributes/variables we own.
6126
6550
  // No innerHTML, appendChild, React portal, clone or second conversation.
6127
6551
  function remoteIdeDock(node, kind) {
6128
6552
  const marker = 'data-rw-ide-' + kind
6129
- const names = [marker, 'data-rw-ide-hidden', 'inert']
6553
+ const names = [marker, 'data-rw-ide-hidden', 'data-rw-ide-tools-expanded', 'inert']
6130
6554
  const attrs = names.map(name => [name, node.getAttribute(name)])
6131
6555
  const vars = ['--rw-ide-x', '--rw-ide-y', '--rw-ide-w', '--rw-ide-h']
6132
6556
  const values = vars.map(name => [name, node.style.getPropertyValue(name), node.style.getPropertyPriority(name)])
@@ -6153,19 +6577,47 @@ window.__ModuleLoader__.load({
6153
6577
  },
6154
6578
  }
6155
6579
  }
6580
+ function RemoteIdeWelcome() {
6581
+ const tr = (key, params) => workspaceText(key, remoteIdeController?.mounted?.getSnapshot?.(), params)
6582
+ return React.createElement('article', { 'data-rw-ide-welcome': '', style: { boxSizing: 'border-box', width: '100%', minHeight: '100%', padding: 'clamp(24px,5vw,64px)', color: T.label, overflowWrap: 'anywhere' } },
6583
+ React.createElement('div', { style: { maxWidth: 560, margin: 'auto' } },
6584
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, color: T.muted, fontSize: 12, marginBottom: 14 } }, React.createElement(WorkbenchIcon, { name: 'remote', size: 24 }), 'dsh / remote'),
6585
+ React.createElement('h1', { style: { fontSize: 'clamp(20px,2vw,28px)', lineHeight: 1.4, fontWeight: 600, margin: '0 0 10px' } }, tr('ide.welcomeTitle')),
6586
+ React.createElement('p', { style: { fontSize: 13, lineHeight: 1.7, margin: '0 0 32px', color: T.muted } }, tr('ide.welcomeHint')),
6587
+ React.createElement('div', { style: { display: 'grid', gap: 24 } }, ['Files','Edit','Agent','Layout'].map((key, index) => React.createElement('section', { key, style: { display: 'flex', gap: 14 } },
6588
+ React.createElement('span', { 'aria-hidden': true, style: { color: T.muted, fontFamily: 'monospace', fontSize: 12, paddingTop: 2 } }, String(index + 1).padStart(2, '0')),
6589
+ React.createElement('div', {}, React.createElement('h2', { style: { fontSize: 13, fontWeight: 600, margin: '0 0 6px' } }, tr({ Files: 'ide.guideFiles', Edit: 'ide.guideEdit', Agent: 'ide.guideAgent', Layout: 'ide.guideLayout' }[key])), React.createElement('p', { style: { color: T.muted, fontSize: 12, lineHeight: 1.75, margin: 0 } }, tr({ Files: 'ide.guideFilesHint', Edit: 'ide.guideEditHint', Agent: 'ide.guideAgentHint', Layout: 'ide.guideLayoutHint' }[key])))))),
6590
+ React.createElement('a', { href: 'https://github.com/flymysql/dsh-remote#readme', target: '_blank', rel: 'noopener noreferrer', style: { display: 'inline-block', color: T.muted, fontSize: 12, marginTop: 32 } }, tr('ide.documentation'))))
6591
+ }
6592
+ // Replace the empty guide or a redundant explorer (already in the left
6593
+ // column). Existing files, terminals and drafts
6594
+ // are untouched, and each action is fenced to the session still on screen.
6595
+ function ensureRemoteIdeWelcome(controller, sessionId) {
6596
+ if (!controller || controller.mounted?.getSnapshot?.() !== sessionId || typeof controller.active !== 'function') return false
6597
+ const tab = controller.active()
6598
+ if (typeof controller.openTabIn !== 'function') return false
6599
+ if (!tab) { controller.openTabIn(sessionId, NATIVE_WELCOME); return true }
6600
+ if (!['guide', NATIVE_EXPLORER].includes(tab.kind) || !tab.id) return false
6601
+ controller.openTabIn(sessionId, NATIVE_WELCOME, { replaceTab: tab.id })
6602
+ controller.closeIn?.(sessionId, tab.id)
6603
+ return true
6604
+ }
6156
6605
  function RemoteIdeShell() {
6157
6606
  const state = useRemoteIdeState()
6158
6607
  const [sessionId, setSessionId] = React.useState('')
6159
6608
  const [, refresh] = React.useState(0)
6160
6609
  const [width, setWidth] = React.useState(() => typeof window.innerWidth === 'number' ? window.innerWidth : 1280)
6161
6610
  const [mobilePane, setMobilePane] = React.useState('chat')
6611
+ const [toolsExpanded, setToolsExpanded] = React.useState(false)
6612
+ const toolsExpandedRef = React.useRef(false)
6613
+ toolsExpandedRef.current = toolsExpanded
6162
6614
  const [availability, setAvailability] = React.useState({ chat: true, editor: true })
6163
6615
  const [expanded, setExpanded] = React.useState([])
6164
6616
  const editorSeat = React.useRef(null), chatSeat = React.useRef(null), shellRef = React.useRef(null)
6165
6617
  const dragCleanup = React.useRef(null)
6166
6618
  const controller = remoteIdeController
6167
6619
  const sizes = remoteIdeWidths(width, state)
6168
- const mirror = sessionId ? mirrorForCwd(sessionCwdFor(sessionId), MIRRORS.list) : null
6620
+ const mirror = sessionId ? workspaceSummary(sessionId) : null
6169
6621
  const active = !!(state.enabled && sessionId && mirror && controller)
6170
6622
  React.useEffect(() => {
6171
6623
  const update = () => {
@@ -6180,7 +6632,11 @@ window.__ModuleLoader__.load({
6180
6632
  window.addEventListener('resize', onResize)
6181
6633
  return () => { unsubscribers.forEach(dispose => dispose?.()); mirrorWatchers.delete(update); window.removeEventListener('resize', onResize); dragCleanup.current?.() }
6182
6634
  }, [controller])
6183
- React.useEffect(() => { setExpanded(explorerMemory.get(sessionId)?.expanded || []) }, [sessionId])
6635
+ React.useEffect(() => { setExpanded(explorerMemory.get(sessionId)?.expanded || []); setToolsExpanded(false) }, [sessionId])
6636
+ React.useEffect(() => {
6637
+ const chat = document.querySelector('[data-rw-ide-chat]')
6638
+ chat?.toggleAttribute('data-rw-ide-tools-expanded', toolsExpanded)
6639
+ }, [active, sessionId, toolsExpanded])
6184
6640
  React.useEffect(() => {
6185
6641
  if (!active) return
6186
6642
  const node = document.createElement('style')
@@ -6200,6 +6656,7 @@ window.__ModuleLoader__.load({
6200
6656
  const update = () => {
6201
6657
  frame = 0
6202
6658
  if (stopped) return
6659
+ ensureRemoteIdeWelcome(controller, sessionId)
6203
6660
  if (!dockChat?.node.isConnected) {
6204
6661
  dockChat?.dispose()
6205
6662
  const content = find('[data-conversation-content][data-conversation-session]', 'data-conversation-session')
@@ -6213,7 +6670,7 @@ window.__ModuleLoader__.load({
6213
6670
  }
6214
6671
  const chatRect = chatSeat.current?.getBoundingClientRect()
6215
6672
  const editorRect = editorSeat.current?.getBoundingClientRect()
6216
- if (dockChat && chatRect) dockChat.position(chatRect, chatRect.width > 0 && chatRect.height > 0)
6673
+ if (dockChat && chatRect) { dockChat.position(chatRect, chatRect.width > 0 && chatRect.height > 0); dockChat.node.toggleAttribute('data-rw-ide-tools-expanded', toolsExpandedRef.current) }
6217
6674
  if (dockEditor && editorRect) dockEditor.position(editorRect, editorRect.width > 0 && editorRect.height > 0)
6218
6675
  const chat = !!dockChat
6219
6676
  const editor = !!dockEditor && dockEditor.node.getAttribute('aria-hidden') !== 'true'
@@ -6223,10 +6680,9 @@ window.__ModuleLoader__.load({
6223
6680
  const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(schedule) : null
6224
6681
  observer?.observe(editorSeat.current); observer?.observe(chatSeat.current)
6225
6682
  // React may replace roots during session navigation. Child-list changes
6226
- // are coalesced; no text/attribute observer loops during token streaming.
6227
- const mutations = typeof MutationObserver === 'function' ? new MutationObserver(() => {
6228
- if (!dockChat?.node.isConnected || !dockEditor?.node.isConnected) schedule()
6229
- }) : null
6683
+ // are coalesced, including a newly opened empty guide. Character data
6684
+ // and style attributes are not observed during token streaming.
6685
+ const mutations = typeof MutationObserver === 'function' ? new MutationObserver(schedule) : null
6230
6686
  mutations?.observe(document.body, { childList: true, subtree: true })
6231
6687
  const unsub = controller.openTabs?.subscribe?.(schedule)
6232
6688
  window.addEventListener('resize', schedule)
@@ -6275,6 +6731,7 @@ window.__ModuleLoader__.load({
6275
6731
  key: pane, type: 'button', style: { ...buttonS, padding: '4px 9px', fontSize: 12 },
6276
6732
  'aria-pressed': mobilePane === pane, onClick: () => setMobilePane(pane),
6277
6733
  }, tr({ files: 'ide.files', editor: 'ide.editor', chat: 'ide.chat' }[pane])))) : null,
6734
+ React.createElement('button', { type: 'button', 'data-rw-ide-tools-toggle': '', 'aria-expanded': toolsExpanded, style: { ...buttonS, padding: '4px 9px', fontSize: 12 }, title: tr('ide.toolsHint'), onClick: () => setToolsExpanded(value => !value) }, tr('ide.tools')),
6278
6735
  React.createElement('button', { type: 'button', 'data-rw-ide-exit': '', style: { ...buttonS, padding: '4px 9px', fontSize: 12 }, title: tr('ide.help'), onClick: () => remoteIdeSet({ enabled: false }) }, tr('ide.exit'))),
6279
6736
  React.createElement('div', { 'data-rw-ide-body': '', style: { gridTemplateColumns: sizes.narrow ? 'minmax(0,1fr)' : sizes.left + 'px 6px minmax(320px,1fr) 6px ' + sizes.right + 'px' } },
6280
6737
  React.createElement('aside', { 'data-rw-ide-tree': '', 'aria-label': tr('ide.files'), style: { display: sizes.narrow && mobilePane !== 'files' ? 'none' : undefined } },