dsh-vscode-mode 0.29.2 → 0.31.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.
Files changed (80) hide show
  1. package/README.md +120 -11
  2. package/lib/client.js +178 -51
  3. package/lib/client.js.map +1 -1
  4. package/lib/index.js +4860 -1576
  5. package/lib/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/skills/dsh-vscodemode-html-plan/LICENSE +202 -0
  8. package/skills/dsh-vscodemode-html-plan/SKILL.md +147 -0
  9. package/skills/dsh-vscodemode-html-plan/examples/scheduled-send.html +298 -0
  10. package/skills/dsh-vscodemode-html-plan/references/blocks.md +227 -0
  11. package/skills/dsh-vscodemode-html-plan/references/subagent-brief.md +17 -0
  12. package/skills/dsh-vscodemode-html-plan/references/upstream-SKILL.md +174 -0
  13. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.css +564 -0
  14. package/skills/dsh-vscodemode-html-plan/runtime/htmlplan.js +1299 -0
  15. package/skills/dsh-vscodemode-html-plan/runtime/pack.mjs +300 -0
  16. package/src/ai/llmTask.ts +178 -0
  17. package/src/ai/llmTypes.ts +6 -0
  18. package/src/ai/svnCommitMsg.ts +107 -0
  19. package/src/ai/svnTriage.ts +34 -85
  20. package/src/client/aiCommit.ts +57 -0
  21. package/src/client/compatSummary.ts +15 -0
  22. package/src/client/editorFlush.ts +55 -0
  23. package/src/client/featurePrefs.ts +63 -0
  24. package/src/client/htmlPlan/HtmlPlanPanel.ts +261 -0
  25. package/src/client/htmlPlan/planActions.ts +347 -0
  26. package/src/client/htmlPlan/planPage.ts +333 -0
  27. package/src/client/htmlPreview.ts +218 -0
  28. package/src/client/index.ts +43 -0
  29. package/src/client/monaco/loader.ts +71 -9
  30. package/src/client/monaco/templateLanguages.ts +300 -0
  31. package/src/client/officialSidebar.ts +16 -4
  32. package/src/client/openPathRouter.ts +7 -0
  33. package/src/client/planState.ts +8 -2
  34. package/src/client/refCopy.ts +70 -0
  35. package/src/client/refIntake.ts +215 -0
  36. package/src/client/sidebar/menuItems.ts +11 -0
  37. package/src/client/sidebar/panels/FileExplorer.ts +11 -0
  38. package/src/client/sidebar/panels/SearchPanel.ts +214 -4
  39. package/src/client/sidebar/panels/SvnPanel.ts +17 -0
  40. package/src/client/sidebar/types.ts +2 -0
  41. package/src/client/styles/editor.css +112 -0
  42. package/src/client/svnActions.ts +7 -0
  43. package/src/client/svnCommit.ts +109 -0
  44. package/src/client/svnNotice.ts +1 -1
  45. package/src/client/svnStatus.ts +5 -2
  46. package/src/client/ui/DiffLauncher.ts +3 -1
  47. package/src/client/ui/EditorView.ts +221 -14
  48. package/src/client/ui/McpSettings.ts +108 -1
  49. package/src/client/ui/SvnAiPlanDialog.ts +24 -4
  50. package/src/client/ui/SvnCommitDialog.ts +458 -0
  51. package/src/client/ui/commandCatalog.ts +11 -0
  52. package/src/client/ui/svnCommitModel.ts +204 -0
  53. package/src/client/univer/UniverCacheSettings.ts +75 -0
  54. package/src/client/univer/UniverHost.ts +177 -0
  55. package/src/client/univer/api.ts +30 -0
  56. package/src/client/univer/routing.ts +32 -0
  57. package/src/client/univer/store.ts +111 -0
  58. package/src/fileOpenSettings.ts +118 -6
  59. package/src/htmlPlanCommand.ts +176 -0
  60. package/src/index.ts +4 -0
  61. package/src/paths.ts +5 -0
  62. package/src/refPointer.ts +193 -0
  63. package/src/rpc.ts +51 -0
  64. package/src/search/replacePlan.ts +144 -0
  65. package/src/search/replaceRun.ts +289 -0
  66. package/src/shared/keybindings.ts +11 -0
  67. package/src/shared/refSyntax.ts +106 -0
  68. package/src/shared/rpc.ts +28 -4
  69. package/src/shared/snippets.ts +17 -0
  70. package/src/shared/svn.ts +191 -10
  71. package/src/shared/svnActions.ts +16 -0
  72. package/src/shared/univer.ts +90 -0
  73. package/src/svn.ts +205 -47
  74. package/src/svnCommit.ts +348 -0
  75. package/src/svnCore.ts +254 -0
  76. package/src/svnToolJson.ts +73 -0
  77. package/src/svnTools.ts +566 -0
  78. package/src/univerBridge.ts +83 -0
  79. package/src/univerCache.ts +205 -0
  80. package/src/univerRpc.ts +144 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * dsh-vscode-mode client — 提交对话框纯投影(分区 / 默认勾选 / 校验 / 结果行)。
