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

import { describe, it, expect } from 'vitest';
import {
  shellReducer,
  initialState,
  type ShellState,
  type ShellAction,
} from './shellReducer.js';
import {
  MAX_SHELL_OUTPUT_SIZE,
  SHELL_OUTPUT_TRUNCATION_BUFFER,
} from '../constants.js';

describe('shellReducer', () => {
  it('should return the initial state', () => {
    // @ts-expect-error - testing default case
    expect(shellReducer(initialState, { type: 'UNKNOWN' })).toEqual(
      initialState,
    );
  });

  it('should handle SET_ACTIVE_PTY', () => {
    const action: ShellAction = { type: 'SET_ACTIVE_PTY', pid: 12345 };
    const state = shellReducer(initialState, action);
    expect(state.activeShellPtyId).toBe(12345);
  });

  it('should handle SET_OUTPUT_TIME', () => {
    const now = Date.now();
    const action: ShellAction = { type: 'SET_OUTPUT_TIME', time: now };
    const state = shellReducer(initialState, action);
    expect(state.lastShellOutputTime).toBe(now);
  });

  it('should handle SET_VISIBILITY', () => {
    const action: ShellAction = { type: 'SET_VISIBILITY', visible: true };
    const state = shellReducer(initialState, action);
    expect(state.isBackgroundTaskVisible).toBe(true);
  });

  it('should handle TOGGLE_VISIBILITY', () => {
    const action: ShellAction = { type: 'TOGGLE_VISIBILITY' };
    let state = shellReducer(initialState, action);
    expect(state.isBackgroundTaskVisible).toBe(true);
    state = shellReducer(state, action);
    expect(state.isBackgroundTaskVisible).toBe(false);
  });

  it('should handle REGISTER_TASK', () => {
    const action: ShellAction = {
      type: 'REGISTER_TASK',
      pid: 1001,
      command: 'ls',
      initialOutput: 'init',
    };
    const state = shellReducer(initialState, action);
    expect(state.backgroundTasks.has(1001)).toBe(true);
    expect(state.backgroundTasks.get(1001)).toEqual({
      pid: 1001,
      command: 'ls',
      output: 'init',
      isBinary: false,
      binaryBytesReceived: 0,
      status: 'running',
    });
  });

  it('should not REGISTER_TASK if PID already exists', () => {
    const action: ShellAction = {
      type: 'REGISTER_TASK',
      pid: 1001,
      command: 'ls',
      initialOutput: 'init',
    };
    const state = shellReducer(initialState, action);
    const state2 = shellReducer(state, { ...action, command: 'other' });
    expect(state2).toBe(state);
    expect(state2.backgroundTasks.get(1001)?.command).toBe('ls');
  });

  it('should handle UPDATE_TASK', () => {
    const registeredState = shellReducer(initialState, {
      type: 'REGISTER_TASK',
      pid: 1001,
      command: 'ls',
      initialOutput: 'init',
    });

    const action: ShellAction = {
      type: 'UPDATE_TASK',
      pid: 1001,
      update: { status: 'exited', exitCode: 0 },
    };
    const state = shellReducer(registeredState, action);
    const shell = state.backgroundTasks.get(1001);
    expect(shell?.status).toBe('exited');
    expect(shell?.exitCode).toBe(0);
    // Map should be new
    expect(state.backgroundTasks).not.toBe(registeredState.backgroundTasks);
  });

  it('should handle APPEND_TASK_OUTPUT when visible (triggers re-render)', () => {
    const visibleState: ShellState = {
      ...initialState,
      isBackgroundTaskVisible: true,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'ls',
            output: 'init',
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = {
      type: 'APPEND_TASK_OUTPUT',
      pid: 1001,
      chunk: ' + more',
    };
    const state = shellReducer(visibleState, action);
    expect(state.backgroundTasks.get(1001)?.output).toBe('init + more');
    // Drawer is visible, so we expect a NEW map object to trigger React re-render
    expect(state.backgroundTasks).not.toBe(visibleState.backgroundTasks);
  });

  it('should handle APPEND_TASK_OUTPUT when hidden (no re-render optimization)', () => {
    const hiddenState: ShellState = {
      ...initialState,
      isBackgroundTaskVisible: false,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'ls',
            output: 'init',
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = {
      type: 'APPEND_TASK_OUTPUT',
      pid: 1001,
      chunk: ' + more',
    };
    const state = shellReducer(hiddenState, action);
    expect(state.backgroundTasks.get(1001)?.output).toBe('init + more');
    // Drawer is hidden, so we expect the SAME map object (mutation optimization)
    expect(state.backgroundTasks).toBe(hiddenState.backgroundTasks);
  });

  it('should handle SYNC_BACKGROUND_TASKS', () => {
    const action: ShellAction = { type: 'SYNC_BACKGROUND_TASKS' };
    const state = shellReducer(initialState, action);
    expect(state.backgroundTasks).not.toBe(initialState.backgroundTasks);
  });

  it('should handle DISMISS_TASK', () => {
    const registeredState: ShellState = {
      ...initialState,
      isBackgroundTaskVisible: true,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'ls',
            output: 'init',
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = { type: 'DISMISS_TASK', pid: 1001 };
    const state = shellReducer(registeredState, action);
    expect(state.backgroundTasks.has(1001)).toBe(false);
    expect(state.isBackgroundTaskVisible).toBe(false); // Auto-hide if last task
  });

  it('should NOT truncate output when below the size threshold', () => {
    const existingOutput = 'x'.repeat(MAX_SHELL_OUTPUT_SIZE - 1);
    const chunk = 'y';
    // combined length = MAX_SHELL_OUTPUT_SIZE, well below MAX + BUFFER
    const taskState: ShellState = {
      ...initialState,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'tail -f log',
            output: existingOutput,
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = {
      type: 'APPEND_TASK_OUTPUT',
      pid: 1001,
      chunk,
    };
    const state = shellReducer(taskState, action);
    const output = state.backgroundTasks.get(1001)?.output;
    expect(typeof output).toBe('string');
    expect((output as string).length).toBe(MAX_SHELL_OUTPUT_SIZE);
    expect((output as string).endsWith(chunk)).toBe(true);
  });

  it('should truncate output to MAX_SHELL_OUTPUT_SIZE when threshold is exceeded', () => {
    // existing output is already at MAX_SHELL_OUTPUT_SIZE + SHELL_OUTPUT_TRUNCATION_BUFFER
    const existingOutput = 'a'.repeat(
      MAX_SHELL_OUTPUT_SIZE + SHELL_OUTPUT_TRUNCATION_BUFFER,
    );
    const chunk = 'b'.repeat(100);
    // combined length = MAX + BUFFER + 100, which exceeds the threshold
    const taskState: ShellState = {
      ...initialState,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'tail -f log',
            output: existingOutput,
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = {
      type: 'APPEND_TASK_OUTPUT',
      pid: 1001,
      chunk,
    };
    const state = shellReducer(taskState, action);
    const output = state.backgroundTasks.get(1001)?.output;
    expect(typeof output).toBe('string');
    // After truncation the result should be exactly MAX_SHELL_OUTPUT_SIZE chars
    expect((output as string).length).toBe(MAX_SHELL_OUTPUT_SIZE);
    // The newest chunk should be preserved at the end
    expect((output as string).endsWith(chunk)).toBe(true);
  });

  it('should preserve output when appending empty string', () => {
    const originalOutput = 'important data' + 'x'.repeat(5000);
    const taskState: ShellState = {
      ...initialState,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'tail -f log',
            output: originalOutput,
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = {
      type: 'APPEND_TASK_OUTPUT',
      pid: 1001,
      chunk: '', // Empty string should not modify output
    };

    const state = shellReducer(taskState, action);
    const output = state.backgroundTasks.get(1001)?.output;

    // Empty string should leave output unchanged
    expect(output).toBe(originalOutput);
    expect(output).not.toBe('');
  });

  it('should handle chunks larger than MAX_SHELL_OUTPUT_SIZE', () => {
    // Setup: existing output that when combined with large chunk exceeds threshold
    const existingOutput = 'a'.repeat(1_500_000); // 1.5 MB
    const largeChunk = 'b'.repeat(MAX_SHELL_OUTPUT_SIZE + 10_000); // 10.01 MB
    // Combined exceeds MAX (10MB) + BUFFER (1MB) = 11MB threshold
    const taskState: ShellState = {
      ...initialState,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'test',
            output: existingOutput,
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = {
      type: 'APPEND_TASK_OUTPUT',
      pid: 1001,
      chunk: largeChunk,
    };

    const state = shellReducer(taskState, action);
    const output = state.backgroundTasks.get(1001)?.output as string;

    expect(typeof output).toBe('string');
    // After truncation, output should be exactly MAX_SHELL_OUTPUT_SIZE
    expect(output.length).toBe(MAX_SHELL_OUTPUT_SIZE);
    // Because largeChunk > MAX_SHELL_OUTPUT_SIZE, we only preserve its tail
    expect(output).toBe('b'.repeat(MAX_SHELL_OUTPUT_SIZE));
  });

  it('should not produce a broken surrogate pair at the truncation boundary', () => {
    // '😀' is U+1F600, encoded as the surrogate pair \uD83D\uDE00 (2 code units).
    // If a slice cuts between the high and low surrogate, the result starts with
    // a stray low surrogate (\uDE00). The reducer must detect and strip it.
    const emoji = '\uD83D\uDE00'; // 😀 — 2 UTF-16 code units
    // Fill up to just below the trigger threshold with 'a', then append an emoji
    // whose low surrogate lands exactly on the boundary so the slice splits it.
    const baseLength =
      MAX_SHELL_OUTPUT_SIZE + SHELL_OUTPUT_TRUNCATION_BUFFER - 1;
    const existingOutput = 'a'.repeat(baseLength);
    // chunk = emoji + padding so combinedLength exceeds the threshold
    const chunk = emoji + 'z';

    const taskState: ShellState = {
      ...initialState,
      backgroundTasks: new Map([
        [
          1001,
          {
            pid: 1001,
            command: 'test',
            output: existingOutput,
            isBinary: false,
            binaryBytesReceived: 0,
            status: 'running',
          },
        ],
      ]),
    };

    const action: ShellAction = {
      type: 'APPEND_TASK_OUTPUT',
      pid: 1001,
      chunk,
    };

    const state = shellReducer(taskState, action);
    const output = state.backgroundTasks.get(1001)?.output as string;

    expect(typeof output).toBe('string');
    // The output must not begin with a lone low surrogate (U+DC00–U+DFFF).
    const firstCharCode = output.charCodeAt(0);
    const isLowSurrogate = firstCharCode >= 0xdc00 && firstCharCode <= 0xdfff;
    expect(isLowSurrogate).toBe(false);
    // The final 'z' from the chunk must always be preserved.
    expect(output.endsWith('z')).toBe(true);
  });
});