Compare commits

..

4 Commits

Author SHA1 Message Date
yiliang114
6fcf0206ea fix(cli): reset profiler state on rate-limit and tailor Windows messages
- When enforceRateLimit() throws in stopCpuProfile(), explicitly stop the
  V8 profiler, disconnect the session, and reset state to 'idle' so the
  user is not stuck and can start a fresh recording.
- Tailor the "stopped externally" info message to omit SIGUSR1 on Windows
  where the signal does not exist.
- Add test verifying state recovery after rate-limit rejection.
2026-06-01 23:18:34 +08:00
yiliang114
bab0f93610 fix(i18n): add missing CPU profile key to en.js
The i18n check failed because zh.js and zh-TW.js had the
"Record a CPU profile for Chrome DevTools analysis" key but
en.js did not. Add the identity mapping to en.js.
2026-05-30 23:30:31 +08:00
yiliang114
95a305f4b2 fix(cli): address cpu-profile review feedback and CI failures
- Platform-aware SIGUSR1 hint (suppress on Windows)
- Log warning when statfsSync is unavailable instead of silent swallow
- Improve error messages for stopping state and lost session
- Add user feedback on abort (report saved file path)
- Fix non-deterministic sort in cleanupOldProfiles on stat failure
- Add initCpuProfiler() ordering comment
- Unify copyright year to 2025
- Add InspectorSession interface rationale comment
- Fix doctorCommand.test.ts assertions for new cpu-profile subcommand
- Add zh-CN/zh-TW translations for cpu-profile command description
2026-05-29 21:15:55 +08:00
yiliang114
3b42a71a99 feat(cli): add CPU profiling support for Chrome DevTools analysis (#4617)
Add a cpuProfiler module that generates .cpuprofile files loadable in
Chrome DevTools Performance tab. Three trigger modes:

- Environment variable: QWEN_CODE_CPU_PROFILE=1 records from start to exit
- Signal toggle: SIGUSR1 starts/stops recording (Linux/macOS)
- Command: /doctor cpu-profile [--duration N] records for N seconds

Output written to ~/.qwen/cpu-profiles/ with safety guards (rate limit,
max 5 files, disk space check). Complements existing heap snapshot and
memory diagnostics infrastructure.
2026-05-29 15:51:03 +08:00
150 changed files with 3440 additions and 12818 deletions

View File

@ -1,136 +0,0 @@
---
title: 'Memory Pressure Monitor'
date: '2026-05-21'
status: 'implemented'
---
# Memory Pressure Monitor
## Problem
Long-running Qwen Code sessions can accumulate memory through large tool
results, repeated file reads, chat history, and native/external allocations.
Before this change, the core package had diagnostics and session-reset cleanup,
but no runtime response when memory pressure rises during normal tool
execution.
The highest-value cache-specific gap is `FileReadCache`: it already has a
bounded FIFO size, but it did not have a time-based eviction path. That means a
session can retain inactive file-read metadata until the hard entry limit is
hit, even when the process is under memory pressure.
## Goals
- Add a low-overhead memory pressure check after tool execution.
- Prefer surgical cleanup before destructive cleanup.
- Respect container memory limits when cgroup v2 or cgroup v1 memory limit
files are available.
- React to V8 heap pressure before JavaScript heap OOM on high-memory hosts.
- Keep subagent/scoped `Config` instances isolated from parent session cleanup.
- Make behavior configurable through environment variables without adding a new
user-facing settings surface.
## Non-Goals
- Do not add a background polling loop.
- Do not make explicit GC the default; it only runs when enabled and Node was
started with `--expose-gc`.
- Do not change prior-read enforcement semantics. Cache eviction can remove old
metadata, but it must not weaken stale-file checks for retained entries.
## Design
`Config.initialize()` creates one `MemoryPressureMonitor` per initialized
`Config`. `getMemoryPressureMonitor()` mirrors the existing `getFileReadCache()`
Object.create isolation pattern: when a child config is created through
prototype delegation, the getter lazily installs an own monitor bound to that
child config.
`CoreToolScheduler.executeSingleToolCall()` calls `scheduleCheck()` in its
`finally` block after ending the tool span. `scheduleCheck()` coalesces multiple
calls in the same event-loop turn with `queueMicrotask`, so concurrent read-like
tool batches do not run one memory check per tool result.
The monitor uses the stronger of two pressure signals:
- RSS divided by an effective process memory limit. Prefer cgroup v2
`/sys/fs/cgroup/memory.max` when it is a finite positive value; fall back to
cgroup v1 `/sys/fs/cgroup/memory/memory.limit_in_bytes`, then to
`os.totalmem()` otherwise. cgroup v1's huge "unlimited" sentinel values are
ignored.
- V8 `heapUsed` divided by `getHeapStatistics().heap_size_limit`.
Using both signals matters because containers usually fail by RSS/cgroup limit,
while local high-memory machines can hit V8 heap OOM long before RSS is a large
fraction of total system memory.
Default thresholds are intentionally conservative enough to react before the OS
or container OOM killer does:
- `softPressureRatio = 0.50`
- `hardPressureRatio = 0.65`
- `criticalRatio = 0.80`
- `cleanupCooldownMs = 5000`
- `enableExplicitGC = false`
Environment overrides:
- `QWEN_MEMORY_PRESSURE_SOFT`
- `QWEN_MEMORY_PRESSURE_HARD`
- `QWEN_MEMORY_PRESSURE_CRITICAL`
- `QWEN_MEMORY_ENABLE_GC=1`
Invalid ratios fall back to defaults. Valid ratios must be ordered as
`soft < hard < critical`, with a lower soft bound of `0.3` and an upper
critical bound of `0.98`. Ratio env vars are parsed strictly with `Number()`,
so values such as `0.8extra` are rejected instead of partially accepted.
Invalid memory-pressure env configuration writes a visible warning to stderr
and to the debug log before falling back to defaults.
## Cleanup Policy
Pressure levels map to increasingly strong cleanup:
- `soft`: evict stale `FileReadCache` entries not accessed in 60 minutes.
- `hard`: evict cache entries not accessed in 30 minutes.
- `critical`: clear the file-read cache and optionally trigger `global.gc()`.
The monitor intentionally does not force chat compaction. Compaction can call
the model backend and rewrite active chat state, so it should be triggered only
from a call site that can safely coordinate with the conversation loop.
Cleanup is fire-and-forget from the scheduler, but the monitor guards cleanup
steps with `cleanupInProgress` and a cooldown timestamp. A higher-pressure
cleanup can bypass the cooldown and queue behind an in-progress lower-pressure
cleanup, so a `critical` check is not lost while a `soft` cleanup is finishing.
After successful cleanup it logs an RSS delta on `setImmediate()`, but RSS
movement is diagnostic only: V8 and libc may retain freed pages even when
JavaScript objects became collectible. Consecutive failures count cleanup-step
exceptions, not unchanged RSS, and the counter is reset on a new session. If
three successful cleanup attempts in a row free less than 1% RSS, the monitor
emits `memory-cleanup-ineffective` as a diagnostic signal without treating the
cleanup step itself as failed.
## Test Coverage
The implementation is covered by:
- threshold validation tests;
- environment config parsing, fallback, visible warning, and explicit GC tests;
- pressure classification tests using mocked `process.memoryUsage()`;
- cgroup v2 `memory.max` and cgroup v1 `memory.limit_in_bytes` behavior;
- V8 heap limit behavior;
- `scheduleCheck()` coalescing;
- scheduler integration that invokes `scheduleCheck()` after tool execution;
- soft and critical cleanup actions;
- cleanup failure accounting for thrown cleanup steps;
- cleanup listener exception isolation and ineffective-cleanup diagnostics;
- child `Config` monitor isolation through `Object.create`;
- `FileReadCache.evictNotAccessedSince()` behavior.
## Risks And Tradeoffs
- RSS can stay flat after cleanup because V8 or libc may retain freed memory.
RSS deltas are logged, but unchanged RSS does not count as a cleanup failure.
- Time-based file-read cache eviction may reduce fast-path hits for old files,
but it preserves recently active entries and only runs under memory pressure.

View File

@ -17,15 +17,13 @@ npm install
### Setup Content
Prepare the public documentation content from the parent `docs` directory:
Link the documentation content from the parent `docs` directory:
```bash
npm run link
```
This creates a `content` directory with copies of the public docs sections.
Internal planning, design, and E2E notes remain outside the docs site content
tree.
This creates a symbolic link from `../docs` to `content` in the project.
### Development

View File

@ -7,10 +7,10 @@
"type": "module",
"main": "index.js",
"scripts": {
"link": "node scripts/link-public-docs.mjs",
"link": "ln -s ../docs content",
"clean": "rm -rf .next",
"dev": "npm run clean && next --turbopack",
"test": "vitest run --config vitest.config.js"
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"next": "^16.0.8",
@ -18,8 +18,5 @@
"nextra-theme-docs": "^4.6.1",
"react": "^19.2.1",
"react-dom": "^19.2.1"
},
"devDependencies": {
"vitest": "^3.2.4"
}
}

View File

