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

import React from 'react';
import { Box, Text } from 'ink';
import { DiffRenderer } from './DiffRenderer.js';
import { MarkdownDisplay } from '../../utils/MarkdownDisplay.js';
import { AnsiOutputText, AnsiLineText } from '../AnsiOutput.js';
import { SlicingMaxSizedBox } from '../shared/SlicingMaxSizedBox.js';
import { MaxSizedBox } from '../shared/MaxSizedBox.js';
import { theme } from '../../semantic-colors.js';
import {
  type AnsiOutput,
  type AnsiLine,
  isSubagentProgress,
  isStructuredToolResult,
} from '@google/gemini-cli-core';
import { useUIState } from '../../contexts/UIStateContext.js';
import { tryParseJSON } from '../../../utils/jsonoutput.js';
import { useAlternateBuffer } from '../../hooks/useAlternateBuffer.js';
import { Scrollable } from '../shared/Scrollable.js';
import { ScrollableList } from '../shared/ScrollableList.js';
import { SCROLL_TO_ITEM_END } from '../shared/VirtualizedList.js';
import { ACTIVE_SHELL_MAX_LINES } from '../../constants.js';
import { calculateToolContentMaxLines } from '../../utils/toolLayoutUtils.js';
import { SubagentProgressDisplay } from './SubagentProgressDisplay.js';
import { isLockFile } from '../../utils/fileUtils.js';

export interface ToolResultDisplayProps {
  resultDisplay: string | object | undefined;
  availableTerminalHeight?: number;
  terminalWidth: number;
  renderOutputAsMarkdown?: boolean;
  maxLines?: number;
  hasFocus?: boolean;
  overflowDirection?: 'top' | 'bottom';
}

interface FileDiffResult {
  fileDiff: string;
  fileName: string;
  isBuildFile?: boolean;
}

function isFileDiffResult(value: unknown): value is FileDiffResult {
  return (
    typeof value === 'object' &&
    value !== null &&
    'fileDiff' in value &&
    typeof value.fileDiff === 'string' &&
    'fileName' in value &&
    typeof value.fileName === 'string'
  );
}

