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

import { Box, Text } from 'ink';
import { useEffect, useState, useRef } from 'react';
import { useUIActions } from '../contexts/UIActionsContext.js';
import { theme } from '../semantic-colors.js';
import {
  ShellExecutionService,
  shortenPath,
  tildeifyPath,
  type AnsiOutput,
  type AnsiLine,
  type AnsiToken,
} from '@google/gemini-cli-core';
import { cpLen, cpSlice, getCachedStringWidth } from '../utils/textUtils.js';
import { type BackgroundTask } from '../hooks/useExecutionLifecycle.js';
import { Command } from '../key/keyMatchers.js';
import { useKeypress } from '../hooks/useKeypress.js';
import { formatCommand } from '../key/keybindingUtils.js';
import {
  ScrollableList,
  type ScrollableListRef,
} from './shared/ScrollableList.js';

import { SCROLL_TO_ITEM_END } from './shared/VirtualizedList.js';

import {
  RadioButtonSelect,
  type RadioSelectItem,
} from './shared/RadioButtonSelect.js';
import { useKeyMatchers } from '../hooks/useKeyMatchers.js';

interface BackgroundTaskDisplayProps {
  shells: Map<number, BackgroundTask>;
  activePid: number;
  width: number;
  height: number;
  isFocused: boolean;
  isListOpenProp: boolean;
}

const CONTENT_PADDING_X = 1;
const BORDER_WIDTH = 2; // Left and Right border
const MAIN_BORDER_HEIGHT = 2; // Top and Bottom border
const HEADER_HEIGHT = 1;
const FOOTER_HEIGHT = 1;
const TOTAL_OVERHEAD_HEIGHT =
  MAIN_BORDER_HEIGHT + HEADER_HEIGHT + FOOTER_HEIGHT;
const PROCESS_LIST_HEADER_HEIGHT = 3; // 1 padding top, 1 text, 1 margin bottom
const TAB_DISPLAY_HORIZONTAL_PADDING = 4;
const LOG_PATH_OVERHEAD = 7; // "Log: " (5) + paddingX (2)

const formatShellCommandForDisplay = (command: string, maxWidth: number) => {
  const commandFirstLine = command.split('\n')[0];
  return cpLen(commandFirstLine) > maxWidth
    ? `${cpSlice(commandFirstLine, 0, maxWidth - 3)}...`
    : commandFirstLine;
};