3
+ *
4
+ * 纯函数、无 RPC、无 React:勾选规则(谁默认勾、谁默认不勾)是产品口径,
5
+ * 必须能单测,否则「默认不勾未版本化」这类保护很容易在改 UI 时被顺手改掉。
6
+ * @author ddj 2026年11月15号
7
+ */
8
+ import type { SvnAiPlanCommit, SvnChangeEntry, SvnCommitEntry, SvnCommitResult, SvnStatusTone } from '../../shared/svn.js'
9
+ import { COMMIT_SUBJECT_MAX, SVN_STATUS_TONE, commitMsgErrorOf, isSvnChange } from '../../shared/svn.js'
10
+
11
+ /** 提交对话框里的一个分区。 */
12
+ export interface CommitSection {
13
+ /** 分区键(changelist:<name> / ungrouped / unversioned)。 */
14
+ key: string
15
+ /** 展示名。 */
16
+ label: string
17
+ /** 分区内条目。 */
18
+ entries: SvnChangeEntry[]
19
+ /** 默认是否勾选。 */
20
+ defaultChecked: boolean
21
+ }
22
+
23
+ /** 提交范围种子(AI 拆分建议 → 预填提交对话框)。 */
24
+ export interface CommitSeed {
25
+ /** 预选路径。 */
26
+ paths: string[]
27
+ /** 预填提交信息。 */
28
+ message?: string
29
+ }
30
+
31
+ /** 「提交时忽略」保留名(TortoiseSVN 约定:该组默认不提交)。 */
32
+ export const IGNORE_ON_COMMIT = 'ignore-on-commit'
33
+
34
+ /**
35
+ * 变更清单 → 分区(changelist 组 / 未分组 / 未版本控制)。
36
+ * 默认勾选:changelist 组与未分组为是;未版本控制与 ignore-on-commit 为否。
37
+ * @author ddj 2026年11月15号
38
+ * @param entries 变更清单
39
+ * @returns 分区列表(顺序:分组按名字、未分组、未版本控制)
40
+ */
41
+ export function commitSectionsOf(entries: readonly SvnChangeEntry[]): CommitSection[] {
42
+ const groups = new Map<string, SvnChangeEntry[]>()
43
+ const ungrouped: SvnChangeEntry[] = []
44
+ const unversioned: SvnChangeEntry[] = []
45
+ for (const entry of entries) {
46
+ if (!entry || !isSvnChange(entry)) continue
47
+ if (entry.status === 'unversioned') { unversioned.push(entry); continue }
48
+ if (entry.changelist) {
49
+ const bucket = groups.get(entry.changelist)
50
+ if (bucket) bucket.push(entry)
51
+ else groups.set(entry.changelist, [entry])
52
+ continue
53
+ }
54
+ ungrouped.push(entry)
55
+ }
56
+ const sections: CommitSection[] = []
57
+ for (const name of [...groups.keys()].sort((a, b) => a.localeCompare(b))) {
58
+ sections.push({
59
+ key: 'changelist:' + name,
60
+ label: name,
61
+ entries: groups.get(name) ?? [],
62
+ defaultChecked: name !== IGNORE_ON_COMMIT,
63
+ })
64
+ }
65
+ if (ungrouped.length) sections.push({ key: 'ungrouped', label: '(未分组)', entries: ungrouped, defaultChecked: true })
66
+ if (unversioned.length) sections.push({ key: 'unversioned', label: '(未版本控制)', entries: unversioned, defaultChecked: false })
67
+ return sections
68
+ }
69
+
70
+ /**
71
+ * 默认勾选集合(种子存在时只勾种子内路径,用于「逐组提交」预填)。
72
+ * @author ddj 2026年11月15号
73
+ * @param sections 分区
74
+ * @param seed 预选路径(空 = 按分区默认)
75
+ * @returns 勾选路径集合
76
+ */
77
+ export function defaultCheckedOf(sections: readonly CommitSection[], seed: readonly string[] = []): Set<string> {
78
+ if (seed.length) return new Set(seed)
79
+ const checked = new Set<string>()
80
+ for (const section of sections) {
81
+ if (!section.defaultChecked) continue
82
+ for (const entry of section.entries) checked.add(entry.path)
83
+ }
84
+ return checked
85
+ }
86
+
87
+ /** 已勾选范围统计(工具带「已选 N / M」、遥测行与主按钮计数同源)。 */
88
+ export interface CommitStats {
89
+ /** 全部分区条目数。 */
90
+ total: number
91
+ /** 已勾选条目数。 */
92
+ picked: number
93
+ /** 已勾选条目按状态分级计数(分级口径见 SVN_STATUS_TONE)。 */
94
+ byTone: Record<SvnStatusTone, number>
95
+ }
96
+
97
+ /**
98
+ * 统计提交范围:总数、勾选数、勾选条目按状态分级计数。
99
+ * @author ddj 2026年11月15号
100
+ * @param sections 分区
101
+ * @param checked 勾选路径集合
102
+ * @returns 统计结果(byTone 只统计已勾选条目;空集合各计数为 0)
103
+ */
104
+ export function commitStatsOf(sections: readonly CommitSection[], checked: ReadonlySet<string>): CommitStats {
105
+ const byTone: Record<SvnStatusTone, number> = { modified: 0, added: 0, deleted: 0, conflict: 0, plain: 0 }
106
+ let total = 0
107
+ let picked = 0
108
+ for (const section of sections) {
109
+ for (const entry of section.entries) {
110
+ total += 1
111
+ if (!checked.has(entry.path)) continue
112
+
113
+ picked += 1
114
+ byTone[SVN_STATUS_TONE[entry.status] ?? 'plain'] += 1
115
+ }
116
+ }
117
+ return { total, picked, byTone }
118
+ }
119
+
120
+ /**
121
+ * 分区勾选三态(分组头的全选 / 半选 / 未选)。
122
+ * @author ddj 2026年11月15号
123
+ * @param section 分区
124
+ * @param checked 勾选路径集合
125
+ * @returns `all` 全选、`none` 未选(含空分区)、`part` 部分勾选
126
+ */
127
+ export function groupTriStateOf(section: CommitSection, checked: ReadonlySet<string>): 'all' | 'none' | 'part' {
128
+ let picked = 0
129
+ for (const entry of section.entries) {
130
+ if (checked.has(entry.path)) picked += 1
131
+ }
132
+ if (!picked) return 'none'
133
+
134
+ return picked === section.entries.length ? 'all' : 'part'
135
+ }
136
+
137
+ /**
138
+ * 提交信息校验(首行 + 正文;与 host 同口径,只用于按钮禁用与就地提示)。
139
+ * @author ddj 2026年11月15号
140
+ * @param message 完整提交信息
141
+ * @returns 错误文案;合法为 null
142
+ */
143
+ export function commitMessageErrorOf(message: string): string | null {
144
+ const text = String(message ?? '')
145
+ if (!text.trim()) return '请填写提交信息'
146
+ const lines = text.replace(/\r\n/g, '\n').split('\n')
147
+ const subject = (lines[0] ?? '').trim()
148
+ const body = lines.slice(1).join('\n').trim()
149
+ return commitMsgErrorOf(subject, body)
150
+ }
151
+
152
+ /**
153
+ * 提交信息字符数提示(首行超长时前置警告)。
154
+ * @author ddj 2026年11月15号
155
+ * @param message 完整提交信息
156
+ * @returns 状态位文案
157
+ */
158
+ export function commitHintOf(message: string): string {
159
+ const lines = String(message ?? '').replace(/\r\n/g, '\n').split('\n')
160
+ const subject = (lines[0] ?? '').trim()
161
+ if (!subject) return '首行将作为提交标题'
162
+ return '首行 ' + subject.length + '/' + COMMIT_SUBJECT_MAX + ' 字符'
163
+ }
164
+
165
+ /**
166
+ * 提交结果 → 展示行(新版本号 / 逐文件动作 / 跳过项 / 冲突)。
167
+ * @author ddj 2026年11月15号
168
+ * @param result 提交结果
169
+ * @returns 展示行(空数组 = 无内容)
170
+ */
171
+ export function commitResultLinesOf(result: SvnCommitResult | null | undefined): string[] {
172
+ if (!result) return []
173
+ const lines: string[] = []
174
+ lines.push(result.revision !== undefined ? '提交成功:r' + result.revision : result.summary)
175
+ for (const entry of result.entries ?? []) lines.push(entry.action + ' ' + entry.path)
176
+ for (const path of result.skipped ?? []) lines.push('跳过 ' + path + '(无待提交变更)')
177
+ for (const path of result.conflicts ?? []) lines.push('冲突 ' + path + '(请先更新并解决)')
178
+ return lines
179
+ }
180
+
181
+ /**
182
+ * AI 拆分建议 → 提交对话框种子(逐组提交入口只预填,不自动提交)。
183
+ * @author ddj 2026年11月15号
184
+ * @param group AI 拆分建议组
185
+ * @returns 种子(路径 + 信息草稿)
186
+ */
187
+ export function commitSeedOf(group: SvnAiPlanCommit): CommitSeed {
188
+ const body = group.body ?? ''
189
+ return {
190
+ paths: [...group.paths],
191
+ message: body ? group.subject + '\n\n' + body : group.subject,
192
+ }
193
+ }
194
+
195
+ /**
196
+ * 逐文件动作 → 着色分组(结果区)。
197
+ * @author ddj 2026年11月15号
198
+ * @param entries 动作列表
199
+ * @returns 每行文本与语义色
200
+ */
201
+ export function commitEntryLinesOf(entries: readonly SvnCommitEntry[]): Array<{ text: string; tone: string }> {
202
+ const tone: Record<SvnCommitEntry['action'], string> = { M: 'modified', A: 'added', D: 'deleted', R: 'added' }
203
+ return entries.map((entry) => ({ text: entry.action + ' ' + entry.path, tone: tone[entry.action] ?? 'plain' }))
204
+ }
@@ -0,0 +1,75 @@
1
+ /** Current-workspace owned Office cache management. @author ddj 2026年11月13号 */
2
+ import React from 'react'
3
+ import { Button, Input } from '@deepseek-ai/dsh-client-ui-primitives'
4
+ import { rpc } from '../rpc.js'
5
+ import { openEditorView, emitRefresh } from '../events.js'
6
+ import { forgetUniver } from './store.js'
7
+ import type { UniverCacheList } from '../../shared/univer.js'
8
+
9
+ /** @private @author ddj 2026年11月13号 @param bytes Actual size. @returns Readable MiB. */
10
+ function sizeLabel(bytes: number): string { return (bytes / 1024 / 1024).toFixed(2) + ' MiB' }
11
+
12
+ /** @public @author ddj 2026年11月13号 @param props Active-session accessor; never accepts arbitrary workspace roots. @returns Explicit selection cleanup surface. */
13
+ export function UniverCacheSettings(props: { getSession: () => string | undefined }): React.ReactElement {
14
+ const [sessionId, setSessionId] = React.useState(props.getSession())
15
+ React.useEffect(() => {
16
+ const timer = window.setInterval(() => setSessionId(props.getSession()), 1000)
17
+ return () => window.clearInterval(timer)
18
+ }, [props.getSession])
19
+ const [cache, setCache] = React.useState<UniverCacheList>()
20
+ const [selected, setSelected] = React.useState(new Set<string>())
21
+ const [busy, setBusy] = React.useState(false)
22
+ const [message, setMessage] = React.useState('')
23
+ const sequence = React.useRef(0)
24
+ React.useEffect(() => {
25
+ void refresh()
26
+ return () => { sequence.current++ }
27
+ }, [sessionId])
28
+ /** @private @author ddj 2026年11月13号 @sideEffects Reads only current workspace; old-session responses never replace current results. */
29
+ async function refresh(): Promise<void> {
30
+ const generation = ++sequence.current
31
+ setCache(undefined)
32
+ setSelected(new Set())
33
+ if (!sessionId) { setMessage('选择一个工作区会话后查看缓存'); return }
34
+ setBusy(true)
35
+ try {
36
+ const result = await rpc('edrv.univer.cacheList', { sessionId })
37
+ if (generation !== sequence.current) return
38
+ if (!result.ok) throw new Error(result.error)
39
+ setCache(result.cache)
40
+ setMessage(result.cache.truncated ? '仅显示前500项,请分批管理' : '')
41
+ } catch (error) { if (generation === sequence.current) setMessage(String(error)) }
42
+ finally { if (generation === sequence.current) setBusy(false) }
43
+ }
44
+ /** @private @author ddj 2026年11月13号 @sideEffects Deletes only selected current revisions after explicit irreversible-loss confirmation. */
45
+ async function clean(): Promise<void> {
46
+ if (!sessionId || !cache || !cache.writable || busy) return
47
+ const chosen = cache.entries.filter((entry) => selected.has(entry.id))
48
+ if (!chosen.length || !window.confirm('清理所选 ' + chosen.length + ' 项缓存(' + sizeLabel(chosen.reduce((sum, entry) => sum + entry.bytes, 0)) + ')?可能包含尚未导出的编辑,删除不可恢复;原Office文件不受影响。占用条目会跳过。')) return
49
+ setBusy(true)
50
+ const generation = sequence.current
51
+ try {
52
+ const result = await rpc('edrv.univer.cacheClean', { sessionId, entries: chosen.map(({ id, revision }) => ({ id, revision })) })
53
+ if (generation !== sequence.current) return
54
+ if (!result.ok) throw new Error(result.error)
55
+ const deleted = new Set(result.results.filter((entry) => entry.status === 'deleted').map((entry) => entry.id))
56
+ forgetUniver(sessionId, chosen.filter((entry) => deleted.has(entry.id)).map((entry) => entry.file))
57
+ emitRefresh({ kind: 'structure' })
58
+ await refresh()
59
+ setMessage(result.results.map((entry) => (entry.status === 'deleted' ? '已删除' : entry.status === 'skipped' ? '已跳过' : '失败') + ':' + (chosen.find((item) => item.id === entry.id)?.source ?? entry.id) + (entry.reason ? ';' + entry.reason : '')).join('\n'))
60
+ } catch (error) { if (generation === sequence.current) setMessage(String(error)) }
61
+ finally { if (generation === sequence.current) setBusy(false) }
62
+ }
63
+ return React.createElement('section', { className: 'edrv-uv-cache-settings' },
64
+ React.createElement('h3', null, 'Univer 工作区缓存'),
65
+ React.createElement('p', null, '缓存可能包含唯一的未导出编辑,不自动清除。服务占用时跳过,不自动停服务。'),
66
+ cache ? React.createElement('p', { title: cache.root }, cache.workspace + ' · ' + cache.entries.length + ' 项 · ' + sizeLabel(cache.entries.reduce((sum, entry) => sum + entry.bytes, 0))) : null,
67
+ React.createElement(Button, { disabled: busy, onClick: refresh }, '刷新'),
68
+ React.createElement(Button, { disabled: busy || !cache?.writable || !selected.size, onClick: clean }, '清理所选'),
69
+ cache?.entries.map((entry) => React.createElement('div', { key: entry.id, className: 'edrv-uv-cache-row' },
70
+ React.createElement(Input, { type: 'checkbox', checked: selected.has(entry.id), disabled: busy || !cache.writable, 'aria-label': '选择 ' + entry.source, onChange: () => setSelected((current) => { const next = new Set(current); if (next.has(entry.id)) next.delete(entry.id); else next.add(entry.id); return next }) }),
71
+ React.createElement('span', null, entry.source, React.createElement('small', null, new Date(entry.createdAt).toLocaleString() + ' · ' + sizeLabel(entry.bytes) + ' · ' + (entry.complete ? '已准备' : '未完成'))),
72
+ React.createElement(Button, { disabled: busy, onClick: () => openEditorView(entry.file) }, '打开缓存'))),
73
+ cache && !cache.entries.length ? React.createElement('p', null, '当前工作区没有受管理的缓存') : null,
74
+ message ? React.createElement('p', { role: 'status', style: { whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' } }, message) : null)
75
+ }
@@ -0,0 +1,177 @@
1
+ /** Compact file-tab host for optional Univer documents. @author ddj 2026年11月12号 */
2
+ import React from 'react'
3
+ import { Button } from '@deepseek-ai/dsh-client-ui-primitives'
4
+ import { rpc } from '../rpc.js'
5
+ import { isUniverPath } from '../../shared/univer.js'
6
+ import { fileState, startGateway } from './api.js'
7
+ import { activeWorktree, reviewAddress, viewerAddress } from './routing.js'
8
+ import { confirmUniver, refreshUniver, subscribeUniver, trackUniver, univerSnapshot } from './store.js'
9
+ import type { SessionState } from './store.js'
10
+ import type { UniverFileState } from '../../shared/univer.js'
11
+
12
+ interface HostProps {
13
+ path: string
14
+ sessionId: string
15
+ onOpen: (path: string) => void
16
+ onFallback: () => void
17
+ source?: string
18
+ sourceChanged?: boolean
19
+ }
20
+ interface ImportControl {
21
+ create: (refresh?: boolean) => Promise<void>
22
+ start: () => Promise<void>
23
+ busy: boolean
24
+ error: string
25
+ }
26
+
27
+ /** @public @author ddj 2026年11月12号 @param sessionId Active scope. @returns Reactive in-page snapshot. */
28
+ export function useUniver(sessionId: string): SessionState {
29
+ const subscribe = React.useCallback((listener: () => void) => subscribeUniver(sessionId, listener), [sessionId])
30
+ const revision = React.useCallback(() => univerSnapshot(sessionId).revision, [sessionId])
31
+ React.useSyncExternalStore(subscribe, revision, revision)
32
+ return univerSnapshot(sessionId)
33
+ }
34
+
35
+ /** @private @author ddj 2026年11月12号 @param props File and scope. @param permitted Explicit writable consent. @param running Gateway state. @returns Latest visible file state or error. */
36
+ function useDocument(props: HostProps, permitted: boolean, running: boolean) {
37
+ const [state, setState] = React.useState<UniverFileState>()
38
+ const [error, setError] = React.useState('')
39
+ React.useEffect(() => {
40
+ void refreshUniver(props.sessionId)
41
+ if (!isUniverPath(props.path) || !permitted || !running) return
42
+ let active = true
43
+ let pending = false
44
+ const controller = new AbortController()
45
+ /** @private @author ddj 2026年11月12号 @sideEffects Polls only visible consented files; drops stale responses. */
46
+ async function load() {
47
+ if (pending || document.visibilityState === 'hidden') return
48
+ pending = true
49
+ try {
50
+ await refreshUniver(props.sessionId)
51
+ const current = univerSnapshot(props.sessionId)
52
+ if (!active || !current.confirmed || !current.capability?.writable || !current.capability.available) return
53
+ const next = await fileState(props.path, props.sessionId, controller.signal)
54
+ if (!active) return
55
+ setState(next)
56
+ trackUniver(props.sessionId, { file: props.path, state: next })
57
+ setError('')
58
+ } catch (cause) {
59
+ if (active) {
60
+ setState(undefined)
61
+ trackUniver(props.sessionId, { file: props.path, state: undefined })
62
+ setError(String(cause))
63
+ }
64
+ }
65
+ finally { pending = false }
66
+ }
67
+ void load()
68
+ const timer = window.setInterval(() => { void load() }, 5000)
69
+ return () => { active = false; controller.abort(); window.clearInterval(timer) }
70
+ }, [props.path, props.sessionId, permitted, running])
71
+ return { state, error }
72
+ }
73
+
74
+ /** @private @author ddj 2026年11月12号 @param props Source and navigation. @returns Explicit import/start commands with mounted-generation guard. */
75
+ function useImport(props: HostProps): ImportControl {
76
+ const [busy, setBusy] = React.useState(false)
77
+ const [error, setError] = React.useState('')
78
+ const operation = React.useRef(crypto.randomUUID())
79
+ const live = React.useRef(true)
80
+ const pending = React.useRef(false)
81
+ React.useEffect(() => { live.current = true; return () => { live.current = false } }, [])
82
+ /** @private @author ddj 2026年11月12号 @sideEffects Creates a new draft copy; never retries on uncertain results or navigates a different session. */
83
+ async function create(refresh = false): Promise<void> {
84
+ if (pending.current) return
85
+ pending.current = true
86
+ setBusy(true)
87
+ setError('创建副本并导入内容…')
88
+ try {
89
+ const source = props.source ?? props.path
90
+ const result = await rpc('edrv.univer.openCached', { sessionId: props.sessionId, source, operationId: operation.current, refresh })
91
+ if (!result.ok) throw new Error(result.error)
92
+ const imported = result.cached.imported
93
+ if (!imported.success) throw new Error((imported.error ?? '导入失败') + ';阶段:' + imported.stage + ';缓存:' + (imported.file ?? '未创建') + '。请在设置中检查,不要重复导入。')
94
+ trackUniver(props.sessionId, { file: imported.file!, source, sourceChanged: result.cached.sourceChanged, worktreeId: imported.worktreeId })
95
+ if (live.current) props.onOpen(imported.file!)
96
+ } catch (cause) { if (live.current) setError(String(cause)) }
97
+ finally { pending.current = false; if (live.current) setBusy(false) }
98
+ }
99
+ /** @private @author ddj 2026年11月12号 @sideEffects Starts Gateway only on explicit action. */
100
+ async function start(): Promise<void> {
101
+ try { setBusy(true); await startGateway(); await refreshUniver(props.sessionId); if (live.current) setError('') }
102
+ catch (cause) { if (live.current) setError(String(cause)) }
103
+ finally { if (live.current) setBusy(false) }
104
+ }
105
+ return { busy, error, create, start }
106
+ }
107
+
108
+ /** @private @author ddj 2026年11月12号 @param props File/scope. @param scope Current capability. @param control Explicit import actions. @returns Import and safety panel in one surface. */
109
+ function importPanel(props: HostProps, scope: SessionState, control: ImportControl): React.ReactElement {
110
+ return React.createElement('section', { className: 'edrv-uv-import' },
111
+ React.createElement('h3', null, '使用 Univer 编辑'),
112
+ React.createElement('p', null, '文档将自动保存到当前工作区 .dsh 专属缓存;原文件保持不变。已有编辑与草稿会保留。'),
113
+ !scope.confirmed ? consentPanel(props.sessionId) : null,
114
+ scope.confirmed ? React.createElement('p', { role: 'status' }, control.error || '正在准备工作区缓存…') : null)
115
+ }
116
+
117
+ /** @private @author ddj 2026年11月12号 @param sessionId Explicit consent scope. @returns Persistent risk explanation and affirmative action. */
118
+ function consentPanel(sessionId: string): React.ReactElement {
119
+ return React.createElement('section', { className: 'edrv-uv-consent' },
120
+ React.createElement('p', null, 'Viewer 仅适用于可信单用户环境,不能保证按会话隔离文件访问。此确认不会改变沙箱权限。'),
121
+ React.createElement(Button, { onClick: () => confirmUniver(sessionId, true) }, '我了解限制,允许当前会话加载 Viewer'))
122
+ }
123
+
124
+ /** @private @author ddj 2026年11月12号 @param props File/scope. @param scope Capability. @param control Import actions. @param state File state. @param selected Draft identity. @returns Guarded surface; no iframe before writable consent. */
125
+ function hostContent(props: HostProps, scope: SessionState, control: ImportControl, state?: UniverFileState, selected?: string): React.ReactNode {
126
+ if (!scope.capability?.available) return React.createElement('p', null, scope.error ?? 'Univer Office 未启用或接口不兼容')
127
+ if (!scope.capability.writable) return React.createElement('p', null, '当前会话为只读或策略不可用,未加载 Univer Viewer')
128
+ if (!isUniverPath(props.path)) return importPanel(props, scope, control)
129
+ if (!scope.confirmed) return consentPanel(props.sessionId)
130
+ if (scope.capability.gateway !== 'running') return React.createElement('section', null,
131
+ React.createElement('p', null, '启动 Univer 服务后可查看文档'), React.createElement(Button, { onClick: control.start, disabled: control.busy }, '启动服务'))
132
+ try {
133
+ const candidate = state && reviewAddress(state, selected)
134
+ if (!candidate) return React.createElement('p', null, '读取文档状态…')
135
+ const address = viewerAddress(candidate, window.location.origin, props.sessionId)
136
+ return React.createElement('iframe', { className: 'edrv-uv-frame', src: address, title: props.path })
137
+ } catch (cause) { return React.createElement('p', null, String(cause)) }
138
+ }
139
+
140
+ /** @public @author ddj 2026年11月12号 @param props File and active session. @returns In-tab import/consent/Viewer surface. */
141
+ export function UniverHost(props: HostProps): React.ReactElement {
142
+ const scope = useUniver(props.sessionId)
143
+ const control = useImport(props)
144
+ const permitted = scope.capability?.available === true && scope.capability.writable && scope.confirmed
145
+ const document = useDocument(props, permitted, scope.capability?.gateway === 'running')
146
+ const started = React.useRef(false)
147
+ React.useEffect(() => {
148
+ if (!permitted || isUniverPath(props.path) || started.current) return
149
+ started.current = true
150
+ void control.create()
151
+ }, [permitted, props.path])
152
+ const [selected, setSelected] = React.useState(univerSnapshot(props.sessionId).documents.get(props.path)?.worktreeId ?? '')
153
+ const drafts = document.state?.worktrees.filter(activeWorktree) ?? []
154
+ const source = props.source ?? scope.documents.get(props.path)?.source
155
+ return React.createElement('div', { className: 'edrv-uv-host', 'data-univer-path': props.path, 'data-univer-session': props.sessionId },
156
+ React.createElement('header', { className: 'edrv-uv-toolbar' }, React.createElement('span', { title: props.path }, (source ?? props.path).split(/[\\/]/).pop()),
157
+ React.createElement(Button, { onClick: () => setSelected('') }, '当前版本'),
158
+ drafts.map((draft) => React.createElement(Button, { key: draft.worktreeId, onClick: () => setSelected(draft.worktreeId) }, (draft.name ?? '草稿') + (draft.status === 'ready' ? ' · 审阅' : ' · 查看'))),
159
+ React.createElement(Button, { onClick: props.onFallback }, '其他打开方式')),
160
+ source ? React.createElement('small', { className: 'edrv-uv-notice' }, '来源:' + source + ';工作区缓存,原文件未修改') : null,
161
+ props.sourceChanged && source ? React.createElement('div', { className: 'edrv-uv-notice' }, '源文件已更新;当前缓存保留已有编辑。',
162
+ React.createElement(Button, { disabled: control.busy, onClick: () => { void control.create(true) } }, '导入源文件新版本')) : null,
163
+ control.error || document.error ? React.createElement('p', { role: 'status', className: 'edrv-uv-notice' }, control.error || document.error) : null,
164
+ hostContent(props, scope, control, document.state, selected),
165
+ React.createElement('footer', { className: 'edrv-uv-footer' }, '可信单用户环境 · 不承诺按会话隔离文件访问 · 原文件不自动覆盖'))
166
+ }
167
+
168
+ /** @public @author ddj 2026年11月12号 @param props Session and navigation. @returns Semantic-review entries excluded from text decisions. */
169
+ export function UniverReviews(props: { sessionId: string; onOpen: (path: string) => void }): React.ReactElement | null {
170
+ const scope = useUniver(props.sessionId)
171
+ if (!scope.capability?.available) return null
172
+ const documents = [...scope.documents.values()].filter((document) => document.state?.worktrees.some(activeWorktree))
173
+ if (!documents.length) return null
174
+ return React.createElement('section', { className: 'edrv-uv-reviews' }, React.createElement('h4', null, 'Univer 草稿'),
175
+ documents.map((document) => React.createElement(Button, { key: document.file, onClick: () => props.onOpen(document.file) }, document.file + ' · 查看 / 审阅')),
176
+ React.createElement('small', null, '仅显示当前会话已发现的文档;不参与代码批量采纳或撤销。'))
177
+ }
@@ -0,0 +1,30 @@
1
+ /** Authenticated same-origin Univer transport. @author ddj 2026年11月12号 */
2
+ import { transportUrl } from '../../shared/remoteChannel.js'
3
+ import type { UniverFileState } from '../../shared/univer.js'
4
+
5
+ /** @private @author ddj 2026年11月12号 @param path Known API path. @param signal Component lifetime. @param method Explicit HTTP method. @returns Checked JSON object. @throws Authentication, network or response failures. */
6
+ async function request(path: string, signal?: AbortSignal, method = 'GET'): Promise<Record<string, unknown>> {
7
+ const response = await fetch(transportUrl(path), { credentials: 'same-origin', method, signal })
8
+ if (!response.ok) throw new Error('Univer HTTP ' + response.status + (response.status === 401 ? ':请重新登录' : response.status === 403 ? ':访问被拒绝' : ''))
9
+ if (!response.headers.get('content-type')?.includes('application/json')) throw new Error('Univer 返回的不是 JSON')
10
+ const result: unknown = await response.json()
11
+ if (!result || typeof result !== 'object') throw new Error('Univer 响应格式不正确')
12
+ return result as Record<string, unknown>
13
+ }
14
+
15
+ /** @public @author ddj 2026年11月12号 @param file Container path. @param sessionId Active session. @param signal Request lifetime. @returns Validated file state, never starts Gateway explicitly. */
16
+ export async function fileState(file: string, sessionId: string, signal?: AbortSignal): Promise<UniverFileState> {
17
+ const result = await request('/univer-api/state?file=' + encodeURIComponent(file) + '&sessionId=' + encodeURIComponent(sessionId), signal)
18
+ if (result.ok !== true || !Array.isArray(result.worktrees) || typeof result.file !== 'string') throw new Error('Univer 文件状态不兼容')
19
+ if (result.viewerUrl !== null && typeof result.viewerUrl !== 'string') throw new Error('Univer Viewer 地址格式不兼容')
20
+ for (const worktree of result.worktrees) {
21
+ if (!worktree || typeof worktree.worktreeId !== 'string' || !Array.isArray(worktree.units) || !['draft', 'ready', 'merged', 'discarded'].includes(worktree.status)) throw new Error('Univer 草稿状态不兼容')
22
+ }
23
+ return result as unknown as UniverFileState
24
+ }
25
+
26
+ /** @public @author ddj 2026年11月12号 @param signal Request lifetime. @returns Explicit Gateway startup outcome. */
27
+ export async function startGateway(signal?: AbortSignal): Promise<void> {
28
+ const result = await request('/univer-api/gateway/start', signal, 'POST')
29
+ if (result.ok !== true) throw new Error(String(result.reason ?? 'Univer 服务启动失败'))
30
+ }
@@ -0,0 +1,32 @@
1
+ /** Optional document routing without importing an Office engine. @author ddj 2026年11月12号 */
2
+ import { isOfficePath, isUniverPath } from '../../shared/univer.js'
3
+ import type { UniverCapability, UniverFileState, UniverWorktree } from '../../shared/univer.js'
4
+
5
+ /** @public @author ddj 2026年11月12号 @param path File. @param capability Optional installed capability. @returns Whether the document uses the embedded host. */
6
+ export function routesUniver(path: string, capability?: UniverCapability): boolean {
7
+ return isUniverPath(path) || (isOfficePath(path) && capability?.available === true)
8
+ }
9
+
10
+ /** @public @author ddj 2026年11月12号 @param value Server-provided URL. @param origin Current application origin. @param sessionId Current session. @returns Validated same-origin Viewer URL. @throws Unsafe or unscoped address. */
11
+ export function viewerAddress(value: string, origin: string, sessionId: string): string {
12
+ const url = new URL(value, origin)
13
+ if (url.origin !== origin || !/^\/univer-viewer(?:\/|$)/.test(url.pathname) || url.searchParams.get('sessionId') !== sessionId) {
14
+ throw new Error('Univer 返回了不安全或缺少会话作用域的 Viewer 地址')
15
+ }
16
+ url.searchParams.set('sidebar', 'collapsed')
17
+ return url.toString()
18
+ }
19
+
20
+ /** @public @author ddj 2026年11月12号 @param state Current file state. @param worktreeId Selected draft. @returns Upstream address appropriate to status. */
21
+ export function reviewAddress(state: UniverFileState, worktreeId?: string): string | undefined {
22
+ const selected = state.worktrees.find((entry) => entry.worktreeId === worktreeId)
23
+ const worktree = selected ?? (state.viewerUrl ? undefined : state.worktrees.find(activeWorktree))
24
+ if (!worktree || !activeWorktree(worktree)) return state.viewerUrl ?? undefined
25
+ if (worktree.status === 'ready') return worktree.mergeUrl
26
+ return worktree.worktreeUrl ?? worktree.openUrl
27
+ }
28
+
29
+ /** @public @author ddj 2026年11月12号 @param worktree Current worktree. @returns True for unmerged drafts. */
30
+ export function activeWorktree(worktree: UniverWorktree): boolean {
31
+ return worktree.status === 'draft' || worktree.status === 'ready'
32
+ }
@@ -0,0 +1,111 @@
1
+ /** Session-scoped optional capability and discovered-document registry. @author ddj 2026年11月12号 */
2
+ import { rpc } from '../rpc.js'
3
+ import type { UniverCapability, UniverFileState } from '../../shared/univer.js'
4
+
5
+ export interface UniverDocument {
6
+ file: string
7
+ source?: string
8
+ sourceChanged?: boolean
9
+ worktreeId?: string
10
+ state?: UniverFileState
11
+ }
12
+ export interface SessionState {
13
+ capability?: UniverCapability
14
+ error?: string
15
+ confirmed: boolean
16
+ documents: Map<string, UniverDocument>
17
+ listeners: Set<() => void>
18
+ pending?: Promise<void>
19
+ revision: number
20
+ }
21
+ const sessions = new Map<string, SessionState>()
22
+ let activeSession = ''
23
+
24
+ /** @private @author ddj 2026年11月12号 @param sessionId Scope. @returns Stable in-page session registry. */
25
+ function sessionState(sessionId: string): SessionState {
26
+ let state = sessions.get(sessionId)
27
+ if (!state) {
28
+ state = { confirmed: false, documents: new Map(), listeners: new Set(), revision: 0 }
29
+ sessions.set(sessionId, state)
30
+ }
31
+ return state
32
+ }
33
+
34
+ /** @private @author ddj 2026年11月12号 @param state Changed registry. Notifies subscribed components. */
35
+ function notify(state: SessionState): void {
36
+ state.revision++
37
+ for (const listener of state.listeners) listener()
38
+ }
39
+
40
+ /** @public @author ddj 2026年11月12号 @param sessionId Current session. Clears safety consent after session switches. */
41
+ export function activateUniver(sessionId: string): void {
42
+ if (activeSession === sessionId) return
43
+ if (activeSession) {
44
+ const previous = sessionState(activeSession)
45
+ previous.confirmed = false
46
+ notify(previous)
47
+ }
48
+ activeSession = sessionId
49
+ }
50
+
51
+ /** @public @author ddj 2026年11月12号 @param sessionId Scope. @returns Current capability without triggering network or Gateway. */
52
+ export function univerCapability(sessionId: string): UniverCapability | undefined {
53
+ return sessionState(sessionId).capability
54
+ }
55
+
56
+ /** @public @author ddj 2026年11月12号 @param sessionId Scope. @returns Snapshot for React rendering. */
57
+ export function univerSnapshot(sessionId: string): SessionState {
58
+ return sessionState(sessionId)
59
+ }
60
+
61
+ /** @public @author ddj 2026年11月12号 @param sessionId Scope. @param listener Subscriber. @returns Cleanup. */
62
+ export function subscribeUniver(sessionId: string, listener: () => void): () => void {
63
+ const state = sessionState(sessionId)
64
+ state.listeners.add(listener)
65
+ return () => { state.listeners.delete(listener) }
66
+ }
67
+
68
+ /** @public @author ddj 2026年11月12号 @param sessionId Scope. @returns Coalesced non-mutating capability refresh. */
69
+ export function refreshUniver(sessionId: string): Promise<void> {
70
+ const state = sessionState(sessionId)
71
+ if (state.pending) return state.pending
72
+ const refresh = async (): Promise<void> => {
73
+ try {
74
+ const result = await rpc('edrv.univer.capabilities', { sessionId })
75
+ if (!result.ok) throw new Error(result.error)
76
+ state.capability = result.capability
77
+ state.error = undefined
78
+ if (!result.capability.available || !result.capability.writable) state.confirmed = false
79
+ } catch (error) {
80
+ state.capability = undefined
81
+ state.confirmed = false
82
+ state.error = String(error)
83
+ } finally {
84
+ state.pending = undefined
85
+ notify(state)
86
+ }
87
+ }
88
+ state.pending = refresh()
89
+ return state.pending
90
+ }
91
+
92
+ /** @public @author ddj 2026年11月12号 @param sessionId Scope. @param confirmed Explicit user consent. */
93
+ export function confirmUniver(sessionId: string, confirmed: boolean): void {
94
+ const state = sessionState(sessionId)
95
+ state.confirmed = confirmed && state.capability?.writable === true
96
+ notify(state)
97
+ }
98
+
99
+ /** @public @author ddj 2026年11月13号 @param sessionId Scope. @param files Deleted managed containers. Removes only cached navigation state. */
100
+ export function forgetUniver(sessionId: string, files: string[]): void {
101
+ const state = sessionState(sessionId)
102
+ for (const file of files) state.documents.delete(file)
103
+ notify(state)
104
+ }
105
+
106
+ /** @public @author ddj 2026年11月12号 @param sessionId Scope. @param document Discovered document; never scans workspace. */
107
+ export function trackUniver(sessionId: string, document: UniverDocument): void {
108
+ const state = sessionState(sessionId)
109
+ state.documents.set(document.file, { ...state.documents.get(document.file), ...document })
110
+ notify(state)
111
+ }