Compare commits

..

4 Commits

Author SHA1 Message Date
qqqys
12f874d04c fix(hooks): restore main config behavior 2026-06-01 11:29:40 +08:00
qqqys
3fe3b2aed2 fix(hooks): remove stale branch regressions 2026-06-01 11:19:59 +08:00
qqqys
0769aebde3 fix(hooks): align InstructionsLoaded branch with main config 2026-06-01 11:12:32 +08:00
qqqys
c954b47837 feat(hooks): add InstructionsLoaded event 2026-06-01 10:57:23 +08:00
66 changed files with 1445 additions and 3113 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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());

View File

@ -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,

View File

@ -12,6 +12,7 @@ import {
FileDiscoveryService,
getAllGeminiMdFilenames,
loadServerHierarchicalMemory,
type LoadServerHierarchicalMemoryOptions,
type LoadServerHierarchicalMemoryResponse,
setGeminiMdFilename as setServerGeminiMdFilename,
resolveTelemetrySettings,
@ -1130,6 +1131,7 @@ export async function loadHierarchicalGeminiMemory(
folderTrust: boolean,
memoryImportFormat: 'flat' | 'tree' = 'tree',
contextRuleExcludes: string[] = [],
options: LoadServerHierarchicalMemoryOptions = {},
): Promise<LoadServerHierarchicalMemoryResponse> {
// FIX: Use real, canonical paths for a reliable comparison to handle symlinks.
const realCwd = fs.realpathSync(path.resolve(currentWorkingDirectory));
@ -1149,6 +1151,7 @@ export async function loadHierarchicalGeminiMemory(
folderTrust,
memoryImportFormat,
contextRuleExcludes,
options,
);
}

View File

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

View File

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

View File

@ -1307,6 +1307,22 @@ export const AppContainer = (props: AppContainerProps) => {
config.isTrustedFolder(),
settings.merged.context?.importFormat || 'tree', // Use setting or default to 'tree'
config.getContextRuleExcludes(),
{
onInstructionsLoaded: async (notification) => {
await config
.getHookSystem()
?.fireInstructionsLoadedEvent(
notification.filePath,
notification.memoryType,
notification.loadReason,
{
globs: notification.globs,
triggerFilePath: notification.triggerFilePath,
parentFilePath: notification.parentFilePath,
},
);
},
},
);
config.setUserMemory(memoryContent);
@ -2108,9 +2124,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,
})
@ -2463,7 +2480,7 @@ export const AppContainer = (props: AppContainerProps) => {
apiTruncateIndex = computeApiTruncationIndex(
historyManager.history,
userItem.id,
geminiClient.getHistoryShallow(),
geminiClient.getHistory(),
);
if (apiTruncateIndex < 0) {
historyManager.addItem(

View File

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

View File

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

View File

@ -241,6 +241,22 @@ export const directoryCommand: SlashCommand = {
context.services.settings.merged.context?.importFormat ||
'tree', // Use setting or default to 'tree'
config.getContextRuleExcludes(),
{
onInstructionsLoaded: async (notification) => {
await config
.getHookSystem()
?.fireInstructionsLoadedEvent(
notification.filePath,
notification.memoryType,
notification.loadReason,
{
globs: notification.globs,
triggerFilePath: notification.triggerFilePath,
parentFilePath: notification.parentFilePath,
},
);
},
},
);
config.setUserMemory(memoryContent);
config.setGeminiMdFileCount(fileCount);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,16 +5,14 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
HookEventName,
HooksConfigSource,
hookEventSupportsMatcher,
} from '@qwen-code/qwen-code-core';
import { HookEventName, HooksConfigSource } from '@qwen-code/qwen-code-core';
// Mock i18n module
vi.mock('../../../i18n/index.js', () => ({
t: vi.fn((key: string) => key),
}));
// Import after mocking
import {
getHookExitCodes,
getHookShortDescription,
@ -22,7 +20,6 @@ import {
getTranslatedSourceDisplayMap,
createEmptyHookEventInfo,
DISPLAY_HOOK_EVENTS,
supportsMatchers,
} from './constants.js';
describe('hooks constants', () => {
@ -86,22 +83,9 @@ describe('hooks constants', () => {
expect(exitCodes).toHaveLength(3);
});
it('should return exit codes for PostCompact event', () => {
const exitCodes = getHookExitCodes(HookEventName.PostCompact);
it('should return exit codes for InstructionsLoaded event', () => {
const exitCodes = getHookExitCodes(HookEventName.InstructionsLoaded);
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', () => {
@ -131,15 +115,9 @@ 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 description for InstructionsLoaded', () => {
const desc = getHookShortDescription(HookEventName.InstructionsLoaded);
expect(desc).toBe('When instruction files are loaded');
});
it('should return empty string for unknown event', () => {
@ -165,17 +143,11 @@ 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 description for InstructionsLoaded', () => {
const desc = getHookDescription(HookEventName.InstructionsLoaded);
expect(desc).toContain('file_path');
expect(desc).toContain('memory_type');
expect(desc).toContain('load_reason');
});
it('should return empty string for unknown event', () => {
@ -197,6 +169,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);
@ -223,44 +196,11 @@ describe('hooks constants', () => {
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PermissionDenied);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.TodoCreated);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.TodoCompleted);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.InstructionsLoaded);
});
it('should have 17 events', () => {
expect(DISPLAY_HOOK_EVENTS).toHaveLength(17);
});
});
describe('supportsMatchers', () => {
it('returns true for events with meaningful matchers', () => {
expect(supportsMatchers(HookEventName.PreToolUse)).toBe(true);
expect(supportsMatchers(HookEventName.PostToolUse)).toBe(true);
expect(supportsMatchers(HookEventName.PostToolUseFailure)).toBe(true);
expect(supportsMatchers(HookEventName.PermissionRequest)).toBe(true);
expect(supportsMatchers(HookEventName.Notification)).toBe(true);
expect(supportsMatchers(HookEventName.SessionStart)).toBe(true);
expect(supportsMatchers(HookEventName.SessionEnd)).toBe(true);
expect(supportsMatchers(HookEventName.SubagentStart)).toBe(true);
expect(supportsMatchers(HookEventName.SubagentStop)).toBe(true);
expect(supportsMatchers(HookEventName.PreCompact)).toBe(true);
expect(supportsMatchers(HookEventName.PostCompact)).toBe(true);
expect(supportsMatchers(HookEventName.StopFailure)).toBe(true);
});
it('returns false for events without matchers', () => {
expect(supportsMatchers(HookEventName.Stop)).toBe(false);
expect(supportsMatchers(HookEventName.UserPromptSubmit)).toBe(false);
expect(supportsMatchers(HookEventName.TodoCreated)).toBe(false);
expect(supportsMatchers(HookEventName.TodoCompleted)).toBe(false);
});
it('returns false for unknown events', () => {
expect(supportsMatchers('unknown_event' as HookEventName)).toBe(false);
});
it('covers every HookEventName value and matches core dispatch', () => {
for (const event of Object.values(HookEventName)) {
expect(supportsMatchers(event)).toBe(hookEventSupportsMatcher(event));
}
it('should have 18 events', () => {
expect(DISPLAY_HOOK_EVENTS).toHaveLength(18);
});
});
@ -274,7 +214,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 +226,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 +236,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 +246,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 +258,17 @@ describe('hooks constants', () => {
);
expect(info.description).toContain('previous_status');
expect(info.exitCodes).toHaveLength(3);
expect(info.matcherGroups).toEqual([]);
expect(info.configs).toEqual([]);
});
it('should create empty info for InstructionsLoaded', () => {
const info = createEmptyHookEventInfo(HookEventName.InstructionsLoaded);
expect(info.event).toBe(HookEventName.InstructionsLoaded);
expect(info.shortDescription).toBe('When instruction files are loaded');
expect(info.description).toContain('file_path');
expect(info.exitCodes).toHaveLength(2);
expect(info.configs).toEqual([]);
});
});
});