export const BackgroundTaskDisplay = ({
  shells,
  activePid,
  width,
  height,
  isFocused,
  isListOpenProp,
}: BackgroundTaskDisplayProps) => {
  const keyMatchers = useKeyMatchers();
  const {
    dismissBackgroundTask,
    setActiveBackgroundTaskPid,
    setIsBackgroundTaskListOpen,
  } = useUIActions();
  const activeShell = shells.get(activePid);
  const [output, setOutput] = useState<string | AnsiOutput>(
    activeShell?.output || '',
  );
  const [highlightedPid, setHighlightedPid] = useState<number | null>(
    activePid,
  );
  const outputRef = useRef<ScrollableListRef<AnsiLine | string>>(null);
  const subscribedRef = useRef(false);

  useEffect(() => {
    if (!activePid) return;

    const ptyWidth = Math.max(1, width - BORDER_WIDTH - CONTENT_PADDING_X * 2);
    const ptyHeight = Math.max(1, height - TOTAL_OVERHEAD_HEIGHT);
    ShellExecutionService.resizePty(activePid, ptyWidth, ptyHeight);
  }, [activePid, width, height]);

  useEffect(() => {
    if (!activePid) {
      setOutput('');
      return;
    }

    // Set initial output from the shell object
    const shell = shells.get(activePid);
    if (shell) {
      setOutput(shell.output);
    }

    subscribedRef.current = false;

    // Subscribe to live updates for the active shell
    const unsubscribe = ShellExecutionService.subscribe(activePid, (event) => {
      if (event.type === 'data') {
        if (typeof event.chunk === 'string') {
          if (!subscribedRef.current) {
            // Initial synchronous update contains full history
            setOutput(event.chunk);
          } else {
            // Subsequent updates are deltas for child_process
            setOutput((prev) =>
              typeof prev === 'string' ? prev + event.chunk : event.chunk,
            );
          }
        } else {
          // PTY always sends full AnsiOutput
          setOutput(event.chunk);
        }
      }
    });

    subscribedRef.current = true;

    return () => {
      unsubscribe();
      subscribedRef.current = false;
    };
  }, [activePid, shells]);

  // Sync highlightedPid with activePid when list opens
  useEffect(() => {
    if (isListOpenProp) {
      setHighlightedPid(activePid);
    }
  }, [isListOpenProp, activePid]);

  useKeypress(
    (key) => {
      if (!activeShell) return;

      if (isListOpenProp) {
        // Navigation (Up/Down/Enter) is handled by RadioButtonSelect
        // We only handle special keys not consumed by RadioButtonSelect or overriding them if needed
        // RadioButtonSelect handles Enter -> onSelect

        if (keyMatchers[Command.BACKGROUND_SHELL_ESCAPE](key)) {
          setIsBackgroundTaskListOpen(false);
          return true;
        }

        if (keyMatchers[Command.KILL_BACKGROUND_SHELL](key)) {
          if (highlightedPid) {
            void dismissBackgroundTask(highlightedPid);
            // If we killed the active one, the list might update via props
          }
          return true;
        }

        if (keyMatchers[Command.TOGGLE_BACKGROUND_SHELL_LIST](key)) {
          if (highlightedPid) {
            setActiveBackgroundTaskPid(highlightedPid);
          }
          setIsBackgroundTaskListOpen(false);
          return true;
        }
        return false;
      }

      if (keyMatchers[Command.TOGGLE_BACKGROUND_SHELL](key)) {
        return false;
      }

      if (keyMatchers[Command.KILL_BACKGROUND_SHELL](key)) {
        void dismissBackgroundTask(activeShell.pid);
        return true;
      }

      if (keyMatchers[Command.TOGGLE_BACKGROUND_SHELL_LIST](key)) {
        setIsBackgroundTaskListOpen(true);
        return true;
      }

      if (keyMatchers[Command.BACKGROUND_SHELL_SELECT](key)) {
        ShellExecutionService.writeToPty(activeShell.pid, '\r');
        return true;
      } else if (keyMatchers[Command.DELETE_CHAR_LEFT](key)) {
        ShellExecutionService.writeToPty(activeShell.pid, '\b');
        return true;
      } else if (key.sequence) {
        ShellExecutionService.writeToPty(activeShell.pid, key.sequence);
        return true;
      }
      return false;
    },
    { isActive: isFocused && !!activeShell },
  );

  const helpTextParts = [
    { label: 'Close', command: Command.TOGGLE_BACKGROUND_SHELL },
    { label: 'Kill', command: Command.KILL_BACKGROUND_SHELL },
    { label: 'List', command: Command.TOGGLE_BACKGROUND_SHELL_LIST },
  ];

  const helpTextStr = helpTextParts
    .map((p) => `${p.label} (${formatCommand(p.command)})`)
    .join(' | ');

  const renderHelpText = () => (
    <Text>
      {helpTextParts.map((p, i) => (
        <Text key={p.label}>
          {i > 0 ? ' | ' : ''}
          {p.label} (
          <Text color={theme.text.accent}>{formatCommand(p.command)}</Text>)
        </Text>
      ))}
    </Text>
  );

  const renderTabs = () => {
    const shellList = Array.from(shells.values()).filter(
      (s) => s.status === 'running',
    );

    const pidInfoWidth = getCachedStringWidth(
      ` (PID: ${activePid}) ${isFocused ? '(Focused)' : ''}`,
    );

    const availableWidth =
      width -
      TAB_DISPLAY_HORIZONTAL_PADDING -
      getCachedStringWidth(helpTextStr) -
      pidInfoWidth;

    let currentWidth = 0;
    const tabs = [];

    for (let i = 0; i < shellList.length; i++) {
      const shell = shellList[i];
      // Account for " i: " (length 4 if i < 9) and spaces (length 2)
      const labelOverhead = 4 + (i + 1).toString().length;
      const maxTabLabelLength = Math.max(
        1,
        Math.floor(availableWidth / shellList.length) - labelOverhead,
      );
      const truncatedCommand = formatShellCommandForDisplay(
        shell.command,
        maxTabLabelLength,
      );
      const label = ` ${i + 1}: ${truncatedCommand} `;
      const labelWidth = getCachedStringWidth(label);

      // If this is the only shell, we MUST show it (truncated if necessary)
      // even if it exceeds availableWidth, as there are no alternatives.
      if (i > 0 && currentWidth + labelWidth > availableWidth) {
        break;
      }

      const isActive = shell.pid === activePid;

      tabs.push(
        <Text
          key={shell.pid}
          color={isActive ? theme.text.primary : theme.text.secondary}
          bold={isActive}
        >
          {label}
        </Text>,
      );
      currentWidth += labelWidth;
    }

    if (shellList.length > tabs.length && !isListOpenProp) {
      const overflowLabel = ` ... (${formatCommand(Command.TOGGLE_BACKGROUND_SHELL_LIST)}) `;
      const overflowWidth = getCachedStringWidth(overflowLabel);

      // If we only have one tab, ensure we don't show the overflow if it's too cramped
      // We want at least 10 chars for the overflow or we favor the first tab.
      const shouldShowOverflow =
        tabs.length > 1 || availableWidth - currentWidth >= overflowWidth;

      if (shouldShowOverflow) {
        tabs.push(
          <Text key="overflow" color={theme.status.warning} bold>
            {overflowLabel}
          </Text>,
        );
      }
    }

    return tabs;
  };

  const renderProcessList = () => {
    const maxCommandLength = Math.max(
      0,
      width - BORDER_WIDTH - CONTENT_PADDING_X * 2 - 10,
    );

    const items: Array<RadioSelectItem<number>> = Array.from(
      shells.values(),
    ).map((shell, index) => {
      const truncatedCommand = formatShellCommandForDisplay(
        shell.command,
        maxCommandLength,
      );

      let label = `${index + 1}: ${truncatedCommand} (PID: ${shell.pid})`;
      if (shell.status === 'exited') {
        label += ` (Exit Code: ${shell.exitCode})`;
      }

      return {
        key: shell.pid.toString(),
        value: shell.pid,
        label,
      };
    });

    const initialIndex = items.findIndex((item) => item.value === activePid);

    return (
      <Box flexDirection="column" height="100%" width="100%">
        <Box flexShrink={0} marginBottom={1} paddingTop={1}>
          <Text bold>
            {`Select Process (${formatCommand(Command.BACKGROUND_SHELL_SELECT)} to select, ${formatCommand(Command.KILL_BACKGROUND_SHELL)} to kill, ${formatCommand(Command.BACKGROUND_SHELL_ESCAPE)} to cancel):`}
          </Text>
        </Box>
        <Box flexGrow={1} width="100%">
          <RadioButtonSelect
            items={items}
            initialIndex={initialIndex >= 0 ? initialIndex : 0}
            onSelect={(pid) => {
              setActiveBackgroundTaskPid(pid);
              setIsBackgroundTaskListOpen(false);
            }}
            onHighlight={(pid) => setHighlightedPid(pid)}
            isFocused={isFocused}
            maxItemsToShow={Math.max(
              1,
              height - TOTAL_OVERHEAD_HEIGHT - PROCESS_LIST_HEADER_HEIGHT,
            )}
            renderItem={(
              item,
              { isSelected: _isSelected, titleColor: _titleColor },
            ) => {
              // Custom render to handle exit code coloring if needed,
              // or just use default. The default RadioButtonSelect renderer
              // handles standard label.
              // But we want to color exit code differently?
              // The previous implementation colored exit code green/red.
              // Let's reimplement that.

              // We need access to shell details here.
              // We can put shell details in the item or lookup.
              // Lookup from shells map.
              const shell = shells.get(item.value);
              if (!shell) return <Text>{item.label}</Text>;

              const truncatedCommand = formatShellCommandForDisplay(
                shell.command,
                maxCommandLength,
              );

              return (
                <Text>
                  {truncatedCommand} (PID: {shell.pid})
                  {shell.status === 'exited' ? (
                    <Text
                      color={
                        shell.exitCode === 0
                          ? theme.status.success
                          : theme.status.error
                      }
                    >
                      {' '}
                      (Exit Code: {shell.exitCode})
                    </Text>
                  ) : null}
                </Text>
              );
            }}
          />
        </Box>
      </Box>
    );
  };

  const renderFooter = () => {
    const pidToDisplay = isListOpenProp
      ? (highlightedPid ?? activePid)
      : activePid;
    if (!pidToDisplay) return null;
    const logPath = ShellExecutionService.getLogFilePath(pidToDisplay);
    const displayPath = shortenPath(
      tildeifyPath(logPath),
      width - LOG_PATH_OVERHEAD,
    );
    return (
      <Box paddingX={1}>
        <Text color={theme.text.secondary}>Log: {displayPath}</Text>
      </Box>
    );
  };

  const renderOutput = () => {
    const lines = typeof output === 'string' ? output.split('\n') : output;

    return (
      <ScrollableList
        ref={outputRef}
        data={lines}
        renderItem={({ item: line, index }) => {
          if (typeof line === 'string') {
            return <Text key={index}>{line}</Text>;
          }
          return (
            <Text key={index} wrap="truncate">
              {line.length > 0
                ? line.map((token: AnsiToken, tokenIndex: number) => (
                    <Text
                      key={tokenIndex}
                      color={token.fg}
                      backgroundColor={token.bg}
                      inverse={token.inverse}
                      dimColor={token.dim}
                      bold={token.bold}
                      italic={token.italic}
                      underline={token.underline}
                    >
                      {token.text}
                    </Text>
                  ))
                : null}
            </Text>
          );
        }}
        estimatedItemHeight={() => 1}
        keyExtractor={(_, index) => index.toString()}
        hasFocus={isFocused}
        initialScrollIndex={SCROLL_TO_ITEM_END}
      />
    );
  };

  return (
    <Box
      flexDirection="column"
      height="100%"
      width="100%"
      borderStyle="single"
      borderColor={isFocused ? theme.ui.focus : undefined}
    >
      <Box
        flexDirection="row"
        justifyContent="space-between"
        borderStyle="single"
        borderBottom={false}
        borderLeft={false}
        borderRight={false}
        borderTop={false}
        paddingX={1}
        borderColor={isFocused ? theme.ui.focus : undefined}
      >
        <Box flexDirection="row">
          {renderTabs()}
          <Text bold>
            {' '}
            (PID: {activeShell?.pid}) {isFocused ? '(Focused)' : ''}
          </Text>
        </Box>
        {renderHelpText()}
      </Box>
      <Box flexGrow={1} overflow="hidden" paddingX={CONTENT_PADDING_X}>
        {isListOpenProp ? renderProcessList() : renderOutput()}
      </Box>
      {renderFooter()}
    </Box>
  );
};