dsh-vscode-mode 0.26.0 → 0.27.1

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.
@@ -8,7 +8,7 @@
8
8
  * 作者 ddj 2026年09月10号
9
9
  */
10
10
  import React from 'react'
11
- import { forwardToEditor, parseOfficialFileAddress, resolveNavLine } from '../officialSidebar.js'
11
+ import { forwardToEditor, parseOfficialFileAddress, resolveNavLine, resolveNavColumn } from '../officialSidebar.js'
12
12
  import { log } from '../log.js'
13
13
 
14
14
  /** 转发尝试次数(含首次)与重试间隔。 */
@@ -68,17 +68,22 @@ export function createClaimRouter(spec) {
68
68
  const doneRef = React.useRef(-1)
69
69
 
70
70
  React.useEffect(() => {
71
- if (revision === doneRef.current) return
72
- doneRef.current = revision
71
+ const intent = JSON.stringify([props?.sessionId, tab?.id, revision, navigation?.address])
72
+ if (intent === doneRef.current) return
73
73
  const parsed = parseOfficialFileAddress(navigation?.address)
74
74
  if (!parsed) {
75
75
  setFailed(true)
76
76
  return
77
77
  }
78
78
  const line = resolveNavLine(navigation?.params)
79
+ const column = resolveNavColumn(navigation?.params)
80
+ let alive = true
81
+ setFailed(false)
79
82
  let left = FORWARD_ATTEMPTS
80
83
  const attempt = () => {
81
- if (forwardToEditor(service, parsed.path, line, navigation?.params?.preview)) {
84
+ if (!alive || tab?.signal?.aborted) return
85
+ if (forwardToEditor(typeof tab?.actions?.openTab === 'function' ? tab.actions : service, parsed.path, line, navigation?.params?.preview, column)) {
86
+ doneRef.current = intent
82
87
  closeTab(tab)
83
88
  return
84
89
  }
@@ -87,7 +92,8 @@ export function createClaimRouter(spec) {
87
92
  else setFailed(true)
88
93
  }
89
94
  attempt()
90
- }, [revision])
95
+ return () => { alive = false }
96
+ }, [revision, props?.sessionId, tab?.id, navigation?.address])
91
97
 
92
98
  if (!failed || typeof fallback !== 'function') return null
93
99
  return React.createElement(fallback, props)
@@ -43,7 +43,15 @@ export function EditorPane(props: PaneProps): React.ReactElement {
43
43
  /** @private @author ddj 2026年10月14号 @param event Close press. Never start a drag. */
44
44
  function stop(event: React.PointerEvent): void { event.stopPropagation() }
45
45
  /** @private @author ddj 2026年10月14号 @param event Keyboard activation. */
46
- function key(event: React.KeyboardEvent): void { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); props.onSelect(group.id, tab.path) } }
46
+ function key(event: React.KeyboardEvent): void {
47
+ if (event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10')) {
48
+ event.preventDefault(); event.stopPropagation()
49
+ const rect = event.currentTarget.getBoundingClientRect()
50
+ props.onMenu(tab.path, { clientX: rect.left, clientY: rect.bottom } as React.MouseEvent)
51
+ return
52
+ }
53
+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); props.onSelect(group.id, tab.path) }
54
+ }
47
55
  return React.createElement('div', {
48
56
  key: tab.path, 'data-edrv-tab-path': tab.path, role: 'tab', tabIndex: 0, 'aria-selected': selected,
49
57
  className: 'edrv-tab' + (selected ? ' edrv-tab-active' : '') + (tab.pinned ? ' edrv-tab-pinned' : ''),
@@ -29,7 +29,7 @@ import { toastDom } from '../externalOpen.js'
29
29
  import { ReviewAllConfirm } from './ReviewAllConfirm.js'
30
30
  import { reviewRegions } from '../../shared/reviewRegions.js'
31
31
  import { PENDING_PREFIX } from '../../shared/pendingReview.js'
32
- import { coveredPathKeys, diffPathKey, diffSummary } from '../state/diffSummary.js'
32
+ import { coveredPathKeys, diffPathKey, diffSummary, reviewPathOf } from '../state/diffSummary.js'
33
33
  import { emitFileChanged, emitRefresh } from '../events.js'
34
34
  import { langOf, loadMonaco, snippetLanguageOf } from '../monaco/loader.js'
35
35
  import { bindEditActions, runEditAction } from '../monaco/editActions.js'
@@ -136,7 +136,7 @@ import { clampToolbarPosition, loadToolbarPosition, saveToolbarPosition } from '
136
136
  import { editorModelPathOf } from '../dap/modelPath.js'
137
137
  import { dapTrace } from '../dap/trace.js'
138
138
  import { isSessionMissingError, sessionErrorText, sessionMissingDetail, sessionMissingTitle } from '../sessionError.js'
139
- import { officialDownView, SESSION_DOWN_NOTICE, SIDECAR_KEEP_DONE } from '../reviewBar.js'
139
+ import { emptyTextReview, officialDownView, SESSION_DOWN_NOTICE, SIDECAR_KEEP_DONE } from '../reviewBar.js'
140
140
 
141
141
  /** 官方差异读取失败前缀:仅用于清理同源陈旧错误,不吞并保存类错误。@author ddj 2026年10月27号 */
142
142
  const REVIEW_LOAD_ERROR = '官方差异读取失败:'
@@ -274,11 +274,11 @@ export function EditorView(props) {
274
274
  const [monacoErr, setMonacoErr] = React.useState(null)
275
275
  const [records, setRecords] = React.useState({})
276
276
  const [review, setReview] = React.useState({ page: null, error: '' })
277
+ React.useEffect(() => { setReview({ page: null, error: '' }) }, [sessionId])
277
278
  React.useEffect(() => {
278
- setReview({ page: null, error: '' })
279
- if (!sessionId) return undefined
279
+ if (!sessionId || props.visible === false) return undefined
280
280
  return subscribeReview(sessionId, setReview)
281
- }, [sessionId])
281
+ }, [sessionId, props.visible])
282
282
  const [tabs, setTabs] = React.useState([])
283
283
  const [active, setDiskActive] = React.useState(null)
284
284
  const [planTabs, setPlanTabs] = React.useState([])
@@ -595,14 +595,9 @@ export function EditorView(props) {
595
595
  const controller = new AbortController()
596
596
  // 待审条目也走同一条行内差异通道:它由累计基线投影而来,形状与官方条目一致,
597
597
  // 因此编辑器里天然就能画行内差异与 Keep/Undo 药丸,不必另开一个窄面板。
598
- const pendingPath = (review.page?.items ?? [])
599
- .filter((item) => String(item.id).startsWith(PENDING_PREFIX))
600
- .map((item) => item.currentPath || item.path)
601
- .find((path) => sameFile(path, active))
602
- const coveredPath = review.page?.overview?.coveredPaths.find((path) => sameFile(path, active))
603
- const reviewPath = coveredPath ?? pendingPath
604
- dbg(sessionId, `[DEBUG reviewPath] active=${active ?? '(null)'} covered=${coveredPath ?? '(none)'}`
605
- + ` pending=${pendingPath ?? '(none)'} coveredCount=${review.page?.overview?.coveredPaths.length ?? -1}`
598
+ const reviewPath = reviewPathOf(active, review.page, sameFile)
599
+ dbg(sessionId, `[DEBUG reviewPath] active=${active ?? '(null)'} resolved=${reviewPath ?? '(none)'}`
600
+ + ` coveredCount=${review.page?.overview?.coveredPaths.length ?? -1}`
606
601
  + ` items=${review.page?.items?.length ?? -1} overview=${review.page?.overview ? 1 : 0}`)
607
602
  if (!active || !reviewPath) {
608
603
  setOfficialDetail(null)
@@ -696,9 +691,11 @@ export function EditorView(props) {
696
691
  const decideRegions = React.useMemo(() => [...pendingRegions, ...staleRegions], [pendingRegions, staleRegions])
697
692
  // 记录的改动已全部不在当前文件中时没有可见差异可审:自动结案,不再让「改动已失效」占用差异栏。
698
693
  React.useEffect(() => {
699
- if (!officialDetail || contentReady !== true || batchBusyRef.current) return
700
- if (pendingRegions.length > 0 || staleRegions.length === 0) return
701
- if (noBlocks || officialDetail.capability?.keep !== true) return
694
+ if (!officialDetail || batchBusyRef.current) return
695
+ // 空净差异只依赖权威快照,不依赖编辑器磁盘加载;定位失效仍须等待当前内容就绪。
696
+ const emptyText = emptyTextReview(officialDetail)
697
+ if (!emptyText && (contentReady !== true || pendingRegions.length > 0 || staleRegions.length === 0 || noBlocks)) return
698
+ if (officialDetail.capability?.keep !== true) return
702
699
  if (dirtyRef.current[active]) return
703
700
 
704
701
  void settleInvisibleRecord(officialDetail)
@@ -1454,12 +1451,12 @@ export function EditorView(props) {
1454
1451
 
1455
1452
  // 挂载:接入会话级共享订阅(单定时器由 recordsFeed 持有,本组件不再自建 interval)
1456
1453
  React.useEffect(() => {
1457
- if (!sessionId) return undefined
1454
+ if (!sessionId || props.visible === false) return undefined
1458
1455
  const offRecords = subscribeRecords(sessionId, applyRecords)
1459
1456
  const offErrors = subscribeErrors(sessionId, (message) => setError('list异常:' + message))
1460
1457
  refreshRecords()
1461
1458
  return () => { offRecords(); offErrors() }
1462
- }, [sessionId])
1459
+ }, [sessionId, props.visible])
1463
1460
 
1464
1461
  /**
1465
1462
  * 展示外部同步提示(按路径+类型去重:同一文件重复回调不重置已关闭的提示)。
@@ -1560,12 +1557,21 @@ export function EditorView(props) {
1560
1557
  })
1561
1558
 
1562
1559
  React.useEffect(() => {
1563
- const publishLsp = (servers) => setLspServers(Array.isArray(servers) ? servers : [])
1560
+ let alive = true
1561
+ let loading = false
1562
+ const publishLsp = (servers) => { if (alive) setLspServers(Array.isArray(servers) ? servers : []) }
1563
+ const refreshLsp = async () => {
1564
+ if (loading || props.visible === false || document.hidden) return
1565
+ loading = true
1566
+ try { publishLsp(await refreshStatus(true)) }
1567
+ finally { loading = false }
1568
+ }
1564
1569
  const unsubscribe = onLspProgress(publishLsp)
1565
- void refreshStatus(true).then(publishLsp)
1566
- const timer = setInterval(() => { void refreshStatus(true).then(publishLsp) }, 1500)
1567
- return () => { unsubscribe(); clearInterval(timer) }
1568
- }, [sessionId])
1570
+ void refreshLsp()
1571
+ const timer = setInterval(refreshLsp, 1500)
1572
+ document.addEventListener('visibilitychange', refreshLsp)
1573
+ return () => { alive = false; unsubscribe(); clearInterval(timer); document.removeEventListener('visibilitychange', refreshLsp) }
1574
+ }, [sessionId, props.visible])
1569
1575
 
1570
1576
  // LSP 会话:EditorView 持有权威 sessionId,直接写入 lspClient 并广播。
1571
1577
  // 直接调用不依赖事件时序(订阅可能晚于首次派发),广播供其它消费方复用。
@@ -1609,6 +1615,9 @@ export function EditorView(props) {
1609
1615
  const fileOpenRef = React.useRef(null)
1610
1616
  /** @private @author ddj 2026年10月08号 @param e Routed file request. Always uses the current workspace and save/preview callbacks. */
1611
1617
  fileOpenRef.current = (e) => {
1618
+ if (e?.detail?.sessionId && e.detail.sessionId !== sessionId) return
1619
+ if (e?.detail?.ownerId && e.detail.ownerId !== props?.ownerId) return
1620
+ if (!e?.detail?.ownerId && props?.visible === false) return
1612
1621
  const p = e?.detail?.path
1613
1622
  if (!p) return
1614
1623
  // G9:入口统一归一为工作区相对路径(差异栏/对话链接/LSP 跳转等都经此事件)
@@ -3540,7 +3549,7 @@ export function EditorView(props) {
3540
3549
  const allPending = React.useMemo(() => {
3541
3550
  const out = []
3542
3551
  for (const rec of Object.values(records)) {
3543
- if (rec.superseded === true || coveredPaths.has(diffPathKey(rec.path))) continue
3552
+ if (rec.archived === true || rec.superseded === true || coveredPaths.has(diffPathKey(rec.path))) continue
3544
3553
  const perHunk = Array.isArray(rec.decisions?.perHunk) ? rec.decisions.perHunk : []
3545
3554
  const hunks = Array.isArray(rec.hunks) ? rec.hunks : []
3546
3555
  for (let i = 0; i < hunks.length; i++) {
@@ -4108,6 +4117,8 @@ export function EditorView(props) {
4108
4117
  }
4109
4118
  const tabMenuActions = (path) => ({
4110
4119
  'add-to-conversation': () => addRefToChat(path),
4120
+ 'forge-open': () => props.forge?.open(sessionId),
4121
+ 'forge-local': () => props.forge?.open(sessionId, true),
4111
4122
  'split-left': () => splitTab(path, 'left'),
4112
4123
  'split-right': () => splitTab(path, 'right'),
4113
4124
  'split-top': () => splitTab(path, 'top'),
@@ -4144,6 +4155,7 @@ export function EditorView(props) {
4144
4155
  cwd,
4145
4156
  hasSession: Boolean(sessionId),
4146
4157
  canAddToConversation: Boolean(addToConversation),
4158
+ forgeReady: props.forge?.available() === true,
4147
4159
  canSplit: workbench.groups.length < GROUP_LIMIT && !workbench.floats.some((item) => item.group === ownerOf(workbench, tabMenu.path)?.id),
4148
4160
  canFloat: workbench.groups.length < GROUP_LIMIT,
4149
4161
  canReturn: ownerOf(workbench, tabMenu.path)?.id !== MAIN_GROUP,
@@ -4442,6 +4454,25 @@ export function EditorView(props) {
4442
4454
  function consumeDrag() { return dragRef.current?.consumeClick() ?? false }
4443
4455
  /** @private @author ddj 2026年10月14号 @param path File. @param event Context trigger. */
4444
4456
  function paneMenu(path, event) { setTabMenu({ path, x: event.clientX, y: event.clientY }) }
4457
+ const menuOwner = React.useRef({ sessionId, scope, alive: true })
4458
+ menuOwner.current.sessionId = sessionId
4459
+ menuOwner.current.scope = scope
4460
+ const menuValid = React.useRef(null)
4461
+ React.useEffect(() => {
4462
+ menuOwner.current.alive = props.visible !== false
4463
+ return () => { menuOwner.current.alive = false; if (menuValid.current) props.officialMenus?.invalidate(menuValid.current) }
4464
+ }, [sessionId, scope, props.visible, props.officialMenus])
4465
+ React.useEffect(() => {
4466
+ if (!tabMenu || !props.officialMenus || !sessionId) return
4467
+ const capturedSession = sessionId
4468
+ const capturedScope = scope
4469
+ const path = tabMenu.path
4470
+ const groupId = ownerOf(benchRef.current, path)?.id
4471
+ const valid = () => menuOwner.current.alive && menuOwner.current.sessionId === capturedSession && menuOwner.current.scope === capturedScope && ownerOf(benchRef.current, path)?.id === groupId && tabsRef.current.some((tab) => tab.path === path)
4472
+ menuValid.current = valid
4473
+ const items = tabMenuEntries().map((entry) => ({ ...entry, run: entry.onClick ?? (() => {}) }))
4474
+ if (props.officialMenus.open('tab', sessionId, path, { x: tabMenu.x, y: tabMenu.y }, items, valid)) setTabMenu(null)
4475
+ }, [tabMenu, props.officialMenus, sessionId, scope])
4445
4476
  /** @private @author ddj 2026年10月14号 @param group Auxiliary group. Return documents rather than closing them. */
4446
4477
  function returnPane(group) { acceptLayout(returnGroup(benchRef.current, group)) }
4447
4478
  /** @private @author ddj 2026年10月14号 @param group Float id. @param rect Viewport-safe bounds. */
@@ -4928,7 +4959,7 @@ export function EditorView(props) {
4928
4959
  * @author ddj 2026年09月29号
4929
4960
  * @returns 含布局及操作回调的差异快照
4930
4961
  */
4931
- const officialFile = review.page?.overview?.coveredPaths.find((path) => sameFile(path, active))
4962
+ const officialFile = reviewPathOf(active, review.page, sameFile)
4932
4963
  // 官方通道自身的失败(list 失败 / 缺 overview)只影响官方栏,不能混进保存类错误。
4933
4964
  const officialDown = officialFile ? null : officialDownView(review.error)
4934
4965
  const rawReviewError = review.error || error
@@ -5047,6 +5078,9 @@ export function EditorView(props) {
5047
5078
  editor: () => editorRef.current,
5048
5079
  outlineSources: props.outlineSources,
5049
5080
  fileMenuItems: props.fileMenuItems,
5081
+ officialMenus: props.officialMenus,
5082
+ visible: props.visible,
5083
+ forge: props.forge,
5050
5084
  addToConversation,
5051
5085
  svn: svnStatus,
5052
5086
  // SVN 变更:面板列表 + 文件树徽标查表(客户端合成,不改 listDir 契约)
@@ -11,7 +11,7 @@ import React from 'react'
11
11
  import { pickSessionScope } from '../sessionScope.js'
12
12
  import { EditorView } from './EditorView.js'
13
13
  import { setSideEditorMounted } from '../sidebarBridge.js'
14
- import { editorMountEpoch, markEditorActive, markEditorMounted, parseOfficialFileAddress, resolveNavLine, resolveNavOpen } from '../officialSidebar.js'
14
+ import { editorMountEpoch, markEditorActive, markEditorMounted, parseOfficialFileAddress, resolveNavLine, resolveNavColumn, resolveNavOpen } from '../officialSidebar.js'
15
15
 
16
16
  /**
17
17
  * 官方侧边栏 Tab 正文组件(keyed slot sidebar.right.pane.tab 装配)。
@@ -22,10 +22,14 @@ export function OfficialSideTab(props) {
22
22
  const sessionId = props?.sessionId
23
23
  const useTabInfo = props?.useTabInfo
24
24
  let navigation
25
+ let tab
26
+ let visible = true
25
27
  // useTabInfo 是 slot 框架按组件实例生成的 hook,须在组件顶层无条件调用
26
28
  if (typeof useTabInfo === 'function') {
27
29
  try {
28
- navigation = useTabInfo()?.tab?.navigation
30
+ tab = useTabInfo()?.tab
31
+ navigation = tab?.navigation
32
+ visible = tab?.visible !== false
29
33
  } catch {
30
34
  navigation = undefined
31
35
  }
@@ -67,16 +71,16 @@ export function OfficialSideTab(props) {
67
71
  // file 资源 Tab:地址即文件(解码出真实路径,透传 params.line 行号定位)
68
72
  const fileHit = parseOfficialFileAddress(navigation?.address)
69
73
  if (fileHit) {
70
- const line = navigation?.params?.line
74
+ const line = resolveNavLine(navigation?.params)
71
75
  window.dispatchEvent(new CustomEvent('edrv:open-editor', {
72
- detail: { path: fileHit.path, line: typeof line === 'number' ? line : undefined, preview: navigation?.params?.preview },
76
+ detail: { sessionId, ownerId: tab?.id, path: fileHit.path, line, column: resolveNavColumn(navigation?.params), preview: navigation?.params?.preview },
73
77
  }))
74
78
  return
75
79
  }
76
80
  // 页类型 Tab:params 携带打开请求(line = 行引用/工具行跳转的行号定位)
77
81
  const request = resolveNavOpen(navigation?.params)
78
82
  window.dispatchEvent(new CustomEvent('edrv:open-editor', {
79
- detail: { path: request.path, focusDiff: request.focusDiff, line: resolveNavLine(navigation?.params), preview: navigation?.params?.preview },
83
+ detail: { sessionId, ownerId: tab?.id, path: request.path, focusDiff: request.focusDiff, line: resolveNavLine(navigation?.params), column: resolveNavColumn(navigation?.params), preview: navigation?.params?.preview },
80
84
  }))
81
85
  })
82
86
 
@@ -84,11 +88,15 @@ export function OfficialSideTab(props) {
84
88
  key: sessionId,
85
89
  sessionId,
86
90
  layout: 'side',
91
+ visible,
92
+ ownerId: tab?.id,
87
93
  schedule: props?.schedule,
88
94
  addToConversation: props?.addToConversation,
89
95
  sidebarPanels: props?.sidebarPanels,
90
96
  outlineSources: props?.outlineSources,
91
97
  fileMenuItems: props?.fileMenuItems,
98
+ officialMenus: props?.officialMenus,
99
+ forge: props?.forge,
92
100
  fileOpeners: props?.fileOpeners,
93
101
  sessions: props?.sessions,
94
102
  })
@@ -2,15 +2,32 @@
2
2
  * 待审差异采集:环绕一次文件写入读取真实前后内容,只有内容确实变化才落库。
3
3
  * @author ddj 2026年10月29号
4
4
  */
5
- import { cwdOf } from '../registry.js'
6
- import { resolveTarget } from '../store.js'
5
+ import { cwdOfSession } from '../store.js'
7
6
  import type { Ctx } from '../store.js'
8
7
  import { log } from '../log.js'
8
+ import { toolTargets, patchDiagnostics } from '../toolTargets.js'
9
+ import { rawText, rawReviewFile } from '../reviewEvidence.js'
9
10
 
10
11
  /** 可被采信为待审来源的写文件工具。 */
11
- const WRITE_TOOLS = ['edit', 'write', 'str_replace_editor']
12
+ const WRITE_TOOLS = ['edit', 'write', 'str_replace_editor', 'apply_patch']
12
13
  /** 单文件文本上限:超过即标注 oversized,不静默截断。 */
13
14
  const MAX_TEXT = 1024 * 1024
15
+ const captureGaps = new Map<string, { cwd: string; sessionId: string; message: string }>()
16
+
17
+ /** @public @author ddj 2026年11月04号 @param cwd Workspace identity. @returns Bounded runtime-only capture diagnostics. */
18
+ export function pendingGaps(cwd: string): string[] {
19
+ return [...captureGaps.values()].filter((gap) => gap.cwd === cwd).map((gap) => gap.message)
20
+ }
21
+
22
+ /** @private @author ddj 2026年11月04号 @param ctx Host scope. @param exec Original call. @param path Failed target. @param error Evidence failure. Records no writable state. */
23
+ function recordGap(scope: { cwd: string; sessionId: string }, exec: WriteExec, path: string, error: unknown): void {
24
+ const { cwd, sessionId } = scope
25
+ const key = JSON.stringify([cwd, sessionId, exec.id, path])
26
+ captureGaps.set(key, { cwd, sessionId, message: path + ': ' + String(error) })
27
+ const local = [...captureGaps].filter(([, gap]) => gap.cwd === cwd)
28
+ while (local.length > 50) captureGaps.delete(local.shift()![0])
29
+ while (captureGaps.size > 500) captureGaps.delete(captureGaps.keys().next().value!)
30
+ }
14
31
 
15
32
  /** 一次已确认的写入。 */
16
33
  export interface PendingWrite {
@@ -33,12 +50,14 @@ export interface PendingCapture {
33
50
  interface CaptureState {
34
51
  busy: Set<string>
35
52
  stopped: boolean
53
+ disposed: Set<string>
36
54
  }
37
55
 
38
56
  /** 工具的写工具参数形状;只取本采集关心的字段。 */
39
57
  interface WriteExec {
58
+ id?: string
40
59
  name?: string
41
- arguments?: { file_path?: unknown; path?: unknown }
60
+ arguments?: { file_path?: unknown; path?: unknown; input?: unknown }
42
61
  agent?: { session?: { id?: string; cwd?: string } }
43
62
  }
44
63
 
@@ -50,12 +69,19 @@ interface WriteExec {
50
69
  * @returns 可释放的采集器
51
70
  */
52
71
  export function installPending(ctx: Ctx, sink: (write: PendingWrite) => void): PendingCapture {
53
- const state: CaptureState = { busy: new Set<string>(), stopped: false }
72
+ const state: CaptureState = { busy: new Set<string>(), stopped: false, disposed: new Set<string>() }
54
73
  ctx.on('tools/execute', (exec: WriteExec, next: () => Promise<unknown>) => aroundTool(ctx, state, sink, exec, next))
74
+ ctx.on('session/disposed', (session: { id: string }) => {
75
+ state.disposed.add(session.id)
76
+ for (const [key, gap] of captureGaps) {
77
+ if (gap.sessionId === session.id) captureGaps.delete(key)
78
+ }
79
+ })
55
80
  return {
56
81
  dispose(): void {
57
82
  state.stopped = true
58
83
  state.busy.clear()
84
+ captureGaps.clear()
59
85
  },
60
86
  }
61
87
  }
@@ -68,20 +94,24 @@ export function installPending(ctx: Ctx, sink: (write: PendingWrite) => void): P
68
94
  * @param exec 工具分发上下文
69
95
  * @returns 采集计划或 null
70
96
  */
71
- async function planOf(ctx: Ctx, state: CaptureState, exec: WriteExec): Promise<CapturePlan | null> {
72
- const session = exec.agent?.session
73
- const requested = exec.arguments?.file_path ?? exec.arguments?.path
74
- if (state.stopped || !session?.id || typeof requested !== 'string') return null
75
- if (!WRITE_TOOLS.includes(String(exec.name))) return null
76
- const cwd = cwdOf(session as never)
77
- if (!cwd) return null
78
- const fs = ctx.get('fs')
79
- const target = await resolveTarget(ctx, session as never, requested)
97
+ async function planOf(scope: { cwd: string; sessionId: string; fs: any }, state: CaptureState, requested: string): Promise<CapturePlan | null> {
98
+ const { cwd, sessionId, fs } = scope
99
+ if (state.stopped || state.disposed.has(sessionId)) return null
100
+ const target = await fs.resolve(requested, { cwd })
80
101
  const identity = fs.processPath(target)
81
- if (typeof identity !== 'string' || !identity || state.busy.has(identity)) return null
82
- const before = await readText(fs, target)
83
- if (before !== null && before.length > MAX_TEXT) return null
84
- return { cwd: String(cwd), sessionId: String(session.id), path: requested, identity, before, session: session as never }
102
+ if (state.stopped || state.disposed.has(sessionId) || typeof identity !== 'string' || !identity || state.busy.has(identity)) return null
103
+ state.busy.add(identity)
104
+ try {
105
+ const before = await readText(fs, target)
106
+ if (state.stopped || state.disposed.has(sessionId) || (before !== null && before.length > MAX_TEXT)) {
107
+ state.busy.delete(identity)
108
+ return null
109
+ }
110
+ return { cwd: String(cwd), sessionId, path: requested, identity, before, target, fs }
111
+ } catch (error) {
112
+ state.busy.delete(identity)
113
+ throw error
114
+ }
85
115
  }
86
116
 
87
117
  /** 一次采集所需的固定信息。 */
@@ -91,7 +121,8 @@ interface CapturePlan {
91
121
  path: string
92
122
  identity: string
93
123
  before: string | null
94
- session: never
124
+ target: unknown
125
+ fs: any
95
126
  }
96
127
 
97
128
  /**
@@ -108,58 +139,76 @@ async function aroundTool(
108
139
  ctx: Ctx, state: CaptureState, sink: (write: PendingWrite) => void,
109
140
  exec: WriteExec, next: () => Promise<unknown>,
110
141
  ): Promise<unknown> {
111
- let plan: CapturePlan | null = null
142
+ if (state.stopped || !WRITE_TOOLS.includes(String(exec.name))) return next()
143
+ const session = exec.agent?.session
144
+ const cwd = session ? cwdOfSession(ctx, session as never) : null
145
+ if (!session?.id || !cwd) return next()
146
+ const scope = { cwd, sessionId: session.id, fs: ctx.get('fs') }
147
+ const plans: CapturePlan[] = []
112
148
  try {
113
- plan = await planOf(ctx, state, exec)
114
- } catch (error) {
115
- log.debug('待审采集跳过:' + String(error))
116
- }
117
- if (!plan) return next()
149
+ const paths = await toolTargets(exec)
150
+ for (const path of paths) {
151
+ try {
152
+ if (plans.length >= 16) throw new Error('capture target budget exceeded')
153
+ const plan = await planOf(scope, state, path)
154
+ if (plan) plans.push(plan)
155
+ } catch (error) { if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, path, error); log.debug('待审采集跳过:' + path + ': ' + String(error)) }
156
+ }
157
+ } catch (error) { if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, String(exec.name), error); log.debug('待审目标不可用:' + String(error)) }
118
158
 
119
- state.busy.add(plan.identity)
120
159
  try {
121
- return await next()
160
+ const result = await next()
161
+ if (exec.name === 'apply_patch' && !state.stopped && !state.disposed.has(scope.sessionId)) {
162
+ for (const diagnostic of patchDiagnostics(result)) recordGap(scope, exec, 'apply_patch', diagnostic)
163
+ }
164
+ return result
122
165
  } finally {
123
- state.busy.delete(plan.identity)
124
- try {
125
- reportWrite(ctx, sink, plan)
126
- } catch (error) {
127
- log.debug('待审上报失败:' + String(error))
166
+ for (const plan of plans) {
167
+ try { await reportWrite(state, sink, plan) }
168
+ catch (error) { if (!state.stopped && !state.disposed.has(scope.sessionId)) recordGap(scope, exec, plan.path, error); log.debug('待审上报失败:' + String(error)) }
169
+ finally { state.busy.delete(plan.identity) }
128
170
  }
129
171
  }
130
172
  }
131
173
 
132
174
  /**
133
- * @author ddj 2026年10月29号
134
- * @description: 写后读回并比较,内容一致视为无净变化不产生条目。
135
- * @param ctx Host 生命周期
175
+ * @author ddj 2026年11月04号
176
+ * @description: 固定目标写后读回;内容一致不产生条目,卸载后不再上报。
177
+ * @param state 采集生命周期状态
136
178
  * @param sink 已确认写入的接收方
137
179
  * @param plan 采集计划
138
180
  * @returns 无;读回失败只记日志
139
181
  */
140
- function reportWrite(ctx: Ctx, sink: (write: PendingWrite) => void, plan: CapturePlan): void {
141
- const fs = ctx.get('fs')
142
- void resolveTarget(ctx, plan.session, plan.path).then(async (target: unknown) => {
143
- const after = await readText(fs, target)
144
- if (after !== null && after.length > MAX_TEXT) return
145
- if (plan.before === after) return
146
- sink({ cwd: plan.cwd, sessionId: plan.sessionId, path: plan.path, identity: plan.identity, before: plan.before, after, now: Date.now() })
147
- }).catch((error: unknown) => log.debug('待审读回失败:' + String(error)))
182
+ async function reportWrite(state: CaptureState, sink: (write: PendingWrite) => void, plan: CapturePlan): Promise<void> {
183
+ if (state.stopped || state.disposed.has(plan.sessionId)) return
184
+ // 目录、provider 和目标均在写前冻结,切目录或卸载不能将内容串到其他工作区。
185
+ const after = await readText(plan.fs, plan.target)
186
+ if (state.stopped || state.disposed.has(plan.sessionId)) return
187
+ if (after !== null && after.length > MAX_TEXT) throw new Error('capture text budget exceeded')
188
+ for (const [key, gap] of captureGaps) {
189
+ const identity = JSON.parse(key) as unknown[]
190
+ if (gap.cwd === plan.cwd && gap.sessionId === plan.sessionId && identity[3] === plan.path) captureGaps.delete(key)
191
+ }
192
+ if (plan.before === after) return
193
+ sink({ cwd: plan.cwd, sessionId: plan.sessionId, path: plan.path, identity: plan.identity, before: plan.before, after, now: Date.now() })
148
194
  }
149
195
 
150
196
  /**
151
197
  * @author ddj 2026年10月29号
152
- * @description: 读取全文;缺失或不可读按"无内容"处理,交由上层决定语义。
198
+ * @description: 读取全文;只有明确缺失返回 null,不可读或超限错误保留失败语义。
153
199
  * @param fs 文件系统
154
200
  * @param target 目标
155
201
  * @returns 文本或 null
156
202
  */
157
- export async function readText(fs: any, target: any): Promise<string | null> {
203
+ export async function readText(fs: any, target: any, signal?: AbortSignal): Promise<string | null> {
158
204
  try {
159
- return String(await fs.readText(target))
205
+ if (typeof fs.readBytes === 'function') {
206
+ return rawText(rawReviewFile(await fs.readBytes(target, signal, MAX_TEXT)))
207
+ }
208
+ throw new Error('Raw byte capture unavailable')
160
209
  } catch (error) {
161
210
  const code = (error as { code?: string }).code
162
- if (code === 'ENOENT' || code === 'FS_NOT_FOUND' || code === 'FS_TOO_LARGE') return null
211
+ if (code === 'ENOENT' || code === 'FS_NOT_FOUND') return null
163
212
  throw error
164
213
  }
165
214
  }
@@ -4,6 +4,7 @@
4
4
  * @author ddj 2026年10月29号
5
5
  */
6
6
  import type { PendingEarlier, PendingLineage } from '../shared/pendingReview.js'
7
+ import { logicalLines } from '../shared/lineEndings.js'
7
8
 
8
9
  /** 内存态条目:比展示投影多保存两侧全文。 */
9
10
  export interface PendingEntry {
@@ -50,12 +51,17 @@ export function sameEntryText(left: string, right: string): boolean {
50
51
 
51
52
  /**
52
53
  * @author ddj 2026年10月29号
53
- * @description: 净零判定:基线等于当前内容即为已解决,但条目仍留在列表等待移除。
54
+ * @description: 净零判定与文本差异生成器保持逻辑行口径一致;只忽略 BOM 和换行编码,不改存储原文。
54
55
  * @param entry 待审条目
55
56
  * @returns 是否已无净差异
56
57
  */
57
58
  export function isSettled(entry: PendingEntry): boolean {
58
- return sameEntryText(entry.oldText, entry.newText)
59
+ if (sameEntryText(entry.oldText, entry.newText)) return true
60
+
61
+ const baselineLines = logicalLines(entry.oldText)
62
+ const currentLines = logicalLines(entry.newText)
63
+ return baselineLines.length === currentLines.length
64
+ && baselineLines.every((line, index) => line === currentLines[index])
59
65
  }
60
66
 
61
67
  /**