feat(sidechat): render PTC run_code sub-call rows

Fold the log-only PTC pair (tool/ptc-dispatch-start + tool/ptc-dispatch) into nested sub-call rows on the run_code transcript row. Sub-calls render indented below the root (outside its disclosure, so a collapsed root still shows them) through the same terminal/diff/read/search/web cards as direct calls; running, failed and start-less dispatches are covered. The run_code line shows the model description and its expanded body shows the program plus the final result. Successful PTC write/edit targets join the clickable path mentions; a PTC present keeps its top-level delivery card and also leaves a sub-call row. Tests: sidechat-ptc-rows, sidechat-ptc-subcalls, sidechat-mention-sources.
This commit is contained in:
Menghuan1918 authored and Atlas Zeng committed 2026-11-18 16:56:36 +08:00
1 parent 168a572119
commit 09b01dd67e
9 files changed
+842 -57

No files matched your search

+30
View File
@@ -526,6 +526,36 @@
margin-top: 2px;
}
/* ── PTC (run_code) sub-call tree ─────────────────────────────────────
* The root tool row owns the whole program call; its sub-calls hang below in
* one indented column on a hairline thread (the host ToolCallTree's
* `.subCalls` recipe). The column is a SIBLING of the root's <details>, so a
* collapsed run_code still shows what the program did. The 22px indent aligns
* under the root's 16px icon + 6px gap; each deeper parent adds one more
* 22px + 8px step. */
.sidechatToolTree {
align-self: stretch;
display: flex;
flex-direction: column;
min-width: 0;
}
.sidechatSubCalls {
display: flex;
flex-direction: column;
gap: 2px;
margin: 4px 0 2px 22px;
padding-left: 8px;
border-left: 1px solid var(--dsw-alias-border-l1);
min-width: 0;
}
.sidechatSubCall {
display: flex;
flex-direction: column;
min-width: 0;
}
/* Turn-tail metrics line: quiet, right-aligned, ink-weight only. */
.sidechatTurnSummary {
align-self: flex-end;
+134 -44
View File
@@ -45,6 +45,7 @@ import {
IconBrowseOutlineRegular,
IconChevronRightOutlineRegular,
IconCloseFillRegular,
IconCodeOutlineRegular,
IconEditOutlineRegular,
IconNewChatOutlineRegular,
IconPaperclipOutlineRegular,
@@ -106,11 +107,13 @@ import {
import {
formatDurationMs,
formatTokens,
parseArgsObject,
toolArgsSummary,
transcriptRows,
sidechatRowKey,
type SidechatAttachment,
type SidechatToolCard,
type SidechatToolChild,
type SidechatTranscriptRow,
} from './sidechat-transcript.ts'
import { api, mediaUrl, SidebarApiError } from './api.ts'
@@ -499,6 +502,27 @@ function isWorkRow(
/** Longest live-detail snippet a running Turn's line carries. */
const RUNNING_LINE_MAX = 80
/**
* The collapsed line's summary plus the `run_code` program body.
*
* `run_code`'s own presentation is the host's `code` variant: the model-written
* `description` is the line and the program is the body. Every other tool keeps
* `toolArgsSummary` — the counted per-row parse the typing-cost spec pins.
* @param name - the wire tool name.
* @param args - the raw arguments JSON.
* @returns the one-line metatext and, for run_code, its program text.
*/
function toolRowParts(name: string, args: string | undefined): { meta: string; code?: string } {
if (name !== 'run_code') return { meta: toolArgsSummary(args) }
const parsed = parseArgsObject(args)
const description = typeof parsed?.description === 'string' ? parsed.description.trim() : ''
const code = typeof parsed?.code === 'string' && parsed.code !== '' ? parsed.code : undefined
return {
meta: description === '' ? toolArgsSummary(args) : description,
...(code === undefined ? {} : { code }),
}
}
/**
* What a RUNNING turn's control line says beyond its label (host
* `liveProcessDetail`): the running tool with its one-line arguments, or the
@@ -510,7 +534,7 @@ function runningProcessLine(
row: Extract<SidechatTranscriptRow, { kind: 'reasoning' | 'tool' }>,
): string | undefined {
if (row.kind === 'tool') {
const summary = toolArgsSummary(row.args)
const summary = toolRowParts(row.name, row.args).meta
return summary === '' ? row.name : `${row.name} · ${summary}`
}
const first = row.text.split('\n', 1)[0]?.trim() ?? ''
@@ -671,11 +695,82 @@ function toolLeading(name: string, failed: boolean): React.ReactNode {
case 'glob':
case 'web_search':
return <IconSearchOutlineRegular size={14} />
case 'run_code':
return <IconCodeOutlineRegular size={14} />
default:
return <IconSparkleRegular size={14} />
}
}
/** The display fields a direct tool row and a PTC sub-call share. */
interface ToolRowData {
name: string
failed: boolean
args?: string
resultText?: string
executing?: boolean
card?: SidechatToolCard
resultAttachments?: readonly SidechatAttachment[]
}
/**
* One tool row: the collapsed line plus the disclosed arguments/result or the
* structured card. A direct call and each PTC sub-call render through this one
* helper, so a sub-call's atoms (terminal / diff / read / search / web) can
* never drift from the same tool's direct-call row.
*/
function ToolRowView(props: {
row: ToolRowData
nodeKey: string
labels: RowLabels
attachments: (list: readonly SidechatAttachment[]) => React.ReactNode
}): React.ReactNode {
const { row, labels } = props
const parts = toolRowParts(row.name, row.args)
const resultAttachments = row.resultAttachments === undefined || row.resultAttachments.length === 0
? null
: props.attachments(row.resultAttachments)
const body = (
<>
{row.card !== undefined
? toolCardBody(row.card, row.executing === true, labels)
: (
<>
{parts.code !== undefined
? <pre className={css.sidechatRowCode}>{parts.code}</pre>
: row.args !== undefined && (
<>
<div className={css.sidechatToolSectionLabel}>{t('sideChatToolArguments')}</div>
<pre className={css.sidechatRowCode}>{row.args}</pre>
</>
)}
{row.resultText !== undefined && (
<>
<div className={css.sidechatToolSectionLabel}>{t('sideChatToolResult')}</div>
<pre className={css.sidechatRowCode}>{row.resultText}</pre>
</>
)}
</>
)}
{resultAttachments}
</>
)
const hasBody = row.card !== undefined || row.args !== undefined || row.resultText !== undefined
|| resultAttachments !== null
return (
<CollapsibleRow
key={props.nodeKey}
label={row.name}
meta={parts.meta}
icon={toolLeading(row.name, row.failed)}
mono
streaming={row.executing === true}
failed={row.failed}
{...(hasBody ? { children: body } : {})}
/>
)
}
/** The per-view helpers every row renderer needs, collected in one stable
* object so a row body never rebuilds them per render. */
interface RowSurface {
@@ -870,55 +965,50 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu
)
}
case 'tool': {
// A tool WITHOUT a structured card (grep/glob/web_search and every host
// tool this view does not know): the collapsed line carries the one-line
// argument summary, and the disclosed body splits into two LABELLED
// sections — raw arguments, then raw output — so a reader who expands
// always knows which block is which (two unlabelled <pre>s of JSON next
// to raw output was a wall of escaped quotes).
const resultAttachments = row.resultAttachments === undefined || row.resultAttachments.length === 0
? null
: surface.attachments(row.resultAttachments)
const body = (
<>
{row.card !== undefined
? toolCardBody(row.card, row.executing === true, labels)
: (
<>
{row.args !== undefined && (
<>
<div className={css.sidechatToolSectionLabel}>{t('sideChatToolArguments')}</div>
<pre className={css.sidechatRowCode}>{row.args}</pre>
</>
)}
{row.resultText !== undefined && (
<>
<div className={css.sidechatToolSectionLabel}>{t('sideChatToolResult')}</div>
<pre className={css.sidechatRowCode}>{row.resultText}</pre>
</>
)}
</>
)}
{resultAttachments}
</>
)
const children = row.children
if (children === undefined || children.length === 0) {
return <ToolRowView row={row} nodeKey={key} labels={labels} attachments={surface.attachments} />
}
// PTC tree: the root row owns the whole `run_code` call, and its
// sub-calls hang BESIDE the root disclosure (never inside it), so a
// collapsed root still shows what the program actually did — the same
// composition as the host's ToolCallTree.
return (
<CollapsibleRow
key={key}
label={row.name}
meta={toolArgsSummary(row.args)}
icon={toolLeading(row.name, row.failed)}
mono
streaming={row.executing === true}
failed={row.failed}
{...(row.args === undefined && row.resultText === undefined && row.card === undefined
&& resultAttachments === null ? {} : { children: body })}
/>
<div key={key} className={css.sidechatToolTree} data-sidechat-tool-tree="">
<ToolRowView row={row} nodeKey={key} labels={labels} attachments={surface.attachments} />
<div className={css.sidechatSubCalls} data-sidechat-subcalls="">
{children.map(child => renderToolChild(child, labels, surface.attachments))}
</div>
</div>
)
}
}
}
/** One PTC sub-call, rendered recursively: the leaf tool row plus its own
* children in the same hairline-indented column. */
function renderToolChild(
child: SidechatToolChild,
labels: RowLabels,
attachments: (list: readonly SidechatAttachment[]) => React.ReactNode,
): React.ReactNode {
const nested = child.children
return (
<div
key={`${String(child.seq)}:${child.callId}`}
className={css.sidechatSubCall}
data-sidechat-subcall=""
>
<ToolRowView row={child} nodeKey={`ptc:${String(child.seq)}`} labels={labels} attachments={attachments} />
{nested !== undefined && nested.length > 0 && (
<div className={css.sidechatSubCalls} data-sidechat-subcalls="">
{nested.map(grandchild => renderToolChild(grandchild, labels, attachments))}
</div>
)}
</div>
)
}
/** One side conversation tab (one thread per tab, Codex-style). */
export function SideChatView(props: {
ctx: Context
+22 -7
View File
@@ -17,7 +17,7 @@
* - a successful `write` / `edit` / `str_replace_editor` call's target path,
* - a `deliverables` row (`files[].path`, the authoritative delivery record).
*/
import type { SidechatTranscriptRow } from './sidechat-transcript.ts'
import type { SidechatToolChild, SidechatTranscriptRow } from './sidechat-transcript.ts'
import { parseArgsObject } from './sidechat-transcript.ts'
import { baseName } from './paths.ts'
@@ -52,7 +52,7 @@ function pathValue(value: unknown): string | undefined {
* @param row - one mapped `tool` row.
* @returns the produced path exactly as the call spelled it.
*/
function producedTargetOf(row: Extract<SidechatTranscriptRow, { kind: 'tool' }>): string | undefined {
function producedTargetOf(row: { name: string; args?: string }): string | undefined {
const pathKey = MUTATION_PATH_KEYS[row.name]
if (pathKey === undefined) return undefined
const args = parseArgsObject(row.args)
@@ -64,10 +64,27 @@ function producedTargetOf(row: Extract<SidechatTranscriptRow, { kind: 'tool' }>)
return pathValue(args[pathKey])
}
/**
* Recurse one tool row and its PTC children into the produced vocabulary. A
* failed node contributes no target of its own (the existing "a failed call
* produced nothing" rule), but its children still count: a `run_code` program
* can fail after a successful write, and a failed sub-call does not retract an
* earlier successful one.
*/
function addProducedPaths(
row: { name: string; args?: string; failed: boolean; children?: readonly SidechatToolChild[] },
add: (value: unknown) => void,
): void {
if (row.failed !== true) add(producedTargetOf(row))
for (const child of row.children ?? []) addProducedPaths(child, add)
}
/**
* Every path this thread produced, in first-seen order and deduplicated: the
* target of a successful (`failed !== true`) mutation call, plus every
* delivered file. Nothing else — see {@link MUTATION_PATH_KEYS}.
* delivered file. Nothing else — see {@link MUTATION_PATH_KEYS}. PTC sub-calls
* count too: a program's `write`/`edit` is the same production as a direct
* call, just nested under its `run_code` row.
* @param rows - the thread's mapped transcript rows.
* @returns the produced paths exactly as the producing row spelled them
* (relative call arguments stay relative; delivery events are absolute).
@@ -78,10 +95,8 @@ export function producedFilePaths(rows: readonly SidechatTranscriptRow[]): strin
if (typeof value === 'string' && value.trim() !== '') seen.add(value)
}
for (const row of rows) {
if (row.kind === 'tool') {
if (row.failed === true) continue
add(producedTargetOf(row))
} else if (row.kind === 'deliverables') {
if (row.kind === 'tool') addProducedPaths(row, add)
else if (row.kind === 'deliverables') {
for (const file of row.files) add(file.path)
}
}
+204 -6
View File
@@ -84,6 +84,41 @@ export interface SidechatDeliverable {
description?: string
}
/**
* One nested PTC sub-call: a tool the model invoked INSIDE a `run_code`
* program. The host logs the pair as `tool/ptc-dispatch-start` (the call) and
* `tool/ptc-dispatch` (the settled result), both keyed by `subCallId`; these
* are log-only events (`deriveMessages()` ignores them), so they never reach
* model history and only the transcript can show them.
*
* The fields mirror a direct tool row exactly (name / args / result / card /
* attachments) so the view renders a sub-call through the same atoms. The
* node lives on its parent's row: `run_code` keeps its own row and owns the
* whole call tree, which is how the main conversation draws it too.
*/
export interface SidechatToolChild {
/** The `tool/ptc-dispatch-start` seq (a dispatch without a start uses its
* own seq). Stable across polls — the view's React key. */
seq: number
/** The host's opaque sub-call id (`<parent>:ptc:<n>`); pairs start/result. */
callId: string
name: string
failed: boolean
/** Raw arguments JSON, serialized from the dispatch's parsed object. */
args?: string
/** Plain text of the settled sub-call result. */
resultText?: string
/** True while the sub-call has not settled yet. */
executing?: boolean
/** Structured render payload (host Block atoms); absent = generic row. */
card?: SidechatToolCard
/** `image` / `file` blocks of the settled sub-call's content list. */
resultAttachments?: readonly SidechatAttachment[]
/** A nested sub-call's own children (a parent chain). The current host does
* not bind `run_code` inside a program, so depth > 1 is defensive only. */
children?: SidechatToolChild[]
}
/** One compact transcript row rendered in the thread view. `seq` is the
* source event's log sequence. Text/reasoning also retain the original
* content-block index: one event can yield several rows, so seq alone is
@@ -145,6 +180,10 @@ export type SidechatTranscriptRow =
card?: SidechatToolCard
/** `image` / `file` blocks of the paired result's content list. */
resultAttachments?: readonly SidechatAttachment[]
/** PTC sub-calls the model dispatched INSIDE this call's program. Only a
* `run_code` call has them; the view draws the tree indented under this
* row, outside its disclosure (so a collapsed root still shows them). */
children?: SidechatToolChild[]
/** The turn this call belongs to, and whether that turn already ended (see
* `reasoning.turn`). */
turn?: number
@@ -366,12 +405,9 @@ function resultBlocks(content: unknown): readonly unknown[] | undefined {
return content as readonly unknown[]
}
/** The plain text of a tool/result message (its text blocks, under either of
* the two shapes {@link resultBlocks} reads). */
function resultTextOf(data: Record<string, unknown>): string {
const message = data.message as { content?: unknown } | undefined
const blocks = resultBlocks(message?.content)
if (blocks === undefined) return ''
/** The plain text of one result content list: its text blocks joined by a
* newline, '' when it carries none. */
function textOfBlocks(blocks: readonly unknown[]): string {
const parts: string[] = []
for (const item of blocks) {
if (item === null || typeof item !== 'object') continue
@@ -383,6 +419,34 @@ function resultTextOf(data: Record<string, unknown>): string {
return parts.join('\n')
}
/** The plain text of a tool/result message (its text blocks, under either of
* the two shapes {@link resultBlocks} reads). */
function resultTextOf(data: Record<string, unknown>): string {
const message = data.message as { content?: unknown } | undefined
const blocks = resultBlocks(message?.content)
return blocks === undefined ? '' : textOfBlocks(blocks)
}
/** The plain text of one PTC dispatch result (`tool/ptc-dispatch.content`,
* which is the same content list a `tool/result` message carries). */
function dispatchResultText(data: Record<string, unknown>): string {
const blocks = resultBlocks(data.content)
return blocks === undefined ? '' : textOfBlocks(blocks)
}
/** The `image` / `file` blocks of one PTC dispatch result. */
function dispatchResultAttachments(data: Record<string, unknown>): SidechatAttachment[] {
const blocks = resultBlocks(data.content)
return blocks === undefined ? [] : attachmentsOf(blocks)
}
/** Whether one PTC dispatch reports a FAILED sub-call. The host sets
* `isError`; `error` is the optional structured identity, kept as a fallback
* for a producer that only records the failure object. */
function dispatchFailed(data: Record<string, unknown>): boolean {
return data.isError === true || data.error !== undefined
}
/**
* Narrow one `image` / `file` content block. A block without the fields the
* transcript can actually render is SKIPPED (no row, no placeholder, no byte
@@ -506,6 +570,19 @@ export function parseArgsObject(args: string | undefined): Record<string, unknow
}
}
/** One PTC dispatch's `arguments` as the raw JSON string a tool row stores.
* The host ships the value already parsed and normalized to lossless JSON
* (see the PTC client types), so serialization is the only transformation;
* a value that still cannot serialize degrades to no arguments. */
function ptcArgsJson(value: unknown): string | undefined {
if (typeof value === 'string') return value
try {
return JSON.stringify(value)
} catch {
return undefined
}
}
/**
* Narrow one delivered-file entry (`{ path, description? }`). The path is
* kept verbatim: the card resolves it against the session cwd on click and
@@ -842,6 +919,10 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
const streamRows = new Map<string, number>()
/** tool callId → index of its tool row in `rows` (result pairing). */
const callRows = new Map<string, number>()
/** PTC subCallId → its child node. A child lives on its parent's row; this
* map makes the dispatch-settles-start lookup O(1) and lets a sub-call be
* the parent of a deeper one. */
const ptcChildren = new Map<string, SidechatToolChild>()
/** present callId → its deliverables card: the card row's index plus the
* call's raw arguments (a FAILED result needs them to rebuild the generic
* tool row). A `deliverables/presented` event attaches to this card
@@ -885,6 +966,94 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
if (typeof turn !== 'number' || !Number.isInteger(turn)) return {}
return { turn, ...(endedTurns.has(turn) ? { turnEnded: true } : {}) }
}
/**
* The mutable children list of one PTC parent: the root `run_code` tool row
* when `parentCallId` is its callId, else a sub-call node. Undefined when the
* parent is outside the event window (the route keeps the newest events, so
* a capped head can lose the root) — the dispatch then has no place in the
* tree and is skipped, exactly like the host UI's node-less sub-call.
*/
const ptcChildListOf = (parentCallId: string): SidechatToolChild[] | undefined => {
const rowIndex = callRows.get(parentCallId)
if (rowIndex !== undefined) {
const row = rows[rowIndex]
if (row === undefined || row.kind !== 'tool') return undefined
row.children ??= []
return row.children
}
const parent = ptcChildren.get(parentCallId)
if (parent === undefined) return undefined
parent.children ??= []
return parent.children
}
/**
* Fold one PTC event into its parent's tree. `started` is true for
* `tool/ptc-dispatch-start` (a running child), false for the settled
* `tool/ptc-dispatch`. All payload fields are model/host wire data, so each
* is narrowed; a malformed event contributes nothing and never throws.
*/
const foldPtc = (eventSeq: number, data: Record<string, unknown>, started: boolean): void => {
const subCallId = typeof data.subCallId === 'string' && data.subCallId !== '' ? data.subCallId : undefined
const name = typeof data.name === 'string' && data.name !== '' ? data.name : 'tool'
if (subCallId === undefined) return
const existing = ptcChildren.get(subCallId)
if (started) {
if (existing !== undefined) return
const parentCallId = typeof data.parentCallId === 'string' && data.parentCallId !== '' ? data.parentCallId : undefined
if (parentCallId === undefined) return
const children = ptcChildListOf(parentCallId)
if (children === undefined) return
const args = ptcArgsJson(data.arguments)
const card = callCard(name, args)
const child: SidechatToolChild = {
seq: eventSeq,
callId: subCallId,
name,
failed: false,
executing: true,
...(args !== undefined ? { args } : {}),
...(card !== undefined ? { card } : {}),
}
children.push(child)
ptcChildren.set(subCallId, child)
return
}
const failed = dispatchFailed(data)
const resultText = dispatchResultText(data)
const resultAttachments = dispatchResultAttachments(data)
if (existing !== undefined) {
// The start's seq stays the child's identity across the settle.
existing.failed = failed
existing.executing = false
if (name !== 'tool') existing.name = name
if (resultText !== '') existing.resultText = resultText
if (resultAttachments.length > 0) existing.resultAttachments = resultAttachments
existing.card = failed ? undefined : resultCard(existing.name, existing.card, data, resultText)
return
}
const parentCallId = typeof data.parentCallId === 'string' && data.parentCallId !== '' ? data.parentCallId : undefined
if (parentCallId === undefined) return
const children = ptcChildListOf(parentCallId)
if (children === undefined) return
const args = ptcArgsJson(data.arguments)
// A dispatch-only sub-call still gets the call-time literal card (bash's
// command line, edit/write's replacement) before the result refines it —
// the same two-stage derivation a direct call uses.
const card = failed ? undefined : resultCard(name, callCard(name, args), data, resultText)
const child: SidechatToolChild = {
seq: eventSeq,
callId: subCallId,
name,
failed,
executing: false,
...(args !== undefined ? { args } : {}),
...(resultText !== '' ? { resultText } : {}),
...(card !== undefined ? { card } : {}),
...(resultAttachments.length > 0 ? { resultAttachments } : {}),
}
children.push(child)
ptcChildren.set(subCallId, child)
}
for (let index = 0; index < events.length; index++) {
const event = events[index]
if (event === undefined) continue
@@ -1151,6 +1320,15 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r
else rows.splice(Math.min(...streamed), streamed.length, ...settled)
break
}
case 'tool/ptc-dispatch-start':
case 'tool/ptc-dispatch': {
// PTC sub-calls are LOG-ONLY: `deriveMessages()` ignores them, so they
// never re-enter model history and the transcript is the only place
// they can be seen. They inherit their parent row's turn visually (the
// view draws the tree under `run_code`); the events carry no turn.
foldPtc(event.seq, data, event.type === 'tool/ptc-dispatch-start')
break
}
case 'tool/call': {
const callId = data.callId
const name = typeof data.name === 'string' ? data.name : 'tool'
@@ -1299,6 +1477,25 @@ function turnAnnotationOf(row: SidechatTranscriptRow): { turn?: number; turnEnde
return row.kind === 'reasoning' || row.kind === 'tool' ? row : {}
}
/** Whether two PTC child trees render the same thing (the row-reuse compare).
* Card payloads are deliberately not compared: like the root tool row, a
* child's card is a pure function of its args/result, and every transition
* that changes it flips one of the compared fields below. */
function toolChildrenEqual(a: readonly SidechatToolChild[] | undefined, b: readonly SidechatToolChild[] | undefined): boolean {
if (a === b) return true
if (a === undefined || b === undefined || a.length !== b.length) return false
return a.every((child, index) => {
const peer = b[index]
if (peer === undefined) return false
return child.seq === peer.seq && child.callId === peer.callId
&& child.name === peer.name && child.failed === peer.failed
&& child.args === peer.args && child.resultText === peer.resultText
&& child.executing === peer.executing
&& attachmentsEqual(child.resultAttachments, peer.resultAttachments)
&& toolChildrenEqual(child.children, peer.children)
})
}
/** Whether two rows carry identical display content (identity fields plus
* every rendered field of their kind). */
function rowsEqual(a: SidechatTranscriptRow, b: SidechatTranscriptRow): boolean {
@@ -1339,6 +1536,7 @@ function rowsEqual(a: SidechatTranscriptRow, b: SidechatTranscriptRow): boolean
return a.name === other.name && a.failed === other.failed && a.args === other.args
&& a.resultText === other.resultText && a.executing === other.executing
&& attachmentsEqual(a.resultAttachments, other.resultAttachments)
&& toolChildrenEqual(a.children, other.children)
&& left.turn === right.turn && left.turnEnded === right.turnEnded
}
case 'deliverables': {