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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type React from 'react';
import { ToolMessage, type ToolMessageProps } from './ToolMessage.js';
import { describe, it, expect, vi } from 'vitest';
import { StreamingState } from '../../types.js';
import { Text } from 'ink';
import {
  type AnsiOutput,
  CoreToolCallStatus,
  Kind,
  makeFakeConfig,
} from '@google/gemini-cli-core';
import { renderWithProviders } from '../../../test-utils/render.js';
import { createMockSettings } from '../../../test-utils/settings.js';
import { tryParseJSON } from '../../../utils/jsonoutput.js';

vi.mock('../GeminiRespondingSpinner.js', () => ({
  GeminiRespondingSpinner: () => <Text>MockRespondingSpinner</Text>,
}));

vi.mock('../TerminalOutput.js', () => ({
  TerminalOutput: function MockTerminalOutput({
    cursor,
  }: {
    cursor: { x: number; y: number } | null;
  }) {
    return (
      <Text>
        MockCursor:({cursor?.x},{cursor?.y})
      </Text>
    );
  },
}));

describe('<ToolMessage />', () => {
  const baseProps: ToolMessageProps = {
    callId: 'tool-123',
    name: 'test-tool',
    description: 'A tool for testing',
    resultDisplay: 'Test result',
    status: CoreToolCallStatus.Success,
    terminalWidth: 80,
    confirmationDetails: undefined,
    emphasis: 'medium',
    isFirst: true,
    borderColor: 'green',
    borderDimColor: false,
  };

  const mockSetEmbeddedShellFocused = vi.fn();
  const uiActions = {
    setEmbeddedShellFocused: mockSetEmbeddedShellFocused,
  };

  // Helper to render with context
  const renderWithContext = async (
    ui: React.ReactElement,
    streamingState: StreamingState,
  ) =>
    renderWithProviders(ui, {
      uiActions,
      uiState: { streamingState },
      width: 80,
    });

  beforeEach(() => {
    vi.clearAllMocks();
    vi.useFakeTimers();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it('renders basic tool information', async () => {
    const { lastFrame, unmount } = await renderWithContext(
      <ToolMessage {...baseProps} />,
      StreamingState.Idle,
    );
    const output = lastFrame();
    expect(output).toMatchSnapshot();
    unmount();
  });

  describe('JSON rendering', () => {
    it('pretty prints valid JSON', async () => {
      const testJSONstring = '{"a": 1, "b": [2, 3]}';
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage
          {...baseProps}
          resultDisplay={testJSONstring}
          renderOutputAsMarkdown={false}
        />,
        StreamingState.Idle,
      );

      const output = lastFrame();

      // Verify the JSON utility correctly parses the input
      expect(tryParseJSON(testJSONstring)).toBeTruthy();
      // Verify pretty-printed JSON appears in output (with proper indentation)
      expect(output).toContain('"a": 1');
      expect(output).toContain('"b": [');
      // Should not use markdown renderer for JSON
      unmount();
    });

    it('renders pretty JSON in ink frame', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} resultDisplay='{"a":1,"b":2}' />,
        StreamingState.Idle,
      );

      const frame = lastFrame();

      expect(frame).toMatchSnapshot();
      unmount();
    });

    it('uses JSON renderer even when renderOutputAsMarkdown=true is true', async () => {
      const testJSONstring = '{"a": 1, "b": [2, 3]}';
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage
          {...baseProps}
          resultDisplay={testJSONstring}
          renderOutputAsMarkdown={true}
        />,
        StreamingState.Idle,
      );

      const output = lastFrame();

      // Verify the JSON utility correctly parses the input
      expect(tryParseJSON(testJSONstring)).toBeTruthy();
      // Verify pretty-printed JSON appears in output
      expect(output).toContain('"a": 1');
      expect(output).toContain('"b": [');
      // Should not use markdown renderer for JSON even when renderOutputAsMarkdown=true
      unmount();
    });
    it('falls back to plain text for malformed JSON', async () => {
      const testJSONstring = 'a": 1, "b": [2, 3]}';
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage
          {...baseProps}
          resultDisplay={testJSONstring}
          renderOutputAsMarkdown={false}
        />,
        StreamingState.Idle,
      );

      const output = lastFrame();

      expect(tryParseJSON(testJSONstring)).toBeFalsy();
      expect(typeof output === 'string').toBeTruthy();
      unmount();
    });

    it('rejects mixed text + JSON renders as plain text', async () => {
      const testJSONstring = `{"result":  "count": 42,"items": ["apple", "banana"]},"meta": {"timestamp": "2025-09-28T12:34:56Z"}}End.`;
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage
          {...baseProps}
          resultDisplay={testJSONstring}
          renderOutputAsMarkdown={false}
        />,
        StreamingState.Idle,
      );

      const output = lastFrame();

      expect(tryParseJSON(testJSONstring)).toBeFalsy();
      expect(typeof output === 'string').toBeTruthy();
      unmount();
    });

    it('rejects ANSI-tained JSON renders as plain text', async () => {
      const testJSONstring =
        '\u001b[32mOK\u001b[0m {"status": "success", "data": {"id": 123, "values": [10, 20, 30]}}';
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage
          {...baseProps}
          resultDisplay={testJSONstring}
          renderOutputAsMarkdown={false}
        />,
        StreamingState.Idle,
      );

      const output = lastFrame();

      expect(tryParseJSON(testJSONstring)).toBeFalsy();
      expect(typeof output === 'string').toBeTruthy();
      unmount();
    });

    it('pretty printing 10kb JSON completes in <50ms', async () => {
      const large = '{"key": "' + 'x'.repeat(10000) + '"}';
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage
          {...baseProps}
          resultDisplay={large}
          renderOutputAsMarkdown={false}
        />,
        StreamingState.Idle,
      );

      const start = performance.now();
      lastFrame();
      expect(performance.now() - start).toBeLessThan(50);
      unmount();
    });
  });

  describe('ToolStatusIndicator rendering', () => {
    it('shows ✓ for Success status', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} status={CoreToolCallStatus.Success} />,
        StreamingState.Idle,
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });

    it('shows o for Pending status', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} status={CoreToolCallStatus.Scheduled} />,
        StreamingState.Idle,
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });

    it('shows ? for Confirming status', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage
          {...baseProps}
          status={CoreToolCallStatus.AwaitingApproval}
        />,
        StreamingState.Idle,
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });

    it('shows - for Canceled status', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} status={CoreToolCallStatus.Cancelled} />,
        StreamingState.Idle,
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });

    it('shows x for Error status', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} status={CoreToolCallStatus.Error} />,
        StreamingState.Idle,
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });

    it('shows paused spinner for Executing status when streamingState is Idle', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} status={CoreToolCallStatus.Executing} />,
        StreamingState.Idle,
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });

    it('shows paused spinner for Executing status when streamingState is WaitingForConfirmation', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} status={CoreToolCallStatus.Executing} />,
        StreamingState.WaitingForConfirmation,
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });

    it('shows MockRespondingSpinner for Executing status when streamingState is Responding', async () => {
      const { lastFrame, unmount } = await renderWithContext(
        <ToolMessage {...baseProps} status={CoreToolCallStatus.Executing} />,
        StreamingState.Responding, // Simulate app still responding
      );
      expect(lastFrame()).toMatchSnapshot();
      unmount();
    });
  });

  it('renders DiffRenderer for diff results', async () => {
    const diffResult = {
      fileDiff: '--- a/file.txt\n+++ b/file.txt\n@@ -1 +1 @@\n-old\n+new',
      fileName: 'file.txt',
      originalContent: 'old',
      newContent: 'new',
      filePath: 'file.txt',
    };
    const { lastFrame, unmount } = await renderWithContext(
      <ToolMessage {...baseProps} resultDisplay={diffResult} />,
      StreamingState.Idle,
    );
    // Check that the output contains the MockDiff content as part of the whole message
    expect(lastFrame()).toMatchSnapshot();
    unmount();
  });

  it('renders emphasis correctly', async () => {
    const {
      lastFrame: highEmphasisFrame,
      waitUntilReady: waitUntilReadyHigh,
      unmount: unmountHigh,
    } = await renderWithContext(
      <ToolMessage {...baseProps} emphasis="high" />,
      StreamingState.Idle,
    );
    await waitUntilReadyHigh();
    // Check for trailing indicator or specific color if applicable (Colors are not easily testable here)
    expect(highEmphasisFrame()).toMatchSnapshot();
    unmountHigh();

    const {
      lastFrame: lowEmphasisFrame,
      waitUntilReady: waitUntilReadyLow,
      unmount: unmountLow,
    } = await renderWithContext(
      <ToolMessage {...baseProps} emphasis="low" />,
      StreamingState.Idle,
    );
    await waitUntilReadyLow();
    // For low emphasis, the name and description might be dimmed (check for dimColor if possible)
    // This is harder to assert directly in text output without color checks.
    // We can at least ensure it doesn't have the high emphasis indicator.
    expect(lowEmphasisFrame()).toMatchSnapshot();
    unmountLow();
  });

  it('renders AnsiOutputText for AnsiOutput results', async () => {
    const ansiResult: AnsiOutput = [
      [
        {
          text: 'hello',
          fg: '#ffffff',
          bg: '#000000',
          bold: false,
          italic: false,
          underline: false,
          dim: false,
          inverse: false,
          isUninitialized: false,
        },
      ],
    ];
    const { lastFrame, unmount } = await renderWithContext(
      <ToolMessage {...baseProps} resultDisplay={ansiResult} />,
      StreamingState.Idle,
    );
    expect(lastFrame()).toMatchSnapshot();
    unmount();
  });

  it('renders McpProgressIndicator with percentage and message for executing tools', async () => {
    const { lastFrame, unmount } = await renderWithContext(
      <ToolMessage
        {...baseProps}
        status={CoreToolCallStatus.Executing}
        progress={42}
        progressTotal={100}
        progressMessage="Working on it..."
      />,
      StreamingState.Responding,
    );
    const output = lastFrame();
    expect(output).toContain('42%');
    expect(output).toContain('Working on it...');
    expect(output).toContain('\u2588');
    expect(output).toContain('\u2591');
    expect(output).not.toContain('A tool for testing (Working on it... - 42%)');
    expect(output).toMatchSnapshot();
    unmount();
  });

  it('renders only percentage when progressMessage is missing', async () => {
    const { lastFrame, unmount } = await renderWithContext(
      <ToolMessage
        {...baseProps}
        status={CoreToolCallStatus.Executing}
        progress={75}
        progressTotal={100}
      />,
      StreamingState.Responding,
    );
    const output = lastFrame();
    expect(output).toContain('75%');
    expect(output).toContain('\u2588');
    expect(output).toContain('\u2591');
    expect(output).not.toContain('A tool for testing (75%)');
    expect(output).toMatchSnapshot();
    unmount();
  });

  it('renders indeterminate progress when total is missing', async () => {
    const { lastFrame, unmount } = await renderWithContext(
      <ToolMessage
        {...baseProps}
        status={CoreToolCallStatus.Executing}
        progress={7}
      />,
      StreamingState.Responding,
    );
    const output = lastFrame();
    expect(output).toContain('7');
    expect(output).toContain('\u2588');
    expect(output).toContain('\u2591');
    expect(output).not.toContain('%');
    expect(output).toMatchSnapshot();
    unmount();
  });

  describe('Truncation', () => {
    it('applies truncation for Kind.Agent when availableTerminalHeight is provided', async () => {
      const multilineString = Array.from(
        { length: 30 },
        (_, i) => `Line ${i + 1}`,
      ).join('\n');

      const { lastFrame, unmount } = await renderWithProviders(
        <ToolMessage
          {...baseProps}
          kind={Kind.Agent}
          resultDisplay={multilineString}
          renderOutputAsMarkdown={false}
          availableTerminalHeight={40}
        />,
        {
          uiActions,
          uiState: {
            streamingState: StreamingState.Idle,
            constrainHeight: true,
          },
          width: 80,
          config: makeFakeConfig({ useAlternateBuffer: true }),
          settings: createMockSettings({ ui: { useAlternateBuffer: true } }),
        },
      );
      const output = lastFrame();

      // Since kind=Kind.Agent and availableTerminalHeight is provided, it should truncate to SUBAGENT_MAX_LINES (15)
      // It should constrain the height, showing the tail of the output (overflowDirection='top' or due to scroll)
      expect(output).not.toMatch(/Line 1\b/);
      expect(output).not.toMatch(/Line 14\b/);
      expect(output).toMatch(/Line 16\b/);
      expect(output).toMatch(/Line 30\b/);
      unmount();
    });

    it('does NOT apply truncation for Kind.Agent when availableTerminalHeight is undefined', async () => {
      const multilineString = Array.from(
        { length: 30 },
        (_, i) => `Line ${i + 1}`,
      ).join('\n');

      const { lastFrame, unmount } = await renderWithProviders(
        <ToolMessage
          {...baseProps}
          kind={Kind.Agent}
          resultDisplay={multilineString}
          renderOutputAsMarkdown={false}
          availableTerminalHeight={undefined}
        />,
        {
          uiActions,
          uiState: { streamingState: StreamingState.Idle },
          width: 80,
          config: makeFakeConfig({ useAlternateBuffer: false }),
          settings: createMockSettings({ ui: { useAlternateBuffer: false } }),
        },
      );
      const output = lastFrame();

      expect(output).toContain('Line 1');
      expect(output).toContain('Line 30');
      unmount();
    });

    it('does NOT apply truncation for Kind.Read', async () => {
      const multilineString = Array.from(
        { length: 30 },
        (_, i) => `Line ${i + 1}`,
      ).join('\n');

      const { lastFrame, unmount } = await renderWithProviders(
        <ToolMessage
          {...baseProps}
          kind={Kind.Read}
          resultDisplay={multilineString}
          renderOutputAsMarkdown={false}
        />,
        {
          uiActions,
          uiState: { streamingState: StreamingState.Idle },
          width: 80,
          config: makeFakeConfig({ useAlternateBuffer: false }),
          settings: createMockSettings({ ui: { useAlternateBuffer: false } }),
        },
      );
      const output = lastFrame();

      expect(output).toContain('Line 1');
      expect(output).toContain('Line 30');
      unmount();
    });
  });
});