mirror of
https://github.com/google-gemini/gemini-cli.git
synced 2026-07-11 18:40:57 -07:00
Merge branch 'main' into fix/headless-log
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
- Always fix react-hooks/exhaustive-deps lint errors by adding the missing
|
||||
dependencies.
|
||||
- **Shortcuts**: only define keyboard shortcuts in
|
||||
`packages/cli/src/config/keyBindings.ts`
|
||||
`packages/cli/src/ui/key/keyBindings.ts`
|
||||
- Do not implement any logic performing custom string measurement or string
|
||||
truncation. Use Ink layout instead leveraging ResizeObserver as needed.
|
||||
- Avoid prop drilling when at all possible.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@google/gemini-cli",
|
||||
"version": "0.35.0-nightly.20260313.bb060d7a9",
|
||||
"version": "0.36.0-nightly.20260317.2f90b4653",
|
||||
"description": "Gemini CLI",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
@@ -26,7 +26,7 @@
|
||||
"dist"
|
||||
],
|
||||
"config": {
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.35.0-nightly.20260313.bb060d7a9"
|
||||
"sandboxImageUri": "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.36.0-nightly.20260317.2f90b4653"
|
||||
},
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.12.0",
|
||||
|
||||
@@ -3347,7 +3347,10 @@ describe('Policy Engine Integration in loadCliConfig', () => {
|
||||
|
||||
expect(ServerConfig.createPolicyEngineConfig).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
policyPaths: ['/path/to/policy1.toml', '/path/to/policy2.toml'],
|
||||
policyPaths: [
|
||||
path.normalize('/path/to/policy1.toml'),
|
||||
path.normalize('/path/to/policy2.toml'),
|
||||
],
|
||||
}),
|
||||
expect.anything(),
|
||||
);
|
||||
|
||||
@@ -244,10 +244,11 @@ export async function parseArguments(
|
||||
// When --resume passed without a value (`gemini --resume`): value = "" (string)
|
||||
// When --resume not passed at all: this `coerce` function is not called at all, and
|
||||
// `yargsInstance.argv.resume` is undefined.
|
||||
if (value === '') {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed === '') {
|
||||
return RESUME_LATEST;
|
||||
}
|
||||
return value;
|
||||
return trimmed;
|
||||
},
|
||||
})
|
||||
.option('list-sessions', {
|
||||
@@ -650,8 +651,12 @@ export async function loadCliConfig(
|
||||
...settings.mcp,
|
||||
allowed: argv.allowedMcpServerNames ?? settings.mcp?.allowed,
|
||||
},
|
||||
policyPaths: argv.policy ?? settings.policyPaths,
|
||||
adminPolicyPaths: argv.adminPolicy ?? settings.adminPolicyPaths,
|
||||
policyPaths: (argv.policy ?? settings.policyPaths)?.map((p) =>
|
||||
resolvePath(p),
|
||||
),
|
||||
adminPolicyPaths: (argv.adminPolicy ?? settings.adminPolicyPaths)?.map(
|
||||
(p) => resolvePath(p),
|
||||
),
|
||||
};
|
||||
|
||||
const { workspacePoliciesDir, policyUpdateConfirmationRequest } =
|
||||
|
||||
@@ -1053,6 +1053,34 @@ const SETTINGS_SCHEMA = {
|
||||
ref: 'ModelDefinition',
|
||||
},
|
||||
},
|
||||
modelIdResolutions: {
|
||||
type: 'object',
|
||||
label: 'Model ID Resolutions',
|
||||
category: 'Model',
|
||||
requiresRestart: true,
|
||||
default: DEFAULT_MODEL_CONFIGS.modelIdResolutions,
|
||||
description:
|
||||
'Rules for resolving requested model names to concrete model IDs based on context.',
|
||||
showInDialog: false,
|
||||
additionalProperties: {
|
||||
type: 'object',
|
||||
ref: 'ModelResolution',
|
||||
},
|
||||
},
|
||||
classifierIdResolutions: {
|
||||
type: 'object',
|
||||
label: 'Classifier ID Resolutions',
|
||||
category: 'Model',
|
||||
requiresRestart: true,
|
||||
default: DEFAULT_MODEL_CONFIGS.classifierIdResolutions,
|
||||
description:
|
||||
'Rules for resolving classifier tiers (flash, pro) to concrete model IDs.',
|
||||
showInDialog: false,
|
||||
additionalProperties: {
|
||||
type: 'object',
|
||||
ref: 'ModelResolution',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -2800,7 +2828,7 @@ export const SETTINGS_SCHEMA_DEFINITIONS: Record<
|
||||
tier: { enum: ['pro', 'flash', 'flash-lite', 'custom', 'auto'] },
|
||||
family: { type: 'string' },
|
||||
isPreview: { type: 'boolean' },
|
||||
dialogLocation: { enum: ['main', 'manual'] },
|
||||
isVisible: { type: 'boolean' },
|
||||
dialogDescription: { type: 'string' },
|
||||
features: {
|
||||
type: 'object',
|
||||
@@ -2811,6 +2839,34 @@ export const SETTINGS_SCHEMA_DEFINITIONS: Record<
|
||||
},
|
||||
},
|
||||
},
|
||||
ModelResolution: {
|
||||
type: 'object',
|
||||
description: 'Model resolution rule.',
|
||||
properties: {
|
||||
default: { type: 'string' },
|
||||
contexts: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
condition: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
useGemini3_1: { type: 'boolean' },
|
||||
useCustomTools: { type: 'boolean' },
|
||||
hasAccessToPreview: { type: 'boolean' },
|
||||
requestedModels: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
target: { type: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function getSettingsSchema(): SettingsSchemaType {
|
||||
|
||||
@@ -649,7 +649,7 @@ export async function main() {
|
||||
process.exit(ExitCodes.FATAL_INPUT_ERROR);
|
||||
}
|
||||
|
||||
const prompt_id = Math.random().toString(16).slice(2);
|
||||
const prompt_id = sessionId;
|
||||
logUserPrompt(
|
||||
config,
|
||||
new UserPromptEvent(
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
* Creates a mocked Config object with default values and allows overrides.
|
||||
*/
|
||||
export const createMockConfig = (overrides: Partial<Config> = {}): Config =>
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
||||
({
|
||||
getSandbox: vi.fn(() => undefined),
|
||||
getQuestion: vi.fn(() => ''),
|
||||
@@ -79,6 +78,8 @@ export const createMockConfig = (overrides: Partial<Config> = {}): Config =>
|
||||
getFileService: vi.fn().mockReturnValue({}),
|
||||
getGitService: vi.fn().mockResolvedValue({}),
|
||||
getUserMemory: vi.fn().mockReturnValue(''),
|
||||
getSystemInstructionMemory: vi.fn().mockReturnValue(''),
|
||||
getSessionMemory: vi.fn().mockReturnValue(''),
|
||||
getGeminiMdFilePaths: vi.fn().mockReturnValue([]),
|
||||
getShowMemoryUsage: vi.fn().mockReturnValue(false),
|
||||
getAccessibility: vi.fn().mockReturnValue({}),
|
||||
@@ -182,11 +183,9 @@ export function createMockSettings(
|
||||
overrides: Record<string, unknown> = {},
|
||||
): LoadedSettings {
|
||||
const merged = createTestMergedSettings(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
||||
(overrides['merged'] as Partial<Settings>) || {},
|
||||
);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
|
||||
return {
|
||||
system: { settings: {} },
|
||||
systemDefaults: { settings: {} },
|
||||
|
||||
@@ -579,6 +579,47 @@ describe('textBufferReducer', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('kill_line_left action', () => {
|
||||
it('should clean up pastedContent when deleting a placeholder line-left', () => {
|
||||
const placeholder = '[Pasted Text: 6 lines]';
|
||||
const stateWithPlaceholder = createStateWithTransformations({
|
||||
lines: [placeholder],
|
||||
cursorRow: 0,
|
||||
cursorCol: cpLen(placeholder),
|
||||
pastedContent: {
|
||||
[placeholder]: 'line1\nline2\nline3\nline4\nline5\nline6',
|
||||
},
|
||||
});
|
||||
|
||||
const state = textBufferReducer(stateWithPlaceholder, {
|
||||
type: 'kill_line_left',
|
||||
});
|
||||
|
||||
expect(state.lines).toEqual(['']);
|
||||
expect(state.cursorCol).toBe(0);
|
||||
expect(Object.keys(state.pastedContent)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('kill_line_right action', () => {
|
||||
it('should reset preferredCol when deleting to end of line', () => {
|
||||
const stateWithText: TextBufferState = {
|
||||
...initialState,
|
||||
lines: ['hello world'],
|
||||
cursorRow: 0,
|
||||
cursorCol: 5,
|
||||
preferredCol: 9,
|
||||
};
|
||||
|
||||
const state = textBufferReducer(stateWithText, {
|
||||
type: 'kill_line_right',
|
||||
});
|
||||
|
||||
expect(state.lines).toEqual(['hello']);
|
||||
expect(state.preferredCol).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toggle_paste_expansion action', () => {
|
||||
const placeholder = '[Pasted Text: 6 lines]';
|
||||
const content = 'line1\nline2\nline3\nline4\nline5\nline6';
|
||||
@@ -937,6 +978,107 @@ describe('useTextBuffer', () => {
|
||||
expect(Object.keys(result.current.pastedContent)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('deleteWordLeft: should clean up pastedContent and avoid #2 suffix on repaste', () => {
|
||||
const { result } = renderHook(() => useTextBuffer({ viewport }));
|
||||
const largeText = '1\n2\n3\n4\n5\n6';
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toBe('[Pasted Text: 6 lines]');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
|
||||
act(() => {
|
||||
for (let i = 0; i < 12; i++) {
|
||||
result.current.deleteWordLeft();
|
||||
}
|
||||
});
|
||||
expect(getBufferState(result).text).toBe('');
|
||||
expect(Object.keys(result.current.pastedContent)).toHaveLength(0);
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toBe('[Pasted Text: 6 lines]');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
});
|
||||
|
||||
it('deleteWordRight: should clean up pastedContent and avoid #2 suffix on repaste', () => {
|
||||
const { result } = renderHook(() => useTextBuffer({ viewport }));
|
||||
const largeText = '1\n2\n3\n4\n5\n6';
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toBe('[Pasted Text: 6 lines]');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
|
||||
act(() => result.current.move('home'));
|
||||
act(() => {
|
||||
for (let i = 0; i < 12; i++) {
|
||||
result.current.deleteWordRight();
|
||||
}
|
||||
});
|
||||
expect(getBufferState(result).text).not.toContain(
|
||||
'[Pasted Text: 6 lines]',
|
||||
);
|
||||
expect(Object.keys(result.current.pastedContent)).toHaveLength(0);
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toContain('[Pasted Text: 6 lines]');
|
||||
expect(getBufferState(result).text).not.toContain('#2');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
});
|
||||
|
||||
it('killLineLeft: should clean up pastedContent and avoid #2 suffix on repaste', () => {
|
||||
const { result } = renderHook(() => useTextBuffer({ viewport }));
|
||||
const largeText = '1\n2\n3\n4\n5\n6';
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toBe('[Pasted Text: 6 lines]');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
|
||||
act(() => result.current.killLineLeft());
|
||||
expect(getBufferState(result).text).toBe('');
|
||||
expect(Object.keys(result.current.pastedContent)).toHaveLength(0);
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toBe('[Pasted Text: 6 lines]');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
});
|
||||
|
||||
it('killLineRight: should clean up pastedContent and avoid #2 suffix on repaste', () => {
|
||||
const { result } = renderHook(() => useTextBuffer({ viewport }));
|
||||
const largeText = '1\n2\n3\n4\n5\n6';
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toBe('[Pasted Text: 6 lines]');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
|
||||
act(() => {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
result.current.move('left');
|
||||
}
|
||||
});
|
||||
act(() => result.current.killLineRight());
|
||||
expect(getBufferState(result).text).toBe('');
|
||||
expect(Object.keys(result.current.pastedContent)).toHaveLength(0);
|
||||
|
||||
act(() => result.current.insert(largeText, { paste: true }));
|
||||
expect(getBufferState(result).text).toBe('[Pasted Text: 6 lines]');
|
||||
expect(result.current.pastedContent['[Pasted Text: 6 lines]']).toBe(
|
||||
largeText,
|
||||
);
|
||||
});
|
||||
|
||||
it('newline: should create a new line and move cursor', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useTextBuffer({
|
||||
|
||||
@@ -1609,6 +1609,47 @@ function generatePastedTextId(
|
||||
return id;
|
||||
}
|
||||
|
||||
function collectPlaceholderIdsFromLines(lines: string[]): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
const pasteRegex = new RegExp(PASTED_TEXT_PLACEHOLDER_REGEX.source, 'g');
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
for (const match of line.matchAll(pasteRegex)) {
|
||||
const placeholderId = match[0];
|
||||
if (placeholderId) {
|
||||
ids.add(placeholderId);
|
||||
}
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function pruneOrphanedPastedContent(
|
||||
pastedContent: Record<string, string>,
|
||||
expandedPasteId: string | null,
|
||||
beforeChangedLines: string[],
|
||||
allLines: string[],
|
||||
): Record<string, string> {
|
||||
if (Object.keys(pastedContent).length === 0) return pastedContent;
|
||||
|
||||
const beforeIds = collectPlaceholderIdsFromLines(beforeChangedLines);
|
||||
if (beforeIds.size === 0) return pastedContent;
|
||||
|
||||
const afterIds = collectPlaceholderIdsFromLines(allLines);
|
||||
const removedIds = [...beforeIds].filter(
|
||||
(id) => !afterIds.has(id) && id !== expandedPasteId,
|
||||
);
|
||||
if (removedIds.length === 0) return pastedContent;
|
||||
|
||||
const pruned = { ...pastedContent };
|
||||
for (const id of removedIds) {
|
||||
if (pruned[id]) {
|
||||
delete pruned[id];
|
||||
}
|
||||
}
|
||||
return pruned;
|
||||
}
|
||||
|
||||
export type TextBufferAction =
|
||||
| { type: 'insert'; payload: string; isPaste?: boolean }
|
||||
| {
|
||||
@@ -2260,9 +2301,11 @@ function textBufferReducerLogic(
|
||||
const newLines = [...nextState.lines];
|
||||
let newCursorRow = cursorRow;
|
||||
let newCursorCol = cursorCol;
|
||||
let beforeChangedLines: string[] = [];
|
||||
|
||||
if (newCursorCol > 0) {
|
||||
const lineContent = currentLine(newCursorRow);
|
||||
beforeChangedLines = [lineContent];
|
||||
const prevWordStart = findPrevWordStartInLine(
|
||||
lineContent,
|
||||
newCursorCol,
|
||||
@@ -2275,6 +2318,7 @@ function textBufferReducerLogic(
|
||||
// Act as a backspace
|
||||
const prevLineContent = currentLine(cursorRow - 1);
|
||||
const currentLineContentVal = currentLine(cursorRow);
|
||||
beforeChangedLines = [prevLineContent, currentLineContentVal];
|
||||
const newCol = cpLen(prevLineContent);
|
||||
newLines[cursorRow - 1] = prevLineContent + currentLineContentVal;
|
||||
newLines.splice(cursorRow, 1);
|
||||
@@ -2282,12 +2326,20 @@ function textBufferReducerLogic(
|
||||
newCursorCol = newCol;
|
||||
}
|
||||
|
||||
const newPastedContent = pruneOrphanedPastedContent(
|
||||
nextState.pastedContent,
|
||||
nextState.expandedPaste?.id ?? null,
|
||||
beforeChangedLines,
|
||||
newLines,
|
||||
);
|
||||
|
||||
return {
|
||||
...nextState,
|
||||
lines: newLines,
|
||||
cursorRow: newCursorRow,
|
||||
cursorCol: newCursorCol,
|
||||
preferredCol: null,
|
||||
pastedContent: newPastedContent,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2304,23 +2356,34 @@ function textBufferReducerLogic(
|
||||
|
||||
const nextState = currentState;
|
||||
const newLines = [...nextState.lines];
|
||||
let beforeChangedLines: string[] = [];
|
||||
|
||||
if (cursorCol >= lineLen) {
|
||||
// Act as a delete, joining with the next line
|
||||
const nextLineContent = currentLine(cursorRow + 1);
|
||||
beforeChangedLines = [lineContent, nextLineContent];
|
||||
newLines[cursorRow] = lineContent + nextLineContent;
|
||||
newLines.splice(cursorRow + 1, 1);
|
||||
} else {
|
||||
beforeChangedLines = [lineContent];
|
||||
const nextWordStart = findNextWordStartInLine(lineContent, cursorCol);
|
||||
const end = nextWordStart === null ? lineLen : nextWordStart;
|
||||
newLines[cursorRow] =
|
||||
cpSlice(lineContent, 0, cursorCol) + cpSlice(lineContent, end);
|
||||
}
|
||||
|
||||
const newPastedContent = pruneOrphanedPastedContent(
|
||||
nextState.pastedContent,
|
||||
nextState.expandedPaste?.id ?? null,
|
||||
beforeChangedLines,
|
||||
newLines,
|
||||
);
|
||||
|
||||
return {
|
||||
...nextState,
|
||||
lines: newLines,
|
||||
preferredCol: null,
|
||||
pastedContent: newPastedContent,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2332,22 +2395,39 @@ function textBufferReducerLogic(
|
||||
if (cursorCol < currentLineLen(cursorRow)) {
|
||||
const nextState = currentState;
|
||||
const newLines = [...nextState.lines];
|
||||
const beforeChangedLines = [lineContent];
|
||||
newLines[cursorRow] = cpSlice(lineContent, 0, cursorCol);
|
||||
const newPastedContent = pruneOrphanedPastedContent(
|
||||
nextState.pastedContent,
|
||||
nextState.expandedPaste?.id ?? null,
|
||||
beforeChangedLines,
|
||||
newLines,
|
||||
);
|
||||
return {
|
||||
...nextState,
|
||||
lines: newLines,
|
||||
preferredCol: null,
|
||||
pastedContent: newPastedContent,
|
||||
};
|
||||
} else if (cursorRow < lines.length - 1) {
|
||||
// Act as a delete
|
||||
const nextState = currentState;
|
||||
const nextLineContent = currentLine(cursorRow + 1);
|
||||
const newLines = [...nextState.lines];
|
||||
const beforeChangedLines = [lineContent, nextLineContent];
|
||||
newLines[cursorRow] = lineContent + nextLineContent;
|
||||
newLines.splice(cursorRow + 1, 1);
|
||||
const newPastedContent = pruneOrphanedPastedContent(
|
||||
nextState.pastedContent,
|
||||
nextState.expandedPaste?.id ?? null,
|
||||
beforeChangedLines,
|
||||
newLines,
|
||||
);
|
||||
return {
|
||||
...nextState,
|
||||
lines: newLines,
|
||||
preferredCol: null,
|
||||
pastedContent: newPastedContent,
|
||||
};
|
||||
}
|
||||
return currentState;
|
||||
@@ -2361,12 +2441,20 @@ function textBufferReducerLogic(
|
||||
const nextState = currentState;
|
||||
const lineContent = currentLine(cursorRow);
|
||||
const newLines = [...nextState.lines];
|
||||
const beforeChangedLines = [lineContent];
|
||||
newLines[cursorRow] = cpSlice(lineContent, cursorCol);
|
||||
const newPastedContent = pruneOrphanedPastedContent(
|
||||
nextState.pastedContent,
|
||||
nextState.expandedPaste?.id ?? null,
|
||||
beforeChangedLines,
|
||||
newLines,
|
||||
);
|
||||
return {
|
||||
...nextState,
|
||||
lines: newLines,
|
||||
cursorCol: 0,
|
||||
preferredCol: null,
|
||||
pastedContent: newPastedContent,
|
||||
};
|
||||
}
|
||||
return currentState;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2026 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook } from '../../test-utils/render.js';
|
||||
import { waitFor } from '../../test-utils/async.js';
|
||||
import { useLogger } from './useLogger.js';
|
||||
import {
|
||||
sessionId as globalSessionId,
|
||||
Logger,
|
||||
type Storage,
|
||||
type Config,
|
||||
} from '@google/gemini-cli-core';
|
||||
import { ConfigContext } from '../contexts/ConfigContext.js';
|
||||
import type React from 'react';
|
||||
|
||||
// Mock Logger
|
||||
vi.mock('@google/gemini-cli-core', async (importOriginal) => {
|
||||
const actual =
|
||||
await importOriginal<typeof import('@google/gemini-cli-core')>();
|
||||
return {
|
||||
...actual,
|
||||
Logger: vi.fn().mockImplementation((id: string) => ({
|
||||
initialize: vi.fn().mockResolvedValue(undefined),
|
||||
sessionId: id,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
describe('useLogger', () => {
|
||||
const mockStorage = {} as Storage;
|
||||
const mockConfig = {
|
||||
getSessionId: vi.fn().mockReturnValue('active-session-id'),
|
||||
} as unknown as Config;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should initialize with the global sessionId by default', async () => {
|
||||
const { result } = renderHook(() => useLogger(mockStorage));
|
||||
|
||||
await waitFor(() => expect(result.current).not.toBeNull());
|
||||
expect(Logger).toHaveBeenCalledWith(globalSessionId, mockStorage);
|
||||
});
|
||||
|
||||
it('should initialize with the active sessionId from ConfigContext when available', async () => {
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<ConfigContext.Provider value={mockConfig}>
|
||||
{children}
|
||||
</ConfigContext.Provider>
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useLogger(mockStorage), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current).not.toBeNull());
|
||||
expect(Logger).toHaveBeenCalledWith('active-session-id', mockStorage);
|
||||
});
|
||||
});
|
||||
@@ -4,17 +4,25 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { sessionId, Logger, type Storage } from '@google/gemini-cli-core';
|
||||
import { useState, useEffect, useContext } from 'react';
|
||||
import {
|
||||
sessionId as globalSessionId,
|
||||
Logger,
|
||||
type Storage,
|
||||
} from '@google/gemini-cli-core';
|
||||
import { ConfigContext } from '../contexts/ConfigContext.js';
|
||||
|
||||
/**
|
||||
* Hook to manage the logger instance.
|
||||
*/
|
||||
export const useLogger = (storage: Storage) => {
|
||||
export const useLogger = (storage: Storage): Logger | null => {
|
||||
const [logger, setLogger] = useState<Logger | null>(null);
|
||||
const config = useContext(ConfigContext);
|
||||
|
||||
useEffect(() => {
|
||||
const newLogger = new Logger(sessionId, storage);
|
||||
const activeSessionId = config?.getSessionId() ?? globalSessionId;
|
||||
const newLogger = new Logger(activeSessionId, storage);
|
||||
|
||||
/**
|
||||
* Start async initialization, no need to await. Using await slows down the
|
||||
* time from launch to see the gemini-cli prompt and it's better to not save
|
||||
@@ -26,7 +34,7 @@ export const useLogger = (storage: Storage) => {
|
||||
setLogger(newLogger);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [storage]);
|
||||
}, [storage, config]);
|
||||
|
||||
return logger;
|
||||
};
|
||||
|
||||
@@ -239,6 +239,44 @@ describe('SessionSelector', () => {
|
||||
expect(result.sessionData.messages[0].content).toBe('Latest session');
|
||||
});
|
||||
|
||||
it('should resolve session by UUID with whitespace (trimming)', async () => {
|
||||
const sessionId = randomUUID();
|
||||
|
||||
// Create test session files
|
||||
const chatsDir = path.join(tmpDir, 'chats');
|
||||
await fs.mkdir(chatsDir, { recursive: true });
|
||||
|
||||
const session = {
|
||||
sessionId,
|
||||
projectHash: 'test-hash',
|
||||
startTime: '2024-01-01T10:00:00.000Z',
|
||||
lastUpdated: '2024-01-01T10:30:00.000Z',
|
||||
messages: [
|
||||
{
|
||||
type: 'user',
|
||||
content: 'Test message',
|
||||
id: 'msg1',
|
||||
timestamp: '2024-01-01T10:00:00.000Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await fs.writeFile(
|
||||
path.join(
|
||||
chatsDir,
|
||||
`${SESSION_FILE_PREFIX}2024-01-01T10-00-${sessionId.slice(0, 8)}.json`,
|
||||
),
|
||||
JSON.stringify(session, null, 2),
|
||||
);
|
||||
|
||||
const sessionSelector = new SessionSelector(config);
|
||||
|
||||
// Test resolving by UUID with leading/trailing spaces
|
||||
const result = await sessionSelector.resolveSession(` ${sessionId} `);
|
||||
expect(result.sessionData.sessionId).toBe(sessionId);
|
||||
expect(result.sessionData.messages[0].content).toBe('Test message');
|
||||
});
|
||||
|
||||
it('should deduplicate sessions by ID', async () => {
|
||||
const sessionId = randomUUID();
|
||||
|
||||
|
||||
@@ -57,10 +57,14 @@ export class SessionError extends Error {
|
||||
/**
|
||||
* Creates an error for when a session identifier is invalid.
|
||||
*/
|
||||
static invalidSessionIdentifier(identifier: string): SessionError {
|
||||
static invalidSessionIdentifier(
|
||||
identifier: string,
|
||||
chatsDir?: string,
|
||||
): SessionError {
|
||||
const dirInfo = chatsDir ? ` in ${chatsDir}` : '';
|
||||
return new SessionError(
|
||||
'INVALID_SESSION_IDENTIFIER',
|
||||
`Invalid session identifier "${identifier}".\n Use --list-sessions to see available sessions, then use --resume {number}, --resume {uuid}, or --resume latest.`,
|
||||
`Invalid session identifier "${identifier}".\n Searched for sessions${dirInfo}.\n Use --list-sessions to see available sessions, then use --resume {number}, --resume {uuid}, or --resume latest.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -416,6 +420,7 @@ export class SessionSelector {
|
||||
* @throws Error if the session is not found or identifier is invalid
|
||||
*/
|
||||
async findSession(identifier: string): Promise<SessionInfo> {
|
||||
const trimmedIdentifier = identifier.trim();
|
||||
const sessions = await this.listSessions();
|
||||
|
||||
if (sessions.length === 0) {
|
||||
@@ -430,24 +435,28 @@ export class SessionSelector {
|
||||
|
||||
// Try to find by UUID first
|
||||
const sessionByUuid = sortedSessions.find(
|
||||
(session) => session.id === identifier,
|
||||
(session) => session.id === trimmedIdentifier,
|
||||
);
|
||||
if (sessionByUuid) {
|
||||
return sessionByUuid;
|
||||
}
|
||||
|
||||
// Parse as index number (1-based) - only allow numeric indexes
|
||||
const index = parseInt(identifier, 10);
|
||||
const index = parseInt(trimmedIdentifier, 10);
|
||||
if (
|
||||
!isNaN(index) &&
|
||||
index.toString() === identifier &&
|
||||
index.toString() === trimmedIdentifier &&
|
||||
index > 0 &&
|
||||
index <= sortedSessions.length
|
||||
) {
|
||||
return sortedSessions[index - 1];
|
||||
}
|
||||
|
||||
throw SessionError.invalidSessionIdentifier(identifier);
|
||||
const chatsDir = path.join(
|
||||
this.config.storage.getProjectTempDir(),
|
||||
'chats',
|
||||
);
|
||||
throw SessionError.invalidSessionIdentifier(trimmedIdentifier, chatsDir);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -458,8 +467,9 @@ export class SessionSelector {
|
||||
*/
|
||||
async resolveSession(resumeArg: string): Promise<SessionSelectionResult> {
|
||||
let selectedSession: SessionInfo;
|
||||
const trimmedResumeArg = resumeArg.trim();
|
||||
|
||||
if (resumeArg === RESUME_LATEST) {
|
||||
if (trimmedResumeArg === RESUME_LATEST) {
|
||||
const sessions = await this.listSessions();
|
||||
|
||||
if (sessions.length === 0) {
|
||||
@@ -475,7 +485,7 @@ export class SessionSelector {
|
||||
selectedSession = sessions[sessions.length - 1];
|
||||
} else {
|
||||
try {
|
||||
selectedSession = await this.findSession(resumeArg);
|
||||
selectedSession = await this.findSession(trimmedResumeArg);
|
||||
} catch (error) {
|
||||
// SessionError already has detailed messages - just rethrow
|
||||
if (error instanceof SessionError) {
|
||||
@@ -483,7 +493,7 @@ export class SessionSelector {
|
||||
}
|
||||
// Wrap unexpected errors with context
|
||||
throw new Error(
|
||||
`Failed to find session "${resumeArg}": ${error instanceof Error ? error.message : String(error)}`,
|
||||
`Failed to find session "${trimmedResumeArg}": ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user