qwen-code/packages/cli/src/nonInteractiveCliCommands.test.ts
jinye a3c8986e59 docs(serve): v0.16-alpha known limits + SDK QWEN_SERVER_TOKEN env fallback (PR 27) (#4473)
* docs(serve): v0.16-alpha known limits + SDK QWEN_SERVER_TOKEN env fallback (PR 27)

First PR in the F5 release chain (PR 27 → 28 → 30a → 31) per the
2026-05-24 v0.16-alpha scope freeze in #4175 (text-only chat / coding
+ local-only deployment).

## SDK ergonomic micro-change (~50 LOC + 4 tests)

`DaemonClient` constructor falls back to `QWEN_SERVER_TOKEN` env
var when `opts.token` is absent — closes the asymmetry where the
daemon side already honors this var (--token CLI flag fallback,
already in main since PR 15) but the SDK forced clients to thread
it through every construction.

Properties:
- Browser-safe via `globalThis.process` indirection (the SDK is
  imported by @qwen-code/webui; literal process.env access would
  explode at module load on browser bundles)
- Whitespace stripped (matches daemon-side trim — handy for
  `export QWEN_SERVER_TOKEN=\"\$(cat token.txt)\"` where cat adds a
  trailing newline)
- Empty / whitespace-only treated as unset (a stale
  `export QWEN_SERVER_TOKEN=\"\"` won't accidentally send
  Authorization: Bearer with no token)
- Resolved at construction, not lazily per-request (later
  process.env mutations don't affect already-built clients)
- Explicit opts.token wins over env

Tests: 4 new in DaemonClient.test.ts `bearer auth` describe
covering env fallback / explicit-wins / empty-treated-unset /
whitespace-stripped. Plus a defensive snapshot/restore on the
existing 'omits Authorization when no token' test so an
inherited test-runner export of QWEN_SERVER_TOKEN doesn't turn
that assertion into a false positive.

This SDK fallback is the entire ergonomic replacement for PR 29's
SDK env/file fallback. PR 29's other features (auto-gen daemon
token, instance-path keying, stale cleanup) remain deferred to
v0.16.x — all are DX improvements over the boot-time security gate
already shipped in PR 15.

## v0.16-alpha docs (~120 LOC markdown)

- docs/users/qwen-serve.md: new "v0.16-alpha known limits" section
  enumerating product surface (text-only ✅, multimodal ❌),
  deployment surface (local launchers ✅, containerized ❌, multi-
  daemon ❌, BYO-token ✅), and hardening posture (boot security
  gate ✅, mutation gate ✅, MCP guardrails ✅, prompt absolute
  deadline ⏸️, rate limiting ⏸️, --max-body-size ⏸️). Adds an
  alpha banner at the top of the file.

- docs/developers/examples/daemon-client-quickstart.md:
  documents the SDK env fallback in both the Hello-daemon
  intro and the Authentication section, with the "export +
  no-token-arg" recommended path called out for local dev.

Verification: 125/125 DaemonClient.test.ts pass (121 existing +
4 new); 4/4 daemon-public-surface.test.ts pass (constructor
signature unchanged); tsc clean on packages/sdk-typescript;
eslint --max-warnings 0 clean on touched .ts files.

Part of #4175.

* fix(sdk): #4473 round 1 fold-in — 2 copilot doc threads adopted

T1 [copilot DaemonClient.ts:144 — stale line refs in readTokenFromEnv
  JSDoc]: removed `runQwenServe.ts:175` (token resolution actually
  lives at line 302-318 today, would drift again on next refactor)
  and `docs/users/qwen-serve.md:173`. Replaced with stable
  symbol/section references ("runQwenServe token-resolution path";
  "qwen-serve user guide CLI flags section").