View File

@ -4,11 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import {
HooksConfigSource,
HookEventName,
hookEventSupportsMatcher,
} from '@qwen-code/qwen-code-core';
import { HooksConfigSource, HookEventName } from '@qwen-code/qwen-code-core';
import type { HookExitCode, HookEventDisplayInfo } from './types.js';
import { t } from '../../../i18n/index.js';
@ -47,6 +43,10 @@ export function getHookExitCodes(eventName: string): HookExitCode[] {
{ code: 0, description: t('stdout/stderr not shown') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.InstructionsLoaded]: [
{ code: 0, description: t('stdout/stderr not shown') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.UserPromptSubmit]: [
{ code: 0, description: t('stdout shown to Qwen') },
{
@ -94,20 +94,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') },
@ -145,6 +131,7 @@ export function getHookShortDescription(eventName: string): string {
[HookEventName.PostToolUse]: t('After tool execution'),
[HookEventName.PostToolUseFailure]: t('After tool execution fails'),
[HookEventName.Notification]: t('When notifications are sent'),
[HookEventName.InstructionsLoaded]: t('When instruction files are loaded'),
[HookEventName.UserPromptSubmit]: t('When the user submits a prompt'),
[HookEventName.SessionStart]: t('When a new session is started'),
[HookEventName.Stop]: t('Right before Qwen Code concludes its response'),
@ -155,10 +142,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',
@ -190,6 +173,9 @@ export function getHookDescription(eventName: string): string {
[HookEventName.Notification]: t(
'Input to command is JSON with notification message and type.',
),
[HookEventName.InstructionsLoaded]: t(
'Input to command is JSON with file_path, memory_type, load_reason, and optional globs, trigger_file_path, and parent_file_path.',
),
[HookEventName.UserPromptSubmit]: t(
'Input to command is JSON with original user prompt text.',
),
@ -208,12 +194,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 +226,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 +247,6 @@ export function createEmptyHookEventInfo(
shortDescription: getHookShortDescription(eventName),
description: getHookDescription(eventName),
exitCodes: getHookExitCodes(eventName),
matcherGroups: [],
configs: [],
};
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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,

View File

@ -49,6 +49,7 @@ import { ToolNames } from '../tools/tool-names.js';
import { fireNotificationHook } from '../core/toolHookTriggers.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import { loadServerHierarchicalMemory } from '../utils/memoryDiscovery.js';
import type { LoadServerHierarchicalMemoryOptions } from '../utils/memoryDiscovery.js';
import { readAutoMemoryIndex } from '../memory/store.js';
import { ExtensionManager } from '../extension/extensionManager.js';
import { SkillManager } from '../skills/skill-manager.js';
@ -1440,7 +1441,7 @@ describe('Server Config (config.ts)', () => {
await config.refreshHierarchicalMemory();
const lastCall = vi.mocked(loadServerHierarchicalMemory).mock.calls.at(-1);
expect(lastCall?.at(-1)).toEqual({ explicitOnly: true });
expect(lastCall?.at(-1)).toMatchObject({ explicitOnly: true });
expect(lastCall?.[1]).toEqual([]);
expect(readAutoMemoryIndex).not.toHaveBeenCalled();
expect(config.getUserMemory()).toContain('Project rules');
@ -1468,7 +1469,51 @@ describe('Server Config (config.ts)', () => {
const lastCall = vi.mocked(loadServerHierarchicalMemory).mock.calls.at(-1);
expect(lastCall?.[1]).toEqual([explicitDir]);
expect(lastCall?.at(-1)).toEqual({ explicitOnly: true });
expect(lastCall?.at(-1)).toMatchObject({ explicitOnly: true });
});
it('refreshHierarchicalMemory should fire InstructionsLoaded hooks from memory notifications', async () => {
const config = new Config(baseParams);
const fireInstructionsLoadedEvent = vi.fn().mockResolvedValue(undefined);
config['hookSystem'] = {
fireInstructionsLoadedEvent,
} as unknown as HookSystem;
vi.mocked(loadServerHierarchicalMemory).mockResolvedValue({
memoryContent: '--- Context from: QWEN.md ---\nProject rules',
fileCount: 1,
ruleCount: 0,
conditionalRules: [],
projectRoot: '/tmp',
});
await config.refreshHierarchicalMemory();
const lastCall = vi.mocked(loadServerHierarchicalMemory).mock.calls.at(-1);
const options = lastCall?.at(-1) as
| LoadServerHierarchicalMemoryOptions
| undefined;
expect(options?.onInstructionsLoaded).toEqual(expect.any(Function));
await options?.onInstructionsLoaded?.({
filePath: '/tmp/project/QWEN.md',
memoryType: 'project',
loadReason: 'include',
globs: ['**/*.ts'],
triggerFilePath: '/tmp/project/AGENTS.md',
parentFilePath: '/tmp/project/AGENTS.md',
});
expect(fireInstructionsLoadedEvent).toHaveBeenCalledWith(
'/tmp/project/QWEN.md',
'project',
'include',
{
globs: ['**/*.ts'],
triggerFilePath: '/tmp/project/AGENTS.md',
parentFilePath: '/tmp/project/AGENTS.md',
},
);
});
it('Config constructor should call setGeminiMdFilename with contextFileName if provided', () => {

View File

@ -1848,7 +1848,21 @@ export class Config {
this.isTrustedFolder(),
this.getImportFormat(),
this.contextRuleExcludes,
{ explicitOnly: this.getBareMode() },
{
explicitOnly: this.getBareMode(),
onInstructionsLoaded: async (notification) => {
await this.hookSystem?.fireInstructionsLoadedEvent(
notification.filePath,
notification.memoryType,
notification.loadReason,
{
globs: notification.globs,
triggerFilePath: notification.triggerFilePath,
parentFilePath: notification.parentFilePath,
},
);
},
},
);
if (this.getManagedAutoMemoryEnabled()) {
const managedAutoMemoryIndex = await readAutoMemoryIndex(

View File

@ -168,6 +168,52 @@ describe('HookEventHandler', () => {
});
});
describe('fireInstructionsLoadedEvent', () => {
it('should include instruction load metadata in hook input', async () => {
const mockPlan = createMockExecutionPlan([
{
type: HookType.Command,
command: 'echo test',
source: HooksConfigSource.Project,
},
]);
vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan);
vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([]);
vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue(
createMockAggregatedResult(true),
);
await hookEventHandler.fireInstructionsLoadedEvent(
'/repo/.qwen/QWEN.local.md',
'local',
'include',
{
parentFilePath: '/repo/QWEN.md',
},
);
expect(mockHookPlanner.createExecutionPlan).toHaveBeenCalledWith(
HookEventName.InstructionsLoaded,
{
filePath: '/repo/.qwen/QWEN.local.md',
},
);
const mockCalls = (mockHookRunner.executeHooksParallel as Mock).mock
.calls;
const input = mockCalls[0][2] as {
file_path: string;
memory_type: string;
load_reason: string;
parent_file_path?: string;
};
expect(input.file_path).toBe('/repo/.qwen/QWEN.local.md');
expect(input.memory_type).toBe('local');
expect(input.load_reason).toBe('include');
expect(input.parent_file_path).toBe('/repo/QWEN.md');
});
});
describe('fireStopEvent', () => {
it('should execute hooks for Stop event', async () => {
const mockPlan = createMockExecutionPlan([]);

View File

@ -45,6 +45,9 @@ import type {
TodoCompletedInput,
TodoItem,
TodoStatus,
InstructionsLoadedInput,
InstructionMemoryType,
InstructionLoadReason,
} from './types.js';
import { HookPhase, PermissionMode } from './types.js';
import { createDebugLogger } from '../utils/debugLogger.js';
@ -116,6 +119,37 @@ export class HookEventHandler {
);
}
async fireInstructionsLoadedEvent(
filePath: string,
memoryType: InstructionMemoryType,
loadReason: InstructionLoadReason,
options: {
globs?: string[];
triggerFilePath?: string;
parentFilePath?: string;
} = {},
signal?: AbortSignal,
): Promise<AggregatedHookResult> {
const input: InstructionsLoadedInput = {
...this.createBaseInput(HookEventName.InstructionsLoaded),
file_path: filePath,
memory_type: memoryType,
load_reason: loadReason,
globs: options.globs,
trigger_file_path: options.triggerFilePath,
parent_file_path: options.parentFilePath,
};
return this.executeHooks(
HookEventName.InstructionsLoaded,
input,
{
filePath,
},
signal,
);
}
/**
* Fire a Stop event
* Called by handleHookExecutionRequest - executes hooks directly

View File

@ -83,6 +83,17 @@ describe('HookPlanner', () => {
});
});
it('returns file path targets for instruction load events', () => {
expect(
getHookMatcherTarget(HookEventName.InstructionsLoaded, {
filePath: '/repo/.qwen/QWEN.local.md',
}),
).toEqual({
kind: 'filePath',
target: '/repo/.qwen/QWEN.local.md',
});
});
it('returns undefined for events without matcher semantics', () => {
expect(getHookMatcherTarget(HookEventName.UserPromptSubmit)).toBe(
undefined,
@ -518,6 +529,46 @@ describe('HookPlanner', () => {
expect(result).not.toBeNull();
});
it('should match instruction loaded file paths with regex', () => {
const entry: HookRegistryEntry = {
config: { type: HookType.Command, command: 'echo test' },
source: HooksConfigSource.Project,
eventName: HookEventName.InstructionsLoaded,
matcher: '\\.qwen/QWEN\\.local\\.md$',
enabled: true,
};
vi.mocked(mockRegistry.getHooksForEvent).mockReturnValue([entry]);
const result = planner.createExecutionPlan(
HookEventName.InstructionsLoaded,
{
filePath: '/repo/.qwen/QWEN.local.md',
},
);
expect(result).not.toBeNull();
});
it('should not match unrelated instruction loaded file paths', () => {
const entry: HookRegistryEntry = {
config: { type: HookType.Command, command: 'echo test' },
source: HooksConfigSource.Project,
eventName: HookEventName.InstructionsLoaded,
matcher: '\\.qwen/QWEN\\.local\\.md$',
enabled: true,
};
vi.mocked(mockRegistry.getHooksForEvent).mockReturnValue([entry]);
const result = planner.createExecutionPlan(
HookEventName.InstructionsLoaded,
{
filePath: '/repo/QWEN.md',
},
);
expect(result).toBeNull();
});
it('should match auth_success notification type', () => {
const entry: HookRegistryEntry = {
config: { type: HookType.Command, command: 'echo test' },

View File

@ -17,7 +17,8 @@ type HookMatcherTargetKind =
| 'trigger'
| 'sessionTrigger'
| 'error'
| 'notificationType';
| 'notificationType'
| 'filePath';
interface HookMatcherTarget {
kind: HookMatcherTargetKind;
@ -57,6 +58,9 @@ export function getHookMatcherTarget(
target: context?.notificationType ?? '',
};
case HookEventName.InstructionsLoaded:
return { kind: 'filePath', target: context?.filePath ?? '' };
case HookEventName.UserPromptSubmit:
case HookEventName.Stop:
case HookEventName.TodoCreated:
@ -70,11 +74,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
*/
@ -167,6 +166,9 @@ export class HookPlanner {
case 'notificationType':
return this.matchesNotificationType(matcher, matcherTarget.target);
case 'filePath':
return this.matchesFilePath(matcher, matcherTarget.target);
case 'sessionTrigger':
return this.matchesSessionTrigger(matcher, matcherTarget.target);
@ -187,6 +189,21 @@ export class HookPlanner {
return matcher === notificationType;
}
/**
* Match loaded instruction file path against matcher pattern.
*/
private matchesFilePath(matcher: string, filePath: string): boolean {
try {
const regex = new RegExp(matcher);
return regex.test(filePath);
} catch (error) {
debugLogger.warn(
`Invalid regex in hook matcher "${matcher}" for file path "${filePath}", falling back to exact match: ${error}`,
);
return matcher === filePath;
}
}
/**
* Match session source or end reason against matcher pattern
*/
@ -275,4 +292,6 @@ export interface HookEventContext {
agentType?: string;
/** Error type for StopFailure matcher filtering (fieldToMatch: 'error') */
error?: string;
/** Loaded instruction/context file path for InstructionsLoaded matcher filtering */
filePath?: string;
}

View File

@ -34,6 +34,8 @@ import type {
StopFailureErrorType,
TodoItem,
TodoStatus,
InstructionMemoryType,
InstructionLoadReason,
} from './types.js';
import { SessionHooksManager } from './sessionHooksManager.js';
import type { AsyncHookRegistry } from './asyncHookRegistry.js';
@ -152,6 +154,29 @@ export class HookSystem {
: undefined;
}
async fireInstructionsLoadedEvent(
filePath: string,
memoryType: InstructionMemoryType,
loadReason: InstructionLoadReason,
options: {
globs?: string[];
triggerFilePath?: string;
parentFilePath?: string;
} = {},
signal?: AbortSignal,
): Promise<DefaultHookOutput | undefined> {
const result = await this.hookEventHandler.fireInstructionsLoadedEvent(
filePath,
memoryType,
loadReason,
options,
signal,
);
return result.finalOutput
? createHookOutput('InstructionsLoaded', result.finalOutput)
: undefined;
}
async fireStopEvent(
stopHookActive: boolean = false,
lastAssistantMessage: string = '',

View File

@ -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

View File

@ -54,6 +54,8 @@ export enum HookEventName {
TodoCreated = 'TodoCreated',
// TodoCompleted - When a todo item's status changes to 'completed' (Qwen Code specific)
TodoCompleted = 'TodoCompleted',
// InstructionsLoaded - When an instruction or context file is loaded
InstructionsLoaded = 'InstructionsLoaded',
}
/**
@ -253,6 +255,22 @@ export interface HookInput {
timestamp: string;
}
export type InstructionMemoryType = 'user' | 'project' | 'local' | 'extension';
export type InstructionLoadReason = 'session_start' | 'include';
/**
* Input for InstructionsLoaded hook events
*/
export interface InstructionsLoadedInput extends HookInput {
file_path: string;
memory_type: InstructionMemoryType;
load_reason: InstructionLoadReason;
globs?: string[];
trigger_file_path?: string;
parent_file_path?: string;
}
/**
* Base hook output - common fields for all events
*/

View File

@ -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,

View File

@ -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);

View File

@ -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;

View File

@ -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);

View File

@ -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,

View File

@ -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');
},
);
});

View File

@ -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,

View File

@ -12,9 +12,11 @@ import { loadServerHierarchicalMemory } from './memoryDiscovery.js';
import {
setGeminiMdFilename,
DEFAULT_CONTEXT_FILENAME,
LOCAL_CONTEXT_FILENAME,
} from '../memory/const.js';
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { QWEN_DIR } from './paths.js';
import type { InstructionsLoadedNotification } from './memoryDiscovery.js';
vi.mock('os', async (importOriginal) => {
const actualOs = await importOriginal<typeof os>();
@ -438,6 +440,162 @@ describe('loadServerHierarchicalMemory', () => {
});
});
it('notifies when startup instruction files are loaded', async () => {
const globalFile = await createTestFile(
path.join(homedir, QWEN_DIR, DEFAULT_CONTEXT_FILENAME),
'global context',
);
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'project context',
);
const extensionFile = await createTestFile(
path.join(testRootDir, 'extensions/ext1/QWEN.md'),
'extension context',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[extensionFile],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
{
filePath: globalFile,
memoryType: 'user',
loadReason: 'session_start',
},
{
filePath: projectFile,
memoryType: 'project',
loadReason: 'session_start',
},
{
filePath: extensionFile,
memoryType: 'extension',
loadReason: 'session_start',
},
]),
);
});
it('notifies when imported instruction files are loaded', async () => {
await createEmptyDir(path.join(projectRoot, '.git'));
const importedFile = await createTestFile(
path.join(projectRoot, 'included.md'),
'included content',
);
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'project context @./included.md',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
expect.objectContaining({
filePath: importedFile,
memoryType: 'project',
loadReason: 'include',
parentFilePath: projectFile,
}),
]),
);
});
it('classifies extension-owned imports as extension memory', async () => {
const extensionDir = path.join(testRootDir, 'extensions/ext1');
const importedFile = await createTestFile(
path.join(extensionDir, 'included.md'),
'extension included content',
);
const extensionFile = await createTestFile(
path.join(extensionDir, DEFAULT_CONTEXT_FILENAME),
'extension context @./included.md',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[extensionFile],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
expect.objectContaining({
filePath: importedFile,
memoryType: 'extension',
loadReason: 'include',
parentFilePath: extensionFile,
}),
]),
);
});
it('still loads memory when instruction load notification fails', async () => {
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'project context',
);
const result = await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: () => {
throw new Error('hook failed');
},
},
);
expect(result.fileCount).toBe(1);
expect(result.memoryContent).toContain(
`--- Context from: ${path.relative(cwd, projectFile)} ---\nproject context`,
);
});
it('should load memory from included directories', async () => {
const includedDir = await createEmptyDir(
path.join(testRootDir, 'included'),
@ -567,6 +725,39 @@ describe('loadServerHierarchicalMemory', () => {
);
});
it('notifies when QWEN.local.md is loaded', async () => {
const localFile = await createTestFile(
path.join(projectRoot, QWEN_DIR, LOCAL_CONTEXT_FILENAME),
'local context content',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
{
filePath: localFile,
memoryType: 'local',
loadReason: 'session_start',
},
]),
);
});
it('orders QWEN.local.md after the project-root QWEN.md', async () => {
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),

View File

@ -14,11 +14,15 @@ import {
} from '../memory/const.js';
import type { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { processImports } from './memoryImportProcessor.js';
import { QWEN_DIR } from './paths.js';
import { isSubpath, QWEN_DIR } from './paths.js';
import { Storage } from '../config/storage.js';
import { createDebugLogger } from './debugLogger.js';
import { findProjectRoot } from './projectRoot.js';
import { loadRules, type RuleFile } from './rulesDiscovery.js';
import type {
InstructionLoadReason,
InstructionMemoryType,
} from '../hooks/types.js';
const logger = createDebugLogger('MEMORY_DISCOVERY');
@ -27,6 +31,15 @@ interface GeminiFileContent {
content: string | null;
}
export interface InstructionsLoadedNotification {
filePath: string;
memoryType: InstructionMemoryType;
loadReason: InstructionLoadReason;
globs?: string[];
triggerFilePath?: string;
parentFilePath?: string;
}
async function getGeminiMdFilePathsInternal(
currentWorkingDirectory: string,
includeDirectoriesToReadGemini: readonly string[],
@ -203,10 +216,24 @@ async function getGeminiMdFilePathsInternalForEachDir(
async function readGeminiMdFiles(
filePaths: string[],
importFormat: 'flat' | 'tree' = 'tree',
getMemoryType: (filePath: string) => InstructionMemoryType,
onInstructionsLoaded?: (
notification: InstructionsLoadedNotification,
) => void | Promise<void>,
): Promise<GeminiFileContent[]> {
// Process files in parallel with concurrency limit to prevent EMFILE errors
const CONCURRENT_LIMIT = 20; // Higher limit for file reads as they're typically faster
const results: GeminiFileContent[] = [];
const notifyInstructionsLoaded = async (
notification: InstructionsLoadedNotification,
) => {
try {
await onInstructionsLoaded?.(notification);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logger.warn(`InstructionsLoaded notification failed: ${message}`);
}
};
for (let i = 0; i < filePaths.length; i += CONCURRENT_LIMIT) {
const batch = filePaths.slice(i, i + CONCURRENT_LIMIT);
@ -219,13 +246,34 @@ async function readGeminiMdFiles(
const processedResult = await processImports(
content,
path.dirname(filePath),
undefined,
{
processedFiles: new Set([path.resolve(filePath)]),
maxDepth: 5,
currentDepth: 0,
currentFile: path.resolve(filePath),
},
undefined,
importFormat,
{
onFileImported: async (notification) => {
await notifyInstructionsLoaded({
filePath: notification.filePath,
memoryType: getMemoryType(notification.filePath),
loadReason: 'include',
triggerFilePath: notification.parentFilePath,
parentFilePath: notification.parentFilePath,
});
},
},
);
logger.debug(
`Successfully read and processed imports: ${filePath} (Length: ${processedResult.content.length})`,
);
await notifyInstructionsLoaded({
filePath,
memoryType: getMemoryType(filePath),
loadReason: 'session_start',
});
return { filePath, content: processedResult.content };
} catch (error: unknown) {
@ -296,6 +344,52 @@ export interface LoadServerHierarchicalMemoryResponse {
export interface LoadServerHierarchicalMemoryOptions {
explicitOnly?: boolean;
onInstructionsLoaded?: (
notification: InstructionsLoadedNotification,
) => void | Promise<void>;
}
function createMemoryTypeClassifier(
userHomePath: string,
foundRoot: string | null,
extensionContextFilePaths: string[],
): (filePath: string) => InstructionMemoryType {
const resolvedHome = path.resolve(userHomePath);
const globalQwenDir = path.resolve(Storage.getGlobalQwenDir());
const resolvedRoot = foundRoot ? path.resolve(foundRoot) : undefined;
const extensionPaths = new Set(
extensionContextFilePaths.map((filePath) => path.resolve(filePath)),
);
const extensionRoots = extensionContextFilePaths.map((filePath) =>
path.dirname(path.resolve(filePath)),
);
return (filePath) => {
const resolvedPath = path.resolve(filePath);
if (
extensionPaths.has(resolvedPath) ||
extensionRoots.some((root) => isSubpath(root, resolvedPath))
) {
return 'extension';
}
if (
resolvedRoot &&
resolvedPath === path.join(resolvedRoot, QWEN_DIR, LOCAL_CONTEXT_FILENAME)
) {
return 'local';
}
if (
resolvedPath.startsWith(`${globalQwenDir}${path.sep}`) ||
path.dirname(resolvedPath) === resolvedHome
) {
return 'user';
}
return 'project';
};
}
/**
@ -374,7 +468,16 @@ export async function loadServerHierarchicalMemory(
let fileCount = 0;
if (filePaths.length > 0) {
const contentsWithPaths = await readGeminiMdFiles(filePaths, importFormat);
const contentsWithPaths = await readGeminiMdFiles(
filePaths,
importFormat,
createMemoryTypeClassifier(
userHomePath,
foundRoot,
extensionContextFilePaths,
),
options.onInstructionsLoaded,
);
// Pass CWD for relative path display in concatenated content
combinedInstructions = concatenateInstructions(
contentsWithPaths,

View File

@ -144,6 +144,45 @@ describe('memoryImportProcessor', () => {
);
});
it('notifies after importing a file', async () => {
const content = 'Some content @./test.md more content';
const basePath = testPath('test', 'path');
const parentFile = path.resolve(basePath, 'QWEN.md');
const importedFile = path.resolve(basePath, 'test.md');
const importedFiles: Array<{
filePath: string;
parentFilePath: string;
}> = [];
mockedFs.access.mockResolvedValue(undefined);
mockedFs.readFile.mockResolvedValue('# Imported Content');
await processImports(
content,
basePath,
{
processedFiles: new Set(),
maxDepth: 5,
currentDepth: 0,
currentFile: parentFile,
},
undefined,
'tree',
{
onFileImported: (event) => {
importedFiles.push(event);
},
},
);
expect(importedFiles).toEqual([
{
filePath: importedFile,
parentFilePath: parentFile,
},
]);
});
it('should import non-md files just like md files', async () => {
const content = 'Some content @./instructions.txt more content';
const basePath = testPath('test', 'path');

View File

@ -39,6 +39,17 @@ export interface ProcessImportsResult {
importTree: MemoryFile;
}
export interface ImportedFileNotification {
filePath: string;
parentFilePath: string;
}
export interface ProcessImportsOptions {
onFileImported?: (
notification: ImportedFileNotification,
) => void | Promise<void>;
}
// `findProjectRoot` now lives in `./projectRoot.ts` and is shared with
// memoryDiscovery. It returns `string | null`; `processImports` below
// preserves the previous "fall back to startDir" contract at the call
@ -190,6 +201,7 @@ export async function processImports(
},
projectRoot?: string,
importFormat: 'flat' | 'tree' = 'tree',
options: ProcessImportsOptions = {},
): Promise<ProcessImportsResult> {
if (!projectRoot) {
// Preserve the previous local helper's contract: if no `.git`
@ -268,6 +280,10 @@ export async function processImports(
try {
await fs.access(fullPath);
const importedContent = await fs.readFile(fullPath, 'utf-8');
await options.onFileImported?.({
filePath: normalizedFullPath,
parentFilePath: normalizedPath,
});
// Process the imported file
await processFlat(
@ -339,6 +355,10 @@ export async function processImports(
try {
await fs.access(fullPath);
const fileContent = await fs.readFile(fullPath, 'utf-8');
await options.onFileImported?.({
filePath: fullPath,
parentFilePath: importState.currentFile ?? path.resolve(basePath),
});
// Mark this file as processed for this import chain
const newImportState: ImportState = {
...importState,
@ -353,6 +373,7 @@ export async function processImports(
newImportState,
projectRoot,
importFormat,
options,
);
result += `<!-- Imported from: ${importPath} -->\n${imported.content}\n<!-- End of import from: ${importPath} -->`;
imports.push(imported.importTree);

View File

@ -29,10 +29,9 @@
* keeps running while no longer serving the recorded session
* (e.g. a hypothetical future mode-switch). Not currently invoked.
*
* The file is written via `atomicWriteJSON` (write-to-temp + rename,
* with in-place fallback when ownership differs).
* The schema is small and stable; external consumers should treat
* unknown fields as forward-compatible additions.
* The file is written atomically (tmp-file + rename) and contains a
* small, stable schema. External consumers should treat unknown fields
* as forward-compatible additions.
*/
import * as fs from 'node:fs/promises';
@ -79,11 +78,17 @@ export interface WriteRuntimeStatusFields {
}
/**
* Write the runtime status file at `filePath`.
* Atomically write the runtime status file at `filePath`.
*
* The parent directory is created on demand. Exceptions propagate to
* the caller; callers that want best-effort semantics should wrap in
* a try/catch.
* Writes via tmp-file + rename so an external observer never sees a
* partially written file: it sees either the previous contents or the
* fully committed new contents.
*
* The parent directory of `filePath` is created on demand. Exceptions
* from the underlying I/O propagate to the caller; this function does
* not log or swallow them. Callers that want best-effort semantics
* should wrap the call in a try/catch. On failure no leftover `.tmp`
* file is kept on disk.
*/
export async function writeRuntimeStatus(
filePath: string,