File size: 9,425 Bytes
9332ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import * as os from 'node:os';
import * as path from 'node:path';
import * as fs from 'node:fs/promises';
import { Storage } from '@google/gemini-cli-core';
import {
  Command,
  commandCategories,
  commandDescriptions,
  defaultKeyBindingConfig,
  KeyBinding,
  loadCustomKeybindings,
} from './keyBindings.js';

describe('KeyBinding', () => {
  describe('constructor', () => {
    it('should parse a simple key', () => {
      const binding = new KeyBinding('a');
      expect(binding.name).toBe('a');
      expect(binding.ctrl).toBe(false);
      expect(binding.shift).toBe(false);
      expect(binding.alt).toBe(false);
      expect(binding.cmd).toBe(false);
    });

    it('should parse ctrl+key', () => {
      const binding = new KeyBinding('ctrl+c');
      expect(binding.name).toBe('c');
      expect(binding.ctrl).toBe(true);
    });

    it('should parse shift+key', () => {
      const binding = new KeyBinding('shift+z');
      expect(binding.name).toBe('z');
      expect(binding.shift).toBe(true);
    });

    it('should parse alt+key', () => {
      const binding = new KeyBinding('alt+left');
      expect(binding.name).toBe('left');
      expect(binding.alt).toBe(true);
    });

    it('should parse cmd+key', () => {
      const binding = new KeyBinding('cmd+f');
      expect(binding.name).toBe('f');
      expect(binding.cmd).toBe(true);
    });

    it('should handle aliases (option/opt/meta)', () => {
      const optionBinding = new KeyBinding('option+b');
      expect(optionBinding.name).toBe('b');
      expect(optionBinding.alt).toBe(true);

      const optBinding = new KeyBinding('opt+b');
      expect(optBinding.name).toBe('b');
      expect(optBinding.alt).toBe(true);

      const metaBinding = new KeyBinding('meta+enter');
      expect(metaBinding.name).toBe('enter');
      expect(metaBinding.cmd).toBe(true);
    });

    it('should parse multiple modifiers', () => {
      const binding = new KeyBinding('ctrl+shift+alt+cmd+x');
      expect(binding.name).toBe('x');
      expect(binding.ctrl).toBe(true);
      expect(binding.shift).toBe(true);
      expect(binding.alt).toBe(true);
      expect(binding.cmd).toBe(true);
    });

    it('should be case-insensitive', () => {
      const binding = new KeyBinding('CTRL+Shift+F');
      expect(binding.name).toBe('f');
      expect(binding.ctrl).toBe(true);
      expect(binding.shift).toBe(true);
    });

    it('should handle named keys with modifiers', () => {
      const binding = new KeyBinding('ctrl+enter');
      expect(binding.name).toBe('enter');
      expect(binding.ctrl).toBe(true);
    });

    it('should throw an error for invalid keys or typos in modifiers', () => {
      expect(() => new KeyBinding('ctrl+unknown')).toThrow(
        'Invalid keybinding key: "unknown" in "ctrl+unknown"',
      );
      expect(() => new KeyBinding('ctlr+a')).toThrow(
        'Invalid keybinding key: "ctlr+a" in "ctlr+a"',
      );
    });
  });
});

describe('keyBindings config', () => {
  it('should have bindings for all commands', () => {
    for (const command of Object.values(Command)) {
      expect(defaultKeyBindingConfig.has(command)).toBe(true);
      expect(defaultKeyBindingConfig.get(command)?.length).toBeGreaterThan(0);
    }
  });

  it('should have platform-specific UNDO bindings', () => {
    const undoBindings = defaultKeyBindingConfig.get(Command.UNDO);
    if (process.platform === 'win32') {
      expect(undoBindings?.[0].name).toBe('z');
      expect(undoBindings?.[0].ctrl).toBe(true);
    } else if (process.platform === 'darwin') {
      expect(undoBindings?.[0].name).toBe('z');
      expect(undoBindings?.[0].cmd).toBe(true);
    } else {
      expect(undoBindings?.[0].name).toBe('z');
      expect(undoBindings?.[0].alt).toBe(true);
      // Ensure ctrl+z is also present for smart bubbling
      expect(undoBindings?.some((b) => b.name === 'z' && b.ctrl)).toBe(true);
    }
  });

  it('should have platform-specific REDO bindings', () => {
    const redoBindings = defaultKeyBindingConfig.get(Command.REDO);
    // Ctrl+Shift+Z is now the universal primary to avoid conflict with YOLO (Ctrl+Y)
    expect(redoBindings?.[0].name).toBe('z');
    expect(redoBindings?.[0].shift).toBe(true);
    expect(redoBindings?.[0].ctrl).toBe(true);
  });

  describe('command metadata', () => {
    const commandValues = Object.values(Command);

    it('has a description entry for every command', () => {
      const describedCommands = Object.keys(commandDescriptions);
      expect(describedCommands.sort()).toEqual([...commandValues].sort());

      for (const command of commandValues) {
        expect(typeof commandDescriptions[command]).toBe('string');
        expect(commandDescriptions[command]?.trim()).not.toHaveLength(0);
      }
    });

    it('categorizes each command exactly once', () => {
      const seen = new Set<Command>();

      for (const category of commandCategories) {
        expect(typeof category.title).toBe('string');
        expect(Array.isArray(category.commands)).toBe(true);

        for (const command of category.commands) {
          expect(commandValues).toContain(command);
          expect(seen.has(command)).toBe(false);
          seen.add(command);
        }
      }

      expect(seen.size).toBe(commandValues.length);
    });
  });
});

