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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
521
522
523
524
525
526
527
528
529
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type React from 'react';
import { useMemo, useState, useRef } from 'react';
import { Box, Text, type DOMElement } from 'ink';
import {
  CoreToolCallStatus,
  type FileDiff,
  type ListDirectoryResult,
  type ReadManyFilesResult,
  isFileDiff,
  hasSummary,
  isGrepResult,
  isListResult,
  isReadManyFilesResult,
} from '@google/gemini-cli-core';
import {
  type IndividualToolCallDisplay,
  type ToolResultDisplay,
  isTodoList,
} from '../../types.js';
import { useAlternateBuffer } from '../../hooks/useAlternateBuffer.js';
import { ToolStatusIndicator } from './ToolShared.js';
import { theme } from '../../semantic-colors.js';
import {
  DiffRenderer,
  renderDiffLines,
  isNewFile,
  parseDiffWithLineNumbers,
} from './DiffRenderer.js';
import { useMouseClick } from '../../hooks/useMouseClick.js';
import { ScrollableList } from '../shared/ScrollableList.js';
import { COMPACT_TOOL_SUBVIEW_MAX_LINES } from '../../constants.js';
import { useSettings } from '../../contexts/SettingsContext.js';
import { colorizeCode } from '../../utils/CodeColorizer.js';
import { useToolActions } from '../../contexts/ToolActionsContext.js';
import { getFileExtension } from '../../utils/fileUtils.js';

const PAYLOAD_MARGIN_LEFT = 6;
const PAYLOAD_BORDER_CHROME_WIDTH = 4; // paddingX=1 (2 cols) + borders (2 cols)
const PAYLOAD_SCROLL_GUTTER = 4;
const PAYLOAD_MAX_WIDTH = 120 + PAYLOAD_SCROLL_GUTTER;

interface DenseToolMessageProps extends IndividualToolCallDisplay {
  terminalWidth: number;
  availableTerminalHeight?: number;
}

interface ViewParts {
  // brief description of action
  description?: React.ReactNode;
  // result summary or status text
  summary?: React.ReactNode;
  // detailed output, e.g. diff or command output
  payload?: React.ReactNode;
}

interface PayloadResult {
  summary: string;
  payload: string;
}

const hasPayload = (res: unknown): res is PayloadResult => {
  if (!hasSummary(res)) return false;
  if (!('payload' in res)) return false;

  const value = (res as { payload?: unknown }).payload;
  return typeof value === 'string';
};

function getFileOpData(
  diff: FileDiff,
  status: CoreToolCallStatus,
  resultDisplay: ToolResultDisplay | undefined,
  terminalWidth: number,
  availableTerminalHeight: number | undefined,
  isClickable: boolean,
): ViewParts {
  const added =
    (diff.diffStat?.model_added_lines ?? 0) +
    (diff.diffStat?.user_added_lines ?? 0);
  const removed =
    (diff.diffStat?.model_removed_lines ?? 0) +
    (diff.diffStat?.user_removed_lines ?? 0);

  const isAcceptedOrConfirming =
    status === CoreToolCallStatus.Success ||
    status === CoreToolCallStatus.Executing ||
    status === CoreToolCallStatus.AwaitingApproval;

  const addColor = isAcceptedOrConfirming
    ? theme.status.success
    : theme.text.secondary;
  const removeColor = isAcceptedOrConfirming
    ? theme.status.error
    : theme.text.secondary;

  // Always show diff stats if available, using neutral colors for rejected
  const showDiffStat = !!diff.diffStat;

  const description = (
    <Box flexDirection="row">
      <Text color={theme.text.secondary} wrap="truncate-end">
        {diff.fileName}
      </Text>
    </Box>
  );
  let resultSummary = '';
  let resultColor = theme.text.secondary;

  if (status === CoreToolCallStatus.AwaitingApproval) {
    resultSummary = 'Confirming';
  } else if (
    status === CoreToolCallStatus.Success ||
    status === CoreToolCallStatus.Executing
  ) {
    resultSummary = 'Accepted';
    resultColor = theme.text.accent;
  } else if (status === CoreToolCallStatus.Cancelled) {
    resultSummary = 'Rejected';
    resultColor = theme.status.error;
  } else if (status === CoreToolCallStatus.Error) {
    resultSummary =
      typeof resultDisplay === 'string' ? resultDisplay : 'Failed';
    resultColor = theme.status.error;
  }

  const summary = (
    <Box flexDirection="row">
      {resultSummary && (
        <Text color={resultColor} wrap="truncate-end">
          β†’{' '}
          <Text underline={isClickable}>
            {resultSummary.replace(/\n/g, ' ')}
          </Text>
        </Text>
      )}
      {showDiffStat && (
        <Box marginLeft={1} marginRight={2}>
          <Text color={theme.text.secondary}>
            {'('}
            <Text color={addColor}>+{added}</Text>
            {', '}
            <Text color={removeColor}>-{removed}</Text>
            {')'}
          </Text>
        </Box>
      )}
    </Box>
  );

  const payload = (
    <DiffRenderer
      diffContent={diff.fileDiff}
      filename={diff.fileName}
      terminalWidth={terminalWidth - PAYLOAD_MARGIN_LEFT}
      availableTerminalHeight={availableTerminalHeight}
      disableColor={status === CoreToolCallStatus.Cancelled}
    />
  );

  return { description, summary, payload };
}

