ADAPT-Chase commited on
Commit
6d75833
·
verified ·
1 Parent(s): 8344751

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/cli/src/ui/themes/theme.ts +451 -0
  2. projects/ui/qwen-code/packages/cli/src/ui/themes/xcode.ts +154 -0
  3. projects/ui/qwen-code/packages/cli/src/ui/utils/CodeColorizer.tsx +217 -0
  4. projects/ui/qwen-code/packages/cli/src/ui/utils/ConsolePatcher.ts +71 -0
  5. projects/ui/qwen-code/packages/cli/src/ui/utils/InlineMarkdownRenderer.tsx +173 -0
  6. projects/ui/qwen-code/packages/cli/src/ui/utils/MarkdownDisplay.test.tsx +244 -0
  7. projects/ui/qwen-code/packages/cli/src/ui/utils/MarkdownDisplay.tsx +415 -0
  8. projects/ui/qwen-code/packages/cli/src/ui/utils/TableRenderer.tsx +159 -0
  9. projects/ui/qwen-code/packages/cli/src/ui/utils/clipboardUtils.test.ts +76 -0
  10. projects/ui/qwen-code/packages/cli/src/ui/utils/clipboardUtils.ts +149 -0
  11. projects/ui/qwen-code/packages/cli/src/ui/utils/commandUtils.test.ts +384 -0
  12. projects/ui/qwen-code/packages/cli/src/ui/utils/commandUtils.ts +106 -0
  13. projects/ui/qwen-code/packages/cli/src/ui/utils/computeStats.test.ts +292 -0
  14. projects/ui/qwen-code/packages/cli/src/ui/utils/computeStats.ts +86 -0
  15. projects/ui/qwen-code/packages/cli/src/ui/utils/displayUtils.test.ts +58 -0
  16. projects/ui/qwen-code/packages/cli/src/ui/utils/displayUtils.ts +32 -0
  17. projects/ui/qwen-code/packages/cli/src/ui/utils/formatters.test.ts +72 -0
  18. projects/ui/qwen-code/packages/cli/src/ui/utils/formatters.ts +63 -0
  19. projects/ui/qwen-code/packages/cli/src/ui/utils/isNarrowWidth.ts +9 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/utils/kittyProtocolDetector.ts +105 -0