@ -1,26 +0,0 @@
import { cp, mkdir, rm, symlink } from 'node:fs/promises';
import { join } from 'node:path';
import { PUBLIC_DOC_ROOTS } from '../src/app/public-docs.js';
const contentDir = 'content';
async function linkPublicDocs() {
try {
await rm(contentDir, { force: true, recursive: true });
await mkdir(contentDir);
await cp('../docs/index.md', join(contentDir, 'index.md'));
await cp('../docs/_meta.ts', join(contentDir, '_meta.ts'));
for (const root of PUBLIC_DOC_ROOTS) {
await symlink(join('..', '..', 'docs', root), join(contentDir, root));
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to link public docs into ${contentDir}: ${message}`,
);
}
}
await linkPublicDocs();

View File

@ -1,23 +1,10 @@
import { generateStaticParamsFor, importPage } from 'nextra/pages';
import { notFound } from 'next/navigation';
import { useMDXComponents as getMDXComponents } from '../../../mdx-components';
import { filterPublicStaticParams, isPublicDocsPath } from '../public-docs';
const generateAllStaticParams = generateStaticParamsFor('mdxPath');
export const dynamicParams = false;
export async function generateStaticParams(...args) {
const staticParams = await generateAllStaticParams(...args);
return filterPublicStaticParams(staticParams);
}
export const generateStaticParams = generateStaticParamsFor('mdxPath');
export async function generateMetadata(props) {
const params = await props.params;
if (!isPublicDocsPath(params.mdxPath)) {
notFound();
}
const { metadata } = await importPage(params.mdxPath);
return metadata;
}
@ -26,10 +13,6 @@ const Wrapper = getMDXComponents().wrapper;
export default async function Page(props) {
const params = await props.params;
if (!isPublicDocsPath(params.mdxPath)) {
notFound();
}
const {
default: MDXContent,
toc,

View File

@ -1,59 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => {
const generateAllStaticParams = vi.fn();
return {
generateAllStaticParams,
generateStaticParamsFor: vi.fn(() => generateAllStaticParams),
};
});
vi.mock('nextra/pages', () => ({
generateStaticParamsFor: mocks.generateStaticParamsFor,
importPage: vi.fn(),
}));
vi.mock('next/navigation', () => ({
notFound: vi.fn(),
}));
vi.mock('../../../mdx-components', () => ({
useMDXComponents: () => ({
wrapper: ({ children }) => children,
}),
}));
describe('generateStaticParams', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('filters internal docs from Nextra static params', async () => {
mocks.generateAllStaticParams.mockResolvedValue([
{ mdxPath: [] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'users'] },
{ mdxPath: ['design', 'bar'] },
{ mdxPath: ['plans'] },
]);
const { generateStaticParams } = await import('./page.jsx');
await expect(generateStaticParams()).resolves.toEqual([
{ mdxPath: [] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'users'] },
]);
});
it('fails closed if Nextra changes the static params shape', async () => {
mocks.generateAllStaticParams.mockResolvedValue([{ slug: ['users'] }]);
const { generateStaticParams } = await import('./page.jsx');
await expect(generateStaticParams()).rejects.toThrow(
'Expected generateStaticParamsFor("mdxPath") to return objects with an mdxPath array.',
);
});
});

View File

@ -1,33 +0,0 @@
const LOCALE_SEGMENTS = new Set(['en', 'zh', 'de', 'fr', 'ja', 'ru', 'pt-BR']);
// Keep this in sync with the public top-level page entries in docs/_meta.ts.
// docs-site/scripts/link-public-docs.mjs consumes the same allowlist.
export const PUBLIC_DOC_ROOTS = ['users', 'developers'];
const PUBLIC_DOC_ROOT_SET = new Set(PUBLIC_DOC_ROOTS);
function publicRootFromSegments(segments = []) {
if (segments.length === 0 || (segments.length === 1 && segments[0] === '')) {
return undefined;
}
const rootIndex = LOCALE_SEGMENTS.has(segments[0]) ? 1 : 0;
return segments[rootIndex];
}
export function isPublicDocsPath(mdxPath = []) {
const root = publicRootFromSegments(mdxPath);
return root === undefined || PUBLIC_DOC_ROOT_SET.has(root);
}
export function filterPublicStaticParams(staticParams = []) {
return staticParams.filter((staticParam) => {
if (!Array.isArray(staticParam?.mdxPath)) {
throw new TypeError(
'Expected generateStaticParamsFor("mdxPath") to return objects with an mdxPath array.',
);
}
return isPublicDocsPath(staticParam.mdxPath);
});
}

View File

@ -1,43 +0,0 @@
import { describe, expect, it } from 'vitest';
import { filterPublicStaticParams, isPublicDocsPath } from './public-docs.js';
describe('isPublicDocsPath', () => {
it.each([
[[], true],
[[''], true],
[['users', 'foo'], true],
[['design', 'bar'], false],
[['en', 'users'], true],
[['plans'], false],
[['en'], true],
])('returns %s for %j', (mdxPath, expected) => {
expect(isPublicDocsPath(mdxPath)).toBe(expected);
});
});
describe('filterPublicStaticParams', () => {
it('keeps public paths and rejects internal docs paths', () => {
expect(
filterPublicStaticParams([
{ mdxPath: [] },
{ mdxPath: [''] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'developers'] },
{ mdxPath: ['design', 'bar'] },
{ mdxPath: ['plans'] },
]),
).toEqual([
{ mdxPath: [] },
{ mdxPath: [''] },
{ mdxPath: ['users', 'foo'] },
{ mdxPath: ['en', 'developers'] },
]);
});
it('fails closed if Nextra changes the static params shape', () => {
expect(() => filterPublicStaticParams([{ slug: ['users'] }])).toThrow(
'Expected generateStaticParamsFor("mdxPath") to return objects with an mdxPath array.',
);
});
});

View File

@ -1,7 +0,0 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['src/**/*.test.{js,jsx}'],
},
});

View File

@ -1,6 +1,9 @@
export default {
settings: 'Settings',
auth: 'Authentication',
memory: {
display: 'hidden',
},
'qwen-ignore': 'Ignoring Files',
'trusted-folders': 'Trusted Folders',
themes: 'Themes',

View File

@ -146,11 +146,7 @@ Settings are organized into categories. Most settings should be placed within th
| `model.maxWallTimeSeconds` | number | Wall-clock budget for headless / unattended runs, in seconds. `-1` means unlimited. Overridable per-invocation via `--max-wall-time`, which requires a positive duration (`90`, `30s`, `5m`, `1h`, `1.5h`); the minimum is 1 second — sub-second values (`500ms`, `0.5`) are rejected as typos. Omit the flag to fall back to this setting. Aborts with exit code 55 when exceeded. | `-1` |
| `model.maxToolCalls` | number | Cumulative tool-call budget for a run (counts every executed tool, success or failure; `structured_output` under `--json-schema` is exempt). `-1` means unlimited; `0` means "no tool calls allowed". Capped at 1,000,000 to catch typos. Overridable via `--max-tool-calls`. Aborts with exit code 55 when exceeded. | `-1` |
| `model.generationConfig` | object | Advanced overrides passed to the underlying content generator. Supports request controls such as `timeout`, `maxRetries`, `enableCacheControl`, `splitToolMedia` (set `true` for strict OpenAI-compatible servers like LM Studio that reject non-text content on `role: "tool"` messages — splits media into a follow-up user message), `contextWindowSize` (override model's context window size), `modalities` (override auto-detected input modalities), `customHeaders` (custom HTTP headers for API requests), and `extra_body` (additional body parameters for OpenAI-compatible API requests only), along with fine-tuning knobs under `samplingParams` (for example `temperature`, `top_p`, `max_tokens`). Leave unset to rely on provider defaults. | `undefined` |
| `model.chatCompression.contextPercentageThreshold` | number | **REMOVED.** Auto-compaction now uses a three-tier threshold ladder (warn / auto / hard) computed internally from the model's context window via the `computeThresholds()` function — no longer user-configurable. Setting this field in `settings.json` is silently ignored (no startup warning). There is currently no replacement for "disable compression entirely" — reactive overflow recovery remains the safety net at the API layer if compression itself fails. (See PR #4345 / `docs/design/auto-compaction-threshold-redesign.md` for the redesign rationale.) | `N/A` |
| `model.chatCompression.maxRecentFilesToRetain` | number | Number of most-recently-touched files whose current content is restored (embedded if small, otherwise referenced by path) into history after auto-compaction. `0` restores none. Env override: `QWEN_COMPACT_MAX_RECENT_FILES`. | `5` |
| `model.chatCompression.maxRecentImagesToRetain` | number | Number of most-recent images (tool screenshots / user pastes) restored into history after auto-compaction. `0` restores none. Env override: `QWEN_COMPACT_MAX_RECENT_IMAGES`. | `3` |
| `model.chatCompression.enableScreenshotTrigger` | boolean | When `true`, auto-compaction also fires once the number of tool-returned images accumulated in history reaches `screenshotTriggerThreshold`, independent of token usage — aimed at computer-use sessions where frequent screenshots dilute model attention. Counts only images returned inside tool results, not user-pasted images. Env override: `QWEN_COMPACT_SCREENSHOT_TRIGGER` (`1`/`true`/`0`/`false`). | `true` |
| `model.chatCompression.screenshotTriggerThreshold` | number | Tool-returned image count at or above which the screenshot trigger fires (only when `enableScreenshotTrigger`). Compaction resets the count — surviving images are re-embedded as top-level parts, which the trigger doesn't count — so it won't immediately re-fire. Env override: `QWEN_COMPACT_SCREENSHOT_THRESHOLD`. | `50` |
| `model.chatCompression.contextPercentageThreshold` | number | **REMOVED.** Auto-compaction now uses a three-tier threshold ladder (warn / auto / hard) computed internally from the model's context window via the `computeThresholds()` function — no longer user-configurable. Setting this field in `settings.json` is silently ignored, and a one-line deprecation warning is emitted to stderr at startup. There is currently no replacement for "disable compression entirely" — reactive overflow recovery remains the safety net at the API layer if compression itself fails. (See PR #4345 / `docs/design/auto-compaction-threshold-redesign.md` for the redesign rationale.) | `N/A` |
| `model.skipNextSpeakerCheck` | boolean | Skip the next speaker check. | `false` |
| `model.skipLoopDetection` | boolean | Disables streaming loop detection checks. Defaults to `true` (loop detection is skipped) to avoid false positives interrupting legitimate workflows. Set to `false` to re-enable streaming loop detection — useful as a guardrail in headless / non-interactive runs where stuck repetition can otherwise waste budget. | `true` |
| `model.skipStartupContext` | boolean | Skips sending the startup workspace context (environment summary and acknowledgement) at the beginning of each session. Enable this if you prefer to provide context manually or want to save tokens on startup. | `false` |

28
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.17.0",
"version": "0.16.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@qwen-code/qwen-code",
"version": "0.17.0",
"version": "0.16.1",
"workspaces": [
"packages/*",
"packages/channels/base",
@ -17080,7 +17080,7 @@
},
"packages/acp-bridge": {
"name": "@qwen-code/acp-bridge",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",
"@qwen-code/qwen-code-core": "file:../core"
@ -17095,7 +17095,7 @@
},
"packages/channels/base": {
"name": "@qwen-code/channel-base",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1"
},
@ -17105,7 +17105,7 @@
},
"packages/channels/dingtalk": {
"name": "@qwen-code/channel-dingtalk",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@qwen-code/channel-base": "file:../base",
"dingtalk-stream-sdk-nodejs": "^2.0.4"
@ -17116,7 +17116,7 @@
},
"packages/channels/feishu": {
"name": "@qwen-code/channel-feishu",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@larksuiteoapi/node-sdk": "^1.45.0",
"@qwen-code/channel-base": "file:../base"
@ -17127,7 +17127,7 @@
},
"packages/channels/plugin-example": {
"name": "@qwen-code/channel-plugin-example",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@qwen-code/channel-base": "file:../base",
"ws": "^8.18.0"
@ -17141,7 +17141,7 @@
},
"packages/channels/telegram": {
"name": "@qwen-code/channel-telegram",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@qwen-code/channel-base": "file:../base",
"grammy": "^1.41.1",
@ -17154,7 +17154,7 @@
},
"packages/channels/weixin": {
"name": "@qwen-code/channel-weixin",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@qwen-code/channel-base": "file:../base"
},
@ -17164,7 +17164,7 @@
},
"packages/cli": {
"name": "@qwen-code/qwen-code",
"version": "0.17.0",
"version": "0.16.1",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",
"@google/genai": "1.30.0",
@ -17587,7 +17587,7 @@
},
"packages/core": {
"name": "@qwen-code/qwen-code-core",
"version": "0.17.0",
"version": "0.16.1",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^0.36.1",
@ -20436,7 +20436,7 @@
},
"packages/vscode-ide-companion": {
"name": "qwen-code-vscode-ide-companion",
"version": "0.17.0",
"version": "0.16.1",
"license": "LICENSE",
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",
@ -20573,7 +20573,7 @@
},
"packages/web-templates": {
"name": "@qwen-code/web-templates",
"version": "0.17.0",
"version": "0.16.1",
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
@ -21101,7 +21101,7 @@
},
"packages/webui": {
"name": "@qwen-code/webui",
"version": "0.17.0",
"version": "0.16.1",
"license": "MIT",
"dependencies": {
"markdown-it": "^14.1.0"

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.17.0",
"version": "0.16.1",
"engines": {
"node": ">=22.0.0"
},
@ -19,7 +19,7 @@
"url": "git+https://github.com/QwenLM/qwen-code.git"
},
"config": {
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.17.0"
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.16.1"
},
"scripts": {
"start": "cross-env node scripts/start.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/acp-bridge",
"version": "0.17.0",
"version": "0.16.1",
"description": "Shared ACP bridge primitives (EventBus, AcpChannel, in-memory channel, PermissionMediator interface) used by qwen serve, channels, IDE, TUI, and remote-control adapters.",
"repository": {
"type": "git",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-base",
"version": "0.17.0",
"version": "0.16.1",
"description": "Base channel infrastructure for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-dingtalk",
"version": "0.17.0",
"version": "0.16.1",
"description": "DingTalk channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-feishu",
"version": "0.17.0",
"version": "0.16.1",
"description": "Feishu (Lark) channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-plugin-example",
"version": "0.17.0",
"version": "0.16.1",
"private": true,
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-telegram",
"version": "0.17.0",
"version": "0.16.1",
"description": "Telegram channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/channel-weixin",
"version": "0.17.0",
"version": "0.16.1",
"description": "WeChat (Weixin) channel adapter for Qwen Code",
"type": "module",
"main": "dist/index.js",

View File

@ -11,6 +11,11 @@ import { initStartupProfiler } from './src/utils/startupProfiler.js';
// Must run before any other imports to capture the earliest possible T0.
initStartupProfiler();
import { initCpuProfiler } from './src/utils/cpuProfiler.js';
// Initialize early to register SIGUSR1 handler and start recording when
// QWEN_CODE_CPU_PROFILE=1, capturing as much of the startup as possible.
initCpuProfiler();
import './src/gemini.js';
import { main } from './src/gemini.js';
import { FatalError } from '@qwen-code/qwen-code-core';

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.17.0",
"version": "0.16.1",
"description": "Qwen Code",
"repository": {
"type": "git",
@ -37,7 +37,7 @@
"dist"
],
"config": {
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.17.0"
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.16.1"
},
"dependencies": {
"@agentclientprotocol/sdk": "^0.14.1",

View File

@ -145,20 +145,7 @@ vi.mock('./runtimeOutputDirContext.js', () => ({
),
}));
vi.mock('./authMethods.js', () => {
const buildAuthMethods = vi.fn();
return {
buildAuthMethods,
pickAuthMethodsForAuthRequired: vi.fn((selectedType?: string) => {
const authMethods = buildAuthMethods();
if (!selectedType) return authMethods;
const matched = authMethods.filter(
(method: { id: string }) => method.id === selectedType,
);
return matched.length ? matched : authMethods;
}),
};
});
vi.mock('./authMethods.js', () => ({ buildAuthMethods: vi.fn() }));
vi.mock('./service/filesystem.js', () => ({
AcpFileSystemService: vi.fn(),
}));
@ -208,7 +195,6 @@ import { loadSettings } from '../config/settings.js';
import { loadCliConfig } from '../config/config.js';
import { Session, buildAvailableCommandsSnapshot } from './session/Session.js';
import { SERVE_STATUS_EXT_METHODS } from '../serve/status.js';
import { buildAuthMethods } from './authMethods.js';
describe('runAcpAgent shutdown cleanup', () => {
let processExitSpy: MockInstance<typeof process.exit>;
@ -806,64 +792,6 @@ describe('QwenAgent MCP SSE/HTTP support', () => {
await agentPromise;
});
it('does not return discontinued qwen-oauth as the only ACP auth option', async () => {
vi.mocked(buildAuthMethods).mockReturnValue([
{
id: 'openai',
name: 'Use OpenAI API key',
description: 'Requires setting OPENAI_API_KEY',
},
]);
const innerConfig = makeInnerConfig();
vi.mocked(innerConfig.getModelsConfig).mockReturnValue({
getCurrentAuthType: vi.fn().mockReturnValue('qwen-oauth'),
} as unknown as ReturnType<Config['getModelsConfig']>);
vi.mocked(innerConfig.refreshAuth).mockRejectedValue(
new Error('qwen-oauth token expired'),
);
vi.mocked(loadSettings).mockReturnValue(makeSessionSettings());
vi.mocked(loadCliConfig).mockResolvedValue(
innerConfig as unknown as Config,
);
vi.mocked(Session).mockImplementation(
() =>
({
getId: vi.fn().mockReturnValue('test-session-id'),
getConfig: vi.fn().mockReturnValue(innerConfig),
sendAvailableCommandsUpdate: vi.fn().mockResolvedValue(undefined),
replayHistory: vi.fn().mockResolvedValue(undefined),
installRewriter: vi.fn(),
}) as unknown as InstanceType<typeof Session>,
);
const agentPromise = runAcpAgent(
mockConfig,
makeSessionSettings(),
mockArgv,
);
await vi.waitFor(() => expect(capturedAgentFactory).toBeDefined());
const agent = capturedAgentFactory!({
get closed() {
return mockConnectionState.promise;
},
}) as AgentLike;
await expect(
agent.newSession({ cwd: '/tmp', mcpServers: [] }),
).rejects.toMatchObject({
authMethods: [
expect.objectContaining({
id: 'openai',
}),
],
});
mockConnectionState.resolve();
await agentPromise;
});
function makeInnerConfig() {
return {
initialize: vi.fn().mockResolvedValue(undefined),

View File

@ -40,6 +40,7 @@ import type { Content } from '@google/genai';
import type {
Agent,
AuthenticateRequest,
AuthMethod,
CancelNotification,
ClientCapabilities,
InitializeRequest,
@ -68,10 +69,7 @@ import type {
SetSessionModeRequest,
SetSessionModeResponse,
} from '@agentclientprotocol/sdk';
import {
buildAuthMethods,
pickAuthMethodsForAuthRequired,
} from './authMethods.js';
import { buildAuthMethods } from './authMethods.js';
import { AcpFileSystemService } from './service/filesystem.js';
import { Readable, Writable } from 'node:stream';
import type { LoadedSettings } from '../config/settings.js';
@ -1938,7 +1936,7 @@ class QwenAgent implements Agent {
const selectedType = config.getModelsConfig().getCurrentAuthType();
if (!selectedType) {
throw RequestError.authRequired(
{ authMethods: pickAuthMethodsForAuthRequired() },
{ authMethods: this.pickAuthMethodsForAuthRequired() },
'Use Qwen Code CLI to authenticate first.',
);
}
@ -1949,13 +1947,51 @@ class QwenAgent implements Agent {
debugLogger.error(`Authentication failed: ${e}`);
throw RequestError.authRequired(
{
authMethods: pickAuthMethodsForAuthRequired(selectedType),
authMethods: this.pickAuthMethodsForAuthRequired(selectedType, e),
},
'Authentication failed: ' + (e as Error).message,
);
}
}
private pickAuthMethodsForAuthRequired(
selectedType?: AuthType | string,
error?: unknown,
): AuthMethod[] {
const authMethods = buildAuthMethods();
const errorMessage = this.extractErrorMessage(error);
if (
errorMessage?.includes('qwen-oauth') ||
errorMessage?.includes('Qwen OAuth')
) {
const qwenOAuthMethods = authMethods.filter(
(m) => m.id === AuthType.QWEN_OAUTH,
);
return qwenOAuthMethods.length ? qwenOAuthMethods : authMethods;
}
if (selectedType) {
const matched = authMethods.filter((m) => m.id === selectedType);
return matched.length ? matched : authMethods;
}
return authMethods;
}
private extractErrorMessage(error?: unknown): string | undefined {
if (error instanceof Error) return error.message;
if (
typeof error === 'object' &&
error != null &&
'message' in error &&
typeof error.message === 'string'
) {
return error.message;
}
if (typeof error === 'string') return error;
return undefined;
}
private setupFileSystem(config: Config): void {
if (!this.clientCapabilities?.fs) return;

View File

@ -125,20 +125,7 @@ vi.mock('./runtimeOutputDirContext.js', () => ({
),
}));
vi.mock('./authMethods.js', () => {
const buildAuthMethods = vi.fn();
return {
buildAuthMethods,
pickAuthMethodsForAuthRequired: vi.fn((selectedType?: string) => {
const authMethods = buildAuthMethods();
if (!selectedType) return authMethods;
const matched = authMethods.filter(
(method: { id: string }) => method.id === selectedType,
);
return matched.length ? matched : authMethods;
}),
};
});
vi.mock('./authMethods.js', () => ({ buildAuthMethods: vi.fn() }));
vi.mock('./service/filesystem.js', () => ({
AcpFileSystemService: vi.fn(),
}));

View File

@ -1,30 +0,0 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it } from 'vitest';
import { AuthType } from '@qwen-code/qwen-code-core';
import {
buildAuthMethods,
pickAuthMethodsForAuthRequired,
} from './authMethods.js';
describe('ACP auth methods', () => {
it('does not advertise discontinued Qwen OAuth', () => {
const authMethods = buildAuthMethods();
expect(authMethods.map((method) => method.id)).toEqual([
AuthType.USE_OPENAI,
]);
});
it('falls back to working methods for a stored discontinued Qwen OAuth selection', () => {
const authMethods = pickAuthMethodsForAuthRequired('qwen-oauth');
expect(authMethods.map((method) => method.id)).toEqual([
AuthType.USE_OPENAI,
]);
});
});

View File

@ -18,17 +18,33 @@ export function buildAuthMethods(): AuthMethod[] {
args: ['--auth-type=openai'],
},
},
{
id: AuthType.QWEN_OAUTH,
name: 'Qwen OAuth',
description: 'Qwen OAuth (free tier discontinued 2026-04-15)',
_meta: {
type: 'terminal',
args: ['--auth-type=qwen-oauth'],
},
},
];
}
export function pickAuthMethodsForAuthRequired(
selectedType?: AuthType | string,
export function filterAuthMethodsById(
authMethods: AuthMethod[],
authMethodId: string,
): AuthMethod[] {
const authMethods = buildAuthMethods();
if (selectedType) {
const matched = authMethods.filter((method) => method.id === selectedType);
return matched.length ? matched : authMethods;
}
return authMethods.filter((method) => method.id === authMethodId);
}
export function pickAuthMethodsForDetails(details?: string): AuthMethod[] {
const authMethods = buildAuthMethods();
if (!details) {
return authMethods;
}
if (details.includes('qwen-oauth') || details.includes('Qwen OAuth')) {
const narrowed = filterAuthMethodsById(authMethods, AuthType.QWEN_OAUTH);
return narrowed.length ? narrowed : authMethods;
}
return authMethods;
}

View File

@ -8,11 +8,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import {
computeInitialTurnFromHistory,
fireSessionPermissionDeniedForAutoMode,
Session,
} from './Session.js';
import { computeInitialTurnFromHistory, Session } from './Session.js';
import type { Content } from '@google/genai';
import type { ChatRecord, Config, GeminiChat } from '@qwen-code/qwen-code-core';
import { ApprovalMode, AuthType } from '@qwen-code/qwen-code-core';
@ -196,8 +192,6 @@ describe('Session', () => {
sendMessageStream: vi.fn(),
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue([]),
getHistoryShallow: vi.fn().mockReturnValue([]),
getLastModelMessageText: vi.fn().mockReturnValue(''),
setHistory: vi.fn(),
truncateHistory: vi.fn(),
stripThoughtsFromHistory: vi.fn(),
@ -331,7 +325,6 @@ describe('Session', () => {
{ role: 'model', parts: [{ text: 'second reply' }] },
];
vi.mocked(mockChat.getHistory).mockReturnValue(history);
vi.mocked(mockChat.getHistoryShallow).mockReturnValue(history);
const result = session.rewindToTurn(1);
@ -351,7 +344,6 @@ describe('Session', () => {
{ role: 'model', parts: [{ text: 'first reply' }] },
];
vi.mocked(mockChat.getHistory).mockReturnValue(history);
vi.mocked(mockChat.getHistoryShallow).mockReturnValue(history);
const result = session.rewindToTurn(0);
@ -360,9 +352,9 @@ describe('Session', () => {
});
it('rejects unreachable user turns', () => {
const history: Content[] = [{ role: 'user', parts: [{ text: 'first' }] }];
vi.mocked(mockChat.getHistory).mockReturnValue(history);
vi.mocked(mockChat.getHistoryShallow).mockReturnValue(history);
vi.mocked(mockChat.getHistory).mockReturnValue([
{ role: 'user', parts: [{ text: 'first' }] },
]);
expect(() => session.rewindToTurn(2)).toThrow(
'Cannot rewind to the requested turn',
@ -857,8 +849,6 @@ describe('Session', () => {
sendMessageStream: vi.fn().mockResolvedValue(createEmptyStream()),
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue([]),
getHistoryShallow: vi.fn().mockReturnValue([]),
getLastModelMessageText: vi.fn().mockReturnValue(''),
} as unknown as GeminiChat;
mockChat.sendMessageStream = vi
@ -918,36 +908,6 @@ describe('Session', () => {
});
});
it('labels the notice as screenshot-triggered when triggerReason is image_overflow', async () => {
mockGeminiClient.tryCompressChat.mockResolvedValueOnce({
originalTokenCount: 1200,
newTokenCount: 450,
compressionStatus: core.CompressionStatus.COMPRESSED,
triggerReason: 'image_overflow',
});
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());
await session.prompt({
sessionId: 'test-session-id',
prompt: [{ type: 'text', text: 'hello' }],
});
expect(mockClient.sessionUpdate).toHaveBeenCalledWith({
sessionId: 'test-session-id',
update: {
sessionUpdate: 'agent_message_chunk',
content: {
type: 'text',
text:
'IMPORTANT: This conversation accumulated enough tool screenshots to trigger compaction for qwen3-code-plus. ' +
'A compressed context will be sent for future messages (compressed from: 1200 to 450 tokens).',
},
},
});
});
it('continues sending when automatic compression fails', async () => {
mockGeminiClient.tryCompressChat.mockRejectedValueOnce(
new Error('compression rate limited'),
@ -1213,8 +1173,6 @@ describe('Session', () => {
sendMessageStream: vi.fn().mockResolvedValue(createEmptyStream()),
addHistory: vi.fn(),
getHistory: vi.fn().mockReturnValue([]),
getHistoryShallow: vi.fn().mockReturnValue([]),
getLastModelMessageText: vi.fn().mockReturnValue(''),
} as unknown as GeminiChat;
mockConfig.getSessionTokenLimit = vi.fn().mockReturnValue(100);
mockGeminiClient.tryCompressChat
@ -1531,9 +1489,6 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValueOnce(createEmptyStream())
@ -1595,9 +1550,6 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValueOnce(createEmptyStream())
@ -1669,9 +1621,6 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());
@ -2221,129 +2170,6 @@ describe('Session', () => {
});
describe('hooks', () => {
describe('PermissionDenied hook', () => {
it('fires PermissionDenied hooks for AUTO classifier blocks', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(false);
const signal = new AbortController().signal;
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'dangerous shell command',
unavailable: false,
stage: 'fast',
durationMs: 20,
},
{ kind: 'blocked', errorMessage: 'blocked' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
signal,
);
expect(hookSystem.firePermissionDeniedEvent).toHaveBeenCalledWith(
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
'classifier_blocked',
signal,
);
});
it('forwards classifier_unavailable reasons to PermissionDenied hooks', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(false);
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'classifier timeout',
unavailable: true,
stage: 'fast',
durationMs: 3000,
},
{ kind: 'blocked', errorMessage: 'blocked' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
new AbortController().signal,
);
expect(hookSystem.firePermissionDeniedEvent).toHaveBeenCalledWith(
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
'classifier_unavailable',
expect.any(AbortSignal),
);
});
it('skips PermissionDenied hooks when hooks are disabled', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(true);
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'dangerous shell command',
unavailable: false,
stage: 'fast',
durationMs: 20,
},
{ kind: 'blocked', errorMessage: 'blocked' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
new AbortController().signal,
);
expect(hookSystem.firePermissionDeniedEvent).not.toHaveBeenCalled();
});
it('skips PermissionDenied hooks when AUTO outcome is not blocked', async () => {
const hookSystem = {
firePermissionDeniedEvent: vi.fn().mockResolvedValue(undefined),
};
mockConfig.getHookSystem = vi.fn().mockReturnValue(hookSystem);
mockConfig.getDisableAllHooks = vi.fn().mockReturnValue(false);
await fireSessionPermissionDeniedForAutoMode(
mockConfig,
{
via: 'classifier',
shouldBlock: true,
reason: 'dangerous shell command',
unavailable: false,
stage: 'fast',
durationMs: 20,
},
{ kind: 'fallback' },
core.ToolNames.SHELL,
{ command: 'rm -rf /tmp/example' },
'auto-denied-acp',
new AbortController().signal,
);
expect(hookSystem.firePermissionDeniedEvent).not.toHaveBeenCalled();
});
});
describe('UserPromptSubmit hook', () => {
it('fires UserPromptSubmit hook before sending prompt', async () => {
const messageBus = {
@ -2422,9 +2248,6 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi.fn().mockResolvedValue(
createStreamWithChunks([
@ -2478,9 +2301,6 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());
@ -2526,9 +2346,6 @@ describe('Session', () => {
.mockReturnValue([
{ role: 'model', parts: [{ text: 'response text' }] },
]);
mockChat.getLastModelMessageText = vi
.fn()
.mockReturnValue('response text');
mockChat.sendMessageStream = vi
.fn()
.mockResolvedValue(createEmptyStream());

View File

@ -23,8 +23,6 @@ import type {
MessageBus,
StreamEvent,
ChatCompressionInfo,
AutoModeDecision,
AutoModeOutcome,
} from '@qwen-code/qwen-code-core';
import {
AuthType,
@ -64,13 +62,11 @@ import {
formatStopHookBlockingCapWarning,
applyAutoModeDecision,
evaluateAutoMode,
getAutoModePermissionDeniedReason,
isApproveOutcome,
MAX_TRANSCRIPT_MESSAGES,
recordAllow,
recordFallbackApprove,
shouldFallback,
shouldFirePermissionDeniedForAutoMode,
shouldRunAutoModeForCall,
} from '@qwen-code/qwen-code-core';
import { getCommandSubcommandNames } from '../../services/commandMetadata.js';
@ -163,31 +159,6 @@ export function computeInitialTurnFromHistory(
return maxPromptTurn > 0 ? maxPromptTurn : userMessageCount;
}
export async function fireSessionPermissionDeniedForAutoMode(
config: Config,
decision: AutoModeDecision,
outcome: AutoModeOutcome,
toolName: string,
toolParams: Record<string, unknown>,
callId: string,
signal?: AbortSignal,
): Promise<void> {
if (
!config.getDisableAllHooks?.() &&
shouldFirePermissionDeniedForAutoMode(decision, outcome)
) {
await config
.getHookSystem?.()
?.firePermissionDeniedEvent(
toolName,
toolParams,
callId,
getAutoModePermissionDeniedReason(decision),
signal,
);
}
}
function getRecordPromptIds(record: ChatRecord): string[] {
const promptIds: string[] = [];
const recordPromptId = (record as { promptId?: unknown }).promptId;
@ -402,7 +373,7 @@ export class Session implements SessionContext {
}
const chat = this.config.getGeminiClient()!.getChat();
const apiHistory = chat.getHistoryShallow();
const apiHistory = chat.getHistory();
const apiTruncateIndex = this.#computeApiTruncationIndexForUserTurn(
apiHistory,
targetTurnIndex,
@ -895,10 +866,16 @@ export class Session implements SessionContext {
return { stopReason: 'end_turn' };
}
// Extract last model text without cloning the full history.
// Get response text from the chat history
const history = this.#getCurrentChat().getHistory();
const lastModelMessage = history
.filter((msg: Content) => msg.role === 'model')
.pop();
const responseText =
this.#getCurrentChat().getLastModelMessageText?.() ||
'[no response text]';
lastModelMessage?.parts
?.filter((p: Part): p is { text: string } & Part => 'text' in p)
.map((p: { text: string }) => p.text)
.join('') || '[no response text]';
const response = await messageBus.request<
HookExecutionRequest,
@ -1143,12 +1120,8 @@ export class Session implements SessionContext {
compressionInfo = compressed;
this.#recordCompressionTokenCount(compressed);
if (compressed.compressionStatus === CompressionStatus.COMPRESSED) {
const reasonClause =
compressed.triggerReason === 'image_overflow'
? `accumulated enough tool screenshots to trigger compaction for ${this.config.getModel()}`
: `approached the input token limit for ${this.config.getModel()}`;
compressionDiagnostic =
`IMPORTANT: This conversation ${reasonClause}. ` +
`IMPORTANT: This conversation approached the input token limit for ${this.config.getModel()}. ` +
`A compressed context will be sent for future messages (compressed from: ` +
`${compressed.originalTokenCount ?? 'unknown'} to ` +
`${compressed.newTokenCount ?? 'unknown'} tokens).`;
@ -2007,15 +1980,6 @@ export class Session implements SessionContext {
this.config,
denialState,
);
await fireSessionPermissionDeniedForAutoMode(
this.config,
decision,
outcome,
fc.name,
toolParams,
callId,
abortSignal,
);
switch (outcome.kind) {
case 'approved':
autoModeAllowed = true;

View File

@ -165,7 +165,7 @@ export function validateAuthMethod(
authMethod: string,
config?: Config,
): string | null {
const settings = loadSettings(process.cwd(), false);
const settings = loadSettings();
loadEnvironment(settings.merged);
if (authMethod === AuthType.USE_OPENAI) {

View File

@ -56,8 +56,6 @@ import {
SETTINGS_VERSION,
SETTINGS_VERSION_KEY,
resetHomeEnvBootstrapForTesting,
ENV_CORRUPTED_PATH,
ENV_WAS_RECOVERED,
} from './settings.js';
import { needsMigration } from './migration/index.js';
import { QWEN_DIR } from '@qwen-code/qwen-code-core';
@ -110,7 +108,6 @@ vi.mock('node:fs', async (importOriginal) => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
renameSync: vi.fn(),
copyFileSync: vi.fn(),
mkdirSync: vi.fn(),
statSync: vi.fn(() => ({ isDirectory: () => false, isFile: () => true })),
realpathSync: (p: string) => p,
@ -129,7 +126,6 @@ vi.mock('fs', async (importOriginal) => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
renameSync: vi.fn(),
copyFileSync: vi.fn(),
mkdirSync: vi.fn(),
statSync: vi.fn(() => ({ isDirectory: () => false, isFile: () => true })),
realpathSync: (p: string) => p,
@ -1878,18 +1874,19 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result).toBeDefined();
// Verify the corrupted file was copied to .corrupted
const copyCalls = (fs.copyFileSync as Mock).mock.calls;
const corruptedCopy = copyCalls.find(
// Verify the corrupted file was renamed with timestamp suffix
const renameCalls = (fs.renameSync as Mock).mock.calls;
const corruptedRename = renameCalls.find(
(call: unknown[]) =>
call[0] === USER_SETTINGS_PATH &&
String(call[1]).includes('.corrupted'),
String(call[1]).includes('.corrupted.'),
);
expect(corruptedCopy).toBeDefined();
expect(corruptedRename).toBeDefined();
// Corrupted dialog is driven by corruptedPath, not by migrationWarnings
expect(result.corruptedPath).toBe(`${USER_SETTINGS_PATH}.corrupted`);
expect(result.wasRecovered).toBe(false);
// Verify migrationWarnings contains recovery message
const warnings = getSettingsWarnings(result);
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(true);
expect(warnings.some((w) => w.includes('renamed'))).toBe(true);
vi.restoreAllMocks();
});
@ -1922,8 +1919,11 @@ describe('Settings Loading and Merging', () => {
);
expect(restoreWrite).toBeDefined();
// Recovery is communicated via wasRecovered flag, not migrationWarnings
expect(result.wasRecovered).toBe(true);
// Verify migrationWarnings informs user about recovery
const warnings = getSettingsWarnings(result);
expect(warnings.some((w) => w.includes('recovered from backup'))).toBe(
true,
);
vi.restoreAllMocks();
});
@ -1954,27 +1954,20 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result).toBeDefined();
expect(result.corruptedPath).toBe(`${USER_SETTINGS_PATH}.corrupted`);
expect(result.wasRecovered).toBe(false);
const resetWrites = (fs.writeFileSync as Mock).mock.calls.filter(
(call: unknown[]) => call[0] === USER_SETTINGS_PATH && call[1] === '{}',
);
expect(resetWrites.length).toBeGreaterThan(0);
// Verify the corrupted file was copied to .corrupted
const copyCalls = (fs.copyFileSync as Mock).mock.calls;
// Verify the corrupted file was renamed
const renameCalls = (fs.renameSync as Mock).mock.calls;
expect(
copyCalls.some(
renameCalls.some(
(call: unknown[]) =>
call[0] === USER_SETTINGS_PATH &&
String(call[1]).includes('.corrupted'),
String(call[1]).includes('.corrupted.'),
),
).toBe(true);
vi.restoreAllMocks();
});
it('should start with empty settings when copy of corrupted file fails', () => {
it('should start with empty settings when rename of corrupted file fails', () => {
const invalidJsonContent = 'invalid json';
(mockFsExistsSync as Mock).mockImplementation((p: fs.PathLike) => {
@ -1990,8 +1983,8 @@ describe('Settings Loading and Merging', () => {
},
);
// Simulate copy failure (e.g., permission denied)
(fs.copyFileSync as Mock).mockImplementation(() => {
// Simulate rename failure (e.g., permission denied)
(fs.renameSync as Mock).mockImplementation(() => {
throw new Error('EACCES: permission denied');
});
@ -1999,11 +1992,11 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result).toBeDefined();
// Corruption warning no longer goes through migrationWarnings —
// copy failed so corruptedPath is undefined too
// Verify the warning message does NOT say "renamed" since rename failed,
// but instead tells user to fix the file manually.
const warnings = getSettingsWarnings(result);
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(false);
expect(result.corruptedPath).toBeUndefined();
expect(warnings.some((w) => w.includes('fix the JSON'))).toBe(true);
expect(warnings.some((w) => w.includes('renamed to'))).toBe(false);
vi.restoreAllMocks();
});
@ -2024,111 +2017,19 @@ describe('Settings Loading and Merging', () => {
const result = loadSettings(MOCK_WORKSPACE_DIR);
const warnings = getSettingsWarnings(result);
// Corruption warning no longer goes through migrationWarnings —
// it is emitted via settings.corruptedPath check in gemini.tsx
// early stderr path instead. Verify corruptedPath is set.
expect(result.corruptedPath).toBeDefined();
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(false);
// Warnings must be non-empty so the early stderr loop in gemini.tsx
// (before relaunchAppInChildProcess) actually emits something.
expect(warnings.length).toBeGreaterThan(0);
// Each warning should be a human-readable string suitable for stderr
for (const w of warnings) {
expect(typeof w).toBe('string');
expect(w.length).toBeGreaterThan(0);
}
expect(warnings.some((w) => w.includes('invalid JSON'))).toBe(true);
vi.restoreAllMocks();
});
describe('corruption env var propagation', () => {
afterEach(() => {
delete process.env[ENV_CORRUPTED_PATH];
delete process.env[ENV_WAS_RECOVERED];
});
it('should propagate corruptedPath/wasRecovered from env vars', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '1';
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result.corruptedPath).toBe(`${USER_SETTINGS_PATH}.corrupted`);
expect(result.wasRecovered).toBe(true);
});
it('should delete env vars after reading so subsequent calls do not re-trigger', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '0';
loadSettings(MOCK_WORKSPACE_DIR);
expect(process.env[ENV_CORRUPTED_PATH]).toBeUndefined();
expect(process.env[ENV_WAS_RECOVERED]).toBeUndefined();
});
it('should only consume env vars for SettingScope.User', () => {
(mockFsExistsSync as Mock).mockImplementation((p: fs.PathLike) => {
const s = p.toString();
return s === USER_SETTINGS_PATH || s === MOCK_WORKSPACE_SETTINGS_PATH;
});
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '1';
const result = loadSettings(MOCK_WORKSPACE_DIR);
// env vars consumed in User scope — scope guard exercised
expect(process.env[ENV_CORRUPTED_PATH]).toBeUndefined();
expect(process.env[ENV_WAS_RECOVERED]).toBeUndefined();
expect(result.corruptedPath).toBeDefined();
});
it('should map wasRecovered="0" to false', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '0';
const result = loadSettings(MOCK_WORKSPACE_DIR);
expect(result.wasRecovered).toBe(false);
});
it('should not consume env vars when consumeCorruptionEnvVars=false', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = `${USER_SETTINGS_PATH}.corrupted`;
process.env[ENV_WAS_RECOVERED] = '1';
loadSettings(MOCK_WORKSPACE_DIR, false);
// env vars should remain untouched so child processes can still read them
expect(process.env[ENV_CORRUPTED_PATH]).toBe(
`${USER_SETTINGS_PATH}.corrupted`,
);
expect(process.env[ENV_WAS_RECOVERED]).toBe('1');
});
it('should reject mismatched ENV_CORRUPTED_PATH', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
(fs.readFileSync as Mock).mockImplementation(() => '{}');
process.env[ENV_CORRUPTED_PATH] = '/some/other/path.corrupted';
process.env[ENV_WAS_RECOVERED] = '1';
const result = loadSettings(MOCK_WORKSPACE_DIR);
// Guard rejected — corruptedPath not propagated
expect(result.corruptedPath).toBeUndefined();
// Env vars not consumed because guard failed
expect(process.env[ENV_CORRUPTED_PATH]).toBe(
'/some/other/path.corrupted',
);
});
});
it('should resolve environment variables in user settings', () => {
process.env['TEST_API_KEY'] = 'user_api_key_from_env';
const userSettingsContent: TestSettings = {
@ -2275,256 +2176,6 @@ describe('Settings Loading and Merging', () => {
delete process.env['SHARED_VAR'];
});
it('should resolve ${VAR} in settings from home-level .env file (#4466)', () => {
const homeQwenEnvPath = path.join(
path.dirname(USER_SETTINGS_PATH),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${MY_SECRET_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === homeQwenEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === homeQwenEnvPath)
return 'MY_SECRET_TOKEN=secret_from_dotenv';
return '{}';
},
);
delete process.env['MY_SECRET_TOKEN'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer secret_from_dotenv',
);
delete process.env['MY_SECRET_TOKEN'];
});
it('should not override process.env values with home .env file (#4466)', () => {
const homeQwenEnvPath = path.join(
path.dirname(USER_SETTINGS_PATH),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${MY_SECRET_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === homeQwenEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === homeQwenEnvPath) return 'MY_SECRET_TOKEN=from_dotenv';
return '{}';
},
);
process.env['MY_SECRET_TOKEN'] = 'from_process_env';
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer from_process_env',
);
delete process.env['MY_SECRET_TOKEN'];
});
it('should not search dirname(qwenDir)/.env when QWEN_HOME is set (#4466)', () => {
const customHome = '/custom/qwen/home';
process.env['QWEN_HOME'] = customHome;
const customSettingsPath = path.join(customHome, 'settings.json');
const dirnameEnvPath = path.join(path.dirname(customHome), '.env');
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${MY_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === customSettingsPath || p === dirnameEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === customSettingsPath)
return JSON.stringify(userSettingsContent);
if (p === dirnameEnvPath) return 'MY_TOKEN=should_not_be_found';
return '{}';
},
);
delete process.env['MY_TOKEN'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer ${MY_TOKEN}',
);
delete process.env['MY_TOKEN'];
delete process.env['QWEN_HOME'];
});
it('should resolve ${VAR} from ~/.env when QWEN_HOME is not set (#4466)', () => {
const homeEnvPath = path.join(
path.dirname(path.dirname(USER_SETTINGS_PATH)),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${HOME_ENV_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === homeEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === homeEnvPath) return 'HOME_ENV_TOKEN=from_home_env';
return '{}';
},
);
delete process.env['HOME_ENV_TOKEN'];
delete process.env['QWEN_HOME'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer from_home_env',
);
delete process.env['HOME_ENV_TOKEN'];
});
it('should prefer ~/.qwen/.env over ~/.env for the same key (first-write-wins) (#4466)', () => {
const qwenEnvPath = path.join(path.dirname(USER_SETTINGS_PATH), '.env');
const homeEnvPath = path.join(
path.dirname(path.dirname(USER_SETTINGS_PATH)),
'.env',
);
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${PRECEDENCE_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) =>
p === USER_SETTINGS_PATH || p === qwenEnvPath || p === homeEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === qwenEnvPath) return 'PRECEDENCE_TOKEN=from_qwen_dir';
if (p === homeEnvPath) return 'PRECEDENCE_TOKEN=from_home_dir';
return '{}';
},
);
delete process.env['PRECEDENCE_TOKEN'];
delete process.env['QWEN_HOME'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer from_qwen_dir',
);
delete process.env['PRECEDENCE_TOKEN'];
});
it('should succeed with unresolved placeholder when .env read throws (#4466)', () => {
const qwenEnvPath = path.join(path.dirname(USER_SETTINGS_PATH), '.env');
const userSettingsContent = {
mcpServers: {
myServer: {
headers: {
Authorization: 'Bearer ${ERROR_TOKEN}',
},
},
},
};
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH || p === qwenEnvPath,
);
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(userSettingsContent);
if (p === qwenEnvPath) throw new Error('EACCES: permission denied');
return '{}';
},
);
delete process.env['ERROR_TOKEN'];
const settings = loadSettings(MOCK_WORKSPACE_DIR);
const mcpServers = settings.merged.mcpServers as Record<
string,
{ headers?: Record<string, string> }
>;
expect(mcpServers?.['myServer']?.headers?.['Authorization']).toBe(
'Bearer ${ERROR_TOKEN}',
);
delete process.env['ERROR_TOKEN'];
});
it('should correctly merge dnsResolutionOrder with workspace taking precedence', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
const userSettingsContent = {

View File

@ -73,22 +73,12 @@ export function getUserSettingsDir(): string {
}
export const DEFAULT_EXCLUDED_ENV_VARS = ['DEBUG', 'DEBUG_MODE'];
// Env var names used for inter-process communication of corruption state.
// Defined as constants to avoid duplicated string literals.
export const ENV_CORRUPTED_PATH = 'QWEN_CODE_SETTINGS_CORRUPTED_PATH';
export const ENV_WAS_RECOVERED = 'QWEN_CODE_SETTINGS_WAS_RECOVERED';
// QWEN_HOME and QWEN_RUNTIME_DIR control where global state (settings, OAuth
// credentials, installation IDs, etc.) is written. A project `.env` must never
// redirect these — that would split global state between the real home and a
// project-controlled directory. Always excluded from project .env files,
// regardless of user-configurable `advanced.excludedEnvVars`.
const PROJECT_ENV_HARDCODED_EXCLUSIONS = [
'QWEN_HOME',
'QWEN_RUNTIME_DIR',
ENV_CORRUPTED_PATH,
ENV_WAS_RECOVERED,
];
const PROJECT_ENV_HARDCODED_EXCLUSIONS = ['QWEN_HOME', 'QWEN_RUNTIME_DIR'];
// Settings version to track migration state
export const SETTINGS_VERSION = 4;
@ -406,8 +396,6 @@ export class LoadedSettings {
isTrusted: boolean,
migratedInMemorScopes: Set<SettingScope>,
migrationWarnings: string[] = [],
corruptedPath: string | undefined = undefined,
wasRecovered: boolean = false,
) {
this.system = system;
this.systemDefaults = systemDefaults;
@ -416,8 +404,6 @@ export class LoadedSettings {
this.isTrusted = isTrusted;
this.migratedInMemorScopes = migratedInMemorScopes;
this.migrationWarnings = migrationWarnings;
this.corruptedPath = corruptedPath;
this.wasRecovered = wasRecovered;
this._merged = this.computeMergedSettings();
}
@ -428,9 +414,6 @@ export class LoadedSettings {
readonly isTrusted: boolean;
readonly migratedInMemorScopes: Set<SettingScope>;
readonly migrationWarnings: string[];
readonly corruptedPath: string | undefined;
readonly wasRecovered: boolean;
corruptionDialogDismissed: boolean = false;
private _merged: Settings;
@ -516,8 +499,6 @@ export function createMinimalSettings(): LoadedSettings {
false,
new Set(),
[],
undefined,
false,
);
}
@ -616,50 +597,6 @@ export function resetHomeEnvBootstrapForTesting(): void {
homeEnvBootstrapped = false;
}
/**
* Collects environment variables from user-level `.env` files and returns
* them as a plain dictionary **without** mutating `process.env`.
*
* Candidates are iterated most-specific-first (`~/.qwen/.env` before
* `~/.env`). `??=` ensures the first file to define a key wins, matching
* dotenv's first-occurrence-wins semantics used elsewhere.
*
* Note: this dict intentionally does NOT filter PROJECT_ENV_HARDCODED_EXCLUSIONS
* or advanced.excludedEnvVars — substitution scope is narrower than process.env
* population handled by preResolveHomeEnvOverrides / readHomeEnvInto.
*/
function getHomeEnvFallbackVars(): Record<string, string> {
const globalQwenDir = Storage.getGlobalQwenDir();
const candidates = [path.join(globalQwenDir, '.env')];
// When QWEN_HOME is set, skip ~/.env to avoid surprise cross-contamination
// from a shared home .env. getUserLevelEnvPaths() always includes ~/.env
// because loadEnvironment() populates process.env independently — the two
// scopes are intentionally different.
if (!process.env['QWEN_HOME']) {
candidates.push(path.join(path.dirname(globalQwenDir), '.env'));
}
const result: Record<string, string> = {};
for (const candidate of candidates) {
if (!fs.existsSync(candidate)) {
continue;
}
try {
const parsed = dotenv.parse(fs.readFileSync(candidate, 'utf-8'));
for (const key in parsed) {
if (Object.hasOwn(parsed, key) && !Object.hasOwn(process.env, key)) {
result[key] ??= parsed[key]!;
}
}
} catch (e) {
debugLogger.warn(
`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`,
);
}
}
return result;
}
/**
* Surfaces a one-shot warning when QWEN_HOME has been redirected but the
* user hasn't migrated their existing global state. Auto-copying OAuth
@ -867,15 +804,12 @@ export function loadEnvironment(settings: Settings): void {
}
}
export const CORRUPTED_SUFFIX = '.corrupted';
/**
* Load and merge settings from all scopes:
* System Defaults → User (~/.qwen/settings.json) → Workspace → System.
* Loads settings from user and workspace directories.
* Project settings override user settings.
*/
export function loadSettings(
workspaceDir: string = process.cwd(),
consumeCorruptionEnvVars: boolean = true,
): LoadedSettings {
// Apply any QWEN_HOME / QWEN_RUNTIME_DIR set in user-level `.env` files
// BEFORE any code reads a path derived from them. After this call, the
@ -917,48 +851,17 @@ export function loadSettings(
const loadAndMigrate = (
filePath: string,
scope: SettingScope,
): {
settings: Settings;
rawJson?: string;
migrationWarnings?: string[];
corruptedPath?: string;
wasRecovered?: boolean;
} => {
): { settings: Settings; rawJson?: string; migrationWarnings?: string[] } => {
try {
if (fs.existsSync(filePath)) {
let content = fs.readFileSync(filePath, 'utf-8');
let rawSettings: unknown;
// Carry corruption state through to the final return so it
// can be attached after the migration pipeline runs.
const corruptedPath = `${filePath}${CORRUPTED_SUFFIX}`;
let corruptedSaved = false;
let recoveredFromBackup = false;
let recoveredFromEnvVar: boolean | null = null;
let recoveryWarning: string | undefined;
try {
rawSettings = JSON.parse(stripJsonComments(content));
} catch (parseError: unknown) {
// ===== JSON parse failed — enter corruption recovery =====
// Strategy: save corrupted file as .corrupted → recover from .orig →
// show dialog in UI. Never crash due to a corrupted settings file.
// Step 1: copy corrupted file to .corrupted for reference
// MUST guarantee .corrupted exists so onExit can restore it.
// Use copy (not rename) — the file must stay on disk so that
// child processes spawned by relaunchAppInChildProcess() can
// enter the existsSync block where env-var propagation is
// checked. Step 2 will overwrite it with .orig if available.
try {
fs.copyFileSync(filePath, corruptedPath);
corruptedSaved = true;
} catch (copyError) {
debugLogger.warn(
`Failed to copy corrupted file: ${getErrorMessage(copyError)}`,
);
}
// Step 2: try recovering from .orig backup (created on each write)
// JSON parse failed — try to recover from .orig backup
const backupPath = `${filePath}.orig`;
if (fs.existsSync(backupPath)) {
debugLogger.warn(
@ -969,63 +872,43 @@ export function loadSettings(
const backupSettings = JSON.parse(
stripJsonComments(backupContent),
);
// Backup valid — overwrite with backup to restore last good state
// Backup is valid — restore it
fs.writeFileSync(filePath, backupContent, 'utf-8');
content = backupContent;
rawSettings = backupSettings;
const recoveryMsg = `Settings file ${filePath} had invalid JSON and was recovered from backup ${backupPath}. Some recent settings changes may have been lost.`;
debugLogger.warn(recoveryMsg);
recoveredFromBackup = true;
// Surface warning to user so they know settings were rolled back
recoveryWarning = recoveryMsg;
} catch (backupError) {
// Backup also corrupted — give up recovery
// Could be invalid JSON, read error, or write-back failure
debugLogger.warn(
`Failed to recover from backup ${backupPath}: ${getErrorMessage(backupError)}. Falling back to empty settings.`,
);
}
}
// Step 3: no backup available — start with empty settings
// No valid backup available — rename the corrupted file so the app
// can start with empty settings rather than crashing.
if (!rawSettings) {
const warningMsg = `Settings file ${filePath} has invalid JSON. Your settings have been reset.`;
debugLogger.warn(warningMsg);
if (corruptedSaved) {
// Clear the original file so the settings UI shows empty settings
// instead of the corrupted content.
try {
fs.writeFileSync(filePath, '{}', 'utf-8');
} catch {
/* ignore — settings are already empty in memory */
}
const corruptedPath = `${filePath}.corrupted.${Date.now()}`;
let warningMsg: string;
try {
fs.renameSync(filePath, corruptedPath);
warningMsg = `Settings file ${filePath} has invalid JSON and was renamed to ${corruptedPath}. Your settings have been reset. To recover, fix the JSON in ${corruptedPath} and rename it back.`;
} catch (renameError) {
// If rename fails, still proceed with empty settings
debugLogger.error(
`Failed to rename corrupted settings file: ${getErrorMessage(renameError)}`,
);
warningMsg = `Settings file ${filePath} has invalid JSON. Your settings have been reset. Please fix the JSON in ${filePath} manually.`;
}
debugLogger.warn(warningMsg);
return {
settings: {},
migrationWarnings: [],
corruptedPath: corruptedSaved ? corruptedPath : undefined,
wasRecovered: false,
migrationWarnings: [warningMsg],
};
}
// Fall through to migration pipeline — .orig backup may be in
// an older schema and needs to go through runMigrations.
}
// Propagate corruption state from parent process via env vars.
// relaunchAppInChildProcess() spawns a child that re-reads
// settings.json (already valid after parent recovered it). The
// env vars preserve the corruption marker across the boundary.
// Only apply to user scope since that's where corruption is detected.
// Clear env vars after reading so subsequent loadSettings calls
// don't re-trigger this path.
const envCorruptedPath = process.env[ENV_CORRUPTED_PATH];
if (
consumeCorruptionEnvVars &&
envCorruptedPath &&
envCorruptedPath === corruptedPath &&
scope === SettingScope.User
) {
corruptedSaved = true;
recoveredFromEnvVar = process.env[ENV_WAS_RECOVERED] === '1';
delete process.env[ENV_CORRUPTED_PATH];
delete process.env[ENV_WAS_RECOVERED];
}
if (
@ -1070,10 +953,6 @@ export function loadSettings(
}
};
// Execute migrations even on recovered settings — the migrated data
// must persist. The disk-write branches below (version normalization)
// are guarded by !corruptedSaved to avoid creating .orig backups
// of freshly-reset settings.
if (needsMigration(settingsObject)) {
const migrationResult = runMigrations(settingsObject, scope);
if (migrationResult.executedMigrations.length > 0) {
@ -1083,10 +962,7 @@ export function loadSettings(
>;
migrationWarnings = migrationResult.warnings;
persistSettingsObject('Error migrating settings file on disk');
} else if (
(hasLegacyNumericVersion || hasInvalidVersion) &&
!corruptedSaved
) {
} else if (hasLegacyNumericVersion || hasInvalidVersion) {
// Migration was deemed needed but nothing executed. Normalize version metadata
// to avoid repeated no-op checks on startup.
settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
@ -1096,30 +972,28 @@ export function loadSettings(
persistSettingsObject('Error normalizing settings version on disk');
}
} else if (
(!hasVersionKey || hasInvalidVersion || hasLegacyNumericVersion) &&
!corruptedSaved
!hasVersionKey ||
hasInvalidVersion ||
hasLegacyNumericVersion
) {
// No migration needed/executable, but version metadata is missing or invalid.
// Normalize it to current version to avoid repeated startup work.
// Skip if we just recovered from corruption — the next startup will
// handle normalization, avoiding an unnecessary writeWithBackupSync
// that would create a .orig file from the freshly reset settings.
settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
persistSettingsObject('Error normalizing settings version on disk');
}
// Attach corruption state if settings were recovered from backup
const result: ReturnType<typeof loadAndMigrate> = {
// Prepend recovery warning if settings were restored from backup
const allWarnings = [
...(recoveryWarning ? [recoveryWarning] : []),
...(migrationWarnings ?? []),
];
return {
settings: settingsObject as Settings,
rawJson: content,
migrationWarnings: migrationWarnings ?? [],
migrationWarnings:
allWarnings.length > 0 ? allWarnings : migrationWarnings,
};
if (corruptedSaved) {
result.corruptedPath = corruptedPath;
result.wasRecovered =
recoveredFromBackup || (recoveredFromEnvVar ?? false);
}
return result;
}
} catch (error: unknown) {
settingsErrors.push({
@ -1159,25 +1033,11 @@ export function loadSettings(
const userOriginalSettings = structuredClone(userResult.settings);
const workspaceOriginalSettings = structuredClone(workspaceResult.settings);
// Resolve ${VAR} placeholders in settings using home .env as fallback.
// getHomeEnvFallbackVars() excludes keys already in process.env, so
// effective precedence is: process.env > home .env > unresolved placeholder.
// The resolver checks customEnv before process.env, but since customEnv
// never contains a process.env key, process.env always wins.
const homeEnvFallback = getHomeEnvFallbackVars();
systemSettings = resolveEnvVarsInObject(
systemResult.settings,
homeEnvFallback,
);
systemDefaultSettings = resolveEnvVarsInObject(
systemDefaultsResult.settings,
homeEnvFallback,
);
userSettings = resolveEnvVarsInObject(userResult.settings, homeEnvFallback);
workspaceSettings = resolveEnvVarsInObject(
workspaceResult.settings,
homeEnvFallback,
);
// Environment variables for runtime use
systemSettings = resolveEnvVarsInObject(systemResult.settings);
systemDefaultSettings = resolveEnvVarsInObject(systemDefaultsResult.settings);
userSettings = resolveEnvVarsInObject(userResult.settings);
workspaceSettings = resolveEnvVarsInObject(workspaceResult.settings);
// Support legacy theme names
if (userSettings.ui?.theme === 'VS') {
@ -1262,8 +1122,6 @@ export function loadSettings(
isTrusted,
migratedInMemorScopes,
allMigrationWarnings,
userResult.corruptedPath,
userResult.wasRecovered ?? false,
);
}

View File

@ -29,8 +29,6 @@ import * as cliConfig from './config/config.js';
import { loadCliConfig, parseArguments } from './config/config.js';
import type { DnsResolutionOrder, LoadedSettings } from './config/settings.js';
import {
ENV_CORRUPTED_PATH,
ENV_WAS_RECOVERED,
createMinimalSettings,
getSettingsWarnings,
loadSettings,
@ -107,11 +105,6 @@ import { installSynchronizedOutput } from './ui/utils/synchronizedOutput.js';
const debugLogger = createDebugLogger('STARTUP');
function clearCorruptionEnvVars(): void {
delete process.env[ENV_CORRUPTED_PATH];
delete process.env[ENV_WAS_RECOVERED];
}
export function validateDnsResolutionOrder(
order: string | undefined,
): DnsResolutionOrder {
@ -337,13 +330,13 @@ export async function startInteractiveUI(
<VimModeProvider settings={settings}>
<AgentViewProvider config={config}>
<BackgroundTaskViewProvider config={config}>
<AppContainer
config={config}
settings={settings}
startupWarnings={startupWarnings}
version={version}
initializationResult={initializationResult}
/>
<AppContainer
config={config}
settings={settings}
startupWarnings={startupWarnings}
version={version}
initializationResult={initializationResult}
/>
</BackgroundTaskViewProvider>
</AgentViewProvider>
</VimModeProvider>
@ -434,19 +427,10 @@ export async function main() {
process.env[QWEN_CODE_SIMPLE_ENV_VAR] = '1';
}
// Load user settings — bare mode uses minimal config, normal mode loads full.
const settings = isBareMode(argv.bare)
? createMinimalSettings()
: loadSettings();
// Propagate corruption state to child process via env vars so
// relaunchAppInChildProcess() doesn't lose the marker.
if (settings.corruptedPath) {
process.env[ENV_CORRUPTED_PATH] = settings.corruptedPath;
process.env[ENV_WAS_RECOVERED] = settings.wasRecovered ? '1' : '0';
}
await cleanupCheckpoints();
// Performance checkpoint
profileCheckpoint('after_load_settings');
// Emit settings warnings early so the parent process surfaces them
@ -456,15 +440,6 @@ export async function main() {
for (const warning of settingsWarnings) {
writeStderrLine(warning);
}
// Corruption notification no longer goes through migrationWarnings —
// check corruptedPath directly to keep stderr visible in relaunch.
if (settings.corruptedPath) {
writeStderrLine(
'Warning: Settings file had invalid JSON and was reset. ' +
'A copy of the corrupted file has been saved at: ' +
settings.corruptedPath,
);
}
// Check for invalid input combinations early to prevent crashes
if (argv.promptInteractive && !process.stdin.isTTY) {
@ -619,9 +594,7 @@ export async function main() {
} else {
// Relaunch app so we always have a child process that can be internally
// restarted if needed.
await relaunchAppInChildProcess(memoryArgs, [], {
afterSpawn: clearCorruptionEnvVars,
});
await relaunchAppInChildProcess(memoryArgs, []);
}
}
@ -982,16 +955,9 @@ export async function main() {
process.cwd(),
initializationResult!,
);
// Clean up corruption env vars so subsequent relaunch children
// and subprocesses don't inherit stale state.
clearCorruptionEnvVars();
return;
}
// Also clean up env vars for non-interactive paths so that
// subprocesses don't inherit stale state.
clearCorruptionEnvVars();
// Non-interactive: defer finalize until after `config.initialize()` runs
// so MCP discovery events (mcp_first_tool_registered, mcp_all_servers_settled,
// gemini_tools_updated) are captured in the profile.

View File

@ -1898,6 +1898,8 @@ export default {
'Open the memory manager.': 'Open the memory manager.',
'Show current process memory diagnostics':
'Show current process memory diagnostics',
'Record a CPU profile for Chrome DevTools analysis':
'Record a CPU profile for Chrome DevTools analysis',
'Save a durable memory to the memory system.':
'Save a durable memory to the memory system.',
'Ask a quick side question without affecting the main conversation':

View File

@ -1485,6 +1485,8 @@ export default {
// === Core: added from PR #3328 ===
'Open the memory manager.': '打開記憶管理器。',
'Show current process memory diagnostics': '顯示目前程序的內存診斷。',
'Record a CPU profile for Chrome DevTools analysis':
'錄製 CPU 效能分析檔案,用於 Chrome DevTools 分析',
'Save a durable memory to the memory system.': '將持久記憶保存到記憶系統。',
'Ask a quick side question without affecting the main conversation':
'在不影響主對話的情況下快速提問旁支問題',

View File

@ -1720,6 +1720,8 @@ export default {
'Loading suggestions...': '正在加载建议...',
'Open the memory manager.': '打开记忆管理器。',
'Show current process memory diagnostics': '显示当前进程的内存诊断。',
'Record a CPU profile for Chrome DevTools analysis':
'录制 CPU 性能分析文件,用于 Chrome DevTools 分析',
'Save a durable memory to the memory system.':
'将一条持久记忆保存到记忆系统。',
'Show per-item context usage breakdown.': '显示按项目划分的上下文使用详情。',

View File

@ -38,8 +38,6 @@ import type {
import { createDaemonStatusProvider } from './daemonStatusProvider.js';
import {
createHttpAcpBridge,
detachSessionIdFromEntryChannel,
findChannelInfoForEntry,
InvalidClientIdError,
InvalidPermissionOptionError,
InvalidSessionMetadataError,
@ -301,56 +299,6 @@ function makeChannel(opts: FakeAgentOpts = {}): ChannelHandle {
}
describe('createHttpAcpBridge', () => {
it('selects a session entry channel when the current attach channel has changed', () => {
// Model the channel-overlap window directly: old channel A still has
// an entry, while new channel B is the current attach target.
const channelA = { name: 'A' };
const channelB = { name: 'B' };
const infoA = { channel: channelA, label: 'old-dying-channel' };
const infoB = { channel: channelB, label: 'fresh-attach-channel' };
expect(
findChannelInfoForEntry(infoB, [infoA, infoB], {
channel: channelA,
}),
).toBe(infoA);
expect(
findChannelInfoForEntry(infoB, [infoB], {
channel: channelA,
}),
).toBeUndefined();
});
it('detaches a session from its entry channel during channel overlap', () => {
// Model the close/kill overlap window directly: old channel A still owns
// the session entry while fresh channel B is the current attach target.
// The detach helper used by closeSession/killSession must decrement A,
// not the current B channel.
const channelA = { name: 'A' };
const channelB = { name: 'B' };
const infoA = {
channel: channelA,
sessionIds: new Set(['session-a']),
label: 'old-dying-channel',
};
const infoB = {
channel: channelB,
sessionIds: new Set(['session-b']),
label: 'fresh-attach-channel',
};
const selected = detachSessionIdFromEntryChannel(
infoB,
[infoA, infoB],
{ channel: channelA },
'session-a',
);
expect(selected).toBe(infoA);
expect(infoA.sessionIds.has('session-a')).toBe(false);
expect(Array.from(infoB.sessionIds)).toEqual(['session-b']);
});
it('accepts a valid BridgeOptions.eventRingSize at construction time', () => {
// Smoke: positive finite integers are accepted; the underlying
// EventBus ring-size threading is exercised end-to-end in
@ -5892,37 +5840,6 @@ describe('createHttpAcpBridge', () => {
await bridge.shutdown();
});
it('keeps a shared ACP channel alive while closing one of several sessions', async () => {
const handles: ChannelHandle[] = [];
const factory: ChannelFactory = async () => {
const h = makeChannel({ sessionIdPrefix: `s${handles.length}` });
handles.push(h);
return h.channel;
};
const bridge = makeBridge({
channelFactory: factory,
sessionScope: 'thread',
});
const a = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const b = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const c = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
expect(handles).toHaveLength(1);
await bridge.closeSession(b.sessionId);
expect(bridge.sessionCount).toBe(2);
expect(handles[0]?.killed).toBe(false);
await bridge.closeSession(a.sessionId);
expect(bridge.sessionCount).toBe(1);
expect(handles[0]?.killed).toBe(false);
await bridge.closeSession(c.sessionId);
expect(bridge.sessionCount).toBe(0);
expect(handles[0]?.killed).toBe(true);
await bridge.shutdown();
});
it('throws SessionNotFoundError for unknown session', async () => {
const bridge = makeBridge();
await expect(bridge.closeSession('nonexistent')).rejects.toThrow(

View File

@ -278,33 +278,6 @@ interface ChannelInfo {
isDying: boolean;
}
/** @internal Visible for bridge lifecycle regression tests. */
export function findChannelInfoForEntry<T extends { channel: unknown }>(
current: T | undefined,
alive: Iterable<T>,
entry: { channel: unknown },
): T | undefined {
if (current?.channel === entry.channel) return current;
for (const info of alive) {
if (info.channel === entry.channel) return info;
}
return undefined;
}
/** @internal Visible for bridge lifecycle regression tests. */
export function detachSessionIdFromEntryChannel<
T extends { channel: unknown; sessionIds: Set<string> },
>(
current: T | undefined,
alive: Iterable<T>,
entry: { channel: unknown },
sessionId: string,
): T | undefined {
const info = findChannelInfoForEntry(current, alive, entry);
info?.sessionIds.delete(sessionId);
return info;
}
interface SessionEntry {
sessionId: string;
workspaceCwd: string;
@ -2058,8 +2031,15 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
return channelInfo;
};
const channelInfoForEntry = (entry: SessionEntry): ChannelInfo | undefined =>
findChannelInfoForEntry(channelInfo, aliveChannels, entry);
const channelInfoForEntry = (
entry: SessionEntry,
): ChannelInfo | undefined => {
if (channelInfo?.channel === entry.channel) return channelInfo;
for (const info of aliveChannels) {
if (info.channel === entry.channel) return info;
}
return undefined;
};
const getChannelClosedReject = (info: ChannelInfo): Promise<never> => {
if (!info.statusClosedReject) {
@ -2907,12 +2887,10 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
: ''),
);
if (defaultEntry === entry) defaultEntry = undefined;
const ci = detachSessionIdFromEntryChannel(
channelInfo,
aliveChannels,
entry,
sessionId,
);
const ci = channelInfo;
if (ci && ci.channel === entry.channel) {
ci.sessionIds.delete(sessionId);
}
for (const id of Array.from(entry.pendingPermissionIds)) {
resolvePending(id, { outcome: { outcome: 'cancelled' } });
}
@ -3739,12 +3717,10 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
// Detach from the channel. The channel dies only when its LAST
// session leaves — other sessions on the same channel keep
// running.
const ci = detachSessionIdFromEntryChannel(
channelInfo,
aliveChannels,
entry,
sessionId,
);
const ci = channelInfo;
if (ci && ci.channel === entry.channel) {
ci.sessionIds.delete(sessionId);
}
// PR 14b fix (codex round 5): tombstone the killed sessionId
// so any in-flight `extNotification` from the (about-to-be-
// killed) child can't seed the early-event buffer for a

View File

@ -14,8 +14,6 @@ import {
type UIActions,
} from './contexts/UIActionsContext.js';
import { AgentViewProvider } from './contexts/AgentViewContext.js';
import { SettingsContext } from './contexts/SettingsContext.js';
import type { LoadedSettings } from '../config/settings.js';
import { StreamingState } from './types.js';
vi.mock('ink', async (importOriginal) => {
@ -67,16 +65,9 @@ describe('App', () => {
updateItem: vi.fn(),
clearItems: vi.fn(),
loadHistory: vi.fn(),
truncateToItem: vi.fn(),
},
};
const mockSettings = {
merged: {},
corruptedPath: undefined,
wasRecovered: false,
} as LoadedSettings;
const mockUIActions = {
refreshStatic: vi.fn(),
} as unknown as UIActions;
@ -86,9 +77,7 @@ describe('App', () => {
<UIActionsContext.Provider value={mockUIActions}>
<AgentViewProvider>
<UIStateContext.Provider value={uiState}>
<SettingsContext.Provider value={mockSettings}>
<App />
</SettingsContext.Provider>
<App />
</UIStateContext.Provider>
</AgentViewProvider>
</UIActionsContext.Provider>,

View File

@ -4,87 +4,21 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { useState } from 'react';
import { Box, useIsScreenReaderEnabled } from 'ink';
import { useIsScreenReaderEnabled } from 'ink';
import { useUIState } from './contexts/UIStateContext.js';
import { useSettings } from './contexts/SettingsContext.js';
import { CORRUPTED_SUFFIX } from '../config/settings.js';
import { writeStderrLine } from '../utils/stdioHelpers.js';
import { StreamingContext } from './contexts/StreamingContext.js';
import { QuittingDisplay } from './components/QuittingDisplay.js';
import { SettingsCorruptedDialog } from './components/SettingsCorruptedDialog.js';
import { ScreenReaderAppLayout } from './layouts/ScreenReaderAppLayout.js';
import { DefaultAppLayout } from './layouts/DefaultAppLayout.js';
import fs from 'node:fs';
export const App = () => {
const uiState = useUIState();
const settings = useSettings();
const isScreenReaderEnabled = useIsScreenReaderEnabled();
const [dismissed, setDismissed] = useState(false);
if (uiState.quittingMessages) {
return <QuittingDisplay />;
}
// Render corrupted dialog at the top level, before any other UI
if (settings.corruptedPath && !dismissed) {
return (
<StreamingContext.Provider value={uiState.streamingState}>
<Box marginX={2}>
<SettingsCorruptedDialog
corruptedPath={settings.corruptedPath}
wasRecovered={settings.wasRecovered}
onExit={() => {
if (
settings.corruptedPath &&
fs.existsSync(settings.corruptedPath)
) {
try {
const settingsPath = settings.corruptedPath.slice(
0,
-CORRUPTED_SUFFIX.length,
);
fs.copyFileSync(settings.corruptedPath, settingsPath);
} catch (e) {
writeStderrLine(
`Failed to restore corrupted file: ${e instanceof Error ? e.message : String(e)}`,
);
process.exit(1);
return;
}
try {
fs.unlinkSync(settings.corruptedPath);
} catch (e) {
writeStderrLine(
`Settings restored, but could not remove ${settings.corruptedPath}: ${e instanceof Error ? e.message : String(e)}`,
);
}
}
process.exit(1);
}}
onContinue={() => {
if (
settings.corruptedPath &&
fs.existsSync(settings.corruptedPath)
) {
try {
fs.unlinkSync(settings.corruptedPath);
} catch (e) {
writeStderrLine(
`Could not remove ${settings.corruptedPath}: ${e instanceof Error ? e.message : String(e)}`,
);
}
}
settings.corruptionDialogDismissed = true;
setDismissed(true);
}}
/>
</Box>
</StreamingContext.Provider>
);
}
return (
<StreamingContext.Provider value={uiState.streamingState}>
{isScreenReaderEnabled ? <ScreenReaderAppLayout /> : <DefaultAppLayout />}

View File

@ -2108,9 +2108,10 @@ export const AppContainer = (props: AppContainerProps) => {
const ac = new AbortController();
suggestionAbortRef.current = ac;
// Only clone the tail — full structuredClone of a large resumed session
// causes transient heap peaks that trigger OOM (#4624).
const conversationHistory = geminiClient.getHistoryTail(40, true);
// Use curated history to avoid invalid/empty entries causing API errors
const fullHistory = geminiClient.getChat().getHistory(true);
const conversationHistory =
fullHistory.length > 40 ? fullHistory.slice(-40) : fullHistory;
generatePromptSuggestion(config, conversationHistory, ac.signal, {
enableCacheSharing: settings.merged.ui?.enableCacheSharing === true,
})
@ -2303,8 +2304,7 @@ export const AppContainer = (props: AppContainerProps) => {
isRewindSelectorOpen ||
isDiffDialogOpen ||
bgTasksDialogOpen ||
showWorktreeExitDialog ||
!!(settings.corruptedPath && !settings.corruptionDialogDismissed);
showWorktreeExitDialog;
dialogsVisibleRef.current = dialogsVisible;
const shouldShowStickyTodos =
stickyTodos !== null &&
@ -2463,7 +2463,7 @@ export const AppContainer = (props: AppContainerProps) => {
apiTruncateIndex = computeApiTruncationIndex(
historyManager.history,
userItem.id,
geminiClient.getHistoryShallow(),
geminiClient.getHistory(),
);
if (apiTruncateIndex < 0) {
historyManager.addItem(

View File

@ -176,11 +176,6 @@ describe('btwCommand', () => {
.mockReturnValue([
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
]),
getHistoryTail: vi
.fn()
.mockReturnValue([
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
]),
getChat: vi.fn().mockReturnValue({
getGenerationConfig: vi.fn().mockReturnValue({
systemInstruction: 'You are helpful',
@ -234,10 +229,6 @@ describe('btwCommand', () => {
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
{ role: 'user', parts: [{ text: '请顺便解释一下湿度怎么看' }] },
]),
getHistoryTail: vi.fn().mockReturnValue([
{ role: 'user', parts: [{ text: '杭州天气如何?' }] },
{ role: 'user', parts: [{ text: '请顺便解释一下湿度怎么看' }] },
]),
getChat: vi.fn().mockReturnValue({
getGenerationConfig: vi.fn().mockReturnValue({
systemInstruction: 'live system prompt',

View File

@ -55,7 +55,7 @@ function getBtwCacheSafeParams(
geminiClient &&
typeof geminiClient === 'object' &&
typeof geminiClient.getChat === 'function' &&
typeof geminiClient.getHistoryTail === 'function'
typeof geminiClient.getHistory === 'function'
) {
const chat = geminiClient.getChat();
if (
@ -65,7 +65,12 @@ function getBtwCacheSafeParams(
) {
const generationConfig = chat.getGenerationConfig();
if (generationConfig) {
const history = geminiClient.getHistoryTail(40, true);
const fullHistory = geminiClient.getHistory(true);
const maxHistoryEntries = 40;
const history =
fullHistory.length > maxHistoryEntries
? fullHistory.slice(-maxHistoryEntries)
: fullHistory;
return {
generationConfig,

View File

@ -177,10 +177,14 @@ describe('doctorCommand', () => {
it('should complete memory subcommand names', async () => {
await expect(doctorCommand.completion!(mockContext, '')).resolves.toEqual([
'memory',
'cpu-profile',
]);
await expect(
doctorCommand.completion!(mockContext, 'mem'),
).resolves.toEqual(['memory']);
await expect(
doctorCommand.completion!(mockContext, 'cpu'),
).resolves.toEqual(['cpu-profile']);
await expect(doctorCommand.completion!(mockContext, 'x')).resolves.toEqual(
[],
);
@ -1049,6 +1053,8 @@ describe('doctorCommand', () => {
});
it('should advertise the memory subcommand on the parent doctor argumentHint', () => {
expect(doctorCommand.argumentHint).toBe('[memory] [--sample] [--snapshot]');
expect(doctorCommand.argumentHint).toBe(
'[memory|cpu-profile] [--sample] [--snapshot] [--duration]',
);
});
});

View File

@ -16,6 +16,11 @@ import {
isHighHeapPressure,
writeMemoryHeapSnapshot,
} from '../../utils/memoryDiagnostics.js';
import {
isCpuProfileRecording,
startCpuProfile,
stopCpuProfile,
} from '../../utils/cpuProfiler.js';
import { t } from '../../i18n/index.js';
import {
collectMemoryDiagnostics,
@ -24,7 +29,8 @@ import {
import { formatMemoryUsage } from '../utils/formatters.js';
const MEMORY_SUBCOMMAND = 'memory';
const DOCTOR_SUBCOMMANDS = [MEMORY_SUBCOMMAND] as const;
const CPU_PROFILE_SUBCOMMAND = 'cpu-profile';
const DOCTOR_SUBCOMMANDS = [MEMORY_SUBCOMMAND, CPU_PROFILE_SUBCOMMAND] as const;
function getHeapSnapshotSensitiveDataWarning(): string {
return t(
'Heap snapshot may contain prompts, file contents, tool results, and other sensitive data. Do not share it publicly without reviewing it first.',
@ -49,12 +55,14 @@ export const doctorCommand: SlashCommand = {
},
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
argumentHint: '[memory] [--sample] [--snapshot]',
argumentHint: '[memory|cpu-profile] [--sample] [--snapshot] [--duration]',
examples: [
'/doctor',
'/doctor memory',
'/doctor memory --sample',
'/doctor memory --snapshot',
'/doctor cpu-profile',
'/doctor cpu-profile --duration 10',
],
completion: async (_context, partialArg) => {
const trimmed = partialArg.trimStart();
@ -181,6 +189,10 @@ export const doctorCommand: SlashCommand = {
};
}
if (subCommand === CPU_PROFILE_SUBCOMMAND) {
return cpuProfileDoctorAction(context, subCommandArgs.slice(1).join(' '));
}
if (executionMode === 'interactive') {
context.ui.setPendingItem({
type: 'info',
@ -233,6 +245,16 @@ export const doctorCommand: SlashCommand = {
argumentHint: '[--json] [--sample] [--snapshot]',
action: memoryDoctorAction,
},
{
name: 'cpu-profile',
get description() {
return t('Record a CPU profile for Chrome DevTools analysis');
},
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
argumentHint: '[--duration <seconds>]',
action: cpuProfileDoctorAction,
},
],
};
@ -382,3 +404,179 @@ function formatCoreDiagnostics(diagnostics: MemoryDiagnostics): string {
);
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// /doctor cpu-profile
// ---------------------------------------------------------------------------
const CPU_PROFILE_USAGE_HINT = '/doctor cpu-profile [--duration <seconds>]';
const DEFAULT_CPU_PROFILE_DURATION_SEC = 30;
const MAX_CPU_PROFILE_DURATION_SEC = 300;
async function cpuProfileDoctorAction(
context: CommandContext,
args = '',
): Promise<void | {
type: 'message';
messageType: 'info' | 'error';
content: string;
}> {
const executionMode = context.executionMode ?? 'interactive';
const abortSignal = context.abortSignal;
if (abortSignal?.aborted) return;
const tokens = args.trim().split(/\s+/).filter(Boolean);
// Parse --duration flag
let durationSec = DEFAULT_CPU_PROFILE_DURATION_SEC;
const durationIdx = tokens.indexOf('--duration');
if (durationIdx !== -1) {
const rawVal = tokens[durationIdx + 1];
const val = rawVal ? parseInt(rawVal, 10) : NaN;
if (
!Number.isFinite(val) ||
val < 1 ||
val > MAX_CPU_PROFILE_DURATION_SEC
) {
const errorMsg = `${t('Duration must be between 1 and {max} seconds', { max: String(MAX_CPU_PROFILE_DURATION_SEC) })}. ${t('Usage')}: ${CPU_PROFILE_USAGE_HINT}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: errorMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: errorMsg };
}
durationSec = val;
}
// Validate unknown arguments
const knownTokens = new Set(['--duration']);
const unknown = tokens.filter((token, idx) => {
if (knownTokens.has(token)) return false;
// Skip the value after --duration
if (idx > 0 && tokens[idx - 1] === '--duration') return false;
return true;
});
if (unknown.length > 0) {
const errorMsg = `${t('Unknown argument(s)')}: ${unknown.join(', ')}. ${t('Usage')}: ${CPU_PROFILE_USAGE_HINT}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: errorMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: errorMsg };
}
// Check if already recording
if (isCpuProfileRecording()) {
const errorMsg =
process.platform === 'win32'
? t('CPU profiling is already in progress. Wait for it to complete.')
: t(
'CPU profiling is already in progress. Send SIGUSR1 or wait for it to complete.',
);
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: errorMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: errorMsg };
}
// Start recording
const startResult = await startCpuProfile();
if (!startResult.ok) {
if (executionMode === 'interactive') {
context.ui.addItem(
{ type: 'error', text: startResult.error },
Date.now(),
);
return;
}
return {
type: 'message',
messageType: 'error',
content: startResult.error,
};
}
if (abortSignal?.aborted) {
const abortResult = await stopCpuProfile();
if (abortResult.ok) {
const msg = t('CPU profile aborted early. Profile saved: {path}', {
path: abortResult.filePath,
});
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: msg }, Date.now());
}
} else {
const msg = `${t('CPU profile aborted but failed to stop cleanly')}: ${abortResult.error}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: msg }, Date.now());
}
}
return;
}
// Show progress in interactive mode
if (executionMode === 'interactive') {
context.ui.setPendingItem({
type: 'info',
text: t('Recording CPU profile for {duration}s...', {
duration: String(durationSec),
}),
});
}
// Wait for duration or abort. Timer is NOT unref'd so non-interactive
// mode keeps the process alive for the full recording window.
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, durationSec * 1000);
if (abortSignal) {
abortSignal.addEventListener(
'abort',
() => {
clearTimeout(timer);
resolve();
},
{ once: true },
);
}
});
if (executionMode === 'interactive') {
context.ui.setPendingItem(null);
}
// Stop and write profile. If profiler is no longer recording (e.g., SIGUSR1
// stopped it during the wait), treat as success — the profile was already written.
const stopResult = await stopCpuProfile();
if (!stopResult.ok) {
const alreadyStopped = stopResult.error.includes('not recording');
if (alreadyStopped) {
const infoMsg =
process.platform === 'win32'
? t(
'CPU profile was stopped externally. Check ~/.qwen/cpu-profiles/ for the output.',
)
: t(
'CPU profile was stopped externally (e.g., via SIGUSR1). Check ~/.qwen/cpu-profiles/ for the output.',
);
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: infoMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'info', content: infoMsg };
}
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: stopResult.error }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: stopResult.error };
}
const successMsg = `${t('CPU profile written:')} ${stopResult.filePath}\n${t('Open in Chrome DevTools → Performance tab → Load profile')}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: successMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'info', content: successMsg };
}

View File

@ -17,6 +17,7 @@ describe('hooksCommand', () => {
beforeEach(() => {
vi.clearAllMocks();
// Create mock config with hook system
mockConfig = {
getHookSystem: vi.fn().mockReturnValue({
getRegistry: vi.fn().mockReturnValue({
@ -68,173 +69,4 @@ describe('hooksCommand', () => {
});
});
});
describe('non-interactive list output', () => {
function makeContext(opts: {
configHooks: Array<{
eventName: string;
matcher?: string;
source: string;
config: {
type: string;
command?: string;
url?: string;
name?: string;
};
}>;
sessionHooks?: Array<{
eventName: string;
matcher?: string;
config: { type: string; command?: string; name?: string };
}>;
}) {
const sessionConfig = {
getHookSystem: vi.fn().mockReturnValue({
getRegistry: vi.fn().mockReturnValue({
getAllHooks: vi.fn().mockReturnValue(opts.configHooks),
}),
getSessionHooksManager: vi.fn().mockReturnValue({
getAllSessionHooks: vi
.fn()
.mockReturnValue(opts.sessionHooks ?? []),
}),
}),
getSessionId: vi.fn().mockReturnValue('sid'),
};
return createMockCommandContext({
executionMode: 'non_interactive',
services: { config: sessionConfig },
});
}
it('groups hooks under matcher headings', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'PreToolUse',
matcher: 'Bash',
source: 'user',
config: { type: 'command', command: '/check-bash.sh' },
},
{
eventName: 'PreToolUse',
matcher: 'Edit|Write',
source: 'project',
config: { type: 'command', command: '/format.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
expect(result).toBeDefined();
const content = (result as { content: string }).content;
expect(content).toContain('### PreToolUse');
expect(content).toContain('#### Matcher: Bash');
expect(content).toContain('/check-bash.sh');
expect(content).toContain('#### Matcher: Edit|Write');
expect(content).toContain('/format.sh');
});
it('renders missing matcher as *', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'PreToolUse',
source: 'user',
config: { type: 'command', command: '/anything.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
expect(content).toContain('#### Matcher: *');
expect(content).toContain('/anything.sh');
});
it('does not emit a Matcher heading for non-matcher events like Stop', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'Stop',
source: 'user',
config: { type: 'command', command: '/stop-hook.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
expect(content).toContain('### Stop');
expect(content).not.toContain('Matcher:');
expect(content).toContain('/stop-hook.sh');
});
it('preserves registration order for non-matcher events with ignored matchers', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'Stop',
matcher: 'A',
source: 'user',
config: { type: 'command', command: '/first.sh' },
},
{
eventName: 'Stop',
matcher: 'B',
source: 'user',
config: { type: 'command', command: '/second.sh' },
},
{
eventName: 'Stop',
matcher: 'A',
source: 'user',
config: { type: 'command', command: '/third.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
expect(content).not.toContain('Matcher:');
expect(content.indexOf('/first.sh')).toBeLessThan(
content.indexOf('/second.sh'),
);
expect(content.indexOf('/second.sh')).toBeLessThan(
content.indexOf('/third.sh'),
);
});
it('groups session hooks by their matcher alongside config hooks', async () => {
const ctx = makeContext({
configHooks: [
{
eventName: 'PreToolUse',
matcher: 'Bash',
source: 'user',
config: { type: 'command', command: '/persistent.sh' },
},
],
sessionHooks: [
{
eventName: 'PreToolUse',
matcher: 'Bash',
config: { type: 'command', command: '/session.sh' },
},
],
});
const result = await hooksCommand.action!(ctx, '');
const content = (result as { content: string }).content;
const matcherOccurrences = content.match(/#### Matcher: Bash/g) ?? [];
expect(matcherOccurrences).toHaveLength(1);
expect(content).toContain('/persistent.sh');
expect(content).toContain('/session.sh');
});
});
});

View File

@ -15,10 +15,7 @@ import { t } from '../../i18n/index.js';
import type {
HookRegistryEntry,
SessionHookEntry,
HookEventName,
} from '@qwen-code/qwen-code-core';
import { supportsMatchers } from '../components/hooks/constants.js';
import { normalizeMatcher } from '../components/hooks/matcherGrouping.js';
/**
* Format hook source for display
@ -74,6 +71,7 @@ const listCommand: SlashCommand = {
const registry = hookSystem.getRegistry();
const configHooks = registry.getAllHooks();
// Get session hooks
const sessionId = config.getSessionId();
const sessionHooksManager = hookSystem.getSessionHooksManager();
const sessionHooks = sessionId
@ -92,94 +90,86 @@ const listCommand: SlashCommand = {
};
}
interface FlattenedHook {
name: string;
source: string;
}
const hooksByEvent = new Map<string, Map<string, FlattenedHook[]>>();
const addHook = (
eventName: string,
matcher: string,
hook: FlattenedHook,
): void => {
const matcherKey = supportsMatchers(eventName as HookEventName)
? matcher
: '*';
let matcherMap = hooksByEvent.get(eventName);
if (!matcherMap) {
matcherMap = new Map<string, FlattenedHook[]>();
hooksByEvent.set(eventName, matcherMap);
}
let bucket = matcherMap.get(matcherKey);
if (!bucket) {
bucket = [];
matcherMap.set(matcherKey, bucket);
}
bucket.push(hook);
};
const extractName = (config: {
type: string;
command?: string;
url?: string;
name?: string;
}): string =>
config.name ||
(config.type === 'command' ? config.command : undefined) ||
(config.type === 'http' ? config.url : undefined) ||
'unnamed';
// Group hooks by event
const hooksByEvent = new Map<
string,
Array<{ hook: HookRegistryEntry | SessionHookEntry; isSession: boolean }>
>();
// Add config hooks
for (const hook of configHooks) {
const configHook = hook as HookRegistryEntry;
const config = configHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
addHook(configHook.eventName, normalizeMatcher(configHook.matcher), {
name: extractName(config),
source: formatHookSource(configHook.source),
});
const eventName = hook.eventName;
if (!hooksByEvent.has(eventName)) {
hooksByEvent.set(eventName, []);
}
hooksByEvent.get(eventName)!.push({ hook, isSession: false });
}
// Add session hooks
for (const hook of sessionHooks) {
const sessionHook = hook as SessionHookEntry;
const config = sessionHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
addHook(sessionHook.eventName, normalizeMatcher(sessionHook.matcher), {
name: extractName(config),
source: formatHookSource('session'),
});
const eventName = hook.eventName;
if (!hooksByEvent.has(eventName)) {
hooksByEvent.set(eventName, []);
}
hooksByEvent.get(eventName)!.push({ hook, isSession: true });
}
let output = `**Configured Hooks (${totalHooks} total)**\n\n`;
for (const [eventName, matcherMap] of hooksByEvent) {
output += `### ${eventName}\n\n`;
const useMatchers = supportsMatchers(eventName as HookEventName);
if (useMatchers) {
for (const [matcher, hookList] of matcherMap) {
output += `#### ${t('Matcher:')} ${matcher}\n`;
for (const hook of hookList) {
output += `- **${hook.name}** [${hook.source}]\n`;
}
output += '\n';
for (const [eventName, hooks] of hooksByEvent) {
output += `### ${eventName}\n`;
for (const { hook, isSession } of hooks) {
let name: string;
let source: string;
let matcher: string;
let config: {
type: string;
command?: string;
url?: string;
name?: string;
};
if (isSession) {
// Session hook
const sessionHook = hook as SessionHookEntry;
config = sessionHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
name =
config.name ||
(config.type === 'command' ? config.command : undefined) ||
(config.type === 'http' ? config.url : undefined) ||
'unnamed';
source = formatHookSource('session');
matcher = sessionHook.matcher
? ` (matcher: ${sessionHook.matcher})`
: '';
} else {
// Config hook
const configHook = hook as HookRegistryEntry;
config = configHook.config as {
type: string;
command?: string;
url?: string;
name?: string;
};
name =
config.name ||
(config.type === 'command' ? config.command : undefined) ||
(config.type === 'http' ? config.url : undefined) ||
'unnamed';
source = formatHookSource(configHook.source);
matcher = configHook.matcher
? ` (matcher: ${configHook.matcher})`
: '';
}
} else {
for (const hookList of matcherMap.values()) {
for (const hook of hookList) {
output += `- **${hook.name}** [${hook.source}]\n`;
}
}
output += '\n';
output += `- **${name}** [${source}]${matcher}\n`;
}
output += '\n';
}
return {
@ -201,6 +191,7 @@ export const hooksCommand: SlashCommand = {
context: CommandContext,
args: string,
): Promise<SlashCommandActionReturn> => {
// In interactive mode, open the hooks dialog
const executionMode = context.executionMode ?? 'interactive';
if (executionMode === 'interactive') {
return {
@ -209,6 +200,7 @@ export const hooksCommand: SlashCommand = {
};
}
// In non-interactive mode, list hooks
const result = await listCommand.action?.(context, args);
return result ?? { type: 'message', messageType: 'info', content: '' };
},

View File

@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { act } from 'react';
import { act } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render } from 'ink-testing-library';
import { MemoryDialog } from './MemoryDialog.js';
@ -41,24 +41,12 @@ describe('MemoryDialog', () => {
mockedUseConfig.mockReturnValue({
getWorkingDir: vi.fn(() => '/tmp/project'),
getProjectRoot: vi.fn(() => '/tmp/project'),
getBareMode: vi.fn(() => false),
// Stale snapshot getters — the dialog must NOT read its toggle state
// from these; it reads from the live merged settings instead.
getManagedAutoMemoryEnabled: vi.fn(() => false),
getManagedAutoDreamEnabled: vi.fn(() => false),
getAutoSkillEnabled: vi.fn(() => false),
} as never);
mockedUseSettings.mockReturnValue({
setValue: vi.fn(),
merged: {
memory: {
enableManagedAutoMemory: false,
enableManagedAutoDream: false,
enableAutoSkill: false,
},
},
} as never);
mockedUseSettings.mockReturnValue({ setValue: vi.fn() } as never);
mockedUseLaunchEditor.mockReturnValue(vi.fn());
});
@ -102,10 +90,10 @@ describe('MemoryDialog', () => {
expect(lastFrame()).toContain('› 1. User memory');
});
it('renders the Auto-skill row with the status from merged settings', () => {
it('renders the Auto-skill row with the status from config', () => {
const { lastFrame } = render(<MemoryDialog onClose={vi.fn()} />);
// beforeEach mocks merged.memory.enableAutoSkill => false
// beforeEach mocks getAutoSkillEnabled => false
expect(lastFrame()).toContain('Auto-skill: off');
});
@ -143,10 +131,7 @@ describe('MemoryDialog', () => {
it('toggles Auto-skill on Enter and persists to workspace settings', () => {
const setValue = vi.fn();
mockedUseSettings.mockReturnValue({
setValue,
merged: { memory: { enableAutoSkill: false } },
} as never);
mockedUseSettings.mockReturnValue({ setValue } as never);
const { lastFrame } = render(<MemoryDialog onClose={vi.fn()} />);
@ -176,44 +161,4 @@ describe('MemoryDialog', () => {
);
expect(lastFrame()).toContain('› Auto-skill: on');
});
it('reflects the persisted value when the dialog is reopened (remounted)', () => {
// Emulate LoadedSettings: setValue writes through to the merged view,
// exactly like the real saveSettings + recomputeMerged path.
const merged = {
memory: {
enableManagedAutoMemory: false,
enableManagedAutoDream: false,
enableAutoSkill: false,
},
};
const setValue = vi.fn((_scope: unknown, key: string, value: boolean) => {
if (key === 'memory.enableAutoSkill') {
merged.memory.enableAutoSkill = value;
}
});
mockedUseSettings.mockReturnValue({ setValue, merged } as never);
const pressKey = (key: { name: string }) => {
const keypressHandler =
mockedUseKeypress.mock.calls[
mockedUseKeypress.mock.calls.length - 1
]![0];
act(() => {
keypressHandler(key as never);
});
};
// First open: toggle Auto-skill on, then close the dialog.
const first = render(<MemoryDialog onClose={vi.fn()} />);
expect(first.lastFrame()).toContain('Auto-skill: off');
pressKey({ name: 'up' }); // focus the Auto-skill row
pressKey({ name: 'return' }); // toggle on
expect(first.lastFrame()).toContain('› Auto-skill: on');
first.unmount();
// Reopen: a fresh mount must read the persisted value, not a stale snapshot.
const second = render(<MemoryDialog onClose={vi.fn()} />);
expect(second.lastFrame()).toContain('Auto-skill: on');
});
});

View File

@ -114,20 +114,14 @@ export function MemoryDialog({ onClose }: MemoryDialogProps) {
const [focusedSection, setFocusedSection] = useState<
'autoMemory' | 'autoDream' | 'autoSkill' | 'list'
>('list');
// Read the initial toggle state from the live merged settings rather than
// the Config snapshot: Config is frozen at startup and never reflects a
// setValue() write, so reopening the dialog would otherwise show stale state.
const bareMode = config.getBareMode();
const readToggle = (value: boolean | undefined): boolean =>
!bareMode && (value ?? true);
const [autoMemoryOn, setAutoMemoryOn] = useState(() =>
readToggle(loadedSettings.merged.memory?.enableManagedAutoMemory),
config.getManagedAutoMemoryEnabled(),
);
const [autoDreamOn, setAutoDreamOn] = useState(() =>
readToggle(loadedSettings.merged.memory?.enableManagedAutoDream),
config.getManagedAutoDreamEnabled(),
);
const [autoSkillOn, setAutoSkillOn] = useState(() =>
readToggle(loadedSettings.merged.memory?.enableAutoSkill),
config.getAutoSkillEnabled(),
);
const [lastDreamAt, setLastDreamAt] = useState<number | null>(null);

View File

@ -1,263 +0,0 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from 'ink-testing-library';
import { SettingsCorruptedDialog } from './SettingsCorruptedDialog.js';
import { KeypressProvider } from '../contexts/KeypressContext.js';
const wait = (ms = 50) => new Promise((resolve) => setTimeout(resolve, ms));
const lastFrameText = (lastFrame: () => string | undefined): string => {
const text = lastFrame();
if (text == null) {
throw new Error('lastFrame returned undefined');
}
return text;
};
const waitFor = async (
predicate: () => void,
options: { timeout?: number; interval?: number } = {},
) => {
const { timeout = 1000, interval = 10 } = options;
const start = Date.now();
let lastError: unknown;
while (Date.now() - start < timeout) {
try {
predicate();
return;
} catch (e) {
lastError = e;
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
if (lastError) {
throw lastError;
}
throw new Error('waitFor timed out');
};
enum TerminalKeys {
ENTER = '\u000D',
UP_ARROW = '\u001B[A',
DOWN_ARROW = '\u001B[B',
ESCAPE = '\u001B',
}
describe('SettingsCorruptedDialog', () => {
const mockCorruptedPath = '/home/user/.qwen/settings.json.corrupted';
const mockOnExit = vi.fn();
const mockOnContinue = vi.fn();
beforeEach(() => {
mockOnExit.mockClear();
mockOnContinue.mockClear();
});
it('should show recovered settings label when wasRecovered=true', async () => {
const { lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={true}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
await waitFor(() => {
expect(lastFrame()).toContain('Continue with recovered settings (esc)');
});
unmount();
});
it('should show empty settings label when wasRecovered=false', async () => {
const { lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
await waitFor(() => {
expect(lastFrame()).toContain('Continue with empty settings (esc)');
});
unmount();
});
it('should move selection with up/down arrows', async () => {
const { stdin, lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
// Initially EXIT is selected — the line containing "Exit and restore"
// must have '>' in it
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const exitLine = lines.find((l) => l.includes('Exit and restore'));
expect(exitLine).toBeTruthy();
expect(exitLine).toContain('>');
});
// Press down — CONTINUE line gets '>'
stdin.write(TerminalKeys.DOWN_ARROW as string);
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const continueLine = lines.find((l) => l.includes('Continue with'));
expect(continueLine).toBeTruthy();
expect(continueLine).toContain('>');
});
// Press up — EXIT line gets '>' back
stdin.write(TerminalKeys.UP_ARROW as string);
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const exitLine = lines.find((l) => l.includes('Exit and restore'));
expect(exitLine).toBeTruthy();
expect(exitLine).toContain('>');
});
unmount();
});
it('should call onExit when pressing Enter on EXIT option', async () => {
const { stdin, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write(TerminalKeys.ENTER as string);
await wait();
await waitFor(() => {
expect(mockOnExit).toHaveBeenCalled();
expect(mockOnContinue).not.toHaveBeenCalled();
});
unmount();
});
it('should call onContinue when pressing Enter on CONTINUE option', async () => {
const { stdin, lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write(TerminalKeys.DOWN_ARROW as string);
await wait();
await waitFor(() => {
const lines = lastFrameText(lastFrame).split('\n');
const continueLine = lines.find((l) => l.includes('Continue with'));
expect(continueLine).toBeTruthy();
expect(continueLine).toContain('>');
});
await wait();
stdin.write(TerminalKeys.ENTER as string);
await wait();
await waitFor(() => {
expect(mockOnContinue).toHaveBeenCalled();
expect(mockOnExit).not.toHaveBeenCalled();
});
unmount();
});
it('should call onContinue when pressing escape', async () => {
const { stdin, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write(TerminalKeys.ESCAPE as string);
await wait();
await waitFor(() => {
expect(mockOnContinue).toHaveBeenCalled();
expect(mockOnExit).not.toHaveBeenCalled();
});
unmount();
});
it('should call onExit when pressing Ctrl+C', async () => {
const { stdin, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
stdin.write('\x03');
await wait();
await waitFor(() => {
expect(mockOnExit).toHaveBeenCalled();
expect(mockOnContinue).not.toHaveBeenCalled();
});
unmount();
});
it('should display the corrupted file path', async () => {
const { lastFrame, unmount } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<SettingsCorruptedDialog
corruptedPath={mockCorruptedPath}
wasRecovered={false}
onExit={mockOnExit}
onContinue={mockOnContinue}
/>
</KeypressProvider>,
);
await wait();
await waitFor(() => {
expect(lastFrame()).toContain(mockCorruptedPath);
});
unmount();
});
});

View File

@ -1,123 +0,0 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import type React from 'react';
import { useState } from 'react';
import { Box, Text } from 'ink';
import { useKeypress } from '../hooks/useKeypress.js';
import { theme } from '../semantic-colors.js';
import { t } from '../../i18n/index.js';
const EXIT_INDEX = 0;
const CONTINUE_INDEX = 1;
interface SettingsCorruptedDialogProps {
corruptedPath: string;
wasRecovered: boolean;
onExit: () => void;
onContinue: () => void;
}
export const SettingsCorruptedDialog: React.FC<
SettingsCorruptedDialogProps
> = ({ corruptedPath, wasRecovered, onExit, onContinue }) => {
const [selectedIndex, setSelectedIndex] = useState(EXIT_INDEX);
useKeypress(
(key) => {
if (key.name === 'escape') {
onContinue();
return;
}
if (key.ctrl && key.name === 'c') {
onExit();
return;
}
if (key.name === 'up') {
setSelectedIndex(EXIT_INDEX);
}
if (key.name === 'down') {
setSelectedIndex(CONTINUE_INDEX);
}
if (key.name === 'return') {
if (selectedIndex === EXIT_INDEX) {
onExit();
} else {
onContinue();
}
}
},
{ isActive: true },
);
const continueLabel = wasRecovered
? t('Continue with recovered settings (esc)')
: t('Continue with empty settings (esc)');
return (
<Box
flexDirection="column"
borderStyle="round"
borderColor={theme.status.error}
padding={1}
width="100%"
marginLeft={1}
>
<Box marginBottom={1} flexDirection="column">
<Text>
<Text color={theme.status.error}>{'> '}</Text>
<Text bold color={theme.status.error}>
{t('Settings file corrupted')}
</Text>
</Text>
<Text color={theme.text.secondary}>
{t(
'Your settings file had invalid JSON. A copy of the corrupted file has been saved for reference.',
)}
</Text>
<Text color={theme.text.secondary}>{corruptedPath}</Text>
</Box>
<Box flexDirection="column">
<Box>
<Text>
{selectedIndex === EXIT_INDEX ? (
<Text color={theme.status.success}>{'> '}</Text>
) : (
' '
)}
</Text>
<Text
color={
selectedIndex === EXIT_INDEX
? theme.status.success
: theme.text.primary
}
>
{t('Exit and restore corrupted file')}
</Text>
</Box>
<Box>
<Text>
{selectedIndex === CONTINUE_INDEX ? (
<Text color={theme.status.success}>{'> '}</Text>
) : (
' '
)}
</Text>
<Text
color={
selectedIndex === CONTINUE_INDEX
? theme.status.success
: theme.text.primary
}
>
{continueLabel}
</Text>
</Box>
</Box>
</Box>
);
};

View File

@ -49,10 +49,7 @@ const config = {
getCliVersion: () => '1.2.3',
getModel: () => 'qwen3-code-plus',
getTargetDir: () => '/repo/project',
getContentGeneratorConfig: () => ({
contextWindowSize: 1000,
reasoning: { effort: 'high' },
}),
getContentGeneratorConfig: () => ({ contextWindowSize: 1000 }),
} as Config;
const uiState = {
@ -87,26 +84,8 @@ describe('StatusLineDialog', () => {
expect(lastFrame()).toContain('Configure Status Line');
expect(lastFrame()).toContain('Type to search');
const frame = lastFrame() ?? '';
expect(frame).toContain('model-with-reasoning');
expect(frame).toContain('model-only');
expect(frame).toContain('git-branch');
expect(frame).toContain('context-remaining');
expect(frame).toContain('current-dir');
expect(frame.indexOf('model-with-reasoning')).toBeLessThan(
frame.indexOf('model-only'),
);
expect(frame.indexOf('model-only')).toBeLessThan(
frame.indexOf('git-branch'),
);
expect(frame.indexOf('git-branch')).toBeLessThan(
frame.indexOf('context-remaining'),
);
expect(frame.indexOf('context-remaining')).toBeLessThan(
frame.indexOf('current-dir'),
);
expect(lastFrame()).toContain('Preview');
expect(lastFrame()).toContain('qwen3-code-plus high');
expect(lastFrame()).toContain('qwen3-code-plus');
});
it('persists selected presets on enter', async () => {
@ -138,10 +117,10 @@ describe('StatusLineDialog', () => {
useThemeColors: true,
items: [
'model-with-reasoning',
'git-branch',
'context-remaining',
'current-dir',
'context-used',
'git-branch',
],
});
expect(
@ -158,53 +137,6 @@ describe('StatusLineDialog', () => {
expect(onClose).toHaveBeenCalled();
});
it('keeps preset priority order after an item is toggled off and on', async () => {
const settings = createSettings();
const { stdin, lastFrame } = render(
<KeypressProvider kittyProtocolEnabled={false}>
<StatusLineDialog
settings={settings}
config={config}
uiState={uiState}
addItem={vi.fn()}
onClose={vi.fn()}
availableTerminalHeight={18}
/>
</KeypressProvider>,
);
const press = async (input: string) => {
act(() => {
stdin.write(input);
});
await new Promise((resolve) => setTimeout(resolve, 0));
};
await press('j');
await press('j');
await press('j');
await press(' ');
await press(' ');
expect(lastFrame()).toContain(
'qwen3-code-plus high | feature/pr-4087-statusline | Context 75% left',
);
await press('\r');
expect(settings.merged.ui?.statusLine).toEqual({
type: 'preset',
useThemeColors: true,
items: [
'model-with-reasoning',
'git-branch',
'context-remaining',
'current-dir',
'context-used',
],
});
});
it('saves back to workspace settings when workspace config is effective', async () => {
const settings = createSettings();
settings.workspace.settings.ui = {

View File

@ -22,7 +22,6 @@ import {
buildStatusLinePresetLines,
DEFAULT_STATUS_LINE_PRESET_CONFIG,
normalizeStatusLinePresetConfig,
orderStatusLinePresetItems,
STATUS_LINE_PRESET_ITEMS,
type StatusLinePresetConfig,
type StatusLinePresetItemId,
@ -58,11 +57,19 @@ function buildInitialSelectedKeys(settings: LoadedSettings): string[] {
function buildConfigFromKeys(keys: readonly string[]): StatusLinePresetConfig {
const selected = new Set(keys);
const validItemIds = new Set(STATUS_LINE_PRESET_ITEMS.map((item) => item.id));
const items = [
...new Set(
keys.filter((key): key is StatusLinePresetItemId =>
validItemIds.has(key as StatusLinePresetItemId),
),
),
];
return {
type: 'preset',
useThemeColors: selected.has(THEME_COLORS_KEY),
items: orderStatusLinePresetItems(keys),
items,
};
}
@ -95,16 +102,15 @@ function getPreviewData(config: Config, uiState: UIState) {
const stats = uiState.sessionStats;
const metrics = stats.metrics;
const { totalInputTokens, totalOutputTokens } = aggregateModelTokens(metrics);
const contentGeneratorConfig = config.getContentGeneratorConfig();
return buildStatusLinePresetData({
sessionId: stats.sessionId,
version: config.getCliVersion(),
modelDisplayName: uiState.currentModel || config.getModel(),
reasoning: contentGeneratorConfig?.reasoning,
currentDir: config.getTargetDir(),
branch: uiState.branchName,
contextWindowSize: contentGeneratorConfig?.contextWindowSize || 0,
contextWindowSize:
config.getContentGeneratorConfig()?.contextWindowSize || 0,
currentUsage: stats.lastPromptTokenCount,
totalInputTokens,
totalOutputTokens,

View File

@ -22,7 +22,7 @@ function makeTodos(count: number): TodoItem[] {
}
describe('StickyTodoList', () => {
it('keeps each visible task number attached to the original task after sorting', () => {
it('keeps each task number attached to the original task after sorting', () => {
const todos: TodoItem[] = [
{
id: 'done',
@ -56,10 +56,15 @@ describe('StickyTodoList', () => {
expect(
lines.find((line) => line.includes('Run cli tests')) ?? '',
).toContain('2.');
expect(output).not.toContain('Summarize results');
expect(
lines.find((line) => line.includes('Summarize results')) ?? '',
).toContain('1.');
expect(output.indexOf('Run core tests')).toBeLessThan(
output.indexOf('Run cli tests'),
);
expect(output.indexOf('Run cli tests')).toBeLessThan(
output.indexOf('Summarize results'),
);
});
it('keeps long todo lists compact with a hidden item summary', () => {
@ -99,7 +104,7 @@ describe('StickyTodoList', () => {
expect(output).toContain('Run cli tests');
expect(output).not.toContain('Run core tests');
expect(output).not.toContain('Summarize results');
expect(output).toContain('... and 1 more');
expect(output).toContain('... and 2 more');
expect(lines).toHaveLength(6);
});
@ -115,26 +120,7 @@ describe('StickyTodoList', () => {
const output = lastFrame() ?? '';
expect(output).toContain('10. ◐ Task 10');
expect(output).not.toContain('... and 9 more');
});
it('hides the sticky panel when every task is completed', () => {
const todos: TodoItem[] = [
{
id: 'done-1',
content: 'Run tests',
status: 'completed',
},
{
id: 'done-2',
content: 'Summarize results',
status: 'completed',
},
];
const { lastFrame } = render(<StickyTodoList todos={todos} width={60} />);
expect(lastFrame()).toBe('');
expect(output).toContain('... and 9 more');
});
it('derives a viewport-aware visible item count', () => {

View File

@ -45,26 +45,20 @@ const StickyTodoListComponent: React.FC<StickyTodoListProps> = ({
width,
maxVisibleItems = STICKY_TODO_MAX_VISIBLE_ITEMS,
}) => {
const orderedOpenTodos = useMemo(
() =>
getOrderedStickyTodos(todos).filter(
(todo) => todo.status !== 'completed',
),
[todos],
);
const orderedTodos = useMemo(() => getOrderedStickyTodos(todos), [todos]);
const todoNumberById = useMemo(
() =>
new Map(todos.map((todo, index) => [todo.id, `${index + 1}.`] as const)),
[todos],
);
if (orderedOpenTodos.length === 0) {
if (todos.length === 0) {
return null;
}
const visibleTodoCount = clampVisibleTodoCount(maxVisibleItems);
const visibleTodos = orderedOpenTodos.slice(0, visibleTodoCount);
const hiddenTodoCount = orderedOpenTodos.length - visibleTodos.length;
const visibleTodos = orderedTodos.slice(0, visibleTodoCount);
const hiddenTodoCount = orderedTodos.length - visibleTodos.length;
const numberColumnWidth =
Math.max(
...visibleTodos.map(

View File

@ -1,267 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from 'ink-testing-library';
import { HooksConfigSource, HookType } from '@qwen-code/qwen-code-core';
import { HandlerListBody } from './HandlerListBody.js';
import type { HookConfigDisplayInfo } from './types.js';
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })),
}));
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: { primary: 'white', secondary: 'gray', accent: 'cyan' },
},
}));
function commandConfig(
command = '/cmd.sh',
async = false,
): HookConfigDisplayInfo {
return {
config: { type: HookType.Command, command, async },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
function httpConfig(
overrides: Partial<{ name: string; url: string }> = {},
): HookConfigDisplayInfo {
return {
config: {
type: HookType.Http,
url: overrides.url ?? 'https://example.test/hook',
...(overrides.name ? { name: overrides.name } : {}),
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
function functionConfig(
overrides: Partial<{ name: string; id: string }> = {},
): HookConfigDisplayInfo {
return {
config: {
type: HookType.Function,
callback: async () => undefined,
errorMessage: 'fn failed',
id: overrides.id ?? 'fn-id',
...(overrides.name ? { name: overrides.name } : {}),
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
function promptConfig(
overrides: Partial<{ name: string; prompt: string }> = {},
): HookConfigDisplayInfo {
return {
config: {
type: HookType.Prompt,
prompt: overrides.prompt ?? 'short prompt',
...(overrides.name ? { name: overrides.name } : {}),
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
}
describe('HandlerListBody', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('describeHook (rendered as the row label)', () => {
it('renders the command path for command hooks', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[commandConfig('/check.sh')]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[command]');
expect(out).toContain('/check.sh');
});
it('marks async command hooks with " async" in the type column', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[commandConfig('/bg.sh', true)]}
selectedIndex={0}
/>,
);
expect(lastFrame() ?? '').toContain('[command async]');
});
it('prefers the http hook name over the URL', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[httpConfig({ name: 'webhook-A', url: 'https://x' })]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[http]');
expect(out).toContain('webhook-A');
expect(out).not.toContain('https://x');
});
it('falls back to the http URL when name is missing', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[httpConfig({ url: 'https://example.test/hook' })]}
selectedIndex={0}
/>,
);
expect(lastFrame() ?? '').toContain('https://example.test/hook');
});
it('prefers the function hook name over the id', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[functionConfig({ name: 'fn-name', id: 'fn-id' })]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[function]');
expect(out).toContain('fn-name');
expect(out).not.toContain('fn-id');
});
it('falls back to function id, then to "function-hook" placeholder', () => {
const withId = render(
<HandlerListBody
configs={[functionConfig({ id: 'only-id' })]}
selectedIndex={0}
/>,
);
expect(withId.lastFrame() ?? '').toContain('only-id');
const noNameNoId = render(
<HandlerListBody
configs={[
{
config: {
type: HookType.Function,
callback: async () => undefined,
errorMessage: 'fn failed',
} as HookConfigDisplayInfo['config'],
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
]}
selectedIndex={0}
/>,
);
expect(noNameNoId.lastFrame() ?? '').toContain('function-hook');
});
it('truncates long prompt text with "..." and keeps short prompts intact', () => {
const long = 'a'.repeat(80);
const { lastFrame: longFrame } = render(
<HandlerListBody
configs={[promptConfig({ prompt: long })]}
selectedIndex={0}
/>,
);
const longOut = longFrame() ?? '';
expect(longOut).toContain('a'.repeat(50) + '...');
expect(longOut).not.toContain('a'.repeat(51));
const { lastFrame: shortFrame } = render(
<HandlerListBody
configs={[promptConfig({ prompt: 'fits' })]}
selectedIndex={0}
/>,
);
const shortOut = shortFrame() ?? '';
expect(shortOut).toContain('fits');
expect(shortOut).not.toContain('...');
});
it('prefers the prompt name over the prompt text', () => {
const { lastFrame } = render(
<HandlerListBody
configs={[
promptConfig({ name: 'classifier', prompt: 'should not appear' }),
]}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('classifier');
expect(out).not.toContain('should not appear');
});
});
describe('source column', () => {
it('appends the extension name for Extensions-source configs', () => {
const config: HookConfigDisplayInfo = {
config: { type: HookType.Command, command: '/ext.sh' },
source: HooksConfigSource.Extensions,
sourceDisplay: 'my-extension',
enabled: true,
};
const { lastFrame } = render(
<HandlerListBody configs={[config]} selectedIndex={0} />,
);
const out = lastFrame() ?? '';
expect(out).toContain('Extensions');
expect(out).toContain('my-extension');
});
it('uses the long "Session (temporary)" label for session-source configs', () => {
const config: HookConfigDisplayInfo = {
config: { type: HookType.Command, command: '/sess.sh' },
source: HooksConfigSource.Session,
sourceDisplay: 'Session (temporary)',
enabled: true,
};
const { lastFrame } = render(
<HandlerListBody configs={[config]} selectedIndex={0} />,
);
expect(lastFrame() ?? '').toContain('Session (temporary)');
});
});
it('renders numbered rows and footer hint, places arrow on selected', () => {
const configs = [commandConfig('/first.sh'), commandConfig('/second.sh')];
const { lastFrame } = render(
<HandlerListBody configs={configs} selectedIndex={1} />,
);
const out = lastFrame() ?? '';
expect(out).toContain('1.');
expect(out).toContain('2.');
expect(out).toContain('Configured hooks:');
expect(out).toContain('Enter to select · Esc to go back');
const arrowLine = out.split('\n').find((line) => line.includes('❯'));
expect(arrowLine).toBeDefined();
expect(arrowLine).toContain('/second.sh');
});
});

View File

@ -1,106 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import { HookType } from '@qwen-code/qwen-code-core';
import type { HookConfigDisplayInfo } from './types.js';
import { getConfigSourceDisplay } from './sourceLabels.js';
import { t } from '../../../i18n/index.js';
interface HandlerListBodyProps {
configs: HookConfigDisplayInfo[];
selectedIndex: number;
}
export function HandlerListBody({
configs,
selectedIndex,
}: HandlerListBodyProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
const commandWidth = Math.floor(terminalWidth * 0.65);
const sourceWidth = Math.floor(terminalWidth * 0.3);
return (
<>
<Text bold color={theme.text.primary}>
{t('Configured hooks:')}
</Text>
{configs.map((config, index) => {
const isSelected = index === selectedIndex;
const sourceDisplay = getConfigSourceDisplay(config);
const hookDisplay = describeHook(config);
const typeDisplay = formatTypeDisplay(config);
return (
<Box key={index}>
<Box width={commandWidth}>
<Box minWidth={2}>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
>
{isSelected ? '❯' : ' '}
</Text>
</Box>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
bold={isSelected}
wrap="wrap"
>
{`${index + 1}. [${typeDisplay}] ${hookDisplay}`}
</Text>
</Box>
<Box width={2} />
<Box width={sourceWidth}>
<Text color={theme.text.secondary} wrap="wrap">
{sourceDisplay}
</Text>
</Box>
</Box>
);
})}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('Enter to select · Esc to go back')}
</Text>
</Box>
</>
);
}
function describeHook(info: HookConfigDisplayInfo): string {
const { config } = info;
switch (config.type) {
case HookType.Command:
return config.command || '';
case HookType.Http:
return config.name || config.url || '';
case HookType.Function:
return config.name || config.id || 'function-hook';
case HookType.Prompt: {
const promptText = config.prompt || '';
const maxLength = 50;
return (
config.name ||
(promptText.length > maxLength
? promptText.slice(0, maxLength) + '...'
: promptText)
);
}
default: {
const _exhaustive: never = config;
void _exhaustive;
return '';
}
}
}
function formatTypeDisplay(info: HookConfigDisplayInfo): string {
const { config } = info;
const isAsync = config.type === HookType.Command && config.async === true;
return isAsync ? `${config.type} async` : String(config.type);
}

View File

@ -14,14 +14,17 @@ import {
import { HookConfigDetailStep } from './HookConfigDetailStep.js';
import type { HookEventDisplayInfo, HookConfigDisplayInfo } from './types.js';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })),
}));
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -48,7 +51,7 @@ describe('HookConfigDetailStep', () => {
},
{ code: 'Other', description: 'show stderr to user only' },
],
matcherGroups: [],
configs: [],
});
const createMockHookConfig = (
@ -167,6 +170,7 @@ describe('HookConfigDetailStep', () => {
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
);
// Should not have Extension label for User Settings
const output = lastFrame();
const extensionMatch = output?.match(/Extension:/g);
expect(extensionMatch).toBeNull();
@ -248,74 +252,6 @@ describe('HookConfigDetailStep', () => {
expect(lastFrame()).toContain('Esc to go back');
});
it('should render Matcher field for matcher-capable events', () => {
const hookEvent = {
...createMockHookEvent(),
event: HookEventName.PreToolUse,
};
const hookConfig: HookConfigDisplayInfo = {
config: {
type: HookType.Command,
command: '/path/to/hook.sh',
},
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
matcher: 'Bash',
enabled: true,
};
const { lastFrame } = render(
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
);
expect(lastFrame()).toContain('Matcher:');
expect(lastFrame()).toContain('Bash');
});
it('should render Matcher as * when matcher is missing for matcher-capable events', () => {
const hookEvent = {
...createMockHookEvent(),
event: HookEventName.PreToolUse,
};
const hookConfig: HookConfigDisplayInfo = {
config: {
type: HookType.Command,
command: '/path/to/hook.sh',
},
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
};
const { lastFrame } = render(
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
);
expect(lastFrame()).toContain('Matcher:');
expect(lastFrame()).toContain('*');
});
it('should not render Matcher field for non-matcher events', () => {
const hookEvent = createMockHookEvent();
const hookConfig: HookConfigDisplayInfo = {
config: {
type: HookType.Command,
command: '/path/to/hook.sh',
},
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
matcher: '*',
enabled: true,
};
const output =
render(
<HookConfigDetailStep hookEvent={hookEvent} hookConfig={hookConfig} />,
).lastFrame() ?? '';
expect(output).not.toContain('Matcher:');
});
it('should handle different event types', () => {
const events = [
HookEventName.PreToolUse,
@ -330,7 +266,7 @@ describe('HookConfigDetailStep', () => {
shortDescription: 'Test',
description: '',
exitCodes: [],
matcherGroups: [],
configs: [],
};
const hookConfig = createMockHookConfig();

View File

@ -10,10 +10,6 @@ import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookConfigDisplayInfo, HookEventDisplayInfo } from './types.js';
import { HooksConfigSource } from '@qwen-code/qwen-code-core';
import { t } from '../../../i18n/index.js';
import {
getTranslatedSourceDisplayMap,
supportsMatchers,
} from './constants.js';
interface HookConfigDetailStepProps {
hookEvent: HookEventDisplayInfo;
@ -26,10 +22,26 @@ export function HookConfigDetailStep({
}: HookConfigDetailStepProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
const sourceDisplay = getTranslatedSourceDisplayMap()[hookConfig.source];
// Get source display
const getSourceDisplay = (): string => {
switch (hookConfig.source) {
case HooksConfigSource.Project:
return t('Local Settings');
case HooksConfigSource.User:
return t('User Settings');
case HooksConfigSource.System:
return t('System Settings');
case HooksConfigSource.Extensions:
return t('Extensions');
default:
return hookConfig.source;
}
};
// Check if this is from an extension
const isFromExtension = hookConfig.source === HooksConfigSource.Extensions;
// Get hook type display
const getHookTypeDisplay = (): string => {
switch (hookConfig.config.type) {
case 'command':
@ -39,6 +51,7 @@ export function HookConfigDetailStep({
}
};
// Get command to display
const getCommand = (): string => {
if (hookConfig.config.type === 'command') {
return hookConfig.config.command;
@ -46,6 +59,7 @@ export function HookConfigDetailStep({
return '';
};
// Get prompt to display
const getPrompt = (): string => {
if (hookConfig.config.type === 'prompt') {
return hookConfig.config.prompt;
@ -53,6 +67,7 @@ export function HookConfigDetailStep({
return '';
};
// Get URL to display
const getUrl = (): string => {
if (hookConfig.config.type === 'http') {
return hookConfig.config.url;
@ -60,19 +75,22 @@ export function HookConfigDetailStep({
return '';
};
// Calculate box width for command display
const commandBoxWidth = Math.min(terminalWidth - 6, 80);
// Label width for alignment (Extension: is the longest label)
const labelWidth = 12;
const showMatcher = supportsMatchers(hookEvent.event);
return (
<Box flexDirection="column" paddingX={1}>
{/* Title */}
<Box marginBottom={1}>
<Text bold color={theme.text.primary}>
{t('Hook details')}
</Text>
</Box>
{/* Event */}
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Event:')}</Text>
@ -80,15 +98,7 @@ export function HookConfigDetailStep({
<Text color={theme.text.primary}>{hookEvent.event}</Text>
</Box>
{showMatcher && (
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Matcher:')}</Text>
</Box>
<Text color={theme.text.primary}>{hookConfig.matcher || '*'}</Text>
</Box>
)}
{/* Type */}
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Type:')}</Text>
@ -96,16 +106,18 @@ export function HookConfigDetailStep({
<Text color={theme.text.primary}>{getHookTypeDisplay()}</Text>
</Box>
{/* Source */}
<Box>
<Box width={labelWidth}>
<Text color={theme.text.secondary}>{t('Source:')}</Text>
</Box>
<Text color={theme.text.primary}>{sourceDisplay}</Text>
<Text color={theme.text.primary}>{getSourceDisplay()}</Text>
{hookConfig.sourcePath && (
<Text color={theme.text.secondary}> ({hookConfig.sourcePath})</Text>
)}
</Box>
{/* Extension name (only for extensions) */}
{isFromExtension && hookConfig.sourceDisplay && (
<Box>
<Box width={labelWidth}>
@ -115,6 +127,7 @@ export function HookConfigDetailStep({
</Box>
)}
{/* Name (if exists) */}
{hookConfig.config.name && (
<Box>
<Box width={labelWidth}>
@ -124,6 +137,7 @@ export function HookConfigDetailStep({
</Box>
)}
{/* Description (if exists) */}
{hookConfig.config.description && (
<Box>
<Box width={labelWidth}>
@ -135,6 +149,7 @@ export function HookConfigDetailStep({
</Box>
)}
{/* Command / Prompt / URL - based on hook type */}
{hookConfig.config.type === 'command' && (
<>
<Box marginTop={1}>
@ -186,6 +201,7 @@ export function HookConfigDetailStep({
</>
)}
{/* Help text */}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t(
@ -194,6 +210,7 @@ export function HookConfigDetailStep({
</Text>
</Box>
{/* Footer hint */}
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>

View File

@ -12,24 +12,19 @@ import {
HookType,
} from '@qwen-code/qwen-code-core';
import { HookDetailStep } from './HookDetailStep.js';
import type { HookConfigDisplayInfo, HookEventDisplayInfo } from './types.js';
import type { HookEventDisplayInfo } from './types.js';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string, options?: { count?: string }) => {
if (key === '{{count}} hook' && options?.count) {
return `${options.count} hook`;
}
if (key === '{{count}} hooks' && options?.count) {
return `${options.count} hooks`;
}
return key;
}),
t: vi.fn((key: string) => key),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })),
}));
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -44,282 +39,190 @@ vi.mock('../../semantic-colors.js', () => ({
},
}));
function makeConfig(
command: string,
source: HooksConfigSource = HooksConfigSource.User,
matcher = '*',
): HookConfigDisplayInfo {
return {
config: { command, type: HookType.Command },
source,
sourceDisplay:
source === HooksConfigSource.User ? 'User Settings' : 'Local Settings',
matcher,
enabled: true,
};
}
function makeHookInfo(
groups: Array<{
matcher: string;
configs: HookConfigDisplayInfo[];
sequential?: boolean;
}>,
opts: {
event?: HookEventName;
description?: string;
exitCodes?: HookEventDisplayInfo['exitCodes'];
flatConfigs?: HookConfigDisplayInfo[];
} = {},
): HookEventDisplayInfo {
const matcherGroups = opts.flatConfigs
? [{ matcher: '*', configs: opts.flatConfigs, sequential: false }]
: groups;
return {
event: opts.event ?? HookEventName.PreToolUse,
shortDescription: 'short',
description: opts.description ?? '',
exitCodes: opts.exitCodes ?? [
describe('HookDetailStep', () => {
const createMockHookInfo = (
event: HookEventName,
configCount = 0,
hasDescription = true,
): HookEventDisplayInfo => ({
event,
shortDescription: `Short description for ${event}`,
description: hasDescription ? `Detailed description for ${event}` : '',
exitCodes: [
{ code: 0, description: 'Success' },
{ code: 2, description: 'Block' },
],
matcherGroups,
};
}
configs: Array(configCount)
.fill(null)
.map((_, i) => ({
config: { command: `hook-command-${i}`, type: HookType.Command },
source:
i % 2 === 0 ? HooksConfigSource.User : HooksConfigSource.Project,
sourceDisplay: i % 2 === 0 ? 'User Settings' : 'Local Settings',
enabled: true,
})),
});
describe('HookDetailStep', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders the "Event - Matchers" title', () => {
const hook = makeHookInfo([
{ matcher: '*', configs: [makeConfig('/x.sh')] },
]);
it('should render hook event name as title', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
expect(lastFrame()).toContain(`${HookEventName.PreToolUse} - Matchers`);
expect(lastFrame()).toContain(HookEventName.PreToolUse);
});
it('renders event description when present', () => {
const hook = makeHookInfo(
[{ matcher: '*', configs: [makeConfig('/x.sh')] }],
{ description: 'desc-for-event' },
);
it('should render description when present', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 0, true);
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
expect(lastFrame()).toContain('desc-for-event');
expect(lastFrame()).toContain('Detailed description for PreToolUse');
});
it('renders inline exit code descriptions', () => {
const hook = makeHookInfo([
{ matcher: '*', configs: [makeConfig('/x.sh')] },
]);
it('should not render description section when empty', () => {
const hook = createMockHookInfo(HookEventName.Stop, 0, false);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('Exit code');
expect(out).toContain('Success');
expect(out).toContain('Block');
const hook2 = makeHookInfo(
[{ matcher: '*', configs: [makeConfig('/x.sh')] }],
{
exitCodes: [{ code: 'Other', description: 'other-desc' }],
},
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const out2 =
render(<HookDetailStep hook={hook2} selectedIndex={0} />).lastFrame() ??
'';
expect(out2).toContain('Other exit codes');
expect(out2).toContain('other-desc');
// Stop event has empty description
const output = lastFrame();
expect(output).toContain(HookEventName.Stop);
});
it('shows empty state when no matcher groups', () => {
const hook = makeHookInfo([]);
it('should render exit codes', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('No hooks configured for this event');
expect(out).toContain('Esc to go back');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('Exit codes');
expect(output).toContain('0');
expect(output).toContain('Success');
expect(output).toContain('2');
expect(output).toContain('Block');
});
it('renders matcher rows with [Source] label and matcher', () => {
const hook = makeHookInfo([
{
matcher: '*',
configs: [makeConfig('/star.sh', HooksConfigSource.User, '*')],
},
{
matcher: 'Bash',
configs: [makeConfig('/bash.sh', HooksConfigSource.User, 'Bash')],
},
]);
it('should show empty state when no configs', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 0);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[User] *');
expect(out).toContain('[User] Bash');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('No hooks configured for this event');
expect(output).toContain('To add hooks, edit settings.json');
});
it('uses Project label for workspace-source matcher groups', () => {
const hook = makeHookInfo([
{
matcher: 'Bash',
configs: [makeConfig('/bash.sh', HooksConfigSource.Project, 'Bash')],
},
]);
it('should show configured hooks list when configs exist', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 2);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[Project] Bash');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('Configured hooks');
expect(output).toContain('[command]');
expect(output).toContain('hook-command-0');
expect(output).toContain('hook-command-1');
});
it('renders all unique source labels for mixed-source matcher groups', () => {
const hook = makeHookInfo([
{
matcher: 'Bash',
configs: [
makeConfig('/user.sh', HooksConfigSource.User, 'Bash'),
makeConfig('/project.sh', HooksConfigSource.Project, 'Bash'),
makeConfig('/user-two.sh', HooksConfigSource.User, 'Bash'),
],
},
]);
it('should show source display for each config', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 2);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[User, Project] Bash');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('User Settings');
expect(output).toContain('Local Settings');
});
it('renders singular "1 hook" and plural "N hooks"', () => {
const hook = makeHookInfo([
{
matcher: '*',
configs: [makeConfig('/a.sh', HooksConfigSource.User, '*')],
},
{
matcher: 'Bash',
configs: [
makeConfig('/b.sh', HooksConfigSource.User, 'Bash'),
makeConfig('/c.sh', HooksConfigSource.User, 'Bash'),
],
},
]);
it('should show selection indicator for first config', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse, 3);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('1 hook');
expect(out).toContain('2 hooks');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('❯');
});
it('does not render specific command text on the matcher list page', () => {
const hook = makeHookInfo([
{
matcher: 'Bash',
configs: [
makeConfig(
'/very-specific-command.sh',
HooksConfigSource.User,
'Bash',
),
],
},
]);
it('should show keyboard hint for going back', () => {
const hook = createMockHookInfo(HookEventName.PreToolUse);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).not.toContain('/very-specific-command.sh');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
expect(lastFrame()).toContain('Esc to go back');
});
it('places the selection arrow on the selected matcher row', () => {
const hook = makeHookInfo([
{
matcher: '*',
configs: [makeConfig('/a.sh', HooksConfigSource.User, '*')],
},
{
matcher: 'Bash',
configs: [makeConfig('/b.sh', HooksConfigSource.User, 'Bash')],
},
]);
it('should render with multiple configs', () => {
const hook = createMockHookInfo(HookEventName.PostToolUse, 5);
const out =
render(<HookDetailStep hook={hook} selectedIndex={1} />).lastFrame() ??
'';
const arrowLine = out.split('\n').find((line) => line.includes('❯'));
expect(arrowLine).toBeDefined();
expect(arrowLine).toContain('Bash');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).toContain('1.');
expect(output).toContain('2.');
expect(output).toContain('3.');
expect(output).toContain('4.');
expect(output).toContain('5.');
});
it('renders the Enter/Esc footer hint', () => {
const hook = makeHookInfo([
{ matcher: '*', configs: [makeConfig('/x.sh')] },
]);
it('should handle hook with no exit codes', () => {
const hook: HookEventDisplayInfo = {
event: HookEventName.PreToolUse,
shortDescription: 'Test',
description: 'Test description',
exitCodes: [],
configs: [],
};
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('Enter to select');
expect(out).toContain('Esc to go back');
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const output = lastFrame();
expect(output).not.toContain('Exit codes');
});
describe('non-matcher events (e.g. Stop)', () => {
it('does not append " - Matchers" to the title', () => {
const hook = makeHookInfo([], {
event: HookEventName.Stop,
flatConfigs: [makeConfig('/stop.sh', HooksConfigSource.User, '*')],
});
it('should handle different hook event types', () => {
const events = [
HookEventName.Stop,
HookEventName.PreToolUse,
HookEventName.PostToolUse,
HookEventName.UserPromptSubmit,
HookEventName.SessionStart,
HookEventName.SessionEnd,
];
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain(HookEventName.Stop);
expect(out).not.toContain('- Matchers');
});
for (const event of events) {
const hook = createMockHookInfo(event, 1);
it('renders the handler list directly (with command and source)', () => {
const hook = makeHookInfo([], {
event: HookEventName.Stop,
flatConfigs: [
makeConfig('/stop-one.sh', HooksConfigSource.User, '*'),
makeConfig('/stop-two.sh', HooksConfigSource.Project, '*'),
],
});
const { lastFrame } = render(
<HookDetailStep hook={hook} selectedIndex={0} />,
);
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('[command]');
expect(out).toContain('/stop-one.sh');
expect(out).toContain('/stop-two.sh');
expect(out).toContain('User Settings');
expect(out).toContain('Local Settings');
expect(out).toContain('Enter to select');
});
it('shows empty state when a non-matcher event has no handlers', () => {
const hook = makeHookInfo([], {
event: HookEventName.Stop,
flatConfigs: [],
});
const out =
render(<HookDetailStep hook={hook} selectedIndex={0} />).lastFrame() ??
'';
expect(out).toContain('No hooks configured for this event');
});
expect(lastFrame()).toContain(event);
}
});
});

View File

@ -4,10 +4,13 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookEventDisplayInfo } from './types.js';
import { supportsMatchers } from './constants.js';
import { HookEventMatcherListStep } from './HookEventMatcherListStep.js';
import { HookEventHandlerListStep } from './HookEventHandlerListStep.js';
import { HooksConfigSource, HookType } from '@qwen-code/qwen-code-core';
import { getTranslatedSourceDisplayMap } from './constants.js';
import { t } from '../../../i18n/index.js';
interface HookDetailStepProps {
hook: HookEventDisplayInfo;
@ -18,10 +21,159 @@ export function HookDetailStep({
hook,
selectedIndex,
}: HookDetailStepProps): React.JSX.Element {
if (supportsMatchers(hook.event)) {
return (
<HookEventMatcherListStep hook={hook} selectedIndex={selectedIndex} />
);
}
return <HookEventHandlerListStep hook={hook} selectedIndex={selectedIndex} />;
const hasConfigs = hook.configs.length > 0;
const { columns: terminalWidth } = useTerminalSize();
// Get translated source display map
const sourceDisplayMap = getTranslatedSourceDisplayMap();
// Calculate column widths (command: 70%, source: 30%)
const commandWidth = Math.floor(terminalWidth * 0.65);
const sourceWidth = Math.floor(terminalWidth * 0.3);
// Get source display for config list
const getConfigSourceDisplay = (config: {
source: HooksConfigSource;
sourceDisplay: string;
}): string => {
if (config.source === HooksConfigSource.Extensions) {
// For extensions, sourceDisplay is the extension name
return `${sourceDisplayMap[HooksConfigSource.Extensions]} (${config.sourceDisplay})`;
}
return sourceDisplayMap[config.source] || config.source;
};
return (
<Box flexDirection="column" paddingX={1}>
{/* Title */}
<Box marginBottom={1}>
<Text bold color={theme.text.primary}>
{hook.event}
</Text>
</Box>
{/* Description */}
{hook.description && (
<Box marginBottom={1}>
<Text color={theme.text.secondary}>{hook.description}</Text>
</Box>
)}
{/* Exit codes */}
{hook.exitCodes.length > 0 && (
<Box flexDirection="column" marginBottom={1}>
<Text bold color={theme.text.primary}>
{t('Exit codes:')}
</Text>
{hook.exitCodes.map((ec, index) => (
<Box key={index}>
<Text color={theme.text.secondary}>
{` ${ec.code}: ${ec.description}`}
</Text>
</Box>
))}
</Box>
)}
<Box marginTop={1} />
{/* Configs or empty state */}
{hasConfigs ? (
<>
<Text bold color={theme.text.primary}>
{t('Configured hooks:')}
</Text>
{hook.configs.map((config, index) => {
const isSelected = index === selectedIndex;
const sourceDisplay = getConfigSourceDisplay(config);
// Get display text based on hook type
let hookDisplay = '';
const hookType = config.config.type;
if (hookType === HookType.Command) {
// For command hook, show command (truncate if too long)
hookDisplay = config.config.command || '';
} else if (hookType === HookType.Http) {
// For http hook, show name or url
hookDisplay = config.config.name || config.config.url || '';
} else if (hookType === HookType.Function) {
// For function hook, show name or id
hookDisplay =
config.config.name || config.config.id || 'function-hook';
} else if (hookType === HookType.Prompt) {
// For prompt hook, show name or prompt content (truncated)
const promptText = config.config.prompt || '';
const maxLength = 50;
hookDisplay =
config.config.name ||
(promptText.length > maxLength
? promptText.slice(0, maxLength) + '...'
: promptText);
}
// Check if this is an async hook (only command hooks support async)
const isAsync =
hookType === HookType.Command && config.config.async === true;
const typeDisplay = isAsync
? `${hookType} async`
: String(hookType);
return (
<Box key={index}>
{/* Left column: selector + display */}
<Box width={commandWidth}>
<Box minWidth={2}>
<Text
color={
isSelected ? theme.text.accent : theme.text.primary
}
>
{isSelected ? '❯' : ' '}
</Text>
</Box>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
bold={isSelected}
wrap="wrap"
>
{`${index + 1}. [${typeDisplay}] ${hookDisplay}`}
</Text>
</Box>
{/* Spacer between columns */}
<Box width={2} />
{/* Right column: source */}
<Box width={sourceWidth}>
<Text color={theme.text.secondary} wrap="wrap">
{sourceDisplay}
</Text>
</Box>
</Box>
);
})}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('Enter to select · Esc to go back')}
</Text>
</Box>
</>
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this event.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('To add hooks, edit settings.json directly or ask Qwen.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
}

View File

@ -1,56 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import type { HookEventDisplayInfo } from './types.js';
import { HookEventHeader } from './HookEventHeader.js';
import { HandlerListBody } from './HandlerListBody.js';
import { getAllConfigs } from './matcherGrouping.js';
import { t } from '../../../i18n/index.js';
interface HookEventHandlerListStepProps {
hook: HookEventDisplayInfo;
selectedIndex: number;
}
export function HookEventHandlerListStep({
hook,
selectedIndex,
}: HookEventHandlerListStepProps): React.JSX.Element {
const flatConfigs = getAllConfigs(hook);
const hasConfigs = flatConfigs.length > 0;
return (
<Box flexDirection="column" paddingX={1}>
<HookEventHeader
title={hook.event}
description={hook.description}
exitCodes={hook.exitCodes}
/>
{hasConfigs ? (
<HandlerListBody configs={flatConfigs} selectedIndex={selectedIndex} />
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this event.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('To add hooks, edit settings.json directly or ask Qwen.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
}

View File

@ -1,65 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import type { HookEventDisplayInfo } from './types.js';
import { t } from '../../../i18n/index.js';
interface HookEventHeaderProps {
title: string;
description: string;
exitCodes: HookEventDisplayInfo['exitCodes'];
}
export function HookEventHeader({
title,
description,
exitCodes,
}: HookEventHeaderProps): React.JSX.Element {
return (
<>
<Box marginBottom={1}>
<Text bold color={theme.text.primary}>
{title}
</Text>
</Box>
{description && (
<Box marginBottom={1}>
<Text color={theme.text.secondary}>{description}</Text>
</Box>
)}
<ExitCodesBlock exitCodes={exitCodes} />
</>
);
}
function ExitCodesBlock({
exitCodes,
}: {
exitCodes: HookEventDisplayInfo['exitCodes'];
}): React.JSX.Element | null {
if (exitCodes.length === 0) return null;
return (
<Box flexDirection="column" marginBottom={1}>
{exitCodes.map((ec, index) => {
const label =
typeof ec.code === 'number'
? `${t('Exit code')} ${ec.code}`
: `${t('Other exit codes')}`;
return (
<Box key={index}>
<Text color={theme.text.secondary}>
{label} - {ec.description}
</Text>
</Box>
);
})}
</Box>
);
}

View File

@ -1,95 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookEventDisplayInfo } from './types.js';
import { HookEventHeader } from './HookEventHeader.js';
import { formatSourceLabels } from './sourceLabels.js';
import { t } from '../../../i18n/index.js';
interface HookEventMatcherListStepProps {
hook: HookEventDisplayInfo;
selectedIndex: number;
}
export function HookEventMatcherListStep({
hook,
selectedIndex,
}: HookEventMatcherListStepProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
const leftWidth = Math.floor(terminalWidth * 0.6);
const hasMatchers = hook.matcherGroups.length > 0;
return (
<Box flexDirection="column" paddingX={1}>
<HookEventHeader
title={`${hook.event} - ${t('Matchers')}`}
description={hook.description}
exitCodes={hook.exitCodes}
/>
{hasMatchers ? (
<>
{hook.matcherGroups.map((group, index) => {
const isSelected = index === selectedIndex;
const sourceLabel = formatSourceLabels(group.configs);
const count = group.configs.length;
const countLabel =
count === 1
? t('{{count}} hook', { count: String(count) })
: t('{{count}} hooks', { count: String(count) });
const rowText = `${index + 1}. [${sourceLabel}] ${group.matcher}`;
return (
<Box key={`${group.matcher}-${index}`}>
<Box minWidth={2}>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
>
{isSelected ? '❯' : ' '}
</Text>
</Box>
<Box width={leftWidth}>
<Text
color={isSelected ? theme.text.accent : theme.text.primary}
bold={isSelected}
wrap="wrap"
>
{rowText}
</Text>
</Box>
<Text color={theme.text.secondary}>{countLabel}</Text>
</Box>
);
})}
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('Enter to select · Esc to go back')}
</Text>
</Box>
</>
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this event.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>
{t('To add hooks, edit settings.json directly or ask Qwen.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
}

View File

@ -1,252 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render } from 'ink-testing-library';
import {
HookEventName,
HooksConfigSource,
HookType,
} from '@qwen-code/qwen-code-core';
import { HookMatcherDetailStep } from './HookMatcherDetailStep.js';
import type {
HookConfigDisplayInfo,
HookEventDisplayInfo,
HookMatcherDisplayInfo,
} from './types.js';
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 100, rows: 24 })),
}));
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
primary: 'white',
secondary: 'gray',
accent: 'cyan',
},
status: {
success: 'green',
error: 'red',
},
},
}));
function makeEvent(
overrides: Partial<HookEventDisplayInfo> = {},
): HookEventDisplayInfo {
return {
event: HookEventName.PreToolUse,
shortDescription: 'short',
description: 'Input to command is JSON of tool call arguments.',
exitCodes: [
{ code: 0, description: 'stdout/stderr not shown' },
{ code: 2, description: 'show stderr to model and block tool call' },
{
code: 'Other',
description: 'show stderr to user only but continue with tool call',
},
],
matcherGroups: [],
...overrides,
};
}
function makeConfig(
command: string,
source: HooksConfigSource = HooksConfigSource.User,
): HookConfigDisplayInfo {
return {
config: { command, type: HookType.Command },
source,
sourceDisplay:
source === HooksConfigSource.User ? 'User Settings' : 'Local Settings',
matcher: 'Bash',
enabled: true,
};
}
describe('HookMatcherDetailStep', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders the "Event - Matcher: <value>" title', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/x.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
expect(lastFrame()).toContain(
`${HookEventName.PreToolUse} - Matcher: Bash`,
);
});
it('keeps the "Matcher:" prefix when the matcher is the * fallback', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: '*',
configs: [makeConfig('/x.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
expect(lastFrame()).toContain(`${HookEventName.PreToolUse} - Matcher: *`);
});
it('keeps the event description visible on the matcher detail page', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/x.sh')],
};
const out =
render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
).lastFrame() ?? '';
expect(out).toContain('Input to command is JSON of tool call arguments.');
});
it('renders inline exit code descriptions on the matcher detail page', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/x.sh')],
};
const out =
render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
).lastFrame() ?? '';
expect(out).toContain('Exit code 0');
expect(out).toContain('stdout/stderr not shown');
expect(out).toContain('Exit code 2');
expect(out).toContain('show stderr to model and block tool call');
expect(out).toContain('Other exit codes');
expect(out).toContain(
'show stderr to user only but continue with tool call',
);
});
it('renders the handler command for command hooks', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/check.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('[command]');
expect(out).toContain('/check.sh');
});
it('renders multiple handler rows with numbering', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Edit|Write',
configs: [
makeConfig('/first.sh'),
makeConfig('/second.sh', HooksConfigSource.Project),
],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={1}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('1.');
expect(out).toContain('2.');
expect(out).toContain('/first.sh');
expect(out).toContain('/second.sh');
expect(out).toContain('User Settings');
expect(out).toContain('Local Settings');
});
it('places the selection arrow on the selected handler row', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [makeConfig('/first.sh'), makeConfig('/second.sh')],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={1}
/>,
);
const out = lastFrame() ?? '';
const arrowLine = out.split('\n').find((line) => line.includes('❯'));
expect(arrowLine).toBeDefined();
expect(arrowLine).toContain('/second.sh');
});
it('renders empty state when the matcher group has no handlers', () => {
const hookEvent = makeEvent();
const matcherGroup: HookMatcherDisplayInfo = {
matcher: 'Bash',
configs: [],
};
const { lastFrame } = render(
<HookMatcherDetailStep
hookEvent={hookEvent}
matcherGroup={matcherGroup}
selectedIndex={0}
/>,
);
const out = lastFrame() ?? '';
expect(out).toContain('No hooks configured for this matcher');
expect(out).toContain('Esc to go back');
});
});

View File

@ -1,54 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { Box, Text } from 'ink';
import { theme } from '../../semantic-colors.js';
import type { HookEventDisplayInfo, HookMatcherDisplayInfo } from './types.js';
import { HookEventHeader } from './HookEventHeader.js';
import { HandlerListBody } from './HandlerListBody.js';
import { t } from '../../../i18n/index.js';
interface HookMatcherDetailStepProps {
hookEvent: HookEventDisplayInfo;
matcherGroup: HookMatcherDisplayInfo;
selectedIndex: number;
}
export function HookMatcherDetailStep({
hookEvent,
matcherGroup,
selectedIndex,
}: HookMatcherDetailStepProps): React.JSX.Element {
const hasConfigs = matcherGroup.configs.length > 0;
return (
<Box flexDirection="column" paddingX={1}>
<HookEventHeader
title={`${hookEvent.event} - ${t('Matcher:')} ${matcherGroup.matcher}`}
description={hookEvent.description}
exitCodes={hookEvent.exitCodes}
/>
{hasConfigs ? (
<HandlerListBody
configs={matcherGroup.configs}
selectedIndex={selectedIndex}
/>
) : (
<>
<Box>
<Text color={theme.text.secondary}>
{t('No hooks configured for this matcher.')}
</Text>
</Box>
<Box marginTop={1}>
<Text color={theme.text.secondary}>{t('Esc to go back')}</Text>
</Box>
</>
)}
</Box>
);
}

View File

@ -14,8 +14,10 @@ import {
import { HooksListStep } from './HooksListStep.js';
import type { HookEventDisplayInfo } from './types.js';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string, options?: { count?: string }) => {
// Handle pluralization
if (key === '{{count}} hook configured' && options?.count) {
return `${options.count} hook configured`;
}
@ -26,10 +28,12 @@ vi.mock('../../../i18n/index.js', () => ({
}),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })),
}));
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -48,30 +52,23 @@ describe('HooksListStep', () => {
const createMockHookInfo = (
event: HookEventName,
configCount = 0,
): HookEventDisplayInfo => {
const configs = Array(configCount)
): HookEventDisplayInfo => ({
event,
shortDescription: `Description for ${event}`,
description: `Detailed description for ${event}`,
exitCodes: [
{ code: 0, description: 'Success' },
{ code: 2, description: 'Block' },
],
configs: Array(configCount)
.fill(null)
.map((_, i) => ({
config: {
command: `hook-${i}`,
type: HookType.Command as const,
},
config: { command: `hook-${i}`, type: HookType.Command },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
matcher: '*',
enabled: true,
}));
return {
event,
shortDescription: `Description for ${event}`,
description: `Detailed description for ${event}`,
exitCodes: [
{ code: 0, description: 'Success' },
{ code: 2, description: 'Block' },
],
matcherGroups: configs.length > 0 ? [{ matcher: '*', configs }] : [],
};
};
})),
});
beforeEach(() => {
vi.clearAllMocks();

View File

@ -10,13 +10,6 @@ import { useTerminalSize } from '../../hooks/useTerminalSize.js';
import type { HookEventDisplayInfo } from './types.js';
import { t } from '../../../i18n/index.js';
function configCountFor(hook: HookEventDisplayInfo): number {
return hook.matcherGroups.reduce(
(sum, group) => sum + group.configs.length,
0,
);
}
interface HooksListStepProps {
hooks: HookEventDisplayInfo[];
selectedIndex: number;
@ -28,6 +21,7 @@ export function HooksListStep({
}: HooksListStepProps): React.JSX.Element {
const { columns: terminalWidth } = useTerminalSize();
// Calculate responsive width for hook name column (min 20, max 35)
const hookNameWidth = Math.min(
35,
Math.max(20, Math.floor(terminalWidth * 0.25)),
@ -41,11 +35,13 @@ export function HooksListStep({
);
}
// Calculate total configured hooks
const totalConfigured = hooks.reduce(
(sum, hook) => sum + configCountFor(hook),
(sum, hook) => sum + hook.configs.length,
0,
);
// Get the correct plural/singular form
const hooksConfiguredText =
totalConfigured === 1
? t('{{count}} hook configured', { count: String(totalConfigured) })
@ -70,7 +66,7 @@ export function HooksListStep({
{hooks.map((hook, index) => {
const isSelected = index === selectedIndex;
const configCount = configCountFor(hook);
const configCount = hook.configs.length;
const maxDigits = String(hooks.length).length;
const paddedIndex = String(index + 1).padStart(maxDigits);

View File

@ -5,46 +5,22 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { cleanup } from 'ink-testing-library';
import { HooksManagementDialog } from './HooksManagementDialog.js';
import { renderWithProviders } from '../../../test-utils/render.js';
import { useKeypress } from '../../hooks/useKeypress.js';
import { useConfig } from '../../contexts/ConfigContext.js';
import { loadSettings, SettingScope } from '../../../config/settings.js';
import type { Key } from '../../contexts/KeypressContext.js';
// Mock useKeypress
vi.mock('../../hooks/useKeypress.js', () => ({
useKeypress: vi.fn(),
}));
const mockedUseKeypress = vi.mocked(useKeypress);
const mockedUseConfig = vi.mocked(useConfig);
const mockedLoadSettings = vi.mocked(loadSettings);
let keypressHandler: ((key: Key) => void) | null = null;
/**
* Returns a `useConfig` return value with `disableAllHooks` flipped on, while
* keeping every other method shaped like the default mock at the top of this
* file. Used with `mockReturnValueOnce` for the initial render — the dialog's
* navigation stack is seeded in a `useState` initializer that only consults
* `disableAllHooks` once, so subsequent renders falling back to the default
* mock is fine.
*/
function disabledHooksConfig(): ReturnType<typeof useConfig> {
return {
getExtensions: vi.fn(() => []),
getDisableAllHooks: vi.fn(() => true),
getHookSystem: vi.fn(() => ({
getSessionHooksManager: vi.fn(() => ({
getAllSessionHooks: vi.fn(() => []),
})),
})),
getSessionId: vi.fn(() => 'test-session-id'),
} as unknown as ReturnType<typeof useConfig>;
}
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string, options?: { count?: string }) => {
// Handle pluralization
if (key === '{{count}} hook configured' && options?.count) {
return `${options.count} hook configured`;
}
@ -57,6 +33,7 @@ vi.mock('../../../i18n/index.js', () => ({
if (key === '{{count}} configured hooks' && options?.count) {
return `${options.count} configured hooks`;
}
// Handle interpolation for disabled message
if (
key ===
'All hooks are currently disabled. You have {{count}} that are not running.' &&
@ -68,10 +45,12 @@ vi.mock('../../../i18n/index.js', () => ({
}),
}));
// Mock useTerminalSize
vi.mock('../../hooks/useTerminalSize.js', () => ({
useTerminalSize: vi.fn(() => ({ columns: 120, rows: 24 })),
}));
// Mock useConfig
vi.mock('../../contexts/ConfigContext.js', async (importOriginal) => {
const actual =
await importOriginal<typeof import('../../contexts/ConfigContext.js')>();
@ -90,6 +69,7 @@ vi.mock('../../contexts/ConfigContext.js', async (importOriginal) => {
};
});
// Mock loadSettings
vi.mock('../../../config/settings.js', async (importOriginal) => {
const actual =
await importOriginal<typeof import('../../../config/settings.js')>();
@ -101,6 +81,7 @@ vi.mock('../../../config/settings.js', async (importOriginal) => {
};
});
// Mock semantic-colors
vi.mock('../../semantic-colors.js', () => ({
theme: {
text: {
@ -119,6 +100,7 @@ vi.mock('../../semantic-colors.js', () => ({
},
}));
// Mock createDebugLogger
vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
@ -126,13 +108,12 @@ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
...actual,
createDebugLogger: vi.fn(() => ({
log: vi.fn(),
debug: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
})),
};
});
// Helper to create a key object
function createKey(name: string, sequence = ''): Key {
return {
name,
@ -144,28 +125,15 @@ function createKey(name: string, sequence = ''): Key {
};
}
function mockSettingsHooks(userHooks: Record<string, unknown>): void {
mockedLoadSettings.mockReturnValue({
forScope: vi.fn((scope: SettingScope) => ({
settings:
scope === SettingScope.User ? { hooks: userHooks } : { hooks: {} },
})),
} as unknown as ReturnType<typeof loadSettings>);
}
function pressKey(name: string, sequence = ''): void {
const latestHandler = mockedUseKeypress.mock.calls.at(-1)?.[0];
expect(latestHandler).toBeDefined();
latestHandler!(createKey(name, sequence));
}
describe('HooksManagementDialog', () => {
const mockOnClose = vi.fn();
let keypressHandler: ((key: Key) => void) | null = null;
beforeEach(() => {
vi.clearAllMocks();
keypressHandler = null;
// Mock useKeypress to capture the handler
mockedUseKeypress.mockImplementation((handler) => {
keypressHandler = handler;
});
@ -173,195 +141,119 @@ describe('HooksManagementDialog', () => {
afterEach(() => {
keypressHandler = null;
cleanup();
});
it('should render loading state initially', () => {
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
describe('Initial rendering', () => {
it('should render loading state initially', () => {
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
expect(lastFrame()).toContain('Loading hooks');
});
it('should allow Escape to close during loading state', () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
});
it('should register the keypress handler with isActive: true', () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
expect(mockedUseKeypress).toHaveBeenCalled();
expect(mockedUseKeypress.mock.calls[0][1]).toEqual({ isActive: true });
});
it('should render HOOKS_DISABLED step on first render when disableAllHooks is true', () => {
// `renderContent` checks the HOOKS_DISABLED branch before the isLoading
// branch, so the disabled view is visible synchronously on the initial
// render — no need to wait for the hooks-loading effect.
mockedUseConfig.mockReturnValueOnce(disabledHooksConfig());
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
expect(lastFrame()).toContain('Hook Configuration - Disabled');
});
it('should close dialog on Escape when disableAllHooks is true', () => {
mockedUseConfig.mockReturnValueOnce(disabledHooksConfig());
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
});
it('should navigate from a matcher hook to matcher detail', async () => {
mockSettingsHooks({
PreToolUse: [
{
matcher: 'Read',
hooks: [{ type: 'command', command: 'echo read' }],
},
{
matcher: 'Bash',
hooks: [{ type: 'command', command: 'echo bash' }],
},
],
expect(lastFrame()).toContain('Loading hooks');
});
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
it('should render with border', async () => {
const { lastFrame, unmount } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hooks');
});
await new Promise((resolve) => setTimeout(resolve, 100));
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('[User] Read');
});
// The dialog should have a border (rendered as box-drawing characters)
const output = lastFrame();
expect(output).toBeTruthy();
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [User] Bash');
});
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('PreToolUse - Matcher: Bash');
expect(lastFrame()).toContain('echo bash');
});
pressKey('escape', '\x1b');
await vi.waitFor(() => {
expect(lastFrame()).toContain('PreToolUse - Matchers');
unmount();
});
});
it('should navigate from matcher detail to config detail', async () => {
mockSettingsHooks({
PreToolUse: [
{
matcher: 'Read',
hooks: [{ type: 'command', command: 'echo read' }],
},
{
matcher: 'Bash',
hooks: [
{ type: 'command', command: 'echo first' },
{ type: 'command', command: 'echo second' },
],
},
],
describe('Keyboard navigation - HOOKS_LIST step', () => {
it('should register keypress handler with isActive: true', async () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
await new Promise((resolve) => setTimeout(resolve, 100));
expect(mockedUseKeypress).toHaveBeenCalled();
const options = mockedUseKeypress.mock.calls[0][1];
expect(options).toEqual({ isActive: true });
});
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
it('should close dialog on Escape key', async () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hooks');
await new Promise((resolve) => setTimeout(resolve, 100));
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
});
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('[User] Read');
});
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [User] Bash');
});
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('PreToolUse - Matcher: Bash');
});
it('should not go above first item when pressing up', async () => {
const { unmount } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [command] echo second');
});
pressKey('return');
await new Promise((resolve) => setTimeout(resolve, 100));
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hook details');
expect(lastFrame()).toContain('echo second');
// Press up multiple times from first item
keypressHandler!(createKey('up'));
keypressHandler!(createKey('up'));
keypressHandler!(createKey('up'));
// Should still be at first item (no crash)
unmount();
});
});
it('should navigate directly from a non-matcher hook to config detail', async () => {
mockSettingsHooks({
Stop: [
{
hooks: [{ type: 'command', command: 'echo stop one' }],
},
{
hooks: [{ type: 'command', command: 'echo stop two' }],
},
],
describe('Keyboard navigation - HOOKS_DISABLED step', () => {
it('should show disabled state when disableAllHooks is true', async () => {
// Override the mock for this test
const configContext = await import('../../contexts/ConfigContext.js');
vi.mocked(configContext.useConfig).mockReturnValue({
getExtensions: vi.fn(() => []),
getDisableAllHooks: vi.fn(() => true),
} as unknown as ReturnType<typeof configContext.useConfig>);
const { lastFrame, unmount } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
await new Promise((resolve) => setTimeout(resolve, 100));
const output = lastFrame();
expect(output).toContain('Hook Configuration - Disabled');
unmount();
});
const { lastFrame } = renderWithProviders(
<HooksManagementDialog onClose={mockOnClose} />,
);
it('should close dialog on Escape key when hooks are disabled', async () => {
const configContext = await import('../../contexts/ConfigContext.js');
vi.mocked(configContext.useConfig).mockReturnValue({
getExtensions: vi.fn(() => []),
getDisableAllHooks: vi.fn(() => true),
} as unknown as ReturnType<typeof configContext.useConfig>);
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hooks');
});
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
for (let i = 0; i < 6; i++) {
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain(`❯ ${i + 2}.`);
});
}
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 7. Stop');
});
pressKey('return');
await vi.waitFor(() => {
expect(lastFrame()).toContain('Stop');
expect(lastFrame()).toContain('echo stop one');
});
await new Promise((resolve) => setTimeout(resolve, 100));
pressKey('down');
await vi.waitFor(() => {
expect(lastFrame()).toContain('❯ 2. [command] echo stop two');
});
pressKey('return');
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
await vi.waitFor(() => {
expect(lastFrame()).toContain('Hook details');
expect(lastFrame()).toContain('echo stop two');
expect(mockOnClose).toHaveBeenCalledTimes(1);
});
});
describe('Loading and error states', () => {
it('should allow Escape to close during loading state', () => {
renderWithProviders(<HooksManagementDialog onClose={mockOnClose} />);
// Don't wait for loading to complete
expect(keypressHandler).not.toBeNull();
keypressHandler!(createKey('escape', '\x1b'));
expect(mockOnClose).toHaveBeenCalledTimes(1);
});
});
});

View File

@ -25,27 +25,28 @@ import type {
HookEventDisplayInfo,
} from './types.js';
import { HOOKS_MANAGEMENT_STEPS } from './types.js';
import { addConfigToMatcherGroup, getAllConfigs } from './matcherGrouping.js';
import { HooksListStep } from './HooksListStep.js';
import { HookDetailStep } from './HookDetailStep.js';
import { HookMatcherDetailStep } from './HookMatcherDetailStep.js';
import { HookConfigDetailStep } from './HookConfigDetailStep.js';
import { HooksDisabledStep } from './HooksDisabledStep.js';
import {
DISPLAY_HOOK_EVENTS,
getTranslatedSourceDisplayMap,
createEmptyHookEventInfo,
supportsMatchers,
} from './constants.js';
import { t } from '../../../i18n/index.js';
const debugLogger = createDebugLogger('HOOKS_DIALOG');
/**
* Type guard to check if a value is a valid HookConfig
*/
function isValidHookConfig(config: unknown): config is HookConfig {
if (typeof config !== 'object' || config === null || !('type' in config)) {
return false;
}
const obj = config as Record<string, unknown>;
// Check based on type
if (obj['type'] === 'command') {
return 'command' in obj && typeof obj['command'] === 'string';
}
@ -61,37 +62,52 @@ function isValidHookConfig(config: unknown): config is HookConfig {
return false;
}
/**
* Type guard to check if a value is a valid HookDefinition
*/
function isValidHookDefinition(def: unknown): def is HookDefinition {
if (typeof def !== 'object' || def === null) {
return false;
}
const obj = def as Record<string, unknown>;
// hooks array is required
if (!('hooks' in obj) || !Array.isArray(obj['hooks'])) {
return false;
}
// Validate each hook config in the array
for (const hook of obj['hooks']) {
if (!isValidHookConfig(hook)) {
return false;
}
}
// matcher is optional but must be a string if present
if ('matcher' in obj && typeof obj['matcher'] !== 'string') {
return false;
}
// sequential is optional but must be a boolean if present
if ('sequential' in obj && typeof obj['sequential'] !== 'boolean') {
return false;
}
return true;
}
/**
* Type guard to check if a value is a valid hooks record
* Note: This validates the structure but allows individual events to have
* invalid configs - those will be filtered out during processing.
*/
function isValidHooksRecord(hooks: unknown): hooks is Record<string, unknown> {
if (typeof hooks !== 'object' || hooks === null) {
return false;
}
// Basic structure check - must be a record with array values for event keys
const record = hooks as Record<string, unknown>;
for (const [key, value] of Object.entries(record)) {
// Skip non-event configuration fields
if (HOOKS_CONFIG_FIELDS.includes(key)) {
continue;
}
// Event values should be arrays (even if contents are invalid)
if (!Array.isArray(value)) {
return false;
}
@ -99,6 +115,10 @@ function isValidHooksRecord(hooks: unknown): hooks is Record<string, unknown> {
return true;
}
/**
* Safely extract hook definitions for a specific event
* Returns empty array if the definitions are invalid
*/
function getValidHookDefinitions(
hooksRecord: Record<string, unknown>,
eventName: string,
@ -128,6 +148,11 @@ export function HooksManagementDialog({
const { columns: width } = useTerminalSize();
const boxWidth = width - 4;
// Check if hooks are disabled
// Note: This value is captured at dialog open time. If disableAllHooks
// changes while the dialog is open (e.g., via settings.json edit),
// the dialog will not react to the change until it's closed and reopened.
// This is intentional - the dialog represents a snapshot of the current state.
const disableAllHooks = config?.getDisableAllHooks() ?? false;
const [navigationStack, setNavigationStack] = useState<string[]>([
@ -136,19 +161,20 @@ export function HooksManagementDialog({
: HOOKS_MANAGEMENT_STEPS.HOOKS_LIST,
]);
const [selectedHookIndex, setSelectedHookIndex] = useState<number>(-1);
const [selectedMatcherIndex, setSelectedMatcherIndex] = useState<number>(-1);
const [selectedConfigIndex, setSelectedConfigIndex] = useState<number>(-1);
// Track selected index within each step for keyboard navigation
const [listSelectedIndex, setListSelectedIndex] = useState<number>(0);
const [detailSelectedIndex, setDetailSelectedIndex] = useState<number>(0);
const [matcherSelectedIndex, setMatcherSelectedIndex] = useState<number>(0);
const [hooks, setHooks] = useState<HookEventDisplayInfo[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [loadError, setLoadError] = useState<string | null>(null);
// Current step
const currentStep =
navigationStack[navigationStack.length - 1] ||
HOOKS_MANAGEMENT_STEPS.HOOKS_LIST;
// Selected hook event
const selectedHook = useMemo(() => {
if (selectedHookIndex >= 0 && selectedHookIndex < hooks.length) {
return hooks[selectedHookIndex];
@ -156,20 +182,11 @@ export function HooksManagementDialog({
return null;
}, [hooks, selectedHookIndex]);
const selectedMatcher = useMemo(() => {
if (
selectedHook &&
selectedMatcherIndex >= 0 &&
selectedMatcherIndex < selectedHook.matcherGroups.length
) {
return selectedHook.matcherGroups[selectedMatcherIndex];
}
return null;
}, [selectedHook, selectedMatcherIndex]);
// Centralized keyboard handler
useKeypress(
(key) => {
if (isLoading || loadError) {
// Allow Escape to close even during loading/error states
if (key.name === 'escape') {
onClose();
}
@ -193,10 +210,8 @@ export function HooksManagementDialog({
} else if (key.name === 'return') {
if (hooks.length > 0 && listSelectedIndex >= 0) {
setSelectedHookIndex(listSelectedIndex);
setSelectedMatcherIndex(-1);
setSelectedConfigIndex(-1);
setDetailSelectedIndex(0);
setMatcherSelectedIndex(0);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL,
@ -210,62 +225,15 @@ export function HooksManagementDialog({
case HOOKS_MANAGEMENT_STEPS.HOOK_DETAIL:
if (key.name === 'escape') {
handleNavigateBack();
} else if (selectedHook) {
const matcherMode = supportsMatchers(selectedHook.event);
if (matcherMode) {
if (selectedHook.matcherGroups.length === 0) {
break;
}
if (keyMatchers[Command.SELECTION_UP](key)) {
setDetailSelectedIndex((prev) => Math.max(0, prev - 1));
} else if (keyMatchers[Command.SELECTION_DOWN](key)) {
setDetailSelectedIndex((prev) =>
Math.min(selectedHook.matcherGroups.length - 1, prev + 1),
);
} else if (key.name === 'return') {
setSelectedMatcherIndex(detailSelectedIndex);
setMatcherSelectedIndex(0);
setSelectedConfigIndex(-1);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_MATCHER_DETAIL,
]);
}
} else {
const flatConfigs = getAllConfigs(selectedHook);
if (flatConfigs.length === 0) {
break;
}
if (keyMatchers[Command.SELECTION_UP](key)) {
setDetailSelectedIndex((prev) => Math.max(0, prev - 1));
} else if (keyMatchers[Command.SELECTION_DOWN](key)) {
setDetailSelectedIndex((prev) =>
Math.min(flatConfigs.length - 1, prev + 1),
);
} else if (key.name === 'return') {
setSelectedMatcherIndex(-1);
setSelectedConfigIndex(detailSelectedIndex);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL,
]);
}
}
}
break;
case HOOKS_MANAGEMENT_STEPS.HOOK_MATCHER_DETAIL:
if (key.name === 'escape') {
handleNavigateBack();
} else if (selectedMatcher && selectedMatcher.configs.length > 0) {
} else if (selectedHook && selectedHook.configs.length > 0) {
if (keyMatchers[Command.SELECTION_UP](key)) {
setMatcherSelectedIndex((prev) => Math.max(0, prev - 1));
setDetailSelectedIndex((prev) => Math.max(0, prev - 1));
} else if (keyMatchers[Command.SELECTION_DOWN](key)) {
setMatcherSelectedIndex((prev) =>
Math.min(selectedMatcher.configs.length - 1, prev + 1),
setDetailSelectedIndex((prev) =>
Math.min(selectedHook.configs.length - 1, prev + 1),
);
} else if (key.name === 'return') {
setSelectedConfigIndex(matcherSelectedIndex);
setSelectedConfigIndex(detailSelectedIndex);
setNavigationStack((prev) => [
...prev,
HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL,
@ -281,12 +249,14 @@ export function HooksManagementDialog({
break;
default:
// No action for unknown steps
break;
}
},
{ isActive: true },
);
// Load hooks data
const fetchHooksData = useCallback((): HookEventDisplayInfo[] => {
if (!config) return [];
@ -296,36 +266,32 @@ export function HooksManagementDialog({
SettingScope.Workspace,
).settings;
// Get translated source display map
const sourceDisplayMap = getTranslatedSourceDisplayMap();
const result: HookEventDisplayInfo[] = [];
for (const eventName of DISPLAY_HOOK_EVENTS) {
const hookInfo = createEmptyHookEventInfo(eventName);
const groupByMatcher = supportsMatchers(eventName);
// Get hooks from user settings (with per-event validation)
const userSettingsRecord = userSettings as Record<string, unknown>;
const userHooksRaw = userSettingsRecord?.['hooks'];
if (isValidHooksRecord(userHooksRaw)) {
const userDefs = getValidHookDefinitions(userHooksRaw, eventName);
for (const def of userDefs) {
for (const hookConfig of def.hooks) {
addConfigToMatcherGroup(
hookInfo,
def.matcher,
def.sequential,
{
config: hookConfig,
source: HooksConfigSource.User,
sourceDisplay: sourceDisplayMap[HooksConfigSource.User],
enabled: true,
},
groupByMatcher,
);
hookInfo.configs.push({
config: hookConfig,
source: HooksConfigSource.User,
sourceDisplay: sourceDisplayMap[HooksConfigSource.User],
enabled: true,
});
}
}
}
// Get hooks from workspace settings (with per-event validation)
const workspaceSettingsRecord = workspaceSettings as Record<
string,
unknown
@ -338,22 +304,17 @@ export function HooksManagementDialog({
);
for (const def of workspaceDefs) {
for (const hookConfig of def.hooks) {
addConfigToMatcherGroup(
hookInfo,
def.matcher,
def.sequential,
{
config: hookConfig,
source: HooksConfigSource.Project,
sourceDisplay: sourceDisplayMap[HooksConfigSource.Project],
enabled: true,
},
groupByMatcher,
);
hookInfo.configs.push({
config: hookConfig,
source: HooksConfigSource.Project,
sourceDisplay: sourceDisplayMap[HooksConfigSource.Project],
enabled: true,
});
}
}
}
// Get hooks from extensions (with type validation)
const extensions = config.getExtensions() || [];
for (const extension of extensions) {
if (extension.isActive && extension.hooks?.[eventName]) {
@ -362,19 +323,13 @@ export function HooksManagementDialog({
for (const def of extensionHooks) {
if (isValidHookDefinition(def)) {
for (const hookConfig of def.hooks) {
addConfigToMatcherGroup(
hookInfo,
def.matcher,
def.sequential,
{
config: hookConfig,
source: HooksConfigSource.Extensions,
sourceDisplay: extension.name,
sourcePath: extension.path,
enabled: true,
},
groupByMatcher,
);
hookInfo.configs.push({
config: hookConfig,
source: HooksConfigSource.Extensions,
sourceDisplay: extension.name,
sourcePath: extension.path,
enabled: true,
});
}
}
}
@ -382,6 +337,7 @@ export function HooksManagementDialog({
}
}
// Get session hooks from SessionHooksManager
const hookSystem = config.getHookSystem();
if (hookSystem) {
const sessionId = config.getSessionId();
@ -390,23 +346,20 @@ export function HooksManagementDialog({
const allSessionHooks =
sessionHooksManager.getAllSessionHooks(sessionId);
// Filter hooks for this event
const eventSessionHooks = allSessionHooks.filter(
(hook: SessionHookEntry) => hook.eventName === eventName,
);
for (const sessionHook of eventSessionHooks) {
addConfigToMatcherGroup(
hookInfo,
sessionHook.matcher,
sessionHook.sequential,
{
config: sessionHook.config as HookConfig,
source: HooksConfigSource.Session,
sourceDisplay: t('Session (temporary)'),
enabled: true,
},
groupByMatcher,
);
// Session hooks have matcher stored separately from config
hookInfo.configs.push({
config: sessionHook.config as HookConfig,
source: HooksConfigSource.Session,
sourceDisplay: t('Session (temporary)'),
matcher: sessionHook.matcher,
enabled: true,
});
}
}
}
@ -417,6 +370,7 @@ export function HooksManagementDialog({
return result;
}, [config]);
// Load hooks data on initial render
useEffect(() => {
let cancelled = false;
setIsLoading(true);
@ -445,6 +399,7 @@ export function HooksManagementDialog({
};
}, [fetchHooksData]);
// Navigation handler for going back
const handleNavigateBack = useCallback(() => {
setNavigationStack((prev) => {
if (prev.length <= 1) {
@ -455,39 +410,27 @@ export function HooksManagementDialog({
});
}, [onClose]);
// Selected hook config
const selectedConfig = useMemo(() => {
if (!selectedHook) return null;
if (!supportsMatchers(selectedHook.event)) {
const flatConfigs = getAllConfigs(selectedHook);
if (
selectedConfigIndex >= 0 &&
selectedConfigIndex < flatConfigs.length
) {
return flatConfigs[selectedConfigIndex];
}
return null;
}
if (
selectedMatcher &&
selectedHook &&
selectedConfigIndex >= 0 &&
selectedConfigIndex < selectedMatcher.configs.length
selectedConfigIndex < selectedHook.configs.length
) {
return selectedMatcher.configs[selectedConfigIndex];
return selectedHook.configs[selectedConfigIndex];
}
return null;
}, [selectedHook, selectedMatcher, selectedConfigIndex]);
}, [selectedHook, selectedConfigIndex]);
// Calculate total configured hooks count
const configuredHooksCount = useMemo(
() =>
hooks.reduce(
(sum, hook) =>
sum + hook.matcherGroups.reduce((s, g) => s + g.configs.length, 0),
0,
),
() => hooks.reduce((sum, hook) => sum + hook.configs.length, 0),
[hooks],
);
// Render based on current step
const renderContent = () => {
// Show disabled state first (before loading check)
if (currentStep === HOOKS_MANAGEMENT_STEPS.HOOKS_DISABLED) {
return <HooksDisabledStep configuredHooksCount={configuredHooksCount} />;
}
@ -535,22 +478,6 @@ export function HooksManagementDialog({
</Box>
);
case HOOKS_MANAGEMENT_STEPS.HOOK_MATCHER_DETAIL:
if (selectedHook && selectedMatcher) {
return (
<HookMatcherDetailStep
hookEvent={selectedHook}
matcherGroup={selectedMatcher}
selectedIndex={matcherSelectedIndex}
/>
);
}
return (
<Box flexDirection="column" paddingX={1}>
<Text color={theme.text.secondary}>{t('No matcher selected')}</Text>
</Box>
);
case HOOKS_MANAGEMENT_STEPS.HOOK_CONFIG_DETAIL:
if (selectedHook && selectedConfig) {
return (

View File

@ -5,16 +5,14 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
HookEventName,
HooksConfigSource,
hookEventSupportsMatcher,
} from '@qwen-code/qwen-code-core';
import { HookEventName, HooksConfigSource } from '@qwen-code/qwen-code-core';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
// Import after mocking
import {
getHookExitCodes,
getHookShortDescription,
@ -22,7 +20,6 @@ import {
getTranslatedSourceDisplayMap,
createEmptyHookEventInfo,
DISPLAY_HOOK_EVENTS,
supportsMatchers,
} from './constants.js';
describe('hooks constants', () => {
@ -86,24 +83,6 @@ describe('hooks constants', () => {
expect(exitCodes).toHaveLength(3);
});
it('should return exit codes for PostCompact event', () => {
const exitCodes = getHookExitCodes(HookEventName.PostCompact);
expect(exitCodes).toHaveLength(2);
expect(exitCodes[0].code).toBe(0);
expect(exitCodes[1].code).toBe('Other');
});
it('should return exit codes for StopFailure event', () => {
// Fire-and-forget per hookAggregator — both rows are documented as ignored.
const exitCodes = getHookExitCodes(HookEventName.StopFailure);
expect(exitCodes).toHaveLength(2);
expect(exitCodes[0].code).toBe(0);
expect(exitCodes[1].code).toBe('Other');
for (const row of exitCodes) {
expect(row.description).toContain('fire-and-forget');
}
});
it('should return empty array for unknown event', () => {
const exitCodes = getHookExitCodes('unknown_event' as HookEventName);
expect(exitCodes).toEqual([]);
@ -131,17 +110,6 @@ describe('hooks constants', () => {
expect(desc).toBe('When a new session is started');
});
it('should return description for PostCompact', () => {
const desc = getHookShortDescription(HookEventName.PostCompact);
expect(desc).toBe('After conversation compaction');
});
it('should return description for StopFailure', () => {
const desc = getHookShortDescription(HookEventName.StopFailure);
expect(desc).toContain('API error');
expect(desc).toContain('Stop');
});
it('should return empty string for unknown event', () => {
const desc = getHookShortDescription('unknown_event' as HookEventName);
expect(desc).toBe('');
@ -165,19 +133,6 @@ describe('hooks constants', () => {
expect(desc).toBe('');
});
it('should return description for PostCompact', () => {
const desc = getHookDescription(HookEventName.PostCompact);
expect(desc).toContain('trigger');
expect(desc).toContain('compact_summary');
});
it('should return description for StopFailure', () => {
const desc = getHookDescription(HookEventName.StopFailure);
expect(desc).toContain('error');
expect(desc).toContain('rate_limit');
expect(desc).toContain('Fire-and-forget');
});
it('should return empty string for unknown event', () => {
const desc = getHookDescription('unknown_event' as HookEventName);
expect(desc).toBe('');
@ -197,6 +152,7 @@ describe('hooks constants', () => {
it('should return translated strings', () => {
const map = getTranslatedSourceDisplayMap();
// All values should be strings (translated)
Object.values(map).forEach((value) => {
expect(typeof value).toBe('string');
expect(value.length).toBeGreaterThan(0);
@ -220,47 +176,12 @@ describe('hooks constants', () => {
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PreCompact);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PostCompact);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PermissionRequest);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PermissionDenied);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.TodoCreated);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.TodoCompleted);
});
it('should have 17 events', () => {
expect(DISPLAY_HOOK_EVENTS).toHaveLength(17);
});
});
describe('supportsMatchers', () => {
it('returns true for events with meaningful matchers', () => {
expect(supportsMatchers(HookEventName.PreToolUse)).toBe(true);
expect(supportsMatchers(HookEventName.PostToolUse)).toBe(true);
expect(supportsMatchers(HookEventName.PostToolUseFailure)).toBe(true);
expect(supportsMatchers(HookEventName.PermissionRequest)).toBe(true);
expect(supportsMatchers(HookEventName.Notification)).toBe(true);
expect(supportsMatchers(HookEventName.SessionStart)).toBe(true);
expect(supportsMatchers(HookEventName.SessionEnd)).toBe(true);
expect(supportsMatchers(HookEventName.SubagentStart)).toBe(true);
expect(supportsMatchers(HookEventName.SubagentStop)).toBe(true);
expect(supportsMatchers(HookEventName.PreCompact)).toBe(true);
expect(supportsMatchers(HookEventName.PostCompact)).toBe(true);
expect(supportsMatchers(HookEventName.StopFailure)).toBe(true);
});
it('returns false for events without matchers', () => {
expect(supportsMatchers(HookEventName.Stop)).toBe(false);
expect(supportsMatchers(HookEventName.UserPromptSubmit)).toBe(false);
expect(supportsMatchers(HookEventName.TodoCreated)).toBe(false);
expect(supportsMatchers(HookEventName.TodoCompleted)).toBe(false);
});
it('returns false for unknown events', () => {
expect(supportsMatchers('unknown_event' as HookEventName)).toBe(false);
});
it('covers every HookEventName value and matches core dispatch', () => {
for (const event of Object.values(HookEventName)) {
expect(supportsMatchers(event)).toBe(hookEventSupportsMatcher(event));
}
it('should have 16 events', () => {
expect(DISPLAY_HOOK_EVENTS).toHaveLength(16);
});
});
@ -274,7 +195,7 @@ describe('hooks constants', () => {
'Input to command is JSON of tool call arguments.',
);
expect(info.exitCodes).toHaveLength(3);
expect(info.matcherGroups).toEqual([]);
expect(info.configs).toEqual([]);
});
it('should create empty info for Stop', () => {
@ -286,7 +207,7 @@ describe('hooks constants', () => {
);
expect(info.description).toBe('');
expect(info.exitCodes).toHaveLength(3);
expect(info.matcherGroups).toEqual([]);
expect(info.configs).toEqual([]);
});
it('should create empty info for unknown event', () => {
@ -296,7 +217,7 @@ describe('hooks constants', () => {
expect(info.shortDescription).toBe('');
expect(info.description).toBe('');
expect(info.exitCodes).toEqual([]);
expect(info.matcherGroups).toEqual([]);
expect(info.configs).toEqual([]);
});
it('should create empty info for TodoCreated', () => {
@ -306,7 +227,7 @@ describe('hooks constants', () => {
expect(info.shortDescription).toBe('When a new todo item is created');
expect(info.description).toContain('todo_id');
expect(info.exitCodes).toHaveLength(3);
expect(info.matcherGroups).toEqual([]);
expect(info.configs).toEqual([]);
});
it('should create empty info for TodoCompleted', () => {
@ -318,7 +239,7 @@ describe('hooks constants', () => {
);
expect(info.description).toContain('previous_status');
expect(info.exitCodes).toHaveLength(3);
expect(info.matcherGroups).toEqual([]);
expect(info.configs).toEqual([]);
});
});
});

View File

@ -4,11 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import {
HooksConfigSource,
HookEventName,
hookEventSupportsMatcher,
} from '@qwen-code/qwen-code-core';
import { HooksConfigSource, HookEventName } from '@qwen-code/qwen-code-core';
import type { HookExitCode, HookEventDisplayInfo } from './types.js';
import { t } from '../../../i18n/index.js';
@ -94,28 +90,10 @@ export function getHookExitCodes(eventName: string): HookExitCode[] {
description: t('show stderr to user only but continue with compaction'),
},
],
[HookEventName.PostCompact]: [
{ code: 0, description: t('stdout/stderr not shown') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.StopFailure]: [
{
code: 0,
description: t('fire-and-forget; exit status is ignored'),
},
{
code: 'Other',
description: t('fire-and-forget; exit status is ignored'),
},
],
[HookEventName.PermissionRequest]: [
{ code: 0, description: t('use hook decision if provided') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.PermissionDenied]: [
{ code: 0, description: t('stdout/stderr not shown') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.TodoCreated]: [
{ code: 0, description: t('allow todo creation') },
{
@ -155,17 +133,10 @@ export function getHookShortDescription(eventName: string): string {
'Right before a subagent concludes its response',
),
[HookEventName.PreCompact]: t('Before conversation compaction'),
[HookEventName.PostCompact]: t('After conversation compaction'),
[HookEventName.StopFailure]: t(
'When the turn ends due to an API error (fires instead of Stop)',
),
[HookEventName.SessionEnd]: t('When a session is ending'),
[HookEventName.PermissionRequest]: t(
'When a permission dialog is displayed',
),
[HookEventName.PermissionDenied]: t(
'When a tool call is denied before a permission dialog is displayed',
),
[HookEventName.TodoCreated]: t('When a new todo item is created'),
[HookEventName.TodoCompleted]: t('When a todo item is marked as completed'),
};
@ -208,18 +179,9 @@ export function getHookDescription(eventName: string): string {
[HookEventName.PreCompact]: t(
'Input to command is JSON with compaction details.',
),
[HookEventName.PostCompact]: t(
'Input to command is JSON with trigger (manual/auto) and compact_summary. Output is ignored for control purposes.',
),
[HookEventName.StopFailure]: t(
'Input to command is JSON with error (rate_limit, authentication_failed, billing_error, invalid_request, server_error, max_output_tokens, unknown) and optional error_details. Fire-and-forget: output and exit status are ignored.',
),
[HookEventName.PermissionRequest]: t(
'Input to command is JSON with tool_name, tool_input, and tool_use_id. Output JSON with hookSpecificOutput containing decision to allow or deny.',
),
[HookEventName.PermissionDenied]: t(
'Input to command is JSON with tool_name, tool_input, tool_use_id, and reason.',
),
[HookEventName.TodoCreated]: t(
'Input to command is JSON with todo_id, todo_content, todo_status, all_todos, and phase. In validation, output JSON with decision (allow/block/deny) and reason. In postWrite, block/deny is ignored.',
),
@ -246,13 +208,19 @@ export function getTranslatedSourceDisplayMap(): Record<
};
}
/**
* List of hook events to display in the UI
* Automatically synced with HookEventName enum from core.
* Note: Order follows the enum definition order. If UI presentation order
* needs to be different (e.g., grouped by lifecycle phase), consider using
* an explicit sorted array instead. Current enum order is acceptable for display.
*/
export const DISPLAY_HOOK_EVENTS: HookEventName[] =
Object.values(HookEventName);
export function supportsMatchers(eventName: HookEventName): boolean {
return hookEventSupportsMatcher(eventName);
}
/**
* Create empty hook event display info
*/
export function createEmptyHookEventInfo(
eventName: HookEventName,
): HookEventDisplayInfo {
@ -261,6 +229,6 @@ export function createEmptyHookEventInfo(
shortDescription: getHookShortDescription(eventName),
description: getHookDescription(eventName),
exitCodes: getHookExitCodes(eventName),
matcherGroups: [],
configs: [],
};
}

View File

@ -1,244 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect } from 'vitest';
import {
HookEventName,
HooksConfigSource,
HookType,
} from '@qwen-code/qwen-code-core';
import type { HookEventDisplayInfo } from './types.js';
import {
addConfigToMatcherGroup,
getAllConfigs,
normalizeMatcher,
} from './matcherGrouping.js';
function emptyHookInfo(): HookEventDisplayInfo {
return {
event: HookEventName.PreToolUse,
shortDescription: '',
description: '',
exitCodes: [],
matcherGroups: [],
};
}
describe('normalizeMatcher', () => {
it('returns "*" when matcher is undefined', () => {
expect(normalizeMatcher(undefined)).toBe('*');
});
it('returns "*" when matcher is empty string', () => {
expect(normalizeMatcher('')).toBe('*');
});
it('returns "*" when matcher is only whitespace', () => {
expect(normalizeMatcher(' ')).toBe('*');
});
it('returns the trimmed matcher when set', () => {
expect(normalizeMatcher(' Bash ')).toBe('Bash');
});
it('preserves regex-style matchers', () => {
expect(normalizeMatcher('Edit|Write')).toBe('Edit|Write');
});
});
describe('addConfigToMatcherGroup', () => {
it('creates a new group for an unseen matcher', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/x.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].matcher).toBe('Bash');
expect(info.matcherGroups[0].configs).toHaveLength(1);
expect(getAllConfigs(info)).toHaveLength(1);
});
it('reuses the existing group for the same matcher', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.Project,
sourceDisplay: 'Local Settings',
enabled: true,
});
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].configs).toHaveLength(2);
expect(getAllConfigs(info)).toHaveLength(2);
});
it('buckets undefined / empty matchers into "*"', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, undefined, undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, '', undefined, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].matcher).toBe('*');
expect(info.matcherGroups[0].configs).toHaveLength(2);
});
it('writes the normalized matcher onto the stored config', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, undefined, undefined, {
config: { type: HookType.Command, command: '/x.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(getAllConfigs(info)[0].matcher).toBe('*');
expect(info.matcherGroups[0].configs[0].matcher).toBe('*');
});
it('promotes group.sequential to true when any handler is sequential', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', false, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Bash', true, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups[0].sequential).toBe(true);
});
it('normalizes missing sequential to a false boolean, not undefined', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Bash', false, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups[0].sequential).toBe(false);
expect(info.matcherGroups[0].sequential).not.toBe(undefined);
const flat = getAllConfigs(info);
expect(flat[0].sequential).toBe(false);
expect(flat[1].sequential).toBe(false);
});
it('preserves insertion order across matchers', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(info, 'Bash', undefined, {
config: { type: HookType.Command, command: '/a.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, 'Edit|Write', undefined, {
config: { type: HookType.Command, command: '/b.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
addConfigToMatcherGroup(info, undefined, undefined, {
config: { type: HookType.Command, command: '/c.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
});
expect(info.matcherGroups.map((g) => g.matcher)).toEqual([
'Bash',
'Edit|Write',
'*',
]);
});
it('keeps non-matcher events in original handler order', () => {
const info = emptyHookInfo();
addConfigToMatcherGroup(
info,
'A',
undefined,
{
config: { type: HookType.Command, command: '/first.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
false,
);
addConfigToMatcherGroup(
info,
'B',
undefined,
{
config: { type: HookType.Command, command: '/second.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
false,
);
addConfigToMatcherGroup(
info,
'A',
undefined,
{
config: { type: HookType.Command, command: '/third.sh' },
source: HooksConfigSource.User,
sourceDisplay: 'User Settings',
enabled: true,
},
false,
);
expect(info.matcherGroups).toHaveLength(1);
expect(info.matcherGroups[0].matcher).toBe('*');
expect(
getAllConfigs(info).map((config) =>
config.config.type === HookType.Command ? config.config.command : '',
),
).toEqual(['/first.sh', '/second.sh', '/third.sh']);
});
});

View File

@ -1,50 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import type { HookConfigDisplayInfo, HookEventDisplayInfo } from './types.js';
export function normalizeMatcher(matcher?: string): string {
const trimmed = matcher?.trim();
return trimmed ? trimmed : '*';
}
export function addConfigToMatcherGroup(
hookInfo: HookEventDisplayInfo,
matcher: string | undefined,
sequential: boolean | undefined,
configInfo: HookConfigDisplayInfo,
groupByMatcher = true,
): void {
const normalizedMatcher = groupByMatcher ? normalizeMatcher(matcher) : '*';
const normalizedSequential = sequential ?? false;
const normalizedConfig: HookConfigDisplayInfo = {
...configInfo,
matcher: normalizedMatcher,
sequential: normalizedSequential,
};
let group = hookInfo.matcherGroups.find(
(candidate) => candidate.matcher === normalizedMatcher,
);
if (!group) {
group = {
matcher: normalizedMatcher,
sequential: normalizedSequential,
configs: [],
};
hookInfo.matcherGroups.push(group);
} else if (normalizedSequential) {
group.sequential = true;
}
group.configs.push(normalizedConfig);
}
export function getAllConfigs(
hookInfo: HookEventDisplayInfo,
): HookConfigDisplayInfo[] {
return hookInfo.matcherGroups.flatMap((group) => group.configs);
}

View File

@ -1,115 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HooksConfigSource, HookType } from '@qwen-code/qwen-code-core';
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
import {
formatSourceLabel,
formatSourceLabels,
getConfigSourceDisplay,
} from './sourceLabels.js';
import type { HookConfigDisplayInfo } from './types.js';
function makeConfig(
source: HooksConfigSource,
sourceDisplay = '',
): HookConfigDisplayInfo {
return {
config: { type: HookType.Command, command: '/x.sh' },
source,
sourceDisplay,
enabled: true,
};
}
describe('sourceLabels', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('formatSourceLabel', () => {
it('returns short label for each known source', () => {
expect(formatSourceLabel(HooksConfigSource.User)).toBe('User');
expect(formatSourceLabel(HooksConfigSource.Project)).toBe('Project');
expect(formatSourceLabel(HooksConfigSource.System)).toBe('System');
expect(formatSourceLabel(HooksConfigSource.Extensions)).toBe('Extension');
expect(formatSourceLabel(HooksConfigSource.Session)).toBe('Session');
});
it('falls back to the raw source string for unknown values', () => {
expect(formatSourceLabel('mystery' as HooksConfigSource)).toBe('mystery');
});
});
describe('formatSourceLabels', () => {
it('returns a single label for a single-source group', () => {
const configs = [
makeConfig(HooksConfigSource.User),
makeConfig(HooksConfigSource.User),
];
expect(formatSourceLabels(configs)).toBe('User');
});
it('joins distinct labels with comma + space for multi-source groups', () => {
const configs = [
makeConfig(HooksConfigSource.User),
makeConfig(HooksConfigSource.Project),
makeConfig(HooksConfigSource.Extensions),
];
expect(formatSourceLabels(configs)).toBe('User, Project, Extension');
});
it('preserves insertion order across distinct sources', () => {
const configs = [
makeConfig(HooksConfigSource.Project),
makeConfig(HooksConfigSource.User),
];
expect(formatSourceLabels(configs)).toBe('Project, User');
});
it('returns empty string when there are no configs', () => {
expect(formatSourceLabels([])).toBe('');
});
});
describe('getConfigSourceDisplay', () => {
it('returns the translated long label for non-extension sources', () => {
expect(getConfigSourceDisplay(makeConfig(HooksConfigSource.User))).toBe(
'User Settings',
);
expect(
getConfigSourceDisplay(makeConfig(HooksConfigSource.Project)),
).toBe('Local Settings');
expect(getConfigSourceDisplay(makeConfig(HooksConfigSource.System))).toBe(
'System Settings',
);
});
it('appends the extension name for Extensions-source configs', () => {
expect(
getConfigSourceDisplay(
makeConfig(HooksConfigSource.Extensions, 'my-ext'),
),
).toBe('Extensions (my-ext)');
});
it('uses the long "Session (temporary)" label for session-source configs', () => {
expect(
getConfigSourceDisplay(makeConfig(HooksConfigSource.Session)),
).toBe('Session (temporary)');
});
it('falls back to the raw source string for unknown sources', () => {
const config = makeConfig('mystery' as HooksConfigSource);
expect(getConfigSourceDisplay(config)).toBe('mystery');
});
});
});

View File

@ -1,44 +0,0 @@
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { HooksConfigSource } from '@qwen-code/qwen-code-core';
import type { HookConfigDisplayInfo } from './types.js';
import { getTranslatedSourceDisplayMap } from './constants.js';
import { t } from '../../../i18n/index.js';
export function formatSourceLabel(source: HooksConfigSource): string {
switch (source) {
case HooksConfigSource.User:
return t('User');
case HooksConfigSource.Project:
return t('Project');
case HooksConfigSource.System:
return t('System');
case HooksConfigSource.Extensions:
return t('Extension');
case HooksConfigSource.Session:
return t('Session');
default:
return source;
}
}
export function formatSourceLabels(configs: HookConfigDisplayInfo[]): string {
return Array.from(
new Set(configs.map((config) => formatSourceLabel(config.source))),
).join(', ');
}
export function getConfigSourceDisplay(config: {
source: HooksConfigSource;
sourceDisplay: string;
}): string {
const sourceDisplayMap = getTranslatedSourceDisplayMap();
if (config.source === HooksConfigSource.Extensions) {
return `${sourceDisplayMap[HooksConfigSource.Extensions]} (${config.sourceDisplay})`;
}
return sourceDisplayMap[config.source] || config.source;
}

View File

@ -10,46 +10,53 @@ import type {
HookEventName,
} from '@qwen-code/qwen-code-core';
/**
* Exit code description for hooks
*/
export interface HookExitCode {
code: number | string;
description: string;
}
/**
* UI display information for a hook event
*/
export interface HookEventDisplayInfo {
event: HookEventName;
shortDescription: string;
description: string;
exitCodes: HookExitCode[];
matcherGroups: HookMatcherDisplayInfo[];
}
export interface HookMatcherDisplayInfo {
matcher: string;
sequential?: boolean;
configs: HookConfigDisplayInfo[];
}
/**
* UI display information for a hook configuration
*/
export interface HookConfigDisplayInfo {
config: HookConfig;
source: HooksConfigSource;
sourceDisplay: string;
sourcePath?: string;
matcher?: string;
sequential?: boolean;
enabled: boolean;
}
/**
* Hook management dialog step names
*/
export const HOOKS_MANAGEMENT_STEPS = {
HOOKS_DISABLED: 'hooks_disabled',
HOOKS_LIST: 'hooks_list',
HOOK_DETAIL: 'hook_detail',
HOOK_MATCHER_DETAIL: 'hook_matcher_detail',
HOOK_CONFIG_DETAIL: 'hook_config_detail',
} as const;
export type HooksManagementStep =
(typeof HOOKS_MANAGEMENT_STEPS)[keyof typeof HOOKS_MANAGEMENT_STEPS];
/**
* Props for HooksManagementDialog
*/
export interface HooksManagementDialogProps {
onClose: () => void;
}

View File

@ -626,8 +626,7 @@ describe('useGeminiStream', () => {
queuedPrompt,
);
const queuedPromptAddItemIndex = mockAddItem.mock.calls.findIndex(
([item]) =>
item.type === MessageType.NOTIFICATION && item.text === queuedPrompt,
([item]) => item.type === MessageType.USER && item.text === queuedPrompt,
);
expect(queuedPromptAddItemIndex).toBeGreaterThanOrEqual(0);
expect(recordMidTurnUserMessage.mock.invocationCallOrder[0]).toBeLessThan(
@ -637,7 +636,7 @@ describe('useGeminiStream', () => {
mockSendMessageStream.mock.invocationCallOrder[0],
);
expect(mockAddItem).toHaveBeenCalledWith(
{ type: MessageType.NOTIFICATION, text: queuedPrompt },
{ type: MessageType.USER, text: queuedPrompt },
expect.any(Number),
);
expect(mockSendMessageStream).toHaveBeenCalledWith(
@ -732,7 +731,7 @@ describe('useGeminiStream', () => {
});
expect(mockAddItem).toHaveBeenCalledWith(
{ type: MessageType.NOTIFICATION, text: queuedPrompt },
{ type: MessageType.USER, text: queuedPrompt },
expect.any(Number),
);
expect(mockSendMessageStream).toHaveBeenCalledWith(

View File

@ -1198,15 +1198,11 @@ export const useGeminiStream = (
addItem(pendingHistoryItemRef.current, userMessageTimestamp);
setPendingHistoryItem(null);
}
const reasonClause =
eventValue?.triggerReason === 'image_overflow'
? `accumulated enough tool screenshots to trigger compaction for ${config.getModel()}`
: `approached the input token limit for ${config.getModel()}`;
return addItem(
{
type: 'info',
text:
`IMPORTANT: This conversation ${reasonClause}. ` +
`IMPORTANT: This conversation approached the input token limit for ${config.getModel()}. ` +
`A compressed context will be sent for future messages (compressed from: ` +
`${eventValue?.originalTokenCount ?? 'unknown'} to ` +
`${eventValue?.newTokenCount ?? 'unknown'} tokens).`,
@ -2351,7 +2347,8 @@ export const useGeminiStream = (
config
.getChatRecordingService()
?.recordMidTurnUserMessage(midTurnUserMessage, msg);
addItem({ type: MessageType.NOTIFICATION, text: msg }, Date.now());
// Record in UI history so the transcript stays complete.
addItem({ type: MessageType.USER, text: msg }, Date.now());
}
}
@ -2462,7 +2459,7 @@ export const useGeminiStream = (
const toolName = toolCall.request.name;
const fileName = path.basename(filePath);
const toolCallWithSnapshotFileName = `${timestamp}-${fileName}-${toolName}.json`;
const clientHistory = geminiClient?.getHistoryShallow();
const clientHistory = await geminiClient?.getHistory();
const toolCallWithSnapshotFilePath = path.join(
checkpointDir,
toolCallWithSnapshotFileName,

View File

@ -8,7 +8,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import * as child_process from 'child_process';
import { StreamingState } from '../types.js';
import type { StatusLinePresetReasoning } from '../statusLinePresets.js';
const debugLogMock = vi.hoisted(() => ({
log: vi.fn(),
@ -50,20 +49,11 @@ vi.mock('../contexts/UIStateContext.js', () => ({
useUIState: () => mockUIState,
}));
type MockContentGeneratorConfig = {
contextWindowSize: number;
reasoning?: StatusLinePresetReasoning;
};
const getMockContentGeneratorConfig = (): MockContentGeneratorConfig => ({
contextWindowSize: 131072,
});
const mockConfig = {
getTargetDir: vi.fn(() => '/test/dir'),
getModel: vi.fn(() => 'test-model'),
getCliVersion: vi.fn(() => '1.0.0'),
getContentGeneratorConfig: vi.fn(getMockContentGeneratorConfig),
getContentGeneratorConfig: vi.fn(() => ({ contextWindowSize: 131072 })),
};
vi.mock('../contexts/ConfigContext.js', () => ({
useConfig: () => mockConfig,
@ -159,9 +149,6 @@ describe('useStatusLine', () => {
mockUIState.sessionStats.metrics.files.totalLinesRemoved = 0;
mockVimMode.vimEnabled = false;
mockVimMode.vimMode = 'INSERT';
mockConfig.getContentGeneratorConfig.mockReturnValue({
contextWindowSize: 131072,
});
// Dynamic import to get fresh module after mocks
const mod = await import('./useStatusLine.js');
@ -249,21 +236,6 @@ describe('useStatusLine', () => {
expect(result.current.lines).toEqual(['test-model']);
});
it('renders model-with-reasoning and model-only together', () => {
mockConfig.getContentGeneratorConfig.mockReturnValue({
contextWindowSize: 131072,
reasoning: { effort: 'high' },
});
setStatusLineConfig({
type: 'preset',
items: ['model', 'model-with-reasoning'],
});
const { result } = renderHook(() => useStatusLine());
expect(child_process.exec).not.toHaveBeenCalled();
expect(result.current.lines).toEqual(['test-model high | test-model']);
});
it('refreshes when status line settings are saved in the same process', async () => {
mockUIState.branchName = 'dragon/feat-reproduce-skill';
setStatusLineConfig({

View File

@ -373,13 +373,12 @@ export function useStatusLine(): {
const { totalInputTokens, totalOutputTokens } = aggregateModelTokens(m);
const contentGeneratorConfig = cfg.getContentGeneratorConfig();
const contextWindowSize = contentGeneratorConfig?.contextWindowSize || 0;
const contextWindowSize =
cfg.getContentGeneratorConfig()?.contextWindowSize || 0;
const data = buildStatusLinePresetData({
sessionId: stats.sessionId,
version: cfg.getCliVersion(),
modelDisplayName: ui.currentModel || cfg.getModel(),
reasoning: contentGeneratorConfig?.reasoning,
currentDir,
branch: ui.branchName,
pullRequestNumber: pullRequestNumberRef.current,

View File

@ -11,18 +11,15 @@ import {
buildStatusLinePresetData,
buildStatusLinePresetLines,
DEFAULT_STATUS_LINE_PRESET_CONFIG,
formatModelWithReasoning,
formatTokenCount,
getRunStateLabel,
inferPullRequestNumber,
normalizeStatusLinePresetConfig,
orderStatusLinePresetItems,
STATUS_LINE_PRESET_ITEM_IDS,
STATUS_LINE_PRESET_ITEMS,
} from './statusLinePresets.js';
describe('statusLinePresets', () => {
it('normalizes valid preset configs and orders items by priority', () => {
it('normalizes valid preset configs and drops unknown items', () => {
expect(
normalizeStatusLinePresetConfig({
type: 'preset',
@ -57,51 +54,7 @@ describe('statusLinePresets', () => {
).toEqual(DEFAULT_STATUS_LINE_PRESET_CONFIG);
});
it('keeps default preset items in priority order', () => {
expect(DEFAULT_STATUS_LINE_PRESET_CONFIG.items).toEqual(
orderStatusLinePresetItems(
[...DEFAULT_STATUS_LINE_PRESET_CONFIG.items].reverse(),
),
);
});
it('orders preset items directly', () => {
expect(orderStatusLinePresetItems([])).toEqual([]);
expect(orderStatusLinePresetItems(['bogus'])).toEqual([]);
expect(orderStatusLinePresetItems([42, null])).toEqual([]);
expect(
orderStatusLinePresetItems([
'run-state',
'model',
'git-branch',
'model',
'context-remaining',
]),
).toEqual(['model', 'git-branch', 'context-remaining', 'run-state']);
});
it('formats model reasoning directly', () => {
expect(formatModelWithReasoning('qwen3-code-plus', false)).toBe(
'qwen3-code-plus reasoning off',
);
expect(
formatModelWithReasoning('qwen3-code-plus', { effort: 'high' }),
).toBe('qwen3-code-plus high');
expect(
formatModelWithReasoning('qwen3-code-plus', { effort: undefined }),
).toBe('qwen3-code-plus');
expect(formatModelWithReasoning('qwen3-code-plus', undefined)).toBe(
'qwen3-code-plus',
);
});
it('labels the plain model preset as model-only', () => {
expect(
STATUS_LINE_PRESET_ITEMS.find((item) => item.id === 'model')?.label,
).toBe('model-only');
});
it('renders available preset items in priority order', () => {
it('renders available preset items and omits unavailable optional fields', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
@ -122,12 +75,12 @@ describe('statusLinePresets', () => {
{
type: 'preset',
items: [
'run-state',
'model',
'branch-changes',
'pull-request-number',
'current-dir',
'context-remaining',
'current-dir',
'pull-request-number',
'branch-changes',
'run-state',
],
},
data,
@ -142,7 +95,6 @@ describe('statusLinePresets', () => {
sessionId: 'session-123',
version: '1.2.3',
modelDisplayName: 'qwen3-code-plus',
reasoning: { effort: 'high' },
currentDir: '/repo/project',
branch: 'feature/pr-4087-statusline',
contextWindowSize: 1000,
@ -163,67 +115,11 @@ describe('statusLinePresets', () => {
data,
),
).toEqual([
'qwen3-code-plus high | qwen3-code-plus | feature/pr-4087-statusline | Context 75% left | 1.2k in | 340 out | /repo/project | project | #4087 | +12 -3 | Context 25% used | Ready | v1.2.3 | 1.0k window | 250 used | session-123',
'qwen3-code-plus | Context 75% left | /repo/project | Context 25% used | feature/pr-4087-statusline | project | #4087 | +12 -3 | Ready | v1.2.3 | 1.0k window | 250 used | 1.2k in | 340 out | session-123',
]);
});
it('renders model and model-with-reasoning together', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
modelDisplayName: 'qwen3-code-plus',
reasoning: { effort: 'high' },
currentDir: '/repo/project',
branch: undefined,
contextWindowSize: 0,
currentUsage: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
totalLinesAdded: 0,
totalLinesRemoved: 0,
streamingState: StreamingState.Idle,
});
expect(
buildStatusLinePresetLines(
{
type: 'preset',
items: ['model', 'model-with-reasoning'],
},
data,
),
).toEqual(['qwen3-code-plus high | qwen3-code-plus']);
});
it('shows when reasoning is disabled', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
modelDisplayName: 'qwen3-code-plus',
reasoning: false,
currentDir: '/repo/project',
branch: undefined,
contextWindowSize: 0,
currentUsage: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
totalLinesAdded: 0,
totalLinesRemoved: 0,
streamingState: StreamingState.Idle,
});
expect(
buildStatusLinePresetLines(
{
type: 'preset',
items: ['model-with-reasoning'],
},
data,
),
).toEqual(['qwen3-code-plus reasoning off']);
});
it('falls back to the model name when reasoning is unset', () => {
it('treats model and model-with-reasoning as mutually exclusive', () => {
const data = buildStatusLinePresetData({
sessionId: 'session-123',
version: '1.2.3',
@ -243,7 +139,7 @@ describe('statusLinePresets', () => {
buildStatusLinePresetLines(
{
type: 'preset',
items: ['model-with-reasoning'],
items: ['model-with-reasoning', 'model'],
},
data,
),

View File

@ -9,20 +9,20 @@ import { StreamingState } from './types.js';
export const STATUS_LINE_PRESET_ITEM_IDS = [
'model-with-reasoning',
'model',
'git-branch',
'context-remaining',
'total-input-tokens',
'total-output-tokens',
'current-dir',
'context-used',
'git-branch',
'model',
'project-name',
'pull-request-number',
'branch-changes',
'context-used',
'run-state',
'qwen-version',
'context-window-size',
'used-tokens',
'total-input-tokens',
'total-output-tokens',
'session-id',
] as const;
@ -42,18 +42,10 @@ export interface StatusLinePresetConfig {
useThemeColors?: boolean;
}
export type StatusLinePresetReasoning =
| false
| {
effort?: 'low' | 'medium' | 'high' | 'max';
}
| undefined;
export interface StatusLinePresetData {
sessionId: string;
version: string;
modelDisplayName: string;
reasoning: StatusLinePresetReasoning;
currentDir: string;
projectName: string | undefined;
branch: string | undefined;
@ -89,9 +81,22 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
defaultSelected: true,
},
{
id: 'model',
label: 'model-only',
description: 'Current model name without reasoning level',
id: 'context-remaining',
label: 'context-remaining',
description: 'Percentage of context window remaining',
defaultSelected: true,
},
{
id: 'current-dir',
label: 'current-dir',
description: 'Current working directory',
defaultSelected: true,
},
{
id: 'context-used',
label: 'context-used',
description: 'Percentage of context window used',
defaultSelected: true,
},
{
id: 'git-branch',
@ -100,26 +105,9 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
defaultSelected: true,
},
{
id: 'context-remaining',
label: 'context-remaining',
description: 'Percentage of context window remaining',
defaultSelected: true,
},
{
id: 'total-input-tokens',
label: 'total-input-tokens',
description: 'Total input tokens used in session',
},
{
id: 'total-output-tokens',
label: 'total-output-tokens',
description: 'Total output tokens used in session',
},
{
id: 'current-dir',
label: 'current-dir',
description: 'Current working directory',
defaultSelected: true,
id: 'model',
label: 'model',
description: 'Current model name',
},
{
id: 'project-name',
@ -136,12 +124,6 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
label: 'branch-changes',
description: 'Session file changes added and removed',
},
{
id: 'context-used',
label: 'context-used',
description: 'Percentage of context window used',
defaultSelected: true,
},
{
id: 'run-state',
label: 'run-state',
@ -162,6 +144,16 @@ export const STATUS_LINE_PRESET_ITEMS: readonly StatusLinePresetItem[] = [
label: 'used-tokens',
description: 'Current prompt tokens used',
},
{
id: 'total-input-tokens',
label: 'total-input-tokens',
description: 'Total input tokens used in session',
},
{
id: 'total-output-tokens',
label: 'total-output-tokens',
description: 'Total output tokens used in session',
},
{
id: 'session-id',
label: 'session-id',
@ -173,26 +165,11 @@ const STATUS_LINE_PRESET_ITEM_ID_SET = new Set<string>(
STATUS_LINE_PRESET_ITEM_IDS,
);
export function orderStatusLinePresetItems(
items: readonly unknown[],
): StatusLinePresetItemId[] {
const selectedItems = new Set(
items.filter(
(item): item is StatusLinePresetItemId =>
typeof item === 'string' && STATUS_LINE_PRESET_ITEM_ID_SET.has(item),
),
);
return STATUS_LINE_PRESET_ITEM_IDS.filter((item) => selectedItems.has(item));
}
export const DEFAULT_STATUS_LINE_PRESET_CONFIG: StatusLinePresetConfig = {
type: 'preset',
useThemeColors: true,
items: orderStatusLinePresetItems(
STATUS_LINE_PRESET_ITEMS.filter((item) => item.defaultSelected).map(
(item) => item.id,
),
items: STATUS_LINE_PRESET_ITEMS.filter((item) => item.defaultSelected).map(
(item) => item.id,
),
};
@ -209,8 +186,12 @@ export function normalizeStatusLinePresetConfig(
}
const hasItemsArray = Array.isArray(candidate['items']);
const rawItems = hasItemsArray ? (candidate['items'] as unknown[]) : [];
const items = hasItemsArray
? orderStatusLinePresetItems(candidate['items'] as unknown[])
? rawItems.filter(
(item): item is StatusLinePresetItemId =>
typeof item === 'string' && STATUS_LINE_PRESET_ITEM_ID_SET.has(item),
)
: [];
return {
@ -219,7 +200,9 @@ export function normalizeStatusLinePresetConfig(
typeof candidate['useThemeColors'] === 'boolean'
? candidate['useThemeColors']
: true,
items: hasItemsArray ? items : [...DEFAULT_STATUS_LINE_PRESET_CONFIG.items],
items: hasItemsArray
? [...new Set(items)]
: [...DEFAULT_STATUS_LINE_PRESET_CONFIG.items],
};
}
@ -257,19 +240,6 @@ export function getRunStateLabel(state: StreamingState): string {
}
}
export function formatModelWithReasoning(
modelDisplayName: string,
reasoning: StatusLinePresetReasoning,
): string {
if (reasoning === false) {
return `${modelDisplayName} reasoning off`;
}
if (reasoning?.effort) {
return `${modelDisplayName} ${reasoning.effort}`;
}
return modelDisplayName;
}
export function inferPullRequestNumber(
branch: string | undefined,
): string | undefined {
@ -286,7 +256,6 @@ export function buildStatusLinePresetData(params: {
sessionId: string;
version: string | undefined;
modelDisplayName: string | undefined;
reasoning?: StatusLinePresetReasoning;
currentDir: string;
branch: string | undefined;
pullRequestNumber?: string | undefined;
@ -315,7 +284,6 @@ export function buildStatusLinePresetData(params: {
sessionId: params.sessionId,
version: params.version || 'unknown',
modelDisplayName: params.modelDisplayName || 'unknown',
reasoning: params.reasoning,
currentDir: params.currentDir,
projectName: nodePath.basename(params.currentDir) || undefined,
branch: params.branch,
@ -337,16 +305,20 @@ export function buildStatusLinePresetParts(
data: StatusLinePresetData,
): string[] {
const parts: string[] = [];
const seen = new Set<StatusLinePresetItemId>();
for (const item of config.items) {
if (seen.has(item)) {
continue;
}
seen.add(item);
for (const item of orderStatusLinePresetItems(config.items)) {
switch (item) {
case 'model-with-reasoning':
parts.push(
formatModelWithReasoning(data.modelDisplayName, data.reasoning),
);
break;
case 'model':
parts.push(data.modelDisplayName);
seen.add('model');
seen.add('model-with-reasoning');
break;
case 'context-remaining':
if (data.contextWindowSize > 0) {

View File

@ -641,7 +641,6 @@ export enum MessageType {
ARENA_SESSION_COMPLETE = 'arena_session_complete',
INSIGHT_PROGRESS = 'insight_progress',
BTW = 'btw',
NOTIFICATION = 'notification',
DIFF_STATS = 'diff_stats',
GOAL_STATUS = 'goal_status',
}

View File

@ -198,45 +198,6 @@ describe('computeApiTruncationIndex', () => {
});
});
describe('mid-turn user messages (notification type)', () => {
it('skips notification items so btw merged into functionResponse does not cause mismatch', () => {
// Mid-turn messages are type 'notification' in UI (not counted by
// isRealUserTurn) and merged into tool_result in API (skipped by
// isUserTextContent). Both sides agree → correct truncation index.
const ui: HistoryItem[] = [
userItem(1, 'first prompt'),
geminiItem(2),
{
type: 'notification',
id: 3,
text: 'btw side question',
} as HistoryItem,
userItem(5, 'next prompt'),
geminiItem(6),
];
const btwMergedIntoToolResult: Content = {
role: 'user',
parts: [
{
functionResponse: { name: 'tool', response: { result: 'ok' } },
} as unknown as Part,
{ text: 'btw side question' } as Part,
],
};
const api: Content[] = [
userContent('first prompt'),
modelContent('response with tool call'),
btwMergedIntoToolResult,
modelContent('response after btw'),
userContent('next prompt'),
modelContent('response 5'),
];
// notification is not counted → uiUserTurnCount=1 before 'next prompt'
// API has 2 user text entries (idx 0 and 4) → finds idx 4 correctly
expect(computeApiTruncationIndex(ui, 5, api)).toBe(4);
});
});
describe('with slash-command items in UI history', () => {
it('ignores slash-command items when counting user turns', () => {
const ui: HistoryItem[] = [

View File

@ -143,11 +143,7 @@ describe('resumeHistoryUtils', () => {
20,
);
expect(items).toContainEqual({
id: 21,
type: 'notification',
text: 'save logs',
});
expect(items).toContainEqual({ id: 21, type: 'user', text: 'save logs' });
});
it('marks tool results as error, captures thought text, and falls back when tool is missing', () => {

View File

@ -295,7 +295,7 @@ function convertToHistoryItems(
payload?.displayText ||
extractTextFromParts(record.message?.parts as Part[]);
if (text) {
items.push({ type: 'notification', text });
items.push({ type: 'user', text });
}
break;
}

View File

@ -234,7 +234,7 @@ describe('getStickyTodos', () => {
});
describe('sticky todo layout helpers', () => {
it('changes the layout key for status-only updates', () => {
it('keeps the layout key stable for status-only updates', () => {
const pendingTodos = [
{
id: 'todo-1',
@ -250,7 +250,7 @@ describe('sticky todo layout helpers', () => {
},
];
expect(getStickyTodosLayoutKey(pendingTodos, 64, 5)).not.toBe(
expect(getStickyTodosLayoutKey(pendingTodos, 64, 5)).toBe(
getStickyTodosLayoutKey(inProgressTodos, 64, 5),
);
expect(getStickyTodosRenderKey(pendingTodos)).not.toBe(
@ -258,33 +258,6 @@ describe('sticky todo layout helpers', () => {
);
});
it('uses the rendered open todos for the layout key', () => {
const todos = [
{
id: 'todo-1',
content: 'Finished task',
status: 'completed' as const,
},
{
id: 'todo-2',
content: 'Active task',
status: 'in_progress' as const,
},
{
id: 'todo-3',
content: 'Pending task',
status: 'pending' as const,
},
];
expect(getStickyTodosLayoutKey(todos, 64, 5)).toBe(
getStickyTodosLayoutKey(todos.slice(1), 64, 5),
);
expect(getStickyTodosLayoutKey(todos, 64, 1)).not.toBe(
getStickyTodosLayoutKey(todos, 64, 2),
);
});
it('changes the layout key when wrapping-sensitive inputs change', () => {
const todos = [
{

View File

@ -181,17 +181,14 @@ export function getStickyTodosLayoutKey(
}
const visibleTodoCount = clampStickyTodoVisibleItems(maxVisibleItems);
const orderedOpenTodos = getOrderedStickyTodos(todos).filter(
(todo) => todo.status !== 'completed',
);
const visibleTodos = orderedOpenTodos.slice(0, visibleTodoCount);
const hasHiddenTodos = orderedOpenTodos.length > visibleTodos.length;
const visibleTodos = todos.slice(0, visibleTodoCount);
const hasHiddenTodos = todos.length > visibleTodos.length;
return JSON.stringify({
width,
maxVisibleItems: visibleTodoCount,
hasHiddenTodos,
todos: visibleTodos.map((todo) => [todo.id, todo.content, todo.status]),
todos: visibleTodos.map((todo) => [todo.id, todo.content]),
});
}

View File

@ -0,0 +1,357 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// Mock cleanup.ts to avoid pulling in @qwen-code/qwen-code-core dependency chain
vi.mock('./cleanup.js', () => ({
registerCleanup: vi.fn(),
}));
import {
_resetCpuProfilerForTest,
_setSessionFactoryForTest,
clearCpuProfileRateLimit,
isCpuProfileRecording,
startCpuProfile,
stopCpuProfile,
} from './cpuProfiler.js';
function createMockSession() {
const mockProfile = {
nodes: [
{
id: 1,
callFrame: {
functionName: 'test',
scriptId: '1',
url: '',
lineNumber: 0,
columnNumber: 0,
},
hitCount: 10,
children: [],
},
],
startTime: 0,
endTime: 1000000,
samples: [1],
timeDeltas: [100],
};
const post = vi.fn().mockImplementation((method: string) => {
if (method === 'Profiler.stop') {
return Promise.resolve({ profile: mockProfile });
}
return Promise.resolve(undefined);
});
const connect = vi.fn();
const disconnect = vi.fn();
return { post, connect, disconnect };
}
describe('cpuProfiler', () => {
let tmpDir: string;
let mockSession: ReturnType<typeof createMockSession>;
beforeEach(() => {
_resetCpuProfilerForTest();
clearCpuProfileRateLimit();
mockSession = createMockSession();
_setSessionFactoryForTest(async () => mockSession);
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cpu-profiler-test-'));
});
afterEach(() => {
_resetCpuProfilerForTest();
_setSessionFactoryForTest(null);
vi.restoreAllMocks();
try {
fs.rmSync(tmpDir, { recursive: true, force: true });
} catch {
// ignore
}
});
describe('isCpuProfileRecording', () => {
it('returns false when not recording', () => {
expect(isCpuProfileRecording()).toBe(false);
});
it('returns true when recording', async () => {
await startCpuProfile();
expect(isCpuProfileRecording()).toBe(true);
});
});
describe('startCpuProfile', () => {
it('starts profiling successfully', async () => {
const result = await startCpuProfile();
expect(result).toEqual({ ok: true });
expect(mockSession.post).toHaveBeenCalledWith('Profiler.enable');
expect(mockSession.post).toHaveBeenCalledWith(
'Profiler.setSamplingInterval',
{ interval: 1000 },
);
expect(mockSession.post).toHaveBeenCalledWith('Profiler.start');
});
it('accepts custom sampling interval', async () => {
await startCpuProfile({ samplingInterval: 500 });
expect(mockSession.post).toHaveBeenCalledWith(
'Profiler.setSamplingInterval',
{ interval: 500 },
);
});
it('returns error when already recording', async () => {
await startCpuProfile();
const result = await startCpuProfile();
expect(result).toEqual({
ok: false,
error: 'CPU profiling is already in progress.',
});
});
it('returns error and resets state on session failure', async () => {
_setSessionFactoryForTest(async () => {
throw new Error('Connection refused');
});
const result = await startCpuProfile();
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toContain('Connection refused');
}
expect(isCpuProfileRecording()).toBe(false);
});
});
describe('stopCpuProfile', () => {
it('stops and writes profile file', async () => {
await startCpuProfile();
const result = await stopCpuProfile({ outputDir: tmpDir });
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.filePath).toMatch(/qwen-code-cpu-\d+-.*\.cpuprofile$/);
expect(fs.existsSync(result.filePath)).toBe(true);
const content = JSON.parse(fs.readFileSync(result.filePath, 'utf8'));
expect(content.nodes).toBeDefined();
expect(content.startTime).toBeDefined();
}
});
it('returns error when not recording', async () => {
const result = await stopCpuProfile({ outputDir: tmpDir });
expect(result).toEqual({
ok: false,
error: 'CPU profiler is not recording.',
});
});
it('calls Profiler.stop and Profiler.disable', async () => {
await startCpuProfile();
mockSession.post.mockClear();
await stopCpuProfile({ outputDir: tmpDir });
expect(mockSession.post).toHaveBeenCalledWith('Profiler.stop');
expect(mockSession.post).toHaveBeenCalledWith('Profiler.disable');
});
it('sets file permissions to 0o600', async () => {
await startCpuProfile();
const result = await stopCpuProfile({ outputDir: tmpDir });
if (result.ok && process.platform !== 'win32') {
const stats = fs.statSync(result.filePath);
expect(stats.mode & 0o777).toBe(0o600);
}
});
});
describe('rate limiting', () => {
it('enforces rate limit between writes', async () => {
const now = new Date('2026-05-29T10:00:00.000Z');
await startCpuProfile();
const first = await stopCpuProfile({ outputDir: tmpDir, now });
expect(first.ok).toBe(true);
// Second write within rate limit window
await startCpuProfile();
const second = await stopCpuProfile({
outputDir: tmpDir,
now: new Date(now.getTime() + 5000), // 5s later, within 30s limit
});
expect(second.ok).toBe(false);
if (!second.ok) {
expect(second.error).toContain('rate limit');
}
});
it('allows write after rate limit expires', async () => {
const now = new Date('2026-05-29T10:00:00.000Z');
await startCpuProfile();
await stopCpuProfile({ outputDir: tmpDir, now });
// After rate limit window
await startCpuProfile();
const result = await stopCpuProfile({
outputDir: tmpDir,
now: new Date(now.getTime() + 31000), // 31s later
});
expect(result.ok).toBe(true);
});
it('resets state to idle when rate-limited so user can retry', async () => {
const now = new Date('2026-05-29T10:00:00.000Z');
await startCpuProfile();
await stopCpuProfile({ outputDir: tmpDir, now });
// Start a new recording, then try to stop within rate limit window
await startCpuProfile();
const rateLimited = await stopCpuProfile({
outputDir: tmpDir,
now: new Date(now.getTime() + 5000),
});
expect(rateLimited.ok).toBe(false);
// State should be reset — a new startCpuProfile() must succeed
const restart = await startCpuProfile();
expect(restart.ok).toBe(true);
});
});
describe('old profile cleanup', () => {
it('removes old profiles beyond max count', async () => {
// Create 5 existing profiles
for (let i = 0; i < 5; i++) {
const name = `qwen-code-cpu-99999-2026-05-29T0${i}-00-00-000Z.cpuprofile`;
fs.writeFileSync(path.join(tmpDir, name), '{}');
// Stagger mtime so sort is deterministic
const mtime = new Date(Date.now() - (5 - i) * 1000);
fs.utimesSync(path.join(tmpDir, name), mtime, mtime);
}
clearCpuProfileRateLimit();
await startCpuProfile();
const result = await stopCpuProfile({
outputDir: tmpDir,
maxProfiles: 5,
});
expect(result.ok).toBe(true);
const files = fs
.readdirSync(tmpDir)
.filter((f) => f.endsWith('.cpuprofile'));
// Should have at most 5 files (new one replaces oldest)
expect(files.length).toBeLessThanOrEqual(5);
});
});
describe('conflict handling', () => {
it('rejects second start while recording', async () => {
const first = await startCpuProfile();
expect(first.ok).toBe(true);
const second = await startCpuProfile();
expect(second.ok).toBe(false);
if (!second.ok) {
expect(second.error).toContain('already in progress');
}
});
it('resets state after stop so new recording can start', async () => {
await startCpuProfile();
await stopCpuProfile({ outputDir: tmpDir });
clearCpuProfileRateLimit();
const result = await startCpuProfile();
expect(result.ok).toBe(true);
});
});
describe('initCpuProfiler', () => {
it('is idempotent — calling twice does not error', async () => {
const { initCpuProfiler } = await import('./cpuProfiler.js');
// First call
initCpuProfiler();
// Second call should be a no-op
initCpuProfiler();
// No error thrown means success
});
it('does not start recording when env var is unset', async () => {
_resetCpuProfilerForTest();
delete process.env['QWEN_CODE_CPU_PROFILE'];
const { initCpuProfiler } = await import('./cpuProfiler.js');
_resetCpuProfilerForTest();
initCpuProfiler();
expect(isCpuProfileRecording()).toBe(false);
});
});
describe('SIGUSR1 toggle (via start/stop cycle)', () => {
it('simulates signal toggle: start then stop', async () => {
// Simulate what handleSigusr1 does internally
expect(isCpuProfileRecording()).toBe(false);
// First signal: start
const startResult = await startCpuProfile();
expect(startResult.ok).toBe(true);
expect(isCpuProfileRecording()).toBe(true);
// Second signal: stop
const stopResult = await stopCpuProfile({ outputDir: tmpDir });
expect(stopResult.ok).toBe(true);
expect(isCpuProfileRecording()).toBe(false);
});
it('ignores stop when in idle state', async () => {
const result = await stopCpuProfile({ outputDir: tmpDir });
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toContain('not recording');
}
});
});
describe('empty profile guard', () => {
it('returns error when V8 returns empty profile', async () => {
_resetCpuProfilerForTest();
const emptyMock = {
post: vi.fn().mockImplementation((method: string) => {
if (method === 'Profiler.stop') {
return Promise.resolve({ profile: undefined });
}
return Promise.resolve(undefined);
}),
connect: vi.fn(),
disconnect: vi.fn(),
};
_setSessionFactoryForTest(async () => emptyMock);
await startCpuProfile();
const result = await stopCpuProfile({ outputDir: tmpDir });
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toContain('empty profile');
}
});
});
});

View File

@ -0,0 +1,440 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
/**
* CPU profiling utility that generates .cpuprofile files for Chrome DevTools.
*
* Three trigger modes:
* 1. Environment variable: QWEN_CODE_CPU_PROFILE=1 — records from process start to exit
* 2. Signal toggle: SIGUSR1 — first signal starts, second stops and writes
* 3. Command: /doctor cpu-profile [--duration N] — records for N seconds
*
* Output: ~/.qwen/cpu-profiles/qwen-code-cpu-<pid>-<timestamp>.cpuprofile
* Zero overhead when disabled (single env var check at init).
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { registerCleanup } from './cleanup.js';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type ProfilerState = 'idle' | 'recording' | 'stopping';
export type CpuProfileStartResult = { ok: true } | { ok: false; error: string };
export type CpuProfileStopResult =
| { ok: true; filePath: string }
| { ok: false; error: string };
// Custom interface rather than importing from node:inspector/promises because
// the official Session.post() generic overload returns Promise<void>, making
// dynamic method dispatch (Profiler.start/stop) cumbersome without per-call casts.
interface InspectorSession {
connect(): void;
disconnect(): void;
post(method: string, params?: Record<string, unknown>): Promise<unknown>;
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MAX_PROFILES = 5;
const RATE_LIMIT_MS = 30_000;
const MIN_FREE_BYTES_AFTER_WRITE = 256 * 1024 * 1024;
const DEFAULT_SAMPLING_INTERVAL_US = 1000; // 1ms
const ESTIMATED_PROFILE_BYTES = 10 * 1024 * 1024; // 10 MiB conservative estimate
// ---------------------------------------------------------------------------
// Module state
// ---------------------------------------------------------------------------
let state: ProfilerState = 'idle';
let session: InspectorSession | null = null;
let initialized = false;
let signalHandlerRegistered = false;
const lastWriteByDir = new Map<string, number>();
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Initialize CPU profiler. Call once at process start.
* Always registers SIGUSR1 handler (for ad-hoc profiling).
* When QWEN_CODE_CPU_PROFILE=1, also starts recording immediately.
*/
export function initCpuProfiler(): void {
if (initialized) return;
initialized = true;
// Always register signal handler for ad-hoc profiling (non-Windows)
registerSignalHandler();
// Always register cleanup to flush any in-progress profile on exit
registerCleanup(async () => {
if (state === 'recording') {
const result = await stopCpuProfile();
if (result.ok) {
process.stderr.write(
`[cpu-profiler] Profile written: ${result.filePath}\n`,
);
}
}
});
const enabled = process.env['QWEN_CODE_CPU_PROFILE'] === '1';
if (!enabled) return;
// Start recording immediately in env-var mode
void startCpuProfile().then((result) => {
if (!result.ok) {
process.stderr.write(`[cpu-profiler] Failed to start: ${result.error}\n`);
}
});
}
/**
* Start CPU profiling.
* @param opts.samplingInterval - Sampling interval in microseconds (default 1000 = 1ms)
*/
export async function startCpuProfile(opts?: {
samplingInterval?: number;
}): Promise<CpuProfileStartResult> {
if (state !== 'idle') {
return {
ok: false,
error:
state === 'recording'
? 'CPU profiling is already in progress.'
: 'CPU profiler is currently stopping. Please wait a moment and try again.',
};
}
// Set state eagerly before the first await to prevent concurrent callers
// (e.g., rapid SIGUSR1 signals) from both passing the idle guard.
state = 'recording';
try {
const inspectorSession = await getOrCreateSession();
await inspectorSession.post('Profiler.enable');
await inspectorSession.post('Profiler.setSamplingInterval', {
interval: opts?.samplingInterval ?? DEFAULT_SAMPLING_INTERVAL_US,
});
await inspectorSession.post('Profiler.start');
return { ok: true };
} catch (error) {
state = 'idle';
disconnectSession();
return { ok: false, error: formatError(error) };
}
}
/**
* Stop CPU profiling and write the .cpuprofile file.
* @returns File path on success.
*/
export async function stopCpuProfile(options?: {
outputDir?: string;
now?: Date;
rateLimitMs?: number;
maxProfiles?: number;
}): Promise<CpuProfileStopResult> {
if (state !== 'recording') {
return {
ok: false,
error:
state === 'idle'
? 'CPU profiler is not recording.'
: 'CPU profiler is already stopping.',
};
}
const outputDir = options?.outputDir ?? defaultOutputDir();
const now = options?.now ?? new Date();
const rateLimitMs = options?.rateLimitMs ?? RATE_LIMIT_MS;
const maxProfiles = options?.maxProfiles ?? MAX_PROFILES;
// Check rate limit BEFORE writing to avoid excessive output.
// If rate-limited, tear down the V8 profiler (data is discarded) and reset
// state to 'idle' so the user can start a fresh recording later.
try {
enforceRateLimit(outputDir, now, rateLimitMs);
} catch (error) {
state = 'idle';
if (session) {
session.post('Profiler.stop').catch(() => {});
session.post('Profiler.disable').catch(() => {});
}
disconnectSession();
return { ok: false, error: formatError(error) };
}
state = 'stopping';
try {
if (!session) {
throw new Error(
'Inspector session lost unexpectedly during Profiler.stop; the profile data could not be retrieved.',
);
}
const result = (await session.post('Profiler.stop')) as {
profile: unknown;
};
if (!result.profile) {
throw new Error(
'V8 Profiler.stop returned an empty profile; recording may have been interrupted.',
);
}
await session.post('Profiler.disable');
fs.mkdirSync(outputDir, { recursive: true, mode: 0o700 });
try {
fs.chmodSync(outputDir, 0o700);
} catch {
// Best-effort hardening on filesystems without POSIX chmod.
}
checkDiskSpace(outputDir);
const filePath = path.join(
outputDir,
`qwen-code-cpu-${process.pid}-${formatTimestamp(now)}.cpuprofile`,
);
try {
fs.writeFileSync(filePath, JSON.stringify(result.profile), {
mode: 0o600,
});
} catch (writeError) {
try {
fs.rmSync(filePath, { force: true });
} catch {
// Best-effort cleanup of partial file.
}
throw writeError;
}
recordWrite(outputDir, now);
cleanupOldProfiles(outputDir, maxProfiles);
state = 'idle';
return { ok: true, filePath };
} catch (error) {
state = 'idle';
disconnectSession();
return { ok: false, error: formatError(error) };
}
}
/**
* Whether the profiler is currently recording.
*/
export function isCpuProfileRecording(): boolean {
return state === 'recording';
}
/**
* Register SIGUSR1 signal handler for toggle mode.
* Safe to call multiple times; only registers once.
* No-op on Windows (SIGUSR1 does not exist).
*/
export function registerSignalHandler(): void {
if (signalHandlerRegistered) return;
if (process.platform === 'win32') return;
signalHandlerRegistered = true;
process.on('SIGUSR1', handleSigusr1);
}
// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------
/** Reset all module state. Test-only. */
export function _resetCpuProfilerForTest(): void {
state = 'idle';
initialized = false;
signalHandlerRegistered = false;
disconnectSession();
lastWriteByDir.clear();
}
/** Clear rate limit state. Test-only. */
export function clearCpuProfileRateLimit(): void {
lastWriteByDir.clear();
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
function defaultOutputDir(): string {
return path.join(os.homedir(), '.qwen', 'cpu-profiles');
}
function formatTimestamp(now: Date): string {
return now.toISOString().replace(/[:.]/g, '-');
}
function formatError(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
// Overridable factory for testing (avoids mocking ESM dynamic imports)
let sessionFactory: (() => Promise<InspectorSession>) | null = null;
/** Override session creation for testing. */
export function _setSessionFactoryForTest(
factory: (() => Promise<InspectorSession>) | null,
): void {
sessionFactory = factory;
}
async function getOrCreateSession(): Promise<InspectorSession> {
if (session) return session;
if (sessionFactory) {
session = await sessionFactory();
return session;
}
// Dynamic import to avoid any overhead when profiling is disabled
const inspectorModule = await import('node:inspector/promises');
const newSession =
new inspectorModule.Session() as unknown as InspectorSession;
newSession.connect();
session = newSession;
return session;
}
function disconnectSession(): void {
if (session) {
try {
session.disconnect();
} catch {
// Ignore disconnect errors during cleanup.
}
session = null;
}
}
function handleSigusr1(): void {
if (state === 'idle') {
void startCpuProfile().then((result) => {
if (result.ok) {
process.stderr.write(
`[cpu-profiler] Recording started (PID ${process.pid}). Send SIGUSR1 again to stop.\n`,
);
} else {
process.stderr.write(
`[cpu-profiler] Failed to start: ${result.error}\n`,
);
}
});
} else if (state === 'recording') {
void stopCpuProfile().then((result) => {
if (result.ok) {
process.stderr.write(
`[cpu-profiler] Profile written: ${result.filePath}\n`,
);
} else {
process.stderr.write(
`[cpu-profiler] Failed to stop: ${result.error}\n`,
);
}
});
}
// state === 'stopping': ignore, already in progress
}
function enforceRateLimit(
outputDir: string,
now: Date,
rateLimitMs: number,
): void {
if (rateLimitMs <= 0) return;
const key = path.resolve(outputDir);
const nowMs = now.getTime();
const lastWriteMs = lastWriteByDir.get(key);
if (lastWriteMs !== undefined && nowMs - lastWriteMs < rateLimitMs) {
const waitSeconds = Math.ceil((rateLimitMs - (nowMs - lastWriteMs)) / 1000);
throw new Error(
`CPU profile rate limit: wait ${waitSeconds}s before writing another profile.`,
);
}
}
function recordWrite(outputDir: string, now: Date): void {
lastWriteByDir.set(path.resolve(outputDir), now.getTime());
}
function checkDiskSpace(outputDir: string): void {
try {
const stats = fs.statfsSync(outputDir);
const available = stats.bavail * stats.bsize;
if (available - ESTIMATED_PROFILE_BYTES < MIN_FREE_BYTES_AFTER_WRITE) {
throw new Error(
'Insufficient free disk space for CPU profile; skipping to avoid filling the disk.',
);
}
} catch (error) {
if (
error instanceof Error &&
error.message.includes('Insufficient free disk')
) {
throw error;
}
// statfsSync is not available on all platforms (e.g. Windows).
// Log a warning so it's not completely silent, but proceed anyway.
process.stderr.write(
'[cpu-profiler] Disk space check unavailable on this platform; skipping.\n',
);
}
}
function cleanupOldProfiles(outputDir: string, maxProfiles: number): void {
if (maxProfiles < 1) return;
let profiles: string[];
try {
profiles = fs
.readdirSync(outputDir)
.filter(
(name) =>
name.startsWith('qwen-code-cpu-') && name.endsWith('.cpuprofile'),
)
.map((name) => path.join(outputDir, name))
.sort((a, b) => {
try {
return (
fs.lstatSync(b).mtimeMs - fs.lstatSync(a).mtimeMs ||
path.basename(b).localeCompare(path.basename(a))
);
} catch {
// Fall back to filename comparison if stat fails
return path.basename(b).localeCompare(path.basename(a));
}
});
} catch {
return;
}
for (const filePath of profiles.slice(maxProfiles)) {
try {
fs.rmSync(filePath, { force: true });
} catch {
// Cleanup is best effort.
}
}
}

View File

@ -20,12 +20,9 @@ import { spawn } from 'node:child_process';
vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:child_process')>();
const mockSpawn = vi.fn();
// Named re-exports must be spelled out for vitest ESM mocking to rebind them.
return {
...actual,
default: { ...actual, spawn: mockSpawn },
spawn: mockSpawn,
spawn: vi.fn(),
};
});
@ -278,36 +275,6 @@ describe('relaunchAppInChildProcess', () => {
// Note: Additional integration tests for spawn behavior are complex due to module mocking
// limitations with ES modules. The core logic is tested in relaunchOnExitCode tests.
it('should invoke afterSpawn immediately after spawn, before waiting for child exit', async () => {
process.argv = ['/usr/bin/node', '/app/cli.js'];
const afterSpawn = vi.fn();
let spawned = false;
const mockChild = createMockChildProcess(0, false);
mockedSpawn.mockImplementation(() => {
spawned = true;
return mockChild;
});
const promise = relaunchAppInChildProcess([], [], { afterSpawn });
// Wait until spawn has been called
await vi.waitFor(() => {
expect(spawned).toBe(true);
});
// afterSpawn must have been called before child exits
expect(afterSpawn).toHaveBeenCalledTimes(1);
// Close the child so the promise resolves
mockChild.emit('close', 0);
await expect(promise).rejects.toThrow('PROCESS_EXIT_CALLED');
// afterSpawn should still be called only once (first spawn)
expect(afterSpawn).toHaveBeenCalledTimes(1);
});
it('should handle null exit code from child process', async () => {
process.argv = ['/usr/bin/node', '/app/cli.js'];

View File

@ -28,7 +28,6 @@ export async function relaunchOnExitCode(runner: () => Promise<number>) {
export async function relaunchAppInChildProcess(
additionalNodeArgs: string[],
additionalScriptArgs: string[],
options?: { afterSpawn?: () => void },
) {
if (process.env['QWEN_CODE_NO_RELAUNCH']) {
return;
@ -57,15 +56,6 @@ export async function relaunchAppInChildProcess(
env: newEnv,
});
// Allow the parent to clean up process.env after spawn copies it
// but before the next relaunch iteration.
try {
options?.afterSpawn?.();
} catch (err) {
child.kill();
throw err;
}
return new Promise<number>((resolve, reject) => {
child.on('error', reject);
child.on('close', (code) => {

View File

@ -1,6 +1,6 @@
{
"name": "@qwen-code/qwen-code-core",
"version": "0.17.0",
"version": "0.16.1",
"description": "Qwen Code Core",
"repository": {
"type": "git",

View File

@ -6,7 +6,11 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { Mock } from 'vitest';
import type { ConfigParameters, SandboxConfig } from './config.js';
import type {
ChatCompressionSettings,
ConfigParameters,
SandboxConfig,
} from './config.js';
import {
Config,
ApprovalMode,
@ -16,7 +20,6 @@ import {
} from './config.js';
import { Storage } from './storage.js';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { setGeminiMdFilename as mockSetGeminiMdFilename } from '../memory/const.js';
import {
@ -289,13 +292,6 @@ vi.mock('../ide/ide-client.js', () => ({
import { BaseLlmClient } from '../core/baseLlmClient.js';
const MEMORY_PRESSURE_ENV_KEYS = [
'QWEN_MEMORY_PRESSURE_SOFT',
'QWEN_MEMORY_PRESSURE_HARD',
'QWEN_MEMORY_PRESSURE_CRITICAL',
'QWEN_MEMORY_ENABLE_GC',
];
vi.mock('../core/baseLlmClient.js');
// Mock fireNotificationHook from toolHookTriggers
vi.mock('../core/toolHookTriggers.js', () => ({
@ -336,9 +332,6 @@ describe('Server Config (config.ts)', () => {
beforeEach(() => {
// Reset mocks if necessary
vi.clearAllMocks();
for (const envName of MEMORY_PRESSURE_ENV_KEYS) {
delete process.env[envName];
}
(fs.existsSync as Mock).mockReturnValue(true);
(fs.readdirSync as Mock).mockReturnValue([]);
(fs.statSync as Mock).mockReturnValue({
@ -433,192 +426,6 @@ describe('Server Config (config.ts)', () => {
});
});
describe('MemoryPressureMonitor isolation', () => {
it('returns a distinct monitor for child Configs created via Object.create', async () => {
const parent = new Config(baseParams);
await parent.initialize({ skipGeminiInitialization: true });
const child = Object.create(parent) as Config;
const parentMonitor = parent.getMemoryPressureMonitor();
const childMonitor = child.getMemoryPressureMonitor();
expect(parentMonitor).toBeDefined();
expect(childMonitor).toBeDefined();
expect(childMonitor).not.toBe(parentMonitor);
expect(child.getMemoryPressureMonitor()).toBe(childMonitor);
});
it('resets monitor cleanup state when starting a new session', async () => {
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
const monitor = config.getMemoryPressureMonitor();
expect(monitor).toBeDefined();
const resetSpy = vi.spyOn(monitor!, 'resetForNewSession');
config.startNewSession();
expect(resetSpy).toHaveBeenCalledTimes(1);
});
});
describe('MemoryPressure configuration environment', () => {
const restorers: Array<() => void> = [];
const originalEnv = new Map<string, string | undefined>();
beforeEach(() => {
originalEnv.clear();
for (const envName of MEMORY_PRESSURE_ENV_KEYS) {
originalEnv.set(envName, process.env[envName]);
delete process.env[envName];
}
});
afterEach(() => {
while (restorers.length > 0) {
restorers.pop()?.();
}
for (const [envName, value] of originalEnv) {
if (value === undefined) {
delete process.env[envName];
} else {
process.env[envName] = value;
}
}
originalEnv.clear();
});
function mockMemoryRatio(rssRatio: number, heapUsedBytes = 0): void {
const spy = vi.spyOn(process, 'memoryUsage').mockReturnValue({
rss: Math.ceil(os.totalmem() * rssRatio),
heapTotal: 512 * 1024 * 1024,
heapUsed: heapUsedBytes,
external: 0,
arrayBuffers: 0,
});
restorers.push(() => spy.mockRestore());
}
function mockStderrWrite(): Mock {
const spy = vi
.spyOn(process.stderr, 'write')
.mockImplementation(() => true);
restorers.push(() => spy.mockRestore());
return spy as unknown as Mock;
}
it('applies valid memory pressure env overrides', async () => {
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.3';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.6';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.9';
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.35);
expect(config.getMemoryPressureMonitor()?.getPressureLevel()).toBe(
'soft',
);
});
it('falls back to defaults and warns on strict env parse failures', async () => {
const stderrSpy = mockStderrWrite();
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.3extra';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.6';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.9';
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.35);
expect(config.getMemoryPressureMonitor()?.getPressureLevel()).toBe(
'normal',
);
expect(stderrSpy).toHaveBeenCalledWith(
expect.stringContaining('Invalid memory pressure config'),
);
});
it('falls back to defaults and warns on invalid threshold ordering', async () => {
const stderrSpy = mockStderrWrite();
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.7';
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
expect(config.getMemoryPressureMonitor()).toBeDefined();
expect(stderrSpy).toHaveBeenCalledWith(
expect.stringContaining(
'softPressureRatio must be < hardPressureRatio',
),
);
});
it.each(['NaN', 'Infinity', '0'])(
'falls back to defaults for invalid soft threshold %s',
async (value) => {
const stderrSpy = mockStderrWrite();
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = value;
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.35);
expect(config.getMemoryPressureMonitor()?.getPressureLevel()).toBe(
'normal',
);
expect(stderrSpy).toHaveBeenCalledWith(
expect.stringContaining('Invalid memory pressure config'),
);
},
);
it('enables explicit GC when requested by env', async () => {
process.env['QWEN_MEMORY_ENABLE_GC'] = '1';
const globalWithGc = global as typeof global & { gc?: () => void };
const originalGc = globalWithGc.gc;
const gcSpy = vi.fn();
Object.defineProperty(globalWithGc, 'gc', {
value: gcSpy,
configurable: true,
});
restorers.push(() => {
if (originalGc) {
Object.defineProperty(globalWithGc, 'gc', {
value: originalGc,
configurable: true,
});
} else {
delete globalWithGc.gc;
}
});
const config = new Config(baseParams);
await config.initialize({ skipGeminiInitialization: true });
mockMemoryRatio(0.85);
config.getMemoryPressureMonitor()?.performCheck();
await Promise.resolve();
expect(gcSpy).toHaveBeenCalledTimes(1);
});
it('child Config monitors inherit the parent memory pressure config snapshot', async () => {
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.3';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.6';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.9';
const parent = new Config(baseParams);
await parent.initialize({ skipGeminiInitialization: true });
process.env['QWEN_MEMORY_PRESSURE_SOFT'] = '0.9';
process.env['QWEN_MEMORY_PRESSURE_HARD'] = '0.95';
process.env['QWEN_MEMORY_PRESSURE_CRITICAL'] = '0.97';
const child = Object.create(parent) as Config;
mockMemoryRatio(0.35);
expect(child.getMemoryPressureMonitor()?.getPressureLevel()).toBe('soft');
});
});
describe('startNewSession', () => {
it('clears the FileReadCache so a new session does not inherit prior reads', () => {
// Regression guard: the file-read cache backs ReadFile's
@ -3561,4 +3368,55 @@ describe('Model Switching and Config Updates', () => {
);
});
});
describe('chatCompression.contextPercentageThreshold deprecation', () => {
// The proportional-threshold knob `contextPercentageThreshold` was
// removed in the auto-compaction threshold redesign (Task 8) — the
// value is now derived from `computeThresholds(...)` in the
// ChatCompressionService and is no longer user-tunable. Existing
// settings.json files that still set the field should keep working
// but get a one-time stderr warning so users know to remove it.
let warnSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
warnSpy.mockRestore();
});
it('logs a stderr warning when the deprecated field is set', () => {
new Config({
...baseParams,
chatCompression: {
contextPercentageThreshold: 0.5,
} as ChatCompressionSettings,
});
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining(
'chatCompression.contextPercentageThreshold has been removed',
),
);
});
it('does not warn when chatCompression is absent', () => {
new Config({ ...baseParams });
const warnCalls = warnSpy.mock.calls.map((c) => String(c[0]));
expect(
warnCalls.some((m) => m.includes('contextPercentageThreshold')),
).toBe(false);
});
it('does not warn when chatCompression is set without the deprecated field', () => {
new Config({
...baseParams,
chatCompression: { imageTokenEstimate: 1600 },
});
const warnCalls = warnSpy.mock.calls.map((c) => String(c[0]));
expect(
warnCalls.some((m) => m.includes('contextPercentageThreshold')),
).toBe(false);
});
});
});

View File

@ -48,12 +48,6 @@ import { GitService } from '../services/gitService.js';
import { GitWorktreeService } from '../services/gitWorktreeService.js';
import { cleanupStaleAgentWorktrees } from '../services/worktreeCleanup.js';
import { CronScheduler } from '../services/cronScheduler.js';
import {
MemoryPressureMonitor,
DEFAULT_PRESSURE_CONFIG,
validateMemoryPressureConfig,
type MemoryPressureConfig,
} from '../services/memoryPressureMonitor.js';
// Tools — only lightweight imports; tool classes are lazy-loaded via dynamic import
import {
@ -115,7 +109,6 @@ import {
import {
PermissionMode,
NotificationType,
type PermissionDeniedReason,
type PermissionSuggestion,
type HookEventName,
type HookDefinition,
@ -162,7 +155,6 @@ import { MemoryManager } from '../memory/manager.js';
import { CommitAttributionService } from '../services/commitAttribution.js';
const gitCoAuthorLogger = createDebugLogger('GIT_CO_AUTHOR');
const memoryPressureConfigLogger = createDebugLogger('MEMORY_PRESSURE');
import {
ModelsConfig,
@ -278,39 +270,12 @@ export interface BugCommandSettings {
export interface ChatCompressionSettings {
/**
* Estimated tokens for a single inline image / document part when
* apportioning chars across history during compression size estimation.
* apportioning chars across history in `findCompressSplitPoint`.
* Also used as the placeholder budget when stripping inline media
* out of the side-query compaction prompt. Default 1600.
* Env override: `QWEN_IMAGE_TOKEN_ESTIMATE`.
*/
imageTokenEstimate?: number;
/**
* Number of most-recently-touched files whose current content is
* restored (embedded or referenced) after auto-compaction. Default 5.
* Env override: `QWEN_COMPACT_MAX_RECENT_FILES`.
*/
maxRecentFilesToRetain?: number;
/**
* Number of most-recent images (tool screenshots / user pastes)
* restored after auto-compaction. Default 3.
* Env override: `QWEN_COMPACT_MAX_RECENT_IMAGES`.
*/
maxRecentImagesToRetain?: number;
/**
* When true, auto-compaction also fires once the number of
* tool-returned images accumulated in history reaches
* `screenshotTriggerThreshold`, independent of token usage. Aimed at
* computer-use sessions where frequent screenshots dilute model
* attention without necessarily exceeding the token budget. Default true.
* Env override: `QWEN_COMPACT_SCREENSHOT_TRIGGER` (`1`/`true`/`0`/`false`).
*/
enableScreenshotTrigger?: boolean;
/**
* Tool-returned image count at or above which the screenshot trigger
* fires (only when `enableScreenshotTrigger`). Default 50.
* Env override: `QWEN_COMPACT_SCREENSHOT_THRESHOLD`.
*/
screenshotTriggerThreshold?: number;
}
/**
@ -856,53 +821,6 @@ function normalizeConfigOutputFormat(
}
}
function loadMemoryPressureConfig(): MemoryPressureConfig {
const config: MemoryPressureConfig = { ...DEFAULT_PRESSURE_CONFIG };
try {
config.softPressureRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_SOFT',
config.softPressureRatio,
);
config.hardPressureRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_HARD',
config.hardPressureRatio,
);
config.criticalRatio = readMemoryPressureRatioEnv(
'QWEN_MEMORY_PRESSURE_CRITICAL',
config.criticalRatio,
);
if (process.env['QWEN_MEMORY_ENABLE_GC'] === '1') {
config.enableExplicitGC = true;
}
validateMemoryPressureConfig(config);
} catch (err) {
const fallbackMsg =
'[QWEN] WARNING: Invalid memory pressure config; using defaults. ' +
`Error: ${getErrorMessage(err)}`;
process.stderr.write(`${fallbackMsg}\n`);
memoryPressureConfigLogger.warn(fallbackMsg);
return { ...DEFAULT_PRESSURE_CONFIG };
}
return config;
}
function readMemoryPressureRatioEnv(envName: string, fallback: number): number {
const raw = process.env[envName];
if (!raw) {
return fallback;
}
const parsed = Number(raw);
if (!Number.isFinite(parsed)) {
throw new Error(`${envName} must be a finite number`);
}
return parsed;
}
/**
* Options for Config.initialize()
*/
@ -958,8 +876,6 @@ export class Config {
private pendingMcpBudgetCallback?: (event: McpBudgetEvent) => void;
private promptRegistry!: PromptRegistry;
private subagentManager!: SubagentManager;
private memoryPressureConfig?: MemoryPressureConfig;
private memoryPressureMonitor?: MemoryPressureMonitor;
private readonly backgroundTaskRegistry = new BackgroundTaskRegistry();
private readonly monitorRegistry = new MonitorRegistry();
private backgroundAgentResumeService?: BackgroundAgentResumeService;
@ -1255,6 +1171,24 @@ export class Config {
this.loadMemoryFromIncludeDirectories =
params.loadMemoryFromIncludeDirectories ?? false;
this.importFormat = params.importFormat ?? 'tree';
// Auto-compaction threshold moved to built-in constants (computeThresholds
// in chatCompressionService.ts). The old `contextPercentageThreshold`
// field is deprecated; if present in user settings, emit a one-time
// warning and ignore the value.
if (
params.chatCompression &&
typeof (params.chatCompression as Record<string, unknown>)[
'contextPercentageThreshold'
] !== 'undefined'
) {
// eslint-disable-next-line no-console
console.warn(
'[qwen-code] chatCompression.contextPercentageThreshold has been removed ' +
'and is now controlled by built-in thresholds. Setting will be ignored. ' +
'Remove this key from your settings.json to silence this warning; ' +
'see docs/users/configuration/settings.md for current compaction behavior.',
);
}
this.chatCompression = params.chatCompression;
this.interactive = params.interactive ?? false;
this.trustedFolder = params.trustedFolder;
@ -1490,16 +1424,6 @@ export class Config {
signal,
);
break;
case 'PermissionDenied':
result = await hookSystem.firePermissionDeniedEvent(
(input['tool_name'] as string) || '',
(input['tool_input'] as Record<string, unknown>) || {},
(input['tool_use_id'] as string) || '',
(input['reason'] as PermissionDeniedReason) ||
'classifier_blocked',
signal,
);
break;
case 'SubagentStart':
result = await hookSystem.fireSubagentStartEvent(
(input['agent_id'] as string) || '',
@ -1563,12 +1487,6 @@ export class Config {
}
this.debugLogger.debug('Skill manager initialized');
this.memoryPressureConfig = loadMemoryPressureConfig();
this.memoryPressureMonitor = new MemoryPressureMonitor(
this,
this.memoryPressureConfig,
);
this.permissionManager = new PermissionManager(this);
this.permissionManager.initialize();
this.debugLogger.debug('Permission manager initialized');
@ -2064,7 +1982,6 @@ export class Config {
// constructed via Object.create — those should clear their own
// cache, not the parent's.
this.getFileReadCache().clear();
this.getMemoryPressureMonitor()?.resetForNewSession();
this.fileHistoryService = undefined;
refreshSessionContext(this.sessionId);
// The commit-attribution singleton accumulates per-file AI edits
@ -2738,10 +2655,6 @@ export class Config {
return this.userMemory;
}
getOutputLanguageFilePath(): string | undefined {
return this.outputLanguageFilePath;
}
setUserMemory(newUserMemory: string): void {
this.userMemory = newUserMemory;
}
@ -3122,33 +3035,6 @@ export class Config {
return this.geminiClient;
}
/**
* Session-scoped memory pressure monitor. Child Configs created with
* `Object.create(parent)` inherit the parent's monitor through the prototype
* chain until this getter installs an own monitor backed by the inherited
* pressure config snapshot. This mirrors getFileReadCache()'s isolation
* contract while keeping type-safe direct field assignment inside the class.
*/
getMemoryPressureMonitor(): MemoryPressureMonitor | undefined {
if (!Object.prototype.hasOwnProperty.call(this, 'memoryPressureMonitor')) {
const inheritedMonitor = this.memoryPressureMonitor;
if (inheritedMonitor) {
const inheritedConfig = this.memoryPressureConfig;
if (!inheritedConfig) {
throw new Error(
'Inherited memory pressure monitor is missing config',
);
}
this.memoryPressureConfig = { ...inheritedConfig };
this.memoryPressureMonitor = new MemoryPressureMonitor(
this,
this.memoryPressureConfig,
);
}
}
return this.memoryPressureMonitor;
}
getCronScheduler(): CronScheduler {
if (!this.cronScheduler) {
this.cronScheduler = new CronScheduler();

View File

@ -22,10 +22,7 @@ vi.mock('../../utils/request-tokenizer/index.js', () => ({
RequestTokenEstimator: vi.fn(() => mockTokenizer),
}));
type AnthropicCreateArgs = [
unknown,
{ signal?: AbortSignal; headers?: Record<string, string> }?,
];
type AnthropicCreateArgs = [unknown, { signal?: AbortSignal }?];
const anthropicMockState: {
constructorOptions?: Record<string, unknown>;
@ -1016,16 +1013,9 @@ describe('AnthropicContentGenerator', () => {
// generateContent(); make sure the per-request header attaches there
// too so streaming Anthropic/DeepSeek requests stay consistent.
const { AnthropicContentGenerator } = await importGenerator();
// Use message_delta (not bare message_stop) so the empty-stream
// fallback is not triggered — bare message_stop now indicates an empty
// stream and causes a non-streaming retry.
anthropicState.createImpl.mockResolvedValue(
(async function* () {
yield {
type: 'message_delta',
delta: { stop_reason: 'end_turn' },
usage: { output_tokens: 1 },
};
yield { type: 'message_stop' };
})(),
);
@ -1046,10 +1036,6 @@ describe('AnthropicContentGenerator', () => {
void _chunk;
}
// Regression guard: normal streams must NOT trigger the empty-stream
// fallback (which would double latency + API cost).
expect(anthropicState.createImpl).toHaveBeenCalledTimes(1);
const [, options] = anthropicState.lastCreateArgs as AnthropicCreateArgs;
const headers = ((options as { headers?: Record<string, string> })
?.headers || {}) as Record<string, string>;
@ -2430,97 +2416,5 @@ describe('AnthropicContentGenerator', () => {
cachedContentTokenCount: 32_088,
});
});
it('falls back to non-streaming when the stream is empty and surfaces provider errors', async () => {
const { AnthropicContentGenerator } = await importGenerator();
anthropicState.createImpl
.mockResolvedValueOnce(
(async function* () {
// Empty stream: compatible gateways can return HTTP 200 with no SSE
// events when the real failure body is only available non-streaming.
})(),
)
.mockRejectedValueOnce(new Error('400 quota exceeded'));
const generator = new AnthropicContentGenerator(
{
model: 'claude-test',
apiKey: 'test-key',
timeout: 10_000,
maxRetries: 2,
samplingParams: { max_tokens: 123 },
schemaCompliance: 'auto',
},
mockConfig,
);
const stream = await generator.generateContentStream({
model: 'models/ignored',
contents: 'Hello',
} as unknown as GenerateContentParameters);
await expect(async () => {
for await (const _chunk of stream) {
void _chunk;
}
}).rejects.toThrow('400 quota exceeded');
expect(anthropicState.createImpl).toHaveBeenCalledTimes(2);
const [streamingRequest] = anthropicState.createImpl.mock
.calls[0] as AnthropicCreateArgs;
const [fallbackRequest] = anthropicState.createImpl.mock
.calls[1] as AnthropicCreateArgs;
expect(streamingRequest).toEqual(
expect.objectContaining({ stream: true }),
);
expect(fallbackRequest).not.toHaveProperty('stream');
});
it('converts the non-streaming fallback response when an empty stream is recoverable', async () => {
const { AnthropicContentGenerator } = await importGenerator();
anthropicState.createImpl
.mockResolvedValueOnce(
(async function* () {
yield { type: 'message_stop' };
})(),
)
.mockResolvedValueOnce({
id: 'msg-fallback',
model: 'claude-test',
stop_reason: 'end_turn',
content: [{ type: 'text', text: 'fallback ok' }],
usage: { input_tokens: 3, output_tokens: 2 },
});
const generator = new AnthropicContentGenerator(
{
model: 'claude-test',
apiKey: 'test-key',
timeout: 10_000,
maxRetries: 2,
samplingParams: { max_tokens: 123 },
schemaCompliance: 'auto',
},
mockConfig,
);
const stream = await generator.generateContentStream({
model: 'models/ignored',
contents: 'Hello',
} as unknown as GenerateContentParameters);
const chunks: GenerateContentResponse[] = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
expect(anthropicState.createImpl).toHaveBeenCalledTimes(2);
expect(chunks).toHaveLength(1);
expect(chunks[0]?.responseId).toBe('msg-fallback');
expect(chunks[0]?.candidates?.[0]?.content?.parts).toEqual([
{ text: 'fallback ok' },
]);
expect(chunks[0]?.candidates?.[0]?.finishReason).toBe(FinishReason.STOP);
});
});
});

View File

@ -266,12 +266,7 @@ export class AnthropicContentGenerator implements ContentGenerator {
throw redactProxyError(error);
}
return this.processStreamWithEmptyFallback(
this.redactStreamErrors(stream),
anthropicRequest,
request.config?.abortSignal,
headers,
);
return this.processStream(this.redactStreamErrors(stream));
}
async countTokens(
@ -973,59 +968,6 @@ export class AnthropicContentGenerator implements ContentGenerator {
}
}
// Some Anthropic-compatible gateways close the SSE stream with HTTP 200
// but emit no assistant content or stop reason (e.g. billing / quota
// limits hit mid-proxy). When that happens we probe once with the same
// request in non-streaming mode so the real provider error surfaces
// instead of the generic "stream ended without a finish reason".
private async *processStreamWithEmptyFallback(
stream: AsyncIterable<RawMessageStreamEvent>,
fallbackRequest: MessageCreateParamsWithThinking,
abortSignal: AbortSignal | undefined,
headers: Record<string, string> | undefined,
): AsyncGenerator<GenerateContentResponse> {
let hasAssistantPayload = false;
let hasFinishReason = false;
for await (const chunk of this.processStream(stream)) {
const candidates = chunk.candidates ?? [];
hasFinishReason ||= candidates.some(
(candidate) => candidate.finishReason !== undefined,
);
hasAssistantPayload ||= candidates.some((candidate) =>
candidate.content?.parts?.some(
(part) =>
part.text ||
part.thought ||
part.thoughtSignature ||
part.functionCall,
),
);
yield chunk;
}
if (hasAssistantPayload || hasFinishReason) {
return;
}
debugLogger.warn(
'Anthropic stream ended without assistant payload or finish reason; ' +
'probing once with a non-streaming request to surface provider errors.',
);
let response: Message;
try {
runtimeDiagnostics.recordAnthropicWireRequest(fallbackRequest);
response = (await this.client.messages.create(fallbackRequest, {
signal: abortSignal,
...(headers ? { headers } : {}),
})) as Message;
yield this.converter.convertAnthropicResponseToGemini(response);
} catch (error) {
throw redactProxyError(error);
}
}
private buildGeminiChunk(
part?: {
text?: string;

View File

@ -19,6 +19,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Content, GenerateContentResponse, Part } from '@google/genai';
import { GeminiClient, SendMessageType } from './client.js';
import { findCompressSplitPoint } from '../services/chatCompressionService.js';
import { getRecentGitStatus } from '../utils/gitUtils.js';
import {
AuthType,
@ -264,6 +265,84 @@ function getLastTurnRequestText(): string {
return JSON.stringify(request ?? '');
}
describe('findCompressSplitPoint', () => {
it('should throw an error for non-positive numbers', () => {
expect(() => findCompressSplitPoint([], 0)).toThrow(
'Fraction must be between 0 and 1',
);
});
it('should throw an error for a fraction greater than or equal to 1', () => {
expect(() => findCompressSplitPoint([], 1)).toThrow(
'Fraction must be between 0 and 1',
);
});
it('should handle an empty history', () => {
expect(findCompressSplitPoint([], 0.5)).toBe(0);
});
it('should handle a fraction in the middle', () => {
const history: Content[] = [
{ role: 'user', parts: [{ text: 'This is the first message.' }] }, // JSON length: 66 (19%)
{ role: 'model', parts: [{ text: 'This is the second message.' }] }, // JSON length: 68 (40%)
{ role: 'user', parts: [{ text: 'This is the third message.' }] }, // JSON length: 66 (60%)
{ role: 'model', parts: [{ text: 'This is the fourth message.' }] }, // JSON length: 68 (80%)
{ role: 'user', parts: [{ text: 'This is the fifth message.' }] }, // JSON length: 65 (100%)
];
expect(findCompressSplitPoint(history, 0.5)).toBe(4);
});
it('should handle a fraction of last index', () => {
const history: Content[] = [
{ role: 'user', parts: [{ text: 'This is the first message.' }] }, // JSON length: 66 (19%)
{ role: 'model', parts: [{ text: 'This is the second message.' }] }, // JSON length: 68 (40%)
{ role: 'user', parts: [{ text: 'This is the third message.' }] }, // JSON length: 66 (60%)
{ role: 'model', parts: [{ text: 'This is the fourth message.' }] }, // JSON length: 68 (80%)
{ role: 'user', parts: [{ text: 'This is the fifth message.' }] }, // JSON length: 65 (100%)
];
expect(findCompressSplitPoint(history, 0.9)).toBe(4);
});
it('should handle a fraction of after last index', () => {
const history: Content[] = [
{ role: 'user', parts: [{ text: 'This is the first message.' }] }, // JSON length: 66 (24%%)
{ role: 'model', parts: [{ text: 'This is the second message.' }] }, // JSON length: 68 (50%)
{ role: 'user', parts: [{ text: 'This is the third message.' }] }, // JSON length: 66 (74%)
{ role: 'model', parts: [{ text: 'This is the fourth message.' }] }, // JSON length: 68 (100%)
];
expect(findCompressSplitPoint(history, 0.8)).toBe(4);
});
it('compresses everything before the trailing in-flight functionCall', () => {
const history: Content[] = [
{ role: 'user', parts: [{ text: 'This is the first message.' }] },
{ role: 'model', parts: [{ text: 'This is the second message.' }] },
{ role: 'user', parts: [{ text: 'This is the third message.' }] },
{ role: 'model', parts: [{ functionCall: {} }] },
];
// Trailing m+fc is in-flight; the in-flight fallback compresses
// everything except the trailing fc (no preceding pair to retain).
expect(findCompressSplitPoint(history, 0.99)).toBe(3);
});
it('should handle a history with only one item', () => {
const historyWithEmptyParts: Content[] = [
{ role: 'user', parts: [{ text: 'Message 1' }] },
];
expect(findCompressSplitPoint(historyWithEmptyParts, 0.5)).toBe(0);
});
it('should handle history with weird parts', () => {
const historyWithEmptyParts: Content[] = [
{ role: 'user', parts: [{ text: 'Message 1' }] },
{ role: 'model', parts: [{ fileData: { fileUri: 'derp' } }] },
{ role: 'user', parts: [{ text: 'Message 2' }] },
];
expect(findCompressSplitPoint(historyWithEmptyParts, 0.5)).toBe(2);
});
});
describe('Gemini Client (client.ts)', () => {
let mockContentGenerator: ContentGenerator;
let mockConfig: Config;

View File

@ -47,6 +47,7 @@ import {
} from './turn.js';
// Services
import { COMPRESSION_PRESERVE_THRESHOLD } from '../services/chatCompressionService.js';
import { LoopDetectionService } from '../services/loopDetectionService.js';
import { CommitAttributionService } from '../services/commitAttribution.js';
@ -2181,3 +2182,7 @@ export class GeminiClient {
return info;
}
}
export const TEST_ONLY = {
COMPRESSION_PRESERVE_THRESHOLD,
};

Some files were not shown because too many files have changed in this diff Show More