feat(sidechat): main-conversation Blocks, turn usage tail, reconnect banner

Rendering-layer upgrade for the Side Chat transcript (data already rides
the raw events; the mapping just stopped discarding it):

- Tool rows with a derivable structure now render the host's
  ui-primitives atoms instead of a generic double <pre>: bash calls map
  onto TerminalBlock (command from call args, output + exit pill
  recovered from the result's trailing exit marker), edit/write map onto
  DiffBlock (call-time literal replacement, refined by the result meta's
  contextual hunks), read maps onto ReadBlock (line-window meta, same
  semantic narrowing the host applies). Every narrowing declines to the
  generic row on malformed input.
- turn/end now emits a turnSummary row: token usage aggregated from
  assistant/message.usage (output summed across steps, input from the
  last request) plus the envelope-time wall duration, printed with the
  main conversation's formatTokens/formatDurationMs cadence.
- The client entry injects 'connection' (DSH 0.1.2-alpha.2+) and the
  thread view shows the host's ConnectionIndicator while the Remote
  transport is down; the reconnect control calls reconnect() and a
  disconnected -> connected transition pulls the transcript immediately
  instead of waiting for the next poll tick.

19 new locale keys propagated across zh/en and all 19 third-language
dictionaries; unit coverage in sidechat-transcript.spec and a new
sidechat-view render spec (jsdom). Real-host mount smoke: 14/14.
This commit is contained in:
Menghuan1918 committed 2026-08-31 23:28:20 +08:00
1 parent d70db8fb02
commit 561ad66071
27 files changed
+1175 -17

No files matched your search

+189 -1
View File
@@ -8,7 +8,13 @@
import { describe, expect, it } from 'vitest'
import type { SidebarHistoryEntry, SidebarSessionEvent } from '../src/context-types.ts'
import { SIDE_BOUNDARY_PREFIX, SIDE_BOUNDARY_PROMPT, SIDE_INJECTION_PLUGIN } from '../src/sidechat-core.ts'
import { toolArgsSummary, transcriptRows, type SidechatTranscriptRow } from '../src/client/sidechat-transcript.ts'
import {
formatDurationMs,
formatTokens,
toolArgsSummary,
transcriptRows,
type SidechatTranscriptRow,
} from '../src/client/sidechat-transcript.ts'
/** One history entry (event + optional view). */
function entry(event: SidebarSessionEvent): SidebarHistoryEntry {
@@ -164,6 +170,188 @@ describe('transcriptRows', () => {
})
})
describe('turnSummary rows', () => {
it('emits one tail row per turn: envelope-time duration + last-input/summed-output usage', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 1, { turn: 1 })),
entry(ev('assistant/message', 2, { turn: 1, step: 1, message: { content: textBlocks('a') }, usage: { inputTokens: 100, outputTokens: 40 } })),
entry(ev('assistant/message', 3, { turn: 1, step: 2, message: { content: textBlocks('b') }, usage: { inputTokens: 160, outputTokens: 30 } })),
entry(ev('turn/end', 4, { turn: 1, reason: 'completed' })),
]
const rows = transcriptRows(entries)
expect(rows.at(-1)).toEqual({ kind: 'turnSummary', seq: 4, inputTokens: 160, outputTokens: 70, durationMs: 3000 })
})
it('keeps a duration-only tail without usage and a usage-only tail without a turn/start', () => {
const cancelled = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/start', 2, { turn: 1 })),
entry(ev('turn/end', 7, { turn: 1, reason: 'cancelled' })),
]
expect(transcriptRows(cancelled).at(-1)).toEqual({ kind: 'turnSummary', seq: 7, durationMs: 5000 })
const seedCutStart = [
entry(ev('session/end-seed', 0)),
entry(ev('assistant/message', 2, { turn: 1, step: 1, message: { content: textBlocks('a') }, usage: { inputTokens: 10, outputTokens: 5 } })),
entry(ev('turn/end', 3, { turn: 1, reason: 'completed' })),
]
expect(transcriptRows(seedCutStart).at(-1)).toEqual({ kind: 'turnSummary', seq: 3, inputTokens: 10, outputTokens: 5 })
})
it('skips the tail entirely when nothing is computable', () => {
const entries = [
entry(ev('session/end-seed', 0)),
entry(ev('turn/end', 1, { turn: 1, reason: 'completed' })),
]
expect(transcriptRows(entries)).toEqual([])
})
})
describe('tool cards', () => {
const callRow = (seq: number, name: string, args: string): SidebarHistoryEntry =>
entry(ev('tool/call', seq, { turn: 1, step: 1, callId: `c${seq}`, name, arguments: args }))
const resultRow = (seq: number, callId: string, text: string, extra: Record<string, unknown> = {}): SidebarHistoryEntry =>
entry(ev('tool/result', seq, {
turn: 1,
step: 1,
message: {
source: { kind: 'tool', callId },
content: [{ type: 'tool-result', toolCallId: callId, content: [{ type: 'text', text }] }],
},
...extra,
}))
const toolRow = (entries: readonly SidebarHistoryEntry[]) => {
const rows = transcriptRows(entries)
expect(rows).toHaveLength(1)
return rows[0] as Extract<SidechatTranscriptRow, { kind: 'tool' }>
}
it('derives the call-time terminal card for bash and refines output/exit from the result marker', () => {
const row = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"echo hi","workdir":"/w"}'),
resultRow(2, 'c1', 'hi\n[exit code: 3]'),
])
expect(row.card).toEqual({ type: 'terminal', command: 'echo hi', cwd: '/w', output: 'hi', exitCode: 3 })
})
it('recovers the signal pill and defaults a marker-less settle to exit code 0', () => {
const signaled = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x"}'),
resultRow(2, 'c1', 'boom\n[killed by signal: SIGKILL]'),
])
expect(signaled.card).toEqual({ type: 'terminal', command: 'x', output: 'boom', signal: 'SIGKILL' })
const clean = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x"}'),
resultRow(2, 'c1', 'ok'),
])
expect(clean.card).toEqual({ type: 'terminal', command: 'x', output: 'ok', exitCode: 0 })
})
it('skips the terminal card for background bash and drops it on failed results', () => {
const background = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x","run_in_background":true}'),
])
expect(background.card).toBeUndefined()
const failed = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'bash', '{"command":"x"}'),
resultRow(2, 'c1', 'denied', { error: { name: 'EACCES', code: 'EACCES' } }),
])
expect(failed.card).toBeUndefined()
})
it('derives literal diff cards for edit/write calls and refines from the result meta hunks', () => {
const edit = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'edit', '{"file_path":"/a.ts","old_string":"x","new_string":"y"}'),
])
expect(edit.card).toEqual({ type: 'diff', diffs: [{ path: '/a.ts', oldText: 'x', newText: 'y' }] })
const write = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'write', '{"file_path":"/new.ts","content":"body"}'),
])
expect(write.card).toEqual({ type: 'diff', diffs: [{ path: '/new.ts', oldText: null, newText: 'body' }] })
const refined = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'edit', '{"file_path":"/a.ts","old_string":"x","new_string":"y"}'),
resultRow(2, 'c1', 'ok', { meta: { diffs: [{ path: '/a.ts', oldText: 'x\nctx', newText: 'y\nctx' }] } }),
])
expect(refined.card).toEqual({ type: 'diff', diffs: [{ path: '/a.ts', oldText: 'x\nctx', newText: 'y\nctx' }] })
const malformed = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'edit', '{"file_path":"/a.ts","old_string":"x","new_string":"y"}'),
resultRow(2, 'c1', 'ok', { meta: { diffs: [{ path: 7, oldText: 'x', newText: 'y' }] } }),
])
// Malformed meta declines to the call-time literal card, never throws.
expect(malformed.card).toEqual({ type: 'diff', diffs: [{ path: '/a.ts', oldText: 'x', newText: 'y' }] })
})
it('builds the read card from the result line-window meta and declines malformed windows', () => {
const read = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'read', '{"path":"/a.ts","offset":2,"limit":2}'),
resultRow(2, 'c1', 'window text', {
meta: { path: '/a.ts', offset: 2, lines: [{ number: 2, text: 'b' }, { number: 3, text: 'c' }], totalLines: 5, lang: 'ts' },
}),
])
expect(read.card).toEqual({
type: 'read',
label: '/a.ts',
lines: [{ number: 2, text: 'b' }, { number: 3, text: 'c' }],
totalLines: 5,
lang: 'ts',
})
const nonMonotonic = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'read', '{"path":"/a.ts"}'),
resultRow(2, 'c1', 'window text', {
meta: { path: '/a.ts', offset: 1, lines: [{ number: 3, text: 'c' }, { number: 2, text: 'b' }], totalLines: 5 },
}),
])
expect(nonMonotonic.card).toBeUndefined()
})
it('leaves unknown tools on the generic row', () => {
const row = toolRow([
entry(ev('session/end-seed', 0)),
callRow(1, 'todo_write', '{"todos":[]}'),
])
expect(row.card).toBeUndefined()
})
})
describe('usage formatting', () => {
it('formatTokens mirrors the main conversation K/M compaction', () => {
expect(formatTokens(517)).toBe('517')
expect(formatTokens(999)).toBe('999')
expect(formatTokens(1_234)).toBe('1.2K')
expect(formatTokens(12_234)).toBe('12.2K')
expect(formatTokens(122_345)).toBe('122K')
expect(formatTokens(1_234_567)).toBe('1.2M')
})
it('formatDurationMs mirrors the main conversation s / m+s cadence', () => {
expect(formatDurationMs(0)).toBe('0s')
expect(formatDurationMs(500)).toBe('0.5s')
expect(formatDurationMs(45_200)).toBe('45.2s')
expect(formatDurationMs(61_000)).toBe('1m1s')
expect(formatDurationMs(162_000)).toBe('2m42s')
})
})
describe('toolArgsSummary', () => {
it('picks the most identifying string field', () => {
expect(toolArgsSummary('{"command":"ls -la","timeout":1000}')).toBe('ls -la')
+212
View File
@@ -0,0 +1,212 @@
/**
* Side Chat view render tests: tool rows with structured cards render the
* host's ui-primitives Blocks (terminal surface from a bash call/result
* pair), the turn-tail usage/duration line renders from the mapped
* turnSummary row, and the connection banner follows `ctx.connection.state`
* (shown + reconnect-click while disconnected, hidden once connected, with
* an immediate transcript pull on recovery).
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { SideChatView } from '../src/client/SideChatView.tsx'
import { attachLocale } from '../src/client/locales.ts'
import type { Context, SidebarSessionList } from '../src/context-types.ts'
import type { SidebarTab } from '../src/client/state.ts'
;(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true
/** Minimal structural fake of the DSH LocaleService face the sidebar uses. */
class FakeLocale {
active: string = 'zh'
getSnapshot(): { active: string } {
return { active: this.active }
}
subscribe(_fn: () => void): () => void {
return () => {}
}
register(_ns: string, _locale: string, _dict: Record<string, string>): () => void {
return () => {}
}
}
/** The thread's own (seed-cut) event log the sidechat.events stub serves. */
const EVENTS = [
{ type: 'session/end-seed', seq: 0, time: 0, data: {} },
{ type: 'user/message', seq: 1, time: 1_000, data: { content: [{ type: 'text', text: 'hi' }], source: { kind: 'user' } }, surfaceOp: 'append' },
{ type: 'turn/start', seq: 2, time: 2_000, data: { turn: 1 } },
{ type: 'tool/call', seq: 3, time: 3_000, data: { turn: 1, step: 1, callId: 'c1', name: 'bash', arguments: '{"command":"echo sidechat-ok-42"}' } },
{
type: 'tool/result',
seq: 4,
time: 4_000,
surfaceOp: 'append',
data: {
turn: 1,
step: 1,
message: {
source: { kind: 'tool', callId: 'c1' },
content: [{ type: 'tool-result', toolCallId: 'c1', content: [{ type: 'text', text: 'sidechat-ok-42\n[exit code: 0]' }] }],
},
},
},
{
type: 'assistant/message',
seq: 5,
time: 5_000,
surfaceOp: 'append',
data: { turn: 1, step: 2, message: { content: [{ type: 'text', text: 'done' }] }, usage: { inputTokens: 1_200, outputTokens: 345 } },
},
{ type: 'turn/end', seq: 6, time: 6_000, data: { turn: 1, reason: 'completed' } },
]
/** A subscribable sessions-list snapshot (mirror of the runtime list feed). */
function makeStore(initial: SidebarSessionList) {
let snapshot = initial
const listeners = new Set<() => void>()
return {
getSnapshot: (): SidebarSessionList => snapshot,
subscribe: (fn: () => void) => {
listeners.add(fn)
return () => { listeners.delete(fn) }
},
}
}
/** A settable connection-state snapshot (the alpha.2 ConnectionHandle face). */
function makeConnection(initial: 'connected' | 'disconnected' | 'connecting') {
let snapshot: 'connected' | 'disconnected' | 'connecting' = initial
const listeners = new Set<() => void>()
return {
state: {
getSnapshot: () => snapshot,
subscribe: (fn: () => void) => {
listeners.add(fn)
return () => { listeners.delete(fn) }
},
},
reconnect: vi.fn(),
set(next: 'connected' | 'disconnected' | 'connecting'): void {
snapshot = next
for (const fn of [...listeners]) fn()
},
}
}
type Connection = ReturnType<typeof makeConnection>
/** The client context face SideChatView touches (everything inert but list). */
function makeCtx(store: ReturnType<typeof makeStore>, connection?: Connection): Context {
return {
sessions: { list: store },
...(connection !== undefined ? { connection } : {}),
get: (key: string) => (key === 'betterSidebar' ? { updateTab: vi.fn(), openTab: vi.fn() } : undefined),
} as unknown as Context
}
function jsonResponse(value: unknown): Response {
return { ok: true, status: 200, json: async () => value } as unknown as Response
}
/** Render `node` into a detached body container under React's act(). */
function mount(node: ReactNode): { container: HTMLDivElement; unmount: () => void } {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
act(() => { root.render(node) })
const unmount = (): void => {
act(() => { root.unmount() })
container.remove()
}
return { container, unmount }
}
let eventsPulls = 0
beforeEach(() => {
attachLocale(new FakeLocale())
eventsPulls = 0
vi.stubGlobal('fetch', async (url: string | URL) => {
const method = String(url).split('/').pop()
if (method === 'sidechat.events') {
eventsPulls += 1
return jsonResponse({ ok: true, value: { events: EVENTS } })
}
if (method === 'sidechat.info') {
return jsonResponse({ ok: true, value: { live: false, provider: 'deepseek', preset: 'side' } })
}
return jsonResponse({ ok: true, value: {} })
})
})
afterEach(() => {
vi.unstubAllGlobals()
attachLocale(undefined)
})
/** The bound-thread view props (tab meta pins threadId 't1'). */
function viewProps(ctx: Context) {
const tab: SidebarTab = { id: 'tab1', type: 'sidechat', title: '线程一', meta: { threadId: 't1' } }
return { ctx, scope: { sessionId: 'root', cwd: '/p' }, tab, visible: true }
}
/** The sessions-list snapshot with one idle side thread bound to 'root'. */
function threadStore(): ReturnType<typeof makeStore> {
return makeStore({
current: 'root',
byId: {
root: { id: 'root', displayTitle: '主会话', running: false },
t1: { id: 't1', displayTitle: 'Side: 线程一', origin: 'subagent', parentId: 'root', running: false },
},
subagentsByParent: {},
jobsBySession: {},
})
}
describe('SideChatView rendering', () => {
it('renders the bash pair as a TerminalBlock and the turn tail with usage + duration', async () => {
const props = viewProps(makeCtx(threadStore()))
const { container, unmount } = mount(createElement(SideChatView, props))
await act(async () => {}) // flush the initial transcript pull
const text = container.textContent ?? ''
// Terminal surface: the command line and the marker-stripped output body.
expect(text).toContain('echo sidechat-ok-42')
expect(text).toContain('sidechat-ok-42')
// Turn tail: 1.2K/345 compaction + 4s envelope-time duration.
expect(text).toContain('输入 1.2K tok · 输出 345 tok · 4s')
unmount()
})
it('shows the disconnect banner, reconnects on click, and pulls immediately on recovery', async () => {
const connection = makeConnection('disconnected')
const props = viewProps(makeCtx(threadStore(), connection))
const { container, unmount } = mount(createElement(SideChatView, props))
await act(async () => {}) // flush the initial transcript pull
expect(container.textContent ?? '').toContain('连接已断开')
const button = container.querySelector<HTMLButtonElement>('button[aria-label="立即重连"]')
expect(button).not.toBeNull()
act(() => { button?.click() })
expect(connection.reconnect).toHaveBeenCalledTimes(1)
// Recovery hides the banner and triggers an immediate transcript pull.
const pullsBefore = eventsPulls
act(() => { connection.set('connected') })
expect(container.textContent ?? '').not.toContain('连接已断开')
expect(eventsPulls).toBeGreaterThan(pullsBefore)
unmount()
})
it('renders no banner without a connection service or while connected', async () => {
const absent = mount(createElement(SideChatView, viewProps(makeCtx(threadStore()))))
expect(absent.container.textContent ?? '').not.toContain('连接已断开')
absent.unmount()
const connection = makeConnection('connected')
const connected = mount(createElement(SideChatView, viewProps(makeCtx(threadStore(), connection))))
expect(connected.container.textContent ?? '').not.toContain('连接已断开')
connected.unmount()
})
})