From 7ec0de79d6efdb2a3ed540a63c07d73bf4a001d1 Mon Sep 17 00:00:00 2001 From: gengruilin Date: Wed, 14 Oct 2026 19:14:33 +0800 Subject: [PATCH] fix(feishu): offer the first trusted setup link and keep the account rules in FeishuAccount An untrusted HTTPS line printed before the setup link no longer uses up the single offer. FeishuAccount now owns its cancellable phases, trusted hosts, and failure classifier, so the specs exercise the shipped rules; generic runner and runtime cases moved to the CLI account kit. --- packages/connector/feishu-cli/src/account.ts | 25 +++- packages/connector/feishu-cli/src/cli.ts | 9 ++ packages/connector/feishu-cli/src/index.ts | 15 +- packages/connector/feishu-cli/src/types.ts | 3 + .../feishu-cli/tests/account.spec.ts | 124 ++++++---------- .../connector/feishu-cli/tests/cli.spec.ts | 135 +++--------------- .../connector/feishu-cli/tests/plugin.spec.ts | 2 +- 7 files changed, 103 insertions(+), 210 deletions(-) diff --git a/packages/connector/feishu-cli/src/account.ts b/packages/connector/feishu-cli/src/account.ts index eec2d4b110..d8af1c66f4 100644 --- a/packages/connector/feishu-cli/src/account.ts +++ b/packages/connector/feishu-cli/src/account.ts @@ -1,10 +1,12 @@ /** Host-owned check, connection, and sign-out of the CLI's default Feishu account. */ +import type { Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' import z from 'zod' -import { CliAccountRuntime, type CliOperationControl } from '@deepseek-ai/dsh-cli-account' +import { CliAccountRuntime, type CliCommandExecutor, type CliOperationControl } from '@deepseek-ai/dsh-cli-account' import { assertNever } from '@deepseek-ai/dsh-util-values' import { parseJson } from './cli.ts' +import { commandFailure } from './diagnostic.ts' import type { FeishuAccountState, FeishuAppId, FeishuOperationFailure, FeishuOperationKind, FeishuPhase } from './types.ts' const NotConfigured = z.object({ ok: z.literal(false), error: z.object({ subtype: z.literal('not_configured') }) }) @@ -27,6 +29,23 @@ interface Check { account: FeishuAccountState; openId?: string | undefined } /** Runs at most one account operation at a time; subscribers observe it without owning it. */ export class FeishuAccount extends CliAccountRuntime { + /** + * @param cli - the lark-cli executor the account runs commands with and disposes. + * @param logger - receives classified operation failures. + */ + constructor(cli: CliCommandExecutor, logger: Context['logger']) { + super({ + name: 'feishu', + cli, + logger, + account: { state: 'unchecked' }, + check: 'check', + cancellable: ['configuring', 'authorizing'], + authorizationHosts: ['feishu.cn', 'larksuite.com'], + classify: commandFailure, + }) + } + protected async perform(kind: FeishuOperationKind, control: Control, signal: AbortSignal): Promise { switch (kind) { case 'check': @@ -57,9 +76,7 @@ export class FeishuAccount extends CliAccountRuntime { const link = stream === 'stderr' && !offered ? CONFIG_LINK.exec(line) : null - if (link === null) return - offered = true - control.offer(link[1] as string) + if (link !== null) offered = control.offer(link[1] as string) }, }) if (setup.exitCode !== 0) throw new Error('feishu: config init failed') diff --git a/packages/connector/feishu-cli/src/cli.ts b/packages/connector/feishu-cli/src/cli.ts index 2d5fe4957a..9ef7581c6f 100644 --- a/packages/connector/feishu-cli/src/cli.ts +++ b/packages/connector/feishu-cli/src/cli.ts @@ -5,6 +5,7 @@ import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import type { CliCommandExecutor } from '@deepseek-ai/dsh-cli-account' +/** The executable name the plugin resolves on its private PATH. */ export const PROGRAM = 'lark-cli' /** @@ -43,6 +44,14 @@ export function parseJson(args: readonly string[], stdout: string): unknown { } } +/** + * Run one command and parse its JSON stdout. + * @param cli - the plugin's lark-cli executor. + * @param args - native arguments without the executable. + * @param signal - the caller's lifetime. + * @returns unvalidated JSON for the caller to check. + * @throws when the command fails, exits nonzero, or prints invalid JSON. + */ export async function runJson(cli: CliCommandExecutor, args: readonly string[], signal: AbortSignal): Promise { const result = await cli.run(args, signal) if (result.exitCode !== 0) { diff --git a/packages/connector/feishu-cli/src/index.ts b/packages/connector/feishu-cli/src/index.ts index 8c7d9d071b..08b47632b3 100644 --- a/packages/connector/feishu-cli/src/index.ts +++ b/packages/connector/feishu-cli/src/index.ts @@ -14,7 +14,6 @@ import type {} from '@deepseek-ai/dsh-skill' import type {} from '@deepseek-ai/dsh-subprocess' import { FeishuAccount } from './account.ts' import { PROGRAM, resolveCliDirectory } from './cli.ts' -import { commandFailure } from './diagnostic.ts' import { FeishuSkillProvider } from './skills.ts' import type { FeishuState } from './types.ts' @@ -27,6 +26,7 @@ declare module '@deepseek-ai/cordis' { } } +/** Where lark-cli is and how long a command that does not wait for the user may run. */ export type Config = CliAccountConfig /** Registers the CLI and skills, and owns the account operations the Plugins page drives. */ @@ -38,7 +38,7 @@ export default class Feishu extends TypertRemoteService { /** * @param ctx - Context carrying the skill registry, subprocess runtime, and Shell environment. - * @param config - CLI location and command limits. + * @param config - CLI location and command deadline. * @throws when the subprocess runtime does not run on this Host or `lark-cli` is not executable. */ constructor(ctx: Context, config: Config) { @@ -48,16 +48,7 @@ export default class Feishu extends TypertRemoteService { } ctx.shellEnv.registerPath({ name: 'feishu', directories: [resolveCliDirectory(config.binDir)] }) const cli = new CliCommandExecutor(ctx.subprocess, ctx.shellEnv, { program: PROGRAM, commandTimeoutMs: config.commandTimeoutMs }) - this.account = new FeishuAccount({ - name: 'feishu', - cli, - logger: ctx.logger, - account: { state: 'unchecked' }, - check: 'check', - cancellable: ['configuring', 'authorizing'], - authorizationHosts: ['feishu.cn', 'larksuite.com'], - classify: commandFailure, - }) + this.account = new FeishuAccount(cli, ctx.logger) ctx.effect(() => () => this.account.dispose()) ctx.skills.registerProvider(control => new FeishuSkillProvider(cli, control, ctx.logger)) } diff --git a/packages/connector/feishu-cli/src/types.ts b/packages/connector/feishu-cli/src/types.ts index a8b1ed0e62..4c03eab572 100644 --- a/packages/connector/feishu-cli/src/types.ts +++ b/packages/connector/feishu-cli/src/types.ts @@ -12,8 +12,10 @@ export type FeishuAccountState = | { readonly state: 'signed-out' | 'unverified'; readonly appId: FeishuAppId } | { readonly state: 'connected'; readonly appId: FeishuAppId; readonly userName?: string } +/** The account operations the Plugins page starts. */ export type FeishuOperationKind = 'check' | 'link-app' | 'sign-in' | 'sign-out' +/** Feishu steps of an operation, besides the runtime's `checking` and `cancelling`. */ export type FeishuPhase = 'configuring' | 'authorizing' | 'verifying' | 'signing-out' /** Safe account-command diagnostics; native messages, paths, and credentials are excluded. */ @@ -24,4 +26,5 @@ export interface FeishuOperationFailure extends CliCommandFailure<'config-init' readonly subtype?: 'sdk_error' | 'storage' | 'file_io' | 'not_configured' | 'invalid_config' | 'invalid_client' } +/** The complete Feishu view a Remote client replaces on every change. */ export type FeishuState = CliAccountView diff --git a/packages/connector/feishu-cli/tests/account.spec.ts b/packages/connector/feishu-cli/tests/account.spec.ts index bc98bc1664..98e465ace8 100644 --- a/packages/connector/feishu-cli/tests/account.spec.ts +++ b/packages/connector/feishu-cli/tests/account.spec.ts @@ -1,15 +1,15 @@ /** Account operations over a scripted lark-cli: checks, app linking, 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 { FeishuAccount } from '../src/account.ts' -import { FeishuCli } from '../src/cli.ts' -import Feishu, { type FeishuAppId, type FeishuOperationId, type FeishuState } from '../src/index.ts' +import { PROGRAM } from '../src/cli.ts' +import Feishu, { type FeishuAppId, type FeishuState } from '../src/index.ts' import { createBinDir, ScriptedSubprocess, type CliReply, type ScriptedProcess } from './harness.ts' -const LIMITS = { commandTimeoutMs: 5_000, authorizationTimeoutMs: 5_000, maxOutputBytes: 1_048_576 } const APP = 'cli_a' as FeishuAppId const STATUS = 'auth status --verify --json' const NOT_CONFIGURED: CliReply = { exitCode: 3, stderr: JSON.stringify({ ok: false, error: { type: 'config', subtype: 'not_configured', message: 'not configured' } }) } @@ -52,15 +52,16 @@ const errors = (): unknown[] => ctx.logger.buffer.filter(message => message.type describe('FeishuAccount', () => { let account: FeishuAccount - let changes: number beforeEach(() => { - ctx.shellEnv.registerPath({ name: 'feishu', directories: [binDir] }) - changes = 0 - account = new FeishuAccount(new FeishuCli(ctx.subprocess, ctx.shellEnv, LIMITS), LIMITS, () => { changes++ }, ctx.logger) + ctx.shellEnv.registerPath({ name: 'feishu', directories: [binDir], programs: [PROGRAM] }) + const cli = new CliCommandExecutor(ctx.subprocess, ctx.shellEnv, { program: PROGRAM, commandTimeoutMs: 5_000 }) + account = new FeishuAccount(cli, ctx.logger) }) - const settled = async (id: FeishuOperationId): Promise => { + afterEach(() => account.dispose()) + + const settled = async (id: CliOperationId): Promise => { await vi.waitFor(() => { expect(account.snapshot().result?.id).toBe(id) }) return account.snapshot() } @@ -75,9 +76,8 @@ describe('FeishuAccount', () => { ])('checks %s', async (_name, reply, expected) => { script[STATUS] = [reply] const id = account.start('check') - expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'checking' }) + 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' } }) - expect(changes).toBeGreaterThan(0) }) it.each<[string, CliReply]>([ @@ -88,13 +88,14 @@ describe('FeishuAccount', () => { expect(await settled(account.start('check'))).toMatchObject({ account: { state: 'unchecked' }, result: { outcome: 'failed' } }) }) - it('links an app through its setup page, offers only a trusted link, and stops before sign-in', async () => { + it('links an app through its setup page, offers only the first trusted link, and stops before sign-in', async () => { script[STATUS] = [SIGNED_OUT] const setup = Promise.withResolvers() script['config init --new'] = (process) => { setup.resolve(process) } const id = account.start('link-app') const configuring = await setup.promise + expect(account.snapshot().operation).toEqual({ id, kind: 'link-app', phase: 'configuring', cancellable: true }) configuring.write('stderr', 'Open this link:\n http://open.feishu.cn/page/cli?x=1\n https://evil.example/page\n') configuring.write('stderr', ' https://open.feishu.cn/page/cli?x=2\n https://open.feishu.cn/page/cli?x=3\n') await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'configuring', authorizationUrl: 'https://open.feishu.cn/page/cli?x=2' }) }) @@ -134,13 +135,6 @@ describe('FeishuAccount', () => { } }) }) - it('reports an attempted command without forwarding an execution exception', async () => { - subprocess.lookup = () => Promise.reject(new Error('private-exception-token')) - const result = await settled(account.start('check')) - expect(result).toMatchObject({ result: { outcome: 'failed', failure: { command: 'auth-status', exitCode: null } } }) - expect(JSON.stringify({ result, errors: errors() })).not.toContain('private-exception-token') - }) - it('retains the observed exit code when the command response is invalid', async () => { script[STATUS] = [{ stdout: 'invalid-json-secret' }] const result = await settled(account.start('check')) @@ -154,7 +148,7 @@ describe('FeishuAccount', () => { script['auth login --json'] = (process) => { signIn.resolve(process) } const id = account.start('sign-in') - expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'authorizing' }) + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'authorizing', cancellable: true }) const authorizing = await signIn.promise const invalid = JSON.stringify({ event: 'device_authorization', verification_uri_complete: 'not a url' }) authorizing.write('stdout', `progress\n{"event":"other"}\n${invalid}\n${LOGIN_LINK}\n`) @@ -181,93 +175,61 @@ describe('FeishuAccount', () => { expect((await settled(account.start(kind))).result).toMatchObject({ kind, outcome: 'failed' }) }) - it('cancels only the named operation, withdraws its link, and ignores later output', async () => { - script[STATUS] = [SIGNED_OUT] - const signIn = Promise.withResolvers() - script['auth login --json'] = (process) => { process.write('stdout', LOGIN_LINK + '\n'); signIn.resolve(process) } - const id = account.start('sign-in') - await vi.waitFor(() => { expect(account.snapshot().operation?.authorizationUrl).toBeDefined() }) - await account.cancel('other' as FeishuOperationId) - expect(account.snapshot().operation?.phase).toBe('authorizing') - - const process = await signIn.promise - process.holdExit = true - const cancelling = account.cancel(id) - expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'cancelling' }) - process.write('stdout', LOGIN_LINK + '\n') - process.release() - await cancelling - expect(account.snapshot()).toEqual({ account: { state: 'unchecked' }, result: { id, kind: 'sign-in', outcome: 'cancelled' } }) - expect(errors()).toEqual([]) - }) - - it('runs one operation at a time and refreshes only when idle', async () => { - const gate = Promise.withResolvers() - script[STATUS] = (process) => { gate.resolve(process) } - const id = account.start('check') - expect(() => account.start('sign-in')).toThrow('another account operation is in progress') - account.refresh() - expect(subprocess.processes).toHaveLength(0) - ;(await gate.promise).reply(CONNECTED) - await settled(id) - script[STATUS] = [CONNECTED] - account.refresh() - await vi.waitFor(() => { expect(commands()).toEqual([STATUS, STATUS]) }) - }) - - it('signs out and reports a rejected sign-out', async () => { + it('signs out without offering cancellation and reports a rejected sign-out', async () => { script[STATUS] = [SIGNED_OUT] script['auth logout --json'] = [{ stdout: '{"ok":true}' }, { exitCode: 1 }] const id = account.start('sign-out') - expect(account.snapshot().operation?.phase).toBe('signing-out') + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-out', phase: 'signing-out', cancellable: false }) expect(await settled(id)).toEqual({ account: { state: 'signed-out', appId: APP }, result: { id, kind: 'sign-out', outcome: 'succeeded' } }) - expect((await settled(account.start('sign-out'))).result).toMatchObject({ kind: 'sign-out', outcome: 'failed' }) - }) - - it('cancels the active operation on disposal and refuses new work', async () => { - script[STATUS] = () => {} - account.start('check') - await vi.waitFor(() => { expect(subprocess.processes).toHaveLength(1) }) - await account.dispose() - expect(subprocess.processes[0]?.terminated).toBe(true) - expect(() => account.start('link-app')).toThrow('plugin disposed') - account.refresh() - await account.dispose() - expect(subprocess.processes).toHaveLength(1) + expect((await settled(account.start('sign-out'))).result).toMatchObject({ + kind: 'sign-out', outcome: 'failed', failure: { command: 'auth-logout', exitCode: 1 }, + }) }) }) describe('Feishu Remote', () => { beforeEach(async () => { - await ctx.plugin(Feishu, { ...LIMITS, binDir }) + await ctx.plugin(Feishu, { commandTimeoutMs: 5_000, binDir }) }) - it('checks for each new follower, streams each change, and starts checks, app links, sign-ins, and sign-outs', async () => { + it('checks for a new follower, streams each change, and starts checks, app links, sign-ins, and sign-outs', async () => { script[STATUS] = [SIGNED_OUT] + const states: FeishuState[] = [] const leave = new AbortController() - const seen: FeishuState[] = [] const following = (async () => { - for await (const state of ctx.feishu.follow(leave.signal)) { - seen.push(state) - if (state.result !== undefined) leave.abort() - } + for await (const state of ctx.feishu.follow(leave.signal)) states.push(state) })() - await following - expect(seen[0]).toMatchObject({ account: { state: 'unchecked' }, operation: { kind: 'check' } }) - expect(seen.at(-1)).toMatchObject({ account: { state: 'signed-out' }, result: { kind: 'check', outcome: 'succeeded' } }) + const finished = async (id?: CliOperationId): Promise => { + 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', appId: APP }) script['auth logout --json'] = [{ stdout: '{"ok":true}' }] const signingOut = ctx.feishu.signOut() expect(() => ctx.feishu.signIn()).toThrow('another account operation is in progress') await ctx.feishu.cancel(signingOut) - script[STATUS] = [SIGNED_OUT] - await ctx.feishu.cancel(ctx.feishu.check()) - await ctx.feishu.cancel(ctx.feishu.linkApp()) + expect(await finished(signingOut)).toMatchObject({ kind: 'sign-out', outcome: 'succeeded' }) + expect(await finished(ctx.feishu.check())).toMatchObject({ kind: 'check', outcome: 'succeeded' }) + + script['config init --new'] = () => {} + const linking = ctx.feishu.linkApp() + await vi.waitFor(() => { expect(commands().at(-1)).toBe('config init --new') }) + await ctx.feishu.cancel(linking) + expect(await finished(linking)).toMatchObject({ kind: 'link-app', outcome: 'cancelled' }) script['auth login --json'] = () => {} const signingIn = ctx.feishu.signIn() await vi.waitFor(() => { expect(commands().at(-1)).toBe('auth login --json') }) await ctx.feishu.cancel(signingIn) + expect(await finished(signingIn)).toMatchObject({ kind: 'sign-in', outcome: 'cancelled' }) expect(subprocess.processes.at(-1)?.terminated).toBe(true) + leave.abort() + await following }) it('ends its streams and stops account work on disposal', async () => { diff --git a/packages/connector/feishu-cli/tests/cli.spec.ts b/packages/connector/feishu-cli/tests/cli.spec.ts index 4479015d2b..f4797a467c 100644 --- a/packages/connector/feishu-cli/tests/cli.spec.ts +++ b/packages/connector/feishu-cli/tests/cli.spec.ts @@ -1,15 +1,12 @@ import { rm } from 'node:fs/promises' -import { homedir } from 'node:os' -import { delimiter } from 'node:path' import { Context } from '@deepseek-ai/cordis' +import { CliCommandExecutor } from '@deepseek-ai/dsh-cli-account' import * as ShellEnv from '@deepseek-ai/dsh-shell-env' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { FeishuCli } from '../src/cli.ts' -import { createBinDir, ScriptedSubprocess } from './harness.ts' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { parseJson, PROGRAM, runJson } from '../src/cli.ts' +import { createBinDir, ScriptedSubprocess, type CliReply } from './harness.ts' -const LIMITS = { commandTimeoutMs: 5_000, maxOutputBytes: 1024 } - -describe('FeishuCli', () => { +describe('lark-cli JSON commands', () => { let ctx: Context let subprocess: ScriptedSubprocess let binDir: string @@ -20,7 +17,7 @@ describe('FeishuCli', () => { await ctx.plugin(ShellEnv) subprocess = ctx.subprocess as ScriptedSubprocess binDir = await createBinDir() - ctx.shellEnv.registerPath({ name: 'feishu', directories: [binDir] }) + ctx.shellEnv.registerPath({ name: 'feishu', directories: [binDir], programs: [PROGRAM] }) }) afterEach(async () => { @@ -28,114 +25,28 @@ describe('FeishuCli', () => { await rm(binDir, { recursive: true, force: true }) }) - const cli = (limits = LIMITS) => new FeishuCli(ctx.subprocess, ctx.shellEnv, limits) + const json = (reply: CliReply) => { + subprocess.respond = (process) => { process.reply(reply) } + const cli = new CliCommandExecutor(ctx.subprocess, ctx.shellEnv, { program: PROGRAM, commandTimeoutMs: 5_000 }) + return runJson(cli, ['skills', 'list', '--json'], AbortSignal.timeout(5_000)) + } - it('finds lark-cli on the prepared private PATH, spawns it with that environment, and parses stdout', async () => { - subprocess.respond = (process) => { process.reply({ stdout: '{"ok":\ntrue}\n' }) } - - await expect(cli().json(['skills', 'list', '--json'], AbortSignal.timeout(5_000))).resolves.toEqual({ ok: true }) - - const [lookup] = subprocess.lookups - expect(lookup?.command).toBe('lark-cli') - expect(lookup?.env?.PATH?.split(delimiter)[0]).toBe(binDir) - const [process] = subprocess.processes - expect(process?.spec).toMatchObject({ - argv: ['/fixture/bin/lark-cli', 'skills', 'list', '--json'], - cwd: homedir(), - stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' }, - }) - expect(process?.spec.env).toBe(lookup?.env) - expect(process?.terminated).toBe(true) + it('runs lark-cli and parses its stdout', async () => { + await expect(json({ stdout: '{"ok":\ntrue}\n' })).resolves.toEqual({ ok: true }) + expect(subprocess.lookups.map(lookup => lookup.command)).toEqual(['lark-cli']) + expect(subprocess.processes[0]?.spec.argv).toEqual(['/fixture/bin/lark-cli', 'skills', 'list', '--json']) }) it.each([ - [{ exitCode: 2, stderr: ' {"ok":false} \n' }, 'lark-cli skills list exited with 2: {"ok":false}'], - [{ exitCode: 1 }, /^lark-cli skills list exited with 1$/u], - [{ exitCode: null, signal: 'SIGKILL' as const }, 'lark-cli skills list exited with SIGKILL'], - [{ stdout: 'x'.repeat(1025) }, 'lark-cli skills list output exceeded 1024 bytes'], - [{ stdout: 'not json' }, 'lark-cli skills list returned invalid JSON'], - ])('rejects a failed command %#', async (reply, message) => { - subprocess.respond = (process) => { process.reply(reply) } - - await expect(cli().json(['skills', 'list'], AbortSignal.timeout(5_000))).rejects.toThrow(message) + [{ exitCode: 2, stderr: ' {"ok":false} \n' }, 'lark-cli skills list --json exited with 2: {"ok":false}'], + [{ exitCode: 1 }, /^lark-cli skills list --json exited with 1$/u], + [{ stdout: 'not json' }, 'lark-cli skills list --json returned invalid JSON'], + ])('names the command that failed %#', async (reply, message) => { + await expect(json(reply)).rejects.toThrow(message) }) - it('keeps draining stdout after it exceeds the limit', async () => { - subprocess.respond = async (process) => { - process.write('stdout', 'x'.repeat(1025)) - await vi.waitFor(() => { expect(process.stdout.readableLength).toBe(0) }) - process.reply({ stdout: 'y' }) - } - - await expect(cli().json(['skills', 'list'], AbortSignal.timeout(5_000))).rejects.toThrow('lark-cli skills list output exceeded 1024 bytes') - }) - - it('reports output lines while the command runs and returns a nonzero exit to the caller', async () => { - const lines: string[] = [] - subprocess.respond = (process) => { - process.write('stderr', 'Open this link:\r\n https://open.feishu.cn/page/cli?code=1\npart') - process.write('stdout', '{"event":"one"}\n') - process.reply({ stdout: '{"event":"two"}', stderr: 'ial\n' + 'e'.repeat(5000), exitCode: 3 }) - } - - const result = await cli().run(['auth', 'login', '--json'], AbortSignal.timeout(5_000), { - timeoutMs: 5_000, onLine: (stream, line) => { lines.push(`${stream}:${line.slice(0, 40)}`) }, - }) - - expect(result.exitCode).toBe(3) - expect(result.stdout).toBe('{"event":"one"}\n{"event":"two"}') - expect(result.stderr).toHaveLength(4096) - // Each stream keeps its own order; the two pipes interleave in any order. - expect(lines.filter(line => line.startsWith('stdout:'))).toEqual(['stdout:{"event":"one"}', 'stdout:{"event":"two"}']) - expect(lines.filter(line => line.startsWith('stderr:'))).toEqual([ - 'stderr:Open this link:', 'stderr: https://open.feishu.cn/page/cli?code=1', 'stderr:partial', `stderr:${'e'.repeat(40)}`, - ]) - }) - - it.each(['lookup', 'process'] as const)('applies the command deadline during %s', async (phase) => { - if (phase === 'lookup') { - subprocess.lookup = signal => new Promise((_resolve, reject) => { - signal?.addEventListener('abort', () => { reject(signal.reason instanceof Error ? signal.reason : new Error('lookup aborted')) }, { once: true }) - }) - } else { - subprocess.respond = () => {} - } - - await expect(cli({ ...LIMITS, commandTimeoutMs: 20 }).json(['skills', 'list'], new AbortController().signal)) - .rejects.toThrow('lark-cli skills list timed out after 20ms') - expect(subprocess.processes.map(process => process.terminated)).toEqual(phase === 'lookup' ? [] : [true]) - }) - - it('keeps a caller deadline reason instead of reporting the command deadline', async () => { - subprocess.respond = () => {} - - await expect(cli().json(['skills', 'list'], AbortSignal.timeout(20))).rejects.toThrow(expect.objectContaining({ name: 'TimeoutError' })) - }) - - it('terminates the process and rejects with the caller reason on cancellation', async () => { - const caller = new AbortController() - subprocess.respond = () => { caller.abort(new Error('caller left')) } - - await expect(cli().json(['skills', 'read', 'lark-doc'], caller.signal)).rejects.toThrow('caller left') - expect(subprocess.processes[0]?.terminated).toBe(true) - }) - - it('settles disposal only after owned processes exit and refuses later commands', async () => { - subprocess.respond = (process) => { process.holdExit = true } - const owner = cli() - const pending = owner.json(['skills', 'list'], new AbortController().signal) - const rejected = expect(pending).rejects.toThrow('plugin disposed') - await vi.waitFor(() => { expect(subprocess.processes).toHaveLength(1) }) - - let disposed = false - const disposal = owner.dispose().then(() => { disposed = true }) - await vi.waitFor(() => { expect(subprocess.processes[0]?.terminated).toBe(true) }) - expect(disposed).toBe(false) - - subprocess.processes[0]?.release() - await disposal - await rejected - await expect(owner.json(['skills', 'list'], new AbortController().signal)).rejects.toThrow('plugin disposed') - expect(subprocess.processes).toHaveLength(1) + it('parses JSON a caller read from another stream', () => { + expect(parseJson(['auth', 'status'], '{"ok":false}')).toEqual({ ok: false }) + expect(() => parseJson(['auth', 'status'], '')).toThrow('lark-cli auth status returned invalid JSON') }) }) diff --git a/packages/connector/feishu-cli/tests/plugin.spec.ts b/packages/connector/feishu-cli/tests/plugin.spec.ts index 3281f93674..3a8450adea 100644 --- a/packages/connector/feishu-cli/tests/plugin.spec.ts +++ b/packages/connector/feishu-cli/tests/plugin.spec.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import Feishu from '../src/index.ts' import { byArguments, CATALOG, createBinDir, DOC_SKILL, ScriptedSubprocess } from './harness.ts' -const CONFIG = { commandTimeoutMs: 5_000, authorizationTimeoutMs: 5_000, maxOutputBytes: 1_048_576 } +const CONFIG = { commandTimeoutMs: 5_000 } const LIST = 'skills list --json' const READ = 'skills read lark-doc --json'