describe('loadCustomKeybindings', () => {
  let tempDir: string;
  let tempFilePath: string;

  beforeEach(async () => {
    tempDir = await fs.mkdtemp(
      path.join(os.tmpdir(), 'gemini-keybindings-test-'),
    );
    tempFilePath = path.join(tempDir, 'keybindings.json');
    vi.spyOn(Storage, 'getUserKeybindingsPath').mockReturnValue(tempFilePath);
  });

  afterEach(async () => {
    await fs.rm(tempDir, { recursive: true, force: true });
    vi.restoreAllMocks();
  });

  it('returns default bindings when file does not exist', async () => {
    // We don't write the file.
    const { config, errors } = await loadCustomKeybindings();

    expect(errors).toHaveLength(0);
    expect(config.get(Command.RETURN)).toEqual([new KeyBinding('enter')]);
  });

  it('merges valid custom bindings, prepending them to defaults', async () => {
    const customJson = JSON.stringify([
      { command: Command.RETURN, key: 'ctrl+a' },
    ]);
    await fs.writeFile(tempFilePath, customJson, 'utf8');

    const { config, errors } = await loadCustomKeybindings();

    expect(errors).toHaveLength(0);
    expect(config.get(Command.RETURN)).toEqual([
      new KeyBinding('ctrl+a'),
      new KeyBinding('enter'),
    ]);
  });

  it('handles JSON with comments', async () => {
    const customJson = `
      [
        // This is a comment
        { "command": "${Command.QUIT}", "key": "ctrl+x" }
      ]
    `;
    await fs.writeFile(tempFilePath, customJson, 'utf8');

    const { config, errors } = await loadCustomKeybindings();

    expect(errors).toHaveLength(0);
    expect(config.get(Command.QUIT)).toEqual([
      new KeyBinding('ctrl+x'),
      new KeyBinding('ctrl+c'),
    ]);
  });

  it('returns validation errors for invalid schema', async () => {
    const invalidJson = JSON.stringify([{ command: 'unknown', key: 'a' }]);
    await fs.writeFile(tempFilePath, invalidJson, 'utf8');

    const { config, errors } = await loadCustomKeybindings();

    expect(errors.length).toBeGreaterThan(0);

    expect(errors[0]).toMatch(/error at 0.command: Invalid command: "unknown"/);
    // Should still have defaults
    expect(config.get(Command.RETURN)).toEqual([new KeyBinding('enter')]);
  });

  it('returns validation errors for invalid key patterns but loads valid ones', async () => {
    const mixedJson = JSON.stringify([
      { command: Command.RETURN, key: 'super+a' }, // invalid
      { command: Command.QUIT, key: 'ctrl+y' }, // valid
    ]);
    await fs.writeFile(tempFilePath, mixedJson, 'utf8');

    const { config, errors } = await loadCustomKeybindings();

    expect(errors.length).toBe(1);
    expect(errors[0]).toMatch(/Invalid keybinding/);
    expect(config.get(Command.QUIT)).toEqual([
      new KeyBinding('ctrl+y'),
      new KeyBinding('ctrl+c'),
    ]);
  });

  it('removes specific bindings when using the minus prefix', async () => {
    const customJson = JSON.stringify([
      { command: `-${Command.RETURN}`, key: 'enter' },
      { command: Command.RETURN, key: 'ctrl+a' },
    ]);
    await fs.writeFile(tempFilePath, customJson, 'utf8');

    const { config, errors } = await loadCustomKeybindings();

    expect(errors).toHaveLength(0);
    // 'enter' should be gone, only 'ctrl+a' should remain
    expect(config.get(Command.RETURN)).toEqual([new KeyBinding('ctrl+a')]);
  });

  it('returns an error when attempting to negate a non-existent binding', async () => {
    const customJson = JSON.stringify([
      { command: `-${Command.RETURN}`, key: 'ctrl+z' },
    ]);
    await fs.writeFile(tempFilePath, customJson, 'utf8');

    const { config, errors } = await loadCustomKeybindings();

    expect(errors.length).toBe(1);
    expect(errors[0]).toMatch(
      /Invalid keybinding for command "-basic.confirm": Error: cannot remove "ctrl\+z" since it is not bound/,
    );
    // Defaults should still be present
    expect(config.get(Command.RETURN)).toEqual([new KeyBinding('enter')]);
  });
});