T2 [copilot daemon-client-quickstart.md:33 — `~/.qwen/server-token`
  implies built-in path that doesn't exist]: PR 27 explicitly defers
  token auto-generation + file-store fallback (PR 29 deferred features).
  The example incorrectly suggested a standard file location.
  Replaced with two explicit user-managed alternatives:
  - `openssl rand -hex 32` one-shot
  - `cat ./my-token-file` user-managed file

Both threads were accurate suggestions caught at the right time
(zero behavior change; pure docstring/example accuracy).

Verification: 125/125 DaemonClient tests pass; tsc + eslint clean
on touched files.
2026-05-27 10:31:34 +08:00

524 lines
15 KiB
TypeScript

/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
getAvailableCommands,
handleSlashCommand,
} from './nonInteractiveCliCommands.js';
import {
__resetActiveGoalStoreForTests,
type Config,
} from '@qwen-code/qwen-code-core';
import type { LoadedSettings } from './config/settings.js';
import { CommandKind, type ExecutionMode } from './ui/commands/types.js';
import { filterCommandsForMode } from './services/commandUtils.js';
import { goalCommand } from './ui/commands/goalCommand.js';
// Mock the CommandService
const mockGetCommands = vi.hoisted(() => vi.fn());
const mockGetCommandsForMode = vi.hoisted(() => vi.fn());
const mockGetModelInvocableCommands = vi.hoisted(() => vi.fn());
const mockCommandServiceCreate = vi.hoisted(() => vi.fn());
vi.mock('./services/CommandService.js', () => ({
CommandService: {
create: mockCommandServiceCreate,
},
}));
describe('handleSlashCommand', () => {
let mockConfig: Config;
let mockSettings: LoadedSettings;
let abortController: AbortController;
beforeEach(() => {
vi.clearAllMocks();
__resetActiveGoalStoreForTests();
// getCommandsForMode applies real mode filtering on top of getCommands()
mockGetCommandsForMode.mockImplementation((mode: ExecutionMode) =>
filterCommandsForMode(mockGetCommands(), mode),
);
mockGetModelInvocableCommands.mockImplementation(() =>
mockGetCommands().filter(
(command: { modelInvocable?: boolean; hidden?: boolean }) =>
!command.hidden && command.modelInvocable === true,
),
);
mockCommandServiceCreate.mockResolvedValue({
getCommands: mockGetCommands,
getCommandsForMode: mockGetCommandsForMode,
getModelInvocableCommands: mockGetModelInvocableCommands,
});
mockConfig = {
getExperimentalZedIntegration: vi.fn().mockReturnValue(false),
isInteractive: vi.fn().mockReturnValue(false),
getSessionId: vi.fn().mockReturnValue('test-session'),
getFolderTrustFeature: vi.fn().mockReturnValue(false),
getFolderTrust: vi.fn().mockReturnValue(false),
getProjectRoot: vi.fn().mockReturnValue('/test/project'),
isTrustedFolder: vi.fn().mockReturnValue(true),
getDisableAllHooks: vi.fn().mockReturnValue(false),
getHookSystem: vi.fn().mockReturnValue({
addFunctionHook: vi.fn().mockReturnValue('goal-hook-id'),
removeFunctionHook: vi.fn().mockReturnValue(true),
}),
setModelInvocableCommandsProvider: vi.fn(),
setModelInvocableCommandsExecutor: vi.fn(),
getDisabledSlashCommands: vi.fn().mockReturnValue([]),
storage: {},
} as unknown as Config;
mockSettings = {
system: { path: '', settings: {} },
systemDefaults: { path: '', settings: {} },
user: { path: '', settings: {} },
workspace: { path: '', settings: {} },
} as LoadedSettings;
abortController = new AbortController();
});
afterEach(() => {
__resetActiveGoalStoreForTests();
});
it('should return no_command for non-slash input', async () => {
const result = await handleSlashCommand(
'regular text',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('no_command');
});
it('should return no_command for unknown slash commands', async () => {
mockGetCommands.mockReturnValue([]);
const result = await handleSlashCommand(
'/unknowncommand',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('no_command');
});
it('should return unsupported for built-in commands without non-interactive supportedModes', async () => {
const mockHelpCommand = {
name: 'help',
description: 'Show help',
kind: CommandKind.BUILT_IN,
// No supportedModes → BUILT_IN fallback → interactive only
action: vi.fn(),
};
mockGetCommands.mockReturnValue([mockHelpCommand]);
const result = await handleSlashCommand(
'/help',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('unsupported');
if (result.type === 'unsupported') {
expect(result.reason).toContain('/help');
expect(result.reason).toContain('not supported');
}
});
it('should return unsupported for /help when using default allowed list', async () => {
const mockHelpCommand = {
name: 'help',
description: 'Show help',
kind: CommandKind.BUILT_IN,
action: vi.fn(),
};
mockGetCommands.mockReturnValue([mockHelpCommand]);
const result = await handleSlashCommand(
'/help',
abortController,
mockConfig,
mockSettings,
// Default allowed list: ['init', 'summary', 'compress']
);
expect(result.type).toBe('unsupported');
if (result.type === 'unsupported') {
expect(result.reason).toBe(
'The command "/help" is not supported in this mode.',
);
}
});
it('should execute local commands with non_interactive supportedModes', async () => {
const mockInitCommand = {
name: 'init',
description: 'Initialize project',
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
action: vi.fn().mockResolvedValue({
type: 'message',
messageType: 'info',
content: 'Project initialized',
}),
};
mockGetCommands.mockReturnValue([mockInitCommand]);
const result = await handleSlashCommand(
'/init',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('message');
if (result.type === 'message') {
expect(result.content).toBe('Project initialized');
}
});
it('should execute /btw with non_interactive supportedModes', async () => {
const mockBtwCommand = {
name: 'btw',
description: 'Ask a side question',
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
action: vi.fn().mockResolvedValue({
type: 'message',
messageType: 'info',
content: 'btw> question\nanswer',
}),
};
mockGetCommands.mockReturnValue([mockBtwCommand]);
const result = await handleSlashCommand(
'/btw question',
abortController,
mockConfig,
mockSettings,
);
expect(mockBtwCommand.action).toHaveBeenCalled();
expect(result.type).toBe('message');
if (result.type === 'message') {
expect(result.content).toBe('btw> question\nanswer');
}
});
it('should execute /goal in non-interactive mode as a submit_prompt command', async () => {
mockGetCommands.mockReturnValue([goalCommand]);
const result = await handleSlashCommand(
'/goal write a hello world script',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('submit_prompt');
if (result.type === 'submit_prompt') {
expect(result.content).toEqual([
expect.objectContaining({
text: expect.stringContaining('write a hello world script'),
}),
]);
}
});
it('should report no active goal for empty non-interactive /goal', async () => {
mockGetCommands.mockReturnValue([goalCommand]);
const result = await handleSlashCommand(
'/goal',
abortController,
mockConfig,
mockSettings,
);
expect(result).toMatchObject({
type: 'message',
messageType: 'info',
content: 'No goal set. Usage: `/goal <condition>` (or `/goal clear`).',
});
});
it('should report active goal status after setting a non-interactive /goal', async () => {
mockGetCommands.mockReturnValue([goalCommand]);
await handleSlashCommand(
'/goal write a hello world script',
abortController,
mockConfig,
mockSettings,
);
const result = await handleSlashCommand(
'/goal',
abortController,
mockConfig,
mockSettings,
);
expect(result).toMatchObject({
type: 'message',
messageType: 'info',
});
if (result.type === 'message') {
expect(result.content).toContain(
'Goal active: write a hello world script',
);
expect(result.content).toContain('not yet evaluated');
}
});
it('should report cleared goal for non-interactive /goal clear', async () => {
mockGetCommands.mockReturnValue([goalCommand]);
await handleSlashCommand(
'/goal write a hello world script',
abortController,
mockConfig,
mockSettings,
);
const result = await handleSlashCommand(
'/goal clear',
abortController,
mockConfig,
mockSettings,
);
expect(result).toMatchObject({
type: 'message',
messageType: 'info',
content: 'Goal cleared: write a hello world script',
});
});
it('should report cleared goal for ACP /goal clear', async () => {
vi.mocked(mockConfig.getExperimentalZedIntegration).mockReturnValue(true);
mockGetCommands.mockReturnValue([goalCommand]);
await handleSlashCommand(
'/goal write a hello world script',
abortController,
mockConfig,
mockSettings,
);
const result = await handleSlashCommand(
'/goal clear',
abortController,
mockConfig,
mockSettings,
);
expect(result).toMatchObject({
type: 'message',
messageType: 'info',
content: 'Goal cleared: write a hello world script',
});
});
it('should execute FILE commands in any mode without explicit supportedModes', async () => {
const mockFileCommand = {
name: 'custom',
description: 'Custom file command',
kind: CommandKind.FILE,
action: vi.fn().mockResolvedValue({
type: 'submit_prompt',
content: [{ text: 'Custom prompt' }],
}),
};
mockGetCommands.mockReturnValue([mockFileCommand]);
const result = await handleSlashCommand(
'/custom',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('submit_prompt');
if (result.type === 'submit_prompt') {
expect(result.content).toEqual([{ text: 'Custom prompt' }]);
}
});
it('should return unsupported for other built-in commands like /quit', async () => {
const mockQuitCommand = {
name: 'quit',
description: 'Quit application',
kind: CommandKind.BUILT_IN,
action: vi.fn(),
};
mockGetCommands.mockReturnValue([mockQuitCommand]);
const result = await handleSlashCommand(
'/quit',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('unsupported');
if (result.type === 'unsupported') {
expect(result.reason).toContain('/quit');
expect(result.reason).toContain('not supported');
}
});
it('should handle command with no action', async () => {
const mockCommand = {
name: 'noaction',
description: 'Command without action',
kind: CommandKind.FILE,
// No action property
};
mockGetCommands.mockReturnValue([mockCommand]);
const result = await handleSlashCommand(
'/noaction',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('no_command');
});
it('should return message when command returns void', async () => {
const mockCommand = {
name: 'voidcmd',
description: 'Command that returns void',
kind: CommandKind.FILE,
action: vi.fn().mockResolvedValue(undefined),
};
mockGetCommands.mockReturnValue([mockCommand]);
const result = await handleSlashCommand(
'/voidcmd',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('message');
if (result.type === 'message') {
expect(result.content).toBe('Command executed successfully.');
expect(result.messageType).toBe('info');
}
});
describe('disabled slash commands', () => {
const mockDisabledCommand = {
name: 'help',
description: 'Show help',
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
action: vi.fn().mockResolvedValue({
type: 'message',
messageType: 'info',
content: 'Help content',
}),
};
it('should return unsupported with disabled reason for a disabled command', async () => {
mockGetCommands.mockReturnValue([mockDisabledCommand]);
vi.mocked(mockConfig.getDisabledSlashCommands).mockReturnValue(['help']);
const result = await handleSlashCommand(
'/help',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('unsupported');
if (result.type === 'unsupported') {
expect(result.reason).toContain('disabled');
expect(result.originalType).toBe('filtered_command');
}
});
it('should match disabled command names case-insensitively', async () => {
mockGetCommands.mockReturnValue([mockDisabledCommand]);
vi.mocked(mockConfig.getDisabledSlashCommands).mockReturnValue(['HELP']);
const result = await handleSlashCommand(
'/help',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('unsupported');
if (result.type === 'unsupported') {
expect(result.reason).toContain('disabled');
}
});
it('should still return no_command for genuinely unknown commands even with a denylist', async () => {
mockGetCommands.mockReturnValue([mockDisabledCommand]);
vi.mocked(mockConfig.getDisabledSlashCommands).mockReturnValue(['help']);
const result = await handleSlashCommand(
'/unknowncommand',
abortController,
mockConfig,
mockSettings,
);
expect(result.type).toBe('no_command');
});
});
});
describe('getAvailableCommands', () => {
let mockConfig: Config;
beforeEach(() => {
vi.clearAllMocks();
mockCommandServiceCreate.mockResolvedValue({
getCommands: mockGetCommands,
getCommandsForMode: mockGetCommandsForMode,
getModelInvocableCommands: mockGetModelInvocableCommands,
});
mockConfig = {
getExperimentalZedIntegration: vi.fn().mockReturnValue(false),
isInteractive: vi.fn().mockReturnValue(false),
getSessionId: vi.fn().mockReturnValue('test-session'),
getFolderTrustFeature: vi.fn().mockReturnValue(false),
getFolderTrust: vi.fn().mockReturnValue(false),
getProjectRoot: vi.fn().mockReturnValue('/test/project'),
getDisabledSlashCommands: vi.fn().mockReturnValue([]),
storage: {},
} as unknown as Config;
});
it('includes /export in the default non-interactive command list', async () => {
const exportCommand = {
name: 'export',
description: 'Export current session',
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
action: vi.fn(),
};
mockGetCommands.mockReturnValue([exportCommand]);
const commands = await getAvailableCommands(
mockConfig,
new AbortController().signal,
);
expect(commands.map((command) => command.name)).toContain('export');
});
});