export const ToolResultDisplay: React.FC<ToolResultDisplayProps> = ({
  resultDisplay,
  availableTerminalHeight,
  terminalWidth,
  renderOutputAsMarkdown = true,
  maxLines,
  hasFocus = false,
  overflowDirection = 'top',
}) => {
  const { renderMarkdown, constrainHeight } = useUIState();
  const isAlternateBuffer = useAlternateBuffer();

  const availableHeight = calculateToolContentMaxLines({
    availableTerminalHeight,
    isAlternateBuffer,
    maxLinesLimit: maxLines,
  });

  const combinedPaddingAndBorderWidth = 4;
  const childWidth = terminalWidth - combinedPaddingAndBorderWidth;

  const keyExtractor = React.useCallback(
    (_: AnsiLine, index: number) => index.toString(),
    [],
  );

  const renderVirtualizedAnsiLine = React.useCallback(
    ({ item }: { item: AnsiLine }) => (
      <Box height={1} overflow="hidden">
        <AnsiLineText line={item} />
      </Box>
    ),
    [],
  );

  if (!resultDisplay) return null;

  // 1. Early return for background tools (Todos)
  if (typeof resultDisplay === 'object' && 'todos' in resultDisplay) {
    // display nothing, as the TodoTray will handle rendering todos
    return null;
  }

  const renderContent = (contentData: string | object | undefined) => {
    // Check if string content is valid JSON and pretty-print it
    const prettyJSON =
      typeof contentData === 'string' ? tryParseJSON(contentData) : null;
    const formattedJSON = prettyJSON
      ? JSON.stringify(prettyJSON, null, 2)
      : null;

    let content: React.ReactNode;

    if (formattedJSON) {
      // Render pretty-printed JSON
      content = (
        <Text wrap="wrap" color={theme.text.primary}>
          {formattedJSON}
        </Text>
      );
    } else if (isSubagentProgress(contentData)) {
      content = (
        <SubagentProgressDisplay
          progress={contentData}
          terminalWidth={childWidth}
        />
      );
    } else if (typeof contentData === 'string' && renderOutputAsMarkdown) {
      content = (
        <MarkdownDisplay
          text={contentData}
          terminalWidth={childWidth}
          renderMarkdown={renderMarkdown}
          isPending={false}
        />
      );
    } else if (typeof contentData === 'string' && !renderOutputAsMarkdown) {
      content = (
        <Text wrap="wrap" color={theme.text.primary}>
          {contentData}
        </Text>
      );
    } else if (isStructuredToolResult(contentData)) {
      if (renderOutputAsMarkdown) {
        content = (
          <MarkdownDisplay
            text={contentData.summary}
            terminalWidth={childWidth}
            renderMarkdown={renderMarkdown}
            isPending={false}
          />
        );
      } else {
        content = (
          <Text wrap="wrap" color={theme.text.primary}>
            {contentData.summary}
          </Text>
        );
      }
    } else if (isFileDiffResult(contentData)) {
      content = (
        <DiffRenderer
          diffContent={contentData.fileDiff}
          filename={contentData.fileName}
          disableTruncation={
            contentData.isBuildFile && !isLockFile(contentData.fileName)
          }
          availableTerminalHeight={availableHeight}
          terminalWidth={childWidth}
        />
      );
    } else if (Array.isArray(contentData)) {
      const shouldDisableTruncation =
        isAlternateBuffer ||
        (availableTerminalHeight === undefined && maxLines === undefined);

      content = (
        <AnsiOutputText
          // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
          data={contentData as AnsiOutput}
          availableTerminalHeight={
            isAlternateBuffer ? undefined : availableHeight
          }
          width={childWidth}
          maxLines={isAlternateBuffer ? undefined : maxLines}
          disableTruncation={shouldDisableTruncation}
        />
      );
    } else if (typeof contentData === 'object' && contentData !== null) {
      // Render as JSON for other non-null objects
      content = (
        <Text wrap="wrap" color={theme.text.primary}>
          {JSON.stringify(contentData, null, 2)}
        </Text>
      );
    } else {
      content = null;
    }

    // Final render based on session mode
    if (isAlternateBuffer) {
      // Use maxLines if provided, otherwise fall back to the calculated available height
      const effectiveMaxHeight = maxLines ?? availableHeight;

      return (
        <Scrollable
          width={childWidth}
          maxHeight={effectiveMaxHeight}
          hasFocus={hasFocus} // Allow scrolling via keyboard (Shift+Up/Down)
          scrollToBottom={true}
          reportOverflow={true}
        >
          {content}
        </Scrollable>
      );
    }

    return content;
  };

  if (Array.isArray(resultDisplay)) {
    const limit = maxLines ?? availableHeight ?? ACTIVE_SHELL_MAX_LINES;
    // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
    const data = resultDisplay as AnsiOutput;

    // Calculate list height: if not constrained, use full data length.
    // If constrained (e.g. alternate buffer), limit to available height
    // to ensure virtualization works and fits within the viewport.
    const listHeight = !constrainHeight
      ? data.length
      : Math.min(data.length, limit);

    if (isAlternateBuffer) {
      const initialScrollIndex =
        overflowDirection === 'bottom' ? 0 : SCROLL_TO_ITEM_END;

      return (
        <Box width={childWidth} flexDirection="column" maxHeight={listHeight}>
          <ScrollableList
            width={childWidth}
            containerHeight={listHeight}
            data={data}
            renderItem={renderVirtualizedAnsiLine}
            estimatedItemHeight={() => 1}
            fixedItemHeight={true}
            keyExtractor={keyExtractor}
            initialScrollIndex={initialScrollIndex}
            hasFocus={hasFocus}
          />
        </Box>
      );
    } else {
      let displayData = data;
      let hiddenLines = 0;

      if (constrainHeight && data.length > listHeight) {
        hiddenLines = data.length - listHeight;
        if (overflowDirection === 'top') {
          displayData = data.slice(hiddenLines);
        } else {
          displayData = data.slice(0, listHeight);
        }
      }

      return (
        <Box width={childWidth} flexDirection="column">
          <MaxSizedBox
            maxHeight={constrainHeight ? listHeight : undefined}
            maxWidth={childWidth}
            overflowDirection={overflowDirection}
            additionalHiddenLinesCount={hiddenLines}
          >
            {displayData.map((item, index) => {
              const actualIndex =
                (overflowDirection === 'top' ? hiddenLines : 0) + index;
              return (
                <Box
                  key={keyExtractor(item, actualIndex)}
                  height={1}
                  overflow="hidden"
                >
                  <AnsiLineText line={item} />
                </Box>
              );
            })}
          </MaxSizedBox>
        </Box>
      );
    }
  }

  // ASB Mode Handling (Interactive/Fullscreen)
  if (isAlternateBuffer) {
    // Standard path for strings/diffs in ASB
    return (
      <Box width={childWidth} flexDirection="column">
        {renderContent(resultDisplay)}
      </Box>
    );
  }

  // Standard Mode Handling (History/Scrollback)
  // We use SlicingMaxSizedBox which includes MaxSizedBox for precision truncation + hidden labels
  return (
    <Box width={childWidth} flexDirection="column">
      <SlicingMaxSizedBox
        data={resultDisplay}
        maxLines={maxLines}
        isAlternateBuffer={isAlternateBuffer}
        maxHeight={availableHeight}
        maxWidth={childWidth}
        overflowDirection={overflowDirection}
      >
        {(truncatedResultDisplay) => renderContent(truncatedResultDisplay)}
      </SlicingMaxSizedBox>
    </Box>
  );
};