dsh-gufa-code 1.3.215 → 1.3.234

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.
@@ -12,6 +12,16 @@ G.BUILD = 'dev'
12
12
  G.PANEL_ID = 'gufa-code'
13
13
  /** 从哪个工作区点进来的(工作区菜单/节点按钮写入,App 启动时消费)。 */
14
14
  G.pendingEntryWorkspace = null
15
+ /** 经典模式悬浮入口:优先打开当前聊天所在工作区(而不是上次保存的项目)。 */
16
+ G.pendingSessionEntry = false
17
+ /** 由 App 暴露给文件打开器使用的编辑器入口(打开指定绝对路径文件)。 */
18
+ G.ideOpenPaths = null
19
+ /** 系统「打开方式」请求的目标条目:App boot 时优先打开该工作区,避免先恢复旧项目再被覆盖。 */
20
+ G.pendingOpenEntries = null
21
+ /** 正在处理系统「打开方式」请求:期间入口工作区同步不得把项目改回当前会话 cwd。 */
22
+ G.openWithActive = false
23
+ /** App 初始 boot(恢复项目/会话)是否完成;open-with 必须等它结束再切目标工作区。 */
24
+ G.ideBootDone = false
15
25
  G.ctx = null
16
26
  G.h = h
17
27
  G.React = React
@@ -1786,6 +1796,8 @@ html[data-platform=darwin][data-fullscreen] .gufa-titlebar{height:44px;padding-l
1786
1796
  color:var(--gufa-text);cursor:pointer;text-align:left;font-size:12.5px;white-space:nowrap;min-width:0;width:100%}
1787
1797
  .gufa-tree-row:hover{background:var(--gufa-hover)}
1788
1798
  .gufa-tree-row[data-selected]{background:var(--gufa-active)}
1799
+ .gufa-tree-row[data-drop]{background:color-mix(in srgb, var(--gufa-accent) 18%, transparent);outline:1px dashed var(--gufa-accent);outline-offset:-1px;border-radius:6px}
1800
+ .gufa-panel-body[data-drop-root]{box-shadow:inset 0 0 0 2px color-mix(in srgb, var(--gufa-accent) 55%, transparent)}
1789
1801
  .gufa-tree-row[data-kind="dir"]{color:var(--gufa-text)}
1790
1802
  .gufa-tree-name{overflow:hidden;text-overflow:ellipsis;flex:1 1 auto;min-width:0}
1791
1803
  .gufa-explorer-notice{margin:4px 10px 0;padding:3px 8px;border-radius:6px;font-size:11px;line-height:1.5;color:var(--gufa-text);
@@ -2010,6 +2022,11 @@ html[data-gufa-ide] .liang-skin-backdrop{display:none!important}
2010
2022
  background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12.5px;cursor:pointer;text-align:left}
2011
2023
  .gufa-more-entry:hover{background:var(--dsw-alias-interactive-bg-hover, var(--gufa-hover))}
