dsh-gufa-code 1.0.0 → 1.0.2

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.
@@ -0,0 +1,156 @@
1
+ /**
2
+ * 58-insert-ref:把系统剪贴板里的文件粘贴进对话输入框时,插入 `@相对路径` 引用。
3
+ *
4
+ * 浏览器/Electron 的剪贴板只给 File 内容、不给磁盘路径,所以流程是:
5
+ * File → 名称/size/sha256 → Host(fs.matchFiles) 在项目内匹配同名同内容文件 → 插入 @引用。
6
+ * 图片保持 DSH 默认的附件行为(不拦截)。
7
+ */
8
+
9
+ /** 轻量提示条(复用 drag-ref 的观感)。 */
10
+ G.refToast = function refToast(text, kind) {
11
+ try {
12
+ let host = document.getElementById('gufa-ref-toast')
13
+ if (host === null) {
14
+ host = document.createElement('div')
15
+ host.id = 'gufa-ref-toast'
16
+ host.style.cssText = 'position:fixed;left:50%;bottom:96px;transform:translateX(-50%);z-index:2147483000;max-width:70vw;padding:7px 14px;border-radius:999px;font:12px/1.5 system-ui,sans-serif;box-shadow:0 6px 20px rgba(16,24,40,.18);pointer-events:none;white-space:pre-wrap'
17
+ document.body.appendChild(host)
18
+ }
19
+ host.textContent = String(text)
20
+ host.style.background = kind === 'err' ? 'rgba(180,35,24,.92)' : kind === 'ok' ? 'rgba(6,118,71,.92)' : 'rgba(28,30,38,.92)'
21
+ host.style.color = '#fff'
22
+ clearTimeout(G.refToast.timer)
23
+ G.refToast.timer = window.setTimeout(() => {
24
+ if (host.parentNode !== null) host.parentNode.removeChild(host)
25
+ }, 3200)
26
+ } catch {
27
+ /* ignore */
28
+ }
29
+ }
30
+
31
+ /** 把相对路径变成 @ 引用文本(含空格的路径加引号)。 */
32
+ G.mentionOfPath = function mentionOfPath(path) {
33
+ const rel = String(path ?? '').replace(/\\/g, '/')
34
+ if (rel === '') return ''
35
+ return /\s/u.test(rel) ? `@"${rel}"` : `@${rel}`
36
+ }
37
+
38
+ /** 取文件 sha256(hex)。 */
39
+ G.sha256OfFile = async function sha256OfFile(file) {
40
+ const buffer = await file.arrayBuffer()
41
+ const digest = await crypto.subtle.digest('SHA-256', buffer)
42
+ return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, '0')).join('')
43
+ }
44
+
45
+ /** 把文本插入当前对话输入框:优先官方 input 服务,失败退回 contenteditable 插入。 */
46
+ G.insertIntoComposer = function insertIntoComposer(text) {
47
+ if (typeof text !== 'string' || text === '') return false
48
+ try {
49
+ const sessionEl = document.querySelector('[data-conversation-session]')
50
+ const sessionId = sessionEl === null ? '' : String(sessionEl.getAttribute('data-conversation-session') ?? '')
51
+ const sessions = G.ctx === null || G.ctx === undefined ? undefined : G.ctx.get('sessions')
52
+ const conversation = G.ctx === null || G.ctx === undefined ? undefined : G.ctx.get('conversation')
53
+ if (sessionId !== '' && sessions !== undefined && conversation !== undefined && typeof sessions.scope === 'function') {
54
+ const actx = sessions.scope(sessionId)
55
+ if (actx !== undefined) {
56
+ const input = conversation.input.for(actx)
57
+ const snapshot = input?.state?.getSnapshot?.()
58
+ if (snapshot !== undefined && input !== null && input !== undefined) {
59
+ const offset = String(snapshot.draft ?? '').length
60
+ const span = { start: offset, end: offset, draftRev: snapshot.draftRev }
61
+ if (typeof input.insertText === 'function' && input.insertText(text, span) === true) return true
62
+ if (typeof input.insertReference === 'function') {
63
+ const mention = G.mentionOfPath(text.replace(/^@/, ''))
64
+ if (mention !== '' && input.insertReference({ source: 'reference', ref: mention, label: text.replace(/^@/, ''), appearance: 'file', clipboardText: mention }, span) === true) return true
65
+ }
66
+ }
67
+ }
68
+ }
69
+ } catch {
70
+ /* fall through */
71
+ }
72
+ try {
73
+ const editor = document.querySelector('[data-conversation-region="composer"] [contenteditable="true"]') || document.querySelector('[data-conversation-region="composer"]')
74
+ if (editor === null) return false
75
+ editor.focus()
76
+ if (document.execCommand('insertText', false, text)) return true
77
+ } catch {
78
+ /* ignore */
79
+ }
80
+ return false
81
+ }
82
+
83
+ /**
84
+ * 安装「粘贴文件 → @引用」监听。
85
+ * @param {object} ctx client 根 context
86
+ * @returns {() => void} 卸载器
87
+ */
88
+ G.installChatFilePaste = function installChatFilePaste(ctx) {
89
+ if (typeof document === 'undefined') return () => {}
90
+ let disposed = false
91
+
92
+ const handleFiles = async (files) => {
93
+ const list = Array.from(files)
94
+ if (list.length === 0) return
95
+ const root = typeof G.projectRoot === 'string' ? G.projectRoot : ''
96
+ if (root === '') {
97
+ G.refToast('还没有打开项目,无法把文件转成 @ 引用', 'err')
98
+ return
99
+ }
100
+ const payloads = []
101
+ for (const file of list) {
102
+ try {
103
+ payloads.push({ name: file.name !== '' ? file.name : 'file', size: file.size, sha256: await G.sha256OfFile(file) })
104
+ } catch {
105
+ /* 读取失败的文件跳过 */
106
+ }
107
+ }
108
+ if (payloads.length === 0) {
109
+ G.refToast('粘贴的文件读取失败', 'err')
110
+ return
111
+ }
112
+ let matches = []
113
+ try {
114
+ const result = await G.api('fs.matchFiles', { root, files: payloads })
115
+ matches = Array.isArray(result?.matches) ? result.matches : []
116
+ } catch (error) {
117
+ G.refToast(`匹配项目文件失败:${G.errorText(error)}`, 'err')
118
+ return
119
+ }
120
+ if (disposed) return
121
+ const refs = []
122
+ const missing = []
123
+ for (const match of matches) {
124
+ if (typeof match?.path === 'string' && match.path !== '') refs.push(G.mentionOfPath(match.path))
125
+ else missing.push(String(match?.name ?? ''))
126
+ }
127
+ if (refs.length > 0) {
128
+ const inserted = G.insertIntoComposer(refs.join(' ') + ' ')
129
+ if (inserted) G.refToast(`已插入 ${refs.length} 个文件引用`, 'ok')
130
+ else G.refToast('插入引用失败:输入框不可用', 'err')
131
+ }
132
+ if (missing.length > 0) {
133
+ G.refToast(`${missing.join('、')} 不在当前项目里,未插入引用(可先粘贴到资源管理器导入项目)`, 'err')
134
+ }
135
+ }
136
+
137
+ const onPaste = (event) => {
138
+ const files = event.clipboardData === null || event.clipboardData === undefined ? undefined : event.clipboardData.files
139
+ if (files === undefined || files === null || files.length === 0) return
140
+ const target = event.target
141
+ const inConversation = target instanceof Element && (target.closest('[data-conversation-region="composer"]') !== null || target.closest('[data-conversation-content]') !== null)
142
+ if (!inConversation) return
143
+ const list = Array.from(files)
144
+ /* 图片保留 DSH 默认的附件粘贴行为 */
145
+ if (list.every((file) => typeof file.type === 'string' && file.type.startsWith('image/'))) return
146
+ event.preventDefault()
147
+ event.stopPropagation()
148
+ void handleFiles(list)
149
+ }
150
+
151
+ document.addEventListener('paste', onPaste, true)
152
+ return () => {
153
+ disposed = true
154
+ document.removeEventListener('paste', onPaste, true)
155
+ }
156
+ }
@@ -221,6 +221,7 @@ G.GufaApp = function GufaApp(props) {
221
221
 
222
222
  /* ── 项目打开 ──────────────────────────────────────────────────────── */
223
223
  const applyProject = useCallback((value) => {
224
+ G.projectRoot = typeof value?.root === 'string' ? value.root : null
224
225
  setProject(value)
225
226
  writeJson(GUFA_LS.project, value?.root ?? null)
226
227
  setTabs([])
@@ -783,11 +784,15 @@ G.GufaApp = function GufaApp(props) {
783
784
  }))
784
785
  }, [])