function getReadManyFilesData(result: ReadManyFilesResult): ViewParts {
  const includePatterns = result.include?.join(', ') ?? '';
  const description = (
    <Text color={theme.text.secondary} wrap="truncate-end">
      Attempting to read files from {includePatterns}
    </Text>
  );

  const skippedCount = result.skipped?.length ?? 0;
  const summaryStr = `Read ${result.files.length} file(s)${
    skippedCount > 0 ? ` (${skippedCount} ignored)` : ''
  }`;
  const summary = <Text color={theme.text.accent}>β†’ {summaryStr}</Text>;

  return { description, summary, payload: undefined };
}

function getListDirectoryData(
  result: ListDirectoryResult,
  originalDescription?: string,
): ViewParts {
  const description = originalDescription ? (
    <Text color={theme.text.secondary} wrap="truncate-end">
      {originalDescription}
    </Text>
  ) : undefined;
  const summary = <Text color={theme.text.accent}>β†’ {result.summary}</Text>;

  // For directory listings, we want NO payload in dense mode
  return { description, summary, payload: undefined };
}

function getListResultData(
  result: ListDirectoryResult | ReadManyFilesResult,
  originalDescription?: string,
): ViewParts {
  if (isReadManyFilesResult(result)) {
    return getReadManyFilesData(result);
  }
  return getListDirectoryData(result, originalDescription);
}

function getGenericSuccessData(
  resultDisplay: unknown,
  originalDescription?: string,
): ViewParts {
  let summary: React.ReactNode;
  let payload: React.ReactNode;

  const description = originalDescription ? (
    <Text color={theme.text.secondary} wrap="truncate-end">
      {originalDescription}
    </Text>
  ) : undefined;

  if (typeof resultDisplay === 'string') {
    const flattened = resultDisplay.replace(/\n/g, ' ').trim();
    summary = (
      <Text color={theme.text.accent} wrap="truncate-end">
        β†’ {flattened}
      </Text>
    );
  } else if (isGrepResult(resultDisplay)) {
    summary = (
      <Text color={theme.text.accent} wrap="truncate-end">
        β†’ {resultDisplay.summary}
      </Text>
    );
  } else if (isTodoList(resultDisplay)) {
    summary = (
      <Text color={theme.text.accent} wrap="wrap">
        β†’ Todos updated
      </Text>
    );
  } else if (hasPayload(resultDisplay)) {
    summary = <Text color={theme.text.accent}>β†’ {resultDisplay.summary}</Text>;
    payload = (
      <Box marginLeft={2}>
        <Text color={theme.text.secondary}>{resultDisplay.payload}</Text>
      </Box>
    );
  } else {
    summary = (
      <Text color={theme.text.accent} wrap="wrap">
        β†’ Returned (possible empty result)
      </Text>
    );
  }

  return { description, summary, payload };
}

