File size: 40,391 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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { act } from 'react';
import { render } from '../../test-utils/render.js';
import { waitFor } from '../../test-utils/async.js';
import {
  vi,
  describe,
  it,
  expect,
  beforeEach,
  afterEach,
  type Mock,
} from 'vitest';
import { NoopSandboxManager, escapeShellArg } from '@google/gemini-cli-core';

const mockIsBinary = vi.hoisted(() => vi.fn());
const mockShellExecutionService = vi.hoisted(() => vi.fn());
const mockShellKill = vi.hoisted(() => vi.fn());
const mockShellBackground = vi.hoisted(() => vi.fn());
const mockShellSubscribe = vi.hoisted(() =>
  vi.fn<
    (pid: number, listener: (event: ShellOutputEvent) => void) => () => void
  >(() => vi.fn()),
); // Returns unsubscribe
const mockShellOnExit = vi.hoisted(() =>
  vi.fn<
    (
      pid: number,
      callback: (exitCode: number, signal?: number) => void,
    ) => () => void
  >(() => vi.fn()),
);
const mockLifecycleSubscribe = vi.hoisted(() =>
  vi.fn<
    (pid: number, listener: (event: ShellOutputEvent) => void) => () => void
  >(() => vi.fn()),
);
const mockLifecycleOnExit = vi.hoisted(() =>
  vi.fn<
    (
      pid: number,
      callback: (exitCode: number, signal?: number) => void,
    ) => () => void
  >(() => vi.fn()),
);
const mockLifecycleKill = vi.hoisted(() => vi.fn());
const mockLifecycleBackground = vi.hoisted(() => vi.fn());
const mockLifecycleOnBackground = vi.hoisted(() => vi.fn());
const mockLifecycleOffBackground = vi.hoisted(() => vi.fn());

vi.mock('@google/gemini-cli-core', async (importOriginal) => {
  const actual =
    await importOriginal<typeof import('@google/gemini-cli-core')>();
  return {
    ...actual,
    ShellExecutionService: {
      execute: mockShellExecutionService,
      kill: mockShellKill,
      background: mockShellBackground,
      subscribe: mockShellSubscribe,
      onExit: mockShellOnExit,
    },
    ExecutionLifecycleService: {
      subscribe: mockLifecycleSubscribe,
      onExit: mockLifecycleOnExit,
      kill: mockLifecycleKill,
      background: mockLifecycleBackground,
      onBackground: mockLifecycleOnBackground,
      offBackground: mockLifecycleOffBackground,
    },
    isBinary: mockIsBinary,
  };
});
vi.mock('node:fs', async (importOriginal) => {
  const actual = await importOriginal<typeof import('node:fs')>();
  const mockFs = {
    ...actual,
    existsSync: vi.fn(),
    mkdtempSync: vi.fn(),
    unlinkSync: vi.fn(),
    readFileSync: vi.fn(),
    rmSync: vi.fn(),
  };
  return {
    ...mockFs,
    default: mockFs,
  };
});
vi.mock('node:os', async (importOriginal) => {
  const actual = await importOriginal<typeof import('node:os')>();
  const mocked = {
    ...actual,
    homedir: vi.fn(() => '/home/user'),
    platform: vi.fn(() => 'linux'),
    tmpdir: vi.fn(() => '/tmp'),
  };
  return {
    ...mocked,
    default: mocked,
  };
});
vi.mock('node:crypto');

import {
  useExecutionLifecycle,
  OUTPUT_UPDATE_INTERVAL_MS,
} from './useExecutionLifecycle.js';
import {
  type Config,
  type GeminiClient,
  type ShellExecutionResult,
  type ShellOutputEvent,
  type AnsiOutput,
  CoreToolCallStatus,
} from '@google/gemini-cli-core';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import * as crypto from 'node:crypto';