785
786
 
787
+ /* 「仅切换 IDE 项目」:项目固定为用户手动打开的目录,不跟随 DSH 会话/工作区 */
788
+ const projectPinnedRef = useRef(false)
789
+
786
790
  /* ── 右侧 AI 面板与当前工作区保持一致 ─────────────────────────────────
787
791
  * ChatDock 停靠的是 DSH「主视图会话」,但主视图会话可能属于别的工作区
788
792
  * (重启恢复、手动切换会话后常见)。项目根变化时自动切到当前工作区的会话。 */
789
793
  const dockSyncRef = useRef('')
790
794
  useEffect(() => {
795
+ if (projectPinnedRef.current === true) return undefined
791
796
  if (project === null || typeof project.root !== 'string' || project.root === '') return undefined
792
797
  if (dockSyncRef.current === project.root) return undefined
793
798
  if (typeof sessionCwd === 'string' && sessionCwd !== '' && sessionCwd === project.root) {
@@ -1039,6 +1044,7 @@ G.GufaApp = function GufaApp(props) {
1039
1044
  /* 点击左侧工作区名 → 切换已有工作区(与经典模式同一份 workspace 列表) */
1040
1045
  const switchWorkspace = useCallback(async (workspace) => {
1041
1046
  if (workspace === null || workspace === undefined) return
1047
+ projectPinnedRef.current = false
1042
1048
  const service = workspaceService()
1043
1049
  try {
1044
1050
  if (service !== undefined && service !== null && typeof service.openWorkspace === 'function' && typeof workspace.id === 'string') {
@@ -1074,6 +1080,20 @@ G.GufaApp = function GufaApp(props) {
1074
1080
  }, [openProjectPath, closeWorkspaceDialog, showBanner])
1075
1081
 
1076
1082
  /* 新建工作区:走经典模式同样的「选目录 → 创建 workspace → 打开并新建会话」 */
1083
+ /* 只切换 IDE 项目目录,不切换 DSH 会话/工作区(方便在同一个会话里边看别的项目边聊) */
1084
+ const pinProjectOnly = useCallback(async (workspace) => {
1085
+ if (workspace === null || workspace === undefined || typeof workspace.path !== 'string' || workspace.path === '') return
1086
+ try {
1087
+ projectPinnedRef.current = true
1088
+ await openProjectPath(workspace.path)
1089
+ closeWorkspaceDialog()
1090
+ showBanner('已切换 IDE 项目(当前会话保持不变)', 'success')
1091
+ } catch (error) {
1092
+ projectPinnedRef.current = false
1093
+ setBanner(G.errorText(error))
1094
+ }
1095
+ }, [openProjectPath, closeWorkspaceDialog, showBanner])
1096
+
1077
1097
  const createWorkspace = useCallback(async () => {
1078
1098
  const ui = workspaceService()
1079
1099
  const registry = workspacesService()
@@ -1856,25 +1876,36 @@ G.GufaApp = function GufaApp(props) {
1856
1876
  ? h('div', { className: 'gufa-hint', style: { padding: '10px 8px' } }, t('workspace.empty'))
1857
1877
  : workspaceDialog.workspaces.map((workspace) =>
1858
1878
  h(
1859
- 'button',
1860
- {
1861
- key: workspace.id,
1862
- type: 'button',
1863
- className: 'gufa-branch-row gufa-workspace-row',
1864
- 'data-current': project !== null && project.root === workspace.path ? '' : undefined,
1865
- title: workspace.path,
1866
- onClick: () => void switchWorkspace(workspace),
1867
- },
1868
- h(G.Icon, { name: 'folder-open', size: 13 }),
1879
+ 'div',
1880
+ { key: workspace.id, className: 'gufa-workspace-row-wrap' },
1869
1881
  h(
1870
- 'span',
1871
- { className: 'gufa-branch-name' },
1872
- h('span', { className: 'gufa-workspace-title' }, workspace.title !== '' ? workspace.title : G.basename(workspace.path)),
1873
- h('span', { className: 'gufa-workspace-path' }, workspace.path),
1882
+ 'button',
1883
+ {
1884
+ type: 'button',
1885
+ className: 'gufa-branch-row gufa-workspace-row',
1886
+ 'data-current': project !== null && project.root === workspace.path ? '' : undefined,
1887
+ title: `切换工作区 + 会话:${workspace.path}`,
1888
+ onClick: () => void switchWorkspace(workspace),
1889
+ },
1890
+ h(G.Icon, { name: 'folder-open', size: 13 }),
1891
+ h(
1892
+ 'span',
1893
+ { className: 'gufa-branch-name' },
1894
+ h('span', { className: 'gufa-workspace-title' }, workspace.title !== '' ? workspace.title : G.basename(workspace.path)),
1895
+ h('span', { className: 'gufa-workspace-path' }, workspace.path),
1896
+ ),
1897
+ project !== null && project.root === workspace.path
1898
+ ? h('span', { className: 'gufa-branch-tag' }, t('workspace.current'))
1899
+ : null,
1874
1900
  ),
1875
- project !== null && project.root === workspace.path
1876
- ? h('span', { className: 'gufa-branch-tag' }, t('workspace.current'))
1877
- : null,
1901
+ h(G.IconButton, {
1902
+ title: '只切换 IDE 项目(保持当前会话)',
1903
+ onClick: (event) => {
1904
+ event.preventDefault()
1905
+ event.stopPropagation()
1906
+ void pinProjectOnly(workspace)
1907
+ },
1908
+ }, h(G.Icon, { name: 'panel-left', size: 13 })),
1878
1909
  ),
1879
1910
  ),
1880
1911
  ),
@@ -225,6 +225,47 @@ const GUFA_PLUGIN = {
225
225
  /* ignore */
226
226
  }
227
227
 
228
+ /* ── 清理「每会话右侧面板布局」里由 dsh-vscode-mode 留下的『文件编辑』标签 ──
229
+ * 官方右侧栏会把每个会话的布局持久化到 localStorage(键 dsh.sidebar-right.v1.<sessionId>),
230
+ * 切换会话时恢复该布局 → 历史上被 vscode-mode 写过标签的会话会「自动展开右侧栏」。
231
+ * 这里在页面加载后清理这些残留键,让会话恢复成默认(收起)状态。 */
232
+ const cleanStaleSidebarLayouts = () => {
233
+ try {
234
+ const keys = []
235
+ for (let index = 0; index < window.localStorage.length; index += 1) {
236
+ const key = window.localStorage.key(index)
237
+ if (key !== null && key.startsWith('dsh.sidebar-right.v1.')) keys.push(key)
238
+ }
239
+ let removed = 0
240
+ for (const key of keys) {
241
+ const raw = window.localStorage.getItem(key)
242
+ if (raw === null) continue
243
+ if (raw.includes('edrvEditor') || raw.includes('vscode-mode')) {
244
+ window.localStorage.removeItem(key)
245
+ removed += 1
246
+ }
247
+ }
248
+ if (removed > 0) {
249
+ void G.api('dev.log', { message: `sidebar-layout-cleanup removed=${removed}/${keys.length}` }).catch(() => {})
250
+ }
251
+ } catch {
252
+ /* localStorage 不可用时忽略 */
253
+ }
254
+ }
255
+ cleanStaleSidebarLayouts()
256
+ window.setTimeout(cleanStaleSidebarLayouts, 1500)
257
+ window.setTimeout(cleanStaleSidebarLayouts, 5000)
258
+
259
+ // 聊天框:粘贴系统文件 → 自动插入 @文件引用(内容匹配项目内文件后插入)
260
+ try {
261
+ if (typeof G.installChatFilePaste === 'function') {
262
+ const disposeChatPaste = G.installChatFilePaste(ctx)
263
+ if (typeof disposeChatPaste === 'function') ctx.effect(() => disposeChatPaste, 'gufa-code: chat file paste')
264
+ }
265
+ } catch (error) {
266
+ console.error('[gufa-code] 安装聊天框文件粘贴失败', error)
267
+ }
268
+
228
269
  // 样式(随插件 context 卸载自动移除)
229
270
  ctx.effect(() => G.injectStyles(), 'gufa-code: styles')
230
271
 
@@ -0,0 +1,16 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Monaco worker 引导脚本(古法编程离线资产)。
4
+ *
5
+ * 与 Monaco 官方 AMD 用法一致:只设置 MonacoEnvironment.baseUrl + importScripts(workerMain.js),
6
+ * workerMain 内部自带的模块加载逻辑会按 baseUrl 去 importScripts 各依赖模块。
7
+ * (不要在这里再 importScripts(loader.js):worker 里 loader 与 workerMain 的模块系统会冲突,
8
+ * 表现为 workerMain 里 “X is not a function”。)
9
+ */
10
+ (function () {
11
+ var href = String(self.location.href || '')
12
+ var base = href.replace(/\/worker-bootstrap\.js(?:\?.*)?$/, '')
13
+ if (base === href || base === '') base = '/gufa-code/asset/monaco'
14
+ self.MonacoEnvironment = { baseUrl: base + '/' }
15
+ importScripts(base + '/base/worker/workerMain.js')
16
+ })()
Binary file