2012
2024
  .gufa-more-entry-label{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
2025
+ /* 经典模式聊天右上角工具区的「古法编程」入口:只加一个显眼边框,其余保持原生 link 样式 */
2026
+ .gufa-header-entry{min-height:28px;flex:none;display:inline-flex;align-items:center;padding:3px 9px;border:1.5px solid var(--gufa-accent, #b13a2b);border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary, var(--gufa-text-dim));font:500 12px/1 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;cursor:pointer;white-space:nowrap;transition:background .15s ease,color .15s ease}
2027
+ .gufa-header-entry:hover{color:var(--dsw-alias-label-primary, var(--gufa-text));background:var(--dsw-alias-interactive-bg-hover, var(--gufa-hover))}
2028
+ .gufa-header-entry:focus-visible{outline:2px solid var(--dsw-focus-ring-color, var(--gufa-accent));outline-offset:2px}
2029
+ .gufa-header-entry-label{white-space:nowrap}
2013
2030
  .gufa-menu{position:absolute;z-index:2147483000;min-width:150px;padding:5px;border-radius:9px;border:1px solid var(--gufa-border-strong);
2014
2031
  background:var(--gufa-solid-overlay-bg);box-shadow:0 12px 30px color-mix(in srgb, #000 28%, transparent)}
2015
2032
  .gufa-menu-item{display:flex;align-items:center;gap:8px;width:100%;height:28px;padding:0 9px;border:0;border-radius:6px;
@@ -413,7 +413,7 @@ const GUFA_DEFINITION_STRONG_KINDS = new Set(['function', 'class', 'method', 'de
413
413
  */
414
414
  /* JS/TS 的 F12 交回 Monaco 原生 TS DefinitionProvider(之前被我们关掉过);
415
415
  Cmd+点击在 click handler 里直接走 Host LanguageService 以拿到最准结果。 */
416
- const GUFA_DEFINITION_LANGUAGES = ['python']
416
+ const GUFA_DEFINITION_LANGUAGES = ['python', 'php']
417
417
  function gufaRegisterDefinitionInfrastructure(monaco) {
418
418
  try {
419
419
  if (monaco === null || monaco === undefined) return
@@ -473,7 +473,7 @@ function gufaRegisterDefinitionInfrastructure(monaco) {
473
473
  language: 'python',
474
474
  content: model.getValue(),
475
475
  })
476
- } else {
476
+ } else if (language === 'javascript' || language === 'typescript') {
477
477
  /* LanguageService 解析定义(TS 编译器),比正则项目搜索准确;
478
478
  JS/TS 不再回退到 code.definition,避免“宁可跳错也不空着”。 */
479
479
  result = await G.api('code.tsDefinition', {
@@ -483,6 +483,16 @@ function gufaRegisterDefinitionInfrastructure(monaco) {
483
483
  column: position.column,
484
484
  content: model.getValue(),
485
485
  })
486
+ } else {
487
+ /* PHP 等无内置语言服务的语言:项目级定义搜索(Host code.definition) */
488
+ result = await G.api('code.definition', {
489
+ root: info.root,
490
+ path: info.path,
491
+ line: position.lineNumber,
492
+ column: position.column,
493
+ word,
494
+ content: model.getValue(),
495
+ })
486
496
  }
487
497
  if (token !== null && token !== undefined && token.isCancellationRequested === true) return []
488
498
  return locationsOf(info.root, result !== null && result !== undefined ? result.matches : null, word, monaco)
@@ -770,6 +780,23 @@ const GUFA_LINT_ENABLED = true
770
780
  const activePathRef = useRef(activePath)
771
781
  const statusRef = useRef('loading')
772
782
  const pendingRevealRef = useRef(null)
783
+ /* 打开未加载的文件时,editor 可能还没挂载/模型还没切换;先记住目标位置,
784
+ 等编辑器就绪或切到目标文件后再落光标,避免只跳文件、位置不准。 */
785
+ const applyPendingReveal = useCallback((editor) => {
786
+ const pending = pendingRevealRef.current
787
+ if (pending === null || pending === undefined) return false
788
+ if (editor === null || editor === undefined) return false
789
+ if (modelPathRef.current !== pending.path) return false
790
+ pendingRevealRef.current = null
791
+ try {
792
+ editor.setPosition({ lineNumber: pending.line, column: pending.column })
793
+ editor.revealLineInCenter(pending.line)
794
+ editor.focus()
795
+ } catch {
796
+ /* ignore */
797
+ }
798
+ return true
799
+ }, [])
773
800
 
774
801
  /** idle → loading → ready / error */
775
802
  const [status, setStatus] = useState('loading')
@@ -1332,6 +1359,33 @@ const GUFA_LINT_ENABLED = true
1332
1359
  clearHoverDecoration()
1333
1360
  return
1334
1361
  }
1362
+ /* 其它语言(PHP / Go / Java …):走项目级定义搜索。
1363
+ queryDefinitions + decideDefinition 已实现,此前没接到点击入口。 */
1364
+ try {
1365
+ const resolved = await queryDefinitions(position, word, model, path, root)
1366
+ const decision = decideDefinition(resolved)
1367
+ if (decision.kind === 'open') {
1368
+ G.bus.emit('editor:open-at', {
1369
+ path: decision.match.path,
1370
+ line: decision.match.line,
1371
+ column: decision.match.column,
1372
+ })
1373
+ clearHoverDecoration()
1374
+ return
1375
+ }
1376
+ if (decision.kind === 'pick') {
1377
+ G.bus.emit('definition:pick', {
1378
+ word,
1379
+ matches: decision.matches,
1380
+ x: Number.isFinite(Number(event.clientX)) ? Number(event.clientX) : 240,
1381
+ y: Number.isFinite(Number(event.clientY)) ? Number(event.clientY) : 240,
1382
+ })
1383
+ clearHoverDecoration()
1384
+ return
1385
+ }
1386
+ } catch {
1387
+ /* 解析失败继续走原生兜底,不跳错 */
1388
+ }
1335
1389
  /* 其它语言:保留 Monaco 原生 action 兜底 */
1336
1390
  try {
1337
1391
  instance.focus()
@@ -1773,17 +1827,7 @@ const GUFA_LINT_ENABLED = true
1773
1827
  }
1774
1828
  }
1775
1829
  reportCursor()
1776
- const pending = pendingRevealRef.current
1777
- if (pending !== null && pending !== undefined && pending.path === targetTab.path) {
1778
- pendingRevealRef.current = null
1779
- try {
1780
- editor.setPosition({ lineNumber: pending.line, column: pending.column })
1781
- editor.revealLineInCenter(pending.line)
1782
- editor.focus()
1783
- } catch {
1784
- /* ignore */
1785
- }
1786
- }
1830
+ applyPendingReveal(editor)
1787
1831
  /* 打开 Python 文件时预热 pyright,避免第一次 Cmd+点击等语言服务启动 */
1788
1832
  if (targetTab.language === 'python' && !GUFA_LSP_WARMED.has(root)) {
1789
1833
  GUFA_LSP_WARMED.add(root)
@@ -1806,19 +1850,28 @@ const GUFA_LINT_ENABLED = true
1806
1850
  } else if (targetTab !== null) {
1807
1851
  modelPathRef.current = targetTab.path
1808
1852
  }
1809
- }, [status, tabs, activePath, root, reportCursor, disposeAllModels, disposeModelAt])
1853
+ }, [status, tabs, activePath, root, reportCursor, applyPendingReveal, disposeAllModels, disposeModelAt])
1854
+
1855
+ /* 编辑器挂载完成/模型已就绪时,把还没落地的定义跳转位置补上 */
1856
+ useEffect(() => {
1857
+ applyPendingReveal(editorRef.current)
1858
+ }, [status, tabs, activePath, applyPendingReveal])
1810
1859
 
1811
1860
  /* 搜索面板点击结果 → 打开文件并跳到对应行列(由 App 通过 bus 发来) */
1812
1861
  useEffect(() => {
1813
1862
  if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
1814
1863
  return G.bus.on('editor:reveal', (detail) => {
1815
1864
  const editor = editorRef.current
1816
- if (editor === null || editor === undefined) return
1817
1865
  const rawLine = Number(detail?.line)
1818
1866
  const rawColumn = Number(detail?.column)
1819
1867
  const line = Number.isFinite(rawLine) ? Math.max(1, Math.trunc(rawLine)) : 1
1820
1868
  const column = Number.isFinite(rawColumn) ? Math.max(1, Math.trunc(rawColumn)) : 1
1821
1869
  const path = typeof detail?.path === 'string' && detail.path !== '' ? detail.path : null
1870
+ if (editor === null || editor === undefined) {
1871
+ /* 编辑器还没挂载(首次打开文件):先记下位置,挂载/切模型后的 effect 会补上 */
1872
+ if (path !== null) pendingRevealRef.current = { path, line, column }
1873
+ return
1874
+ }
1822
1875
  if (path !== null && modelPathRef.current !== path) {
1823
1876
  pendingRevealRef.current = { path, line, column }
1824
1877
  return
@@ -3,6 +3,8 @@
3
3
  * 纯展示 + 直接调用 Host API,状态自持;容器在 90-app.js。
4
4
  */
5
5
 
6
+ const GUFA_EXPLORER_MOVE_TYPE = 'application/x-gufa-explorer-move'
7
+
6
8
  /* ── 资源管理器 ────────────────────────────────────────────────────────── */
7
9
  G.Explorer = function Explorer(props) {
8
10
  const t = G.useT()
@@ -12,6 +14,8 @@ G.Explorer = function Explorer(props) {
12
14
  const [selected, setSelected] = useState(() => (props.activePath ? { path: props.activePath, kind: 'file' } : null))
13
15
  const [multi, setMulti] = useState([])
14
16
  const [clipboard, setClipboard] = useState(null)
17
+ const [dragTarget, setDragTarget] = useState(null)
18
+ const internalDragRef = useRef(null)
15
19
  const [menu, setMenu] = useState(null)
16
20
  const [menuError, setMenuError] = useState('')
17
21
  const [notice, setNotice] = useState('')
@@ -135,8 +139,12 @@ G.Explorer = function Explorer(props) {
135
139
 
136
140
  const copySelection = (paths) => {
137
141
  if (!Array.isArray(paths) || paths.length === 0) return
138
- setClipboard({ entries: paths.slice() })
142
+ const entries = paths.filter((path) => typeof path === 'string' && path !== '')
143
+ if (entries.length === 0) return
144
+ setClipboard({ entries })
139
145
  setMenuError('')
146
+ /* 同时写入系统剪贴板(file URL / alias 列表):另一个古法编程实例或 Finder 可以直接粘贴 */
147
+ void G.api('fs.copyToSystemClipboard', { root, from: entries }).catch(() => {})
140
148
  }
141
149
 
142
150
  /* 内置剪贴板(IDE 内复制/剪切)优先;没有时读系统剪贴板里的文件/文件夹路径(Finder/资源管理器复制)。 */
@@ -180,6 +188,59 @@ G.Explorer = function Explorer(props) {
180
188
  return () => window.removeEventListener('blur', clear)
181
189
  }, [])
182
190
 
191
+ const selectRoot = () => {
192
+ containerRef.current?.focus?.()
193
+ setMulti([])
194
+ setSelected({ path: '', kind: 'dir' })
195
+ }
196
+
197
+ /** 内部拖拽目标目录:拖到文件行 = 其父目录;拖到文件夹/空白 = 文件夹/根目录。 */
198
+ const internalDropTargetDir = (target) => {
199
+ const row = target instanceof Element ? target.closest('[data-edrv-path]') : null
200
+ if (row === null) return ''
201
+ const path = row.getAttribute('data-edrv-path') ?? ''
202
+ const kind = row.getAttribute('data-kind')
203
+ return kind === 'dir' ? path : projectDirOf(path)
204
+ }
205
+
206
+ /** 把资源管理器里拖拽的条目移动到目标目录(根目录传 '')。 */
207
+ const moveEntries = async (paths, targetDir) => {
208
+ const list = (Array.isArray(paths) ? paths : []).filter((path) => typeof path === 'string' && path !== '')
209
+ const movable = list.filter((path) => {
210
+ if (path === targetDir) return false
211
+ if (targetDir !== '' && targetDir.startsWith(`${path}/`)) return false
212
+ return true
213
+ })
214
+ if (movable.length === 0) return
215
+ showNotice(`正在移动 ${movable.length} 项…`)
216
+ const failed = []
217
+ let moved = 0
218
+ let last = null
219
+ for (const path of movable) {
220
+ const base = path.split('/').filter(Boolean).pop() ?? path
221
+ const nextPath = targetDir === '' ? base : `${targetDir}/${base}`
222
+ if (nextPath === path) continue
223
+ try {
224
+ await G.api('fs.rename', { root, path, nextPath })
225
+ moved += 1
226
+ last = { path: nextPath, kind: kindByPathRef.current.get(path) ?? 'file' }
227
+ } catch (error) {
228
+ failed.push(`${path}:${G.errorText(error)}`)
229
+ }
230
+ }
231
+ const dirsToRefresh = new Set(['', targetDir])
232
+ for (const path of movable) dirsToRefresh.add(projectDirOf(path))
233
+ for (const dir of dirsToRefresh) void loadDir(dir)
234
+ props.onChanged?.()
235
+ if (last !== null) {
236
+ setMulti([])
237
+ setSelected(last)
238
+ if (last.kind === 'dir') setExpanded((current) => ({ ...current, [last.path]: true }))
239
+ }
240
+ if (moved > 0) showNotice(`已移动 ${moved} 项${failed.length > 0 ? `,${failed.length} 项失败` : ''}`)
241
+ else if (failed.length > 0) showNotice(`移动失败:${failed[0]}`)
242
+ }
243
+
183
244
  const noticeRef = useRef(0)
184
245
  const showNotice = (text) => {
185
246
  setNotice(text)
@@ -332,6 +393,8 @@ G.Explorer = function Explorer(props) {
332
393
  'data-git-status': status !== undefined ? status : undefined,
333
394
  /* 给 dsh-drag-ref 用:把资源管理器行变成可拖拽的 @ 引用来源 */
334
395
  'data-edrv-path': entry.path,
396
+ 'data-drop': isDir && dragTarget === entry.path ? '' : undefined,
397
+ draggable: true,
335
398
  style: { paddingLeft: 8 + depth * 14 },
336
399
  title: entry.path,
337
400
  onClick: (event) => {
@@ -355,6 +418,22 @@ G.Explorer = function Explorer(props) {
355
418
  onDoubleClick: () => {
356
419
  if (!isDir) props.onOpenFile?.(entry.path, { preview: false })
357
420
  },
421
+ onDragStart: (event) => {
422
+ const dragPaths = multi.length > 0 && multi.includes(entry.path) ? multi.slice() : [entry.path]
423
+ internalDragRef.current = dragPaths
424
+ try {
425
+ if (event.dataTransfer !== null && event.dataTransfer !== undefined) {
426
+ event.dataTransfer.effectAllowed = 'copyMove'
427
+ event.dataTransfer.setData(GUFA_EXPLORER_MOVE_TYPE, JSON.stringify({ paths: dragPaths }))
428
+ }
429
+ } catch {
430
+ /* ignore */
431
+ }
432
+ },
433
+ onDragEnd: () => {
434
+ internalDragRef.current = null
435
+ setDragTarget(null)
436
+ },
358
437
  onContextMenu: (event) => openContextMenu(event, entry),
359
438
  },
360
439
  h(
@@ -406,28 +485,59 @@ G.Explorer = function Explorer(props) {
406
485
  },
407
486
  onDragOver: (event) => {
408
487
  const types = event.dataTransfer?.types
409
- if (types === undefined || types === null || !Array.from(types).includes('Files')) return
488
+ if (types === undefined || types === null) return
489
+ const list = Array.from(types)
490
+ if (list.includes(GUFA_EXPLORER_MOVE_TYPE)) {
491
+ event.preventDefault()
492
+ event.stopPropagation()
493
+ if (event.dataTransfer !== null && event.dataTransfer !== undefined) event.dataTransfer.dropEffect = 'move'
494
+ setDragTarget(internalDropTargetDir(event.target))
495
+ return
496
+ }
497
+ if (!list.includes('Files')) return
410
498
  event.preventDefault()
411
499
  event.stopPropagation()
412
500
  event.dataTransfer.dropEffect = 'copy'
413
501
  },
502
+ onDragLeave: (event) => {
503
+ if (event.currentTarget instanceof Node && event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) return
504
+ setDragTarget(null)
505
+ },
414
506
  onDrop: (event) => {
507
+ const types = event.dataTransfer?.types
508
+ if (types !== undefined && types !== null && Array.from(types).includes(GUFA_EXPLORER_MOVE_TYPE)) {
509
+ event.preventDefault()
510
+ event.stopPropagation()
511
+ const paths = internalDragRef.current
512
+ internalDragRef.current = null
513
+ const targetDir = internalDropTargetDir(event.target)
514
+ setDragTarget(null)
515
+ void moveEntries(paths, targetDir)
516
+ return
517
+ }
415
518
  const files = event.dataTransfer?.files
416
519
  if (files === undefined || files === null || files.length === 0) return
417
520
  event.preventDefault()
418
521
  event.stopPropagation()
419
522
  void uploadFiles(files, dropTargetDir(event.target))
420
523
  },
524
+ onClick: (event) => {
525
+ /* 点击资源管理器空白处:选中根目录,而不是保留上一次选中的文件/文件夹 */
526
+ if (!(event.target instanceof Element)) return
527
+ if (event.target.closest('[data-edrv-path]') !== null) return
528
+ if (event.target.closest('.gufa-panel-head, button, input, textarea, [role="menu"]') !== null) return
529
+ selectRoot()
530
+ },
421
531
  onKeyDown: (event) => {
422
532
  if (event.key === 'Enter') {
423
- if (selected === null) return
533
+ if (selected === null || selected.path === '') return
424
534
  event.preventDefault()
425
535
  props.onRename?.(selected.path)
426
536
  return
427
537
  }
428
538
  const mod = event.metaKey || event.ctrlKey
429
539
  if (!mod || event.altKey) {
430
- if (event.key === 'Delete' && selected !== null) {
540
+ if (event.key === 'Delete' && selected !== null && selected.path !== '') {
431
541
  event.preventDefault()
432
542
  props.onDelete?.(selected.path)
433
543
  }
@@ -442,7 +552,7 @@ G.Explorer = function Explorer(props) {
442
552
  void pasteInto(selectedDir())
443
553
  } else if (key === 'backspace' || event.key === 'Delete') {
444
554
  event.preventDefault()
445
- if (selected !== null) props.onDelete?.(selected.path)
555
+ if (selected !== null && selected.path !== '') props.onDelete?.(selected.path)
446
556
  }
447
557
  },
448
558
  },
@@ -462,6 +572,7 @@ G.Explorer = function Explorer(props) {
462
572
  'div',
463
573
  {
464
574
  className: 'gufa-panel-body gufa-scroll',
575
+ 'data-drop-root': dragTarget === '' ? '' : undefined,
465
576
  onContextMenu: (event) => {
466
577
  try {
467
578
  if (event.target !== null && event.target !== undefined && typeof event.target.closest === 'function' && event.target.closest('.gufa-tree-row') !== null) return
@@ -261,6 +261,9 @@ function install(ctx) {
261
261
  };
262
262
  const onDrop = (event) => {
263
263
  if (!isOurs(event.dataTransfer)) return;
264
+ /* 资源管理器内部拖拽移动文件:交给 Explorer 自己的 drop 处理,不当作 @ 引用插入 */
265
+ if (event.dataTransfer !== null && Array.prototype.indexOf.call(event.dataTransfer.types, "application/x-gufa-explorer-move") !== -1
266
+ && event.target instanceof Element && event.target.closest(".gufa-sidepanel") !== null) return;
264
267
  if (dropZoneOf(event.target) === null) {
265
268
  toast("松手位置不在输入框内,未插入", "err");
266
269
  return;
@@ -351,6 +351,9 @@ G.GufaApp = function GufaApp(props) {
351
351
  const [banner, setBanner] = useState('')
352
352
  const [tabs, setTabs] = useState([])
353
353
  const [activePath, setActivePath] = useState(null)
354
+ const activePathRef = useRef(activePath)
355
+ activePathRef.current = activePath
356
+ const pendingOpenAtRef = useRef(null)
354
357
  /* 选区(给右侧 AI 用)单独更新;光标位置/行数走 G.cursorStore,避免每次按键重渲染整个 IDE。 */
355
358
  const [selection, setSelection] = useState(null)
356
359
  /* 编辑器内容缓冲:Monaco 每次按键只写这里,300ms 停顿后才同步进 tabs(保存/自动保存直接读缓冲)。 */
@@ -378,6 +381,20 @@ G.GufaApp = function GufaApp(props) {
378
381
  const [workspaceSessions, setWorkspaceSessions] = useState({ status: 'idle', sessions: [], groups: [], sessionIds: [], archivedSessionIds: [] })
379
382
  const [workspaceIndex, setWorkspaceIndex] = useState([])
380
383
  const [recentCurrentIds, setRecentCurrentIds] = useState([])
384
+ const [bootStage, setBootStage] = useState('idle')
385
+ useLayoutEffect(() => {
386
+ /* App 挂载是新实例:先清掉上一实例的 boot 完成标记,避免 open-with 看到陈旧 true */
387
+ G.ideBootDone = false
388
+ }, [])
389
+ useEffect(() => {
390
+ if (bootStage === 'done') {
391
+ G.ideBootDone = true
392
+ void G.api('dev.log', { message: 'boot-stage done' }).catch(() => {})
393
+ } else if (bootStage === 'loading') {
394
+ G.ideBootDone = false
395
+ }
396
+ return () => { if (bootStage === 'done') G.ideBootDone = false }
397
+ }, [bootStage])
381
398
  /* 会话运行状态(与经典侧边栏同源:uiSession.sessionStatus,含 running/pendingInteraction/completionUnread) */
382
399
  const [sessionStatuses, setSessionStatuses] = useState(() => new Map())
383
400
  const [sessionStatusReady, setSessionStatusReady] = useState(false)
@@ -427,6 +444,14 @@ G.GufaApp = function GufaApp(props) {
427
444
  G.projectRoot = typeof value?.root === 'string' ? value.root : null
428
445
  setProject(value)
429
446
  writeJson(GUFA_LS.project, value?.root ?? null)
447
+ try {
448
+ if ((window.__gufaProjectApplyLogs ?? 20) > 0) {
449
+ window.__gufaProjectApplyLogs = (window.__gufaProjectApplyLogs ?? 20) - 1
450
+ void G.api('dev.log', { message: `project-apply root=${String(value?.root ?? '')}` }).catch(() => {})
451
+ }
452
+ } catch {
453
+ /* ignore */
454
+ }
430
455
  setTabs([])
431
456
  setActivePath(null)
432
457
  setSelection(null)
@@ -451,8 +476,31 @@ G.GufaApp = function GufaApp(props) {
451
476
  if (bootedRef.current) return
452
477
  bootedRef.current = true
453
478
  let cancelled = false
479
+ setBootStage('idle')
454
480
  void (async () => {
455
481
  /* 从工作区菜单点进来的:跳过「恢复上次项目」,直接按入口工作区打开 */
482
+ /* 系统「打开方式」:优先直接打开文件所在目录,绝不先恢复上次项目,避免随后覆盖 */
483
+ const pendingOpenEntries = Array.isArray(G.pendingOpenEntries) ? G.pendingOpenEntries : null
484
+ if (pendingOpenEntries !== null && pendingOpenEntries.length > 0) {
485
+ const firstOpen = pendingOpenEntries.find((entry) => entry !== null && typeof entry === 'object' && typeof entry.path === 'string' && entry.path !== '')
486
+ if (firstOpen !== undefined) {
487
+ const openPath = String(firstOpen.path)
488
+ const normalizedOpen = openPath.replace(/\\/g, '/')
489
+ const openDir = firstOpen.kind === 'dir'
490
+ ? openPath
491
+ : (normalizedOpen.lastIndexOf('/') > 0 ? openPath.slice(0, normalizedOpen.lastIndexOf('/')) : openPath)
492
+ try {
493
+ const value = await G.api('project.open', { path: openDir })
494
+ if (!cancelled) applyProject(value)
495
+ void G.api('dev.log', { message: `open-with boot workspace=${value.root}` }).catch(() => {})
496
+ return
497
+ } catch (error) {
498
+ if (!cancelled) setBootError(G.errorText(error))
499
+ }
500
+ }
501
+ }
502
+ const preferSessionWorkspace = G.pendingSessionEntry === true
503
+ if (preferSessionWorkspace) G.pendingSessionEntry = false
456
504
  const pendingEntry = G.pendingEntryWorkspace
457
505
  if (pendingEntry !== null && pendingEntry !== undefined && typeof pendingEntry.key === 'string') {
458
506
  try {
@@ -468,6 +516,15 @@ G.GufaApp = function GufaApp(props) {
468
516
  /* 回落到恢复上次项目 */
469
517
  }
470
518
  }
519
+ if (preferSessionWorkspace && typeof sessionCwd === 'string' && sessionCwd !== '') {
520
+ try {
521
+ const value = await G.api('project.open', { path: sessionCwd })
522
+ if (!cancelled) applyProject(value)
523
+ } catch (error) {
524
+ if (!cancelled) setBootError(G.errorText(error))
525
+ }
526
+ return
527
+ }
471
528
  const saved = floatState !== null && floatState !== undefined && typeof floatState.projectRoot === 'string' && floatState.projectRoot !== ''
472
529
  ? floatState.projectRoot
473
530
  : readJson(GUFA_LS.project)
@@ -491,7 +548,10 @@ G.GufaApp = function GufaApp(props) {
491
548
  if (!cancelled) setBootError(G.errorText(error))
492
549
  }
493
550
  }
494
- })()
551
+ })().catch(() => {}).finally(() => {
552
+ /* 依赖变化触发的 cleanup 不代表组件卸载;这里必须无条件发出 boot 完成信号 */
553
+ setBootStage('done')
554
+ })
495
555
  return () => {
496
556
  cancelled = true
497
557
  }
@@ -644,7 +704,7 @@ G.GufaApp = function GufaApp(props) {
644
704
  /* ignore */
645
705
  }
646
706
  setActivePath(existing.path)
647
- return
707
+ return true
648
708
  }
649
709
  try {
650
710
  const doc = await G.api('fs.read', { root: project.root, path })
@@ -675,8 +735,10 @@ G.GufaApp = function GufaApp(props) {
675
735
  ))
676
736
  }
677
737
  setActivePath(gufaNormalizeProjectPath(doc.path ?? path))
738
+ return true
678
739
  } catch (error) {
679
740
  setBanner(G.errorText(error))
741
+ return false
680
742
  }
681
743
  }, [project, tabs])
682
744
 
@@ -688,20 +750,106 @@ G.GufaApp = function GufaApp(props) {
688
750
 
689
751
  /* 从搜索/定位结果打开文件并跳到指定行列(等 tab 切换完成后再触发编辑器 reveal) */
690
752
  const openFileAt = useCallback(async (rawPath, line, column) => {
691
- if (typeof rawPath !== 'string' || rawPath === '') return
753
+ if (typeof rawPath !== 'string' || rawPath === '') return false
692
754
  const path = gufaNormalizeProjectPath(rawPath)
693
- await openFile(path)
755
+ const opened = await openFile(path)
756
+ if (opened === false) return false
694
757
  const targetLine = Number.isFinite(Number(line)) ? Math.max(1, Math.trunc(Number(line))) : 1
695
758
  const targetColumn = Number.isFinite(Number(column)) ? Math.max(1, Math.trunc(Number(column))) : 1
696
- window.setTimeout(() => {
697
- try {
698
- G.bus.emit('editor:reveal', { path, line: targetLine, column: targetColumn })
699
- } catch {
700
- /* ignore */
701
- }
702
- }, 120)
759
+ const target = { path, line: targetLine, column: targetColumn }
760
+ const currentActive = activePathRef.current === null ? null : gufaNormalizeProjectPath(activePathRef.current)
761
+ if (currentActive === path) {
762
+ /* 文件本来就打开着:编辑器/model 已就绪,延迟一帧即可 */
763
+ window.setTimeout(() => {
764
+ try { G.bus.emit('editor:reveal', target) } catch { /* ignore */ }
765
+ }, 80)
766
+ return
767
+ }
768
+ /* 文件未打开:交给 activePath effect,在 tab 真正切过去之后再 reveal(避免固定 120ms 的竞态) */
769
+ pendingOpenAtRef.current = target
703
770
  }, [openFile])
704
771
 
772
+ /* 系统文件「打开方式」:暴露入口给 99-main 的 pending 轮询(打开指定绝对路径文件)。 */
773
+ const projectRef = useRef(project)
774
+ projectRef.current = project
775
+ const applyProjectRef = useRef(applyProject)
776
+ applyProjectRef.current = applyProject
777
+ const openFileAtRef = useRef(openFileAt)
778
+ openFileAtRef.current = openFileAt
779
+ const openFileRef = useRef(openFile)
780
+ openFileRef.current = openFile
781
+ useEffect(() => {
782
+ const sleep = (ms) => new Promise((resolve) => { window.setTimeout(resolve, ms) })
783
+ const normalize = (value) => String(value ?? '').replace(/\\/g, '/').replace(/\/+$/, '')
784
+ const dirOf = (value) => {
785
+ const normalized = String(value ?? '').replace(/\\/g, '/')
786
+ const index = normalized.lastIndexOf('/')
787
+ return index > 0 ? String(value).slice(0, value.length - (normalized.length - index)) : value
788
+ }
789
+ const handler = async (entries) => {
790
+ const list = Array.isArray(entries)
791
+ ? entries.filter((entry) => entry !== null && typeof entry === 'object' && typeof entry.path === 'string' && entry.path !== '')
792
+ : []
793
+ if (list.length === 0) return false
794
+ const first = list[0]
795
+ const targetDir = first.kind === 'dir' ? first.path : dirOf(first.path)
796
+ const targetRoot = normalize(targetDir)
797
+ if (normalize(projectRef.current?.root) !== targetRoot) {
798
+ try {
799
+ const value = await G.api('project.open', { path: targetDir })
800
+ applyProjectRef.current(value)
801
+ /* 等 React 把项目状态提交;如果 boot 恢复旧项目还在覆盖,继续等目标根稳定 */
802
+ for (let attempt = 0; attempt < 10; attempt += 1) {
803
+ await sleep(150)
804
+ if (normalize(projectRef.current?.root) === targetRoot) break
805
+ }
806
+ if (normalize(projectRef.current?.root) !== targetRoot) {
807
+ console.error('[gufa-code] 目标工作区未稳定', targetRoot, projectRef.current?.root)
808
+ return false
809
+ }
810
+ } catch (error) {
811
+ console.error('[gufa-code] 打开文件所在工作区失败', error)
812
+ return false
813
+ }
814
+ }
815
+ const root = normalize(projectRef.current?.root ?? targetRoot)
816
+ void G.api('dev.log', { message: `open-with apply dir=${targetDir} root=${root}` }).catch(() => {})
817
+ const files = list.filter((entry) => entry.kind !== 'dir')
818
+ for (let index = 0; index < files.length; index += 1) {
819
+ const absolute = normalize(files[index].path)
820
+ const rel = absolute.startsWith(`${root}/`) ? absolute.slice(root.length + 1) : absolute.split('/').pop()
821
+ if (typeof rel !== 'string' || rel === '' || rel.includes('..')) continue
822
+ void G.api('dev.log', { message: `open-with open rel=${rel}` }).catch(() => {})
823
+ const opened = index === 0
824
+ ? await openFileAtRef.current(rel, 1, 1)
825
+ : await openFileRef.current(rel)
826
+ if (opened === false) {
827
+ void G.api('dev.log', { message: `open-with open-failed rel=${rel}` }).catch(() => {})
828
+ return false
829
+ }
830
+ }
831
+ G.pendingOpenEntries = null
832
+ return true
833
+ }
834
+ G.ideOpenPaths = handler
835
+ return () => {
836
+ if (G.ideOpenPaths === handler) G.ideOpenPaths = null
837
+ }
838
+ }, [])
839
+
840
+
841
+ /* 未打开文件跳转:activePath 切到目标文件后(子组件编辑器 effect 已先行)再发 reveal */
842
+ useEffect(() => {
843
+ const pending = pendingOpenAtRef.current
844
+ if (pending === null || pending === undefined) return undefined
845
+ if (activePath === null || gufaNormalizeProjectPath(activePath) !== gufaNormalizeProjectPath(pending.path)) return undefined
846
+ pendingOpenAtRef.current = null
847
+ const timer = window.setTimeout(() => {
848
+ try { G.bus.emit('editor:reveal', pending) } catch { /* ignore */ }
849
+ }, 40)
850
+ return () => window.clearTimeout(timer)
851
+ }, [activePath])
852
+
705
853
  /* Cmd/Ctrl+点击定义:编辑器 → App 跳转 / 多结果选择(兜底搜索在 host/code.js) */
706
854
  useEffect(() => {
707
855
  if (G.bus === null || G.bus === undefined || typeof G.bus.on !== 'function') return undefined
@@ -1838,6 +1986,11 @@ G.GufaApp = function GufaApp(props) {
1838
1986
  const entryWorkspaceSyncedRef = useRef(false)
1839
1987
  useEffect(() => {
1840
1988
  if (entryWorkspaceSyncedRef.current) return
1989
+ /* 系统「打开方式」正在处理:工作区由 open-with 决定,入口同步不得改回会话 cwd */
1990
+ if (G.openWithActive === true) {
1991
+ entryWorkspaceSyncedRef.current = true
1992
+ return
1993
+ }
1841
1994
  /* 实例窗口:保持空工作区,不跟随主窗口/DSH 当前会话自动打开项目 */
1842
1995
  if (G.instanceBoot === true) {
1843
1996
  entryWorkspaceSyncedRef.current = true
@@ -1848,14 +2001,12 @@ G.GufaApp = function GufaApp(props) {
1848
2001
  entryWorkspaceSyncedRef.current = true
1849
2002
  return
1850
2003
  }
1851
- if (project === null && (G.pendingEntryWorkspace === null || G.pendingEntryWorkspace === undefined)) return
1852
2004
  const pending = G.pendingEntryWorkspace
1853
2005
  if (pending === null || pending === undefined || typeof pending.key !== 'string') {
1854
- if (typeof sessionCwd !== 'string' || sessionCwd === '') return
2006
+ /* 没有显式入口(例如重启 DSH 自动恢复 IDE):保留 boot 已恢复的「上次工作区」,
2007
+ 不要改回当前会话 cwd —— 否则 open-with 打开的工作区永远不会被记住。 */
1855
2008
  entryWorkspaceSyncedRef.current = true
1856
- if (project !== null && typeof project.root === 'string' && project.root !== sessionCwd) {
1857
- void openProjectPath(sessionCwd).catch((error) => setBanner(G.errorText(error)))
1858
- }
2009
+ void G.api('dev.log', { message: `entry-sync keep-saved project=${project !== null && typeof project.root === 'string' ? project.root : 'null'} sessionCwd=${typeof sessionCwd === 'string' ? sessionCwd : ''}` }).catch(() => {})
1859
2010
  return
1860
2011
  }
1861
2012
  entryWorkspaceSyncedRef.current = true