Files
apes-sidebar/tests/sidechat-view.spec.tsx
T
Menghuan1918 6586e3e2d3 feat: adapt to DSH 0.1.7-alpha.1 and yield the read-only previews
DSH 0.1.7-alpha.1 is 1299 commits past 0.1.6-alpha.2 and rewrites four
contracts this plugin was built on. The peer floor moves to
^0.1.7-alpha.1 (semver's prerelease rule means ^0.1.6-alpha.2 can never
match a 0.1.7 prerelease); 0.1.6-alpha.2 and earlier stay on v0.19.1.
Released as 0.21.0-alpha.1 (dist-tag alpha).

Hard breaks:
- dsh-settings was rewritten: register(ns, schema) is gone, a form is
  addressed by the plugin row's Loader entry id and read from the
  module's exported Config. The preferences are merged into Config and
  marked volatile — which requires DSH's own schemastery, because only
  that build wraps a volatile field in the cosmokit reference the
  loader's volatile commit walks. With the public package a settings
  write reports success and revision 1 while the effective value never
  changes.
- ui-primitives renamed its whole icon family (IconXxx14/16 ->
  IconXxxRegular/Medium): 26 imported symbols, 17 files. The failing
  mode is render-time, not load-time. Five call sites that relied on the
  old 14px default now pass size={14} explicitly.
- Session format v4 rejects source.kind === 'plugin'; the side-chat
  boundary injection now writes plugin:dsh-better-sidebar, the same kind
  DSH's own v3->v4 migration produces, so historical threads survive.
  Tool results moved to role 'tool' with top-level content/isError; all
  four parsers accept both shapes.
- The client session snapshot dropped subagentsByParent/jobsBySession
  and the on-demand subagent-catalog observation API. The Tasks page
  reads projectionsBySession and a new jobs.list route.

Yields and convergence:
- The read-only previews go to DSH's documentpreview (Office->PDF, a
  spreadsheet worker, zoom, per-directory refresh); editor.canOpen
  refuses those 26 extensions. Markdown, HTML (with its sandbox
  switches) and the editable code buffer stay.
- The host browser kind is desktop-profile-only now, so the web e2e
  lanes expect no browser entry and assert its absence.
- Link takeover claims only urlTarget links and passes the rest to the
  host, fixing a regression from the 0.1.6 round: the fallback pointed
  at a 'browser' type the plugin no longer registers, so http links in
  its own markdown did nothing.

Also fixed, found along the way:
- The file tree refreshes live (new directory watch over the plugin's
  own socket), since the plugin owns the `files` kind.
- ctx.sessions.list has no `current` field at either tag; the three
  readers were dead. They now use ctx.sidebarRight.mounted.
- package.json.files was missing lib/client-locale.js.
- Two genuinely dead call sites: sessions.openSubagent/open/
  refreshSubagents do not exist on the current baseline, so the
  topology click, the jump-back and the retry were all no-ops.
- The test harness window shim lacked addEventListener, which the 0.1.7
  primitives call at module-evaluation time; and the e2e token exchange
  needs Playwright's request stack, not Node's fetch.
2026-09-22 17:09:08 +08:00

209 lines
7.9 KiB
TypeScript

/**
* 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 } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot, setupReactAct } from './test-utils.ts'
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'
setupReactAct()
/** 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) {
const 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
}
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({
byId: {
root: { id: 'root', displayTitle: '主会话', running: false },
t1: { id: 't1', displayTitle: 'Side: 线程一', origin: 'subagent', parentId: 'root', running: false },
},
// The side thread's parent catalog (DSH 0.1.7 projection shape); the view
// below reads the summary row, not the catalog, but the fixture is the
// real snapshot shape so a future reader cannot copy a phantom field.
projectionsBySession: {
root: {
values: {
subagentCatalog: [{ id: 't1', createdAt: 1_000, mode: 'continuable', label: 'Side: 线程一' }],
},
state: 'ready',
error: null,
},
},
})
}
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 } = renderRoot(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 } = renderRoot(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 = renderRoot(createElement(SideChatView, viewProps(makeCtx(threadStore()))))
expect(absent.container.textContent ?? '').not.toContain('连接已断开')
absent.unmount()
const connection = makeConnection('connected')
const connected = renderRoot(createElement(SideChatView, viewProps(makeCtx(threadStore(), connection))))
expect(connected.container.textContent ?? '').not.toContain('连接已断开')
connected.unmount()
})
})