projects/ui/qwen-code/packages/cli/src/ui/themes/theme.ts ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import type { CSSProperties } from 'react';
8
+ import { SemanticColors } from './semantic-tokens.js';
9
+ import { resolveColor } from './color-utils.js';
10
+
11
+ export type ThemeType = 'light' | 'dark' | 'ansi' | 'custom';
12
+
13
+ export interface ColorsTheme {
14
+ type: ThemeType;
15
+ Background: string;
16
+ Foreground: string;
17
+ LightBlue: string;
18
+ AccentBlue: string;
19
+ AccentPurple: string;
20
+ AccentCyan: string;
21
+ AccentGreen: string;
22
+ AccentYellow: string;
23
+ AccentRed: string;
24
+ DiffAdded: string;
25
+ DiffRemoved: string;
26
+ Comment: string;
27
+ Gray: string;
28
+ GradientColors?: string[];
29
+ }
30
+
31
+ export interface CustomTheme {
32
+ type: 'custom';
33
+ name: string;
34
+
35
+ text?: {
36
+ primary?: string;
37
+ secondary?: string;
38
+ link?: string;
39
+ accent?: string;
40
+ };
41
+ background?: {
42
+ primary?: string;
43
+ diff?: {
44
+ added?: string;
45
+ removed?: string;
46
+ };
47
+ };
48
+ border?: {
49
+ default?: string;
50
+ focused?: string;
51
+ };
52
+ ui?: {
53
+ comment?: string;
54
+ symbol?: string;
55
+ gradient?: string[];
56
+ };
57
+ status?: {
58
+ error?: string;
59
+ success?: string;
60
+ warning?: string;
61
+ };
62
+
63
+ // Legacy properties (all optional)
64
+ Background?: string;
65
+ Foreground?: string;
66
+ LightBlue?: string;
67
+ AccentBlue?: string;
68
+ AccentPurple?: string;
69
+ AccentCyan?: string;
70
+ AccentGreen?: string;
71
+ AccentYellow?: string;
72
+ AccentRed?: string;
73
+ DiffAdded?: string;
74
+ DiffRemoved?: string;
75
+ Comment?: string;
76
+ Gray?: string;
77
+ GradientColors?: string[];
78
+ }
79
+
80
+ export const lightTheme: ColorsTheme = {
81
+ type: 'light',
82
+ Background: '#FAFAFA',
83
+ Foreground: '#3C3C43',
84
+ LightBlue: '#89BDCD',
85
+ AccentBlue: '#3B82F6',
86
+ AccentPurple: '#8B5CF6',
87
+ AccentCyan: '#06B6D4',
88
+ AccentGreen: '#3CA84B',
89
+ AccentYellow: '#D5A40A',
90
+ AccentRed: '#DD4C4C',
91
+ DiffAdded: '#C6EAD8',
92
+ DiffRemoved: '#FFCCCC',
93
+ Comment: '#008000',
94
+ Gray: '#97a0b0',
95
+ GradientColors: ['#4796E4', '#847ACE', '#C3677F'],
96
+ };
97
+
98
+ export const darkTheme: ColorsTheme = {
99
+ type: 'dark',
100
+ Background: '#1E1E2E',
101
+ Foreground: '#CDD6F4',
102
+ LightBlue: '#ADD8E6',
103
+ AccentBlue: '#89B4FA',
104
+ AccentPurple: '#CBA6F7',
105
+ AccentCyan: '#89DCEB',
106
+ AccentGreen: '#A6E3A1',
107
+ AccentYellow: '#F9E2AF',
108
+ AccentRed: '#F38BA8',
109
+ DiffAdded: '#28350B',
110
+ DiffRemoved: '#430000',
111
+ Comment: '#6C7086',
112
+ Gray: '#6C7086',
113
+ GradientColors: ['#4796E4', '#847ACE', '#C3677F'],
114
+ };
115
+
116
+ export const ansiTheme: ColorsTheme = {
117
+ type: 'ansi',
118
+ Background: 'black',
119
+ Foreground: 'white',
120
+ LightBlue: 'blue',
121
+ AccentBlue: 'blue',
122
+ AccentPurple: 'magenta',
123
+ AccentCyan: 'cyan',
124
+ AccentGreen: 'green',
125
+ AccentYellow: 'yellow',
126
+ AccentRed: 'red',
127
+ DiffAdded: 'green',
128
+ DiffRemoved: 'red',
129
+ Comment: 'gray',
130
+ Gray: 'gray',
131
+ };
132
+
133
+ export class Theme {
134
+ /**
135
+ * The default foreground color for text when no specific highlight rule applies.
136
+ * This is an Ink-compatible color string (hex or name).
137
+ */
138
+ readonly defaultColor: string;
139
+ /**
140
+ * Stores the mapping from highlight.js class names (e.g., 'hljs-keyword')
141
+ * to Ink-compatible color strings (hex or name).
142
+ */
143
+ protected readonly _colorMap: Readonly<Record<string, string>>;
144
+
145
+ /**
146
+ * Creates a new Theme instance.
147
+ * @param name The name of the theme.
148
+ * @param rawMappings The raw CSSProperties mappings from a react-syntax-highlighter theme object.
149
+ */
150
+ constructor(
151
+ readonly name: string,
152
+ readonly type: ThemeType,
153
+ rawMappings: Record<string, CSSProperties>,
154
+ readonly colors: ColorsTheme,
155
+ readonly semanticColors: SemanticColors,
156
+ ) {
157
+ this._colorMap = Object.freeze(this._buildColorMap(rawMappings)); // Build and freeze the map
158
+
159
+ // Determine the default foreground color
160
+ const rawDefaultColor = rawMappings['hljs']?.color;
161
+ this.defaultColor =
162
+ (rawDefaultColor ? Theme._resolveColor(rawDefaultColor) : undefined) ??
163
+ ''; // Default to empty string if not found or resolvable
164
+ }
165
+
166
+ /**
167
+ * Gets the Ink-compatible color string for a given highlight.js class name.
168
+ * @param hljsClass The highlight.js class name (e.g., 'hljs-keyword', 'hljs-string').
169
+ * @returns The corresponding Ink color string (hex or name) if it exists.
170
+ */
171
+ getInkColor(hljsClass: string): string | undefined {
172
+ return this._colorMap[hljsClass];
173
+ }
174
+
175
+ /**
176
+ * Resolves a CSS color value (name or hex) into an Ink-compatible color string.
177
+ * @param colorValue The raw color string (e.g., 'blue', '#ff0000', 'darkkhaki').
178
+ * @returns An Ink-compatible color string (hex or name), or undefined if not resolvable.
179
+ */
180
+ private static _resolveColor(colorValue: string): string | undefined {
181
+ return resolveColor(colorValue);
182
+ }
183
+
184
+ /**
185
+ * Builds the internal map from highlight.js class names to Ink-compatible color strings.
186
+ * This method is protected and primarily intended for use by the constructor.
187
+ * @param hljsTheme The raw CSSProperties mappings from a react-syntax-highlighter theme object.
188
+ * @returns An Ink-compatible theme map (Record<string, string>).
189
+ */
190
+ protected _buildColorMap(
191
+ hljsTheme: Record<string, CSSProperties>,
192
+ ): Record<string, string> {
193
+ const inkTheme: Record<string, string> = {};
194
+ for (const key in hljsTheme) {
195
+ // Ensure the key starts with 'hljs-' or is 'hljs' for the base style
196
+ if (!key.startsWith('hljs-') && key !== 'hljs') {
197
+ continue; // Skip keys not related to highlighting classes
198
+ }
199
+
200
+ const style = hljsTheme[key];
201
+ if (style?.color) {
202
+ const resolvedColor = Theme._resolveColor(style.color);
203
+ if (resolvedColor !== undefined) {
204
+ // Use the original key from the hljsTheme (e.g., 'hljs-keyword')
205
+ inkTheme[key] = resolvedColor;
206
+ }
207
+ // If color is not resolvable, it's omitted from the map,
208
+ // this enables falling back to the default foreground color.
209
+ }
210
+ // We currently only care about the 'color' property for Ink rendering.
211
+ // Other properties like background, fontStyle, etc., are ignored.
212
+ }
213
+ return inkTheme;
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Creates a Theme instance from a custom theme configuration.
219
+ * @param customTheme The custom theme configuration.
220
+ * @returns A new Theme instance.
221
+ */
222
+ export function createCustomTheme(customTheme: CustomTheme): Theme {
223
+ const colors: ColorsTheme = {
224
+ type: 'custom',
225
+ Background: customTheme.background?.primary ?? customTheme.Background ?? '',
226
+ Foreground: customTheme.text?.primary ?? customTheme.Foreground ?? '',
227
+ LightBlue: customTheme.text?.link ?? customTheme.LightBlue ?? '',
228
+ AccentBlue: customTheme.text?.link ?? customTheme.AccentBlue ?? '',
229
+ AccentPurple: customTheme.text?.accent ?? customTheme.AccentPurple ?? '',
230
+ AccentCyan: customTheme.text?.link ?? customTheme.AccentCyan ?? '',
231
+ AccentGreen: customTheme.status?.success ?? customTheme.AccentGreen ?? '',
232
+ AccentYellow: customTheme.status?.warning ?? customTheme.AccentYellow ?? '',
233
+ AccentRed: customTheme.status?.error ?? customTheme.AccentRed ?? '',
234
+ DiffAdded:
235
+ customTheme.background?.diff?.added ?? customTheme.DiffAdded ?? '',
236
+ DiffRemoved:
237
+ customTheme.background?.diff?.removed ?? customTheme.DiffRemoved ?? '',
238
+ Comment: customTheme.ui?.comment ?? customTheme.Comment ?? '',
239
+ Gray: customTheme.text?.secondary ?? customTheme.Gray ?? '',
240
+ GradientColors: customTheme.ui?.gradient ?? customTheme.GradientColors,
241
+ };
242
+
243
+ // Generate CSS properties mappings based on the custom theme colors
244
+ const rawMappings: Record<string, CSSProperties> = {
245
+ hljs: {
246
+ display: 'block',
247
+ overflowX: 'auto',
248
+ padding: '0.5em',
249
+ background: colors.Background,
250
+ color: colors.Foreground,
251
+ },
252
+ 'hljs-keyword': {
253
+ color: colors.AccentBlue,
254
+ },
255
+ 'hljs-literal': {
256
+ color: colors.AccentBlue,
257
+ },
258
+ 'hljs-symbol': {
259
+ color: colors.AccentBlue,
260
+ },
261
+ 'hljs-name': {
262
+ color: colors.AccentBlue,
263
+ },
264
+ 'hljs-link': {
265
+ color: colors.AccentBlue,
266
+ textDecoration: 'underline',
267
+ },
268
+ 'hljs-built_in': {
269
+ color: colors.AccentCyan,
270
+ },
271
+ 'hljs-type': {
272
+ color: colors.AccentCyan,
273
+ },
274
+ 'hljs-number': {
275
+ color: colors.AccentGreen,
276
+ },
277
+ 'hljs-class': {
278
+ color: colors.AccentGreen,
279
+ },
280
+ 'hljs-string': {
281
+ color: colors.AccentYellow,
282
+ },
283
+ 'hljs-meta-string': {
284
+ color: colors.AccentYellow,
285
+ },
286
+ 'hljs-regexp': {
287
+ color: colors.AccentRed,
288
+ },
289
+ 'hljs-template-tag': {
290
+ color: colors.AccentRed,
291
+ },
292
+ 'hljs-subst': {
293
+ color: colors.Foreground,
294
+ },
295
+ 'hljs-function': {
296
+ color: colors.Foreground,
297
+ },
298
+ 'hljs-title': {
299
+ color: colors.Foreground,
300
+ },
301
+ 'hljs-params': {
302
+ color: colors.Foreground,
303
+ },
304
+ 'hljs-formula': {
305
+ color: colors.Foreground,
306
+ },
307
+ 'hljs-comment': {
308
+ color: colors.Comment,
309
+ fontStyle: 'italic',
310
+ },
311
+ 'hljs-quote': {
312
+ color: colors.Comment,
313
+ fontStyle: 'italic',
314
+ },
315
+ 'hljs-doctag': {
316
+ color: colors.Comment,
317
+ },
318
+ 'hljs-meta': {
319
+ color: colors.Gray,
320
+ },
321
+ 'hljs-meta-keyword': {
322
+ color: colors.Gray,
323
+ },
324
+ 'hljs-tag': {
325
+ color: colors.Gray,
326
+ },
327
+ 'hljs-variable': {
328
+ color: colors.AccentPurple,
329
+ },
330
+ 'hljs-template-variable': {
331
+ color: colors.AccentPurple,
332
+ },
333
+ 'hljs-attr': {
334
+ color: colors.LightBlue,
335
+ },
336
+ 'hljs-attribute': {
337
+ color: colors.LightBlue,
338
+ },
339
+ 'hljs-builtin-name': {
340
+ color: colors.LightBlue,
341
+ },
342
+ 'hljs-section': {
343
+ color: colors.AccentYellow,
344
+ },
345
+ 'hljs-emphasis': {
346
+ fontStyle: 'italic',
347
+ },
348
+ 'hljs-strong': {
349
+ fontWeight: 'bold',
350
+ },
351
+ 'hljs-bullet': {
352
+ color: colors.AccentYellow,
353
+ },
354
+ 'hljs-selector-tag': {
355
+ color: colors.AccentYellow,
356
+ },
357
+ 'hljs-selector-id': {
358
+ color: colors.AccentYellow,
359
+ },
360
+ 'hljs-selector-class': {
361
+ color: colors.AccentYellow,
362
+ },
363
+ 'hljs-selector-attr': {
364
+ color: colors.AccentYellow,
365
+ },
366
+ 'hljs-selector-pseudo': {
367
+ color: colors.AccentYellow,
368
+ },
369
+ 'hljs-addition': {
370
+ backgroundColor: colors.AccentGreen,
371
+ display: 'inline-block',
372
+ width: '100%',
373
+ },
374
+ 'hljs-deletion': {
375
+ backgroundColor: colors.AccentRed,
376
+ display: 'inline-block',
377
+ width: '100%',
378
+ },
379
+ };
380
+
381
+ const semanticColors: SemanticColors = {
382
+ text: {
383
+ primary: colors.Foreground,
384
+ secondary: colors.Gray,
385
+ link: colors.AccentBlue,
386
+ accent: colors.AccentPurple,
387
+ },
388
+ background: {
389
+ primary: colors.Background,
390
+ diff: {
391
+ added: colors.DiffAdded,
392
+ removed: colors.DiffRemoved,
393
+ },
394
+ },
395
+ border: {
396
+ default: colors.Gray,
397
+ focused: colors.AccentBlue,
398
+ },
399
+ ui: {
400
+ comment: colors.Comment,
401
+ symbol: colors.Gray,
402
+ gradient: colors.GradientColors,
403
+ },
404
+ status: {
405
+ error: colors.AccentRed,
406
+ success: colors.AccentGreen,
407
+ warning: colors.AccentYellow,
408
+ },
409
+ };
410
+
411
+ return new Theme(
412
+ customTheme.name,
413
+ 'custom',
414
+ rawMappings,
415
+ colors,
416
+ semanticColors,
417
+ );
418
+ }
419
+
420
+ /**
421
+ * Validates a custom theme configuration.
422
+ * @param customTheme The custom theme to validate.
423
+ * @returns An object with isValid boolean and error message if invalid.
424
+ */
425
+ export function validateCustomTheme(customTheme: Partial<CustomTheme>): {
426
+ isValid: boolean;
427
+ error?: string;
428
+ warning?: string;
429
+ } {
430
+ // Since all fields are optional, we only need to validate the name.
431
+ if (customTheme.name && !isValidThemeName(customTheme.name)) {
432
+ return {
433
+ isValid: false,
434
+ error: `Invalid theme name: ${customTheme.name}`,
435
+ };
436
+ }
437
+
438
+ return {
439
+ isValid: true,
440
+ };
441
+ }
442
+
443
+ /**
444
+ * Checks if a theme name is valid.
445
+ * @param name The theme name to validate.
446
+ * @returns True if the theme name is valid.
447
+ */
448
+ function isValidThemeName(name: string): boolean {
449
+ // Theme name should be non-empty and not contain invalid characters
450
+ return name.trim().length > 0 && name.trim().length <= 50;
451
+ }
projects/ui/qwen-code/packages/cli/src/ui/themes/xcode.ts ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { type ColorsTheme, Theme } from './theme.js';
8
+ import { lightSemanticColors } from './semantic-tokens.js';
9
+
10
+ const xcodeColors: ColorsTheme = {
11
+ type: 'light',
12
+ Background: '#fff',
13
+ Foreground: '#444',
14
+ LightBlue: '#0E0EFF',
15
+ AccentBlue: '#1c00cf',
16
+ AccentPurple: '#aa0d91',
17
+ AccentCyan: '#3F6E74',
18
+ AccentGreen: '#007400',
19
+ AccentYellow: '#836C28',
20
+ AccentRed: '#c41a16',
21
+ DiffAdded: '#C6EAD8',
22
+ DiffRemoved: '#FEDEDE',
23
+ Comment: '#007400',
24
+ Gray: '#c0c0c0',
25
+ GradientColors: ['#1c00cf', '#007400'],
26
+ };
27
+
28
+ export const XCode: Theme = new Theme(
29
+ 'Xcode',
30
+ 'light',
31
+ {
32
+ hljs: {
33
+ display: 'block',
34
+ overflowX: 'auto',
35
+ padding: '0.5em',
36
+ background: xcodeColors.Background,
37
+ color: xcodeColors.Foreground,
38
+ },
39
+ 'xml .hljs-meta': {
40
+ color: xcodeColors.Gray,
41
+ },
42
+ 'hljs-comment': {
43
+ color: xcodeColors.Comment,
44
+ },
45
+ 'hljs-quote': {
46
+ color: xcodeColors.Comment,
47
+ },
48
+ 'hljs-tag': {
49
+ color: xcodeColors.AccentPurple,
50
+ },
51
+ 'hljs-attribute': {
52
+ color: xcodeColors.AccentPurple,
53
+ },
54
+ 'hljs-keyword': {
55
+ color: xcodeColors.AccentPurple,
56
+ },
57
+ 'hljs-selector-tag': {
58
+ color: xcodeColors.AccentPurple,
59
+ },
60
+ 'hljs-literal': {
61
+ color: xcodeColors.AccentPurple,
62
+ },
63
+ 'hljs-name': {
64
+ color: xcodeColors.AccentPurple,
65
+ },
66
+ 'hljs-variable': {
67
+ color: xcodeColors.AccentCyan,
68
+ },
69
+ 'hljs-template-variable': {
70
+ color: xcodeColors.AccentCyan,
71
+ },
72
+ 'hljs-code': {
73
+ color: xcodeColors.AccentRed,
74
+ },
75
+ 'hljs-string': {
76
+ color: xcodeColors.AccentRed,
77
+ },
78
+ 'hljs-meta-string': {
79
+ color: xcodeColors.AccentRed,
80
+ },
81
+ 'hljs-regexp': {
82
+ color: xcodeColors.LightBlue,
83
+ },
84
+ 'hljs-link': {
85
+ color: xcodeColors.LightBlue,
86
+ },
87
+ 'hljs-title': {
88
+ color: xcodeColors.AccentBlue,
89
+ },
90
+ 'hljs-symbol': {
91
+ color: xcodeColors.AccentBlue,
92
+ },
93
+ 'hljs-bullet': {
94
+ color: xcodeColors.AccentBlue,
95
+ },
96
+ 'hljs-number': {
97
+ color: xcodeColors.AccentBlue,
98
+ },
99
+ 'hljs-section': {
100
+ color: xcodeColors.AccentYellow,
101
+ },
102
+ 'hljs-meta': {
103
+ color: xcodeColors.AccentYellow,
104
+ },
105
+ 'hljs-class .hljs-title': {
106
+ color: xcodeColors.AccentPurple,
107
+ },
108
+ 'hljs-type': {
109
+ color: xcodeColors.AccentPurple,
110
+ },
111
+ 'hljs-built_in': {
112
+ color: xcodeColors.AccentPurple,
113
+ },
114
+ 'hljs-builtin-name': {
115
+ color: xcodeColors.AccentPurple,
116
+ },
117
+ 'hljs-params': {
118
+ color: xcodeColors.AccentPurple,
119
+ },
120
+ 'hljs-attr': {
121
+ color: xcodeColors.AccentYellow,
122
+ },
123
+ 'hljs-subst': {
124
+ color: xcodeColors.Foreground,
125
+ },
126
+ 'hljs-formula': {
127
+ backgroundColor: '#eee',
128
+ fontStyle: 'italic',
129
+ },
130
+ 'hljs-addition': {
131
+ backgroundColor: '#baeeba',
132
+ },
133
+ 'hljs-deletion': {
134
+ backgroundColor: '#ffc8bd',
135
+ },
136
+ 'hljs-selector-id': {
137
+ color: xcodeColors.AccentYellow,
138
+ },
139
+ 'hljs-selector-class': {
140
+ color: xcodeColors.AccentYellow,
141
+ },
142
+ 'hljs-doctag': {
143
+ fontWeight: 'bold',
144
+ },
145
+ 'hljs-strong': {
146
+ fontWeight: 'bold',
147
+ },
148
+ 'hljs-emphasis': {
149
+ fontStyle: 'italic',
150
+ },
151
+ },
152
+ xcodeColors,
153
+ lightSemanticColors,
154
+ );
projects/ui/qwen-code/packages/cli/src/ui/utils/CodeColorizer.tsx ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Text, Box } from 'ink';
9
+ import { common, createLowlight } from 'lowlight';
10
+ import type {
11
+ Root,
12
+ Element,
13
+ Text as HastText,
14
+ ElementContent,
15
+ RootContent,
16
+ } from 'hast';
17
+ import { themeManager } from '../themes/theme-manager.js';
18
+ import { Theme } from '../themes/theme.js';
19
+ import {
20
+ MaxSizedBox,
21
+ MINIMUM_MAX_HEIGHT,
22
+ } from '../components/shared/MaxSizedBox.js';
23
+ import { LoadedSettings } from '../../config/settings.js';
24
+
25
+ // Configure theming and parsing utilities.
26
+ const lowlight = createLowlight(common);
27
+
28
+ function renderHastNode(
29
+ node: Root | Element | HastText | RootContent,
30
+ theme: Theme,
31
+ inheritedColor: string | undefined,
32
+ ): React.ReactNode {
33
+ if (node.type === 'text') {
34
+ // Use the color passed down from parent element, if any
35
+ return <Text color={inheritedColor}>{node.value}</Text>;
36
+ }
37
+
38
+ // Handle Element Nodes: Determine color and pass it down, don't wrap
39
+ if (node.type === 'element') {
40
+ const nodeClasses: string[] =
41
+ (node.properties?.['className'] as string[]) || [];
42
+ let elementColor: string | undefined = undefined;
43
+
44
+ // Find color defined specifically for this element's class
45
+ for (let i = nodeClasses.length - 1; i >= 0; i--) {
46
+ const color = theme.getInkColor(nodeClasses[i]);
47
+ if (color) {
48
+ elementColor = color;
49
+ break;
50
+ }
51
+ }
52
+
53
+ // Determine the color to pass down: Use this element's specific color
54
+ // if found; otherwise, continue passing down the already inherited color.
55
+ const colorToPassDown = elementColor || inheritedColor;
56
+
57
+ // Recursively render children, passing the determined color down
58
+ // Ensure child type matches expected HAST structure (ElementContent is common)
59
+ const children = node.children?.map(
60
+ (child: ElementContent, index: number) => (
61
+ <React.Fragment key={index}>
62
+ {renderHastNode(child, theme, colorToPassDown)}
63
+ </React.Fragment>
64
+ ),
65
+ );
66
+
67
+ // Element nodes now only group children; color is applied by Text nodes.
68
+ // Use a React Fragment to avoid adding unnecessary elements.
69
+ return <React.Fragment>{children}</React.Fragment>;
70
+ }
71
+
72
+ // Handle Root Node: Start recursion with initially inherited color
73
+ if (node.type === 'root') {
74
+ // Check if children array is empty - this happens when lowlight can't detect language – fall back to plain text
75
+ if (!node.children || node.children.length === 0) {
76
+ return null;
77
+ }
78
+
79
+ // Pass down the initial inheritedColor (likely undefined from the top call)
80
+ // Ensure child type matches expected HAST structure (RootContent is common)
81
+ return node.children?.map((child: RootContent, index: number) => (
82
+ <React.Fragment key={index}>
83
+ {renderHastNode(child, theme, inheritedColor)}
84
+ </React.Fragment>
85
+ ));
86
+ }
87
+
88
+ // Handle unknown or unsupported node types
89
+ return null;
90
+ }
91
+
92
+ function highlightAndRenderLine(
93
+ line: string,
94
+ language: string | null,
95
+ theme: Theme,
96
+ ): React.ReactNode {
97
+ try {
98
+ const getHighlightedLine = () =>
99
+ !language || !lowlight.registered(language)
100
+ ? lowlight.highlightAuto(line)
101
+ : lowlight.highlight(language, line);
102
+
103
+ const renderedNode = renderHastNode(getHighlightedLine(), theme, undefined);
104
+
105
+ return renderedNode !== null ? renderedNode : line;
106
+ } catch (_error) {
107
+ return line;
108
+ }
109
+ }
110
+
111
+ export function colorizeLine(
112
+ line: string,
113
+ language: string | null,
114
+ theme?: Theme,
115
+ ): React.ReactNode {
116
+ const activeTheme = theme || themeManager.getActiveTheme();
117
+ return highlightAndRenderLine(line, language, activeTheme);
118
+ }
119
+
120
+ /**
121
+ * Renders syntax-highlighted code for Ink applications using a selected theme.
122
+ *
123
+ * @param code The code string to highlight.
124
+ * @param language The language identifier (e.g., 'javascript', 'css', 'html')
125
+ * @returns A React.ReactNode containing Ink <Text> elements for the highlighted code.
126
+ */
127
+ export function colorizeCode(
128
+ code: string,
129
+ language: string | null,
130
+ availableHeight?: number,
131
+ maxWidth?: number,
132
+ theme?: Theme,
133
+ settings?: LoadedSettings,
134
+ ): React.ReactNode {
135
+ const codeToHighlight = code.replace(/\n$/, '');
136
+ const activeTheme = theme || themeManager.getActiveTheme();
137
+ const showLineNumbers = settings?.merged.showLineNumbers ?? true;
138
+
139
+ try {
140
+ // Render the HAST tree using the adapted theme
141
+ // Apply the theme's default foreground color to the top-level Text element
142
+ let lines = codeToHighlight.split('\n');
143
+ const padWidth = String(lines.length).length; // Calculate padding width based on number of lines
144
+
145
+ let hiddenLinesCount = 0;
146
+
147
+ // Optimization to avoid highlighting lines that cannot possibly be displayed.
148
+ if (availableHeight !== undefined) {
149
+ availableHeight = Math.max(availableHeight, MINIMUM_MAX_HEIGHT);
150
+ if (lines.length > availableHeight) {
151
+ const sliceIndex = lines.length - availableHeight;
152
+ hiddenLinesCount = sliceIndex;
153
+ lines = lines.slice(sliceIndex);
154
+ }
155
+ }
156
+
157
+ return (
158
+ <MaxSizedBox
159
+ maxHeight={availableHeight}
160
+ maxWidth={maxWidth}
161
+ additionalHiddenLinesCount={hiddenLinesCount}
162
+ overflowDirection="top"
163
+ >
164
+ {lines.map((line, index) => {
165
+ const contentToRender = highlightAndRenderLine(
166
+ line,
167
+ language,
168
+ activeTheme,
169
+ );
170
+
171
+ return (
172
+ <Box key={index}>
173
+ {showLineNumbers && (
174
+ <Text color={activeTheme.colors.Gray}>
175
+ {`${String(index + 1 + hiddenLinesCount).padStart(
176
+ padWidth,
177
+ ' ',
178
+ )} `}
179
+ </Text>
180
+ )}
181
+ <Text color={activeTheme.defaultColor} wrap="wrap">
182
+ {contentToRender}
183
+ </Text>
184
+ </Box>
185
+ );
186
+ })}
187
+ </MaxSizedBox>
188
+ );
189
+ } catch (error) {
190
+ console.error(
191
+ `[colorizeCode] Error highlighting code for language "${language}":`,
192
+ error,
193
+ );
194
+ // Fall back to plain text with default color on error
195
+ // Also display line numbers in fallback
196
+ const lines = codeToHighlight.split('\n');
197
+ const padWidth = String(lines.length).length; // Calculate padding width based on number of lines
198
+ return (
199
+ <MaxSizedBox
200
+ maxHeight={availableHeight}
201
+ maxWidth={maxWidth}
202
+ overflowDirection="top"
203
+ >
204
+ {lines.map((line, index) => (
205
+ <Box key={index}>
206
+ {showLineNumbers && (
207
+ <Text color={activeTheme.defaultColor}>
208
+ {`${String(index + 1).padStart(padWidth, ' ')} `}
209
+ </Text>
210
+ )}
211
+ <Text color={activeTheme.colors.Gray}>{line}</Text>
212
+ </Box>
213
+ ))}
214
+ </MaxSizedBox>
215
+ );
216
+ }
217
+ }
projects/ui/qwen-code/packages/cli/src/ui/utils/ConsolePatcher.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import util from 'util';
8
+ import { ConsoleMessageItem } from '../types.js';
9
+
10
+ interface ConsolePatcherParams {
11
+ onNewMessage?: (message: Omit<ConsoleMessageItem, 'id'>) => void;
12
+ debugMode: boolean;
13
+ stderr?: boolean;
14
+ }
15
+
16
+ export class ConsolePatcher {
17
+ private originalConsoleLog = console.log;
18
+ private originalConsoleWarn = console.warn;
19
+ private originalConsoleError = console.error;
20
+ private originalConsoleDebug = console.debug;
21
+ private originalConsoleInfo = console.info;
22
+
23
+ private params: ConsolePatcherParams;
24
+
25
+ constructor(params: ConsolePatcherParams) {
26
+ this.params = params;
27
+ }
28
+
29
+ patch() {
30
+ console.log = this.patchConsoleMethod('log', this.originalConsoleLog);
31
+ console.warn = this.patchConsoleMethod('warn', this.originalConsoleWarn);
32
+ console.error = this.patchConsoleMethod('error', this.originalConsoleError);
33
+ console.debug = this.patchConsoleMethod('debug', this.originalConsoleDebug);
34
+ console.info = this.patchConsoleMethod('info', this.originalConsoleInfo);
35
+ }
36
+
37
+ cleanup = () => {
38
+ console.log = this.originalConsoleLog;
39
+ console.warn = this.originalConsoleWarn;
40
+ console.error = this.originalConsoleError;
41
+ console.debug = this.originalConsoleDebug;
42
+ console.info = this.originalConsoleInfo;
43
+ };
44
+
45
+ private formatArgs = (args: unknown[]): string => util.format(...args);
46
+
47
+ private patchConsoleMethod =
48
+ (
49
+ type: 'log' | 'warn' | 'error' | 'debug' | 'info',
50
+ originalMethod: (...args: unknown[]) => void,
51
+ ) =>
52
+ (...args: unknown[]) => {
53
+ if (this.params.stderr) {
54
+ if (type !== 'debug' || this.params.debugMode) {
55
+ this.originalConsoleError(this.formatArgs(args));
56
+ }
57
+ } else {
58
+ if (this.params.debugMode) {
59
+ originalMethod.apply(console, args);
60
+ }
61
+
62
+ if (type !== 'debug' || this.params.debugMode) {
63
+ this.params.onNewMessage?.({
64
+ type,
65
+ content: this.formatArgs(args),
66
+ count: 1,
67
+ });
68
+ }
69
+ }
70
+ };
71
+ }
projects/ui/qwen-code/packages/cli/src/ui/utils/InlineMarkdownRenderer.tsx ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Text } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import stringWidth from 'string-width';
11
+
12
+ // Constants for Markdown parsing
13
+ const BOLD_MARKER_LENGTH = 2; // For "**"
14
+ const ITALIC_MARKER_LENGTH = 1; // For "*" or "_"
15
+ const STRIKETHROUGH_MARKER_LENGTH = 2; // For "~~"
16
+ const INLINE_CODE_MARKER_LENGTH = 1; // For "`"
17
+ const UNDERLINE_TAG_START_LENGTH = 3; // For "<u>"
18
+ const UNDERLINE_TAG_END_LENGTH = 4; // For "</u>"
19
+
20
+ interface RenderInlineProps {
21
+ text: string;
22
+ }
23
+
24
+ const RenderInlineInternal: React.FC<RenderInlineProps> = ({ text }) => {
25
+ // Early return for plain text without markdown or URLs
26
+ if (!/[*_~`<[https?:]/.test(text)) {
27
+ return <Text>{text}</Text>;
28
+ }
29
+
30
+ const nodes: React.ReactNode[] = [];
31
+ let lastIndex = 0;
32
+ const inlineRegex =
33
+ /(\*\*.*?\*\*|\*.*?\*|_.*?_|~~.*?~~|\[.*?\]\(.*?\)|`+.+?`+|<u>.*?<\/u>|https?:\/\/\S+)/g;
34
+ let match;
35
+
36
+ while ((match = inlineRegex.exec(text)) !== null) {
37
+ if (match.index > lastIndex) {
38
+ nodes.push(
39
+ <Text key={`t-${lastIndex}`}>
40
+ {text.slice(lastIndex, match.index)}
41
+ </Text>,
42
+ );
43
+ }
44
+
45
+ const fullMatch = match[0];
46
+ let renderedNode: React.ReactNode = null;
47
+ const key = `m-${match.index}`;
48
+
49
+ try {
50
+ if (
51
+ fullMatch.startsWith('**') &&
52
+ fullMatch.endsWith('**') &&
53
+ fullMatch.length > BOLD_MARKER_LENGTH * 2
54
+ ) {
55
+ renderedNode = (
56
+ <Text key={key} bold>
57
+ {fullMatch.slice(BOLD_MARKER_LENGTH, -BOLD_MARKER_LENGTH)}
58
+ </Text>
59
+ );
60
+ } else if (
61
+ fullMatch.length > ITALIC_MARKER_LENGTH * 2 &&
62
+ ((fullMatch.startsWith('*') && fullMatch.endsWith('*')) ||
63
+ (fullMatch.startsWith('_') && fullMatch.endsWith('_'))) &&
64
+ !/\w/.test(text.substring(match.index - 1, match.index)) &&
65
+ !/\w/.test(
66
+ text.substring(inlineRegex.lastIndex, inlineRegex.lastIndex + 1),
67
+ ) &&
68
+ !/\S[./\\]/.test(text.substring(match.index - 2, match.index)) &&
69
+ !/[./\\]\S/.test(
70
+ text.substring(inlineRegex.lastIndex, inlineRegex.lastIndex + 2),
71
+ )
72
+ ) {
73
+ renderedNode = (
74
+ <Text key={key} italic>
75
+ {fullMatch.slice(ITALIC_MARKER_LENGTH, -ITALIC_MARKER_LENGTH)}
76
+ </Text>
77
+ );
78
+ } else if (
79
+ fullMatch.startsWith('~~') &&
80
+ fullMatch.endsWith('~~') &&
81
+ fullMatch.length > STRIKETHROUGH_MARKER_LENGTH * 2
82
+ ) {
83
+ renderedNode = (
84
+ <Text key={key} strikethrough>
85
+ {fullMatch.slice(
86
+ STRIKETHROUGH_MARKER_LENGTH,
87
+ -STRIKETHROUGH_MARKER_LENGTH,
88
+ )}
89
+ </Text>
90
+ );
91
+ } else if (
92
+ fullMatch.startsWith('`') &&
93
+ fullMatch.endsWith('`') &&
94
+ fullMatch.length > INLINE_CODE_MARKER_LENGTH
95
+ ) {
96
+ const codeMatch = fullMatch.match(/^(`+)(.+?)\1$/s);
97
+ if (codeMatch && codeMatch[2]) {
98
+ renderedNode = (
99
+ <Text key={key} color={Colors.AccentPurple}>
100
+ {codeMatch[2]}
101
+ </Text>
102
+ );
103
+ }
104
+ } else if (
105
+ fullMatch.startsWith('[') &&
106
+ fullMatch.includes('](') &&
107
+ fullMatch.endsWith(')')
108
+ ) {
109
+ const linkMatch = fullMatch.match(/\[(.*?)\]\((.*?)\)/);
110
+ if (linkMatch) {
111
+ const linkText = linkMatch[1];
112
+ const url = linkMatch[2];
113
+ renderedNode = (
114
+ <Text key={key}>
115
+ {linkText}
116
+ <Text color={Colors.AccentBlue}> ({url})</Text>
117
+ </Text>
118
+ );
119
+ }
120
+ } else if (
121
+ fullMatch.startsWith('<u>') &&
122
+ fullMatch.endsWith('</u>') &&
123
+ fullMatch.length >
124
+ UNDERLINE_TAG_START_LENGTH + UNDERLINE_TAG_END_LENGTH - 1 // -1 because length is compared to combined length of start and end tags
125
+ ) {
126
+ renderedNode = (
127
+ <Text key={key} underline>
128
+ {fullMatch.slice(
129
+ UNDERLINE_TAG_START_LENGTH,
130
+ -UNDERLINE_TAG_END_LENGTH,
131
+ )}
132
+ </Text>
133
+ );
134
+ } else if (fullMatch.match(/^https?:\/\//)) {
135
+ renderedNode = (
136
+ <Text key={key} color={Colors.AccentBlue}>
137
+ {fullMatch}
138
+ </Text>
139
+ );
140
+ }
141
+ } catch (e) {
142
+ console.error('Error parsing inline markdown part:', fullMatch, e);
143
+ renderedNode = null;
144
+ }
145
+
146
+ nodes.push(renderedNode ?? <Text key={key}>{fullMatch}</Text>);
147
+ lastIndex = inlineRegex.lastIndex;
148
+ }
149
+
150
+ if (lastIndex < text.length) {
151
+ nodes.push(<Text key={`t-${lastIndex}`}>{text.slice(lastIndex)}</Text>);
152
+ }
153
+
154
+ return <>{nodes.filter((node) => node !== null)}</>;
155
+ };
156
+
157
+ export const RenderInline = React.memo(RenderInlineInternal);
158
+
159
+ /**
160
+ * Utility function to get the plain text length of a string with markdown formatting
161
+ * This is useful for calculating column widths in tables
162
+ */
163
+ export const getPlainTextLength = (text: string): number => {
164
+ const cleanText = text
165
+ .replace(/\*\*(.*?)\*\*/g, '$1')
166
+ .replace(/\*(.*?)\*/g, '$1')
167
+ .replace(/_(.*?)_/g, '$1')
168
+ .replace(/~~(.*?)~~/g, '$1')
169
+ .replace(/`(.*?)`/g, '$1')
170
+ .replace(/<u>(.*?)<\/u>/g, '$1')
171
+ .replace(/\[(.*?)\]\(.*?\)/g, '$1');
172
+ return stringWidth(cleanText);
173
+ };
projects/ui/qwen-code/packages/cli/src/ui/utils/MarkdownDisplay.test.tsx ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { render } from 'ink-testing-library';
8
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
9
+ import { MarkdownDisplay } from './MarkdownDisplay.js';
10
+ import { LoadedSettings } from '../../config/settings.js';
11
+ import { SettingsContext } from '../contexts/SettingsContext.js';
12
+
13
+ describe('<MarkdownDisplay />', () => {
14
+ const baseProps = {
15
+ isPending: false,
16
+ terminalWidth: 80,
17
+ availableTerminalHeight: 40,
18
+ };
19
+
20
+ const mockSettings = new LoadedSettings(
21
+ { path: '', settings: {} },
22
+ { path: '', settings: {} },
23
+ { path: '', settings: {} },
24
+ [],
25
+ );
26
+
27
+ beforeEach(() => {
28
+ vi.clearAllMocks();
29
+ });
30
+
31
+ it('renders nothing for empty text', () => {
32
+ const { lastFrame } = render(
33
+ <SettingsContext.Provider value={mockSettings}>
34
+ <MarkdownDisplay {...baseProps} text="" />
35
+ </SettingsContext.Provider>,
36
+ );
37
+ expect(lastFrame()).toMatchSnapshot();
38
+ });
39
+
40
+ it('renders a simple paragraph', () => {
41
+ const text = 'Hello, world.';
42
+ const { lastFrame } = render(
43
+ <SettingsContext.Provider value={mockSettings}>
44
+ <MarkdownDisplay {...baseProps} text={text} />
45
+ </SettingsContext.Provider>,
46
+ );
47
+ expect(lastFrame()).toMatchSnapshot();
48
+ });
49
+
50
+ it('renders headers with correct levels', () => {
51
+ const text = `
52
+ # Header 1
53
+ ## Header 2
54
+ ### Header 3
55
+ #### Header 4
56
+ `;
57
+ const { lastFrame } = render(
58
+ <SettingsContext.Provider value={mockSettings}>
59
+ <MarkdownDisplay {...baseProps} text={text} />
60
+ </SettingsContext.Provider>,
61
+ );
62
+ expect(lastFrame()).toMatchSnapshot();
63
+ });
64
+
65
+ it('renders a fenced code block with a language', () => {
66
+ const text = '```javascript\nconst x = 1;\nconsole.log(x);\n```';
67
+ const { lastFrame } = render(
68
+ <SettingsContext.Provider value={mockSettings}>
69
+ <MarkdownDisplay {...baseProps} text={text} />
70
+ </SettingsContext.Provider>,
71
+ );
72
+ expect(lastFrame()).toMatchSnapshot();
73
+ });
74
+
75
+ it('renders a fenced code block without a language', () => {
76
+ const text = '```\nplain text\n```';
77
+ const { lastFrame } = render(
78
+ <SettingsContext.Provider value={mockSettings}>
79
+ <MarkdownDisplay {...baseProps} text={text} />
80
+ </SettingsContext.Provider>,
81
+ );
82
+ expect(lastFrame()).toMatchSnapshot();
83
+ });
84
+
85
+ it('handles unclosed (pending) code blocks', () => {
86
+ const text = '```typescript\nlet y = 2;';
87
+ const { lastFrame } = render(
88
+ <SettingsContext.Provider value={mockSettings}>
89
+ <MarkdownDisplay {...baseProps} text={text} isPending={true} />
90
+ </SettingsContext.Provider>,
91
+ );
92
+ expect(lastFrame()).toMatchSnapshot();
93
+ });
94
+
95
+ it('renders unordered lists with different markers', () => {
96
+ const text = `
97
+ - item A
98
+ * item B
99
+ + item C
100
+ `;
101
+ const { lastFrame } = render(
102
+ <SettingsContext.Provider value={mockSettings}>
103
+ <MarkdownDisplay {...baseProps} text={text} />
104
+ </SettingsContext.Provider>,
105
+ );
106
+ expect(lastFrame()).toMatchSnapshot();
107
+ });
108
+
109
+ it('renders nested unordered lists', () => {
110
+ const text = `
111
+ * Level 1
112
+ * Level 2
113
+ * Level 3
114
+ `;
115
+ const { lastFrame } = render(
116
+ <SettingsContext.Provider value={mockSettings}>
117
+ <MarkdownDisplay {...baseProps} text={text} />
118
+ </SettingsContext.Provider>,
119
+ );
120
+ expect(lastFrame()).toMatchSnapshot();
121
+ });
122
+
123
+ it('renders ordered lists', () => {
124
+ const text = `
125
+ 1. First item
126
+ 2. Second item
127
+ `;
128
+ const { lastFrame } = render(
129
+ <SettingsContext.Provider value={mockSettings}>
130
+ <MarkdownDisplay {...baseProps} text={text} />
131
+ </SettingsContext.Provider>,
132
+ );
133
+ expect(lastFrame()).toMatchSnapshot();
134
+ });
135
+
136
+ it('renders horizontal rules', () => {
137
+ const text = `
138
+ Hello
139
+ ---
140
+ World
141
+ ***
142
+ Test
143
+ `;
144
+ const { lastFrame } = render(
145
+ <SettingsContext.Provider value={mockSettings}>
146
+ <MarkdownDisplay {...baseProps} text={text} />
147
+ </SettingsContext.Provider>,
148
+ );
149
+ expect(lastFrame()).toMatchSnapshot();
150
+ });
151
+
152
+ it('renders tables correctly', () => {
153
+ const text = `
154
+ | Header 1 | Header 2 |
155
+ |----------|:--------:|
156
+ | Cell 1 | Cell 2 |
157
+ | Cell 3 | Cell 4 |
158
+ `;
159
+ const { lastFrame } = render(
160
+ <SettingsContext.Provider value={mockSettings}>
161
+ <MarkdownDisplay {...baseProps} text={text} />
162
+ </SettingsContext.Provider>,
163
+ );
164
+ expect(lastFrame()).toMatchSnapshot();
165
+ });
166
+
167
+ it('handles a table at the end of the input', () => {
168
+ const text = `
169
+ Some text before.
170
+ | A | B |
171
+ |---|
172
+ | 1 | 2 |`;
173
+ const { lastFrame } = render(
174
+ <SettingsContext.Provider value={mockSettings}>
175
+ <MarkdownDisplay {...baseProps} text={text} />
176
+ </SettingsContext.Provider>,
177
+ );
178
+ expect(lastFrame()).toMatchSnapshot();
179
+ });
180
+
181
+ it('inserts a single space between paragraphs', () => {
182
+ const text = `Paragraph 1.
183
+
184
+ Paragraph 2.`;
185
+ const { lastFrame } = render(
186
+ <SettingsContext.Provider value={mockSettings}>
187
+ <MarkdownDisplay {...baseProps} text={text} />
188
+ </SettingsContext.Provider>,
189
+ );
190
+ expect(lastFrame()).toMatchSnapshot();
191
+ });
192
+
193
+ it('correctly parses a mix of markdown elements', () => {
194
+ const text = `
195
+ # Main Title
196
+
197
+ Here is a paragraph.
198
+
199
+ - List item 1
200
+ - List item 2
201
+
202
+ \`\`\`
203
+ some code
204
+ \`\`\`
205
+
206
+ Another paragraph.
207
+ `;
208
+ const { lastFrame } = render(
209
+ <SettingsContext.Provider value={mockSettings}>
210
+ <MarkdownDisplay {...baseProps} text={text} />
211
+ </SettingsContext.Provider>,
212
+ );
213
+ expect(lastFrame()).toMatchSnapshot();
214
+ });
215
+
216
+ it('hides line numbers in code blocks when showLineNumbers is false', () => {
217
+ const text = '```javascript\nconst x = 1;\n```';
218
+ const settings = new LoadedSettings(
219
+ { path: '', settings: {} },
220
+ { path: '', settings: { showLineNumbers: false } },
221
+ { path: '', settings: {} },
222
+ [],
223
+ );
224
+
225
+ const { lastFrame } = render(
226
+ <SettingsContext.Provider value={settings}>
227
+ <MarkdownDisplay {...baseProps} text={text} />
228
+ </SettingsContext.Provider>,
229
+ );
230
+ expect(lastFrame()).toMatchSnapshot();
231
+ expect(lastFrame()).not.toContain(' 1 ');
232
+ });
233
+
234
+ it('shows line numbers in code blocks by default', () => {
235
+ const text = '```javascript\nconst x = 1;\n```';
236
+ const { lastFrame } = render(
237
+ <SettingsContext.Provider value={mockSettings}>
238
+ <MarkdownDisplay {...baseProps} text={text} />
239
+ </SettingsContext.Provider>,
240
+ );
241
+ expect(lastFrame()).toMatchSnapshot();
242
+ expect(lastFrame()).toContain(' 1 ');
243
+ });
244
+ });
projects/ui/qwen-code/packages/cli/src/ui/utils/MarkdownDisplay.tsx ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Text, Box } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import { colorizeCode } from './CodeColorizer.js';
11
+ import { TableRenderer } from './TableRenderer.js';
12
+ import { RenderInline } from './InlineMarkdownRenderer.js';
13
+ import { useSettings } from '../contexts/SettingsContext.js';
14
+
15
+ interface MarkdownDisplayProps {
16
+ text: string;
17
+ isPending: boolean;
18
+ availableTerminalHeight?: number;
19
+ terminalWidth: number;
20
+ }
21
+
22
+ // Constants for Markdown parsing and rendering
23
+
24
+ const EMPTY_LINE_HEIGHT = 1;
25
+ const CODE_BLOCK_PREFIX_PADDING = 1;
26
+ const LIST_ITEM_PREFIX_PADDING = 1;
27
+ const LIST_ITEM_TEXT_FLEX_GROW = 1;
28
+
29
+ const MarkdownDisplayInternal: React.FC<MarkdownDisplayProps> = ({
30
+ text,
31
+ isPending,
32
+ availableTerminalHeight,
33
+ terminalWidth,
34
+ }) => {
35
+ if (!text) return <></>;
36
+
37
+ const lines = text.split('\n');
38
+ const headerRegex = /^ *(#{1,4}) +(.*)/;
39
+ const codeFenceRegex = /^ *(`{3,}|~{3,}) *(\w*?) *$/;
40
+ const ulItemRegex = /^([ \t]*)([-*+]) +(.*)/;
41
+ const olItemRegex = /^([ \t]*)(\d+)\. +(.*)/;
42
+ const hrRegex = /^ *([-*_] *){3,} *$/;
43
+ const tableRowRegex = /^\s*\|(.+)\|\s*$/;
44
+ const tableSeparatorRegex = /^\s*\|?\s*(:?-+:?)\s*(\|\s*(:?-+:?)\s*)+\|?\s*$/;
45
+
46
+ const contentBlocks: React.ReactNode[] = [];
47
+ let inCodeBlock = false;
48
+ let lastLineEmpty = true;
49
+ let codeBlockContent: string[] = [];
50
+ let codeBlockLang: string | null = null;
51
+ let codeBlockFence = '';
52
+ let inTable = false;
53
+ let tableRows: string[][] = [];
54
+ let tableHeaders: string[] = [];
55
+
56
+ function addContentBlock(block: React.ReactNode) {
57
+ if (block) {
58
+ contentBlocks.push(block);
59
+ lastLineEmpty = false;
60
+ }
61
+ }
62
+
63
+ lines.forEach((line, index) => {
64
+ const key = `line-${index}`;
65
+
66
+ if (inCodeBlock) {
67
+ const fenceMatch = line.match(codeFenceRegex);
68
+ if (
69
+ fenceMatch &&
70
+ fenceMatch[1].startsWith(codeBlockFence[0]) &&
71
+ fenceMatch[1].length >= codeBlockFence.length
72
+ ) {
73
+ addContentBlock(
74
+ <RenderCodeBlock
75
+ key={key}
76
+ content={codeBlockContent}
77
+ lang={codeBlockLang}
78
+ isPending={isPending}
79
+ availableTerminalHeight={availableTerminalHeight}
80
+ terminalWidth={terminalWidth}
81
+ />,
82
+ );
83
+ inCodeBlock = false;
84
+ codeBlockContent = [];
85
+ codeBlockLang = null;
86
+ codeBlockFence = '';
87
+ } else {
88
+ codeBlockContent.push(line);
89
+ }
90
+ return;
91
+ }
92
+
93
+ const codeFenceMatch = line.match(codeFenceRegex);
94
+ const headerMatch = line.match(headerRegex);
95
+ const ulMatch = line.match(ulItemRegex);
96
+ const olMatch = line.match(olItemRegex);
97
+ const hrMatch = line.match(hrRegex);
98
+ const tableRowMatch = line.match(tableRowRegex);
99
+ const tableSeparatorMatch = line.match(tableSeparatorRegex);
100
+
101
+ if (codeFenceMatch) {
102
+ inCodeBlock = true;
103
+ codeBlockFence = codeFenceMatch[1];
104
+ codeBlockLang = codeFenceMatch[2] || null;
105
+ } else if (tableRowMatch && !inTable) {
106
+ // Potential table start - check if next line is separator
107
+ if (
108
+ index + 1 < lines.length &&
109
+ lines[index + 1].match(tableSeparatorRegex)
110
+ ) {
111
+ inTable = true;
112
+ tableHeaders = tableRowMatch[1].split('|').map((cell) => cell.trim());
113
+ tableRows = [];
114
+ } else {
115
+ // Not a table, treat as regular text
116
+ addContentBlock(
117
+ <Box key={key}>
118
+ <Text wrap="wrap">
119
+ <RenderInline text={line} />
120
+ </Text>
121
+ </Box>,
122
+ );
123
+ }
124
+ } else if (inTable && tableSeparatorMatch) {
125
+ // Skip separator line - already handled
126
+ } else if (inTable && tableRowMatch) {
127
+ // Add table row
128
+ const cells = tableRowMatch[1].split('|').map((cell) => cell.trim());
129
+ // Ensure row has same column count as headers
130
+ while (cells.length < tableHeaders.length) {
131
+ cells.push('');
132
+ }
133
+ if (cells.length > tableHeaders.length) {
134
+ cells.length = tableHeaders.length;
135
+ }
136
+ tableRows.push(cells);
137
+ } else if (inTable && !tableRowMatch) {
138
+ // End of table
139
+ if (tableHeaders.length > 0 && tableRows.length > 0) {
140
+ addContentBlock(
141
+ <RenderTable
142
+ key={`table-${contentBlocks.length}`}
143
+ headers={tableHeaders}
144
+ rows={tableRows}
145
+ terminalWidth={terminalWidth}
146
+ />,
147
+ );
148
+ }
149
+ inTable = false;
150
+ tableRows = [];
151
+ tableHeaders = [];
152
+
153
+ // Process current line as normal
154
+ if (line.trim().length > 0) {
155
+ addContentBlock(
156
+ <Box key={key}>
157
+ <Text wrap="wrap">
158
+ <RenderInline text={line} />
159
+ </Text>
160
+ </Box>,
161
+ );
162
+ }
163
+ } else if (hrMatch) {
164
+ addContentBlock(
165
+ <Box key={key}>
166
+ <Text dimColor>---</Text>
167
+ </Box>,
168
+ );
169
+ } else if (headerMatch) {
170
+ const level = headerMatch[1].length;
171
+ const headerText = headerMatch[2];
172
+ let headerNode: React.ReactNode = null;
173
+ switch (level) {
174
+ case 1:
175
+ headerNode = (
176
+ <Text bold color={Colors.AccentCyan}>
177
+ <RenderInline text={headerText} />
178
+ </Text>
179
+ );
180
+ break;
181
+ case 2:
182
+ headerNode = (
183
+ <Text bold color={Colors.AccentBlue}>
184
+ <RenderInline text={headerText} />
185
+ </Text>
186
+ );
187
+ break;
188
+ case 3:
189
+ headerNode = (
190
+ <Text bold>
191
+ <RenderInline text={headerText} />
192
+ </Text>
193
+ );
194
+ break;
195
+ case 4:
196
+ headerNode = (
197
+ <Text italic color={Colors.Gray}>
198
+ <RenderInline text={headerText} />
199
+ </Text>
200
+ );
201
+ break;
202
+ default:
203
+ headerNode = (
204
+ <Text>
205
+ <RenderInline text={headerText} />
206
+ </Text>
207
+ );
208
+ break;
209
+ }
210
+ if (headerNode) addContentBlock(<Box key={key}>{headerNode}</Box>);
211
+ } else if (ulMatch) {
212
+ const leadingWhitespace = ulMatch[1];
213
+ const marker = ulMatch[2];
214
+ const itemText = ulMatch[3];
215
+ addContentBlock(
216
+ <RenderListItem
217
+ key={key}
218
+ itemText={itemText}
219
+ type="ul"
220
+ marker={marker}
221
+ leadingWhitespace={leadingWhitespace}
222
+ />,
223
+ );
224
+ } else if (olMatch) {
225
+ const leadingWhitespace = olMatch[1];
226
+ const marker = olMatch[2];
227
+ const itemText = olMatch[3];
228
+ addContentBlock(
229
+ <RenderListItem
230
+ key={key}
231
+ itemText={itemText}
232
+ type="ol"
233
+ marker={marker}
234
+ leadingWhitespace={leadingWhitespace}
235
+ />,
236
+ );
237
+ } else {
238
+ if (line.trim().length === 0 && !inCodeBlock) {
239
+ if (!lastLineEmpty) {
240
+ contentBlocks.push(
241
+ <Box key={`spacer-${index}`} height={EMPTY_LINE_HEIGHT} />,
242
+ );
243
+ lastLineEmpty = true;
244
+ }
245
+ } else {
246
+ addContentBlock(
247
+ <Box key={key}>
248
+ <Text wrap="wrap">
249
+ <RenderInline text={line} />
250
+ </Text>
251
+ </Box>,
252
+ );
253
+ }
254
+ }
255
+ });
256
+
257
+ if (inCodeBlock) {
258
+ addContentBlock(
259
+ <RenderCodeBlock
260
+ key="line-eof"
261
+ content={codeBlockContent}
262
+ lang={codeBlockLang}
263
+ isPending={isPending}
264
+ availableTerminalHeight={availableTerminalHeight}
265
+ terminalWidth={terminalWidth}
266
+ />,
267
+ );
268
+ }
269
+
270
+ // Handle table at end of content
271
+ if (inTable && tableHeaders.length > 0 && tableRows.length > 0) {
272
+ addContentBlock(
273
+ <RenderTable
274
+ key={`table-${contentBlocks.length}`}
275
+ headers={tableHeaders}
276
+ rows={tableRows}
277
+ terminalWidth={terminalWidth}
278
+ />,
279
+ );
280
+ }
281
+
282
+ return <>{contentBlocks}</>;
283
+ };
284
+
285
+ // Helper functions (adapted from static methods of MarkdownRenderer)
286
+
287
+ interface RenderCodeBlockProps {
288
+ content: string[];
289
+ lang: string | null;
290
+ isPending: boolean;
291
+ availableTerminalHeight?: number;
292
+ terminalWidth: number;
293
+ }
294
+
295
+ const RenderCodeBlockInternal: React.FC<RenderCodeBlockProps> = ({
296
+ content,
297
+ lang,
298
+ isPending,
299
+ availableTerminalHeight,
300
+ terminalWidth,
301
+ }) => {
302
+ const settings = useSettings();
303
+ const MIN_LINES_FOR_MESSAGE = 1; // Minimum lines to show before the "generating more" message
304
+ const RESERVED_LINES = 2; // Lines reserved for the message itself and potential padding
305
+
306
+ if (isPending && availableTerminalHeight !== undefined) {
307
+ const MAX_CODE_LINES_WHEN_PENDING = Math.max(
308
+ 0,
309
+ availableTerminalHeight - RESERVED_LINES,
310
+ );
311
+
312
+ if (content.length > MAX_CODE_LINES_WHEN_PENDING) {
313
+ if (MAX_CODE_LINES_WHEN_PENDING < MIN_LINES_FOR_MESSAGE) {
314
+ // Not enough space to even show the message meaningfully
315
+ return (
316
+ <Box paddingLeft={CODE_BLOCK_PREFIX_PADDING}>
317
+ <Text color={Colors.Gray}>... code is being written ...</Text>
318
+ </Box>
319
+ );
320
+ }
321
+ const truncatedContent = content.slice(0, MAX_CODE_LINES_WHEN_PENDING);
322
+ const colorizedTruncatedCode = colorizeCode(
323
+ truncatedContent.join('\n'),
324
+ lang,
325
+ availableTerminalHeight,
326
+ terminalWidth - CODE_BLOCK_PREFIX_PADDING,
327
+ undefined,
328
+ settings,
329
+ );
330
+ return (
331
+ <Box paddingLeft={CODE_BLOCK_PREFIX_PADDING} flexDirection="column">
332
+ {colorizedTruncatedCode}
333
+ <Text color={Colors.Gray}>... generating more ...</Text>
334
+ </Box>
335
+ );
336
+ }
337
+ }
338
+
339
+ const fullContent = content.join('\n');
340
+ const colorizedCode = colorizeCode(
341
+ fullContent,
342
+ lang,
343
+ availableTerminalHeight,
344
+ terminalWidth - CODE_BLOCK_PREFIX_PADDING,
345
+ undefined,
346
+ settings,
347
+ );
348
+
349
+ return (
350
+ <Box
351
+ paddingLeft={CODE_BLOCK_PREFIX_PADDING}
352
+ flexDirection="column"
353
+ width={terminalWidth}
354
+ flexShrink={0}
355
+ >
356
+ {colorizedCode}
357
+ </Box>
358
+ );
359
+ };
360
+
361
+ const RenderCodeBlock = React.memo(RenderCodeBlockInternal);
362
+
363
+ interface RenderListItemProps {
364
+ itemText: string;
365
+ type: 'ul' | 'ol';
366
+ marker: string;
367
+ leadingWhitespace?: string;
368
+ }
369
+
370
+ const RenderListItemInternal: React.FC<RenderListItemProps> = ({
371
+ itemText,
372
+ type,
373
+ marker,
374
+ leadingWhitespace = '',
375
+ }) => {
376
+ const prefix = type === 'ol' ? `${marker}. ` : `${marker} `;
377
+ const prefixWidth = prefix.length;
378
+ const indentation = leadingWhitespace.length;
379
+
380
+ return (
381
+ <Box
382
+ paddingLeft={indentation + LIST_ITEM_PREFIX_PADDING}
383
+ flexDirection="row"
384
+ >
385
+ <Box width={prefixWidth}>
386
+ <Text>{prefix}</Text>
387
+ </Box>
388
+ <Box flexGrow={LIST_ITEM_TEXT_FLEX_GROW}>
389
+ <Text wrap="wrap">
390
+ <RenderInline text={itemText} />
391
+ </Text>
392
+ </Box>
393
+ </Box>
394
+ );
395
+ };
396
+
397
+ const RenderListItem = React.memo(RenderListItemInternal);
398
+
399
+ interface RenderTableProps {
400
+ headers: string[];
401
+ rows: string[][];
402
+ terminalWidth: number;
403
+ }
404
+
405
+ const RenderTableInternal: React.FC<RenderTableProps> = ({
406
+ headers,
407
+ rows,
408
+ terminalWidth,
409
+ }) => (
410
+ <TableRenderer headers={headers} rows={rows} terminalWidth={terminalWidth} />
411
+ );
412
+
413
+ const RenderTable = React.memo(RenderTableInternal);
414
+
415
+ export const MarkdownDisplay = React.memo(MarkdownDisplayInternal);
projects/ui/qwen-code/packages/cli/src/ui/utils/TableRenderer.tsx ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import React from 'react';
8
+ import { Text, Box } from 'ink';
9
+ import { Colors } from '../colors.js';
10
+ import { RenderInline, getPlainTextLength } from './InlineMarkdownRenderer.js';
11
+
12
+ interface TableRendererProps {
13
+ headers: string[];
14
+ rows: string[][];
15
+ terminalWidth: number;
16
+ }
17
+
18
+ /**
19
+ * Custom table renderer for markdown tables
20
+ * We implement our own instead of using ink-table due to module compatibility issues
21
+ */
22
+ export const TableRenderer: React.FC<TableRendererProps> = ({
23
+ headers,
24
+ rows,
25
+ terminalWidth,
26
+ }) => {
27
+ // Calculate column widths using actual display width after markdown processing
28
+ const columnWidths = headers.map((header, index) => {
29
+ const headerWidth = getPlainTextLength(header);
30
+ const maxRowWidth = Math.max(
31
+ ...rows.map((row) => getPlainTextLength(row[index] || '')),
32
+ );
33
+ return Math.max(headerWidth, maxRowWidth) + 2; // Add padding
34
+ });
35
+
36
+ // Ensure table fits within terminal width
37
+ const totalWidth = columnWidths.reduce((sum, width) => sum + width + 1, 1);
38
+ const scaleFactor =
39
+ totalWidth > terminalWidth ? terminalWidth / totalWidth : 1;
40
+ const adjustedWidths = columnWidths.map((width) =>
41
+ Math.floor(width * scaleFactor),
42
+ );
43
+
44
+ // Helper function to render a cell with proper width
45
+ const renderCell = (
46
+ content: string,
47
+ width: number,
48
+ isHeader = false,
49
+ ): React.ReactNode => {
50
+ const contentWidth = Math.max(0, width - 2);
51
+ const displayWidth = getPlainTextLength(content);
52
+
53
+ let cellContent = content;
54
+ if (displayWidth > contentWidth) {
55
+ if (contentWidth <= 3) {
56
+ // Just truncate by character count
57
+ cellContent = content.substring(
58
+ 0,
59
+ Math.min(content.length, contentWidth),
60
+ );
61
+ } else {
62
+ // Truncate preserving markdown formatting using binary search
63
+ let left = 0;
64
+ let right = content.length;
65
+ let bestTruncated = content;
66
+
67
+ // Binary search to find the optimal truncation point
68
+ while (left <= right) {
69
+ const mid = Math.floor((left + right) / 2);
70
+ const candidate = content.substring(0, mid);
71
+ const candidateWidth = getPlainTextLength(candidate);
72
+
73
+ if (candidateWidth <= contentWidth - 3) {
74
+ bestTruncated = candidate;
75
+ left = mid + 1;
76
+ } else {
77
+ right = mid - 1;
78
+ }
79
+ }
80
+
81
+ cellContent = bestTruncated + '...';
82
+ }
83
+ }
84
+
85
+ // Calculate exact padding needed
86
+ const actualDisplayWidth = getPlainTextLength(cellContent);
87
+ const paddingNeeded = Math.max(0, contentWidth - actualDisplayWidth);
88
+
89
+ return (
90
+ <Text>
91
+ {isHeader ? (
92
+ <Text bold color={Colors.AccentCyan}>
93
+ <RenderInline text={cellContent} />
94
+ </Text>
95
+ ) : (
96
+ <RenderInline text={cellContent} />
97
+ )}
98
+ {' '.repeat(paddingNeeded)}
99
+ </Text>
100
+ );
101
+ };
102
+
103
+ // Helper function to render border
104
+ const renderBorder = (type: 'top' | 'middle' | 'bottom'): React.ReactNode => {
105
+ const chars = {
106
+ top: { left: '┌', middle: '┬', right: '┐', horizontal: '─' },
107
+ middle: { left: '├', middle: '┼', right: '┤', horizontal: '─' },
108
+ bottom: { left: '└', middle: '┴', right: '┘', horizontal: '─' },
109
+ };
110
+
111
+ const char = chars[type];
112
+ const borderParts = adjustedWidths.map((w) => char.horizontal.repeat(w));
113
+ const border = char.left + borderParts.join(char.middle) + char.right;
114
+
115
+ return <Text>{border}</Text>;
116
+ };
117
+
118
+ // Helper function to render a table row
119
+ const renderRow = (cells: string[], isHeader = false): React.ReactNode => {
120
+ const renderedCells = cells.map((cell, index) => {
121
+ const width = adjustedWidths[index] || 0;
122
+ return renderCell(cell || '', width, isHeader);
123
+ });
124
+
125
+ return (
126
+ <Text>
127
+ │{' '}
128
+ {renderedCells.map((cell, index) => (
129
+ <React.Fragment key={index}>
130
+ {cell}
131
+ {index < renderedCells.length - 1 ? ' │ ' : ''}
132
+ </React.Fragment>
133
+ ))}{' '}
134
+
135
+ </Text>
136
+ );
137
+ };
138
+
139
+ return (
140
+ <Box flexDirection="column" marginY={1}>
141
+ {/* Top border */}
142
+ {renderBorder('top')}
143
+
144
+ {/* Header row */}
145
+ {renderRow(headers, true)}
146
+
147
+ {/* Middle border */}
148
+ {renderBorder('middle')}
149
+
150
+ {/* Data rows */}
151
+ {rows.map((row, index) => (
152
+ <React.Fragment key={index}>{renderRow(row)}</React.Fragment>
153
+ ))}
154
+
155
+ {/* Bottom border */}
156
+ {renderBorder('bottom')}
157
+ </Box>
158
+ );
159
+ };
projects/ui/qwen-code/packages/cli/src/ui/utils/clipboardUtils.test.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import {
9
+ clipboardHasImage,
10
+ saveClipboardImage,
11
+ cleanupOldClipboardImages,
12
+ } from './clipboardUtils.js';
13
+
14
+ describe('clipboardUtils', () => {
15
+ describe('clipboardHasImage', () => {
16
+ it('should return false on non-macOS platforms', async () => {
17
+ if (process.platform !== 'darwin') {
18
+ const result = await clipboardHasImage();
19
+ expect(result).toBe(false);
20
+ } else {
21
+ // Skip on macOS as it would require actual clipboard state
22
+ expect(true).toBe(true);
23
+ }
24
+ });
25
+
26
+ it('should return boolean on macOS', async () => {
27
+ if (process.platform === 'darwin') {
28
+ const result = await clipboardHasImage();
29
+ expect(typeof result).toBe('boolean');
30
+ } else {
31
+ // Skip on non-macOS
32
+ expect(true).toBe(true);
33
+ }
34
+ });
35
+ });
36
+
37
+ describe('saveClipboardImage', () => {
38
+ it('should return null on non-macOS platforms', async () => {
39
+ if (process.platform !== 'darwin') {
40
+ const result = await saveClipboardImage();
41
+ expect(result).toBe(null);
42
+ } else {
43
+ // Skip on macOS
44
+ expect(true).toBe(true);
45
+ }
46
+ });
47
+
48
+ it('should handle errors gracefully', async () => {
49
+ // Test with invalid directory (should not throw)
50
+ const result = await saveClipboardImage(
51
+ '/invalid/path/that/does/not/exist',
52
+ );
53
+
54
+ if (process.platform === 'darwin') {
55
+ // On macOS, might return null due to various errors
56
+ expect(result === null || typeof result === 'string').toBe(true);
57
+ } else {
58
+ // On other platforms, should always return null
59
+ expect(result).toBe(null);
60
+ }
61
+ });
62
+ });
63
+
64
+ describe('cleanupOldClipboardImages', () => {
65
+ it('should not throw errors', async () => {
66
+ // Should handle missing directories gracefully
67
+ await expect(
68
+ cleanupOldClipboardImages('/path/that/does/not/exist'),
69
+ ).resolves.not.toThrow();
70
+ });
71
+
72
+ it('should complete without errors on valid directory', async () => {
73
+ await expect(cleanupOldClipboardImages('.')).resolves.not.toThrow();
74
+ });
75
+ });
76
+ });
projects/ui/qwen-code/packages/cli/src/ui/utils/clipboardUtils.ts ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { exec } from 'child_process';
8
+ import { promisify } from 'util';
9
+ import * as fs from 'fs/promises';
10
+ import * as path from 'path';
11
+
12
+ const execAsync = promisify(exec);
13
+
14
+ /**
15
+ * Checks if the system clipboard contains an image (macOS only for now)
16
+ * @returns true if clipboard contains an image
17
+ */
18
+ export async function clipboardHasImage(): Promise<boolean> {
19
+ if (process.platform !== 'darwin') {
20
+ return false;
21
+ }
22
+
23
+ try {
24
+ // Use osascript to check clipboard type
25
+ const { stdout } = await execAsync(
26
+ `osascript -e 'clipboard info' 2>/dev/null | grep -qE "«class PNGf»|TIFF picture|JPEG picture|GIF picture|«class JPEG»|«class TIFF»" && echo "true" || echo "false"`,
27
+ { shell: '/bin/bash' },
28
+ );
29
+ return stdout.trim() === 'true';
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Saves the image from clipboard to a temporary file (macOS only for now)
37
+ * @param targetDir The target directory to create temp files within
38
+ * @returns The path to the saved image file, or null if no image or error
39
+ */
40
+ export async function saveClipboardImage(
41
+ targetDir?: string,
42
+ ): Promise<string | null> {
43
+ if (process.platform !== 'darwin') {
44
+ return null;
45
+ }
46
+
47
+ try {
48
+ // Create a temporary directory for clipboard images within the target directory
49
+ // This avoids security restrictions on paths outside the target directory
50
+ const baseDir = targetDir || process.cwd();
51
+ const tempDir = path.join(baseDir, '.gemini-clipboard');
52
+ await fs.mkdir(tempDir, { recursive: true });
53
+
54
+ // Generate a unique filename with timestamp
55
+ const timestamp = new Date().getTime();
56
+
57
+ // Try different image formats in order of preference
58
+ const formats = [
59
+ { class: 'PNGf', extension: 'png' },
60
+ { class: 'JPEG', extension: 'jpg' },
61
+ { class: 'TIFF', extension: 'tiff' },
62
+ { class: 'GIFf', extension: 'gif' },
63
+ ];
64
+
65
+ for (const format of formats) {
66
+ const tempFilePath = path.join(
67
+ tempDir,
68
+ `clipboard-${timestamp}.${format.extension}`,
69
+ );
70
+
71
+ // Try to save clipboard as this format
72
+ const script = `
73
+ try
74
+ set imageData to the clipboard as «class ${format.class}»
75
+ set fileRef to open for access POSIX file "${tempFilePath}" with write permission
76
+ write imageData to fileRef
77
+ close access fileRef
78
+ return "success"
79
+ on error errMsg
80
+ try
81
+ close access POSIX file "${tempFilePath}"
82
+ end try
83
+ return "error"
84
+ end try
85
+ `;
86
+
87
+ const { stdout } = await execAsync(`osascript -e '${script}'`);
88
+
89
+ if (stdout.trim() === 'success') {
90
+ // Verify the file was created and has content
91
+ try {
92
+ const stats = await fs.stat(tempFilePath);
93
+ if (stats.size > 0) {
94
+ return tempFilePath;
95
+ }
96
+ } catch {
97
+ // File doesn't exist, continue to next format
98
+ }
99
+ }
100
+
101
+ // Clean up failed attempt
102
+ try {
103
+ await fs.unlink(tempFilePath);
104
+ } catch {
105
+ // Ignore cleanup errors
106
+ }
107
+ }
108
+
109
+ // No format worked
110
+ return null;
111
+ } catch (error) {
112
+ console.error('Error saving clipboard image:', error);
113
+ return null;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Cleans up old temporary clipboard image files
119
+ * Removes files older than 1 hour
120
+ * @param targetDir The target directory where temp files are stored
121
+ */
122
+ export async function cleanupOldClipboardImages(
123
+ targetDir?: string,
124
+ ): Promise<void> {
125
+ try {
126
+ const baseDir = targetDir || process.cwd();
127
+ const tempDir = path.join(baseDir, '.gemini-clipboard');
128
+ const files = await fs.readdir(tempDir);
129
+ const oneHourAgo = Date.now() - 60 * 60 * 1000;
130
+
131
+ for (const file of files) {
132
+ if (
133
+ file.startsWith('clipboard-') &&
134
+ (file.endsWith('.png') ||
135
+ file.endsWith('.jpg') ||
136
+ file.endsWith('.tiff') ||
137
+ file.endsWith('.gif'))
138
+ ) {
139
+ const filePath = path.join(tempDir, file);
140
+ const stats = await fs.stat(filePath);
141
+ if (stats.mtimeMs < oneHourAgo) {
142
+ await fs.unlink(filePath);
143
+ }
144
+ }
145
+ }
146
+ } catch {
147
+ // Ignore errors in cleanup
148
+ }
149
+ }
projects/ui/qwen-code/packages/cli/src/ui/utils/commandUtils.test.ts ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, Mock } from 'vitest';
8
+ import { spawn } from 'child_process';
9
+ import { EventEmitter } from 'events';
10
+ import {
11
+ isAtCommand,
12
+ isSlashCommand,
13
+ copyToClipboard,
14
+ getUrlOpenCommand,
15
+ } from './commandUtils.js';
16
+
17
+ // Mock child_process
18
+ vi.mock('child_process');
19
+
20
+ // Mock process.platform for platform-specific tests
21
+ const mockProcess = vi.hoisted(() => ({
22
+ platform: 'darwin',
23
+ }));
24
+
25
+ vi.stubGlobal('process', {
26
+ ...process,
27
+ get platform() {
28
+ return mockProcess.platform;
29
+ },
30
+ });
31
+
32
+ interface MockChildProcess extends EventEmitter {
33
+ stdin: EventEmitter & {
34
+ write: Mock;
35
+ end: Mock;
36
+ };
37
+ stderr: EventEmitter;
38
+ }
39
+
40
+ describe('commandUtils', () => {
41
+ let mockSpawn: Mock;
42
+ let mockChild: MockChildProcess;
43
+
44
+ beforeEach(async () => {
45
+ vi.clearAllMocks();
46
+ // Dynamically import and set up spawn mock
47
+ const { spawn } = await import('child_process');
48
+ mockSpawn = spawn as Mock;
49
+
50
+ // Create mock child process with stdout/stderr emitters
51
+ mockChild = Object.assign(new EventEmitter(), {
52
+ stdin: Object.assign(new EventEmitter(), {
53
+ write: vi.fn(),
54
+ end: vi.fn(),
55
+ }),
56
+ stderr: new EventEmitter(),
57
+ }) as MockChildProcess;
58
+
59
+ mockSpawn.mockReturnValue(mockChild as unknown as ReturnType<typeof spawn>);
60
+ });
61
+
62
+ describe('isAtCommand', () => {
63
+ it('should return true when query starts with @', () => {
64
+ expect(isAtCommand('@file')).toBe(true);
65
+ expect(isAtCommand('@path/to/file')).toBe(true);
66
+ expect(isAtCommand('@')).toBe(true);
67
+ });
68
+
69
+ it('should return true when query contains @ preceded by whitespace', () => {
70
+ expect(isAtCommand('hello @file')).toBe(true);
71
+ expect(isAtCommand('some text @path/to/file')).toBe(true);
72
+ expect(isAtCommand(' @file')).toBe(true);
73
+ });
74
+
75
+ it('should return false when query does not start with @ and has no spaced @', () => {
76
+ expect(isAtCommand('file')).toBe(false);
77
+ expect(isAtCommand('hello')).toBe(false);
78
+ expect(isAtCommand('')).toBe(false);
79
+ expect(isAtCommand('email@domain.com')).toBe(false);
80
+ expect(isAtCommand('user@host')).toBe(false);
81
+ });
82
+
83
+ it('should return false when @ is not preceded by whitespace', () => {
84
+ expect(isAtCommand('hello@file')).toBe(false);
85
+ expect(isAtCommand('text@path')).toBe(false);
86
+ });
87
+ });
88
+
89
+ describe('isSlashCommand', () => {
90
+ it('should return true when query starts with /', () => {
91
+ expect(isSlashCommand('/help')).toBe(true);
92
+ expect(isSlashCommand('/memory show')).toBe(true);
93
+ expect(isSlashCommand('/clear')).toBe(true);
94
+ expect(isSlashCommand('/')).toBe(true);
95
+ });
96
+
97
+ it('should return false when query does not start with /', () => {
98
+ expect(isSlashCommand('help')).toBe(false);
99
+ expect(isSlashCommand('memory show')).toBe(false);
100
+ expect(isSlashCommand('')).toBe(false);
101
+ expect(isSlashCommand('path/to/file')).toBe(false);
102
+ expect(isSlashCommand(' /help')).toBe(false);
103
+ });
104
+ });
105
+
106
+ describe('copyToClipboard', () => {
107
+ describe('on macOS (darwin)', () => {
108
+ beforeEach(() => {
109
+ mockProcess.platform = 'darwin';
110
+ });
111
+
112
+ it('should successfully copy text to clipboard using pbcopy', async () => {
113
+ const testText = 'Hello, world!';
114
+
115
+ // Simulate successful execution
116
+ setTimeout(() => {
117
+ mockChild.emit('close', 0);
118
+ }, 0);
119
+
120
+ await copyToClipboard(testText);
121
+
122
+ expect(mockSpawn).toHaveBeenCalledWith('pbcopy', []);
123
+ expect(mockChild.stdin.write).toHaveBeenCalledWith(testText);
124
+ expect(mockChild.stdin.end).toHaveBeenCalled();
125
+ });
126
+
127
+ it('should handle pbcopy command failure', async () => {
128
+ const testText = 'Hello, world!';
129
+
130
+ // Simulate command failure
131
+ setTimeout(() => {
132
+ mockChild.stderr.emit('data', 'Command not found');
133
+ mockChild.emit('close', 1);
134
+ }, 0);
135
+
136
+ await expect(copyToClipboard(testText)).rejects.toThrow(
137
+ "'pbcopy' exited with code 1: Command not found",
138
+ );
139
+ });
140
+
141
+ it('should handle spawn error', async () => {
142
+ const testText = 'Hello, world!';
143
+
144
+ setTimeout(() => {
145
+ mockChild.emit('error', new Error('spawn error'));
146
+ }, 0);
147
+
148
+ await expect(copyToClipboard(testText)).rejects.toThrow('spawn error');
149
+ });
150
+
151
+ it('should handle stdin write error', async () => {
152
+ const testText = 'Hello, world!';
153
+
154
+ setTimeout(() => {
155
+ mockChild.stdin.emit('error', new Error('stdin error'));
156
+ }, 0);
157
+
158
+ await expect(copyToClipboard(testText)).rejects.toThrow('stdin error');
159
+ });
160
+ });
161
+
162
+ describe('on Windows (win32)', () => {
163
+ beforeEach(() => {
164
+ mockProcess.platform = 'win32';
165
+ });
166
+
167
+ it('should successfully copy text to clipboard using clip', async () => {
168
+ const testText = 'Hello, world!';
169
+
170
+ setTimeout(() => {
171
+ mockChild.emit('close', 0);
172
+ }, 0);
173
+
174
+ await copyToClipboard(testText);
175
+
176
+ expect(mockSpawn).toHaveBeenCalledWith('clip', []);
177
+ expect(mockChild.stdin.write).toHaveBeenCalledWith(testText);
178
+ expect(mockChild.stdin.end).toHaveBeenCalled();
179
+ });
180
+ });
181
+
182
+ describe('on Linux', () => {
183
+ beforeEach(() => {
184
+ mockProcess.platform = 'linux';
185
+ });
186
+
187
+ it('should successfully copy text to clipboard using xclip', async () => {
188
+ const testText = 'Hello, world!';
189
+
190
+ setTimeout(() => {
191
+ mockChild.emit('close', 0);
192
+ }, 0);
193
+
194
+ await copyToClipboard(testText);
195
+
196
+ expect(mockSpawn).toHaveBeenCalledWith('xclip', [
197
+ '-selection',
198
+ 'clipboard',
199
+ ]);
200
+ expect(mockChild.stdin.write).toHaveBeenCalledWith(testText);
201
+ expect(mockChild.stdin.end).toHaveBeenCalled();
202
+ });
203
+
204
+ it('should fall back to xsel when xclip fails', async () => {
205
+ const testText = 'Hello, world!';
206
+ let callCount = 0;
207
+
208
+ mockSpawn.mockImplementation(() => {
209
+ const child = Object.assign(new EventEmitter(), {
210
+ stdin: Object.assign(new EventEmitter(), {
211
+ write: vi.fn(),
212
+ end: vi.fn(),
213
+ }),
214
+ stderr: new EventEmitter(),
215
+ }) as MockChildProcess;
216
+
217
+ setTimeout(() => {
218
+ if (callCount === 0) {
219
+ // First call (xclip) fails
220
+ child.stderr.emit('data', 'xclip not found');
221
+ child.emit('close', 1);
222
+ callCount++;
223
+ } else {
224
+ // Second call (xsel) succeeds
225
+ child.emit('close', 0);
226
+ }
227
+ }, 0);
228
+
229
+ return child as unknown as ReturnType<typeof spawn>;
230
+ });
231
+
232
+ await copyToClipboard(testText);
233
+
234
+ expect(mockSpawn).toHaveBeenCalledTimes(2);
235
+ expect(mockSpawn).toHaveBeenNthCalledWith(1, 'xclip', [
236
+ '-selection',
237
+ 'clipboard',
238
+ ]);
239
+ expect(mockSpawn).toHaveBeenNthCalledWith(2, 'xsel', [
240
+ '--clipboard',
241
+ '--input',
242
+ ]);
243
+ });
244
+
245
+ it('should throw error when both xclip and xsel fail', async () => {
246
+ const testText = 'Hello, world!';
247
+ let callCount = 0;
248
+
249
+ mockSpawn.mockImplementation(() => {
250
+ const child = Object.assign(new EventEmitter(), {
251
+ stdin: Object.assign(new EventEmitter(), {
252
+ write: vi.fn(),
253
+ end: vi.fn(),
254
+ }),
255
+ stderr: new EventEmitter(),
256
+ });
257
+
258
+ setTimeout(() => {
259
+ if (callCount === 0) {
260
+ // First call (xclip) fails
261
+ child.stderr.emit('data', 'xclip command not found');
262
+ child.emit('close', 1);
263
+ callCount++;
264
+ } else {
265
+ // Second call (xsel) fails
266
+ child.stderr.emit('data', 'xsel command not found');
267
+ child.emit('close', 1);
268
+ }
269
+ }, 0);
270
+
271
+ return child as unknown as ReturnType<typeof spawn>;
272
+ });
273
+
274
+ await expect(copyToClipboard(testText)).rejects.toThrow(
275
+ /All copy commands failed/,
276
+ );
277
+
278
+ expect(mockSpawn).toHaveBeenCalledTimes(2);
279
+ });
280
+ });
281
+
282
+ describe('on unsupported platform', () => {
283
+ beforeEach(() => {
284
+ mockProcess.platform = 'unsupported';
285
+ });
286
+
287
+ it('should throw error for unsupported platform', async () => {
288
+ await expect(copyToClipboard('test')).rejects.toThrow(
289
+ 'Unsupported platform: unsupported',
290
+ );
291
+ });
292
+ });
293
+
294
+ describe('error handling', () => {
295
+ beforeEach(() => {
296
+ mockProcess.platform = 'darwin';
297
+ });
298
+
299
+ it('should handle command exit without stderr', async () => {
300
+ const testText = 'Hello, world!';
301
+
302
+ setTimeout(() => {
303
+ mockChild.emit('close', 1);
304
+ }, 0);
305
+
306
+ await expect(copyToClipboard(testText)).rejects.toThrow(
307
+ "'pbcopy' exited with code 1",
308
+ );
309
+ });
310
+
311
+ it('should handle empty text', async () => {
312
+ setTimeout(() => {
313
+ mockChild.emit('close', 0);
314
+ }, 0);
315
+
316
+ await copyToClipboard('');
317
+
318
+ expect(mockChild.stdin.write).toHaveBeenCalledWith('');
319
+ });
320
+
321
+ it('should handle multiline text', async () => {
322
+ const multilineText = 'Line 1\nLine 2\nLine 3';
323
+
324
+ setTimeout(() => {
325
+ mockChild.emit('close', 0);
326
+ }, 0);
327
+
328
+ await copyToClipboard(multilineText);
329
+
330
+ expect(mockChild.stdin.write).toHaveBeenCalledWith(multilineText);
331
+ });
332
+
333
+ it('should handle special characters', async () => {
334
+ const specialText = 'Special chars: !@#$%^&*()_+-=[]{}|;:,.<>?';
335
+
336
+ setTimeout(() => {
337
+ mockChild.emit('close', 0);
338
+ }, 0);
339
+
340
+ await copyToClipboard(specialText);
341
+
342
+ expect(mockChild.stdin.write).toHaveBeenCalledWith(specialText);
343
+ });
344
+ });
345
+ });
346
+
347
+ describe('getUrlOpenCommand', () => {
348
+ describe('on macOS (darwin)', () => {
349
+ beforeEach(() => {
350
+ mockProcess.platform = 'darwin';
351
+ });
352
+ it('should return open', () => {
353
+ expect(getUrlOpenCommand()).toBe('open');
354
+ });
355
+ });
356
+
357
+ describe('on Windows (win32)', () => {
358
+ beforeEach(() => {
359
+ mockProcess.platform = 'win32';
360
+ });
361
+ it('should return start', () => {
362
+ expect(getUrlOpenCommand()).toBe('start');
363
+ });
364
+ });
365
+
366
+ describe('on Linux (linux)', () => {
367
+ beforeEach(() => {
368
+ mockProcess.platform = 'linux';
369
+ });
370
+ it('should return xdg-open', () => {
371
+ expect(getUrlOpenCommand()).toBe('xdg-open');
372
+ });
373
+ });
374
+
375
+ describe('on unmatched OS', () => {
376
+ beforeEach(() => {
377
+ mockProcess.platform = 'unmatched';
378
+ });
379
+ it('should return xdg-open', () => {
380
+ expect(getUrlOpenCommand()).toBe('xdg-open');
381
+ });
382
+ });
383
+ });
384
+ });
projects/ui/qwen-code/packages/cli/src/ui/utils/commandUtils.ts ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { spawn } from 'child_process';
8
+
9
+ /**
10
+ * Checks if a query string potentially represents an '@' command.
11
+ * It triggers if the query starts with '@' or contains '@' preceded by whitespace
12
+ * and followed by a non-whitespace character.
13
+ *
14
+ * @param query The input query string.
15
+ * @returns True if the query looks like an '@' command, false otherwise.
16
+ */
17
+ export const isAtCommand = (query: string): boolean =>
18
+ // Check if starts with @ OR has a space, then @
19
+ query.startsWith('@') || /\s@/.test(query);
20
+
21
+ /**
22
+ * Checks if a query string potentially represents an '/' command.
23
+ * It triggers if the query starts with '/'
24
+ *
25
+ * @param query The input query string.
26
+ * @returns True if the query looks like an '/' command, false otherwise.
27
+ */
28
+ export const isSlashCommand = (query: string): boolean => query.startsWith('/');
29
+
30
+ // Copies a string snippet to the clipboard for different platforms
31
+ export const copyToClipboard = async (text: string): Promise<void> => {
32
+ const run = (cmd: string, args: string[]) =>
33
+ new Promise<void>((resolve, reject) => {
34
+ const child = spawn(cmd, args);
35
+ let stderr = '';
36
+ child.stderr.on('data', (chunk) => (stderr += chunk.toString()));
37
+ child.on('error', reject);
38
+ child.on('close', (code) => {
39
+ if (code === 0) return resolve();
40
+ const errorMsg = stderr.trim();
41
+ reject(
42
+ new Error(
43
+ `'${cmd}' exited with code ${code}${errorMsg ? `: ${errorMsg}` : ''}`,
44
+ ),
45
+ );
46
+ });
47
+ child.stdin.on('error', reject);
48
+ child.stdin.write(text);
49
+ child.stdin.end();
50
+ });
51
+
52
+ switch (process.platform) {
53
+ case 'win32':
54
+ return run('clip', []);
55
+ case 'darwin':
56
+ return run('pbcopy', []);
57
+ case 'linux':
58
+ try {
59
+ await run('xclip', ['-selection', 'clipboard']);
60
+ } catch (primaryError) {
61
+ try {
62
+ // If xclip fails for any reason, try xsel as a fallback.
63
+ await run('xsel', ['--clipboard', '--input']);
64
+ } catch (fallbackError) {
65
+ const primaryMsg =
66
+ primaryError instanceof Error
67
+ ? primaryError.message
68
+ : String(primaryError);
69
+ const fallbackMsg =
70
+ fallbackError instanceof Error
71
+ ? fallbackError.message
72
+ : String(fallbackError);
73
+ throw new Error(
74
+ `All copy commands failed. xclip: "${primaryMsg}", xsel: "${fallbackMsg}". Please ensure xclip or xsel is installed and configured.`,
75
+ );
76
+ }
77
+ }
78
+ return;
79
+ default:
80
+ throw new Error(`Unsupported platform: ${process.platform}`);
81
+ }
82
+ };
83
+
84
+ export const getUrlOpenCommand = (): string => {
85
+ // --- Determine the OS-specific command to open URLs ---
86
+ let openCmd: string;
87
+ switch (process.platform) {
88
+ case 'darwin':
89
+ openCmd = 'open';
90
+ break;
91
+ case 'win32':
92
+ openCmd = 'start';
93
+ break;
94
+ case 'linux':
95
+ openCmd = 'xdg-open';
96
+ break;
97
+ default:
98
+ // Default to xdg-open, which appears to be supported for the less popular operating systems.
99
+ openCmd = 'xdg-open';
100
+ console.warn(
101
+ `Unknown platform: ${process.platform}. Attempting to open URLs with: ${openCmd}.`,
102
+ );
103
+ break;
104
+ }
105
+ return openCmd;
106
+ };
projects/ui/qwen-code/packages/cli/src/ui/utils/computeStats.test.ts ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import {
9
+ calculateAverageLatency,
10
+ calculateCacheHitRate,
11
+ calculateErrorRate,
12
+ computeSessionStats,
13
+ } from './computeStats.js';
14
+ import { ModelMetrics, SessionMetrics } from '../contexts/SessionContext.js';
15
+
16
+ describe('calculateErrorRate', () => {
17
+ it('should return 0 if totalRequests is 0', () => {
18
+ const metrics: ModelMetrics = {
19
+ api: { totalRequests: 0, totalErrors: 0, totalLatencyMs: 0 },
20
+ tokens: {
21
+ prompt: 0,
22
+ candidates: 0,
23
+ total: 0,
24
+ cached: 0,
25
+ thoughts: 0,
26
+ tool: 0,
27
+ },
28
+ };
29
+ expect(calculateErrorRate(metrics)).toBe(0);
30
+ });
31
+
32
+ it('should calculate the error rate correctly', () => {
33
+ const metrics: ModelMetrics = {
34
+ api: { totalRequests: 10, totalErrors: 2, totalLatencyMs: 0 },
35
+ tokens: {
36
+ prompt: 0,
37
+ candidates: 0,
38
+ total: 0,
39
+ cached: 0,
40
+ thoughts: 0,
41
+ tool: 0,
42
+ },
43
+ };
44
+ expect(calculateErrorRate(metrics)).toBe(20);
45
+ });
46
+ });
47
+
48
+ describe('calculateAverageLatency', () => {
49
+ it('should return 0 if totalRequests is 0', () => {
50
+ const metrics: ModelMetrics = {
51
+ api: { totalRequests: 0, totalErrors: 0, totalLatencyMs: 1000 },
52
+ tokens: {
53
+ prompt: 0,
54
+ candidates: 0,
55
+ total: 0,
56
+ cached: 0,
57
+ thoughts: 0,
58
+ tool: 0,
59
+ },
60
+ };
61
+ expect(calculateAverageLatency(metrics)).toBe(0);
62
+ });
63
+
64
+ it('should calculate the average latency correctly', () => {
65
+ const metrics: ModelMetrics = {
66
+ api: { totalRequests: 10, totalErrors: 0, totalLatencyMs: 1500 },
67
+ tokens: {
68
+ prompt: 0,
69
+ candidates: 0,
70
+ total: 0,
71
+ cached: 0,
72
+ thoughts: 0,
73
+ tool: 0,
74
+ },
75
+ };
76
+ expect(calculateAverageLatency(metrics)).toBe(150);
77
+ });
78
+ });
79
+
80
+ describe('calculateCacheHitRate', () => {
81
+ it('should return 0 if prompt tokens is 0', () => {
82
+ const metrics: ModelMetrics = {
83
+ api: { totalRequests: 0, totalErrors: 0, totalLatencyMs: 0 },
84
+ tokens: {
85
+ prompt: 0,
86
+ candidates: 0,
87
+ total: 0,
88
+ cached: 100,
89
+ thoughts: 0,
90
+ tool: 0,
91
+ },
92
+ };
93
+ expect(calculateCacheHitRate(metrics)).toBe(0);
94
+ });
95
+
96
+ it('should calculate the cache hit rate correctly', () => {
97
+ const metrics: ModelMetrics = {
98
+ api: { totalRequests: 0, totalErrors: 0, totalLatencyMs: 0 },
99
+ tokens: {
100
+ prompt: 200,
101
+ candidates: 0,
102
+ total: 0,
103
+ cached: 50,
104
+ thoughts: 0,
105
+ tool: 0,
106
+ },
107
+ };
108
+ expect(calculateCacheHitRate(metrics)).toBe(25);
109
+ });
110
+ });
111
+
112
+ describe('computeSessionStats', () => {
113
+ it('should return all zeros for initial empty metrics', () => {
114
+ const metrics: SessionMetrics = {
115
+ models: {},
116
+ tools: {
117
+ totalCalls: 0,
118
+ totalSuccess: 0,
119
+ totalFail: 0,
120
+ totalDurationMs: 0,
121
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
122
+ byName: {},
123
+ },
124
+ files: {
125
+ totalLinesAdded: 0,
126
+ totalLinesRemoved: 0,
127
+ },
128
+ };
129
+
130
+ const result = computeSessionStats(metrics);
131
+
132
+ expect(result).toEqual({
133
+ totalApiTime: 0,
134
+ totalToolTime: 0,
135
+ agentActiveTime: 0,
136
+ apiTimePercent: 0,
137
+ toolTimePercent: 0,
138
+ cacheEfficiency: 0,
139
+ totalDecisions: 0,
140
+ successRate: 0,
141
+ agreementRate: 0,
142
+ totalPromptTokens: 0,
143
+ totalCachedTokens: 0,
144
+ totalLinesAdded: 0,
145
+ totalLinesRemoved: 0,
146
+ });
147
+ });
148
+
149
+ it('should correctly calculate API and tool time percentages', () => {
150
+ const metrics: SessionMetrics = {
151
+ models: {
152
+ 'gemini-pro': {
153
+ api: { totalRequests: 1, totalErrors: 0, totalLatencyMs: 750 },
154
+ tokens: {
155
+ prompt: 10,
156
+ candidates: 10,
157
+ total: 20,
158
+ cached: 0,
159
+ thoughts: 0,
160
+ tool: 0,
161
+ },
162
+ },
163
+ },
164
+ tools: {
165
+ totalCalls: 1,
166
+ totalSuccess: 1,
167
+ totalFail: 0,
168
+ totalDurationMs: 250,
169
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
170
+ byName: {},
171
+ },
172
+ files: {
173
+ totalLinesAdded: 0,
174
+ totalLinesRemoved: 0,
175
+ },
176
+ };
177
+
178
+ const result = computeSessionStats(metrics);
179
+
180
+ expect(result.totalApiTime).toBe(750);
181
+ expect(result.totalToolTime).toBe(250);
182
+ expect(result.agentActiveTime).toBe(1000);
183
+ expect(result.apiTimePercent).toBe(75);
184
+ expect(result.toolTimePercent).toBe(25);
185
+ });
186
+
187
+ it('should correctly calculate cache efficiency', () => {
188
+ const metrics: SessionMetrics = {
189
+ models: {
190
+ 'gemini-pro': {
191
+ api: { totalRequests: 2, totalErrors: 0, totalLatencyMs: 1000 },
192
+ tokens: {
193
+ prompt: 150,
194
+ candidates: 10,
195
+ total: 160,
196
+ cached: 50,
197
+ thoughts: 0,
198
+ tool: 0,
199
+ },
200
+ },
201
+ },
202
+ tools: {
203
+ totalCalls: 0,
204
+ totalSuccess: 0,
205
+ totalFail: 0,
206
+ totalDurationMs: 0,
207
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
208
+ byName: {},
209
+ },
210
+ files: {
211
+ totalLinesAdded: 0,
212
+ totalLinesRemoved: 0,
213
+ },
214
+ };
215
+
216
+ const result = computeSessionStats(metrics);
217
+
218
+ expect(result.cacheEfficiency).toBeCloseTo(33.33); // 50 / 150
219
+ });
220
+
221
+ it('should correctly calculate success and agreement rates', () => {
222
+ const metrics: SessionMetrics = {
223
+ models: {},
224
+ tools: {
225
+ totalCalls: 10,
226
+ totalSuccess: 8,
227
+ totalFail: 2,
228
+ totalDurationMs: 1000,
229
+ totalDecisions: { accept: 6, reject: 2, modify: 2 },
230
+ byName: {},
231
+ },
232
+ files: {
233
+ totalLinesAdded: 0,
234
+ totalLinesRemoved: 0,
235
+ },
236
+ };
237
+
238
+ const result = computeSessionStats(metrics);
239
+
240
+ expect(result.successRate).toBe(80); // 8 / 10
241
+ expect(result.agreementRate).toBe(60); // 6 / 10
242
+ });
243
+
244
+ it('should handle division by zero gracefully', () => {
245
+ const metrics: SessionMetrics = {
246
+ models: {},
247
+ tools: {
248
+ totalCalls: 0,
249
+ totalSuccess: 0,
250
+ totalFail: 0,
251
+ totalDurationMs: 0,
252
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
253
+ byName: {},
254
+ },
255
+ files: {
256
+ totalLinesAdded: 0,
257
+ totalLinesRemoved: 0,
258
+ },
259
+ };
260
+
261
+ const result = computeSessionStats(metrics);
262
+
263
+ expect(result.apiTimePercent).toBe(0);
264
+ expect(result.toolTimePercent).toBe(0);
265
+ expect(result.cacheEfficiency).toBe(0);
266
+ expect(result.successRate).toBe(0);
267
+ expect(result.agreementRate).toBe(0);
268
+ });
269
+
270
+ it('should correctly include line counts', () => {
271
+ const metrics: SessionMetrics = {
272
+ models: {},
273
+ tools: {
274
+ totalCalls: 0,
275
+ totalSuccess: 0,
276
+ totalFail: 0,
277
+ totalDurationMs: 0,
278
+ totalDecisions: { accept: 0, reject: 0, modify: 0 },
279
+ byName: {},
280
+ },
281
+ files: {
282
+ totalLinesAdded: 42,
283
+ totalLinesRemoved: 18,
284
+ },
285
+ };
286
+
287
+ const result = computeSessionStats(metrics);
288
+
289
+ expect(result.totalLinesAdded).toBe(42);
290
+ expect(result.totalLinesRemoved).toBe(18);
291
+ });
292
+ });
projects/ui/qwen-code/packages/cli/src/ui/utils/computeStats.ts ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ SessionMetrics,
9
+ ComputedSessionStats,
10
+ ModelMetrics,
11
+ } from '../contexts/SessionContext.js';
12
+
13
+ export function calculateErrorRate(metrics: ModelMetrics): number {
14
+ if (metrics.api.totalRequests === 0) {
15
+ return 0;
16
+ }
17
+ return (metrics.api.totalErrors / metrics.api.totalRequests) * 100;
18
+ }
19
+
20
+ export function calculateAverageLatency(metrics: ModelMetrics): number {
21
+ if (metrics.api.totalRequests === 0) {
22
+ return 0;
23
+ }
24
+ return metrics.api.totalLatencyMs / metrics.api.totalRequests;
25
+ }
26
+
27
+ export function calculateCacheHitRate(metrics: ModelMetrics): number {
28
+ if (metrics.tokens.prompt === 0) {
29
+ return 0;
30
+ }
31
+ return (metrics.tokens.cached / metrics.tokens.prompt) * 100;
32
+ }
33
+
34
+ export const computeSessionStats = (
35
+ metrics: SessionMetrics,
36
+ ): ComputedSessionStats => {
37
+ const { models, tools, files } = metrics;
38
+ const totalApiTime = Object.values(models).reduce(
39
+ (acc, model) => acc + model.api.totalLatencyMs,
40
+ 0,
41
+ );
42
+ const totalToolTime = tools.totalDurationMs;
43
+ const agentActiveTime = totalApiTime + totalToolTime;
44
+ const apiTimePercent =
45
+ agentActiveTime > 0 ? (totalApiTime / agentActiveTime) * 100 : 0;
46
+ const toolTimePercent =
47
+ agentActiveTime > 0 ? (totalToolTime / agentActiveTime) * 100 : 0;
48
+
49
+ const totalCachedTokens = Object.values(models).reduce(
50
+ (acc, model) => acc + model.tokens.cached,
51
+ 0,
52
+ );
53
+ const totalPromptTokens = Object.values(models).reduce(
54
+ (acc, model) => acc + model.tokens.prompt,
55
+ 0,
56
+ );
57
+ const cacheEfficiency =
58
+ totalPromptTokens > 0 ? (totalCachedTokens / totalPromptTokens) * 100 : 0;
59
+
60
+ const totalDecisions =
61
+ tools.totalDecisions.accept +
62
+ tools.totalDecisions.reject +
63
+ tools.totalDecisions.modify;
64
+ const successRate =
65
+ tools.totalCalls > 0 ? (tools.totalSuccess / tools.totalCalls) * 100 : 0;
66
+ const agreementRate =
67
+ totalDecisions > 0
68
+ ? (tools.totalDecisions.accept / totalDecisions) * 100
69
+ : 0;
70
+
71
+ return {
72
+ totalApiTime,
73
+ totalToolTime,
74
+ agentActiveTime,
75
+ apiTimePercent,
76
+ toolTimePercent,
77
+ cacheEfficiency,
78
+ totalDecisions,
79
+ successRate,
80
+ agreementRate,
81
+ totalCachedTokens,
82
+ totalPromptTokens,
83
+ totalLinesAdded: files.totalLinesAdded,
84
+ totalLinesRemoved: files.totalLinesRemoved,
85
+ };
86
+ };
projects/ui/qwen-code/packages/cli/src/ui/utils/displayUtils.test.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import {
9
+ getStatusColor,
10
+ TOOL_SUCCESS_RATE_HIGH,
11
+ TOOL_SUCCESS_RATE_MEDIUM,
12
+ USER_AGREEMENT_RATE_HIGH,
13
+ USER_AGREEMENT_RATE_MEDIUM,
14
+ CACHE_EFFICIENCY_HIGH,
15
+ CACHE_EFFICIENCY_MEDIUM,
16
+ } from './displayUtils.js';
17
+ import { Colors } from '../colors.js';
18
+
19
+ describe('displayUtils', () => {
20
+ describe('getStatusColor', () => {
21
+ const thresholds = {
22
+ green: 80,
23
+ yellow: 50,
24
+ };
25
+
26
+ it('should return green for values >= green threshold', () => {
27
+ expect(getStatusColor(90, thresholds)).toBe(Colors.AccentGreen);
28
+ expect(getStatusColor(80, thresholds)).toBe(Colors.AccentGreen);
29
+ });
30
+
31
+ it('should return yellow for values < green and >= yellow threshold', () => {
32
+ expect(getStatusColor(79, thresholds)).toBe(Colors.AccentYellow);
33
+ expect(getStatusColor(50, thresholds)).toBe(Colors.AccentYellow);
34
+ });
35
+
36
+ it('should return red for values < yellow threshold', () => {
37
+ expect(getStatusColor(49, thresholds)).toBe(Colors.AccentRed);
38
+ expect(getStatusColor(0, thresholds)).toBe(Colors.AccentRed);
39
+ });
40
+
41
+ it('should return defaultColor for values < yellow threshold when provided', () => {
42
+ expect(
43
+ getStatusColor(49, thresholds, { defaultColor: Colors.Foreground }),
44
+ ).toBe(Colors.Foreground);
45
+ });
46
+ });
47
+
48
+ describe('Threshold Constants', () => {
49
+ it('should have the correct values', () => {
50
+ expect(TOOL_SUCCESS_RATE_HIGH).toBe(95);
51
+ expect(TOOL_SUCCESS_RATE_MEDIUM).toBe(85);
52
+ expect(USER_AGREEMENT_RATE_HIGH).toBe(75);
53
+ expect(USER_AGREEMENT_RATE_MEDIUM).toBe(45);
54
+ expect(CACHE_EFFICIENCY_HIGH).toBe(40);
55
+ expect(CACHE_EFFICIENCY_MEDIUM).toBe(15);
56
+ });
57
+ });
58
+ });
projects/ui/qwen-code/packages/cli/src/ui/utils/displayUtils.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Colors } from '../colors.js';
8
+
9
+ // --- Thresholds ---
10
+ export const TOOL_SUCCESS_RATE_HIGH = 95;
11
+ export const TOOL_SUCCESS_RATE_MEDIUM = 85;
12
+
13
+ export const USER_AGREEMENT_RATE_HIGH = 75;
14
+ export const USER_AGREEMENT_RATE_MEDIUM = 45;
15
+
16
+ export const CACHE_EFFICIENCY_HIGH = 40;
17
+ export const CACHE_EFFICIENCY_MEDIUM = 15;
18
+
19
+ // --- Color Logic ---
20
+ export const getStatusColor = (
21
+ value: number,
22
+ thresholds: { green: number; yellow: number },
23
+ options: { defaultColor?: string } = {},
24
+ ) => {
25
+ if (value >= thresholds.green) {
26
+ return Colors.AccentGreen;
27
+ }
28
+ if (value >= thresholds.yellow) {
29
+ return Colors.AccentYellow;
30
+ }
31
+ return options.defaultColor || Colors.AccentRed;
32
+ };
projects/ui/qwen-code/packages/cli/src/ui/utils/formatters.test.ts ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import { formatDuration, formatMemoryUsage } from './formatters.js';
9
+
10
+ describe('formatters', () => {
11
+ describe('formatMemoryUsage', () => {
12
+ it('should format bytes into KB', () => {
13
+ expect(formatMemoryUsage(12345)).toBe('12.1 KB');
14
+ });
15
+
16
+ it('should format bytes into MB', () => {
17
+ expect(formatMemoryUsage(12345678)).toBe('11.8 MB');
18
+ });
19
+
20
+ it('should format bytes into GB', () => {
21
+ expect(formatMemoryUsage(12345678901)).toBe('11.50 GB');
22
+ });
23
+ });
24
+
25
+ describe('formatDuration', () => {
26
+ it('should format milliseconds less than a second', () => {
27
+ expect(formatDuration(500)).toBe('500ms');
28
+ });
29
+
30
+ it('should format a duration of 0', () => {
31
+ expect(formatDuration(0)).toBe('0s');
32
+ });
33
+
34
+ it('should format an exact number of seconds', () => {
35
+ expect(formatDuration(5000)).toBe('5.0s');
36
+ });
37
+
38
+ it('should format a duration in seconds with one decimal place', () => {
39
+ expect(formatDuration(12345)).toBe('12.3s');
40
+ });
41
+
42
+ it('should format an exact number of minutes', () => {
43
+ expect(formatDuration(120000)).toBe('2m');
44
+ });
45
+
46
+ it('should format a duration in minutes and seconds', () => {
47
+ expect(formatDuration(123000)).toBe('2m 3s');
48
+ });
49
+
50
+ it('should format an exact number of hours', () => {
51
+ expect(formatDuration(3600000)).toBe('1h');
52
+ });
53
+
54
+ it('should format a duration in hours and seconds', () => {
55
+ expect(formatDuration(3605000)).toBe('1h 5s');
56
+ });
57
+
58
+ it('should format a duration in hours, minutes, and seconds', () => {
59
+ expect(formatDuration(3723000)).toBe('1h 2m 3s');
60
+ });
61
+
62
+ it('should handle large durations', () => {
63
+ expect(formatDuration(86400000 + 3600000 + 120000 + 1000)).toBe(
64
+ '25h 2m 1s',
65
+ );
66
+ });
67
+
68
+ it('should handle negative durations', () => {
69
+ expect(formatDuration(-100)).toBe('0s');
70
+ });
71
+ });
72
+ });
projects/ui/qwen-code/packages/cli/src/ui/utils/formatters.ts ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export const formatMemoryUsage = (bytes: number): string => {
8
+ const gb = bytes / (1024 * 1024 * 1024);
9
+ if (bytes < 1024 * 1024) {
10
+ return `${(bytes / 1024).toFixed(1)} KB`;
11
+ }
12
+ if (bytes < 1024 * 1024 * 1024) {
13
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
14
+ }
15
+ return `${gb.toFixed(2)} GB`;
16
+ };
17
+
18
+ /**
19
+ * Formats a duration in milliseconds into a concise, human-readable string (e.g., "1h 5s").
20
+ * It omits any time units that are zero.
21
+ * @param milliseconds The duration in milliseconds.
22
+ * @returns A formatted string representing the duration.
23
+ */
24
+ export const formatDuration = (milliseconds: number): string => {
25
+ if (milliseconds <= 0) {
26
+ return '0s';
27
+ }
28
+
29
+ if (milliseconds < 1000) {
30
+ return `${Math.round(milliseconds)}ms`;
31
+ }
32
+
33
+ const totalSeconds = milliseconds / 1000;
34
+
35
+ if (totalSeconds < 60) {
36
+ return `${totalSeconds.toFixed(1)}s`;
37
+ }
38
+
39
+ const hours = Math.floor(totalSeconds / 3600);
40
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
41
+ const seconds = Math.floor(totalSeconds % 60);
42
+
43
+ const parts: string[] = [];
44
+
45
+ if (hours > 0) {
46
+ parts.push(`${hours}h`);
47
+ }
48
+ if (minutes > 0) {
49
+ parts.push(`${minutes}m`);
50
+ }
51
+ if (seconds > 0) {
52
+ parts.push(`${seconds}s`);
53
+ }
54
+
55
+ // If all parts are zero (e.g., exactly 1 hour), return the largest unit.
56
+ if (parts.length === 0) {
57
+ if (hours > 0) return `${hours}h`;
58
+ if (minutes > 0) return `${minutes}m`;
59
+ return `${seconds}s`;
60
+ }
61
+
62
+ return parts.join(' ');
63
+ };
projects/ui/qwen-code/packages/cli/src/ui/utils/isNarrowWidth.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export function isNarrowWidth(width: number): boolean {
8
+ return width < 80;
9
+ }
projects/ui/qwen-code/packages/cli/src/ui/utils/kittyProtocolDetector.ts ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ let detectionComplete = false;
8
+ let protocolSupported = false;
9
+ let protocolEnabled = false;
10
+
11
+ /**
12
+ * Detects Kitty keyboard protocol support.
13
+ * Definitive document about this protocol lives at https://sw.kovidgoyal.net/kitty/keyboard-protocol/
14
+ * This function should be called once at app startup.
15
+ */
16
+ export async function detectAndEnableKittyProtocol(): Promise<boolean> {
17
+ if (detectionComplete) {
18
+ return protocolSupported;
19
+ }
20
+
21
+ return new Promise((resolve) => {
22
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
23
+ detectionComplete = true;
24
+ resolve(false);
25
+ return;
26
+ }
27
+
28
+ const originalRawMode = process.stdin.isRaw;
29
+ if (!originalRawMode) {
30
+ process.stdin.setRawMode(true);
31
+ }
32
+
33
+ let responseBuffer = '';
34
+ let progressiveEnhancementReceived = false;
35
+ let checkFinished = false;
36
+
37
+ const handleData = (data: Buffer) => {
38
+ responseBuffer += data.toString();
39
+
40
+ // Check for progressive enhancement response (CSI ? <flags> u)
41
+ if (responseBuffer.includes('\x1b[?') && responseBuffer.includes('u')) {
42
+ progressiveEnhancementReceived = true;
43
+ }
44
+
45
+ // Check for device attributes response (CSI ? <attrs> c)
46
+ if (responseBuffer.includes('\x1b[?') && responseBuffer.includes('c')) {
47
+ if (!checkFinished) {
48
+ checkFinished = true;
49
+ process.stdin.removeListener('data', handleData);
50
+
51
+ if (!originalRawMode) {
52
+ process.stdin.setRawMode(false);
53
+ }
54
+
55
+ if (progressiveEnhancementReceived) {
56
+ // Enable the protocol
57
+ process.stdout.write('\x1b[>1u');
58
+ protocolSupported = true;
59
+ protocolEnabled = true;
60
+
61
+ // Set up cleanup on exit
62
+ process.on('exit', disableProtocol);
63
+ process.on('SIGTERM', disableProtocol);
64
+ }
65
+
66
+ detectionComplete = true;
67
+ resolve(protocolSupported);
68
+ }
69
+ }
70
+ };
71
+
72
+ process.stdin.on('data', handleData);
73
+
74
+ // Send queries
75
+ process.stdout.write('\x1b[?u'); // Query progressive enhancement
76
+ process.stdout.write('\x1b[c'); // Query device attributes
77
+
78
+ // Timeout after 50ms
79
+ setTimeout(() => {
80
+ if (!checkFinished) {
81
+ process.stdin.removeListener('data', handleData);
82
+ if (!originalRawMode) {
83
+ process.stdin.setRawMode(false);
84
+ }
85
+ detectionComplete = true;
86
+ resolve(false);
87
+ }
88
+ }, 50);
89
+ });
90
+ }
91
+
92
+ function disableProtocol() {
93
+ if (protocolEnabled) {
94
+ process.stdout.write('\x1b[<u');
95
+ protocolEnabled = false;
96
+ }
97
+ }
98
+
99
+ export function isKittyProtocolEnabled(): boolean {
100
+ return protocolEnabled;
101
+ }
102
+
103
+ export function isKittyProtocolSupported(): boolean {
104
+ return protocolSupported;
105
+ }