merge pr-921 (#921 fix: 修复 PTC 模式下本轮文件列表为空) into dev(@wang-kaopu)

冲突解决:extractFileOps 的文档注释与实现合并「PTC 事件对 + 会话 cwd 路径解析」两半,
参数解析抽成 ptcArgs(PTC 的 arguments 已是对象);测试保留 PTC 四例并按 #940 去掉分组名。
host 路由 / ops-stream 头注释恢复英文行文(行为不变),README_EN.md 保持删除、README.md 取 dev。
This commit is contained in:
Menghuan1918 committed 2026-10-16 16:41:11 +08:00
commit db2a87f360
4 files changed
+104 -36

No files matched your search

+37 -26
View File
@@ -1,10 +1,5 @@
/**
* File-operation extraction for the changes tab's session lens: folds the
* session's append-only event log (`tool/call` + `tool/result` pairs) into
* one op per file-touching call — the same semantics as the standalone
* dsh-file-trace plugin's Chat-view extraction, reading the authoritative
* event log instead (the repo's stated preference for cross-feature session
* data). Pure — no React, no DOM.
* 将会话日志中的直接调用与 PTC 子调用整理为文件操作,供本轮文件视角使用。
*/
import type { SidebarSessionEvent } from '../../context-types.ts'
import { resolveSidebarPath } from '../paths.ts'
@@ -14,7 +9,7 @@ export type FileOpKind = 'read' | 'write' | 'edit'
/** One extracted file operation. */
export interface FileOp {
/** Stable identity: the originating tool-call id. */
/** 直接调用使用 callId,PTC 子调用使用 subCallId。 */
readonly callId: string
readonly kind: FileOpKind
/** Path resolved against the session cwd when available. */
@@ -62,6 +57,12 @@ function parseArgs(argsRaw: string): Record<string, unknown> {
}
}
/** PTC sub-call arguments arrive already parsed (an object, never a string). */
function ptcArgs(value: unknown): Record<string, unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return {}
return value as Record<string, unknown>
}
/** Extract the path field common to every file tool's arguments. */
function pathOf(args: Record<string, unknown>): string | undefined {
for (const key of ['file_path', 'path', 'filePath']) {
@@ -132,8 +133,12 @@ function resultIsError(message: ToolResultMessageLike): boolean {
* Fold a session event log into the file operations it contains, newest
* first. A `tool/call` seeds a running op (payload from the model's
* arguments); its `tool/result` settles it (read content, error text).
* Calls dispatched through a host tool such as run_code appear as their own
* `tool/call` rows in the log, so nested file calls fold in naturally.
*
* A `<code>` block's file tools never surface as `tool/call`: they arrive as
* a PTC pair — `tool/ptc-dispatch-start` (arguments as a parsed OBJECT, keyed
* by `subCallId`) and `tool/ptc-dispatch` (the same payload plus the result).
* The dispatch row is self-contained, so a missing start still yields a row,
* and the pair inherits the start's time to order as ONE operation.
* @param events - the session's append-only event log (oldest → newest).
* @param cwd - the session working directory used to resolve relative paths.
* @returns the ordered operation list.
@@ -141,39 +146,45 @@ function resultIsError(message: ToolResultMessageLike): boolean {
export function extractFileOps(events: readonly SidebarSessionEvent[], cwd?: string): FileOp[] {
const byCall = new Map<string, FileOp>()
for (const event of events) {
if (event.type === 'tool/call') {
const data = event.data as { name?: unknown; callId?: unknown; arguments?: unknown }
if (typeof data.name !== 'string' || typeof data.callId !== 'string') continue
if (event.type === 'tool/call' || event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch') {
const data = event.data as { name?: unknown; callId?: unknown; subCallId?: unknown; arguments?: unknown }
const isPtc = event.type !== 'tool/call'
const callId = isPtc ? data.subCallId : data.callId
if (typeof data.name !== 'string' || typeof callId !== 'string') continue
const kind = kindOf(data.name)
if (kind === undefined) continue
const args = parseArgs(typeof data.arguments === 'string' ? data.arguments : '')
// A PTC dispatch ships its arguments already parsed, the plain tool call
// ships the model's JSON string.
const args = isPtc ? ptcArgs(data.arguments) : parseArgs(typeof data.arguments === 'string' ? data.arguments : '')
const rawPath = pathOf(args)
if (rawPath === undefined) continue
const path = resolveSidebarPath(cwd, rawPath)
const base: FileOp = { callId: data.callId, kind, path, time: event.time, running: true, isError: false }
const time = event.type === 'tool/ptc-dispatch' ? byCall.get(callId)?.time ?? event.time : event.time
const base: FileOp = { callId, kind, path, time, running: true, isError: false }
let op = base
if (kind === 'edit') {
const oldString = args.old_string
const newString = args.new_string
byCall.set(data.callId, typeof oldString === 'string' && typeof newString === 'string'
op = typeof oldString === 'string' && typeof newString === 'string'
? { ...base, edit: { oldString, newString } }
: base)
continue
}
if (kind === 'write') {
: base
} else if (kind === 'write') {
const content = args.content
byCall.set(data.callId, typeof content === 'string' && content.length > 0 ? { ...base, content } : base)
continue
op = typeof content === 'string' && content.length > 0 ? { ...base, content } : base
}
byCall.set(data.callId, base)
} else if (event.type === 'tool/result') {
const message = (event.data as { message?: unknown }).message as ToolResultMessageLike | undefined
byCall.set(callId, op)
}
if (event.type === 'tool/result' || event.type === 'tool/ptc-dispatch') {
const message = event.type === 'tool/result'
? (event.data as { message?: unknown }).message as ToolResultMessageLike | undefined
: event.data as ToolResultMessageLike
if (message === undefined) continue
const callId = message.source?.callId
const callId = event.type === 'tool/result' ? message.source?.callId : event.data.subCallId
if (typeof callId !== 'string') continue
const op = byCall.get(callId)
if (op === undefined) continue
const text = resultText(message)
const isError = resultIsError(message)
const isError = event.type === 'tool/ptc-dispatch' ? event.data.isError === true : resultIsError(message)
const patch: { running: boolean; isError: boolean; errorText?: string; read?: string; content?: string } = { running: false, isError }
if (text !== undefined && text.length > 0) {
if (isError) patch.errorText = text
+7 -5
View File
@@ -2,11 +2,13 @@
* The session's live FILE-OPERATION stream — the signal the editor's
* auto-refresh rides (#855).
*
* The model's file tools leave their calls in the session event log, and the
* plugin's own `changes.ops` route ships that log's `tool/call` +
* `tool/result` rows as a `seq > afterSeq` delta (see `src/index.ts`). This
* module folds those deltas into "which file did the model just write or
* edit", which is the whole question an open preview has to answer.
* The model's file tools leave their calls in the session event log — as a
* plain `tool/call` + `tool/result` pair, or as a PTC pair
* (`tool/ptc-dispatch-start` / `tool/ptc-dispatch`) when the call ran inside
* `<code>` — and the plugin's own `changes.ops` route ships those rows as a
* `seq > afterSeq` delta (see `src/index.ts`). This module folds those deltas
* into "which file did the model just write or edit", which is the whole
* question an open preview has to answer.
*
* Design constraints it exists to honour:
*
+7 -5
View File
@@ -1047,10 +1047,11 @@ function buildApi(
// The session's file-tool events for the changes tab's session lens
// (and its badge): the CLIENT runtime's sessions face has no event-log
// access, so the events cross the wire here — live session log first,
// the persisted logical log for not-yet-hydrated sessions. Only the
// two event types the lens folds are sent, narrowed to `seq > afterSeq`
// so polling is a small delta, with the same recent-window cap the
// client accumulator applies.
// the persisted logical log for not-yet-hydrated sessions. Only the event
// types the lens folds are sent (a plain `tool/call` + `tool/result` pair,
// or a PTC `tool/ptc-dispatch-start` / `tool/ptc-dispatch` pair), narrowed
// to `seq > afterSeq` so polling is a small delta, with the same
// recent-window cap the client accumulator applies.
'changes.ops': async (payload) => {
const sessionId = requireString(payload, 'sessionId')
const rawAfter = (payload as { afterSeq?: unknown } | null)?.afterSeq
@@ -1077,7 +1078,8 @@ function buildApi(
if (events === undefined) return { events: [], lastSeq: Math.max(afterSeq, 0) }
const CHANGES_EVENTS_CAP = 4000
const filtered = events.filter(
event => (event.type === 'tool/call' || event.type === 'tool/result') && event.seq > afterSeq,
event => (event.type === 'tool/call' || event.type === 'tool/result'
|| event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch') && event.seq > afterSeq,
)
const window = filtered.length > CHANGES_EVENTS_CAP ? filtered.slice(filtered.length - CHANGES_EVENTS_CAP) : filtered
return { events: window, lastSeq: window.at(-1)?.seq ?? afterSeq }
+53
View File
@@ -168,6 +168,59 @@ describe('extractFileOps', () => {
expect(ops.find(op => op.kind === 'read')?.errorText).toBe('cannot read "b": not found')
})
it('records PTC file calls by subCallId and settles them from dispatch results', () => {
const rootCallId = 'root'
const write = {
rootCallId, parentCallId: rootCallId, subCallId: 'root:ptc:1', name: 'write',
arguments: { file_path: 'notes.txt', content: 'PTC content' },
}
const read = {
rootCallId, parentCallId: rootCallId, subCallId: 'root:ptc:2', name: 'read',
arguments: { file_path: 'notes.txt' },
}
const ops = extractFileOps([
call(1, 'run_code', rootCallId, { code: 'write(); read()' }),
ev('tool/ptc-dispatch-start', 2, 20, write),
ev('tool/ptc-dispatch-start', 3, 30, read),
ev('tool/ptc-dispatch', 4, 40, { ...read, isError: false, content: [{ type: 'text', text: '<content>\n1: PTC content\n</content>' }] }),
ev('tool/ptc-dispatch', 5, 50, { ...write, isError: false, content: [{ type: 'text', text: 'written' }] }),
result(6, rootCallId, 'run_code completed'),
])
expect(ops.map(op => op.callId)).toEqual(['root:ptc:2', 'root:ptc:1'])
expect(ops[0]).toMatchObject({ kind: 'read', path: 'notes.txt', time: 30, running: false, isError: false, read: '<content>\n1: PTC content\n</content>' })
expect(ops[1]).toMatchObject({ kind: 'write', path: 'notes.txt', time: 20, running: false, isError: false, content: 'PTC content' })
})
it('keeps an unfinished PTC call running and recovers a complete dispatch without its start', () => {
const rootCallId = 'root'
const edit = {
rootCallId, parentCallId: rootCallId, subCallId: 'root:ptc:1', name: 'edit',
arguments: { file_path: 'draft.txt', old_string: 'before', new_string: 'after' },
}
const failedWrite = {
rootCallId, parentCallId: rootCallId, subCallId: 'root:ptc:2', name: 'write',
arguments: { file_path: 'readonly.txt', content: 'new' },
isError: true, content: [{ type: 'text', text: 'permission denied' }],
}
const ops = extractFileOps([
ev('tool/ptc-dispatch-start', 1, 10, edit),
ev('tool/ptc-dispatch', 2, 20, failedWrite),
])
expect(ops.find(op => op.callId === edit.subCallId)).toMatchObject({ kind: 'edit', running: true, edit: { oldString: 'before', newString: 'after' } })
expect(ops.find(op => op.callId === failedWrite.subCallId)).toMatchObject({ kind: 'write', time: 20, running: false, isError: true, errorText: 'permission denied' })
})
it('settles a PTC edit with its replacement payload', () => {
const dispatch = {
rootCallId: 'root', parentCallId: 'root', subCallId: 'root:ptc:1', name: 'edit',
arguments: { file_path: 'draft.txt', old_string: 'before', new_string: 'after' },
isError: false, content: [{ type: 'text', text: 'edited' }],
}
expect(extractFileOps([ev('tool/ptc-dispatch', 1, 10, dispatch)])).toMatchObject([
{ callId: 'root:ptc:1', kind: 'edit', path: 'draft.txt', running: false, isError: false, edit: { oldString: 'before', newString: 'after' } },
])
})
it('keeps operations newest-first and recovers prior write content', () => {
const ops = extractFileOps([
call(1, 'write', 'w1', { file_path: 'a.ts', content: 'first' }),