describe('useExecutionLifecycle', () => {
  let addItemToHistoryMock: Mock;
  let setPendingHistoryItemMock: Mock;
  let onExecMock: Mock;
  let onDebugMessageMock: Mock;
  let mockConfig: Config;
  let mockGeminiClient: GeminiClient;

  let mockShellOutputCallback: (event: ShellOutputEvent) => void;
  let resolveExecutionPromise: (result: ShellExecutionResult) => void;

  let setShellInputFocusedMock: Mock;

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

    addItemToHistoryMock = vi.fn();
    setPendingHistoryItemMock = vi.fn();
    onExecMock = vi.fn();
    onDebugMessageMock = vi.fn();
    setShellInputFocusedMock = vi.fn();
    mockConfig = {
      getTargetDir: () => '/test/dir',
      getEnableInteractiveShell: () => false,
      getSessionId: () => 'test-session-id',
      getShellExecutionConfig: () => ({
        terminalHeight: 20,
        terminalWidth: 80,
        sandboxManager: new NoopSandboxManager(),
        sanitizationConfig: {
          allowedEnvironmentVariables: [],
          blockedEnvironmentVariables: [],
          enableEnvironmentVariableRedaction: false,
        },
      }),
    } as unknown as Config;
    mockGeminiClient = { addHistory: vi.fn() } as unknown as GeminiClient;

    vi.mocked(os.platform).mockReturnValue('linux');
    vi.mocked(os.tmpdir).mockReturnValue('/tmp');
    (vi.mocked(crypto.randomBytes) as Mock).mockReturnValue(
      Buffer.from('abcdef', 'hex'),
    );
    mockIsBinary.mockReturnValue(false);
    vi.mocked(fs.existsSync).mockReturnValue(false);
    vi.mocked(fs.mkdtempSync).mockReturnValue('/tmp/gemini-shell-abcdef');

    mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
      mockShellOutputCallback = callback;
      return Promise.resolve({
        pid: 12345,
        result: new Promise((resolve) => {
          resolveExecutionPromise = resolve;
        }),
      });
    });
  });

  const renderProcessorHook = async () => {
    let hookResult: ReturnType<typeof useExecutionLifecycle>;
    let renderCount = 0;
    function TestComponent({
      isWaitingForConfirmation,
    }: {
      isWaitingForConfirmation?: boolean;
    }) {
      renderCount++;
      hookResult = useExecutionLifecycle(
        addItemToHistoryMock,
        setPendingHistoryItemMock,
        onExecMock,
        onDebugMessageMock,
        mockConfig,
        mockGeminiClient,
        setShellInputFocusedMock,
        undefined,
        undefined,
        undefined,
        isWaitingForConfirmation,
      );
      return null;
    }
    const { rerender } = await render(<TestComponent />);
    return {
      result: {
        get current() {
          return hookResult;
        },
      },
      getRenderCount: () => renderCount,
      rerender: (isWaitingForConfirmation?: boolean) =>
        rerender(
          <TestComponent isWaitingForConfirmation={isWaitingForConfirmation} />,
        ),
    };
  };

  const createMockServiceResult = (
    overrides: Partial<ShellExecutionResult> = {},
  ): ShellExecutionResult => ({
    rawOutput: Buffer.from(overrides.output || ''),
    output: 'Success',
    exitCode: 0,
    signal: null,
    error: null,
    aborted: false,
    pid: 12345,
    executionMethod: 'child_process',
    ...overrides,
  });

  it('should initiate command execution and set pending state', async () => {
    const { result } = await renderProcessorHook();

    await act(async () => {
      result.current.handleShellCommand('ls -l', new AbortController().signal);
    });

    expect(addItemToHistoryMock).toHaveBeenCalledWith(
      { type: 'user_shell', text: 'ls -l' },
      expect.any(Number),
    );
    expect(setPendingHistoryItemMock).toHaveBeenCalledWith({
      type: 'tool_group',
      tools: [
        expect.objectContaining({
          name: 'Shell Command',
          status: CoreToolCallStatus.Executing,
        }),
      ],
    });
    const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
    const escapedTmpFile = escapeShellArg(tmpFile, 'bash');
    const wrappedCommand = `{\nls -l\n}\n__code=$?; pwd > ${escapedTmpFile}; exit $__code`;
    expect(mockShellExecutionService).toHaveBeenCalledWith(
      wrappedCommand,
      '/test/dir',
      expect.any(Function),
      expect.any(Object),
      false,
      expect.objectContaining({
        sessionId: 'test-session-id',
      }),
    );
    expect(onExecMock).toHaveBeenCalledWith(expect.any(Promise));
  });

  it('should pass the config sessionId into shell execution config', async () => {
    const { result } = await renderProcessorHook();

    await act(async () => {
      result.current.handleShellCommand('top', new AbortController().signal);
    });

    expect(mockShellExecutionService).toHaveBeenCalledWith(
      expect.any(String),
      '/test/dir',
      expect.any(Function),
      expect.any(Object),
      false,
      expect.objectContaining({
        sessionId: 'test-session-id',
      }),
    );
  });

  it('should handle successful execution and update history correctly', async () => {
    const { result } = await renderProcessorHook();

    act(() => {
      result.current.handleShellCommand(
        'echo "ok"',
        new AbortController().signal,
      );
    });
    const execPromise = onExecMock.mock.calls[0][0];

    act(() => {
      resolveExecutionPromise(createMockServiceResult({ output: 'ok' }));
    });
    await act(async () => await execPromise);

    expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
    expect(addItemToHistoryMock).toHaveBeenCalledTimes(2); // Initial + final
    expect(addItemToHistoryMock.mock.calls[1][0]).toEqual(
      expect.objectContaining({
        tools: [
          expect.objectContaining({
            status: CoreToolCallStatus.Success,
            resultDisplay: 'ok',
          }),
        ],
      }),
    );
    expect(mockGeminiClient.addHistory).toHaveBeenCalled();
    expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
  });

  it('should handle command failure and display error status', async () => {
    const { result } = await renderProcessorHook();

    act(() => {
      result.current.handleShellCommand(
        'bad-cmd',
        new AbortController().signal,
      );
    });
    const execPromise = onExecMock.mock.calls[0][0];

    act(() => {
      resolveExecutionPromise(
        createMockServiceResult({ exitCode: 127, output: 'not found' }),
      );
    });
    await act(async () => await execPromise);

    const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
    expect(finalHistoryItem.tools[0].status).toBe(CoreToolCallStatus.Error);
    expect(finalHistoryItem.tools[0].resultDisplay).toContain(
      'Command exited with code 127',
    );
    expect(finalHistoryItem.tools[0].resultDisplay).toContain('not found');
    expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
  });

  describe('UI Streaming and Throttling', () => {
    beforeEach(() => {
      vi.useFakeTimers({ toFake: ['Date'] });
    });
    afterEach(() => {
      vi.useRealTimers();
    });

    it('should update UI for text streams (non-interactive)', async () => {
      const { result } = await renderProcessorHook();
      await act(async () => {
        result.current.handleShellCommand(
          'stream',
          new AbortController().signal,
        );
      });

      const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
      const escapedTmpFile = escapeShellArg(tmpFile, 'bash');
      const wrappedCommand = `{\nstream\n}\n__code=$?; pwd > ${escapedTmpFile}; exit $__code`;
      expect(mockShellExecutionService).toHaveBeenCalledWith(
        wrappedCommand,
        '/test/dir',
        expect.any(Function),
        expect.any(Object),
        false, // enableInteractiveShell
        expect.any(Object),
      );

      // Wait for the async PID update to happen.
      // Call 1: Initial, Call 2: PID update
      await waitFor(() => {
        expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
      });

      // Get the state after the PID update to feed into the stream updaters
      const pidUpdateFn = setPendingHistoryItemMock.mock.calls[1][0];
      const initialState = setPendingHistoryItemMock.mock.calls[0][0];
      const stateAfterPid = pidUpdateFn(initialState);

      // Simulate first output chunk
      act(() => {
        mockShellOutputCallback({
          type: 'data',
          chunk: 'hello',
        });
      });
      // A UI update should have occurred.
      expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(3);

      const streamUpdateFn1 = setPendingHistoryItemMock.mock.calls[2][0];
      const stateAfterStream1 = streamUpdateFn1(stateAfterPid);
      expect(stateAfterStream1.tools[0].resultDisplay).toBe('hello');

      // Simulate second output chunk
      act(() => {
        mockShellOutputCallback({
          type: 'data',
          chunk: ' world',
        });
      });
      // Another UI update should have occurred.
      expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(4);

      const streamUpdateFn2 = setPendingHistoryItemMock.mock.calls[3][0];
      const stateAfterStream2 = streamUpdateFn2(stateAfterStream1);
      expect(stateAfterStream2.tools[0].resultDisplay).toBe('hello world');
    });

    it('should show binary progress messages correctly', async () => {
      const { result } = await renderProcessorHook();
      act(() => {
        result.current.handleShellCommand(
          'cat img',
          new AbortController().signal,
        );
      });

      // Should immediately show the detection message
      act(() => {
        mockShellOutputCallback({ type: 'binary_detected' });
      });
      await act(async () => {
        await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
      });
      // Send another event to trigger the update
      act(() => {
        mockShellOutputCallback({ type: 'binary_progress', bytesReceived: 0 });
      });

      // The state update is functional, so we test it by executing it.
      const updaterFn1 = setPendingHistoryItemMock.mock.lastCall?.[0];
      if (!updaterFn1) {
        throw new Error('setPendingHistoryItem was not called');
      }
      const initialState = setPendingHistoryItemMock.mock.calls[0][0];
      const stateAfterBinaryDetected = updaterFn1(initialState);

      expect(stateAfterBinaryDetected).toEqual(
        expect.objectContaining({
          tools: [
            expect.objectContaining({
              resultDisplay: '[Binary output detected. Halting stream...]',
            }),
          ],
        }),
      );

      // Now test progress updates
      await act(async () => {
        await vi.advanceTimersByTimeAsync(OUTPUT_UPDATE_INTERVAL_MS + 1);
      });
      act(() => {
        mockShellOutputCallback({
          type: 'binary_progress',
          bytesReceived: 2048,
        });
      });

      const updaterFn2 = setPendingHistoryItemMock.mock.lastCall?.[0];
      if (!updaterFn2) {
        throw new Error('setPendingHistoryItem was not called');
      }
      const stateAfterProgress = updaterFn2(stateAfterBinaryDetected);
      expect(stateAfterProgress).toEqual(
        expect.objectContaining({
          tools: [
            expect.objectContaining({
              resultDisplay: '[Receiving binary output... 2.0 KB received]',
            }),
          ],
        }),
      );
    });
  });

  it('should not wrap the command on Windows', async () => {
    vi.mocked(os.platform).mockReturnValue('win32');
    const { result } = await renderProcessorHook();

    await act(async () => {
      result.current.handleShellCommand('dir', new AbortController().signal);
    });

    expect(mockShellExecutionService).toHaveBeenCalledWith(
      'dir',
      '/test/dir',
      expect.any(Function),
      expect.any(Object),
      false,
      expect.any(Object),
    );

    await act(async () => {
      resolveExecutionPromise(createMockServiceResult());
    });
    await act(async () => await onExecMock.mock.calls[0][0]);
  });

  it('should handle command abort and display cancelled status', async () => {
    const { result } = await renderProcessorHook();
    const abortController = new AbortController();

    act(() => {
      result.current.handleShellCommand('sleep 5', abortController.signal);
    });
    const execPromise = onExecMock.mock.calls[0][0];

    act(() => {
      abortController.abort();
      resolveExecutionPromise(
        createMockServiceResult({ aborted: true, output: 'Canceled' }),
      );
    });
    await act(async () => await execPromise);

    // With the new logic, cancelled commands are not added to history by this hook
    // to avoid duplication/flickering, as they are handled by useGeminiStream.
    expect(addItemToHistoryMock).toHaveBeenCalledTimes(1);
    expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
    expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
  });

  it('should handle binary output result correctly', async () => {
    const { result } = await renderProcessorHook();
    const binaryBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
    mockIsBinary.mockReturnValue(true);

    act(() => {
      result.current.handleShellCommand(
        'cat image.png',
        new AbortController().signal,
      );
    });
    const execPromise = onExecMock.mock.calls[0][0];

    act(() => {
      resolveExecutionPromise(
        createMockServiceResult({ rawOutput: binaryBuffer }),
      );
    });
    await act(async () => await execPromise);

    const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
    expect(finalHistoryItem.tools[0].status).toBe(CoreToolCallStatus.Success);
    expect(finalHistoryItem.tools[0].resultDisplay).toBe(
      '[Command produced binary output, which is not shown.]',
    );
  });

  it('should prepend warnings to AnsiOutput array', async () => {
    const { result } = await renderProcessorHook();

    act(() => {
      result.current.handleShellCommand('ls', new AbortController().signal);
    });
    const execPromise = onExecMock.mock.calls[0][0];

    const ansiOutput: AnsiOutput = [
      [
        {
          text: 'ansi line 1',
          fg: '',
          bg: '',
          bold: false,
          dim: false,
          italic: false,
          underline: false,
          inverse: false,
          isUninitialized: false,
        },
      ],
    ];

    act(() => {
      resolveExecutionPromise(
        createMockServiceResult({
          exitCode: 1,
          output: 'ansi line 1',
          ansiOutput,
        }),
      );
    });
    await act(async () => await execPromise);

    expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
    expect(addItemToHistoryMock).toHaveBeenCalledTimes(2);

    const historyCall = addItemToHistoryMock.mock.calls[1][0];
    const display = historyCall.tools[0].resultDisplay;

    expect(Array.isArray(display)).toBe(true);
    expect(display.length).toBe(3); // Error line, empty line, original output
    expect(display[0][0].text).toBe('Command exited with code 1.');
    expect(display[2][0].text).toBe('ansi line 1');
  });

  it('should handle promise rejection and show an error', async () => {
    const { result } = await renderProcessorHook();
    const testError = new Error('Unexpected failure');
    mockShellExecutionService.mockImplementation(() => ({
      pid: 12345,
      result: Promise.reject(testError),
    }));

    act(() => {
      result.current.handleShellCommand(
        'a-command',
        new AbortController().signal,
      );
    });
    const execPromise = onExecMock.mock.calls[0][0];

    await act(async () => await execPromise);

    expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
    expect(addItemToHistoryMock).toHaveBeenCalledTimes(2);
    expect(addItemToHistoryMock.mock.calls[1][0]).toEqual({
      type: 'error',
      text: 'An unexpected error occurred: Unexpected failure',
    });
    expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
  });

  it('should handle synchronous errors during execution and clean up resources', async () => {
    const testError = new Error('Synchronous spawn error');
    mockShellExecutionService.mockImplementation(() => {
      throw testError;
    });
    // Mock that the temp file was created before the error was thrown
    vi.mocked(fs.existsSync).mockReturnValue(true);

    const { result } = await renderProcessorHook();

    act(() => {
      result.current.handleShellCommand(
        'a-command',
        new AbortController().signal,
      );
    });
    const execPromise = onExecMock.mock.calls[0][0];

    await act(async () => await execPromise);

    expect(setPendingHistoryItemMock).toHaveBeenCalledWith(null);
    expect(addItemToHistoryMock).toHaveBeenCalledTimes(2);
    expect(addItemToHistoryMock.mock.calls[1][0]).toEqual({
      type: 'error',
      text: 'An unexpected error occurred: Synchronous spawn error',
    });
    const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
    // Verify that the temporary file was cleaned up
    expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
    expect(setShellInputFocusedMock).toHaveBeenCalledWith(false);
  });

  describe('Directory Change Warning', () => {
    it('should show a warning if the working directory changes', async () => {
      const tmpFile = path.join('/tmp/gemini-shell-abcdef', 'pwd.tmp');
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.readFileSync).mockReturnValue('/test/dir/new'); // A different directory

      const { result } = await renderProcessorHook();
      act(() => {
        result.current.handleShellCommand(
          'cd new',
          new AbortController().signal,
        );
      });
      const execPromise = onExecMock.mock.calls[0][0];

      act(() => {
        resolveExecutionPromise(createMockServiceResult());
      });
      await act(async () => await execPromise);

      const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
      expect(finalHistoryItem.tools[0].resultDisplay).toContain(
        "WARNING: shell mode is stateless; the directory change to '/test/dir/new' will not persist.",
      );
      expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalledWith(tmpFile);
    });

    it('should NOT show a warning if the directory does not change', async () => {
      vi.mocked(fs.existsSync).mockReturnValue(true);
      vi.mocked(fs.readFileSync).mockReturnValue('/test/dir'); // The same directory

      const { result } = await renderProcessorHook();
      act(() => {
        result.current.handleShellCommand('ls', new AbortController().signal);
      });
      const execPromise = onExecMock.mock.calls[0][0];

      act(() => {
        resolveExecutionPromise(createMockServiceResult());
      });
      await act(async () => await execPromise);

      const finalHistoryItem = addItemToHistoryMock.mock.calls[1][0];
      expect(finalHistoryItem.tools[0].resultDisplay).not.toContain('WARNING');
    });
  });

  describe('ActiveShellPtyId management', () => {
    beforeEach(() => {
      // The real service returns a promise that resolves with the pid and result promise
      mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
        mockShellOutputCallback = callback;
        return Promise.resolve({
          pid: 12345,
          result: new Promise((resolve) => {
            resolveExecutionPromise = resolve;
          }),
        });
      });
    });

    it('should have activeShellPtyId as null initially', async () => {
      const { result } = await renderProcessorHook();
      expect(result.current.activeShellPtyId).toBeNull();
    });

    it('should set activeShellPtyId when a command with a PID starts', async () => {
      const { result } = await renderProcessorHook();

      await act(async () => {
        result.current.handleShellCommand('ls', new AbortController().signal);
      });

      expect(result.current.activeShellPtyId).toBe(12345);
    });

    it('should update the pending history item with the ptyId', async () => {
      const { result } = await renderProcessorHook();

      await act(async () => {
        result.current.handleShellCommand('ls', new AbortController().signal);
      });

      await waitFor(() => {
        // Wait for the second call which is the functional update
        expect(setPendingHistoryItemMock).toHaveBeenCalledTimes(2);
      });

      // The state update is functional, so we test it by executing it.
      const updaterFn = setPendingHistoryItemMock.mock.lastCall?.[0];
      expect(typeof updaterFn).toBe('function');

      // The initial state is the first call to setPendingHistoryItem
      const initialState = setPendingHistoryItemMock.mock.calls[0][0];
      const stateAfterPid = updaterFn(initialState);

      expect(stateAfterPid.tools[0].ptyId).toBe(12345);
    });

    it('should reset activeShellPtyId to null after successful execution', async () => {
      const { result } = await renderProcessorHook();

      await act(async () => {
        result.current.handleShellCommand('ls', new AbortController().signal);
      });
      const execPromise = onExecMock.mock.calls[0][0];

      expect(result.current.activeShellPtyId).toBe(12345);

      await act(async () => {
        resolveExecutionPromise(createMockServiceResult());
      });
      await act(async () => await execPromise);

      expect(result.current.activeShellPtyId).toBeNull();
    });

    it('should reset activeShellPtyId to null after failed execution', async () => {
      const { result } = await renderProcessorHook();

      await act(async () => {
        result.current.handleShellCommand(
          'bad-cmd',
          new AbortController().signal,
        );
      });
      const execPromise = onExecMock.mock.calls[0][0];

      expect(result.current.activeShellPtyId).toBe(12345);

      await act(async () => {
        resolveExecutionPromise(createMockServiceResult({ exitCode: 1 }));
      });
      await act(async () => await execPromise);

      expect(result.current.activeShellPtyId).toBeNull();
    });

    it('should reset activeShellPtyId to null if execution promise rejects', async () => {
      let rejectResultPromise: (reason?: unknown) => void;
      mockShellExecutionService.mockImplementation(() =>
        Promise.resolve({
          pid: 12345,
          result: new Promise((_, reject) => {
            rejectResultPromise = reject;
          }),
        }),
      );
      const { result } = await renderProcessorHook();

      await act(async () => {
        result.current.handleShellCommand('cmd', new AbortController().signal);
      });
      const execPromise = onExecMock.mock.calls[0][0];

      expect(result.current.activeShellPtyId).toBe(12345);

      await act(async () => {
        rejectResultPromise(new Error('Failure'));
      });

      await act(async () => await execPromise);

      expect(result.current.activeShellPtyId).toBeNull();
    });

    it('should not set activeShellPtyId on synchronous execution error and should remain null', async () => {
      mockShellExecutionService.mockImplementation(() => {
        throw new Error('Sync Error');
      });
      const { result } = await renderProcessorHook();

      expect(result.current.activeShellPtyId).toBeNull(); // Pre-condition

      act(() => {
        result.current.handleShellCommand('cmd', new AbortController().signal);
      });
      const execPromise = onExecMock.mock.calls[0][0];

      // The hook's state should not have changed to a PID
      expect(result.current.activeShellPtyId).toBeNull();

      await act(async () => await execPromise); // Let the promise resolve

      // And it should still be null after everything is done
      expect(result.current.activeShellPtyId).toBeNull();
    });

    it('should not set activeShellPtyId if service does not return a PID', async () => {
      mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
        mockShellOutputCallback = callback;
        return Promise.resolve({
          pid: undefined, // No PID
          result: new Promise((resolve) => {
            resolveExecutionPromise = resolve;
          }),
        });
      });

      const { result } = await renderProcessorHook();

      act(() => {
        result.current.handleShellCommand('ls', new AbortController().signal);
      });

      // Let microtasks run
      await act(async () => {});

      expect(result.current.activeShellPtyId).toBeNull();
    });
  });

  describe('Background Shell Management', () => {
    it('should register a background shell and update count', async () => {
      const { result } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });

      expect(result.current.backgroundTaskCount).toBe(1);
      const shell = result.current.backgroundTasks.get(1001);
      expect(shell).toEqual(
        expect.objectContaining({
          pid: 1001,
          command: 'bg-cmd',
          output: 'initial',
        }),
      );
      expect(mockLifecycleOnExit).toHaveBeenCalledWith(
        1001,
        expect.any(Function),
      );
      expect(mockLifecycleSubscribe).toHaveBeenCalledWith(
        1001,
        expect.any(Function),
      );
    });

    it('should toggle background shell visibility', async () => {
      const { result } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });

      expect(result.current.isBackgroundTaskVisible).toBe(false);

      act(() => {
        result.current.toggleBackgroundTasks();
      });

      expect(result.current.isBackgroundTaskVisible).toBe(true);

      act(() => {
        result.current.toggleBackgroundTasks();
      });

      expect(result.current.isBackgroundTaskVisible).toBe(false);
    });

    it('should show info message when toggling background shells if none are active', async () => {
      const { result } = await renderProcessorHook();

      act(() => {
        result.current.toggleBackgroundTasks();
      });

      expect(addItemToHistoryMock).toHaveBeenCalledWith(
        expect.objectContaining({
          type: 'info',
          text: 'No background tasks are currently active.',
        }),
        expect.any(Number),
      );
      expect(result.current.isBackgroundTaskVisible).toBe(false);
    });

    it('should dismiss a background shell and remove it from state', async () => {
      const { result } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });

      await act(async () => {
        await result.current.dismissBackgroundTask(1001);
      });

      expect(mockLifecycleKill).toHaveBeenCalledWith(1001);
      expect(result.current.backgroundTaskCount).toBe(0);
      expect(result.current.backgroundTasks.has(1001)).toBe(false);
    });

    it('should handle backgrounding the current shell', async () => {
      // Simulate an active shell
      mockShellExecutionService.mockImplementation((_cmd, _cwd, callback) => {
        mockShellOutputCallback = callback;
        return Promise.resolve({
          pid: 555,
          result: new Promise((resolve) => {
            resolveExecutionPromise = resolve;
          }),
        });
      });

      const { result } = await renderProcessorHook();

      await act(async () => {
        result.current.handleShellCommand('top', new AbortController().signal);
      });

      expect(result.current.activeShellPtyId).toBe(555);

      act(() => {
        result.current.backgroundCurrentExecution();
      });

      expect(mockShellBackground).toHaveBeenCalledWith(555);
      // The actual state update happens when the promise resolves with backgrounded: true
      // which is handled in handleShellCommand's .then block.
      // We simulate that here:

      await act(async () => {
        resolveExecutionPromise(
          createMockServiceResult({
            backgrounded: true,
            pid: 555,
            output: 'running...',
          }),
        );
      });
      // Wait for promise resolution
      await act(async () => await onExecMock.mock.calls[0][0]);

      expect(result.current.backgroundTaskCount).toBe(1);
      expect(result.current.activeShellPtyId).toBeNull();
    });

    it('should auto-dismiss background task on successful exit', async () => {
      const { result } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(888, 'auto-exit', '');
      });

      // Find the exit callback registered
      const exitCallback = mockLifecycleOnExit.mock.calls.find(
        (call) => call[0] === 888,
      )?.[1];
      expect(exitCallback).toBeDefined();

      if (exitCallback) {
        act(() => {
          exitCallback(0);
        });
      }

      // Should be auto-dismissed from the panel
      expect(result.current.backgroundTaskCount).toBe(0);
      expect(result.current.backgroundTasks.has(888)).toBe(false);
    });

    it('should auto-dismiss background task on failed exit', async () => {
      const { result } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(999, 'fail-exit', '');
      });

      const exitCallback = mockLifecycleOnExit.mock.calls.find(
        (call) => call[0] === 999,
      )?.[1];
      expect(exitCallback).toBeDefined();

      if (exitCallback) {
        act(() => {
          exitCallback(1);
        });
      }

      // Should be auto-dismissed from the panel
      expect(result.current.backgroundTaskCount).toBe(0);
      expect(result.current.backgroundTasks.has(999)).toBe(false);
    });

    it('should NOT trigger re-render on background shell output when visible', async () => {
      const { result, getRenderCount } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });

      // Show the background shells
      act(() => {
        result.current.toggleBackgroundTasks();
      });

      const initialRenderCount = getRenderCount();

      const subscribeCallback = mockLifecycleSubscribe.mock.calls.find(
        (call) => call[0] === 1001,
      )?.[1];
      expect(subscribeCallback).toBeDefined();

      if (subscribeCallback) {
        act(() => {
          subscribeCallback({ type: 'data', chunk: ' + updated' });
        });
      }

      expect(getRenderCount()).toBeGreaterThan(initialRenderCount);
      const shell = result.current.backgroundTasks.get(1001);
      expect(shell?.output).toBe('initial + updated');
    });

    it('should NOT trigger re-render on background shell output when hidden', async () => {
      const { result, getRenderCount } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });

      // Ensure background shells are hidden (default)
      const initialRenderCount = getRenderCount();

      const subscribeCallback = mockLifecycleSubscribe.mock.calls.find(
        (call) => call[0] === 1001,
      )?.[1];
      expect(subscribeCallback).toBeDefined();

      if (subscribeCallback) {
        act(() => {
          subscribeCallback({ type: 'data', chunk: ' + updated' });
        });
      }

      expect(getRenderCount()).toBeGreaterThan(initialRenderCount);
      const shell = result.current.backgroundTasks.get(1001);
      expect(shell?.output).toBe('initial + updated');
    });

    it('should trigger re-render on binary progress when visible', async () => {
      const { result, getRenderCount } = await renderProcessorHook();

      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });

      // Show the background shells
      act(() => {
        result.current.toggleBackgroundTasks();
      });

      const initialRenderCount = getRenderCount();

      const subscribeCallback = mockLifecycleSubscribe.mock.calls.find(
        (call) => call[0] === 1001,
      )?.[1];
      expect(subscribeCallback).toBeDefined();

      if (subscribeCallback) {
        act(() => {
          subscribeCallback({ type: 'binary_progress', bytesReceived: 1024 });
        });
      }

      expect(getRenderCount()).toBeGreaterThan(initialRenderCount);
      const shell = result.current.backgroundTasks.get(1001);
      expect(shell?.isBinary).toBe(true);
      expect(shell?.binaryBytesReceived).toBe(1024);
    });

    it('should NOT hide background shell when model is responding without confirmation', async () => {
      const { result, rerender } = await renderProcessorHook();

      // 1. Register and show background shell
      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });
      act(() => {
        result.current.toggleBackgroundTasks();
      });
      expect(result.current.isBackgroundTaskVisible).toBe(true);

      // 2. Simulate model responding (not waiting for confirmation)
      act(() => {
        rerender(false); // isWaitingForConfirmation = false
      });

      // Should stay visible
      expect(result.current.isBackgroundTaskVisible).toBe(true);
    });

    it('should hide background shell when waiting for confirmation and restore after delay', async () => {
      const { result, rerender } = await renderProcessorHook();

      // 1. Register and show background shell
      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });
      act(() => {
        result.current.toggleBackgroundTasks();
      });
      expect(result.current.isBackgroundTaskVisible).toBe(true);

      // 2. Simulate tool confirmation showing up
      act(() => {
        rerender(true); // isWaitingForConfirmation = true
      });

      // Should be hidden
      expect(result.current.isBackgroundTaskVisible).toBe(false);

      // 3. Simulate confirmation accepted (waiting for PTY start)
      act(() => {
        rerender(false);
      });

      // Should STAY hidden during the 300ms gap
      expect(result.current.isBackgroundTaskVisible).toBe(false);

      // 4. Wait for restore delay
      await waitFor(() =>
        expect(result.current.isBackgroundTaskVisible).toBe(true),
      );
    });

    it('should auto-hide background shell when foreground shell starts and restore when it ends', async () => {
      const { result } = await renderProcessorHook();

      // 1. Register and show background shell
      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });
      act(() => {
        result.current.toggleBackgroundTasks();
      });
      expect(result.current.isBackgroundTaskVisible).toBe(true);

      // 2. Start foreground shell
      act(() => {
        result.current.handleShellCommand('ls', new AbortController().signal);
      });

      // Wait for PID to be set
      await waitFor(() => expect(result.current.activeShellPtyId).toBe(12345));

      // Should be hidden automatically
      expect(result.current.isBackgroundTaskVisible).toBe(false);

      // 3. Complete foreground shell
      act(() => {
        resolveExecutionPromise(createMockServiceResult());
      });

      await waitFor(() => expect(result.current.activeShellPtyId).toBe(null));

      // Should be restored automatically (after delay)
      await waitFor(() =>
        expect(result.current.isBackgroundTaskVisible).toBe(true),
      );
    });

    it('should NOT restore background shell if it was manually hidden during foreground execution', async () => {
      const { result } = await renderProcessorHook();

      // 1. Register and show background shell
      act(() => {
        result.current.registerBackgroundTask(1001, 'bg-cmd', 'initial');
      });
      act(() => {
        result.current.toggleBackgroundTasks();
      });
      expect(result.current.isBackgroundTaskVisible).toBe(true);

      // 2. Start foreground shell
      act(() => {
        result.current.handleShellCommand('ls', new AbortController().signal);
      });
      await waitFor(() => expect(result.current.activeShellPtyId).toBe(12345));
      expect(result.current.isBackgroundTaskVisible).toBe(false);

      // 3. Manually toggle visibility (e.g. user wants to peek)
      act(() => {
        result.current.toggleBackgroundTasks();
      });
      expect(result.current.isBackgroundTaskVisible).toBe(true);

      // 4. Complete foreground shell
      act(() => {
        resolveExecutionPromise(createMockServiceResult());
      });
      await waitFor(() => expect(result.current.activeShellPtyId).toBe(null));

      // It should NOT change visibility because manual toggle cleared the auto-restore flag
      // After delay it should stay true (as it was manually toggled to true)
      await waitFor(() =>
        expect(result.current.isBackgroundTaskVisible).toBe(true),
      );
    });
  });
});