export const DenseToolMessage: React.FC<DenseToolMessageProps> = (props) => {
  const {
    callId,
    name,
    status,
    resultDisplay,
    confirmationDetails,
    outputFile,
    terminalWidth,
    availableTerminalHeight,
    description: originalDescription,
  } = props;

  const settings = useSettings();
  const isAlternateBuffer = useAlternateBuffer();
  const { isExpanded: isExpandedInContext, toggleExpansion } = useToolActions();

  // Handle optional context members
  const [localIsExpanded, setLocalIsExpanded] = useState(false);
  const isExpanded = isExpandedInContext
    ? isExpandedInContext(callId)
    : localIsExpanded;

  const [isFocused, setIsFocused] = useState(false);
  const toggleRef = useRef<DOMElement>(null);

  // Unified File Data Extraction (Safely bridge resultDisplay and confirmationDetails)
  const diff = useMemo((): FileDiff | undefined => {
    if (isFileDiff(resultDisplay)) return resultDisplay;
    if (confirmationDetails?.type === 'edit') {
      const details = confirmationDetails;
      return {
        fileName: details.fileName,
        fileDiff: details.fileDiff,
        filePath: details.filePath,
        originalContent: details.originalContent,
        newContent: details.newContent,
        diffStat: details.diffStat,
      };
    }
    return undefined;
  }, [resultDisplay, confirmationDetails]);

  const handleToggle = () => {
    const next = !isExpanded;
    if (!next) {
      setIsFocused(false);
    } else {
      setIsFocused(true);
    }

    if (toggleExpansion) {
      toggleExpansion(callId);
    } else {
      setLocalIsExpanded(next);
    }
  };

  useMouseClick(toggleRef, handleToggle, {
    isActive: isAlternateBuffer && !!diff,
  });

  // State-to-View Coordination
  const viewParts = useMemo((): ViewParts => {
    if (diff) {
      return getFileOpData(
        diff,
        status,
        resultDisplay,
        terminalWidth,
        availableTerminalHeight,
        isAlternateBuffer,
      );
    }
    if (isListResult(resultDisplay)) {
      return getListResultData(resultDisplay, originalDescription);
    }

    if (isGrepResult(resultDisplay)) {
      return getGenericSuccessData(resultDisplay, originalDescription);
    }

    if (status === CoreToolCallStatus.Success && resultDisplay) {
      return getGenericSuccessData(resultDisplay, originalDescription);
    }
    if (status === CoreToolCallStatus.Error) {
      const text =
        typeof resultDisplay === 'string'
          ? resultDisplay.replace(/\n/g, ' ')
          : 'Failed';
      const errorSummary = (
        <Text color={theme.status.error} wrap="truncate-end">
          β†’ {text}
        </Text>
      );
      const descriptionText = originalDescription ? (
        <Text color={theme.text.secondary} wrap="truncate-end">
          {originalDescription}
        </Text>
      ) : undefined;
      return {
        description: descriptionText,
        summary: errorSummary,
        payload: undefined,
      };
    }

    const descriptionText = originalDescription ? (
      <Text color={theme.text.secondary} wrap="truncate-end">
        {originalDescription}
      </Text>
    ) : undefined;
    return {
      description: descriptionText,
      summary: undefined,
      payload: undefined,
    };
  }, [
    diff,
    status,
    resultDisplay,
    terminalWidth,
    availableTerminalHeight,
    originalDescription,
    isAlternateBuffer,
  ]);

  const { description, summary } = viewParts;

  const diffLines = useMemo(() => {
    if (!diff || !isExpanded || !isAlternateBuffer) return [];

    const parsedLines = parseDiffWithLineNumbers(diff.fileDiff);
    const isNewFileResult = isNewFile(parsedLines);

    if (isNewFileResult) {
      const addedContent = parsedLines
        .filter((line) => line.type === 'add')
        .map((line) => line.content)
        .join('\n');

      const fileExtension = getFileExtension(diff.fileName);

      return colorizeCode({
        code: addedContent,
        language: fileExtension,
        maxWidth: terminalWidth - PAYLOAD_MARGIN_LEFT,
        settings,
        disableColor: status === CoreToolCallStatus.Cancelled,
        returnLines: true,
      });
    } else {
      return renderDiffLines({
        parsedLines,
        filename: diff.fileName,
        terminalWidth: terminalWidth - PAYLOAD_MARGIN_LEFT,
        disableColor: status === CoreToolCallStatus.Cancelled,
      });
    }
  }, [diff, isExpanded, isAlternateBuffer, terminalWidth, settings, status]);

  const showPayload = useMemo(() => {
    const policy = !isAlternateBuffer || !diff || isExpanded;
    if (!policy) return false;

    if (diff) {
      if (isAlternateBuffer) {
        return isExpanded && diffLines.length > 0;
      }
      // In non-alternate buffer mode, we always show the diff.
      return true;
    }

    return !!(viewParts.payload || outputFile);
  }, [
    isAlternateBuffer,
    diff,
    isExpanded,
    diffLines.length,
    viewParts.payload,
    outputFile,
  ]);

  const keyExtractor = (_item: React.ReactNode, index: number) =>
    `diff-line-${index}`;
  const renderItem = ({ item }: { item: React.ReactNode }) => (
    <Box minHeight={1}>{item}</Box>
  );

  return (
    <Box flexDirection="column">
      <Box marginLeft={2} flexDirection="row" flexWrap="wrap">
        <Box flexDirection="row" flexShrink={1}>
          <ToolStatusIndicator status={status} name={name} />
          <Box maxWidth={25} flexShrink={0} flexGrow={0}>
            <Text color={theme.text.primary} bold wrap="truncate-end">
              {name}{' '}
            </Text>
          </Box>
          <Box marginLeft={1} flexShrink={1} flexGrow={0}>
            {description}
          </Box>
        </Box>

        {summary && (
          <Box
            key="tool-summary"
            ref={isAlternateBuffer && diff ? toggleRef : undefined}
            marginLeft={1}
            flexGrow={0}
          >
            {summary}
          </Box>
        )}
      </Box>

      {showPayload && isAlternateBuffer && diffLines.length > 0 && (
        <Box
          marginLeft={PAYLOAD_MARGIN_LEFT}
          marginTop={1}
          marginBottom={1}
          paddingX={1}
          flexDirection="column"
          height={
            Math.min(diffLines.length, COMPACT_TOOL_SUBVIEW_MAX_LINES) + 2
          }
          maxHeight={COMPACT_TOOL_SUBVIEW_MAX_LINES + 2}
          borderStyle="round"
          borderColor={theme.border.default}
          borderDimColor={true}
          maxWidth={Math.min(
            PAYLOAD_MAX_WIDTH,
            terminalWidth - PAYLOAD_MARGIN_LEFT,
          )}
        >
          <ScrollableList
            data={diffLines}
            renderItem={renderItem}
            keyExtractor={keyExtractor}
            estimatedItemHeight={() => 1}
            hasFocus={isFocused}
            width={Math.min(
              PAYLOAD_MAX_WIDTH,
              terminalWidth -
                PAYLOAD_MARGIN_LEFT -
                PAYLOAD_BORDER_CHROME_WIDTH -
                PAYLOAD_SCROLL_GUTTER,
            )}
          />
        </Box>
      )}

      {showPayload && (!isAlternateBuffer || !diff) && viewParts.payload && (
        <Box marginLeft={PAYLOAD_MARGIN_LEFT} marginTop={1} marginBottom={1}>
          {viewParts.payload}
        </Box>
      )}

      {showPayload && outputFile && (
        <Box marginLeft={PAYLOAD_MARGIN_LEFT} marginTop={1} marginBottom={1}>
          <Text color={theme.text.secondary}>
            (Output saved to: {outputFile})
          </Text>
        </Box>
      )}
    </Box>
  );
};