-
Notifications
You must be signed in to change notification settings - Fork 38.3k
Expand file tree
/
Copy pathhookActions.ts
More file actions
872 lines (779 loc) · 30.8 KB
/
hookActions.ts
File metadata and controls
872 lines (779 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { parse as parseJSONC } from '../../../../../base/common/jsonc.js';
import { setProperty, applyEdits } from '../../../../../base/common/jsonEdit.js';
import { FormattingOptions } from '../../../../../base/common/jsonFormatter.js';
import { isEqual } from '../../../../../base/common/resources.js';
import { URI } from '../../../../../base/common/uri.js';
import { VSBuffer } from '../../../../../base/common/buffer.js';
import { DisposableStore } from '../../../../../base/common/lifecycle.js';
import { ChatViewId } from '../chat.js';
import { CHAT_CATEGORY, CHAT_CONFIG_MENU_ID } from '../actions/chatActions.js';
import { localize, localize2 } from '../../../../../nls.js';
import { ChatContextKeys } from '../../common/actions/chatContextKeys.js';
import { ServicesAccessor } from '../../../../../editor/browser/editorExtensions.js';
import { Action2, registerAction2 } from '../../../../../platform/actions/common/actions.js';
import { Codicon } from '../../../../../base/common/codicons.js';
import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js';
import { IPromptsService, PromptsStorage } from '../../common/promptSyntax/service/promptsService.js';
import { PromptsType, Target } from '../../common/promptSyntax/promptTypes.js';
import { CancellationToken } from '../../../../../base/common/cancellation.js';
import { IQuickInputButton, IQuickInputService, IQuickPick, IQuickPickItem, IQuickPickSeparator } from '../../../../../platform/quickinput/common/quickInput.js';
import { IFileService } from '../../../../../platform/files/common/files.js';
import { HOOK_METADATA, HOOKS_BY_TARGET, HookType, IHookTypeMeta } from '../../common/promptSyntax/hookTypes.js';
import { formatHookCommandLabel, getEffectiveCommandFieldKey } from '../../common/promptSyntax/hookSchema.js';
import { getCopilotCliHookTypeName, resolveCopilotCliHookType } from '../../common/promptSyntax/hookCopilotCliCompat.js';
import { getHookSourceFormat, HookSourceFormat, buildNewHookEntry } from '../../common/promptSyntax/hookCompatibility.js';
import { getClaudeHookTypeName, resolveClaudeHookType } from '../../common/promptSyntax/hookClaudeCompat.js';
import { ILabelService } from '../../../../../platform/label/common/label.js';
import { IEditorService } from '../../../../services/editor/common/editorService.js';
import { ITextEditorSelection } from '../../../../../platform/editor/common/editor.js';
import { findHookCommandSelection, findHookCommandInYaml, parseAllHookFiles, IParsedHook } from './hookUtils.js';
import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js';
import { IPathService } from '../../../../services/path/common/pathService.js';
import { INotificationService } from '../../../../../platform/notification/common/notification.js';
import { IBulkEditService, ResourceTextEdit } from '../../../../../editor/browser/services/bulkEditService.js';
import { Range } from '../../../../../editor/common/core/range.js';
import { getCodeEditor } from '../../../../../editor/browser/editorBrowser.js';
import { IRemoteAgentService } from '../../../../services/remote/common/remoteAgentService.js';
import { OperatingSystem, OS } from '../../../../../base/common/platform.js';
/**
* Action ID for the `Configure Hooks` action.
*/
const CONFIGURE_HOOKS_ACTION_ID = 'workbench.action.chat.configure.hooks';
interface IHookTypeQuickPickItem extends IQuickPickItem {
readonly hookType: HookType;
readonly hookTypeMeta: IHookTypeMeta;
}
interface IHookQuickPickItem extends IQuickPickItem {
readonly hookEntry?: IParsedHook;
readonly isAddNewHook?: boolean;
}
interface IHookFileQuickPickItem extends IQuickPickItem {
readonly fileUri?: URI;
readonly isCreateNewFile?: boolean;
}
/**
* Detects if existing hooks use Copilot CLI naming convention (camelCase).
* Returns true if any existing key matches the Copilot CLI format.
*/
function usesCopilotCliNaming(hooksObj: Record<string, unknown>): boolean {
for (const key of Object.keys(hooksObj)) {
// Check if any key resolves to a Copilot CLI hook type
if (resolveCopilotCliHookType(key) !== undefined) {
return true;
}
}
return false;
}
/**
* Gets the appropriate key name for a hook type based on the naming convention used in the file.
*/
function getHookTypeKeyName(hookTypeId: HookType, useCopilotCliNamingConvention: boolean): string {
if (useCopilotCliNamingConvention) {
const copilotCliName = getCopilotCliHookTypeName(hookTypeId);
if (copilotCliName) {
return copilotCliName;
}
}
// Fall back to PascalCase (enum value)
return hookTypeId;
}
/**
* Adds a hook to an existing hook file.
*/
async function addHookToFile(
hookFileUri: URI,
hookTypeId: HookType,
fileService: IFileService,
editorService: IEditorService,
notificationService: INotificationService,
bulkEditService: IBulkEditService,
openEditorOverride?: (resource: URI, options?: { selection?: ITextEditorSelection }) => Promise<void>,
): Promise<void> {
// Parse existing file
let hooksContent: { hooks: Record<string, unknown[]> };
const fileExists = await fileService.exists(hookFileUri);
if (fileExists) {
const existingContent = await fileService.readFile(hookFileUri);
try {
hooksContent = parseJSONC(existingContent.value.toString());
// Ensure hooks object exists
if (!hooksContent.hooks) {
hooksContent.hooks = {};
}
} catch {
// If parsing fails, show error and open file for user to fix
notificationService.error(localize('commands.new.hook.parseError', "Failed to parse existing hooks file. Please fix the JSON syntax errors and try again."));
await editorService.openEditor({ resource: hookFileUri });
return;
}
} else {
// Create new structure
hooksContent = { hooks: {} };
}
// Detect source format from file URI
const sourceFormat = getHookSourceFormat(hookFileUri);
const isClaude = sourceFormat === HookSourceFormat.Claude;
// Detect naming convention from existing keys
const useCopilotCliNamingConvention = !isClaude && usesCopilotCliNaming(hooksContent.hooks);
const hookTypeKeyName = isClaude
? (getClaudeHookTypeName(hookTypeId) ?? hookTypeId)
: getHookTypeKeyName(hookTypeId, useCopilotCliNamingConvention);
// Also check if there's an existing key for this hook type (with either naming)
// Find existing key that resolves to the same hook type
let existingKeyForType: string | undefined;
for (const key of Object.keys(hooksContent.hooks)) {
const resolvedType = isClaude
? resolveClaudeHookType(key)
: resolveCopilotCliHookType(key);
if (resolvedType === hookTypeId || key === hookTypeId) {
existingKeyForType = key;
break;
}
}
// Use existing key if found, otherwise use the detected naming convention
const keyToUse = existingKeyForType ?? hookTypeKeyName;
// Determine the new hook index (append if hook type already exists)
const newHookEntry = buildNewHookEntry(sourceFormat);
const existingHooks = hooksContent.hooks[keyToUse];
const newHookIndex = Array.isArray(existingHooks) ? existingHooks.length : 0;
// Generate the new JSON content using setProperty to preserve comments
let jsonContent: string;
if (fileExists) {
// Use setProperty to make targeted edits that preserve comments
const originalText = (await fileService.readFile(hookFileUri)).value.toString();
const detectedEol = originalText.includes('\r\n') ? '\r\n' : '\n';
const formattingOptions: FormattingOptions = { tabSize: 1, insertSpaces: false, eol: detectedEol };
const edits = setProperty(originalText, ['hooks', keyToUse, newHookIndex], newHookEntry, formattingOptions);
jsonContent = applyEdits(originalText, edits);
} else {
// New file - use JSON.stringify since there are no comments to preserve
const newContent = { hooks: { [keyToUse]: [newHookEntry] } };
jsonContent = JSON.stringify(newContent, null, '\t');
}
// Check if the file is already open in an editor
const existingEditor = editorService.editors.find(e => isEqual(e.resource, hookFileUri));
if (existingEditor) {
// File is already open - first focus the editor, then update its model directly
await editorService.openEditor({
resource: hookFileUri,
options: {
pinned: false
}
});
// Get the code editor and update its content directly
const editor = getCodeEditor(editorService.activeTextEditorControl);
if (editor && editor.hasModel() && isEqual(editor.getModel().uri, hookFileUri)) {
const model = editor.getModel();
// Apply the full content replacement using executeEdits
model.pushEditOperations([], [{
range: model.getFullModelRange(),
text: jsonContent
}], () => null);
// Find and apply the selection
const selection = findHookCommandSelection(jsonContent, keyToUse, newHookIndex, 'command');
if (selection && selection.endLineNumber !== undefined && selection.endColumn !== undefined) {
editor.setSelection({
startLineNumber: selection.startLineNumber,
startColumn: selection.startColumn,
endLineNumber: selection.endLineNumber,
endColumn: selection.endColumn
});
editor.revealLineInCenter(selection.startLineNumber);
}
} else {
// Fallback: active editor/model check failed, apply via bulk edit service
await bulkEditService.apply([
new ResourceTextEdit(hookFileUri, { range: new Range(1, 1, Number.MAX_SAFE_INTEGER, 1), text: jsonContent })
], { label: localize('addHook', "Add Hook") });
// Find the selection for the new hook's command field
const selection = findHookCommandSelection(jsonContent, keyToUse, newHookIndex, 'command');
// Re-open editor with selection
await editorService.openEditor({
resource: hookFileUri,
options: {
selection,
pinned: false
}
});
}
} else {
// File is not currently open in an editor
if (!fileExists) {
// File doesn't exist - write new file directly and open
await fileService.writeFile(hookFileUri, VSBuffer.fromString(jsonContent));
} else {
// File exists but isn't open - open it first, then use bulk edit for undo support
await editorService.openEditor({
resource: hookFileUri,
options: { pinned: false }
});
// Apply the edit via bulk edit service for proper undo support
await bulkEditService.apply([
new ResourceTextEdit(hookFileUri, { range: new Range(1, 1, Number.MAX_SAFE_INTEGER, 1), text: jsonContent })
], { label: localize('addHook', "Add Hook") });
}
// Find the selection for the new hook's command field
const selection = findHookCommandSelection(jsonContent, keyToUse, newHookIndex, 'command');
// Open editor with selection (or re-focus if already open)
if (openEditorOverride) {
await openEditorOverride(hookFileUri, { selection });
} else {
await editorService.openEditor({
resource: hookFileUri,
options: {
selection,
pinned: false
}
});
}
}
}
/**
* Awaits a single pick interaction on the given picker.
* Returns the selected item, 'back' if the back button was pressed, or undefined if cancelled.
*/
function awaitPick<T extends IQuickPickItem>(
picker: IQuickPick<IQuickPickItem, { useSeparators: true }>,
backButton: IQuickInputButton,
): Promise<T | 'back' | undefined> {
return new Promise<T | 'back' | undefined>(resolve => {
let resolved = false;
const done = (value: T | 'back' | undefined) => {
if (!resolved) {
resolved = true;
disposables.dispose();
resolve(value);
}
};
const disposables = new DisposableStore();
disposables.add(picker.onDidAccept(() => {
done(picker.activeItems[0] as T | undefined);
}));
disposables.add(picker.onDidTriggerButton(button => {
if (button === backButton) {
done('back');
}
}));
disposables.add(picker.onDidHide(() => {
done(undefined);
}));
});
}
const enum Step {
SelectHookType = 1,
SelectHook = 2,
SelectFile = 3,
SelectFolder = 4,
EnterFilename = 5,
}
/**
* Optional callbacks and settings for customizing the hook creation and opening behaviour.
* The agentic editor passes these to open hooks in the embedded editor and
* track worktree files for auto-commit.
*/
export interface IHookQuickPickOptions {
/** Override how the hook file is opened. If not provided, uses editorService.openEditor. */
readonly openEditor?: (resource: URI, options?: { selection?: ITextEditorSelection }) => Promise<void>;
/** Called after a new hook file is created on disk. */
readonly onHookFileCreated?: (uri: URI) => void;
/** Filter the displayed hook types to those supported by the given target. */
readonly target?: Target;
}
/**
* Shows the Configure Hooks quick pick UI, allowing the user to view,
* open, or create hooks. Can be called from the action or slash command.
*/
export async function showConfigureHooksQuickPick(
accessor: ServicesAccessor,
options?: IHookQuickPickOptions,
): Promise<void> {
const promptsService = accessor.get(IPromptsService);
const quickInputService = accessor.get(IQuickInputService);
const fileService = accessor.get(IFileService);
const labelService = accessor.get(ILabelService);
const editorService = accessor.get(IEditorService);
const workspaceService = accessor.get(IWorkspaceContextService);
const pathService = accessor.get(IPathService);
const notificationService = accessor.get(INotificationService);
const bulkEditService = accessor.get(IBulkEditService);
const remoteAgentService = accessor.get(IRemoteAgentService);
// Get the remote OS (or fall back to local OS)
const remoteEnv = await remoteAgentService.getEnvironment();
const targetOS = remoteEnv?.os ?? OS;
// Get workspace root and user home for path resolution
const workspaceFolder = workspaceService.getWorkspace().folders[0];
const workspaceRootUri = workspaceFolder?.uri;
const userHomeUri = await pathService.userHome();
const userHome = userHomeUri.fsPath ?? userHomeUri.path;
// Parse all hook files upfront to count hooks per type
const hookEntries = await parseAllHookFiles(
promptsService,
fileService,
labelService,
workspaceRootUri,
userHome,
targetOS,
CancellationToken.None,
{ includeAgentHooks: true }
);
// Count hooks per type
const hookCountByType = new Map<HookType, number>();
for (const entry of hookEntries) {
hookCountByType.set(entry.hookType, (hookCountByType.get(entry.hookType) ?? 0) + 1);
}
// Create a single picker instance reused across all steps
const store = new DisposableStore();
const picker = store.add(quickInputService.createQuickPick<IQuickPickItem>({ useSeparators: true }));
const backButton = quickInputService.backButton;
let suppressHideDispose = false;
store.add(picker.onDidHide(() => {
if (!suppressHideDispose) {
store.dispose();
}
}));
picker.show();
let step = Step.SelectHookType;
let selectedHookType: IHookTypeQuickPickItem | undefined;
let selectedHook: IHookQuickPickItem | undefined;
let selectedFile: IHookFileQuickPickItem | undefined;
let selectedFolder: { uri: URI } | undefined;
// Track steps that were actually shown to the user, so Back
// skips over auto-executed steps and returns to the last visible one.
const stepHistory: Step[] = [];
const goBack = (): Step | undefined => stepHistory.pop();
while (true) {
switch (step) {
case Step.SelectHookType: {
// Step 1: Show lifecycle events with hook counts, filtered by target
const makeItem = ([hookType, meta]: [HookType, IHookTypeMeta]): IHookTypeQuickPickItem => {
const count = hookCountByType.get(hookType) ?? 0;
const countLabel = count > 0 ? ` (${count})` : '';
return {
label: `${meta.label}${countLabel}`,
description: meta.description,
hookType,
hookTypeMeta: meta
};
};
let pickerItems: (IHookTypeQuickPickItem | IQuickPickSeparator)[];
if (options?.target) {
// Filtered to a specific target
const targetHookTypes = new Set(Object.values(HOOKS_BY_TARGET[options.target]));
pickerItems = (Object.entries(HOOK_METADATA) as [HookType, IHookTypeMeta][])
.filter(([hookType]) => targetHookTypes.has(hookType))
.map(makeItem);
} else {
// No target: group into Default (shared), VS Code Only, Copilot CLI Only
const vscodeTypes = new Set(Object.values(HOOKS_BY_TARGET[Target.VSCode]));
const copilotTypes = new Set(Object.values(HOOKS_BY_TARGET[Target.GitHubCopilot]));
const allEntries = Object.entries(HOOK_METADATA) as [HookType, IHookTypeMeta][];
const shared = allEntries.filter(([h]) => vscodeTypes.has(h) && copilotTypes.has(h));
const vscodeOnly = allEntries.filter(([h]) => vscodeTypes.has(h) && !copilotTypes.has(h));
const copilotOnly = allEntries.filter(([h]) => !vscodeTypes.has(h) && copilotTypes.has(h));
pickerItems = [];
if (shared.length > 0) {
pickerItems.push({ type: 'separator', label: localize('hookSection.default', "Local/Copilot CLI Agents") });
pickerItems.push(...shared.map(makeItem));
}
if (vscodeOnly.length > 0) {
pickerItems.push({ type: 'separator', label: localize('hookSection.vscodeOnly', "Local Agents") });
pickerItems.push(...vscodeOnly.map(makeItem));
}
if (copilotOnly.length > 0) {
pickerItems.push({ type: 'separator', label: localize('hookSection.copilotCliOnly', "Copilot CLI Agents") });
pickerItems.push(...copilotOnly.map(makeItem));
}
}
picker.items = pickerItems;
picker.value = '';
picker.placeholder = localize('commands.hooks.selectEvent.placeholder', 'Select a lifecycle event');
picker.title = localize('commands.hooks.title', 'Hooks');
picker.buttons = [];
const result = await awaitPick<IHookTypeQuickPickItem>(picker, backButton);
if (!result || result === 'back') {
picker.hide();
return;
}
selectedHookType = result;
stepHistory.push(Step.SelectHookType);
step = Step.SelectHook;
break;
}
case Step.SelectHook: {
// Filter hooks by the selected type
const hooksOfType = hookEntries.filter(h => h.hookType === selectedHookType!.hookType);
// Separate hooks by source
const fileHooks = hooksOfType.filter(h => !h.agentName);
const agentHooks = hooksOfType.filter(h => h.agentName);
// Step 2: Show "Add new hook" + existing hooks of this type
const hookItems: (IHookQuickPickItem | IQuickPickSeparator)[] = [];
// Add "Add new hook" option at the top
hookItems.push({
label: `$(plus) ${localize('commands.addNewHook.label', 'Add new hook...')}`,
isAddNewHook: true,
alwaysShow: true
});
// Add existing file-based hooks
if (fileHooks.length > 0) {
hookItems.push({
type: 'separator',
label: localize('existingHooks', "Existing Hooks")
});
for (const entry of fileHooks) {
const description = labelService.getUriLabel(entry.fileUri, { relative: true });
hookItems.push({
label: entry.commandLabel,
description,
hookEntry: entry
});
}
}
// Add agent-defined hooks grouped by agent name
if (agentHooks.length > 0) {
const agentNames = [...new Set(agentHooks.map(h => h.agentName!))];
for (const agentName of agentNames) {
hookItems.push({
type: 'separator',
label: localize('agentHooks', "Agent: {0}", agentName)
});
for (const entry of agentHooks.filter(h => h.agentName === agentName)) {
const description = labelService.getUriLabel(entry.fileUri, { relative: true });
hookItems.push({
label: entry.commandLabel,
description,
hookEntry: entry
});
}
}
}
// Auto-execute if only "Add new hook" is available (no existing hooks)
if (hooksOfType.length === 0) {
selectedHook = hookItems[0] as IHookQuickPickItem;
} else {
picker.items = hookItems;
picker.value = '';
picker.placeholder = localize('commands.hooks.selectHook.placeholder', 'Select a hook to open or add a new one');
picker.title = selectedHookType!.hookTypeMeta.label;
picker.buttons = [backButton];
const result = await awaitPick<IHookQuickPickItem>(picker, backButton);
if (result === 'back') {
step = goBack() ?? Step.SelectHookType;
break;
}
if (!result) {
picker.hide();
return;
}
selectedHook = result;
stepHistory.push(Step.SelectHook);
}
// Handle clicking on existing hook (focus into command)
if (selectedHook.hookEntry) {
const entry = selectedHook.hookEntry;
let selection: ITextEditorSelection | undefined;
if (entry.agentName) {
// Agent hook: search the YAML frontmatter for the command
try {
const content = await fileService.readFile(entry.fileUri);
const commandText = formatHookCommandLabel(entry.command, targetOS);
if (commandText) {
selection = findHookCommandInYaml(content.value.toString(), commandText);
}
} catch {
// Ignore errors and just open without selection
}
} else {
// File hook: use JSON-based selection finder
const commandFieldName = getEffectiveCommandFieldKey(entry.command, targetOS);
if (commandFieldName) {
try {
const content = await fileService.readFile(entry.fileUri);
selection = findHookCommandSelection(
content.value.toString(),
entry.originalHookTypeId,
entry.index,
commandFieldName
);
} catch {
// Ignore errors and just open without selection
}
}
}
picker.hide();
if (options?.openEditor) {
await options.openEditor(entry.fileUri, { selection });
} else {
await editorService.openEditor({
resource: entry.fileUri,
options: {
selection,
pinned: false
}
});
}
return;
}
// "Add new hook" was selected
step = Step.SelectFile;
break;
}
case Step.SelectFile: {
// Step 3: Handle "Add new hook" - show create new file + existing hook files
// Get existing hook files (local storage only, not User Data)
const hookFiles = await promptsService.listPromptFilesForStorage(PromptsType.hook, PromptsStorage.local, CancellationToken.None);
const fileItems: (IHookFileQuickPickItem | IQuickPickSeparator)[] = [];
// Add "Create new hook config file" option at the top
fileItems.push({
label: `$(new-file) ${localize('commands.createNewHookFile.label', 'Create new hook config file...')}`,
isCreateNewFile: true,
alwaysShow: true
});
// Add existing hook files
if (hookFiles.length > 0) {
fileItems.push({
type: 'separator',
label: localize('existingHookFiles', "Existing Hook Files")
});
for (const hookFile of hookFiles) {
const relativePath = labelService.getUriLabel(hookFile.uri, { relative: true });
fileItems.push({
label: relativePath,
fileUri: hookFile.uri
});
}
}
// Auto-execute if no existing hook files
if (hookFiles.length === 0) {
selectedFile = fileItems[0] as IHookFileQuickPickItem;
} else {
picker.items = fileItems;
picker.value = '';
picker.placeholder = localize('commands.hooks.selectFile.placeholder', 'Select a hook file or create a new one');
picker.title = localize('commands.hooks.addHook.title', 'Add Hook');
picker.buttons = [backButton];
const result = await awaitPick<IHookFileQuickPickItem>(picker, backButton);
if (result === 'back') {
step = goBack() ?? Step.SelectHook;
break;
}
if (!result) {
picker.hide();
return;
}
selectedFile = result;
stepHistory.push(Step.SelectFile);
}
// Handle adding hook to existing file
if (selectedFile.fileUri) {
picker.hide();
await addHookToFile(
selectedFile.fileUri,
selectedHookType!.hookType,
fileService,
editorService,
notificationService,
bulkEditService,
options?.openEditor,
);
return;
}
// "Create new hook config file" was selected
step = Step.SelectFolder;
break;
}
case Step.SelectFolder: {
// Get source folders for hooks
const allFolders = await promptsService.getSourceFolders(PromptsType.hook);
const localFolders = allFolders.filter(f => f.storage === PromptsStorage.local);
if (localFolders.length === 0) {
picker.hide();
notificationService.error(localize('commands.hook.noLocalFolders', "Please open a workspace folder to configure hooks."));
return;
}
// Auto-select if only one folder, otherwise show picker
selectedFolder = localFolders[0];
if (localFolders.length > 1) {
const folderItems = localFolders.map(folder => ({
label: labelService.getUriLabel(folder.uri, { relative: true }),
folder
}));
picker.items = folderItems;
picker.value = '';
picker.placeholder = localize('commands.hook.selectFolder.placeholder', 'Select a location for the hook file');
picker.title = localize('commands.hook.selectFolder.title', 'Hook File Location');
picker.buttons = [backButton];
const result = await awaitPick<typeof folderItems[0]>(picker, backButton);
if (result === 'back') {
step = goBack() ?? Step.SelectFile;
break;
}
if (!result) {
picker.hide();
return;
}
selectedFolder = result.folder;
stepHistory.push(Step.SelectFolder);
}
step = Step.EnterFilename;
break;
}
case Step.EnterFilename: {
// Hide the picker and show an input box for the filename
suppressHideDispose = true;
picker.hide();
suppressHideDispose = false;
const fileNameResult = await new Promise<string | 'back' | undefined>(resolve => {
let resolved = false;
const done = (value: string | 'back' | undefined) => {
if (!resolved) {
resolved = true;
inputDisposables.dispose();
resolve(value);
}
};
const inputDisposables = new DisposableStore();
const inputBox = inputDisposables.add(quickInputService.createInputBox());
inputBox.prompt = localize('commands.hook.filename.prompt', "Enter hook file name");
inputBox.placeholder = localize('commands.hook.filename.placeholder', "e.g., hooks, diagnostics, security");
inputBox.title = localize('commands.hook.filename.title', "Hook File Name");
inputBox.buttons = [backButton];
inputBox.ignoreFocusOut = true;
inputDisposables.add(inputBox.onDidAccept(async () => {
const value = inputBox.value;
if (!value || !value.trim()) {
inputBox.validationMessage = localize('commands.hook.filename.required', "File name is required");
return;
}
const name = value.trim();
if (/[/\\:*?"<>|]/.test(name)) {
inputBox.validationMessage = localize('commands.hook.filename.invalidChars', "File name contains invalid characters");
return;
}
done(name);
}));
inputDisposables.add(inputBox.onDidChangeValue(() => {
inputBox.validationMessage = undefined;
}));
inputDisposables.add(inputBox.onDidTriggerButton(button => {
if (button === backButton) {
done('back');
}
}));
inputDisposables.add(inputBox.onDidHide(() => {
done(undefined);
}));
inputBox.show();
});
if (fileNameResult === 'back') {
// Re-show the picker for the previous step
picker.show();
step = goBack() ?? Step.SelectFolder;
break;
}
if (!fileNameResult) {
store.dispose();
return;
}
// Create the hooks folder if it doesn't exist
await fileService.createFolder(selectedFolder!.uri);
// Use user-provided filename with .json extension
const hookFileName = fileNameResult.endsWith('.json') ? fileNameResult : `${fileNameResult}.json`;
const hookFileUri = URI.joinPath(selectedFolder!.uri, hookFileName);
// Check if file already exists
if (await fileService.exists(hookFileUri)) {
// File exists - add hook to it instead of creating new
store.dispose();
await addHookToFile(
hookFileUri,
selectedHookType!.hookType,
fileService,
editorService,
notificationService,
bulkEditService,
options?.openEditor,
);
return;
}
// Detect if new file is a Claude hooks file based on its path
const newFileFormat = getHookSourceFormat(hookFileUri);
const isClaudeNewFile = newFileFormat === HookSourceFormat.Claude;
const isCopilotCliOnly = !isClaudeNewFile
&& !new Set(Object.values(HOOKS_BY_TARGET[Target.VSCode])).has(selectedHookType!.hookType)
&& new Set(Object.values(HOOKS_BY_TARGET[Target.GitHubCopilot])).has(selectedHookType!.hookType);
const hookTypeKey = isClaudeNewFile
? (getClaudeHookTypeName(selectedHookType!.hookType) ?? selectedHookType!.hookType)
: isCopilotCliOnly
? (getCopilotCliHookTypeName(selectedHookType!.hookType) ?? selectedHookType!.hookType)
: selectedHookType!.hookType;
const newFileHookEntry = isCopilotCliOnly
? { type: 'command', [targetOS === OperatingSystem.Windows ? 'powershell' : 'bash']: '' }
: buildNewHookEntry(newFileFormat);
const commandFieldKey = isCopilotCliOnly
? (targetOS === OperatingSystem.Windows ? 'powershell' : 'bash')
: 'command';
// Create new hook file with the selected hook type
const hooksContent: Record<string, unknown> = {
...(isCopilotCliOnly ? { version: 1 } : {}),
hooks: {
[hookTypeKey]: [
newFileHookEntry
]
}
};
const jsonContent = JSON.stringify(hooksContent, null, '\t');
await fileService.writeFile(hookFileUri, VSBuffer.fromString(jsonContent));
options?.onHookFileCreated?.(hookFileUri);
// Find the selection for the new hook's command field
const selection = findHookCommandSelection(jsonContent, hookTypeKey, 0, commandFieldKey);
// Open editor with selection
store.dispose();
if (options?.openEditor) {
await options.openEditor(hookFileUri, { selection });
} else {
await editorService.openEditor({
resource: hookFileUri,
options: {
selection,
pinned: false
}
});
}
return;
}
}
}
}
class ManageHooksAction extends Action2 {
constructor() {
super({
id: CONFIGURE_HOOKS_ACTION_ID,
title: localize2('configure-hooks', "Configure Hooks..."),
shortTitle: localize2('configure-hooks.short', "Hooks"),
icon: Codicon.zap,
f1: true,
precondition: ChatContextKeys.enabled,
category: CHAT_CATEGORY,
menu: {
id: CHAT_CONFIG_MENU_ID,
when: ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.equals('view', ChatViewId)),
order: 12,
group: '1_level'
}
});
}
public override async run(
accessor: ServicesAccessor,
): Promise<void> {
return showConfigureHooksQuickPick(accessor);
}
}
/**
* Helper to register the `Manage Hooks` action.
*/
export function registerHookActions(): void {
registerAction2(ManageHooksAction);
}