test(tencent-meeting): cover the account, the Plugins page, and the skills session

Specs drive a scripted tmeet through each auth status text, a sign-in with trusted and untrusted links, cancellation, and sign-out, and check the cache link and the one-entry skill. The Web E2E runs a stand-in tmeet through a failed and a successful sign-in and a confirmed sign-out; it needs the scaffold to resolve every selected bundle's dependencies, as the other CLI app plugins' do. The tencent-meeting-skills snapshot pins the skill catalog and a tmeet call on the private PATH.
This commit is contained in:
gengruilin committed 2026-10-19 12:04:19 +08:00
1 parent e6f2f2cfd1
commit de82f1ea97
18 files changed
+1140 -1

No files matched your search

@@ -0,0 +1,146 @@
// @vitest-environment jsdom
/** The account section, title tag, activation guidance, and notices render the Host view the page mirrors. */
import type { ComponentProps } from 'react'
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { CliOperationId } from '@deepseek-ai/dsh-cli-account/types'
import type { PluginPackageRef, PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
import type { TencentMeetingState } from '@deepseek-ai/dsh-tencent-meeting-cli/types'
import { afterEach, expect, it, vi } from 'vitest'
import type { ConnectionSnapshot } from '../src/client/connection.ts'
import { en, zh } from '../src/client/locales.ts'
import {
TencentMeetingConnectionActivation, TencentMeetingConnectionBadge, TencentMeetingConnectionSection, TencentMeetingConnectionToast,
} from '../src/client/TencentMeetingConnection.tsx'
afterEach(cleanup)
const OP = 'op' as CliOperationId
const LINK = 'https://meeting.tencent.com/marketplace/tencentmeeting-cli-auth.html?code=fixture'
const SIGNED_OUT: TencentMeetingState = { account: { state: 'signed-out' } }
const CONNECTED: TencentMeetingState = { account: { state: 'connected', userName: '测试用户' } }
function fixture(view?: TencentMeetingState, copy: typeof zh = zh) {
const state = createSnapshotStore<ConnectionSnapshot>({ view, linked: true, stopped: false, busy: false, notice: undefined })
const face = {
useTencentMeetingConnection: bindSnapshotSelector(state),
check: vi.fn(), signIn: vi.fn(), signOut: vi.fn(), cancel: vi.fn(),
openAuthorization: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(),
t: makeTranslate(copy),
}
return { face, set: (change: Partial<ConnectionSnapshot>) => { act(() => { state.set({ ...state.getSnapshot(), ...change }) }) } }
}
const button = (name: string) => screen.getByRole('button', { name })
it('offers the next step while signing in', () => {
const b = fixture(SIGNED_OUT)
render(<TencentMeetingConnectionSection {...b.face} />)
expect(screen.getByText(zh['detail.disconnected'])).toBeTruthy()
expect(screen.getByText(zh.hint)).toBeTruthy()
fireEvent.click(button(zh['action.connect']))
expect(b.face.signIn).toHaveBeenCalledOnce()
b.set({ view: { ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', cancellable: true } } })
expect(screen.getByText(zh['step.authorizing'])).toBeTruthy()
expect(screen.queryByRole('button', { name: zh['action.open'] })).toBeNull()
b.set({ view: { ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', cancellable: true, authorizationUrl: LINK } } })
expect(screen.getByText(zh['detail.authorizing'])).toBeTruthy()
fireEvent.click(button(zh['action.open']))
fireEvent.click(button(zh['action.cancel']))
expect(b.face.openAuthorization).toHaveBeenCalledOnce()
expect(b.face.cancel).toHaveBeenCalledOnce()
b.set({ view: { ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase: 'checking', cancellable: false } } })
expect(screen.getByText(zh['step.connecting'])).toBeTruthy()
expect(screen.queryAllByRole('button')).toHaveLength(0)
b.set({ view: undefined })
expect(screen.getByText(zh['status.checking'])).toBeTruthy()
expect(screen.queryAllByRole('button')).toHaveLength(0)
})
it('names the signed-in user and signs out only after confirmation', () => {
const b = fixture(CONNECTED)
render(<TencentMeetingConnectionSection {...b.face} />)
expect(screen.getByText(zh['detail.connected'].replace('{name}', '测试用户'))).toBeTruthy()
fireEvent.click(button(zh['action.signOut']))
const dialog = screen.getByRole('dialog')
expect(within(dialog).getByText(zh['signOut.body'])).toBeTruthy()
fireEvent.click(within(dialog).getByRole('button', { name: zh['action.cancel'] }))
expect(b.face.signOut).not.toHaveBeenCalled()
fireEvent.click(button(zh['action.signOut']))
fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: zh['action.signOut'] }))
expect(b.face.signOut).toHaveBeenCalledOnce()
b.set({ view: { ...CONNECTED, operation: { id: OP, kind: 'sign-out', phase: 'signing-out', cancellable: false } } })
expect(screen.getByText(zh['step.signing-out'])).toBeTruthy()
expect(screen.queryAllByRole('button')).toHaveLength(0)
})
it.each([['zh', zh], ['en', en]] as const)('reports a failed sign-in with its command and exit code in %s', (_locale, copy) => {
const b = fixture({ ...SIGNED_OUT, result: { id: OP, kind: 'sign-in', outcome: 'failed', failure: { command: 'auth-login', exitCode: 1 } } }, copy)
render(<TencentMeetingConnectionSection {...b.face} />)
const details = copy['failure.details'].replace('{details}', `auth-login · ${copy['failure.exitCode'].replace('{code}', '1')}`)
expect(screen.getByRole('alert').textContent).toBe(`${copy.failed} ${details}`)
expect(button(copy['action.connect'])).toBeTruthy()
b.set({ view: { ...SIGNED_OUT, result: { id: OP, kind: 'sign-in', outcome: 'cancelled' } } })
expect(screen.queryByRole('alert')).toBeNull()
})
it('retries an unconfirmed sign-in by checking again', () => {
const b = fixture({ account: { state: 'unverified' } })
render(<TencentMeetingConnectionSection {...b.face} />)
expect(screen.getByText(zh['detail.unavailable'])).toBeTruthy()
fireEvent.click(button(zh['action.retry']))
expect(b.face.check).toHaveBeenCalledOnce()
})
it('explains a stopped Host component and retries even while the stream is offline', () => {
const b = fixture(undefined)
render(<TencentMeetingConnectionSection {...b.face} />)
b.set({ linked: false, stopped: true })
expect(screen.getByText(zh['status.stopped'])).toBeTruthy()
expect(screen.getByText(zh['detail.stopped'])).toBeTruthy()
fireEvent.click(button(zh['action.retry']))
expect(b.face.retry).toHaveBeenCalledOnce()
})
it('tags only the enabled Tencent Meeting bundle', () => {
const b = fixture(CONNECTED)
const pkg = (name: string, enabled = true): PluginPackageRef => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] })
const badge = (subject: PluginsSubject) =>
<TencentMeetingConnectionBadge {...{ ...b.face, subject } as ComponentProps<typeof TencentMeetingConnectionBadge>} />
const { rerender } = render(badge({ kind: 'bundle', pkg: pkg('@deepseek-ai/dsh-tencent-meeting') }))
expect(screen.getByText(zh['badge.connected'])).toBeTruthy()
b.set({ view: SIGNED_OUT })
expect(screen.getByText(zh['badge.disconnected'])).toBeTruthy()
rerender(badge({ kind: 'bundle', pkg: pkg('@acme/other') }))
expect(document.body.textContent).toBe('')
})
it('guides a newly enabled bundle to sign in, and steps aside once connected', () => {
const b = fixture()
const onDismiss = vi.fn(), onOpenDetails = vi.fn()
const props = { ...b.face, packageName: '@deepseek-ai/dsh-tencent-meeting', onDismiss, onOpenDetails } as ComponentProps<typeof TencentMeetingConnectionActivation>
render(<TencentMeetingConnectionActivation {...props} />)
expect(screen.queryByText(zh['activation.body'])).toBeNull()
b.set({ view: SIGNED_OUT })
fireEvent.click(button(zh['action.connect']))
expect(onOpenDetails).toHaveBeenCalledOnce()
expect(b.face.signIn).toHaveBeenCalledOnce()
b.set({ view: CONNECTED })
expect(onDismiss).toHaveBeenCalledOnce()
})
it('reports the latest notice', () => {
const b = fixture()
render(<TencentMeetingConnectionToast {...b.face} />)
expect(document.body.textContent).toBe('')
b.set({ notice: { seq: 1, kind: 'signed-out' } })
expect(screen.getByText(zh['notice.signed-out'])).toBeTruthy()
})
@@ -0,0 +1,134 @@
// @vitest-environment jsdom
/** The page derives the Tencent Meeting account from the Host's view and drives operations through its Remote. */
import { Context } from '@deepseek-ai/cordis'
import type { RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client'
import type { CliOperationId } from '@deepseek-ai/dsh-cli-account/types'
import type { TencentMeetingState } from '@deepseek-ai/dsh-tencent-meeting-cli/types'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { expect, it, onTestFinished, vi } from 'vitest'
import { createConnection, presentConnection, type ConnectionPresentation } from '../src/client/connection.ts'
type Operation = NonNullable<TencentMeetingState['operation']>
const OP = 'op-1' as CliOperationId
const LINK = 'https://meeting.tencent.com/marketplace/tencentmeeting-cli-auth.html?code=fixture'
const SIGNED_OUT: TencentMeetingState = { account: { state: 'signed-out' } }
const CONNECTED: TencentMeetingState = { account: { state: 'connected', userName: '测试用户' } }
const FAILED_SIGN_IN: NonNullable<TencentMeetingState['result']> = { id: OP, kind: 'sign-in', outcome: 'failed', failure: { command: 'auth-login', exitCode: 1 } }
const FAILED_CHECK: NonNullable<TencentMeetingState['result']> = { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 1 } }
function operation(kind: Operation['kind'], phase: Operation['phase'], cancellable = false, authorizationUrl?: string): Operation {
return { id: OP, kind, phase, cancellable, ...authorizationUrl === undefined ? {} : { authorizationUrl } }
}
it.each<[string, TencentMeetingState | undefined, ConnectionPresentation]>([
['a stopped stream', SIGNED_OUT, { phase: 'stopped', failed: undefined }],
['no view yet', undefined, { phase: 'checking', failed: undefined }],
['an unchecked account', { account: { state: 'unchecked' } }, { phase: 'checking', failed: undefined }],
['a check', { ...SIGNED_OUT, operation: operation('check', 'checking') }, { phase: 'checking', failed: undefined }],
['a first check that failed', { account: { state: 'unchecked' }, result: FAILED_CHECK }, { phase: 'unavailable', failed: FAILED_CHECK }],
['no sign-in', SIGNED_OUT, { phase: 'disconnected', failed: undefined }],
['a failed sign-in', { ...SIGNED_OUT, result: FAILED_SIGN_IN }, { phase: 'disconnected', failed: FAILED_SIGN_IN }],
['a cancelled sign-in', { ...SIGNED_OUT, result: { id: OP, kind: 'sign-in', outcome: 'cancelled' } }, { phase: 'disconnected', failed: undefined }],
['an unconfirmed sign-in', { account: { state: 'unverified' } }, { phase: 'unavailable', failed: undefined }],
['a signed-in user', CONNECTED, { phase: 'connected', userName: '测试用户', failed: undefined }],
['an authorization', { ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', true, LINK) },
{ phase: 'connecting', step: 'authorizing', url: LINK, cancellable: true }],
['a confirmation', { ...SIGNED_OUT, operation: operation('sign-in', 'checking') }, { phase: 'connecting', step: 'connecting', url: undefined, cancellable: false }],
['cancellation', { ...SIGNED_OUT, operation: operation('sign-in', 'cancelling') }, { phase: 'connecting', step: 'connecting', url: undefined, cancellable: false }],
['a sign-out', { ...CONNECTED, operation: operation('sign-out', 'signing-out') }, { phase: 'connecting', step: 'signing-out', url: undefined, cancellable: false }],
])('presents %s', (name, view, expected) => {
expect(presentConnection({ view, stopped: name === 'a stopped stream' })).toEqual(expected)
})
function fixture() {
const queue: TencentMeetingState[] = []
let wake: (() => void) | undefined, closed = false, accepted = 0
let options!: RemoteStreamOptions<TencentMeetingState>
const ok = <T>(value: T): RemoteResult<T> => ({ ok: true, value })
const remote = {
follow: vi.fn(),
check: vi.fn(async () => ok(OP)),
signIn: vi.fn(async () => ok(OP)),
signOut: vi.fn(async () => ok(OP)),
cancel: vi.fn(async (_id: CliOperationId) => ok(undefined)),
}
const ctx = new Context()
ctx.provide('remote', {
tencentMeeting: remote,
$stream: (value: typeof options) => {
options = value
return {
async *[Symbol.asyncIterator]() {
for (;;) {
if (closed) return
const next = queue.shift()
if (next === undefined) { await new Promise<void>((resolve) => { wake = resolve }); continue }
yield { value: next, accept: () => { accepted++ } }
}
},
dispose: async () => { closed = true; wake?.() },
}
},
})
const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null)
const { connection, face } = createConnection(ctx)
onTestFinished(async () => { await connection.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() })
return {
face, remote, open: windowOpen, options: () => options,
snapshot: () => connection.state.getSnapshot(),
async publish(view: TencentMeetingState) {
const target = accepted + 1
queue.push(view)
wake?.()
await vi.waitFor(() => { expect(accepted).toBe(target) })
},
}
}
const settle = async (b: ReturnType<typeof fixture>) => { await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) }
it('follows the tencentMeeting Remote and exposes the mirror to the page', async () => {
const b = fixture()
const signal = new AbortController().signal
b.options().open(signal)
expect(b.remote.follow).toHaveBeenCalledWith(signal)
await b.publish(SIGNED_OUT)
expect(b.face.hooks.tencentMeetingConnection.getSnapshot()).toMatchObject({ view: SIGNED_OUT, linked: true, busy: false })
})
it('signs in through the Remote, opens the authorization page once, and reports the connection', async () => {
const b = fixture()
await b.publish(SIGNED_OUT)
b.face.signIn()
await settle(b)
expect(b.remote.signIn).toHaveBeenCalledOnce()
await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', true, LINK) })
await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', true, LINK) })
expect(b.open.mock.calls.map(call => call[0])).toEqual([LINK])
b.face.cancel()
await settle(b)
expect(b.remote.cancel).toHaveBeenCalledWith(OP)
await b.publish({ ...CONNECTED, result: { id: OP, kind: 'sign-in', outcome: 'succeeded' } })
expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'connected' })
})
it('signs out through the Remote and reports it', async () => {
const b = fixture()
await b.publish(CONNECTED)
b.face.signOut()
await settle(b)
expect(b.remote.signOut).toHaveBeenCalledOnce()
await b.publish({ ...SIGNED_OUT, result: { id: OP, kind: 'sign-out', outcome: 'succeeded' } })
expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'signed-out' })
})
it('checks again without a notice', async () => {
const b = fixture()
await b.publish({ account: { state: 'unverified' } })
b.face.check()
await settle(b)
expect(b.remote.check).toHaveBeenCalledOnce()
await b.publish({ ...CONNECTED, result: { id: OP, kind: 'check', outcome: 'succeeded' } })
expect(b.snapshot().notice).toBeUndefined()
})
@@ -0,0 +1,80 @@
/** The browser half mounts the Tencent Meeting Remote, registers its surfaces, and withdraws both on disposal or failure. */
import { Context, Service } from '@deepseek-ai/cordis'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol'
import { expect, it, vi } from 'vitest'
import { apply as hostApply } from '../src/index.ts'
import { TencentMeetingConnectionActivation, TencentMeetingConnectionBadge, TencentMeetingConnectionSection, TencentMeetingConnectionToast } from '../src/client/TencentMeetingConnection.tsx'
const REMOTE: TypertRemoteContribution = { package: '@deepseek-ai/dsh-tencent-meeting-cli', descriptors: [] }
const SLOTS = [
['plugins.bundle.config', TencentMeetingConnectionSection],
['plugins.bundle.activation', TencentMeetingConnectionActivation],
['plugins.detail.badge', TencentMeetingConnectionBadge],
['shell.overlay', TencentMeetingConnectionToast],
] as const
async function fixture() {
const ctx = new Context()
const unmount = vi.fn(async () => {})
const dispose = vi.fn(async () => {})
class Remote extends Service {
constructor() { super(ctx, 'remote') }
async $mount(contribution: TypertRemoteContribution) {
expect(contribution).toBe(REMOTE)
ctx.provide('remote.tencentMeeting', { follow: vi.fn() })
return unmount
}
$stream() {
return { async *[Symbol.asyncIterator]() { /* the Host reports nothing in this composition */ }, dispose }
}
}
new Remote()
ctx.provide('locale', new LocaleRuntime(ctx))
await ctx.plugin(SlotRegistry)
ctx.slots.register({ name: 'root', children: {
'plugins.bundle.activation': { kind: 'keyed', scope: 'root' },
'plugins.bundle.config': { kind: 'keyed', scope: 'root' },
'plugins.detail.badge': { kind: 'list', scope: 'root' },
'shell.overlay': { kind: 'list', scope: 'root' },
} } as never, () => null)
vi.doMock('@deepseek-ai/dsh-tencent-meeting-cli/remote', () => ({ default: REMOTE }))
const browser = await import('../src/client/index.ts')
return { ctx, unmount, dispose, browser }
}
it('registers the connection surfaces with one shared face, then withdraws them and the Remote', async () => {
hostApply()
const b = await fixture()
try {
const fiber = b.ctx.plugin({ inject: [...b.browser.inject], apply: b.browser.apply })
await fiber
const faces = SLOTS.map(([slot, component]) => {
const [entry] = b.ctx.slots.entries(slot)
expect(entry).toMatchObject({ locale: 'tencent-meeting', component })
return entry!.inject!()
})
expect(new Set(faces.map(face => face.hooks)).size).toBe(1)
expect(b.ctx.slots.entries('plugins.bundle.config')[0]!.options.key).toBe('@deepseek-ai/dsh-tencent-meeting')
await fiber.dispose()
for (const [slot] of SLOTS) expect(b.ctx.slots.entries(slot)).toHaveLength(0)
expect(b.dispose).toHaveBeenCalledOnce()
expect(b.unmount).toHaveBeenCalledOnce()
} finally {
await b.ctx.fiber.dispose()
vi.doUnmock('@deepseek-ai/dsh-tencent-meeting-cli/remote')
}
})
it('withdraws the Remote when the surfaces fail to register', async () => {
const b = await fixture()
vi.spyOn(b.ctx.slots, 'inject').mockImplementationOnce(() => { throw new Error('slot failed') })
try {
await expect(b.browser.apply(b.ctx)).rejects.toThrow('slot failed')
expect(b.unmount).toHaveBeenCalledOnce()
} finally {
await b.ctx.fiber.dispose()
vi.doUnmock('@deepseek-ai/dsh-tencent-meeting-cli/remote')
}
})
@@ -0,0 +1,227 @@
/** Account operations over a scripted tmeet: status text, sign-in, sign-out, cancellation, and the Remote wiring. */
import { rm } from 'node:fs/promises'
import { Context } from '@deepseek-ai/cordis'
import { CliCommandExecutor, type CliOperationId } from '@deepseek-ai/dsh-cli-account'
import SkillRegistry from '@deepseek-ai/dsh-skill'
import * as ShellEnv from '@deepseek-ai/dsh-shell-env'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { TencentMeetingAccount } from '../src/account.ts'
import { PROGRAM } from '../src/directory.ts'
import TencentMeeting, { type TencentMeetingState } from '../src/index.ts'
import { createBinDir, ScriptedSubprocess, type CliReply, type ScriptedProcess } from './harness.ts'
const STATUS = 'auth status'
const LOGIN = 'auth login --no-browser'
const LOGOUT = 'auth logout'
const LOGIN_LINK = 'https://meeting.tencent.com/marketplace/tencentmeeting-cli-auth.html?code=fixture-code'
const CONNECTED: CliReply = {
stdout: 'Logged in\n OpenId: ou_fixture\n UserName: 测试 用户\n'
+ ' AccessToken: valid (expires at 2026-11-01 10:00:00, remaining 15d 0h 6m)\n'
+ ' RefreshToken: valid (expires at 2027-01-01 10:00:00, remaining 76d 0h 6m)\n',
}
const NOT_LOGGED_IN: CliReply = { stdout: 'Not logged in. Please use \'tmeet auth login\' to authenticate.\n' }
const SESSION_EXPIRED: CliReply = { stdout: ' Session has expired. Please use \'tmeet auth login\' to re-authenticate.\n' }
const REFRESH_EXPIRED: CliReply = {
stdout: 'Logged in\n OpenId: ou_fixture\n AccessToken: expired (at 2026-09-01 10:00:00)\n RefreshToken: expired (at 2026-10-01 10:00:00)\n',
}
const UNVERIFIED: CliReply = {
stdout: 'Logged in\n OpenId: ou_fixture\n AccessToken: valid (expires at 2026-11-01 10:00:00, remaining 15d 0h 6m)\n'
+ ' RefreshToken: valid (expires at 2027-01-01 10:00:00, remaining 76d 0h 6m)\n',
}
type Script = (process: ScriptedProcess) => void
let ctx: Context
let subprocess: ScriptedSubprocess
let binDir: string
let script: Record<string, Script | CliReply[]>
beforeEach(async () => {
ctx = new Context()
await ctx.plugin(SkillRegistry)
await ctx.plugin(ScriptedSubprocess)
await ctx.plugin(ShellEnv)
subprocess = ctx.subprocess as ScriptedSubprocess
binDir = await createBinDir()
script = {}
subprocess.respond = (process) => {
const handler = script[process.spec.argv.slice(1).join(' ')]
if (handler === undefined) process.reply({ exitCode: 1, stderr: `unexpected: ${process.spec.argv.join(' ')}` })
else if (Array.isArray(handler)) process.reply(handler.length > 1 ? handler.shift()! : handler[0]!)
else handler(process)
}
})
afterEach(async () => {
await ctx.fiber.dispose()
await rm(binDir, { recursive: true, force: true })
})
const commands = () => subprocess.processes.map(process => process.spec.argv.slice(1).join(' '))
const errors = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'error').map((message): unknown => message.args)
describe('TencentMeetingAccount', () => {
let account: TencentMeetingAccount
beforeEach(() => {
ctx.shellEnv.registerPath({ name: 'tencent-meeting', directories: [binDir], programs: [PROGRAM] })
const cli = new CliCommandExecutor(ctx.subprocess, ctx.shellEnv, { program: PROGRAM, commandTimeoutMs: 5_000 })
account = new TencentMeetingAccount(cli, ctx.logger)
})
afterEach(() => account.dispose())
const settled = async (id: CliOperationId): Promise<TencentMeetingState> => {
await vi.waitFor(() => { expect(account.snapshot().result?.id).toBe(id) })
return account.snapshot()
}
it.each<[string, CliReply, TencentMeetingState['account']]>([
['a sign-in the server accepts', CONNECTED, { state: 'connected', userName: '测试 用户' }],
['no sign-in', NOT_LOGGED_IN, { state: 'signed-out' }],
['a sign-in the CLI cleared after a failed refresh', SESSION_EXPIRED, { state: 'signed-out' }],
['a sign-in whose refresh token expired', REFRESH_EXPIRED, { state: 'signed-out' }],
['a stored sign-in the server did not confirm', UNVERIFIED, { state: 'unverified' }],
])('checks %s', async (_name, reply, expected) => {
script[STATUS] = [reply]
const id = account.start('check')
expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'checking', cancellable: false })
expect(await settled(id)).toEqual({ account: expected, result: { id, kind: 'check', outcome: 'succeeded' } })
})
it.each<[string, CliReply]>([
['a failed status command', { exitCode: 1, stderr: 'Error: failed to read user config' }],
['a status this version does not print', { stdout: 'Signed in as ou_fixture\n' }],
])('keeps the previous account and reports only the command and exit code on %s', async (_name, reply) => {
script[STATUS] = [reply]
const result = await settled(account.start('check'))
expect(result).toEqual({
account: { state: 'unchecked' },
result: { id: result.result?.id, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: reply.exitCode ?? 0 } },
})
expect(errors()).toEqual([['tencent-meeting: account operation failed: %o', {
id: result.result?.id, kind: 'check', phase: 'checking', command: 'auth-status', exitCode: reply.exitCode ?? 0,
}]])
})
it('signs in through the authorization page, offers only trusted links, and confirms the sign-in', async () => {
script[STATUS] = [CONNECTED]
const login = Promise.withResolvers<ScriptedProcess>()
script[LOGIN] = (process) => { login.resolve(process) }
const id = account.start('sign-in')
expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'authorizing', cancellable: true })
const authorizing = await login.promise
authorizing.write('stderr', `authorize url: ${LOGIN_LINK}\n`)
authorizing.write('stdout', '\nPlease open the following URL in your browser to authorize\n\n')
authorizing.write('stdout', 'authorize url: http://meeting.tencent.com/insecure\nauthorize url: https://evil.example/auth\n')
authorizing.write('stdout', `authorize url: ${LOGIN_LINK}\n\nwaiting for authorization...\n`)
await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'authorizing', authorizationUrl: LOGIN_LINK }) })
authorizing.reply({ stdout: 'Login successful. Start managing your meetings using tmeet.\n' })
expect(await settled(id)).toEqual({
account: { state: 'connected', userName: '测试 用户' }, result: { id, kind: 'sign-in', outcome: 'succeeded' },
})
expect(commands()).toEqual([LOGIN, STATUS])
expect(errors()).toEqual([])
})
it.each<[string, Record<string, CliReply[]>, NonNullable<TencentMeetingState['result']>['failure']]>([
['a failed sign-in', { [LOGIN]: [{ exitCode: 1, stdout: `authorize url: ${LOGIN_LINK}\n` }] }, { command: 'auth-login', exitCode: 1 }],
['a sign-in the server did not confirm', { [LOGIN]: [{}], [STATUS]: [UNVERIFIED] }, { command: 'auth-status', exitCode: 0 }],
])('fails on %s without exposing CLI output', async (_name, replies, failure) => {
Object.assign(script, replies)
const result = await settled(account.start('sign-in'))
expect(result.result).toMatchObject({ kind: 'sign-in', outcome: 'failed', failure })
expect(JSON.stringify({ result, errors: errors() })).not.toContain('fixture-code')
})
it('cancels only while waiting for authorization and withdraws the link', async () => {
script[LOGIN] = (process) => { process.write('stdout', `authorize url: ${LOGIN_LINK}\n`) }
const id = account.start('sign-in')
await vi.waitFor(() => { expect(account.snapshot().operation?.authorizationUrl).toBe(LOGIN_LINK) })
await account.cancel('other' as CliOperationId)
expect(account.snapshot().operation?.phase).toBe('authorizing')
const cancelling = account.cancel(id)
expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'cancelling', cancellable: false })
await cancelling
expect(account.snapshot()).toEqual({ account: { state: 'unchecked' }, result: { id, kind: 'sign-in', outcome: 'cancelled' } })
expect(subprocess.processes[0]?.terminated).toBe(true)
expect(errors()).toEqual([])
})
it('signs out without cancellation, then checks again', async () => {
script[STATUS] = [NOT_LOGGED_IN]
const logout = Promise.withResolvers<ScriptedProcess>()
script[LOGOUT] = (process) => { logout.resolve(process) }
const id = account.start('sign-out')
const signingOut = await logout.promise
expect(account.snapshot().operation).toEqual({ id, kind: 'sign-out', phase: 'signing-out', cancellable: false })
await account.cancel(id)
signingOut.reply({ stdout: 'Logout success, welcome to use it again.\n' })
expect(await settled(id)).toEqual({ account: { state: 'signed-out' }, result: { id, kind: 'sign-out', outcome: 'succeeded' } })
expect(commands()).toEqual([LOGOUT, STATUS])
})
it('reports a failed sign-out without checking again', async () => {
script[LOGOUT] = [{ exitCode: 1, stderr: 'Error: logout failed' }]
const result = await settled(account.start('sign-out'))
expect(result.result).toMatchObject({ kind: 'sign-out', outcome: 'failed', failure: { command: 'auth-logout', exitCode: 1 } })
expect(commands()).toEqual([LOGOUT])
})
})
describe('Tencent Meeting Remote', () => {
beforeEach(async () => {
await ctx.plugin(TencentMeeting, { commandTimeoutMs: 5_000, binDir })
})
it('checks for a new follower, streams each change, and starts checks, sign-ins, and sign-outs', async () => {
script[STATUS] = [NOT_LOGGED_IN]
const states: TencentMeetingState[] = []
const leave = new AbortController()
const following = (async () => {
for await (const state of ctx.tencentMeeting.follow(leave.signal)) states.push(state)
})()
const finished = async (id?: CliOperationId): Promise<TencentMeetingState['result']> => {
await vi.waitFor(() => {
expect(states.at(-1)?.result).toBeDefined()
if (id !== undefined) expect(states.at(-1)?.result?.id).toBe(id)
})
return states.at(-1)?.result
}
expect(await finished()).toMatchObject({ kind: 'check', outcome: 'succeeded' })
expect(states[0]).toMatchObject({ account: { state: 'unchecked' }, operation: { kind: 'check' } })
expect(states.at(-1)?.account).toEqual({ state: 'signed-out' })
expect(await finished(ctx.tencentMeeting.check())).toMatchObject({ kind: 'check', outcome: 'succeeded' })
script[LOGIN] = () => {}
const signingIn = ctx.tencentMeeting.signIn()
expect(() => ctx.tencentMeeting.check()).toThrow('another account operation is in progress')
await vi.waitFor(() => { expect(commands().at(-1)).toBe(LOGIN) })
await ctx.tencentMeeting.cancel(signingIn)
expect(await finished(signingIn)).toMatchObject({ kind: 'sign-in', outcome: 'cancelled' })
expect(subprocess.processes.at(-1)?.terminated).toBe(true)
script[LOGOUT] = [{}]
expect(await finished(ctx.tencentMeeting.signOut())).toMatchObject({ kind: 'sign-out', outcome: 'succeeded' })
leave.abort()
await following
})
it('ends its streams and stops account work on disposal', async () => {
script[STATUS] = () => {}
const states: TencentMeetingState[] = []
const following = (async () => {
for await (const state of ctx.tencentMeeting.follow(new AbortController().signal)) states.push(state)
})()
await vi.waitFor(() => { expect(subprocess.processes).toHaveLength(1) })
await ctx.fiber.dispose()
await following
expect(states.length).toBeGreaterThan(0)
expect(subprocess.processes[0]?.terminated).toBe(true)
})
})
@@ -0,0 +1,57 @@
/** The private PATH directory: a configured `binDir`, or a cache link to the installed platform executable. */
import { mkdtemp, readlink, rm, symlink, unlink } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { basename, dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest'
import { resolveCliDirectory } from '../src/directory.ts'
import { createBinDir } from './harness.ts'
const PLATFORM_EXECUTABLES: Readonly<Partial<Record<string, string>>> = {
'darwin-arm64': 'tmeet-macOS-AppleSilicon',
'darwin-x64': 'tmeet-macOS-Intel',
'linux-arm64': 'tmeet-Linux-ARM64',
'linux-x64': 'tmeet-Linux-x86_64',
}
const executable = PLATFORM_EXECUTABLES[`${process.platform}-${process.arch}`]
const PACKAGE_DIST = join(dirname(fileURLToPath(import.meta.resolve('@tencentcloud/tmeet/package.json'))), 'dist')
let home: string
beforeEach(async () => {
home = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-home-'))
vi.stubEnv('DSH_HOME', home)
})
afterEach(async () => {
vi.unstubAllEnvs()
await rm(home, { recursive: true, force: true })
})
it.runIf(executable !== undefined)('links the installed platform executable as tmeet in a cache directory and relinks it on every load', async () => {
const directory = resolveCliDirectory(undefined)
expect(dirname(directory)).toBe(join(home, 'cache', 'tencent-meeting'))
expect(basename(directory)).toMatch(/^[0-9a-f]{16}$/u)
expect(await readlink(join(directory, 'tmeet'))).toBe(join(PACKAGE_DIST, executable!))
await unlink(join(directory, 'tmeet'))
await symlink('/nonexistent/tmeet', join(directory, 'tmeet'))
expect(resolveCliDirectory(undefined)).toBe(directory)
expect(await readlink(join(directory, 'tmeet'))).toBe(join(PACKAGE_DIST, executable!))
})
it('names a platform the package ships no executable for', () => {
const arch = Object.getOwnPropertyDescriptor(process, 'arch')!
Object.defineProperty(process, 'arch', { ...arch, value: 'fixture-arch' })
onTestFinished(() => { Object.defineProperty(process, 'arch', arch) })
expect(() => resolveCliDirectory(undefined))
.toThrow(`tencent-meeting: @tencentcloud/tmeet has no executable for ${process.platform}-fixture-arch; set binDir`)
})
it('accepts a configured directory and names its missing executable with the remedy', async () => {
const binDir = await createBinDir()
onTestFinished(() => rm(binDir, { recursive: true, force: true }))
expect(resolveCliDirectory(binDir)).toBe(binDir)
expect(() => resolveCliDirectory(home))
.toThrow(`tencent-meeting: ${join(home, 'tmeet')} is not executable; set binDir to a directory containing an executable tmeet`)
})
@@ -0,0 +1,132 @@
/** Scripted tmeet processes and a temporary bin directory for Tencent Meeting plugin specs. */
import { chmod, mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { PassThrough } from 'node:stream'
import { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'
import type {
SubprocessCollectedOutputs,
SubprocessHandle,
SubprocessOutcome,
SubprocessSpawnSpec,
SubprocessTerminalEnvironment,
} from '@deepseek-ai/dsh-subprocess'
/** Output and exit facts one scripted command reports. */
export interface CliReply {
stdout?: string
stderr?: string
exitCode?: number | null
signal?: NodeJS.Signals | null
}
/** A piped process whose managed range exits on termination unless held. */
export class ScriptedProcess implements SubprocessHandle {
readonly stdin = undefined
readonly stdout = new PassThrough()
readonly stderr = new PassThrough()
readonly control = undefined
readonly collected: SubprocessCollectedOutputs = {}
readonly done: Promise<SubprocessOutcome>
terminated = false
holdExit = false
private readonly outcome = Promise.withResolvers<SubprocessOutcome>()
private readonly exit = Promise.withResolvers<boolean>()
constructor(readonly spec: SubprocessSpawnSpec) {
this.done = this.outcome.promise
spec.signal?.addEventListener('abort', () => { this.terminate() }, { once: true })
}
/** Write output while the command keeps running. */
write(stream: 'stdout' | 'stderr', text: string): void {
this[stream].write(text)
}
/** Finish the command with the given output; the managed range stays alive until termination. */
reply(reply: CliReply): void {
if (reply.stdout !== undefined) this.stdout.write(reply.stdout)
if (reply.stderr !== undefined) this.stderr.write(reply.stderr)
this.close()
this.outcome.resolve({ exitCode: reply.exitCode === undefined ? 0 : reply.exitCode, signal: reply.signal ?? null })
}
terminate(): void {
this.terminated = true
this.close()
this.outcome.resolve({ exitCode: null, signal: 'SIGTERM' })
if (!this.holdExit) this.exit.resolve(true)
}
private close(): void {
if (!this.stdout.writableEnded) this.stdout.end()
if (!this.stderr.writableEnded) this.stderr.end()
}
/** Empty a held managed range. */
release(): void {
this.exit.resolve(true)
}
waitForExit(): Promise<boolean> {
return this.exit.promise
}
}
/** Host subprocess runtime whose lookups and spawns are recorded and answered by `respond`. */
export class ScriptedSubprocess extends SubprocessRuntime {
readonly lookups: Array<{ command: string; env: Readonly<Record<string, string>> | undefined }> = []
readonly processes: ScriptedProcess[] = []
host = true
lookup: (signal?: AbortSignal) => Promise<string> = () => Promise.resolve('/fixture/bin/tmeet')
respond: (process: ScriptedProcess) => void | Promise<void> = (process) => { process.reply({ stdout: '{}' }) }
override get runsOnHost(): boolean {
return this.host
}
override resolveExecutable(command: string, env?: Readonly<Record<string, string>>, signal?: AbortSignal): Promise<string> {
this.lookups.push({ command, env })
return this.lookup(signal)
}
override terminalEnvironment(): Promise<SubprocessTerminalEnvironment> {
return Promise.resolve({ platform: 'posix' })
}
override spawn(spec: SubprocessSpawnSpec): ScriptedProcess {
spec.signal?.throwIfAborted()
const process = new ScriptedProcess(spec)
this.processes.push(process)
queueMicrotask(() => { void this.respond(process) })
return process
}
override spawnTerminal(): Promise<never> {
throw new Error('tmeet commands never allocate a terminal')
}
}
/**
* Answer each command by its arguments after the executable.
* @param replies - reply per space-joined argument list.
* @returns a `respond` function that fails unknown commands.
*/
export function byArguments(replies: Record<string, CliReply>): (process: ScriptedProcess) => void {
return (process) => {
const reply = replies[process.spec.argv.slice(1).join(' ')]
process.reply(reply ?? { exitCode: 1, stderr: `unexpected command: ${process.spec.argv.join(' ')}` })
}
}
/**
* Create a temporary directory holding an executable `tmeet` placeholder.
* @returns the absolute bin directory.
*/
export async function createBinDir(): Promise<string> {
const directory = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-bin-'))
await writeFile(join(directory, 'tmeet'), '')
await chmod(join(directory, 'tmeet'), 0o755)
return directory
}
@@ -0,0 +1,60 @@
import { rm } from 'node:fs/promises'
import { Context } from '@deepseek-ai/cordis'
import SkillRegistry from '@deepseek-ai/dsh-skill'
import * as ShellEnv from '@deepseek-ai/dsh-shell-env'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import TencentMeeting from '../src/index.ts'
import { createBinDir, ScriptedSubprocess } from './harness.ts'
const CONFIG = { commandTimeoutMs: 5_000 }
describe('Tencent Meeting plugin', () => {
let ctx: Context
let subprocess: ScriptedSubprocess
let binDir: string
beforeEach(async () => {
ctx = new Context()
await ctx.plugin(SkillRegistry)
await ctx.plugin(ScriptedSubprocess)
await ctx.plugin(ShellEnv)
subprocess = ctx.subprocess as ScriptedSubprocess
subprocess.respond = (process) => { process.reply({ stdout: 'Not logged in. Please use \'tmeet auth login\' to authenticate.\n' }) }
binDir = await createBinDir()
})
afterEach(async () => {
await ctx.fiber.dispose()
await rm(binDir, { recursive: true, force: true })
})
it('publishes one tencent-meeting entry skill whose body carries the DSH guidance', async () => {
await ctx.plugin(TencentMeeting, { ...CONFIG, binDir })
const catalog = await ctx.skills.list()
expect(catalog.map(skill => `${skill.provider}/${skill.source}/${skill.name}`)).toEqual(['tencent-meeting/bundled/tencent-meeting'])
const entry = await ctx.skills.get('tencent-meeting')
expect(entry?.content).toContain('`tmeet` 由腾讯会议插件安装并加入 Host Shell 的 PATH')
expect(entry?.content).toContain('跳过运行 `scripts/agent_init.py` 的要求')
expect(await ctx.skills.get('tmeet-skill')).toBeUndefined()
})
it('refuses to load without a Host subprocess runtime', () => {
subprocess.host = false
expect(() => new TencentMeeting(ctx, { ...CONFIG, binDir })).toThrow('tencent-meeting: tmeet and its default sign-in are local to this Host')
expect(ctx.shellEnv.getPathPrefix(ctx.subprocess)).toBeUndefined()
})
it('withdraws the private PATH and skills on disposal', async () => {
const fiber = await ctx.plugin(TencentMeeting, { ...CONFIG, binDir })
expect(ctx.shellEnv.getPathPrefix(ctx.subprocess)).toBe(binDir)
expect(await ctx.skills.list()).not.toEqual([])
await fiber.dispose()
expect(ctx.shellEnv.getPathPrefix(ctx.subprocess)).toBeUndefined()
expect(await ctx.skills.list()).toEqual([])
})
})
@@ -0,0 +1,37 @@
/** The bundled entry skill: its index names exactly the upstream guides, and it reaches the model below the pruner threshold. */
import { readdirSync, readFileSync, statSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { renderSkillContent } from '@deepseek-ai/dsh-skill'
import { expect, it } from 'vitest'
const entry = fileURLToPath(new URL('../skills/tencent-meeting/', import.meta.url))
const guides = join(entry, 'guides')
/**
* `packages/bundle/web-app/presets/standard.patch.yml` prunes a tool result only above `thresholdChars: 8192`
* code points; a skill result below it reaches the model intact.
*/
const PRUNER_THRESHOLD_CHARS = 8192
/** The body the `skill` tool returns: the file without its YAML frontmatter. */
function body(): string {
const text = readFileSync(join(entry, 'SKILL.md'), 'utf8')
const end = text.indexOf('\n---\n', 4)
return text.slice(end + '\n---\n'.length)
}
it('ships only the tencent-meeting entry at the bundled skill root', () => {
expect(readdirSync(fileURLToPath(new URL('../skills/', import.meta.url)))).toEqual(['tencent-meeting'])
})
it('renders the entry below the pruner threshold', () => {
const rendered = renderSkillContent({ name: 'tencent-meeting', provider: 'tencent-meeting', resourceBase: { kind: 'directory', path: entry }, content: body() })
expect(Array.from(rendered).length).toBeLessThan(PRUNER_THRESHOLD_CHARS)
})
it('indexes every upstream guide exactly once, and each indexed guide exists', () => {
const indexed = [...body().matchAll(/^- `([a-z-]+)`:/gmu)].map(match => match[1] ?? '')
expect(indexed.toSorted()).toEqual(readdirSync(guides).toSorted())
for (const name of indexed) expect(() => statSync(join(guides, name, 'SKILL.md')), name).not.toThrow()
})