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

+3
View File
@@ -4,6 +4,9 @@
### 未发布
- 💻 **侧边对话显示 PTC(run_code)工具调用树**:`run_code` 行收起时显示模型写的 description,展开后显示程序代码和最终结果;程序内通过 PTC 派发的 bash / read / grep / edit 等子调用缩进挂在它下方,根行收起也可见,并复用终端 / diff / read / search / web 结构卡片。运行中、失败、无 start 的 dispatch 都有对应显示;PTC 内成功 write/edit 的文件也进入可点击路径提及。`present` 仍保留顶层交付卡片,同时在子调用区留下一行。
- 🧪 测试:`tests/sidechat-ptc-rows.spec.ts`(配对 / 运行态 / 失败 / 无 start / 嵌套 / 父行缺失 / 身份复用)、`tests/sidechat-ptc-subcalls.spec.tsx`(description 摘要、代码体、缩进与卡片、根行收起仍可见)、`tests/sidechat-mention-sources.spec.tsx`(PTC mutation 进入提及、read 不进入)。
- 🧩 **局域网明文 HTTP 下侧边对话与底部终端页签恢复正常**([#1166](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1166)):浏览器只在**安全上下文**(https 或 localhost)暴露 `crypto.randomUUID`;用 `http://<局域网 IP>:<端口>` 打开 GUI 时它是 `undefined`,而新开侧边对话页签、新开底部终端都直接调用它——异常发生在宿主创建页签的过程中,界面只剩一个空面板。现在这三处改为一个内部 `freshId()`:有 `randomUUID` 就用它,否则用 `crypto.getRandomValues`(不受安全上下文限制)取 64 位随机数 + 毫秒时间戳兜底,id 仍然唯一。
- 🧪 测试:`tests/builtins.spec.ts` 在删掉 `crypto.randomUUID` 的全局环境下驱动真实 `createTab` 工厂,断言侧边对话与终端各自产出非空且互不相同的 id。
+3
View File
@@ -6,6 +6,9 @@
### Unreleased
- 💻 **Side Chat renders PTC (run_code) tool trees**: the collapsed `run_code` line shows the model-written description, and its expanded body shows the program plus the final result. Tools dispatched inside the program (bash / read / grep / edit, …) render as indented rows under it — visible even when the root row is collapsed — through the same terminal / diff / read / search / web cards. Running, failed and start-less dispatches all render; successful PTC writes/edits join the clickable path mentions. `present` keeps its top-level delivery card and also leaves a sub-call row.
- 🧪 Tests: `tests/sidechat-ptc-rows.spec.ts` (pairing / running / failed / no-start / nested / missing parent / identity reuse), `tests/sidechat-ptc-subcalls.spec.tsx` (description summary, program body, indentation and cards, collapsed-root visibility) and `tests/sidechat-mention-sources.spec.tsx` (PTC mutations count, reads do not).
- 🧩 **Side Chat and the bottom terminal work again over plain-HTTP LAN** ([#1166](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1166)): browsers expose `crypto.randomUUID` only in a **secure context** (https or localhost); opened as `http://<LAN IP>:<port>` it is `undefined`, and minting a new Side Chat tab or a new bottom terminal called it unguarded — the throw happened inside the host's tab creation, leaving an empty pane. Those three sites now go through an internal `freshId()`: `randomUUID` when available, otherwise `crypto.getRandomValues` (not restricted to secure contexts) for 64 random bits plus a millisecond timestamp, so the ids stay unique.
- 🧪 `tests/builtins.spec.ts` drives the real `createTab` factories with `crypto.randomUUID` deleted and asserts non-empty, mutually distinct ids for both tabs.
+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': {
+73
View File
@@ -174,4 +174,77 @@ describe('the mention vocabulary is scoped to producing tools (D12)', () => {
rendered.unmount()
}
})
it('counts mutation targets dispatched inside run_code, and still excludes its reads', async () => {
const PTC_WRITTEN = 'src/ptc-written.ts'
const PTC_READ = 'src/ptc-read.ts'
const root = 'ptc-root'
const dispatch = (seq: number, sub: string, name: string, args: Record<string, unknown>, text: string): SidebarSessionEvent[] => [
{
type: 'tool/ptc-dispatch-start',
seq,
time: seq * 1_000,
data: { rootCallId: root, parentCallId: root, subCallId: sub, name, arguments: args },
} as SidebarSessionEvent,
{
type: 'tool/ptc-dispatch',
seq: seq + 1,
time: (seq + 1) * 1_000,
data: { rootCallId: root, parentCallId: root, subCallId: sub, name, arguments: args, isError: false, content: [{ type: 'text', text }] },
} as SidebarSessionEvent,
]
const list: SidebarSessionEvent[] = [
{ type: 'session/end-seed', seq: 0, time: 0, data: { inherited: true } } as SidebarSessionEvent,
{
type: 'user/message',
seq: 1,
time: 1_000,
data: { content: [{ type: 'text', text: 'do it in code' }], source: { kind: 'user' } },
} as SidebarSessionEvent,
{ type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } } as SidebarSessionEvent,
{
type: 'tool/call',
seq: 3,
time: 3_000,
data: { turn: 1, step: 1, callId: root, name: 'run_code', arguments: JSON.stringify({ code: 'await tools.write({})', description: 'Write a file' }) },
} as SidebarSessionEvent,
...dispatch(4, root + ':ptc:1', 'write', { file_path: PTC_WRITTEN, content: 'x' }, 'written'),
...dispatch(6, root + ':ptc:2', 'read', { file_path: PTC_READ }, 'read'),
{
type: 'tool/result',
seq: 8,
time: 8_000,
data: {
turn: 1,
step: 1,
message: { source: { kind: 'tool', callId: root }, content: [{ type: 'tool-result', content: [{ type: 'text', text: 'done' }] }] },
},
} as SidebarSessionEvent,
{
type: 'assistant/message',
seq: 9,
time: 9_000,
data: {
turn: 1,
step: 2,
message: { content: [{ type: 'text', text: 'I wrote `' + PTC_WRITTEN + '` and read `' + PTC_READ + '`.' }] },
},
} as SidebarSessionEvent,
]
const produced = producedFilePaths(transcriptRows(entries(list)))
expect(produced, 'a write inside run_code is production').toContain(PTC_WRITTEN)
expect(produced, 'a read inside run_code is not production').not.toContain(PTC_READ)
harness.wire.events = list
const rendered = harness.mount()
await harness.flush(4)
try {
const { container } = rendered
expect(mentionOf(container, PTC_WRITTEN), 'the PTC write stays clickable').toBeDefined()
expect(mentionOf(container, PTC_READ), 'the PTC read stays inert').toBeUndefined()
} finally {
rendered.unmount()
}
})
})
+243
View File
@@ -0,0 +1,243 @@
/**
* PTC (run_code) transcript mapping: the side-chat transcript must fold the
* log-only PTC pair (tool/ptc-dispatch-start + tool/ptc-dispatch) into the
* root run_code row's children, with the same tool-row fields a direct call
* gets (args, result text, failed state, structured card, attachments).
*
* ============================ CONTRACT ============================
* 1. A start attaches a RUNNING child (executing: true) under its parent;
* the paired dispatch settles the SAME child in place, keeping the start
* event's seq as its identity.
* 2. A dispatch without a start still yields a settled child.
* 3. A failed dispatch marks the child failed and drops its structured card.
* 4. parentCallId pointing at another subCallId nests one level deeper.
* 5. A PTC event whose parent row is outside the event window contributes
* nothing (no orphan top-level row).
* 6. The row-reuse pass compares children: unchanged PTC trees keep their
* object identity, a settled dispatch rebuilds the root row.
* ==================================================================
*/
import { describe, expect, it } from 'vitest'
import type { SidebarHistoryEntry, SidebarSessionEvent } from '../src/context-types.ts'
import { transcriptRows, type SidechatTranscriptRow } from '../src/client/sidechat-transcript.ts'
const ROOT = 'root'
function entry(event: SidebarSessionEvent): SidebarHistoryEntry {
return { event }
}
/** One log event fixture; the surface-eligible message events carry the
* append marker exactly like the live pipeline appends them. */
function ev(type: string, seq: number, data: Record<string, unknown> = {}): SidebarSessionEvent {
const event: SidebarSessionEvent = { type, seq, time: seq * 1_000, data }
if (type === 'user/message' || type === 'assistant/message' || type === 'tool/result') {
return { ...event, surfaceOp: 'append' } as SidebarSessionEvent
}
return event
}
/** The root program call: a run_code with code + description. */
function rootCall(seq = 3): SidebarSessionEvent {
return ev('tool/call', seq, {
turn: 1,
step: 1,
callId: ROOT,
name: 'run_code',
arguments: JSON.stringify({
code: 'const r = await tools.bash({ command: "echo root-code-only" })',
description: 'Inspect the repo',
}),
})
}
/** One PTC sub-call start. */
function start(seq: number, sub: string, name: string, args: Record<string, unknown>, parent = ROOT): SidebarSessionEvent {
return ev('tool/ptc-dispatch-start', seq, {
rootCallId: ROOT,
parentCallId: parent,
subCallId: sub,
name,
arguments: args,
})
}
/** One PTC sub-call result. */
function dispatch(
seq: number,
sub: string,
name: string,
args: Record<string, unknown>,
content: unknown[],
extra: Record<string, unknown> = {},
): SidebarSessionEvent {
return ev('tool/ptc-dispatch', seq, {
rootCallId: ROOT,
parentCallId: ROOT,
subCallId: sub,
name,
arguments: args,
isError: false,
content,
...extra,
})
}
function rootResult(seq: number, text = 'done'): SidebarSessionEvent {
return ev('tool/result', seq, {
turn: 1,
step: 1,
message: { source: { kind: 'tool', callId: ROOT }, content: [{ type: 'tool-result', content: [{ type: 'text', text }] }] },
})
}
type ToolRow = Extract<SidechatTranscriptRow, { kind: 'tool' }>
function toolRows(events: SidebarSessionEvent[]): ToolRow[] {
return transcriptRows(events.map(entry)).filter((row): row is ToolRow => row.kind === 'tool')
}
const BASH_ARGS = { command: 'echo ptc-child-ok' }
const READ_ARGS = { file_path: 'src/a.ts' }
describe('PTC sub-call rows', () => {
it('attaches paired bash/read sub-calls to the run_code row with their structured cards', () => {
const root = rootCall()
const bashStart = start(4, ROOT + ':ptc:1', 'bash', BASH_ARGS)
const bashDispatch = dispatch(5, ROOT + ':ptc:1', 'bash', BASH_ARGS, [{ type: 'text', text: 'ptc-child-ok\n[exit code: 0]' }], { meta: { cwd: '/p' } })
const readStart = start(6, ROOT + ':ptc:2', 'read', READ_ARGS)
const readDispatch = dispatch(7, ROOT + ':ptc:2', 'read', READ_ARGS, [{ type: 'text', text: '<content>\n1: read-child-ok\n</content>' }], {
meta: { path: 'src/a.ts', offset: 1, lines: [{ number: 1, text: 'read-child-ok' }], totalLines: 1, lang: 'ts' },
})
const result = rootResult(8)
const rows = toolRows([ev('session/end-seed', 0), root, bashStart, bashDispatch, readStart, readDispatch, result])
expect(rows).toHaveLength(1)
const tool = rows[0]!
expect(tool.name).toBe('run_code')
expect(tool.executing).toBe(false)
expect(tool.resultText).toBe('done')
expect(tool.children).toHaveLength(2)
const bash = tool.children![0]!
expect(bash).toMatchObject({ name: 'bash', callId: ROOT + ':ptc:1', seq: 4, executing: false, failed: false, args: JSON.stringify(BASH_ARGS) })
expect(bash.card).toMatchObject({ type: 'terminal', command: 'echo ptc-child-ok', output: 'ptc-child-ok', exitCode: 0 })
expect(bash.resultText).toBe('ptc-child-ok\n[exit code: 0]')
const read = tool.children![1]!
expect(read).toMatchObject({ name: 'read', callId: ROOT + ':ptc:2', seq: 6, executing: false })
expect(read.card).toMatchObject({
type: 'read',
label: 'src/a.ts',
lines: [{ number: 1, text: 'read-child-ok' }],
totalLines: 1,
lang: 'ts',
})
})
it('keeps a started-only sub-call running until its dispatch lands', () => {
const rows = toolRows([
ev('session/end-seed', 0),
rootCall(),
start(4, ROOT + ':ptc:1', 'bash', BASH_ARGS),
])
expect(rows).toHaveLength(1)
expect(rows[0]!.executing).toBe(true)
expect(rows[0]!.children).toHaveLength(1)
expect(rows[0]!.children![0]).toMatchObject({ name: 'bash', executing: true, failed: false })
expect(rows[0]!.children![0]!.resultText).toBeUndefined()
})
it('recovers a settled sub-call from a dispatch without its start', () => {
const rows = toolRows([
ev('session/end-seed', 0),
rootCall(),
dispatch(4, ROOT + ':ptc:1', 'bash', BASH_ARGS, [{ type: 'text', text: 'recovered\n[exit code: 1]' }], { isError: false }),
])
expect(rows).toHaveLength(1)
const child = rows[0]!.children![0]!
expect(child).toMatchObject({ seq: 4, name: 'bash', executing: false, failed: false })
expect(child.card).toMatchObject({ type: 'terminal', command: 'echo ptc-child-ok', output: 'recovered', exitCode: 1 })
})
it('marks a failed dispatch failed and drops the structured card', () => {
const failed = dispatch(5, ROOT + ':ptc:1', 'write', { file_path: 'readonly.txt', content: 'new' }, [{ type: 'text', text: 'permission denied' }], { isError: true })
const rows = toolRows([
ev('session/end-seed', 0),
rootCall(),
start(4, ROOT + ':ptc:1', 'write', { file_path: 'readonly.txt', content: 'new' }),
failed,
])
const child = rows[0]!.children![0]!
expect(child.failed).toBe(true)
expect(child.executing).toBe(false)
expect(child.resultText).toBe('permission denied')
expect(child.card).toBeUndefined()
})
it('nests a sub-call under its sub-call parent', () => {
const rows = toolRows([
ev('session/end-seed', 0),
rootCall(),
start(4, ROOT + ':ptc:1', 'bash', BASH_ARGS),
start(5, ROOT + ':ptc:1:ptc:1', 'read', READ_ARGS, ROOT + ':ptc:1'),
dispatch(6, ROOT + ':ptc:1:ptc:1', 'read', READ_ARGS, [{ type: 'text', text: 'nested' }]),
])
const outer = rows[0]!.children![0]!
expect(outer.name).toBe('bash')
expect(outer.children).toHaveLength(1)
expect(outer.children![0]).toMatchObject({ name: 'read', callId: ROOT + ':ptc:1:ptc:1' })
})
it('ignores PTC events whose parent row is outside the window', () => {
const rows = toolRows([
ev('session/end-seed', 0),
start(1, 'orphan:ptc:1', 'bash', BASH_ARGS, 'missing-root'),
dispatch(2, 'orphan:ptc:1', 'bash', BASH_ARGS, [{ type: 'text', text: 'no parent' }]),
])
expect(rows).toEqual([])
})
it('keeps unchanged PTC trees by identity and rebuilds on a settle', () => {
const events = [
ev('session/end-seed', 0),
rootCall(),
start(4, ROOT + ':ptc:1', 'bash', BASH_ARGS),
]
const first = transcriptRows(events.map(entry))
const second = transcriptRows(events.map(entry), first)
expect(second[0]).toBe(first[0])
const settled = [...events, dispatch(5, ROOT + ':ptc:1', 'bash', BASH_ARGS, [{ type: 'text', text: 'out\n[exit code: 0]' }])]
const third = transcriptRows(settled.map(entry), second)
expect(third[0]).not.toBe(second[0])
expect((third[0] as ToolRow).children![0]).toMatchObject({ executing: false, resultText: 'out\n[exit code: 0]' })
})
it('keeps a PTC present as a child row while the delivery card stays top-level', () => {
const presentArgs = { files: [{ path: 'out/report.pdf' }] }
const rows = transcriptRows([
ev('session/end-seed', 0),
rootCall(),
start(4, ROOT + ':ptc:1', 'present', presentArgs),
dispatch(5, ROOT + ':ptc:1', 'present', presentArgs, [{ type: 'text', text: 'Presented out/report.pdf' }]),
ev('deliverables/presented', 6, { turn: 1, callId: ROOT + ':ptc:1', files: [{ path: '/p/out/report.pdf' }] }),
].map(entry))
const tool = rows.find((row): row is ToolRow => row.kind === 'tool')
expect(tool?.children).toHaveLength(1)
expect(tool?.children?.[0]).toMatchObject({ name: 'present', callId: ROOT + ':ptc:1', executing: false })
const delivery = rows.find(row => row.kind === 'deliverables')
expect(delivery).toMatchObject({ kind: 'deliverables', callId: ROOT + ':ptc:1', files: [{ path: '/p/out/report.pdf' }] })
})
it('never throws on a malformed PTC payload', () => {
const rows = toolRows([
ev('session/end-seed', 0),
rootCall(),
ev('tool/ptc-dispatch-start', 4, { parentCallId: ROOT, name: 'bash' }),
ev('tool/ptc-dispatch', 5, { parentCallId: ROOT, name: 'bash', content: 'not-an-array' }),
])
expect(rows).toHaveLength(1)
expect(rows[0]!.children).toBeUndefined()
})
})
+130
View File
@@ -0,0 +1,130 @@
// @vitest-environment jsdom
/**
* PTC (run_code) display in the real SideChatView.
*
* Why this spec exists: a PTC program logs only `run_code` as a tool/call and
* dispatches its inner tools as log-only `tool/ptc-dispatch*` pairs, so the
* side transcript used to show one raw-JSON run_code row and none of the
* work the program did. The main conversation renders that call tree (root
* row + indented sub-calls + the same structured cards); the side chat must
* agree.
*
* ============================ CONTRACT ============================
* 1. The run_code row's collapsed line carries the model-written description,
* never the raw arguments JSON.
* 2. Its disclosed body shows the PROGRAM, not the escaped argument blob; the
* final output stays in its own labelled Result section.
* 3. PTC sub-calls render as indented rows under that root, in
* `[data-sidechat-subcalls]`, OUTSIDE the root <details> — so a collapsed
* root still shows them.
* 4. A bash sub-call renders the terminal card (command + output), and a read
* sub-call renders its line window; neither falls back to raw JSON.
* ==================================================================
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx'
const ROOT = 'root'
function ev(type: string, seq: number, data: Record<string, unknown> = {}): unknown {
return { type, seq, time: seq * 1_000, data }
}
const BASH_ARGS = { command: 'echo ptc-child-ok' }
const READ_ARGS = { file_path: 'src/a.ts' }
function events(): unknown[] {
return [
ev('session/end-seed', 0),
ev('user/message', 1, { content: [{ type: 'text', text: 'run it' }], source: { kind: 'user' } }),
ev('turn/start', 2, { turn: 1 }),
ev('tool/call', 3, {
turn: 1,
step: 1,
callId: ROOT,
name: 'run_code',
arguments: JSON.stringify({
code: 'const r = await tools.bash({ command: "echo root-code-only" })',
description: 'Inspect the repo',
}),
}),
ev('tool/ptc-dispatch-start', 4, { rootCallId: ROOT, parentCallId: ROOT, subCallId: ROOT + ':ptc:1', name: 'bash', arguments: BASH_ARGS }),
ev('tool/ptc-dispatch', 5, {
rootCallId: ROOT,
parentCallId: ROOT,
subCallId: ROOT + ':ptc:1',
name: 'bash',
arguments: BASH_ARGS,
isError: false,
content: [{ type: 'text', text: 'ptc-child-ok\n[exit code: 0]' }],
meta: { cwd: '/p' },
}),
ev('tool/ptc-dispatch-start', 6, { rootCallId: ROOT, parentCallId: ROOT, subCallId: ROOT + ':ptc:2', name: 'read', arguments: READ_ARGS }),
ev('tool/ptc-dispatch', 7, {
rootCallId: ROOT,
parentCallId: ROOT,
subCallId: ROOT + ':ptc:2',
name: 'read',
arguments: READ_ARGS,
isError: false,
content: [{ type: 'text', text: '<content>\n1: read-child-ok\n</content>' }],
meta: { path: 'src/a.ts', offset: 1, lines: [{ number: 1, text: 'read-child-ok' }], totalLines: 1, lang: 'ts' },
}),
ev('tool/result', 8, {
turn: 1,
step: 1,
message: { source: { kind: 'tool', callId: ROOT }, content: [{ type: 'tool-result', content: [{ type: 'text', text: 'program done' }] }] },
}),
ev('assistant/message', 9, { turn: 1, step: 2, message: { content: [{ type: 'text', text: 'finished' }] } }),
// No turn/end: the turn fold stays open, so the root row is in view.
]
}
let harness: SidechatHarness
beforeEach(() => {
harness = installSidechatHarness({ events: events() })
})
afterEach(() => {
harness.cleanup()
})
describe('PTC run_code display in SideChatView', () => {
it('shows the description, the program body and indented bash/read sub-call cards', async () => {
const rendered = harness.mount()
await harness.flush(4)
try {
const { container } = rendered
const allDetails = [...container.querySelectorAll<HTMLDetailsElement>('details')]
const root = allDetails.find(element => element.querySelector('summary')?.textContent?.includes('run_code') === true)
expect(root, 'the run_code row renders as a disclosure').toBeDefined()
if (root === undefined) return
const summary = root.querySelector('summary')
expect(summary).not.toBeNull()
expect(summary!.textContent, 'the collapsed line is the model description').toContain('Inspect the repo')
expect(summary!.textContent, 'the collapsed line never dumps raw arguments').not.toContain('{"code"')
expect(root.open, 'the run_code row starts closed').toBe(false)
expect(root.textContent, 'the disclosed body shows the program').toContain('root-code-only')
expect(root.textContent, 'the final result keeps its own section').toContain('program done')
const subcalls = container.querySelector<HTMLElement>('[data-sidechat-subcalls]')
expect(subcalls, 'PTC sub-calls render in their own column').not.toBeNull()
expect(root.contains(subcalls), 'the column is outside the root disclosure').toBe(false)
const children = [...subcalls!.querySelectorAll<HTMLElement>('[data-sidechat-subcall]')]
expect(children, 'both dispatched sub-calls render').toHaveLength(2)
const summaries = children.map(child => child.querySelector('summary')?.textContent ?? '')
expect(summaries[0], 'bash carries its command summary').toContain('bash')
expect(summaries[0]).toContain('echo ptc-child-ok')
expect(summaries[0], 'the bash line is not raw JSON').not.toContain('{"command"')
expect(summaries[1], 'read carries its path summary').toContain('src/a.ts')
const text = container.textContent ?? ''
expect(text, 'the bash terminal output is visible').toContain('ptc-child-ok')
expect(text, 'the read line window is visible').toContain('read-child-ok')
} finally {
rendered.unmount()
}
})
})