Compare commits
6 Commits
main
...
worktree-f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63a835620f | ||
|
|
96eb00ca1f | ||
|
|
6ec95252b0 | ||
|
|
a2ab29a72c | ||
|
|
478a20e779 | ||
|
|
6982b2f374 |
@ -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.
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@ -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();
|
||||
@ -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,
|
||||
|
||||
@ -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.',
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -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);
|
||||
});
|
||||
}
|
||||
@ -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.',
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -1,7 +0,0 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['src/**/*.test.{js,jsx}'],
|
||||
},
|
||||
});
|
||||
@ -1,6 +1,9 @@
|
||||
export default {
|
||||
settings: 'Settings',
|
||||
auth: 'Authentication',
|
||||
memory: {
|
||||
display: 'hidden',
|
||||
},
|
||||
'qwen-ignore': 'Ignoring Files',
|
||||
'trusted-folders': 'Trusted Folders',
|
||||
themes: 'Themes',
|
||||
|
||||
@ -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),
|
||||
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -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(),
|
||||
}));
|
||||
|
||||
@ -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,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -196,8 +196,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 +329,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 +348,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 +356,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 +853,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
|
||||
@ -1213,8 +1207,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 +1523,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 +1584,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 +1655,6 @@ describe('Session', () => {
|
||||
.mockReturnValue([
|
||||
{ role: 'model', parts: [{ text: 'response text' }] },
|
||||
]);
|
||||
mockChat.getLastModelMessageText = vi
|
||||
.fn()
|
||||
.mockReturnValue('response text');
|
||||
mockChat.sendMessageStream = vi
|
||||
.fn()
|
||||
.mockResolvedValue(createEmptyStream());
|
||||
@ -2422,9 +2405,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 +2458,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 +2503,6 @@ describe('Session', () => {
|
||||
.mockReturnValue([
|
||||
{ role: 'model', parts: [{ text: 'response text' }] },
|
||||
]);
|
||||
mockChat.getLastModelMessageText = vi
|
||||
.fn()
|
||||
.mockReturnValue('response text');
|
||||
mockChat.sendMessageStream = vi
|
||||
.fn()
|
||||
.mockResolvedValue(createEmptyStream());
|
||||
|
||||
@ -402,7 +402,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 +895,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,
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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 = {
|
||||
|
||||
@ -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,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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>,
|
||||
|
||||
@ -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 />}
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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',
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -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: '' };
|
||||
},
|
||||
|
||||
@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@ -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);
|
||||
|
||||
|
||||
@ -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();
|
||||
});
|
||||
});
|
||||
@ -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>
|
||||
);
|
||||
};
|
||||
@ -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 = {
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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', () => {
|
||||
|
||||
@ -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(
|
||||
|
||||
@ -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');
|
||||
});
|
||||
});
|
||||
@ -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);
|
||||
}
|
||||
@ -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();
|
||||
|
||||
|
||||
@ -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>
|
||||
|
||||
@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -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');
|
||||
});
|
||||
});
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -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();
|
||||
|
||||
@ -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);
|
||||
|
||||
|
||||
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -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 (
|
||||
|
||||
@ -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);
|
||||
@ -230,40 +186,6 @@ describe('hooks constants', () => {
|
||||
});
|
||||
});
|
||||
|
||||
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));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('createEmptyHookEventInfo', () => {
|
||||
it('should create empty info for PreToolUse', () => {
|
||||
const info = createEmptyHookEventInfo(HookEventName.PreToolUse);
|
||||
@ -274,7 +196,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 +208,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 +218,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 +228,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 +240,7 @@ describe('hooks constants', () => {
|
||||
);
|
||||
expect(info.description).toContain('previous_status');
|
||||
expect(info.exitCodes).toHaveLength(3);
|
||||
expect(info.matcherGroups).toEqual([]);
|
||||
expect(info.configs).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -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,20 +90,6 @@ 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') },
|
||||
@ -155,10 +137,6 @@ 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',
|
||||
@ -208,12 +186,6 @@ 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.',
|
||||
),
|
||||
@ -246,13 +218,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 +239,6 @@ export function createEmptyHookEventInfo(
|
||||
shortDescription: getHookShortDescription(eventName),
|
||||
description: getHookDescription(eventName),
|
||||
exitCodes: getHookExitCodes(eventName),
|
||||
matcherGroups: [],
|
||||
configs: [],
|
||||
};
|
||||
}
|
||||
|
||||
@ -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']);
|
||||
});
|
||||
});
|
||||
@ -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);
|
||||
}
|
||||
@ -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');
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -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;
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -2462,7 +2462,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,
|
||||
|
||||
@ -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({
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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,
|
||||
),
|
||||
|
||||
@ -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) {
|
||||
|
||||
@ -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 = [
|
||||
{
|
||||
|
||||
@ -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]),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@ -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'];
|
||||
|
||||
|
||||
@ -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) => {
|
||||
|
||||
172
packages/core/src/config/config-session-env.test.ts
Normal file
172
packages/core/src/config/config-session-env.test.ts
Normal file
@ -0,0 +1,172 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* Tests for the module-level `sessionEnvClaimed` guard in Config.
|
||||
*
|
||||
* The guard ensures that only the first Config instance in a process sets
|
||||
* `process.env['QWEN_CODE_SESSION_ID']`, preventing throwaway instances
|
||||
* (e.g. telemetry-only) from overwriting the real session's ID.
|
||||
*
|
||||
* We use `vi.isolateModules` to get a fresh module scope (resetting the
|
||||
* module-level flag) for each test.
|
||||
*/
|
||||
|
||||
// Shared mocks needed by Config constructor
|
||||
vi.mock('node:fs');
|
||||
vi.mock('node:fs/promises');
|
||||
vi.mock('../telemetry/index.js', () => ({
|
||||
QwenLogger: vi.fn().mockImplementation(() => ({
|
||||
logStartSessionEvent: vi.fn().mockResolvedValue(undefined),
|
||||
logEndSessionEvent: vi.fn().mockResolvedValue(undefined),
|
||||
shutdown: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
DEFAULT_TELEMETRY_TARGET: 'none',
|
||||
DEFAULT_OTLP_ENDPOINT: '',
|
||||
isTelemetrySdkInitialized: vi.fn().mockReturnValue(false),
|
||||
shutdownTelemetry: vi.fn().mockResolvedValue(undefined),
|
||||
refreshSessionContext: vi.fn(),
|
||||
}));
|
||||
vi.mock('../core/contentGenerator.js', () => ({
|
||||
resolveContentGeneratorConfigWithSources: vi.fn().mockReturnValue({
|
||||
config: { model: 'test-model', apiKey: 'test-key' },
|
||||
sources: {},
|
||||
}),
|
||||
createContentGeneratorConfig: vi.fn().mockReturnValue({}),
|
||||
createContentGenerator: vi.fn().mockReturnValue({}),
|
||||
AuthType: { API_KEY: 'apiKey' },
|
||||
}));
|
||||
vi.mock('../core/baseLlmClient.js');
|
||||
vi.mock('../core/toolHookTriggers.js', () => ({
|
||||
fireNotificationHook: vi.fn().mockResolvedValue({}),
|
||||
}));
|
||||
vi.mock('../services/skillManager.js', () => {
|
||||
const SkillManagerMock = vi.fn();
|
||||
SkillManagerMock.prototype.startWatching = vi
|
||||
.fn()
|
||||
.mockResolvedValue(undefined);
|
||||
SkillManagerMock.prototype.refreshCache = vi
|
||||
.fn()
|
||||
.mockResolvedValue(undefined);
|
||||
SkillManagerMock.prototype.stopWatching = vi.fn();
|
||||
SkillManagerMock.prototype.listSkills = vi.fn().mockResolvedValue([]);
|
||||
SkillManagerMock.prototype.addChangeListener = vi.fn();
|
||||
SkillManagerMock.prototype.removeChangeListener = vi.fn();
|
||||
SkillManagerMock.prototype.matchAndActivateByPath = vi
|
||||
.fn()
|
||||
.mockResolvedValue([]);
|
||||
SkillManagerMock.prototype.matchAndActivateByPaths = vi
|
||||
.fn()
|
||||
.mockResolvedValue([]);
|
||||
return { SkillManager: SkillManagerMock };
|
||||
});
|
||||
vi.mock('../subagents/subagent-manager.js', () => {
|
||||
const SubagentManagerMock = vi.fn();
|
||||
SubagentManagerMock.prototype.loadSessionSubagents = vi.fn();
|
||||
SubagentManagerMock.prototype.addChangeListener = vi
|
||||
.fn()
|
||||
.mockReturnValue(() => {});
|
||||
SubagentManagerMock.prototype.listSubagents = vi.fn().mockResolvedValue([]);
|
||||
return { SubagentManager: SubagentManagerMock };
|
||||
});
|
||||
vi.mock('../ide/ide-client.js', () => ({
|
||||
IdeClient: {
|
||||
getInstance: vi.fn().mockResolvedValue({
|
||||
getConnectionStatus: vi.fn(),
|
||||
initialize: vi.fn(),
|
||||
shutdown: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock('../memory/const.js', () => ({
|
||||
setGeminiMdFilename: vi.fn(),
|
||||
}));
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import type { Mock } from 'vitest';
|
||||
import type { ConfigParameters } from './config.js';
|
||||
|
||||
const baseParams: ConfigParameters = {
|
||||
cwd: '/tmp',
|
||||
targetDir: '/tmp',
|
||||
debugMode: false,
|
||||
model: 'test-model',
|
||||
telemetry: { enabled: false },
|
||||
usageStatisticsEnabled: false,
|
||||
overrideExtensions: [],
|
||||
};
|
||||
|
||||
describe('Config sessionEnvClaimed guard', () => {
|
||||
let originalEnv: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
originalEnv = process.env['QWEN_CODE_SESSION_ID'];
|
||||
delete process.env['QWEN_CODE_SESSION_ID'];
|
||||
|
||||
(fs.existsSync as Mock).mockReturnValue(true);
|
||||
(fs.readdirSync as Mock).mockReturnValue([]);
|
||||
(fs.statSync as Mock).mockReturnValue({
|
||||
isDirectory: vi.fn().mockReturnValue(true),
|
||||
});
|
||||
vi.mocked(fs.realpathSync).mockImplementation((p) => String(p));
|
||||
(fs.mkdirSync as Mock).mockImplementation(() => undefined);
|
||||
(fs.writeFileSync as Mock).mockImplementation(() => undefined);
|
||||
(fs.renameSync as Mock).mockImplementation(() => undefined);
|
||||
(fs.copyFileSync as Mock).mockImplementation(() => undefined);
|
||||
(fs.unlinkSync as Mock).mockImplementation(() => undefined);
|
||||
(fs.readFileSync as Mock).mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env['QWEN_CODE_SESSION_ID'] = originalEnv;
|
||||
} else {
|
||||
delete process.env['QWEN_CODE_SESSION_ID'];
|
||||
}
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it('first Config sets process.env QWEN_CODE_SESSION_ID to its sessionId', async () => {
|
||||
const { Config } = await import('./config.js');
|
||||
const config = new Config({ ...baseParams });
|
||||
|
||||
expect(process.env['QWEN_CODE_SESSION_ID']).toBe(config.getSessionId());
|
||||
});
|
||||
|
||||
it('subsequent Config does not overwrite the env var set by the first', async () => {
|
||||
const { Config } = await import('./config.js');
|
||||
const firstConfig = new Config({ ...baseParams });
|
||||
const firstSessionId = firstConfig.getSessionId();
|
||||
|
||||
// Second Config (e.g. telemetry-only throwaway instance)
|
||||
const secondConfig = new Config({
|
||||
...baseParams,
|
||||
sessionId: 'throwaway-session-id',
|
||||
});
|
||||
|
||||
// The env var should still be the first config's session ID
|
||||
expect(process.env['QWEN_CODE_SESSION_ID']).toBe(firstSessionId);
|
||||
expect(process.env['QWEN_CODE_SESSION_ID']).not.toBe(
|
||||
secondConfig.getSessionId(),
|
||||
);
|
||||
});
|
||||
|
||||
it('startNewSession updates env var to the new session ID', async () => {
|
||||
const { Config } = await import('./config.js');
|
||||
const config = new Config({ ...baseParams });
|
||||
const originalSessionId = config.getSessionId();
|
||||
|
||||
expect(process.env['QWEN_CODE_SESSION_ID']).toBe(originalSessionId);
|
||||
|
||||
// Simulate /clear or session switch
|
||||
config.startNewSession('new-session-uuid-123');
|
||||
|
||||
expect(process.env['QWEN_CODE_SESSION_ID']).toBe('new-session-uuid-123');
|
||||
expect(process.env['QWEN_CODE_SESSION_ID']).not.toBe(originalSessionId);
|
||||
});
|
||||
});
|
||||
@ -16,7 +16,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 +288,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 +328,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 +422,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
|
||||
|
||||
@ -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 {
|
||||
@ -162,7 +156,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,
|
||||
@ -856,53 +849,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()
|
||||
*/
|
||||
@ -926,6 +872,12 @@ const DEFAULT_BARE_CORE_TOOLS = [
|
||||
ToolNames.SHELL,
|
||||
];
|
||||
|
||||
// Tracks whether the first Config in this process has claimed the global
|
||||
// QWEN_CODE_SESSION_ID env var. Prevents throwaway Config instances from
|
||||
// overwriting the real session's ID while still allowing nested qwen-code
|
||||
// processes to claim their own (they start with a fresh module scope).
|
||||
let sessionEnvClaimed = false;
|
||||
|
||||
export class Config {
|
||||
private sessionId: string;
|
||||
private sessionData?: ResumedSessionData;
|
||||
@ -958,8 +910,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;
|
||||
@ -1130,6 +1080,16 @@ export class Config {
|
||||
|
||||
constructor(params: ConfigParameters) {
|
||||
this.sessionId = params.sessionId ?? randomUUID();
|
||||
// Only set the global env marker once per process lifetime, so
|
||||
// throwaway Config instances (e.g. telemetry-only) don't clobber
|
||||
// the real interactive session's ID. Uses a module-level flag
|
||||
// rather than checking env existence — otherwise a nested qwen-code
|
||||
// launched from within a session would inherit the parent's ID and
|
||||
// never claim its own.
|
||||
if (!sessionEnvClaimed && process.env) {
|
||||
process.env['QWEN_CODE_SESSION_ID'] = this.sessionId;
|
||||
sessionEnvClaimed = true;
|
||||
}
|
||||
this.sessionData = params.sessionData;
|
||||
setDebugLogSession(this);
|
||||
this.debugLogger = createDebugLogger();
|
||||
@ -1563,12 +1523,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');
|
||||
@ -2048,6 +2002,12 @@ export class Config {
|
||||
|
||||
const previousSessionId = this.sessionId;
|
||||
this.sessionId = sessionId ?? randomUUID();
|
||||
// Unconditional: startNewSession is only called on the canonical Config
|
||||
// instance (the one that already claimed via sessionEnvClaimed), so this
|
||||
// correctly updates the env var to reflect the new active session.
|
||||
if (process.env) {
|
||||
process.env['QWEN_CODE_SESSION_ID'] = this.sessionId;
|
||||
}
|
||||
this.sessionData = sessionData;
|
||||
setDebugLogSession(this);
|
||||
this.debugLogger = createDebugLogger();
|
||||
@ -2064,7 +2024,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 +2697,6 @@ export class Config {
|
||||
return this.userMemory;
|
||||
}
|
||||
|
||||
getOutputLanguageFilePath(): string | undefined {
|
||||
return this.outputLanguageFilePath;
|
||||
}
|
||||
|
||||
setUserMemory(newUserMemory: string): void {
|
||||
this.userMemory = newUserMemory;
|
||||
}
|
||||
@ -3122,33 +3077,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();
|
||||
|
||||
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -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;
|
||||
|
||||
@ -499,7 +499,6 @@ describe('CoreToolScheduler', () => {
|
||||
disableHooks?: boolean;
|
||||
onAllToolCallsComplete?: ReturnType<typeof vi.fn>;
|
||||
onToolCallsUpdate?: ReturnType<typeof vi.fn>;
|
||||
memoryMonitor?: { scheduleCheck: () => void };
|
||||
}) {
|
||||
const ensureTool = vi.fn(
|
||||
async (name: string) =>
|
||||
@ -550,7 +549,6 @@ describe('CoreToolScheduler', () => {
|
||||
getUseModelRouter: () => false,
|
||||
getGeminiClient: () => null,
|
||||
getChatRecordingService: () => undefined,
|
||||
getMemoryPressureMonitor: () => options.memoryMonitor,
|
||||
getMessageBus: vi.fn().mockReturnValue(options.messageBus),
|
||||
getHookSystem: vi.fn().mockReturnValue(options.hookSystem),
|
||||
getDisableAllHooks: vi
|
||||
@ -632,43 +630,6 @@ describe('CoreToolScheduler', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('schedules a memory pressure check after tool execution', async () => {
|
||||
const execute = vi.fn().mockResolvedValue({
|
||||
llmContent: 'ok',
|
||||
returnDisplay: 'ok',
|
||||
});
|
||||
const toolsByName = new Map<string, MockTool>([
|
||||
[
|
||||
'mockTool',
|
||||
new MockTool({
|
||||
name: 'mockTool',
|
||||
execute,
|
||||
}),
|
||||
],
|
||||
]);
|
||||
const scheduleCheck = vi.fn();
|
||||
const { scheduler } = createSchedulerForLegacyToolTests({
|
||||
toolsByName,
|
||||
memoryMonitor: { scheduleCheck },
|
||||
});
|
||||
|
||||
await scheduler.schedule(
|
||||
[
|
||||
{
|
||||
callId: 'memory-check',
|
||||
name: 'mockTool',
|
||||
args: {},
|
||||
isClientInitiated: false,
|
||||
prompt_id: 'prompt-memory-check',
|
||||
},
|
||||
],
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
expect(execute).toHaveBeenCalledOnce();
|
||||
expect(scheduleCheck).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('applies canonical legacy tool names to the deny-list fallback', async () => {
|
||||
const execute = vi.fn().mockResolvedValue({
|
||||
llmContent: 'edited',
|
||||
|
||||
@ -51,7 +51,6 @@ import { fileURLToPath } from 'node:url';
|
||||
import { ToolNames, ToolNamesMigration } from '../tools/tool-names.js';
|
||||
import { escapeSystemReminderTags, escapeXml } from '../utils/xml.js';
|
||||
import { unescapePath, PATH_ARG_KEYS } from '../utils/paths.js';
|
||||
import type { MemoryPressureMonitor } from '../services/memoryPressureMonitor.js';
|
||||
import { CONCURRENCY_SAFE_KINDS } from '../tools/tools.js';
|
||||
import { isShellCommandReadOnly } from '../utils/shellReadOnlyChecker.js';
|
||||
import { stripShellWrapper } from '../utils/shell-utils.js';
|
||||
@ -841,10 +840,6 @@ export class CoreToolScheduler {
|
||||
this.chatRecordingService = options.chatRecordingService;
|
||||
}
|
||||
|
||||
private get memoryMonitor(): MemoryPressureMonitor | undefined {
|
||||
return this.config.getMemoryPressureMonitor?.();
|
||||
}
|
||||
|
||||
private setStatusInternal(
|
||||
targetCallId: string,
|
||||
status: 'success',
|
||||
@ -2604,7 +2599,6 @@ export class CoreToolScheduler {
|
||||
// _executeToolCallBody pre-sets status (OK / FAILURE / CANCELLED) via
|
||||
// setToolSpan*; finalize without metadata to preserve that.
|
||||
this.finalizeToolSpan(callId);
|
||||
this.memoryMonitor?.scheduleCheck();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1633,11 +1633,6 @@ describe('GeminiChat', async () => {
|
||||
});
|
||||
|
||||
it('seeds inherited token count via setLastPromptTokenCount', async () => {
|
||||
vi.mocked(mockConfig.getContentGeneratorConfig).mockReturnValue({
|
||||
authType: AuthType.USE_GEMINI,
|
||||
model: 'test-model',
|
||||
contextWindowSize: 200_000,
|
||||
});
|
||||
const subagentChat = new GeminiChat(mockConfig, config, [
|
||||
{ role: 'user', parts: [{ text: 'inherited' }] },
|
||||
{ role: 'model', parts: [{ text: 'inherited reply' }] },
|
||||
@ -2388,17 +2383,6 @@ describe('GeminiChat', async () => {
|
||||
{ role: 'user', parts: [{ text: 'summary' }] },
|
||||
{ role: 'model', parts: [{ text: 'ack' }] },
|
||||
];
|
||||
const recordChatCompression = vi.fn();
|
||||
const chatWithRecording = new GeminiChat(
|
||||
mockConfig,
|
||||
config,
|
||||
[],
|
||||
{
|
||||
recordAssistantTurn: vi.fn(),
|
||||
recordChatCompression,
|
||||
} as unknown as ConstructorParameters<typeof GeminiChat>[3],
|
||||
uiTelemetryService,
|
||||
);
|
||||
const compressSpy = vi
|
||||
.spyOn(ChatCompressionService.prototype, 'compress')
|
||||
.mockResolvedValueOnce({
|
||||
@ -2416,10 +2400,10 @@ describe('GeminiChat', async () => {
|
||||
// Seed lastPromptTokenCount JUST under the 177K hard threshold; the
|
||||
// pending user message adds a handful of estimate-tokens that pushes
|
||||
// effective >= 177K, so the rescue must trigger.
|
||||
chatWithRecording.setLastPromptTokenCount(176_999);
|
||||
chat.setLastPromptTokenCount(176_999);
|
||||
|
||||
const userMessage = 'this is the next user message';
|
||||
const stream = await chatWithRecording.sendMessageStream(
|
||||
const stream = await chat.sendMessageStream(
|
||||
'test-model',
|
||||
{ message: userMessage },
|
||||
'prompt-id-hard-rescue-forces',
|
||||
@ -2443,164 +2427,6 @@ describe('GeminiChat', async () => {
|
||||
(part) => part.text === userMessage,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(recordChatCompression).toHaveBeenCalledTimes(1);
|
||||
const recordPayload = recordChatCompression.mock.calls[0][0];
|
||||
expect(recordPayload.info).toEqual(
|
||||
expect.objectContaining({
|
||||
compressionStatus: CompressionStatus.COMPRESSED,
|
||||
newTokenCount: 40_000,
|
||||
}),
|
||||
);
|
||||
expect(recordPayload.compressedHistory).toEqual([
|
||||
{ role: 'user', parts: [{ text: 'summary' }] },
|
||||
{ role: 'model', parts: [{ text: 'ack' }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects before request serialization when oversized resumed history cannot be compressed', async () => {
|
||||
const oversizedResumedHistory: Content[] = [
|
||||
{ role: 'user', parts: [{ text: 'x'.repeat(720_000) }] },
|
||||
{ role: 'model', parts: [{ text: 'ack' }] },
|
||||
];
|
||||
chat.setHistory(oversizedResumedHistory);
|
||||
expect(chat.getLastPromptTokenCount()).toBe(0);
|
||||
|
||||
const compressSpy = vi
|
||||
.spyOn(ChatCompressionService.prototype, 'compress')
|
||||
.mockResolvedValueOnce({
|
||||
newHistory: null,
|
||||
info: {
|
||||
originalTokenCount: 180_000,
|
||||
newTokenCount: 180_000,
|
||||
compressionStatus:
|
||||
CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY,
|
||||
},
|
||||
});
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockRejectedValue(
|
||||
new Error('Invalid string length'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
chat.sendMessageStream(
|
||||
'test-model',
|
||||
{ message: 'continue' },
|
||||
'prompt-id-oversized-resume-guard',
|
||||
),
|
||||
).rejects.toThrow(
|
||||
/compression status: COMPRESSION_FAILED_EMPTY_SUMMARY/i,
|
||||
);
|
||||
|
||||
expect(compressSpy).toHaveBeenCalledTimes(1);
|
||||
expect(compressSpy.mock.calls[0][1].force).toBe(true);
|
||||
expect(mockContentGenerator.generateContentStream).not.toHaveBeenCalled();
|
||||
expect(chat.getLastPromptTokenCount()).toBe(0);
|
||||
expect(chat.getHistory()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('rejects before request serialization and restores history when hard-rescue compression is still oversized', async () => {
|
||||
const originalHistory: Content[] = [
|
||||
{ role: 'user', parts: [{ text: 'x'.repeat(720_000) }] },
|
||||
{ role: 'model', parts: [{ text: 'ack' }] },
|
||||
];
|
||||
const recordChatCompression = vi.fn();
|
||||
const chatWithRecording = new GeminiChat(
|
||||
mockConfig,
|
||||
config,
|
||||
[],
|
||||
{
|
||||
recordAssistantTurn: vi.fn(),
|
||||
recordChatCompression,
|
||||
} as unknown as ConstructorParameters<typeof GeminiChat>[3],
|
||||
uiTelemetryService,
|
||||
);
|
||||
chatWithRecording.setHistory(originalHistory);
|
||||
chatWithRecording.setLastPromptTokenCount(176_999);
|
||||
|
||||
vi.spyOn(
|
||||
ChatCompressionService.prototype,
|
||||
'compress',
|
||||
).mockResolvedValueOnce({
|
||||
newHistory: [
|
||||
{ role: 'user', parts: [{ text: 'still large summary' }] },
|
||||
{ role: 'model', parts: [{ text: 'ack' }] },
|
||||
],
|
||||
info: {
|
||||
originalTokenCount: 180_000,
|
||||
newTokenCount: 177_000,
|
||||
compressionStatus: CompressionStatus.COMPRESSED,
|
||||
},
|
||||
});
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockRejectedValue(
|
||||
new Error('Invalid string length'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
chatWithRecording.sendMessageStream(
|
||||
'test-model',
|
||||
{ message: 'continue' },
|
||||
'prompt-id-oversized-after-compression',
|
||||
),
|
||||
).rejects.toThrow(/compression status: COMPRESSED/i);
|
||||
|
||||
expect(mockContentGenerator.generateContentStream).not.toHaveBeenCalled();
|
||||
expect(recordChatCompression).not.toHaveBeenCalled();
|
||||
expect(chatWithRecording.getLastPromptTokenCount()).toBe(176_999);
|
||||
expect(chatWithRecording.getHistory()[0].parts?.[0].text).toBe(
|
||||
originalHistory[0].parts?.[0].text,
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects when compressed history is below hard but the pending user message pushes it over', async () => {
|
||||
const originalHistory: Content[] = [
|
||||
{ role: 'user', parts: [{ text: 'x'.repeat(720_000) }] },
|
||||
{ role: 'model', parts: [{ text: 'ack' }] },
|
||||
];
|
||||
const recordChatCompression = vi.fn();
|
||||
const chatWithRecording = new GeminiChat(
|
||||
mockConfig,
|
||||
config,
|
||||
[],
|
||||
{
|
||||
recordAssistantTurn: vi.fn(),
|
||||
recordChatCompression,
|
||||
} as unknown as ConstructorParameters<typeof GeminiChat>[3],
|
||||
uiTelemetryService,
|
||||
);
|
||||
chatWithRecording.setHistory(originalHistory);
|
||||
chatWithRecording.setLastPromptTokenCount(175_500);
|
||||
|
||||
vi.spyOn(
|
||||
ChatCompressionService.prototype,
|
||||
'compress',
|
||||
).mockResolvedValueOnce({
|
||||
newHistory: [
|
||||
{ role: 'user', parts: [{ text: 'summary' }] },
|
||||
{ role: 'model', parts: [{ text: 'ack' }] },
|
||||
],
|
||||
info: {
|
||||
originalTokenCount: 180_000,
|
||||
newTokenCount: 176_000,
|
||||
compressionStatus: CompressionStatus.COMPRESSED,
|
||||
},
|
||||
});
|
||||
vi.mocked(mockContentGenerator.generateContentStream).mockResolvedValue(
|
||||
makeStreamResponse('should not send'),
|
||||
);
|
||||
|
||||
await expect(
|
||||
chatWithRecording.sendMessageStream(
|
||||
'test-model',
|
||||
{ message: 'x'.repeat(8_000) },
|
||||
'prompt-id-oversized-after-compression-and-user',
|
||||
),
|
||||
).rejects.toThrow(/Estimated prompt tokens: 178000; hard limit: 177000/i);
|
||||
|
||||
expect(mockContentGenerator.generateContentStream).not.toHaveBeenCalled();
|
||||
expect(recordChatCompression).not.toHaveBeenCalled();
|
||||
expect(chatWithRecording.getLastPromptTokenCount()).toBe(175_500);
|
||||
expect(chatWithRecording.getHistory()[0].parts?.[0].text).toBe(
|
||||
originalHistory[0].parts?.[0].text,
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards latched consecutiveFailures into hard-rescue (no pre-call reset); success recovers via the post-call branch', async () => {
|
||||
|
||||
@ -106,38 +106,6 @@ function isCompressionFailureStatus(status: CompressionStatus): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function shouldStopAfterHardRescue(
|
||||
shouldForceFromHard: boolean,
|
||||
hardLimit: number,
|
||||
localPromptTokensAfterCompression: number,
|
||||
): boolean {
|
||||
return shouldForceFromHard && localPromptTokensAfterCompression >= hardLimit;
|
||||
}
|
||||
|
||||
function getHardRescueFailureMessage(
|
||||
effectiveTokens: number,
|
||||
hardLimit: number,
|
||||
compressionInfo: ChatCompressionInfo,
|
||||
localPromptTokensAfterCompression: number,
|
||||
): string {
|
||||
const compressionStatus =
|
||||
CompressionStatus[compressionInfo.compressionStatus] ??
|
||||
String(compressionInfo.compressionStatus);
|
||||
const tokenCount =
|
||||
compressionInfo.compressionStatus === CompressionStatus.COMPRESSED
|
||||
? Math.max(
|
||||
compressionInfo.newTokenCount,
|
||||
localPromptTokensAfterCompression,
|
||||
)
|
||||
: Math.max(effectiveTokens, localPromptTokensAfterCompression);
|
||||
return (
|
||||
`Context is too large to send safely after automatic compression. ` +
|
||||
`Estimated prompt tokens: ${tokenCount}; hard limit: ${hardLimit}; ` +
|
||||
`compression status: ${compressionStatus}. ` +
|
||||
`Start a new session or reduce the resumed history before continuing.`
|
||||
);
|
||||
}
|
||||
|
||||
export enum StreamEventType {
|
||||
/** A regular content chunk from the API. */
|
||||
CHUNK = 'chunk',
|
||||
@ -189,11 +157,6 @@ interface TryCompressOptions {
|
||||
* `getHistory(true)` clone per send. (review #4168 R1.3 / R1.4)
|
||||
*/
|
||||
precomputedEffectiveTokens?: number;
|
||||
/**
|
||||
* Delay writing the compression checkpoint until the caller has run any
|
||||
* post-compression guards that may roll the in-memory chat state back.
|
||||
*/
|
||||
deferChatCompressionRecord?: boolean;
|
||||
}
|
||||
|
||||
const INVALID_CONTENT_RETRY_OPTIONS: ContentRetryOptions = {
|
||||
@ -1362,11 +1325,9 @@ export class GeminiChat {
|
||||
*
|
||||
* Returns the compression info regardless of outcome. On a successful
|
||||
* compaction (`COMPRESSED`), this method has already mutated the chat's
|
||||
* history, recorded the event to `chatRecordingService` (if wired and
|
||||
* unless `options.deferChatCompressionRecord` is set), and updated both
|
||||
* the per-chat token count and (when wired) the global telemetry singleton.
|
||||
* Deferred callers are responsible for recording after their own
|
||||
* post-compression guards pass.
|
||||
* history, recorded the event to `chatRecordingService` (if wired), and
|
||||
* updated both the per-chat token count and (when wired) the global
|
||||
* telemetry singleton.
|
||||
*/
|
||||
async tryCompress(
|
||||
promptId: string,
|
||||
@ -1391,12 +1352,10 @@ export class GeminiChat {
|
||||
});
|
||||
|
||||
if (info.compressionStatus === CompressionStatus.COMPRESSED && newHistory) {
|
||||
if (!options?.deferChatCompressionRecord) {
|
||||
this.chatRecordingService?.recordChatCompression({
|
||||
info,
|
||||
compressedHistory: newHistory,
|
||||
});
|
||||
}
|
||||
this.chatRecordingService?.recordChatCompression({
|
||||
info,
|
||||
compressedHistory: newHistory,
|
||||
});
|
||||
this.setHistory(newHistory);
|
||||
debugLogger.debug('[FILE_READ_CACHE] clear after auto tryCompress');
|
||||
this.config.getFileReadCache().clear();
|
||||
@ -1566,13 +1525,9 @@ export class GeminiChat {
|
||||
imageTokenEstimate,
|
||||
);
|
||||
const shouldForceFromHard = effectiveTokens >= hard;
|
||||
const historyBeforeHardRescue = shouldForceFromHard
|
||||
? this.getHistoryShallow()
|
||||
: undefined;
|
||||
const lastPromptTokenCountBeforeHardRescue = this.lastPromptTokenCount;
|
||||
if (shouldForceFromHard) {
|
||||
debugLogger.warn(
|
||||
`[compaction] hard-tier rescue triggered: prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, hard=${hard}, consecutiveFailures=${this.consecutiveFailures}.`,
|
||||
`[compaction] hard-tier rescue triggered: effectiveTokens=${effectiveTokens}, hard=${hard}, consecutiveFailures=${this.consecutiveFailures}.`,
|
||||
);
|
||||
}
|
||||
|
||||
@ -1584,7 +1539,6 @@ export class GeminiChat {
|
||||
{
|
||||
pendingUserMessage: userContent,
|
||||
precomputedEffectiveTokens: effectiveTokens,
|
||||
deferChatCompressionRecord: shouldForceFromHard,
|
||||
// Hard-rescue is force=true to bypass the cheap-gate breaker
|
||||
// but it remains a semantically AUTOMATIC trigger. Tag the
|
||||
// compactTrigger explicitly as 'auto' so the PostCompact
|
||||
@ -1599,66 +1553,6 @@ export class GeminiChat {
|
||||
},
|
||||
);
|
||||
|
||||
const localPromptTokensAfterCompression = shouldForceFromHard
|
||||
? estimatePromptTokens(
|
||||
this.lastPromptTokenCount > 0 ? [] : this.getHistoryShallow(true),
|
||||
userContent,
|
||||
this.lastPromptTokenCount,
|
||||
imageTokenEstimate,
|
||||
)
|
||||
: 0;
|
||||
if (
|
||||
shouldStopAfterHardRescue(
|
||||
shouldForceFromHard,
|
||||
hard,
|
||||
localPromptTokensAfterCompression,
|
||||
)
|
||||
) {
|
||||
const message = getHardRescueFailureMessage(
|
||||
effectiveTokens,
|
||||
hard,
|
||||
compressionInfo,
|
||||
localPromptTokensAfterCompression,
|
||||
);
|
||||
if (
|
||||
compressionInfo.compressionStatus === CompressionStatus.COMPRESSED &&
|
||||
historyBeforeHardRescue
|
||||
) {
|
||||
// Hard-rescue compression mutates in-memory history before this
|
||||
// guard can compare the compressed prompt size. If the compressed
|
||||
// prompt is still too large to send, restore the pre-compression
|
||||
// state. The JSONL compression checkpoint is intentionally not
|
||||
// written because the send is about to be rejected.
|
||||
this.setHistory(historyBeforeHardRescue);
|
||||
this.lastPromptTokenCount = lastPromptTokenCountBeforeHardRescue;
|
||||
this.telemetryService?.setLastPromptTokenCount(
|
||||
lastPromptTokenCountBeforeHardRescue,
|
||||
);
|
||||
}
|
||||
const compressionStatus =
|
||||
CompressionStatus[compressionInfo.compressionStatus] ??
|
||||
String(compressionInfo.compressionStatus);
|
||||
debugLogger.warn(
|
||||
`[compaction] hard-tier rescue stopped oversized prompt: ` +
|
||||
`prompt_id=${prompt_id}, effectiveTokens=${effectiveTokens}, ` +
|
||||
`hard=${hard}, localPromptTokensAfterCompression=` +
|
||||
`${localPromptTokensAfterCompression}, compressionStatus=` +
|
||||
`${compressionStatus}, newTokenCount=` +
|
||||
`${compressionInfo.newTokenCount}, consecutiveFailures=` +
|
||||
`${this.consecutiveFailures}. ${message}`,
|
||||
);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (
|
||||
shouldForceFromHard &&
|
||||
compressionInfo.compressionStatus === CompressionStatus.COMPRESSED
|
||||
) {
|
||||
this.chatRecordingService?.recordChatCompression({
|
||||
info: compressionInfo,
|
||||
compressedHistory: this.getHistoryShallow(),
|
||||
});
|
||||
}
|
||||
|
||||
// Add user content to history ONCE before any attempts.
|
||||
this.history.push(userContent);
|
||||
userContentAdded = true;
|
||||
|
||||
@ -1474,504 +1474,6 @@ describe('OpenAIContentConverter', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('should drop tool responses that are not adjacent to their assistant tool call', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_a',
|
||||
name: 'read_file',
|
||||
args: { path: 'a.txt' },
|
||||
},
|
||||
},
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_b',
|
||||
name: 'grep',
|
||||
args: { pattern: 'needle' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_a',
|
||||
name: 'read_file',
|
||||
response: { output: 'A' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [{ text: 'history text inserted between tool results' }],
|
||||
},
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_c',
|
||||
name: 'list_files',
|
||||
args: {},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_c',
|
||||
name: 'list_files',
|
||||
response: { output: 'C' },
|
||||
},
|
||||
},
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_b',
|
||||
name: 'grep',
|
||||
response: { output: 'B' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
requestContext,
|
||||
);
|
||||
const assistantWithCallA = messages.find(
|
||||
(message): message is OpenAI.Chat.ChatCompletionAssistantMessageParam =>
|
||||
message.role === 'assistant' &&
|
||||
'tool_calls' in message &&
|
||||
Array.isArray(message.tool_calls) &&
|
||||
message.tool_calls.some((toolCall) => toolCall.id === 'call_a'),
|
||||
);
|
||||
|
||||
expect(
|
||||
assistantWithCallA?.tool_calls?.map((toolCall) => toolCall.id),
|
||||
).toEqual(['call_a']);
|
||||
|
||||
const toolCallIds = messages
|
||||
.filter(
|
||||
(message): message is OpenAI.Chat.ChatCompletionToolMessageParam =>
|
||||
message.role === 'tool' && 'tool_call_id' in message,
|
||||
)
|
||||
.map((message) => message.tool_call_id);
|
||||
|
||||
expect(toolCallIds).toEqual(['call_a', 'call_c']);
|
||||
});
|
||||
|
||||
it('should keep assistant text when all tool calls are orphaned', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{ text: 'I can answer without the tool.' },
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_missing',
|
||||
name: 'read_file',
|
||||
args: { path: 'missing.txt' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [{ text: 'continue' }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
requestContext,
|
||||
);
|
||||
const assistant = messages.find(
|
||||
(message): message is OpenAI.Chat.ChatCompletionAssistantMessageParam =>
|
||||
message.role === 'assistant',
|
||||
);
|
||||
|
||||
expect(assistant?.content).toBe('I can answer without the tool.');
|
||||
expect('tool_calls' in (assistant ?? {})).toBe(false);
|
||||
expect(messages.some((message) => message.role === 'tool')).toBe(false);
|
||||
});
|
||||
|
||||
it('should drop assistant-only tool calls when all responses are orphaned', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_missing',
|
||||
name: 'read_file',
|
||||
args: { path: 'missing.txt' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [{ text: 'break adjacency' }],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [{ text: 'continue' }],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
requestContext,
|
||||
);
|
||||
|
||||
expect(messages.some((message) => message.role === 'assistant')).toBe(
|
||||
false,
|
||||
);
|
||||
expect(messages.some((message) => message.role === 'tool')).toBe(false);
|
||||
});
|
||||
|
||||
it('should keep a tool response after an empty-id tool message', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_a',
|
||||
name: 'read_file',
|
||||
args: { path: 'a.txt' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: 'empty_id',
|
||||
response: { output: 'no id' },
|
||||
},
|
||||
},
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_a',
|
||||
name: 'read_file',
|
||||
response: { output: 'A' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
requestContext,
|
||||
);
|
||||
const toolCallIds = messages
|
||||
.filter(
|
||||
(message): message is OpenAI.Chat.ChatCompletionToolMessageParam =>
|
||||
message.role === 'tool' && 'tool_call_id' in message,
|
||||
)
|
||||
.map((message) => message.tool_call_id);
|
||||
|
||||
expect(toolCallIds).toEqual(['call_a']);
|
||||
});
|
||||
|
||||
it('should clean after merging consecutive assistant turns', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_a',
|
||||
name: 'read_file',
|
||||
args: { path: 'a.txt' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'model',
|
||||
parts: [{ text: 'A short follow-up.' }],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_a',
|
||||
name: 'read_file',
|
||||
response: { output: 'A' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
requestContext,
|
||||
);
|
||||
|
||||
expect(messages[0]).toMatchObject({
|
||||
role: 'assistant',
|
||||
content: 'A short follow-up.',
|
||||
});
|
||||
expect(
|
||||
(
|
||||
messages[0] as OpenAI.Chat.ChatCompletionAssistantMessageParam
|
||||
).tool_calls?.map((toolCall) => toolCall.id),
|
||||
).toEqual(['call_a']);
|
||||
expect(messages[1]).toMatchObject({
|
||||
role: 'tool',
|
||||
tool_call_id: 'call_a',
|
||||
});
|
||||
});
|
||||
|
||||
it('should keep split media after all adjacent tool responses across content items', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: { id: 'call_a', name: 'shot_a', args: {} },
|
||||
},
|
||||
{
|
||||
functionCall: { id: 'call_b', name: 'shot_b', args: {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_a',
|
||||
name: 'shot_a',
|
||||
response: { output: 'A' },
|
||||
parts: [
|
||||
{ inlineData: { mimeType: 'image/png', data: 'aaa' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_b',
|
||||
name: 'shot_b',
|
||||
response: { output: 'B' },
|
||||
parts: [
|
||||
{ inlineData: { mimeType: 'image/png', data: 'bbb' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const strictContext: RequestContext = {
|
||||
...requestContext,
|
||||
splitToolMedia: true,
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
strictContext,
|
||||
);
|
||||
const assistantIndex = messages.findIndex(
|
||||
(message) => message.role === 'assistant',
|
||||
);
|
||||
|
||||
expect(messages[assistantIndex + 1]).toMatchObject({
|
||||
role: 'tool',
|
||||
tool_call_id: 'call_a',
|
||||
});
|
||||
expect(messages[assistantIndex + 2]).toMatchObject({
|
||||
role: 'tool',
|
||||
tool_call_id: 'call_b',
|
||||
});
|
||||
expect(messages[assistantIndex + 3]?.role).toBe('user');
|
||||
expect(messages[assistantIndex + 4]?.role).toBe('user');
|
||||
});
|
||||
|
||||
it('should not keep split media from orphaned tool responses', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: { id: 'call_a', name: 'shot_a', args: {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_x',
|
||||
name: 'shot_x',
|
||||
response: { output: 'X' },
|
||||
parts: [
|
||||
{ inlineData: { mimeType: 'image/png', data: 'xxx' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_a',
|
||||
name: 'shot_a',
|
||||
response: { output: 'A' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const strictContext: RequestContext = {
|
||||
...requestContext,
|
||||
splitToolMedia: true,
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
strictContext,
|
||||
);
|
||||
|
||||
expect(messages.map((message) => message.role)).toEqual([
|
||||
'assistant',
|
||||
'tool',
|
||||
]);
|
||||
expect(messages[1]).toMatchObject({
|
||||
role: 'tool',
|
||||
tool_call_id: 'call_a',
|
||||
});
|
||||
});
|
||||
|
||||
it('should merge assistant turns created by orphan cleanup', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: { id: 'call_a', name: 'read_file', args: {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_a',
|
||||
name: 'read_file',
|
||||
response: { output: 'A' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'model',
|
||||
parts: [{ text: 'Next I will call another tool.' }],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_orphan',
|
||||
name: 'stale_tool',
|
||||
response: { output: 'stale' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{
|
||||
functionCall: { id: 'call_b', name: 'grep', args: {} },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: 'call_b',
|
||||
name: 'grep',
|
||||
response: { output: 'B' },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
requestContext,
|
||||
);
|
||||
|
||||
for (let index = 1; index < messages.length; index += 1) {
|
||||
expect([messages[index - 1].role, messages[index].role]).not.toEqual([
|
||||
'assistant',
|
||||
'assistant',
|
||||
]);
|
||||
}
|
||||
expect(
|
||||
messages
|
||||
.filter(
|
||||
(message): message is OpenAI.Chat.ChatCompletionToolMessageParam =>
|
||||
message.role === 'tool' && 'tool_call_id' in message,
|
||||
)
|
||||
.map((message) => message.tool_call_id),
|
||||
).toEqual(['call_a', 'call_b']);
|
||||
});
|
||||
|
||||
describe('assistant message with reasoning-only content (issue #3421)', () => {
|
||||
/**
|
||||
* Regression tests for https://github.com/QwenLM/qwen-code/issues/3421
|
||||
@ -2012,41 +1514,6 @@ describe('OpenAIContentConverter', () => {
|
||||
).toBe('I reasoned about it.');
|
||||
});
|
||||
|
||||
it('should keep reasoning content when orphaned tool calls are removed', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
contents: [
|
||||
{
|
||||
role: 'model',
|
||||
parts: [
|
||||
{ text: 'I need to inspect this.', thought: true },
|
||||
{
|
||||
functionCall: {
|
||||
id: 'call_missing',
|
||||
name: 'read_file',
|
||||
args: {},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{ role: 'user', parts: [{ text: 'break adjacency' }] },
|
||||
],
|
||||
};
|
||||
|
||||
const messages = converter.convertGeminiRequestToOpenAI(
|
||||
request,
|
||||
requestContext,
|
||||
);
|
||||
|
||||
const assistantMsg = messages.find((m) => m.role === 'assistant');
|
||||
expect(assistantMsg).toBeDefined();
|
||||
expect((assistantMsg as { content: unknown }).content).toBe('');
|
||||
expect(
|
||||
(assistantMsg as { reasoning_content?: string }).reasoning_content,
|
||||
).toBe('I need to inspect this.');
|
||||
expect('tool_calls' in (assistantMsg ?? {})).toBe(false);
|
||||
});
|
||||
|
||||
it('should keep content null when assistant has only tool_calls and no reasoning', () => {
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'models/test',
|
||||
|
||||
@ -29,7 +29,6 @@ import {
|
||||
} from '../../utils/schemaConverter.js';
|
||||
|
||||
const debugLogger = createDebugLogger('CONVERTER');
|
||||
const SPLIT_TOOL_MEDIA_TEXT = '(attached media from previous tool call)';
|
||||
|
||||
/**
|
||||
* Extended usage type that supports both OpenAI standard format and alternative formats
|
||||
@ -381,11 +380,11 @@ export function convertGeminiRequestToOpenAI(
|
||||
// Handle contents
|
||||
processContents(request.contents, messages, requestContext);
|
||||
|
||||
messages = mergeConsecutiveAssistantMessages(messages);
|
||||
// Clean up orphaned tool calls and merge consecutive assistant messages
|
||||
if (options.cleanOrphanToolCalls) {
|
||||
messages = cleanOrphanedToolCalls(messages);
|
||||
messages = mergeConsecutiveAssistantMessages(messages);
|
||||
}
|
||||
messages = mergeConsecutiveAssistantMessages(messages);
|
||||
|
||||
return messages;
|
||||
}
|
||||
@ -646,7 +645,7 @@ function processContent(
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: SPLIT_TOOL_MEDIA_TEXT,
|
||||
text: '(attached media from previous tool call)',
|
||||
},
|
||||
...accumulatedSplitMedia,
|
||||
] as unknown as OpenAI.Chat.ChatCompletionContentPartText[],
|
||||
@ -1388,126 +1387,51 @@ function mapGeminiFinishReasonToOpenAI(
|
||||
}
|
||||
}
|
||||
|
||||
/** Type guard: is this an assistant message with at least one tool call? */
|
||||
function hasToolCalls(
|
||||
message: OpenAI.Chat.ChatCompletionMessageParam,
|
||||
): message is OpenAI.Chat.ChatCompletionAssistantMessageParam & {
|
||||
tool_calls: OpenAI.Chat.ChatCompletionMessageToolCall[];
|
||||
} {
|
||||
return (
|
||||
message.role === 'assistant' &&
|
||||
'tool_calls' in message &&
|
||||
Array.isArray(message.tool_calls) &&
|
||||
message.tool_calls.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
function isSplitToolMediaMessage(
|
||||
message: OpenAI.Chat.ChatCompletionMessageParam,
|
||||
): boolean {
|
||||
if (
|
||||
message.role !== 'user' ||
|
||||
!('content' in message) ||
|
||||
!Array.isArray(message.content)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const firstPart = message.content[0] as
|
||||
| { type?: string; text?: string }
|
||||
| undefined;
|
||||
return firstPart?.type === 'text' && firstPart.text === SPLIT_TOOL_MEDIA_TEXT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up orphaned tool calls from message history to prevent OpenAI API errors.
|
||||
*
|
||||
* Assumes consecutive assistant messages have already been merged.
|
||||
*/
|
||||
function cleanOrphanedToolCalls(
|
||||
messages: OpenAI.Chat.ChatCompletionMessageParam[],
|
||||
): OpenAI.Chat.ChatCompletionMessageParam[] {
|
||||
const cleaned: OpenAI.Chat.ChatCompletionMessageParam[] = [];
|
||||
const adjacentToolResponseIdsByAssistant = new Map<number, Set<string>>();
|
||||
const validToolResponseIndexesByAssistant = new Map<number, number[]>();
|
||||
const splitMediaIndexesByAssistant = new Map<number, number[]>();
|
||||
const emittedWithAssistant = new Set<number>();
|
||||
const toolCallIds = new Set<string>();
|
||||
const toolResponseIds = new Set<string>();
|
||||
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const message = messages[index];
|
||||
if (hasToolCalls(message)) {
|
||||
const toolCallIds = new Set(
|
||||
message.tool_calls
|
||||
.map((toolCall) => toolCall.id)
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
);
|
||||
const adjacentToolResponseIds = new Set<string>();
|
||||
const toolResponseIndexes: number[] = [];
|
||||
const splitMediaIndexes: number[] = [];
|
||||
let lastToolResponseMatchesAssistant = false;
|
||||
|
||||
for (
|
||||
let nextIndex = index + 1;
|
||||
nextIndex < messages.length;
|
||||
nextIndex += 1
|
||||
) {
|
||||
const nextMessage = messages[nextIndex];
|
||||
if (nextMessage.role === 'tool' && 'tool_call_id' in nextMessage) {
|
||||
if (!nextMessage.tool_call_id) {
|
||||
lastToolResponseMatchesAssistant = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (toolCallIds.has(nextMessage.tool_call_id)) {
|
||||
adjacentToolResponseIds.add(nextMessage.tool_call_id);
|
||||
toolResponseIndexes.push(nextIndex);
|
||||
lastToolResponseMatchesAssistant = true;
|
||||
} else {
|
||||
lastToolResponseMatchesAssistant = false;
|
||||
}
|
||||
|
||||
// Other tool responses in this block may belong to another assistant.
|
||||
continue;
|
||||
// First pass: collect all tool call IDs and tool response IDs
|
||||
for (const message of messages) {
|
||||
if (
|
||||
message.role === 'assistant' &&
|
||||
'tool_calls' in message &&
|
||||
message.tool_calls
|
||||
) {
|
||||
for (const toolCall of message.tool_calls) {
|
||||
if (toolCall.id) {
|
||||
toolCallIds.add(toolCall.id);
|
||||
}
|
||||
|
||||
if (isSplitToolMediaMessage(nextMessage)) {
|
||||
if (lastToolResponseMatchesAssistant) {
|
||||
splitMediaIndexes.push(nextIndex);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (nextMessage.role === 'assistant' && !hasToolCalls(nextMessage)) {
|
||||
// Consecutive assistant turns are merged before cleanup.
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
adjacentToolResponseIdsByAssistant.set(index, adjacentToolResponseIds);
|
||||
validToolResponseIndexesByAssistant.set(index, toolResponseIndexes);
|
||||
splitMediaIndexesByAssistant.set(index, splitMediaIndexes);
|
||||
} else if (
|
||||
message.role === 'tool' &&
|
||||
'tool_call_id' in message &&
|
||||
message.tool_call_id
|
||||
) {
|
||||
toolResponseIds.add(message.tool_call_id);
|
||||
}
|
||||
}
|
||||
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
if (emittedWithAssistant.has(index)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const message = messages[index];
|
||||
if (hasToolCalls(message)) {
|
||||
const reasoningContent = (
|
||||
message as ExtendedChatCompletionAssistantMessageParam
|
||||
).reasoning_content;
|
||||
const adjacentToolResponseIds =
|
||||
adjacentToolResponseIdsByAssistant.get(index) ?? new Set<string>();
|
||||
// Second pass: filter out orphaned messages
|
||||
for (const message of messages) {
|
||||
if (
|
||||
message.role === 'assistant' &&
|
||||
'tool_calls' in message &&
|
||||
message.tool_calls
|
||||
) {
|
||||
// Filter out tool calls that don't have corresponding responses
|
||||
const validToolCalls = message.tool_calls.filter(
|
||||
(toolCall) => toolCall.id && adjacentToolResponseIds.has(toolCall.id),
|
||||
(toolCall) => toolCall.id && toolResponseIds.has(toolCall.id),
|
||||
);
|
||||
|
||||
if (validToolCalls.length > 0) {
|
||||
// Keep the message but only with valid tool calls
|
||||
const cleanedMessage = { ...message };
|
||||
(
|
||||
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
|
||||
@ -1515,30 +1439,11 @@ function cleanOrphanedToolCalls(
|
||||
}
|
||||
).tool_calls = validToolCalls;
|
||||
cleaned.push(cleanedMessage);
|
||||
|
||||
for (const toolResponseIndex of validToolResponseIndexesByAssistant.get(
|
||||
index,
|
||||
) ?? []) {
|
||||
const toolResponse = messages[toolResponseIndex];
|
||||
if (toolResponse) {
|
||||
cleaned.push(toolResponse);
|
||||
emittedWithAssistant.add(toolResponseIndex);
|
||||
}
|
||||
}
|
||||
|
||||
for (const splitMediaIndex of splitMediaIndexesByAssistant.get(index) ??
|
||||
[]) {
|
||||
const splitMediaMessage = messages[splitMediaIndex];
|
||||
if (splitMediaMessage) {
|
||||
cleaned.push(splitMediaMessage);
|
||||
emittedWithAssistant.add(splitMediaIndex);
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
(typeof message.content === 'string' && message.content.trim()) ||
|
||||
reasoningContent
|
||||
typeof message.content === 'string' &&
|
||||
message.content.trim()
|
||||
) {
|
||||
// Keep text/reasoning content, but remove orphaned tool calls.
|
||||
// Keep the message if it has text content, but remove tool calls
|
||||
const cleanedMessage = { ...message };
|
||||
delete (
|
||||
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
|
||||
@ -1546,25 +1451,91 @@ function cleanOrphanedToolCalls(
|
||||
}
|
||||
).tool_calls;
|
||||
cleaned.push(cleanedMessage);
|
||||
} else {
|
||||
debugLogger.debug(
|
||||
`cleanOrphanedToolCalls: dropping assistant with ${message.tool_calls.length} orphaned tool call(s) and no text/reasoning content`,
|
||||
);
|
||||
}
|
||||
} else if (message.role === 'tool' && 'tool_call_id' in message) {
|
||||
debugLogger.debug(
|
||||
`cleanOrphanedToolCalls: dropping orphaned tool response ${message.tool_call_id || '<empty>'}`,
|
||||
);
|
||||
} else if (isSplitToolMediaMessage(message)) {
|
||||
debugLogger.debug(
|
||||
'cleanOrphanedToolCalls: dropping orphaned split tool media message',
|
||||
);
|
||||
// If no valid tool calls and no content, skip the message entirely
|
||||
} else if (
|
||||
message.role === 'tool' &&
|
||||
'tool_call_id' in message &&
|
||||
message.tool_call_id
|
||||
) {
|
||||
// Only keep tool responses that have corresponding tool calls
|
||||
if (toolCallIds.has(message.tool_call_id)) {
|
||||
cleaned.push(message);
|
||||
}
|
||||
} else {
|
||||
// Keep all other messages as-is
|
||||
cleaned.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
return cleaned;
|
||||
// Final validation: ensure every assistant message with tool_calls has corresponding tool responses
|
||||
const finalCleaned: OpenAI.Chat.ChatCompletionMessageParam[] = [];
|
||||
const finalToolCallIds = new Set<string>();
|
||||
|
||||
// Collect all remaining tool call IDs
|
||||
for (const message of cleaned) {
|
||||
if (
|
||||
message.role === 'assistant' &&
|
||||
'tool_calls' in message &&
|
||||
message.tool_calls
|
||||
) {
|
||||
for (const toolCall of message.tool_calls) {
|
||||
if (toolCall.id) {
|
||||
finalToolCallIds.add(toolCall.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify all tool calls have responses
|
||||
const finalToolResponseIds = new Set<string>();
|
||||
for (const message of cleaned) {
|
||||
if (
|
||||
message.role === 'tool' &&
|
||||
'tool_call_id' in message &&
|
||||
message.tool_call_id
|
||||
) {
|
||||
finalToolResponseIds.add(message.tool_call_id);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove any remaining orphaned tool calls
|
||||
for (const message of cleaned) {
|
||||
if (
|
||||
message.role === 'assistant' &&
|
||||
'tool_calls' in message &&
|
||||
message.tool_calls
|
||||
) {
|
||||
const finalValidToolCalls = message.tool_calls.filter(
|
||||
(toolCall) => toolCall.id && finalToolResponseIds.has(toolCall.id),
|
||||
);
|
||||
|
||||
if (finalValidToolCalls.length > 0) {
|
||||
const cleanedMessage = { ...message };
|
||||
(
|
||||
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
|
||||
tool_calls?: OpenAI.Chat.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
).tool_calls = finalValidToolCalls;
|
||||
finalCleaned.push(cleanedMessage);
|
||||
} else if (
|
||||
typeof message.content === 'string' &&
|
||||
message.content.trim()
|
||||
) {
|
||||
const cleanedMessage = { ...message };
|
||||
delete (
|
||||
cleanedMessage as OpenAI.Chat.ChatCompletionMessageParam & {
|
||||
tool_calls?: OpenAI.Chat.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
).tool_calls;
|
||||
finalCleaned.push(cleanedMessage);
|
||||
}
|
||||
} else {
|
||||
finalCleaned.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
return finalCleaned;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -15,7 +15,7 @@ import { OpenAIContentConverter } from './converter.js';
|
||||
import { openaiRequestCaptureContext } from './requestCaptureContext.js';
|
||||
import { StreamingToolCallParser } from './streamingToolCallParser.js';
|
||||
import type { Config } from '../../config/config.js';
|
||||
import { AuthType, type ContentGeneratorConfig } from '../contentGenerator.js';
|
||||
import type { ContentGeneratorConfig, AuthType } from '../contentGenerator.js';
|
||||
import type { OpenAICompatibleProvider } from './provider/index.js';
|
||||
|
||||
// Mock dependencies
|
||||
@ -463,31 +463,15 @@ describe('ContentGenerationPipeline', () => {
|
||||
});
|
||||
|
||||
it('should override enable_thinking when thinkingConfig disables it', async () => {
|
||||
// Arrange — provider injects enable_thinking: true via extra_body
|
||||
// (e.g. user configured `enableThinking: true` via setup wizard,
|
||||
// see provider-config.ts), but request explicitly disables thinking.
|
||||
// DashScope hostname + qwen model name are both required: the gate
|
||||
// is hostname + model-name to avoid leaking the qwen-specific
|
||||
// `enable_thinking` field to non-qwen routings (off-DashScope, or
|
||||
// GLM/DeepSeek on the same DashScope hostname).
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
model: 'qwen3.5-flash',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
// Arrange — provider injects enable_thinking: true via extra_body,
|
||||
// but request explicitly disables thinking
|
||||
(mockProvider.buildRequest as Mock).mockImplementation((req) => ({
|
||||
...req,
|
||||
enable_thinking: true, // Simulates extra_body injection
|
||||
}));
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'qwen3.5-flash',
|
||||
model: 'test-model',
|
||||
contents: [{ parts: [{ text: 'Suggest next' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
@ -763,375 +747,6 @@ describe('ContentGenerationPipeline', () => {
|
||||
expect(apiCall.thinking).toBeUndefined();
|
||||
});
|
||||
|
||||
it('emits enable_thinking:false on DashScope hostname when includeThoughts is false', async () => {
|
||||
// Regression for #4501: qwen3 hybrid models (e.g. qwen3.5-flash)
|
||||
// default to thinking-on. Provider buildRequest never auto-injects
|
||||
// `enable_thinking`, so a previous guarded `'enable_thinking' in typed`
|
||||
// check never fired and side-queries burned reasoning tokens (24-95x
|
||||
// output bloat in production). The disable must be emitted explicitly.
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
model: 'qwen3.5-flash',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
// Provider passes the request through unchanged — simulates the
|
||||
// common case where the user has not configured
|
||||
// `extra_body.enable_thinking` (so the field never appears on the
|
||||
// wire body unless we add it here).
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'qwen3.5-flash',
|
||||
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Summarize' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBe(false);
|
||||
});
|
||||
|
||||
it('emits enable_thinking:false on DashScope hostname when reasoning is configured to false', async () => {
|
||||
// Config-level opt-out (`reasoning: false`) should also disable
|
||||
// qwen3 thinking, mirroring the DeepSeek pair above.
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
model: 'qwen3.5-flash',
|
||||
reasoning: false,
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'qwen3.5-flash',
|
||||
contents: [{ parts: [{ text: 'Hello' }], role: 'user' }],
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Hello' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'main');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBe(false);
|
||||
});
|
||||
|
||||
it('emits enable_thinking:false on QWEN_OAUTH with the default coder-model', async () => {
|
||||
// QWEN_OAUTH is the default auth flow for first-time users and
|
||||
// ships with `model: 'coder-model'` (DEFAULT_QWEN_MODEL in
|
||||
// config/models.ts — aliased to Qwen 3.6 Plus hybrid). The string
|
||||
// doesn't start with `qwen`, so the gate must special-case it;
|
||||
// otherwise the exact regression that #4501 fixes (side-queries
|
||||
// burning reasoning tokens on the default flow) remains live.
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
authType: AuthType.QWEN_OAUTH,
|
||||
baseUrl: 'https://some-oauth-issued-endpoint.example/v1',
|
||||
model: 'coder-model',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'coder-model',
|
||||
contents: [{ parts: [{ text: 'Hi' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Hi' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBe(false);
|
||||
});
|
||||
|
||||
it('emits enable_thinking:false on internal alibaba-inc.com hostname', async () => {
|
||||
// Internal Alibaba domains proxy to DashScope-compatible APIs and
|
||||
// are treated as DashScope by design (provider/dashscope.ts:75-78).
|
||||
// Cover the internal-origin path explicitly so a future tightening
|
||||
// of the hostname rules does not silently drop coverage for
|
||||
// internal users.
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://gateway.alibaba-inc.com/v1',
|
||||
model: 'qwen3.5-flash',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'qwen3.5-flash',
|
||||
contents: [{ parts: [{ text: 'Hi' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Hi' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBe(false);
|
||||
});
|
||||
|
||||
it('does NOT emit enable_thinking on a non-DashScope hostname', async () => {
|
||||
// `enable_thinking` is a qwen-specific extension. Pushing it at a
|
||||
// strict OpenAI-compatible backend could trip an unknown-key 400
|
||||
// and would also pollute logs with a meaningless field. Mirror of
|
||||
// the DeepSeek negative test above.
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
model: 'gpt-5',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'test-model',
|
||||
contents: [{ parts: [{ text: 'Suggest' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Suggest' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does NOT emit enable_thinking on a non-qwen model routed through DashScope', async () => {
|
||||
// DashScope's compatible-mode endpoint routes multiple model families
|
||||
// (qwen3, GLM, DeepSeek). Hostname alone is not enough — GLM uses
|
||||
// `extra_body.thinking.enabled` and DeepSeek-on-DashScope uses
|
||||
// `thinking: { type: 'disabled' }`, so sending `enable_thinking` is
|
||||
// at best a no-op and at worst forwarded upstream and rejected.
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
model: 'glm-5',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'glm-5',
|
||||
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Summarize' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBeUndefined();
|
||||
});
|
||||
|
||||
it('gates on the wire model, not config: qwen config + non-qwen request.model does NOT emit', async () => {
|
||||
// buildRequest ships `context.model` (= request.model || config.model).
|
||||
// A qwen *config* with a non-qwen *request* model must gate on the
|
||||
// request model — otherwise the qwen-only field leaks to the non-qwen
|
||||
// routing that is actually on the wire (e.g. GLM rejecting it upstream).
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
model: 'qwen3.5-flash',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'glm-5', // request-level override to a non-qwen wire model
|
||||
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Summarize' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBeUndefined();
|
||||
});
|
||||
|
||||
it('gates on the wire model, not config: non-qwen config + qwen request.model emits false', async () => {
|
||||
// The mirror direction: a non-qwen *config* with a qwen *request* model
|
||||
// must still emit the disable signal, since the wire model is qwen and
|
||||
// would otherwise keep thinking-on (the #4501 regression).
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||||
model: 'glm-5',
|
||||
} as ContentGeneratorConfig;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'qwen3.5-flash', // request-level override to a qwen wire model
|
||||
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Summarize' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBe(false);
|
||||
});
|
||||
|
||||
it('emits enable_thinking:false when baseUrl is unset (DashScope default)', async () => {
|
||||
// `isDashScopeProvider` treats a missing baseUrl as DashScope
|
||||
// (`dashscope.ts:49` returns true for `!baseUrl`). A fresh install
|
||||
// that hasn't run the setup wizard hits this path. All other
|
||||
// positive tests above explicitly set baseUrl, so pin this
|
||||
// implicit-default branch separately to detect future tightening
|
||||
// of the `!baseUrl` early-return.
|
||||
mockContentGeneratorConfig = {
|
||||
...mockContentGeneratorConfig,
|
||||
model: 'qwen3.5-flash',
|
||||
} as ContentGeneratorConfig;
|
||||
delete (mockContentGeneratorConfig as { baseUrl?: string }).baseUrl;
|
||||
mockConfig = {
|
||||
...mockConfig,
|
||||
contentGeneratorConfig: mockContentGeneratorConfig,
|
||||
};
|
||||
pipeline = new ContentGenerationPipeline(mockConfig);
|
||||
|
||||
const request: GenerateContentParameters = {
|
||||
model: 'qwen3.5-flash',
|
||||
contents: [{ parts: [{ text: 'Summarize' }], role: 'user' }],
|
||||
config: { thinkingConfig: { includeThoughts: false } },
|
||||
};
|
||||
|
||||
(mockConverter.convertGeminiRequestToOpenAI as Mock).mockReturnValue([
|
||||
{ role: 'user', content: 'Summarize' },
|
||||
]);
|
||||
(mockConverter.convertOpenAIResponseToGemini as Mock).mockReturnValue(
|
||||
new GenerateContentResponse(),
|
||||
);
|
||||
(mockClient.chat.completions.create as Mock).mockResolvedValue({
|
||||
id: 'r',
|
||||
choices: [{ message: { content: 'ok' }, finish_reason: 'stop' }],
|
||||
} as OpenAI.Chat.ChatCompletion);
|
||||
|
||||
await pipeline.execute(request, 'forked_query');
|
||||
|
||||
const apiCall = (mockClient.chat.completions.create as Mock).mock
|
||||
.calls[0][0];
|
||||
expect(apiCall.enable_thinking).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle errors and log them', async () => {
|
||||
// Arrange
|
||||
const request: GenerateContentParameters = {
|
||||
|
||||
@ -11,7 +11,6 @@ import {
|
||||
} from '@google/genai';
|
||||
import type { ContentGeneratorConfig } from '../contentGenerator.js';
|
||||
import { OpenAIContentConverter } from './converter.js';
|
||||
import { DashScopeOpenAICompatibleProvider } from './provider/dashscope.js';
|
||||
import { isDeepSeekHostname } from './provider/deepseek.js';
|
||||
import { openaiRequestCaptureContext } from './requestCaptureContext.js';
|
||||
import { StreamingToolCallParser } from './streamingToolCallParser.js';
|
||||
@ -342,33 +341,7 @@ export class ContentGenerationPipeline {
|
||||
this.contentGeneratorConfig.reasoning === false;
|
||||
if (reasoningDisabled) {
|
||||
const typed = providerRequest as unknown as Record<string, unknown>;
|
||||
// Provider buildRequest doesn't auto-inject `enable_thinking`, so a
|
||||
// guarded `in typed` check would never fire for default qwen3 configs.
|
||||
// Hostname + model-name gate avoids leaking this qwen-specific field
|
||||
// to non-qwen routings on the same DashScope hostname (GLM uses
|
||||
// `extra_body.thinking.enabled`, DeepSeek-on-DashScope uses
|
||||
// `thinking: { type: 'disabled' }`; sending `enable_thinking` to them
|
||||
// is at best a no-op, at worst forwarded upstream and rejected).
|
||||
//
|
||||
// Gate on the *wire* model (`context.model`, i.e.
|
||||
// `request.model || contentGeneratorConfig.model` — the same value
|
||||
// baseRequest.model is built from above), not on the config model. A
|
||||
// request-level model override would otherwise desync the gate from
|
||||
// what actually ships: a qwen config with a non-qwen request model
|
||||
// would leak the field, and a non-qwen config with a qwen request
|
||||
// model would miss the disable signal (the #4501 regression).
|
||||
//
|
||||
// `coder-model` is the QWEN_OAUTH default (DEFAULT_QWEN_MODEL in
|
||||
// config/models.ts, aliased to Qwen 3.6 Plus hybrid) — it doesn't
|
||||
// start with `qwen` but is the most common hybrid-thinking model
|
||||
// for first-time users, so it must be covered.
|
||||
const model = (context.model ?? '').toLowerCase();
|
||||
if (
|
||||
DashScopeOpenAICompatibleProvider.isDashScopeProvider(
|
||||
this.contentGeneratorConfig,
|
||||
) &&
|
||||
(model.startsWith('qwen') || model === 'coder-model')
|
||||
) {
|
||||
if ('enable_thinking' in typed) {
|
||||
typed['enable_thinking'] = false;
|
||||
}
|
||||
// Strip reasoning config — extra_body could inject it, overriding
|
||||
@ -478,8 +451,7 @@ export class ContentGenerationPipeline {
|
||||
// - glm-4.7 — thinking is enabled by default; can be disabled via `extra_body.thinking.enabled`
|
||||
// - kimi-k2-thinking — thinking is enabled by default and cannot be disabled
|
||||
// - gpt-5.x series — thinking is enabled by default; can be disabled via `reasoning.effort`
|
||||
// - qwen3 series — model-dependent; emitted as `enable_thinking: false`
|
||||
// on DashScope endpoints when reasoning is disabled
|
||||
// - qwen3 series — model-dependent; can be manually disabled via `extra_body.enable_thinking`
|
||||
//
|
||||
// Given this inconsistency, we avoid mapping values and only pass through the
|
||||
// configured reasoning object when explicitly enabled. This keeps provider- and
|
||||
|
||||
@ -70,11 +70,6 @@ export function getHookMatcherTarget(
|
||||
}
|
||||
}
|
||||
|
||||
export function hookEventSupportsMatcher(eventName: HookEventName): boolean {
|
||||
const target = getHookMatcherTarget(eventName);
|
||||
return typeof target === 'object' && target !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook planner that selects matching hooks and creates execution plans
|
||||
*/
|
||||
|
||||
@ -29,6 +29,7 @@ import { FunctionHookRunner } from './functionHookRunner.js';
|
||||
import { PromptHookRunner } from './promptHookRunner.js';
|
||||
import { AsyncHookRegistry, generateHookId } from './asyncHookRegistry.js';
|
||||
import type { Config } from '../config/config.js';
|
||||
import { getShellContextEnvVars } from '../utils/shellContextEnv.js';
|
||||
|
||||
const debugLogger = createDebugLogger('TRUSTED_HOOKS');
|
||||
|
||||
@ -573,6 +574,7 @@ export class HookRunner {
|
||||
GEMINI_PROJECT_DIR: input.cwd,
|
||||
CLAUDE_PROJECT_DIR: input.cwd, // For compatibility
|
||||
QWEN_PROJECT_DIR: input.cwd, // For Qwen Code compatibility
|
||||
...getShellContextEnvVars(),
|
||||
...hookConfig.env,
|
||||
};
|
||||
|
||||
|
||||
@ -12,7 +12,7 @@ export { HookSystem } from './hookSystem.js';
|
||||
export { HookRegistry } from './hookRegistry.js';
|
||||
export { HookRunner } from './hookRunner.js';
|
||||
export { HookAggregator } from './hookAggregator.js';
|
||||
export { HookPlanner, hookEventSupportsMatcher } from './hookPlanner.js';
|
||||
export { HookPlanner } from './hookPlanner.js';
|
||||
export { HookEventHandler } from './hookEventHandler.js';
|
||||
|
||||
// Export new hook runners
|
||||
|
||||
@ -388,11 +388,7 @@ export * from './test-utils/index.js';
|
||||
// ============================================================================
|
||||
|
||||
export * from './hooks/types.js';
|
||||
export {
|
||||
HookSystem,
|
||||
HookRegistry,
|
||||
hookEventSupportsMatcher,
|
||||
} from './hooks/index.js';
|
||||
export { HookSystem, HookRegistry } from './hooks/index.js';
|
||||
export type { HookRegistryEntry, SessionHookEntry } from './hooks/index.js';
|
||||
export {
|
||||
DEFAULT_STOP_HOOK_BLOCK_CAP,
|
||||
|
||||
@ -704,121 +704,4 @@ describe('FileReadCache', () => {
|
||||
expect(cache.check(makeStats({ ino: 0 })).state).not.toBe('unknown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('evictNotAccessedSince', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('evicts entries with lastReadAt before the cutoff', () => {
|
||||
const cache = new FileReadCache();
|
||||
const now = 2_000_000_000;
|
||||
const old = now - 100 * 60_000; // 100 minutes ago
|
||||
const recent = now - 5 * 60_000; // 5 minutes ago
|
||||
|
||||
const oldStats = makeStats({ ino: 1 });
|
||||
const recentStats = makeStats({ ino: 2 });
|
||||
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(old);
|
||||
cache.recordRead('/x/old.ts', oldStats, { full: true, cacheable: true });
|
||||
|
||||
vi.setSystemTime(recent);
|
||||
cache.recordRead('/x/recent.ts', recentStats, {
|
||||
full: true,
|
||||
cacheable: true,
|
||||
});
|
||||
|
||||
// Now set time to "now" and evict entries older than 30 minutes
|
||||
vi.setSystemTime(now);
|
||||
|
||||
const evicted = cache.evictNotAccessedSince(30);
|
||||
expect(evicted).toBe(1);
|
||||
expect(cache.check(oldStats).state).toBe('unknown');
|
||||
expect(cache.check(recentStats).state).toBe('fresh');
|
||||
});
|
||||
|
||||
it('evicts entries that were only written, never read', () => {
|
||||
const cache = new FileReadCache();
|
||||
vi.useFakeTimers();
|
||||
|
||||
const pastWrite = 1000; // some fixed timestamp in the past
|
||||
vi.setSystemTime(pastWrite);
|
||||
cache.recordWrite('/x/old-write.ts', makeStats({ ino: 2 }));
|
||||
|
||||
// Advance time by 120 minutes
|
||||
vi.setSystemTime(pastWrite + 120 * 60_000);
|
||||
|
||||
const evicted = cache.evictNotAccessedSince(60);
|
||||
expect(evicted).toBe(1);
|
||||
expect(cache.size()).toBe(0);
|
||||
});
|
||||
|
||||
it('preserves recently accessed entries', () => {
|
||||
const cache = new FileReadCache();
|
||||
vi.useFakeTimers();
|
||||
|
||||
const now = Date.now();
|
||||
vi.setSystemTime(now);
|
||||
|
||||
cache.recordRead('/x/recent.ts', makeStats({ ino: 1 }), {
|
||||
full: true,
|
||||
cacheable: true,
|
||||
});
|
||||
|
||||
const evicted = cache.evictNotAccessedSince(30);
|
||||
expect(evicted).toBe(0);
|
||||
expect(cache.size()).toBe(1);
|
||||
});
|
||||
|
||||
it('returns correct eviction count', () => {
|
||||
const cache = new FileReadCache();
|
||||
vi.useFakeTimers();
|
||||
|
||||
const now = Date.now();
|
||||
vi.setSystemTime(now);
|
||||
|
||||
// 3 recent entries
|
||||
for (let i = 0; i < 3; i++) {
|
||||
cache.recordRead(`/x/recent-${i}.ts`, makeStats({ ino: i }), {
|
||||
full: true,
|
||||
cacheable: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Jump 120 minutes back, add 2 old entries
|
||||
vi.setSystemTime(now - 120 * 60_000);
|
||||
for (let i = 10; i < 12; i++) {
|
||||
cache.recordRead(`/x/old-${i}.ts`, makeStats({ ino: i }), {
|
||||
full: true,
|
||||
cacheable: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Back to now
|
||||
vi.setSystemTime(now);
|
||||
|
||||
const evicted = cache.evictNotAccessedSince(60);
|
||||
expect(evicted).toBe(2);
|
||||
expect(cache.size()).toBe(3);
|
||||
});
|
||||
|
||||
it('returns 0 for empty cache', () => {
|
||||
const cache = new FileReadCache();
|
||||
expect(cache.evictNotAccessedSince(30)).toBe(0);
|
||||
});
|
||||
|
||||
it('does not evict entries for sub-minute windows', () => {
|
||||
const cache = new FileReadCache();
|
||||
cache.recordRead('/x/recent.ts', makeStats({ ino: 1 }), {
|
||||
full: true,
|
||||
cacheable: true,
|
||||
});
|
||||
|
||||
expect(cache.evictNotAccessedSince(0)).toBe(0);
|
||||
expect(cache.evictNotAccessedSince(-30)).toBe(0);
|
||||
expect(cache.evictNotAccessedSince(0.0000001)).toBe(0);
|
||||
expect(cache.size()).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -317,36 +317,6 @@ export class FileReadCache {
|
||||
this.byInode.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Evict entries whose most recent Read (or Write; both set
|
||||
* {@link FileReadEntry.lastReadAt}) is older than `minutes`.
|
||||
*
|
||||
* This is a memory-pressure-driven eviction: it targets entries the
|
||||
* model is least likely to need again, trading cache hit rate for lower
|
||||
* memory footprint. Unlike {@link clear}, it preserves recently-read
|
||||
* entries so the file_unchanged fast-path stays available for active
|
||||
* files.
|
||||
*
|
||||
* @returns Number of entries evicted.
|
||||
*/
|
||||
evictNotAccessedSince(minutes: number): number {
|
||||
if (!Number.isFinite(minutes) || minutes < 1) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const cutoff = Date.now() - minutes * 60 * 1000;
|
||||
let evicted = 0;
|
||||
|
||||
for (const [key, entry] of this.byInode) {
|
||||
if (entry.lastReadAt !== undefined && entry.lastReadAt < cutoff) {
|
||||
this.byInode.delete(key);
|
||||
evicted++;
|
||||
}
|
||||
}
|
||||
|
||||
return evicted;
|
||||
}
|
||||
|
||||
/** Number of tracked entries. Diagnostic / test use only. */
|
||||
size(): number {
|
||||
return this.byInode.size;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,605 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Qwen Team
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import * as os from 'node:os';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { getHeapStatistics } from 'node:v8';
|
||||
import { createDebugLogger } from '../utils/debugLogger.js';
|
||||
import { getErrorMessage } from '../utils/errors.js';
|
||||
import type { Config } from '../config/config.js';
|
||||
|
||||
// Types
|
||||
|
||||
export interface MemoryPressureConfig {
|
||||
/** RSS / totalmem ratio at which light cleanup begins. Default 0.50. */
|
||||
softPressureRatio: number;
|
||||
/** RSS / totalmem ratio at which moderate cleanup begins. Default 0.65. */
|
||||
hardPressureRatio: number;
|
||||
/** RSS / totalmem ratio at which aggressive cleanup begins. Default 0.80. */
|
||||
criticalRatio: number;
|
||||
/** Minimum ms between consecutive cleanups. Default 5000. */
|
||||
cleanupCooldownMs: number;
|
||||
/** Allow global.gc() in aggressive cleanup. Requires --expose-gc. */
|
||||
enableExplicitGC: boolean;
|
||||
}
|
||||
|
||||
export interface CleanupRecommendation {
|
||||
action: 'none' | 'light' | 'moderate' | 'aggressive';
|
||||
steps: CleanupStep[];
|
||||
}
|
||||
|
||||
export type CleanupStep =
|
||||
| 'clear_file_cache'
|
||||
| 'evict_cold_cache'
|
||||
| 'evict_stale_cache'
|
||||
| 'trigger_gc';
|
||||
|
||||
export interface MemoryCleanupFailureEvent {
|
||||
rss: number;
|
||||
consecutiveFailures: number;
|
||||
recommendation: CleanupRecommendation;
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface MemoryCleanupIneffectiveEvent {
|
||||
rss: number;
|
||||
freedBytes: number;
|
||||
freedRatio: number;
|
||||
consecutiveIneffectiveCleanups: number;
|
||||
recommendation: CleanupRecommendation;
|
||||
}
|
||||
|
||||
export const DEFAULT_PRESSURE_CONFIG: MemoryPressureConfig = {
|
||||
softPressureRatio: 0.5,
|
||||
hardPressureRatio: 0.65,
|
||||
criticalRatio: 0.8,
|
||||
cleanupCooldownMs: 5_000,
|
||||
enableExplicitGC: false,
|
||||
};
|
||||
|
||||
// Validation
|
||||
|
||||
export function validateMemoryPressureConfig(c: MemoryPressureConfig): void {
|
||||
for (const [name, ratio] of [
|
||||
['softPressureRatio', c.softPressureRatio],
|
||||
['hardPressureRatio', c.hardPressureRatio],
|
||||
['criticalRatio', c.criticalRatio],
|
||||
] as const) {
|
||||
if (!Number.isFinite(ratio) || ratio < 0.3 || ratio > 0.98) {
|
||||
throw new Error(`${name} must be a finite ratio in [0.3, 0.98]`);
|
||||
}
|
||||
}
|
||||
if (c.softPressureRatio >= c.hardPressureRatio) {
|
||||
throw new Error('softPressureRatio must be < hardPressureRatio');
|
||||
}
|
||||
if (c.hardPressureRatio >= c.criticalRatio) {
|
||||
throw new Error('hardPressureRatio must be < criticalRatio');
|
||||
}
|
||||
if (!Number.isFinite(c.cleanupCooldownMs) || c.cleanupCooldownMs < 0) {
|
||||
throw new Error('cleanupCooldownMs must be a non-negative number');
|
||||
}
|
||||
}
|
||||
|
||||
const debugLogger = createDebugLogger('MEMORY_PRESSURE');
|
||||
const MIN_CGROUP_MEMORY_LIMIT = 64 * 1024 * 1024;
|
||||
|
||||
// Monitor
|
||||
|
||||
export class MemoryPressureMonitor extends EventEmitter {
|
||||
private readonly config: MemoryPressureConfig;
|
||||
private readonly coreConfig: Config;
|
||||
|
||||
private pendingCheck = false;
|
||||
private cleanupInProgress = false;
|
||||
private activeCleanupAction: CleanupRecommendation['action'] = 'none';
|
||||
private lastCleanupAction: CleanupRecommendation['action'] = 'none';
|
||||
private queuedCleanupRecommendation?: CleanupRecommendation;
|
||||
private lastCleanupTime = 0;
|
||||
private consecutiveCleanupFailures = 0;
|
||||
private consecutiveIneffectiveCleanups = 0;
|
||||
private consecutiveIneffectiveAggressiveCleanups = 0;
|
||||
private cleanupGeneration = 0;
|
||||
private readonly effectiveMemoryLimit: number;
|
||||
|
||||
constructor(coreConfig: Config, pressureConfig?: MemoryPressureConfig) {
|
||||
super();
|
||||
this.coreConfig = coreConfig;
|
||||
this.config = { ...(pressureConfig ?? DEFAULT_PRESSURE_CONFIG) };
|
||||
validateMemoryPressureConfig(this.config);
|
||||
this.effectiveMemoryLimit = this.computeEffectiveMemoryLimit();
|
||||
const heapSizeLimit = getHeapStatistics().heap_size_limit;
|
||||
debugLogger.info(
|
||||
`Effective memory limit: ${formatMiB(this.effectiveMemoryLimit)} MiB; ` +
|
||||
`V8 heap limit: ${formatMiB(heapSizeLimit)} MiB`,
|
||||
);
|
||||
if (this.effectiveMemoryLimit <= 0) {
|
||||
debugLogger.warn(
|
||||
'Effective memory limit is not positive; RSS pressure checks are disabled',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Public API
|
||||
|
||||
getConsecutiveFailures(): number {
|
||||
return this.consecutiveCleanupFailures;
|
||||
}
|
||||
|
||||
resetConsecutiveFailures(): void {
|
||||
this.consecutiveCleanupFailures = 0;
|
||||
this.consecutiveIneffectiveCleanups = 0;
|
||||
this.consecutiveIneffectiveAggressiveCleanups = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset session-scoped cleanup state and invalidate any async cleanup tail
|
||||
* that was queued against the previous session's cache.
|
||||
*/
|
||||
resetForNewSession(): void {
|
||||
this.cleanupGeneration++;
|
||||
this.resetConsecutiveFailures();
|
||||
this.cleanupInProgress = false;
|
||||
this.activeCleanupAction = 'none';
|
||||
this.queuedCleanupRecommendation = undefined;
|
||||
this.lastCleanupAction = 'none';
|
||||
this.lastCleanupTime = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a deferred memory check after a tool finishes execution.
|
||||
* Uses queueMicrotask to batch checks across concurrently-completing
|
||||
* tools within the same event-loop tick.
|
||||
*/
|
||||
scheduleCheck(): void {
|
||||
if (this.pendingCheck) return;
|
||||
this.pendingCheck = true;
|
||||
queueMicrotask(() => {
|
||||
try {
|
||||
this.performCheck();
|
||||
} finally {
|
||||
this.pendingCheck = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Force an immediate check (e.g. after a concurrent batch completes). */
|
||||
performCheck(): void {
|
||||
try {
|
||||
this.performCheckInternal();
|
||||
} catch (err) {
|
||||
debugLogger.error(
|
||||
`Memory pressure check failed: ${getErrorMessage(err)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private performCheckInternal(): void {
|
||||
const pressure = this.getPressureLevel();
|
||||
if (pressure !== 'critical') {
|
||||
this.consecutiveIneffectiveAggressiveCleanups = 0;
|
||||
}
|
||||
if (pressure === 'normal') return;
|
||||
|
||||
const recommendation = this.recommendCleanup(pressure);
|
||||
if (recommendation.action === 'none') return;
|
||||
|
||||
const now = Date.now();
|
||||
const isEscalation =
|
||||
cleanupActionRank(recommendation.action) >
|
||||
cleanupActionRank(this.lastCleanupAction);
|
||||
const cleanupCooldownMs = this.getCleanupCooldownMs(recommendation.action);
|
||||
if (!isEscalation && now - this.lastCleanupTime < cleanupCooldownMs) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.executeCleanup(recommendation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the current memory pressure level from the stronger of:
|
||||
* - RSS as a fraction of the effective memory limit (cgroup-aware).
|
||||
* - V8 heap usage as a fraction of V8's heap size limit.
|
||||
*/
|
||||
getPressureLevel(): 'normal' | 'soft' | 'hard' | 'critical' {
|
||||
let mem: ReturnType<typeof process.memoryUsage>;
|
||||
try {
|
||||
mem = process.memoryUsage();
|
||||
} catch (err) {
|
||||
debugLogger.error(
|
||||
`Failed to read memory usage for pressure check: ${getErrorMessage(err)}`,
|
||||
);
|
||||
return 'normal';
|
||||
}
|
||||
|
||||
const rssRatio =
|
||||
this.effectiveMemoryLimit > 0 ? mem.rss / this.effectiveMemoryLimit : 0;
|
||||
const heapSizeLimit = getHeapStatistics().heap_size_limit;
|
||||
const heapRatio = heapSizeLimit > 0 ? mem.heapUsed / heapSizeLimit : 0;
|
||||
const ratio = Math.max(rssRatio, heapRatio);
|
||||
|
||||
if (ratio >= this.config.criticalRatio) return 'critical';
|
||||
if (ratio >= this.config.hardPressureRatio) return 'hard';
|
||||
if (ratio >= this.config.softPressureRatio) return 'soft';
|
||||
return 'normal';
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
|
||||
private recommendCleanup(
|
||||
pressure: 'soft' | 'hard' | 'critical',
|
||||
): CleanupRecommendation {
|
||||
switch (pressure) {
|
||||
case 'critical':
|
||||
return {
|
||||
action: 'aggressive',
|
||||
steps: [
|
||||
'clear_file_cache',
|
||||
...(this.config.enableExplicitGC ? ['trigger_gc' as const] : []),
|
||||
],
|
||||
};
|
||||
case 'hard':
|
||||
return {
|
||||
action: 'moderate',
|
||||
steps: ['evict_cold_cache'],
|
||||
};
|
||||
case 'soft':
|
||||
return {
|
||||
action: 'light',
|
||||
steps: ['evict_stale_cache'],
|
||||
};
|
||||
default:
|
||||
return assertNever(pressure);
|
||||
}
|
||||
}
|
||||
|
||||
private executeCleanup(recommendation: CleanupRecommendation): void {
|
||||
if (this.cleanupInProgress) {
|
||||
const recommendationRank = cleanupActionRank(recommendation.action);
|
||||
const activeRank = cleanupActionRank(this.activeCleanupAction);
|
||||
const queuedRank = this.queuedCleanupRecommendation
|
||||
? cleanupActionRank(this.queuedCleanupRecommendation.action)
|
||||
: 0;
|
||||
if (recommendationRank > activeRank && recommendationRank > queuedRank) {
|
||||
this.queuedCleanupRecommendation = recommendation;
|
||||
debugLogger.debug(
|
||||
`Queued escalated cleanup "${recommendation.action}" while ` +
|
||||
`"${this.activeCleanupAction}" is in progress`,
|
||||
);
|
||||
} else {
|
||||
debugLogger.debug('Cleanup already in progress, skipping');
|
||||
}
|
||||
return;
|
||||
}
|
||||
let memBefore: number;
|
||||
try {
|
||||
memBefore = process.memoryUsage().rss;
|
||||
} catch (err) {
|
||||
this.recordCleanupFailure(recommendation, err);
|
||||
return;
|
||||
}
|
||||
|
||||
this.cleanupInProgress = true;
|
||||
this.activeCleanupAction = recommendation.action;
|
||||
this.lastCleanupAction = recommendation.action;
|
||||
this.lastCleanupTime = Date.now();
|
||||
const cleanupGeneration = this.cleanupGeneration;
|
||||
|
||||
void this.runCleanupSteps(recommendation.steps, cleanupGeneration)
|
||||
.then(() => {
|
||||
if (cleanupGeneration !== this.cleanupGeneration) {
|
||||
return;
|
||||
}
|
||||
this.consecutiveCleanupFailures = 0;
|
||||
setImmediate(() => {
|
||||
if (cleanupGeneration !== this.cleanupGeneration) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const memAfter = process.memoryUsage().rss;
|
||||
this.logCleanupResult(memBefore, memAfter, recommendation);
|
||||
} catch (err) {
|
||||
debugLogger.error(
|
||||
`Cleanup measurement failed: ${getErrorMessage(err)}`,
|
||||
);
|
||||
} finally {
|
||||
this.finishCleanupAndRunQueued(cleanupGeneration);
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
if (cleanupGeneration !== this.cleanupGeneration) {
|
||||
return;
|
||||
}
|
||||
this.recordCleanupFailure(recommendation, err);
|
||||
this.finishCleanupAndRunQueued(cleanupGeneration);
|
||||
});
|
||||
}
|
||||
|
||||
private finishCleanupAndRunQueued(cleanupGeneration: number): void {
|
||||
if (cleanupGeneration !== this.cleanupGeneration) {
|
||||
return;
|
||||
}
|
||||
this.cleanupInProgress = false;
|
||||
this.activeCleanupAction = 'none';
|
||||
const queuedRecommendation = this.queuedCleanupRecommendation;
|
||||
this.queuedCleanupRecommendation = undefined;
|
||||
if (queuedRecommendation) {
|
||||
try {
|
||||
this.executeCleanup(queuedRecommendation);
|
||||
} catch (err) {
|
||||
this.recordCleanupFailure(queuedRecommendation, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getCleanupCooldownMs(
|
||||
action: CleanupRecommendation['action'],
|
||||
): number {
|
||||
const baseCooldownMs = this.config.cleanupCooldownMs;
|
||||
if (
|
||||
action !== 'aggressive' ||
|
||||
baseCooldownMs === 0 ||
|
||||
this.consecutiveIneffectiveAggressiveCleanups < 3
|
||||
) {
|
||||
return baseCooldownMs;
|
||||
}
|
||||
|
||||
const exponent = Math.min(
|
||||
this.consecutiveIneffectiveAggressiveCleanups - 2,
|
||||
6,
|
||||
);
|
||||
return baseCooldownMs * 2 ** exponent;
|
||||
}
|
||||
|
||||
private logCleanupResult(
|
||||
memBefore: number,
|
||||
memAfter: number,
|
||||
recommendation: CleanupRecommendation,
|
||||
): void {
|
||||
const freed = memBefore - memAfter;
|
||||
const freedRatio = memBefore > 0 ? freed / memBefore : 0;
|
||||
|
||||
debugLogger.info(
|
||||
`Cleanup "${recommendation.action}" completed; RSS delta ${freed} bytes ` +
|
||||
`(${(freedRatio * 100).toFixed(1)}%)`,
|
||||
);
|
||||
|
||||
if (freedRatio < 0.01) {
|
||||
this.consecutiveIneffectiveCleanups++;
|
||||
if (recommendation.action === 'aggressive') {
|
||||
this.consecutiveIneffectiveAggressiveCleanups++;
|
||||
}
|
||||
if (shouldEmitRepeatedDiagnostic(this.consecutiveIneffectiveCleanups)) {
|
||||
const event = {
|
||||
rss: memAfter,
|
||||
freedBytes: freed,
|
||||
freedRatio,
|
||||
consecutiveIneffectiveCleanups: this.consecutiveIneffectiveCleanups,
|
||||
recommendation,
|
||||
} satisfies MemoryCleanupIneffectiveEvent;
|
||||
debugLogger.warn(
|
||||
`Cleanup "${recommendation.action}" has been ineffective ` +
|
||||
`${this.consecutiveIneffectiveCleanups} times consecutively`,
|
||||
);
|
||||
this.emitSafely('memory-cleanup-ineffective', event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.consecutiveIneffectiveCleanups = 0;
|
||||
if (recommendation.action === 'aggressive') {
|
||||
this.consecutiveIneffectiveAggressiveCleanups = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private recordCleanupFailure(
|
||||
recommendation: CleanupRecommendation,
|
||||
err: unknown,
|
||||
): void {
|
||||
const error = getErrorMessage(err);
|
||||
let rss = 0;
|
||||
try {
|
||||
rss = process.memoryUsage().rss;
|
||||
} catch (rssErr) {
|
||||
debugLogger.error(
|
||||
`Failed to read RSS after cleanup failure: ${getErrorMessage(rssErr)}`,
|
||||
);
|
||||
}
|
||||
|
||||
this.consecutiveCleanupFailures++;
|
||||
debugLogger.error(
|
||||
`Cleanup "${recommendation.action}" failed: ${error}; ` +
|
||||
`consecutive failures: ${this.consecutiveCleanupFailures}`,
|
||||
);
|
||||
|
||||
if (shouldEmitRepeatedDiagnostic(this.consecutiveCleanupFailures)) {
|
||||
this.emitSafely('memory-cleanup-failed', {
|
||||
rss,
|
||||
consecutiveFailures: this.consecutiveCleanupFailures,
|
||||
recommendation,
|
||||
error,
|
||||
} satisfies MemoryCleanupFailureEvent);
|
||||
}
|
||||
}
|
||||
|
||||
private emitSafely(eventName: string, event: unknown): void {
|
||||
try {
|
||||
this.emit(eventName, event);
|
||||
} catch (err) {
|
||||
debugLogger.error(`${eventName} handler threw: ${getErrorMessage(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async runCleanupSteps(
|
||||
steps: CleanupStep[],
|
||||
cleanupGeneration: number,
|
||||
): Promise<void> {
|
||||
for (const step of steps) {
|
||||
if (cleanupGeneration !== this.cleanupGeneration) {
|
||||
return;
|
||||
}
|
||||
this.executeStep(step);
|
||||
// Keep a promise boundary between steps so escalated cleanups can queue
|
||||
// behind the active cleanup instead of interleaving in the same stack.
|
||||
await Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
private executeStep(step: CleanupStep): void {
|
||||
switch (step) {
|
||||
case 'clear_file_cache': {
|
||||
this.coreConfig.getFileReadCache().clear();
|
||||
debugLogger.debug('FileReadCache cleared');
|
||||
break;
|
||||
}
|
||||
case 'evict_cold_cache': {
|
||||
const evicted = this.coreConfig
|
||||
.getFileReadCache()
|
||||
.evictNotAccessedSince(30);
|
||||
debugLogger.debug(`FileReadCache cold eviction: ${evicted} entries`);
|
||||
break;
|
||||
}
|
||||
case 'evict_stale_cache': {
|
||||
const evicted = this.coreConfig
|
||||
.getFileReadCache()
|
||||
.evictNotAccessedSince(60);
|
||||
debugLogger.debug(`FileReadCache stale eviction: ${evicted} entries`);
|
||||
break;
|
||||
}
|
||||
case 'trigger_gc': {
|
||||
if (typeof global.gc === 'function') {
|
||||
const before = process.memoryUsage().rss;
|
||||
global.gc();
|
||||
const after = process.memoryUsage().rss;
|
||||
debugLogger.debug(`global.gc() freed ${before - after} bytes`);
|
||||
} else {
|
||||
debugLogger.warn(
|
||||
'trigger_gc requested but global.gc is not available; ' +
|
||||
'start Node.js with --expose-gc',
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return assertNever(step);
|
||||
}
|
||||
}
|
||||
|
||||
// Memory metrics
|
||||
|
||||
private computeEffectiveMemoryLimit(): number {
|
||||
const hostTotal = os.totalmem();
|
||||
const cgroupV2Limit = this.readCgroupMemoryLimit(
|
||||
'/sys/fs/cgroup/memory.max',
|
||||
hostTotal,
|
||||
);
|
||||
if (cgroupV2Limit !== undefined) {
|
||||
debugLogger.info(
|
||||
`Using cgroup v2 memory limit: ${formatMiB(cgroupV2Limit)} MiB`,
|
||||
);
|
||||
return cgroupV2Limit;
|
||||
}
|
||||
|
||||
const cgroupV1Limit = this.readCgroupMemoryLimit(
|
||||
'/sys/fs/cgroup/memory/memory.limit_in_bytes',
|
||||
hostTotal,
|
||||
);
|
||||
if (cgroupV1Limit !== undefined) {
|
||||
debugLogger.info(
|
||||
`Using cgroup v1 memory limit: ${formatMiB(cgroupV1Limit)} MiB`,
|
||||
);
|
||||
return cgroupV1Limit;
|
||||
}
|
||||
|
||||
debugLogger.info(`Using host memory limit: ${formatMiB(hostTotal)} MiB`);
|
||||
return hostTotal;
|
||||
}
|
||||
|
||||
private readCgroupMemoryLimit(
|
||||
filePath: string,
|
||||
hostTotal: number,
|
||||
): number | undefined {
|
||||
try {
|
||||
const raw = readFileSync(filePath, 'utf-8').trim();
|
||||
if (raw === 'max') return undefined;
|
||||
|
||||
if (!/^-?\d+$/.test(raw)) {
|
||||
debugLogger.warn(
|
||||
`Ignoring non-numeric cgroup memory limit from ${filePath}: ${raw}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const limit = Number(raw);
|
||||
if (!Number.isFinite(limit) || limit <= 0) {
|
||||
debugLogger.warn(
|
||||
`Ignoring out-of-range cgroup memory limit from ${filePath}: ${raw}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (limit < MIN_CGROUP_MEMORY_LIMIT) {
|
||||
debugLogger.warn(
|
||||
`Ignoring unrealistically small cgroup memory limit from ` +
|
||||
`${filePath}: ${raw}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// cgroup v1 represents "unlimited" with huge sentinel values.
|
||||
if (!Number.isSafeInteger(limit)) {
|
||||
debugLogger.debug(
|
||||
`Ignoring unlimited cgroup memory limit from ${filePath}: ${raw}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (hostTotal > 0 && limit > hostTotal) {
|
||||
debugLogger.debug(
|
||||
`Ignoring cgroup memory limit above host total from ${filePath}: ` +
|
||||
`${raw}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return limit;
|
||||
} catch (err) {
|
||||
debugLogger.debug(
|
||||
`Failed to read cgroup memory limit from ${filePath}: ` +
|
||||
getErrorMessage(err),
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupActionRank(action: CleanupRecommendation['action']): number {
|
||||
switch (action) {
|
||||
case 'aggressive':
|
||||
return 3;
|
||||
case 'moderate':
|
||||
return 2;
|
||||
case 'light':
|
||||
return 1;
|
||||
case 'none':
|
||||
return 0;
|
||||
default:
|
||||
return assertNever(action);
|
||||
}
|
||||
}
|
||||
|
||||
function shouldEmitRepeatedDiagnostic(count: number): boolean {
|
||||
// Emit once at the threshold, once soon after, then every 20 repeats so
|
||||
// sustained pressure remains visible without flooding event listeners.
|
||||
return count === 3 || count === 10 || (count > 10 && count % 20 === 0);
|
||||
}
|
||||
|
||||
function formatMiB(bytes: number): string {
|
||||
return (bytes / 1024 / 1024).toFixed(0);
|
||||
}
|
||||
|
||||
function assertNever(value: never): never {
|
||||
throw new Error(`Unhandled memory pressure monitor value: ${String(value)}`);
|
||||
}
|
||||
@ -49,7 +49,7 @@ export async function generateSessionRecap(
|
||||
const geminiClient = config.getGeminiClient();
|
||||
if (!geminiClient) return null;
|
||||
|
||||
const fullHistory = geminiClient.getHistoryShallow();
|
||||
const fullHistory = geminiClient.getChat().getHistory();
|
||||
if (fullHistory.length < 2) return null;
|
||||
|
||||
const dialog = filterToDialog(fullHistory);
|
||||
|
||||
@ -31,7 +31,6 @@ function makeConfig(opts: MockOptions): {
|
||||
getFastModel: vi.fn(() => opts.fastModel ?? undefined),
|
||||
getModel: vi.fn(() => 'qwen-plus'),
|
||||
getGeminiClient: vi.fn(() => ({
|
||||
getHistoryShallow: () => opts.history ?? [],
|
||||
getChat: () => ({
|
||||
getHistory: () => opts.history ?? [],
|
||||
}),
|
||||
@ -203,10 +202,7 @@ describe('tryGenerateSessionTitle', () => {
|
||||
getFastModel: vi.fn(() => 'qwen-turbo'),
|
||||
getModel: vi.fn(() => 'qwen-plus'),
|
||||
getGeminiClient: vi.fn(() => ({
|
||||
getHistoryShallow: () => history,
|
||||
getChat: () => ({
|
||||
getHistory: () => history,
|
||||
}),
|
||||
getChat: () => ({ getHistory: () => history }),
|
||||
})),
|
||||
getBaseLlmClient: vi.fn(() => ({ generateJson })),
|
||||
} as unknown as Config;
|
||||
@ -244,10 +240,7 @@ describe('tryGenerateSessionTitle', () => {
|
||||
getFastModel: vi.fn(() => 'qwen-turbo'),
|
||||
getModel: vi.fn(() => 'qwen-plus'),
|
||||
getGeminiClient: vi.fn(() => ({
|
||||
getHistoryShallow: () => history,
|
||||
getChat: () => ({
|
||||
getHistory: () => history,
|
||||
}),
|
||||
getChat: () => ({ getHistory: () => history }),
|
||||
})),
|
||||
getBaseLlmClient: vi.fn(() => ({ generateJson })),
|
||||
} as unknown as Config;
|
||||
|
||||
@ -113,7 +113,7 @@ export async function tryGenerateSessionTitle(
|
||||
const geminiClient = config.getGeminiClient();
|
||||
if (!geminiClient) return { ok: false, reason: 'no_client' };
|
||||
|
||||
const fullHistory = geminiClient.getHistoryShallow();
|
||||
const fullHistory = geminiClient.getChat().getHistory();
|
||||
if (fullHistory.length < 2) return { ok: false, reason: 'empty_history' };
|
||||
|
||||
const dialog = filterToDialog(fullHistory);
|
||||
|
||||
@ -21,6 +21,7 @@ import {
|
||||
type AnsiOutput,
|
||||
} from '../utils/terminalSerializer.js';
|
||||
import { normalizePathEnvForWindows } from '../utils/windowsPath.js';
|
||||
import { getShellContextEnvVars } from '../utils/shellContextEnv.js';
|
||||
import { createDebugLogger } from '../utils/debugLogger.js';
|
||||
const { Terminal } = pkg;
|
||||
|
||||
@ -550,6 +551,7 @@ export class ShellExecutionService {
|
||||
QWEN_CODE: '1',
|
||||
TERM: 'xterm-256color',
|
||||
PAGER: 'cat',
|
||||
...getShellContextEnvVars(),
|
||||
},
|
||||
});
|
||||
|
||||
@ -1152,6 +1154,7 @@ export class ShellExecutionService {
|
||||
TERM: 'xterm-256color',
|
||||
PAGER: shellExecutionConfig.pager ?? 'cat',
|
||||
GIT_PAGER: shellExecutionConfig.pager ?? 'cat',
|
||||
...getShellContextEnvVars(),
|
||||
},
|
||||
handleFlowControl: true,
|
||||
});
|
||||
|
||||
@ -102,7 +102,11 @@ export async function readWorktreeSession(
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** Writes the worktree session sidecar via `atomicWriteJSON`. */
|
||||
/**
|
||||
* Atomically writes the sidecar. Uses `atomicWriteJSON` (write-to-temp +
|
||||
* rename) so a crash mid-write can never leave a half-written file that
|
||||
* subsequent reads would reject as malformed.
|
||||
*/
|
||||
export async function writeWorktreeSession(
|
||||
filePath: string,
|
||||
session: WorktreeSession,
|
||||
|
||||
@ -53,6 +53,7 @@ import {
|
||||
isShellCommandReadOnlyAST,
|
||||
} from '../utils/shellAstParser.js';
|
||||
import { getCurrentAgentId } from '../agents/runtime/agent-context.js';
|
||||
import { getShellContextEnvVars } from '../utils/shellContextEnv.js';
|
||||
|
||||
const debugLogger = createDebugLogger('MONITOR');
|
||||
|
||||
@ -366,6 +367,7 @@ class MonitorToolInvocation extends BaseToolInvocation<
|
||||
QWEN_CODE: '1',
|
||||
TERM: 'dumb', // no color codes for streaming
|
||||
PAGER: 'cat',
|
||||
...getShellContextEnvVars(),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@ -269,160 +269,4 @@ describe('atomicWriteFile', () => {
|
||||
path.normalize('../otherDir/target.txt'),
|
||||
);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'should use atomic rename when ownership matches (inode changes)',
|
||||
async () => {
|
||||
const filePath = path.join(tmpDir, 'mine.txt');
|
||||
await fs.writeFile(filePath, 'original');
|
||||
const inoBefore = (await fs.stat(filePath)).ino;
|
||||
|
||||
await atomicWriteFile(filePath, 'updated');
|
||||
|
||||
const statAfter = await fs.stat(filePath);
|
||||
// Atomic rename produces a new inode.
|
||||
expect(statAfter.ino).not.toBe(inoBefore);
|
||||
expect(await fs.readFile(filePath, 'utf-8')).toBe('updated');
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(
|
||||
process.platform === 'win32' || typeof process.geteuid !== 'function',
|
||||
)(
|
||||
'should fall back to in-place write when atomic rename would change ownership',
|
||||
async () => {
|
||||
// Simulate a file owned by a different user by replacing process.geteuid
|
||||
// so it reports a uid that doesn't match the file's real uid. The code
|
||||
// should detect rename would strip ownership and fall back to in-place
|
||||
// writeFile, which preserves the inode — our signal that fallback ran.
|
||||
const filePath = path.join(tmpDir, 'shared.txt');
|
||||
await fs.writeFile(filePath, 'original');
|
||||
await fs.chmod(filePath, 0o664);
|
||||
|
||||
const realStat = await fs.stat(filePath);
|
||||
const inoBefore = realStat.ino;
|
||||
const realGeteuid = process.geteuid!;
|
||||
process.geteuid = () => realStat.uid + 1;
|
||||
|
||||
try {
|
||||
await atomicWriteFile(filePath, 'updated');
|
||||
} finally {
|
||||
process.geteuid = realGeteuid;
|
||||
}
|
||||
|
||||
expect(await fs.readFile(filePath, 'utf-8')).toBe('updated');
|
||||
|
||||
const statAfter = await fs.stat(filePath);
|
||||
// In-place write preserves the inode — proves rename was skipped.
|
||||
expect(statAfter.ino).toBe(inoBefore);
|
||||
// Permissions preserved.
|
||||
expect(statAfter.mode & 0o777).toBe(0o664);
|
||||
// No leftover temp file.
|
||||
expect(await fs.readdir(tmpDir)).toEqual(['shared.txt']);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(
|
||||
process.platform === 'win32' || typeof process.geteuid !== 'function',
|
||||
)(
|
||||
'should skip in-place fallback for non-regular files and use atomic replace',
|
||||
async () => {
|
||||
// FIFO + ownership mismatch must NOT take the in-place fallback —
|
||||
// open(O_WRONLY|O_TRUNC) against a FIFO would block forever
|
||||
// waiting for a reader. The atomic rename path instead replaces
|
||||
// the FIFO with a regular file, which is the only sane behavior
|
||||
// for "write to this path" semantics on a special file.
|
||||
const { execSync } = await import('node:child_process');
|
||||
const fifoPath = path.join(tmpDir, 'pipe.fifo');
|
||||
execSync(`mkfifo "${fifoPath}"`);
|
||||
|
||||
const realStat = await fs.stat(fifoPath);
|
||||
expect(realStat.isFIFO()).toBe(true);
|
||||
|
||||
const realGeteuid = process.geteuid!;
|
||||
process.geteuid = () => realStat.uid + 1;
|
||||
|
||||
try {
|
||||
// If the in-place fallback were taken, this would hang
|
||||
// indefinitely. Vitest's default timeout will catch that.
|
||||
await atomicWriteFile(fifoPath, 'content');
|
||||
} finally {
|
||||
process.geteuid = realGeteuid;
|
||||
}
|
||||
|
||||
// Atomic path replaced the FIFO with a regular file.
|
||||
const statAfter = await fs.stat(fifoPath);
|
||||
expect(statAfter.isFile()).toBe(true);
|
||||
expect(await fs.readFile(fifoPath, 'utf-8')).toBe('content');
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(
|
||||
process.platform === 'win32' || typeof process.geteuid !== 'function',
|
||||
)(
|
||||
'should write via in-place fallback through a resolved symlink when ownership differs',
|
||||
async () => {
|
||||
// atomicWriteFile resolves the symlink via resolveSymlinkChain
|
||||
// before stat, so the in-place write targets the real file.
|
||||
// Verifies the symlink itself is preserved.
|
||||
const realFile = path.join(tmpDir, 'real.txt');
|
||||
const symlinkAt = path.join(tmpDir, 'attacker-symlink.txt');
|
||||
await fs.writeFile(realFile, 'real-content');
|
||||
await fs.symlink(realFile, symlinkAt);
|
||||
|
||||
const realGeteuid = process.geteuid!;
|
||||
const realStat = await fs.stat(realFile);
|
||||
const inoBefore = realStat.ino;
|
||||
process.geteuid = () => realStat.uid + 1;
|
||||
|
||||
try {
|
||||
await atomicWriteFile(symlinkAt, 'updated');
|
||||
} finally {
|
||||
process.geteuid = realGeteuid;
|
||||
}
|
||||
|
||||
// The real file is updated; the symlink itself is preserved.
|
||||
expect(await fs.readFile(realFile, 'utf-8')).toBe('updated');
|
||||
expect((await fs.stat(realFile)).ino).toBe(inoBefore);
|
||||
expect((await fs.lstat(symlinkAt)).isSymbolicLink()).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(
|
||||
process.platform === 'win32' ||
|
||||
typeof process.geteuid !== 'function' ||
|
||||
// chmod 0o000 against the file's real owner still succeeds via
|
||||
// POSIX rename in CI/sandbox setups where the user is effectively
|
||||
// root; only assert real EACCES when we own and can be denied.
|
||||
process.geteuid() === 0,
|
||||
)(
|
||||
'should surface EACCES when in-place fallback hits an unwritable file',
|
||||
async () => {
|
||||
// Atomic rename used to silently replace files the calling user
|
||||
// has no write permission on (rename only needs parent-dir write).
|
||||
// The in-place fallback respects the file's mode and surfaces
|
||||
// EACCES — the correct behavior for "you don't own this, you
|
||||
// shouldn't be replacing it" scenarios.
|
||||
const filePath = path.join(tmpDir, 'readonly.txt');
|
||||
await fs.writeFile(filePath, 'original');
|
||||
await fs.chmod(filePath, 0o444);
|
||||
|
||||
const realStat = await fs.stat(filePath);
|
||||
const realGeteuid = process.geteuid!;
|
||||
process.geteuid = () => realStat.uid + 1;
|
||||
|
||||
try {
|
||||
await expect(atomicWriteFile(filePath, 'updated')).rejects.toThrow(
|
||||
/EACCES/,
|
||||
);
|
||||
} finally {
|
||||
process.geteuid = realGeteuid;
|
||||
// Restore mode so afterEach's rm can clean up.
|
||||
await fs.chmod(filePath, 0o644);
|
||||
}
|
||||
|
||||
// Original content untouched.
|
||||
expect(await fs.readFile(filePath, 'utf-8')).toBe('original');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@ -5,7 +5,6 @@
|
||||
*/
|
||||
|
||||
import * as crypto from 'node:crypto';
|
||||
import type { Stats } from 'node:fs';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
import { isNodeError } from './errors.js';
|
||||
@ -95,12 +94,19 @@ async function resolveSymlinkChain(filePath: string): Promise<string> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically write content to a file (write-to-temp + rename).
|
||||
* Atomically write arbitrary content (string or Buffer) to a file.
|
||||
*
|
||||
* Falls back to in-place write when the existing file's uid differs
|
||||
* from the process's euid — POSIX rename would reset ownership.
|
||||
* Also falls back on EXDEV (cross-device). Both fallbacks lose crash
|
||||
* atomicity but preserve the existing inode's uid.
|
||||
* 1. Resolve symlinks (including broken ones) so the temp file lives
|
||||
* next to the real target.
|
||||
* 2. Write to a temporary file with fsync (`flush: true` by default).
|
||||
* 3. Preserve the original file's permissions (or apply `options.mode`).
|
||||
* 4. Atomic rename (POSIX) with retry (Windows).
|
||||
* 5. On EXDEV (cross-device rename), fall back to direct write.
|
||||
* **Note:** the EXDEV fallback is non-atomic — a crash mid-write
|
||||
* can leave a partially-written file. EXDEV only occurs when the
|
||||
* resolved target path is on a different filesystem than its parent
|
||||
* directory, which is rare in practice.
|
||||
* 6. Always clean up the temp file on failure.
|
||||
*
|
||||
* The parent directory of `filePath` must already exist.
|
||||
*/
|
||||
@ -116,20 +122,19 @@ export async function atomicWriteFile(
|
||||
|
||||
const targetPath = await resolveSymlinkChain(filePath);
|
||||
|
||||
// Stat the target to preserve existing permissions and detect
|
||||
// ownership-changing renames (see the ownership-preservation note in
|
||||
// the function doc).
|
||||
let existingStat: Stats | undefined;
|
||||
const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
||||
|
||||
// Stat the target to preserve existing permissions (mask out file-type bits).
|
||||
let existingMode: number | undefined;
|
||||
try {
|
||||
existingStat = await fs.stat(targetPath);
|
||||
const stat = await fs.stat(targetPath);
|
||||
existingMode = stat.mode & 0o7777;
|
||||
} catch (err) {
|
||||
if (!isNodeError(err) || err.code !== 'ENOENT') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const existingMode =
|
||||
existingStat !== undefined ? existingStat.mode & 0o7777 : undefined;
|
||||
const desiredMode = existingMode ?? options?.mode;
|
||||
|
||||
const writeOptions: {
|
||||
@ -151,33 +156,6 @@ export async function atomicWriteFile(
|
||||
}
|
||||
};
|
||||
|
||||
// Detect when atomic rename would silently change ownership. POSIX
|
||||
// rename creates a new inode owned by the process's euid:egid; if the
|
||||
// existing file has a different uid, fall back to in-place write which
|
||||
// preserves the inode and therefore uid. Only uid is compared — gid
|
||||
// is intentionally skipped because macOS inherits the parent
|
||||
// directory's GID for new files, making egid !== file.gid a
|
||||
// false positive on the most common dev platform.
|
||||
const ownershipWouldChange = (): boolean => {
|
||||
if (existingStat === undefined) return false;
|
||||
if (process.platform === 'win32') return false;
|
||||
const euid = process.geteuid?.();
|
||||
if (euid === undefined) return false;
|
||||
return existingStat.uid !== euid;
|
||||
};
|
||||
|
||||
if (
|
||||
existingStat !== undefined &&
|
||||
existingStat.isFile() &&
|
||||
ownershipWouldChange()
|
||||
) {
|
||||
await fs.writeFile(targetPath, data, writeOptions);
|
||||
await tryChmod(targetPath);
|
||||
return;
|
||||
}
|
||||
|
||||
const tmpPath = `${targetPath}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
||||
|
||||
try {
|
||||
await fs.writeFile(tmpPath, data, writeOptions);
|
||||
await tryChmod(tmpPath);
|
||||
@ -201,7 +179,17 @@ export async function atomicWriteFile(
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomically write a JSON value to a file. Delegates to {@link atomicWriteFile}. */
|
||||
/**
|
||||
* Atomically write a JSON value to a file.
|
||||
*
|
||||
* Delegates to {@link atomicWriteFile} for the actual atomic
|
||||
* write-to-temp + rename flow.
|
||||
*
|
||||
* Note: if `filePath` is a symlink, the write resolves the chain
|
||||
* and updates the real target file — the symlink itself is preserved.
|
||||
*
|
||||
* The parent directory of `filePath` must already exist.
|
||||
*/
|
||||
export async function atomicWriteJSON(
|
||||
filePath: string,
|
||||
data: unknown,
|
||||
|
||||
@ -116,45 +116,4 @@ describe('contextLengthError', () => {
|
||||
|
||||
expect(info.isExceeded).toBe(false);
|
||||
});
|
||||
|
||||
it('skips accessor properties that throw while collecting error text', () => {
|
||||
const error = new Error('Connection error.');
|
||||
|
||||
Object.defineProperty(error, 'name', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
throw new TypeError('Value of "this" must be of DOMException');
|
||||
},
|
||||
});
|
||||
Object.defineProperty(error, 'details', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
throw new TypeError('Value of "this" must be of DOMException');
|
||||
},
|
||||
});
|
||||
|
||||
const info = getContextLengthExceededInfo(error);
|
||||
|
||||
expect(info.isExceeded).toBe(false);
|
||||
expect(info.message).toContain('Connection error.');
|
||||
});
|
||||
|
||||
it('skips throwing accessors on plain objects', () => {
|
||||
const errorLike: Record<string, unknown> = {};
|
||||
Object.defineProperty(errorLike, 'detail', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
throw new TypeError('accessor refused');
|
||||
},
|
||||
});
|
||||
Object.defineProperty(errorLike, 'message', {
|
||||
enumerable: true,
|
||||
value: 'context_length_exceeded: too many tokens',
|
||||
});
|
||||
|
||||
const info = getContextLengthExceededInfo(errorLike);
|
||||
|
||||
expect(info.isExceeded).toBe(true);
|
||||
expect(info.message).toContain('context_length_exceeded');
|
||||
});
|
||||
});
|
||||
|
||||
@ -103,32 +103,6 @@ function tryParseEmbeddedJson(text: string): unknown | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
function safeReadProperty(value: object, key: string): unknown {
|
||||
try {
|
||||
return (value as Record<string, unknown>)[key];
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function enumerableValues(value: object): unknown[] {
|
||||
try {
|
||||
return Object.values(value);
|
||||
} catch {
|
||||
try {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(value);
|
||||
return Object.values(descriptors)
|
||||
.filter(
|
||||
(descriptor): descriptor is PropertyDescriptor & { value: unknown } =>
|
||||
'value' in descriptor && descriptor.enumerable === true,
|
||||
)
|
||||
.map((descriptor) => descriptor.value);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function collectStrings(
|
||||
value: unknown,
|
||||
seen: Set<object>,
|
||||
@ -161,21 +135,11 @@ function collectStrings(
|
||||
|
||||
const strings: string[] = [];
|
||||
if (value instanceof Error) {
|
||||
const name = safeReadProperty(value, 'name');
|
||||
const message = safeReadProperty(value, 'message');
|
||||
|
||||
if (typeof name === 'string') {
|
||||
strings.push(name);
|
||||
}
|
||||
if (typeof message === 'string') {
|
||||
strings.push(message);
|
||||
}
|
||||
strings.push(
|
||||
...collectStrings(safeReadProperty(value, 'cause'), seen, depth + 1),
|
||||
);
|
||||
strings.push(value.name, value.message);
|
||||
strings.push(...collectStrings(value.cause, seen, depth + 1));
|
||||
}
|
||||
|
||||
for (const nested of enumerableValues(value)) {
|
||||
for (const [, nested] of Object.entries(value)) {
|
||||
strings.push(...collectStrings(nested, seen, depth + 1));
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user