-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathChatView.spec.tsx
More file actions
1239 lines (1084 loc) · 31.2 KB
/
Copy pathChatView.spec.tsx
File metadata and controls
1239 lines (1084 loc) · 31.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// pnpm --filter @roo-code/vscode-webview test src/components/chat/__tests__/ChatView.spec.tsx
import React from "react"
import { render, waitFor, act, fireEvent } from "@/utils/test-utils"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { ExtensionStateContextProvider } from "@src/context/ExtensionStateContext"
import { vscode } from "@src/utils/vscode"
import type { SuggestionItem } from "@roo-code/types"
import ChatView, { ChatViewProps } from "../ChatView"
// Define minimal types needed for testing
interface ClineMessage {
type: "say" | "ask"
say?: string
ask?: string
ts: number
text?: string
partial?: boolean
}
interface ExtensionState {
version: string
clineMessages: ClineMessage[]
taskHistory: any[]
shouldShowAnnouncement: boolean
allowedCommands: string[]
alwaysAllowExecute: boolean
[key: string]: any
}
// Mock vscode API
vi.mock("@src/utils/vscode", () => ({
vscode: {
postMessage: vi.fn(),
},
}))
// Mock use-sound hook
const mockPlayFunction = vi.fn()
vi.mock("use-sound", () => ({
default: vi.fn().mockImplementation(() => {
return [mockPlayFunction]
}),
}))
// Mock components that use ESM dependencies
vi.mock("../ChatRow", () => ({
default: function MockChatRow({
message,
onSuggestionClick,
}: {
message: ClineMessage
onSuggestionClick?: (suggestion: SuggestionItem, event?: React.MouseEvent) => void
}) {
if (message.type === "ask" && message.ask === "followup" && message.text) {
try {
const followUp = JSON.parse(message.text) as { suggest?: SuggestionItem[] }
return (
<div data-testid="chat-row">
{followUp.suggest?.map((suggestion) => (
<button
key={suggestion.answer}
type="button"
onClick={(event) => onSuggestionClick?.(suggestion, event)}>
{suggestion.answer}
</button>
))}
</div>
)
} catch {
// Fall through to the generic row renderer.
}
}
return <div data-testid="chat-row">{JSON.stringify(message)}</div>
},
}))
vi.mock("../AutoApproveMenu", () => ({
default: () => null,
}))
// Mock react-virtuoso to render items directly without virtualization
// This allows tests to verify items rendered in the chat list
vi.mock("react-virtuoso", () => ({
Virtuoso: function MockVirtuoso({
data,
itemContent,
}: {
data: ClineMessage[]
itemContent: (index: number, item: ClineMessage) => React.ReactNode
}) {
return (
<div data-testid="virtuoso-item-list">
{data.map((item, index) => (
<div key={item.ts} data-testid={`virtuoso-item-${index}`}>
{itemContent(index, item)}
</div>
))}
</div>
)
},
}))
// Mock VersionIndicator - returns null by default to prevent rendering in tests
vi.mock("../../common/VersionIndicator", () => ({
default: vi.fn(() => null),
}))
// Get the mock function after the module is mocked
const mockVersionIndicator = vi.mocked((await import("../../common/VersionIndicator")).default)
vi.mock("../Announcement", () => ({
default: function MockAnnouncement({ hideAnnouncement }: { hideAnnouncement: () => void }) {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const React = require("react")
return React.createElement(
"div",
{ "data-testid": "announcement-modal" },
React.createElement("div", null, "What's New"),
React.createElement("button", { onClick: hideAnnouncement }, "Close"),
)
},
}))
// Mock QueuedMessages component
vi.mock("../QueuedMessages", () => ({
QueuedMessages: function MockQueuedMessages({
queue = [],
onRemove,
}: {
queue?: Array<{ id: string; text: string; images?: string[] }>
onRemove?: (index: number) => void
onUpdate?: (index: number, newText: string) => void
}) {
if (!queue || queue.length === 0) {
return null
}
return (
<div data-testid="queued-messages">
{queue.map((msg, index) => (
<div key={msg.id}>
<span>{msg.text}</span>
<button aria-label="Remove message" onClick={() => onRemove?.(index)}>
Remove
</button>
</div>
))}
</div>
)
},
}))
// Mock RooTips component
vi.mock("@src/components/welcome/RooTips", () => ({
default: function MockRooTips() {
return <div data-testid="roo-tips">Tips content</div>
},
}))
// Mock RooHero component
vi.mock("@src/components/welcome/RooHero", () => ({
default: function MockRooHero() {
return <div data-testid="roo-hero">Hero content</div>
},
}))
// Mock TelemetryBanner component
vi.mock("../common/TelemetryBanner", () => ({
default: function MockTelemetryBanner() {
return null // Don't render anything to avoid interference
},
}))
// Mock i18n
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: any) => {
if (key === "chat:versionIndicator.ariaLabel" && options?.version) {
return `Version ${options.version}`
}
return key
},
}),
initReactI18next: {
type: "3rdParty",
init: () => {},
},
Trans: ({ i18nKey, children }: { i18nKey: string; children?: React.ReactNode }) => {
return <>{children || i18nKey}</>
},
}))
interface ChatTextAreaProps {
onSend: () => void
inputValue?: string
setInputValue?: (value: string) => void
sendingDisabled?: boolean
placeholderText?: string
selectedImages?: string[]
shouldDisableImages?: boolean
}
const mockInputRef = React.createRef<HTMLInputElement>()
const mockFocus = vi.fn()
vi.mock("../ChatTextArea", () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const mockReact = require("react")
const ChatTextAreaComponent = mockReact.forwardRef(function MockChatTextArea(
props: ChatTextAreaProps,
ref: React.ForwardedRef<{ focus: () => void }>,
) {
// Use useImperativeHandle to expose the mock focus method
mockReact.useImperativeHandle(ref, () => ({
focus: mockFocus,
}))
return (
<div data-testid="chat-textarea">
<input
ref={mockInputRef}
type="text"
value={props.inputValue || ""}
onChange={(e) => {
// Use parent's setInputValue if available
if (props.setInputValue) {
props.setInputValue(e.target.value)
}
}}
onKeyDown={(e) => {
// Only call onSend when Enter is pressed (simulating real behavior)
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault()
props.onSend()
}
}}
data-sending-disabled={props.sendingDisabled}
/>
</div>
)
})
return {
default: ChatTextAreaComponent,
ChatTextArea: ChatTextAreaComponent, // Export as named export too
}
})
// Mock VSCode components
vi.mock("@vscode/webview-ui-toolkit/react", () => ({
VSCodeButton: function MockVSCodeButton({
children,
onClick,
appearance,
}: {
children: React.ReactNode
onClick?: () => void
appearance?: string
}) {
return (
<button onClick={onClick} data-appearance={appearance}>
{children}
</button>
)
},
VSCodeTextField: function MockVSCodeTextField({
value,
onInput,
placeholder,
}: {
value?: string
onInput?: (e: { target: { value: string } }) => void
placeholder?: string
}) {
return (
<input
type="text"
value={value}
onChange={(e) => onInput?.({ target: { value: e.target.value } })}
placeholder={placeholder}
/>
)
},
VSCodeLink: function MockVSCodeLink({ children, href }: { children: React.ReactNode; href?: string }) {
return <a href={href}>{children}</a>
},
}))
// Mock window.postMessage to trigger state hydration
const mockPostMessage = (state: Partial<ExtensionState>) => {
window.postMessage(
{
type: "state",
state: {
version: "1.0.0",
clineMessages: [],
taskHistory: [],
shouldShowAnnouncement: false,
allowedCommands: [],
alwaysAllowExecute: false,
cloudIsAuthenticated: false,
telemetrySetting: "enabled",
...state,
},
},
"*",
)
}
const defaultProps: ChatViewProps = {
isHidden: false,
showAnnouncement: false,
hideAnnouncement: () => {},
}
const queryClient = new QueryClient()
const renderChatView = (props: Partial<ChatViewProps> = {}) => {
return render(
<ExtensionStateContextProvider>
<QueryClientProvider client={queryClient}>
<ChatView {...defaultProps} {...props} />
</QueryClientProvider>
</ExtensionStateContextProvider>,
)
}
describe("ChatView - Sound Playing Tests", () => {
beforeEach(() => vi.clearAllMocks())
it("plays celebration sound for completion results", async () => {
renderChatView()
// First hydrate state with initial task
mockPostMessage({
soundEnabled: true, // Enable sound
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
],
})
// Clear any initial calls
mockPlayFunction.mockClear()
// Add completion result
mockPostMessage({
soundEnabled: true, // Enable sound
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "ask",
ask: "completion_result",
ts: Date.now(),
text: "Task completed successfully",
partial: false, // Ensure it's not partial
},
],
})
// Wait for sound to be played
await waitFor(() => {
expect(mockPlayFunction).toHaveBeenCalled()
})
})
it("plays progress_loop sound for api failures", async () => {
renderChatView()
// First hydrate state with initial task
mockPostMessage({
soundEnabled: true, // Enable sound
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
],
})
// Clear any initial calls
mockPlayFunction.mockClear()
// Add API failure
mockPostMessage({
soundEnabled: true, // Enable sound
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "ask",
ask: "api_req_failed",
ts: Date.now(),
text: "API request failed",
partial: false, // Ensure it's not partial
},
],
})
// Wait for sound to be played
await waitFor(() => {
expect(mockPlayFunction).toHaveBeenCalled()
})
})
it("does not play sound when resuming a task from history", () => {
renderChatView()
// Clear any initial calls
mockPlayFunction.mockClear()
// Hydrate state with a task that has a resumeTaskId (indicating it's resumed from history)
mockPostMessage({
resumeTaskId: "task-123",
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Resumed task",
},
{
type: "ask",
ask: "tool",
ts: Date.now(),
text: JSON.stringify({ tool: "readFile", path: "test.txt" }),
},
],
})
// Should not play sound when resuming from history
expect(mockPlayFunction).not.toHaveBeenCalled()
})
it("does not play sound when resuming a completed task from history", () => {
renderChatView()
// Clear any initial calls
mockPlayFunction.mockClear()
// Hydrate state with a completed task that has a resumeTaskId
mockPostMessage({
resumeTaskId: "task-123",
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Resumed task",
},
{
type: "ask",
ask: "completion_result",
ts: Date.now(),
text: "Task completed",
},
],
})
// Should not play sound for completion when resuming from history
expect(mockPlayFunction).not.toHaveBeenCalled()
})
})
describe("ChatView - Focus Grabbing Tests", () => {
beforeEach(() => vi.clearAllMocks())
it("does not grab focus when follow-up question presented", async () => {
const { getByTestId } = renderChatView()
// First hydrate state with initial task
mockPostMessage({
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
],
})
// Wait for the component to fully render and settle before clearing mocks
await waitFor(() => {
expect(getByTestId("chat-textarea")).toBeInTheDocument()
})
// Wait for the debounced focus effect to fire (50ms debounce + buffer for CI variability)
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 100))
})
// Clear any initial calls after state has settled
mockFocus.mockClear()
// Add follow-up question
mockPostMessage({
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "ask",
ask: "followup",
ts: Date.now(),
text: "Should I continue?",
},
],
})
// Wait for state update to complete
await waitFor(() => {
expect(getByTestId("chat-textarea")).toBeInTheDocument()
})
// Should not grab focus for follow-up questions
expect(mockFocus).not.toHaveBeenCalled()
})
})
describe("ChatView - Version Indicator Tests", () => {
beforeEach(() => {
vi.clearAllMocks()
// Reset the mock to return null by default
mockVersionIndicator.mockReturnValue(null)
})
it("displays version indicator button", () => {
// Mock VersionIndicator to return a button
mockVersionIndicator.mockReturnValue(
React.createElement("button", {
"data-testid": "version-indicator",
"aria-label": "Version 1.0.0",
className: "version-indicator-button",
}),
)
const { getByTestId } = renderChatView()
// Hydrate state with no active task
mockPostMessage({
version: "1.0.0",
clineMessages: [],
})
// Should display version indicator
expect(getByTestId("version-indicator")).toBeInTheDocument()
})
it("opens announcement modal when version indicator is clicked", async () => {
// Mock VersionIndicator to return a button with onClick
mockVersionIndicator.mockImplementation(({ onClick }: { onClick?: () => void }) =>
React.createElement("button", {
"data-testid": "version-indicator",
onClick,
}),
)
const { getByTestId, queryByTestId } = renderChatView({ showAnnouncement: false })
// Hydrate state
mockPostMessage({
version: "1.0.0",
clineMessages: [],
})
// Wait for component to render
await waitFor(() => {
expect(getByTestId("version-indicator")).toBeInTheDocument()
})
// Click version indicator
const versionIndicator = getByTestId("version-indicator")
act(() => {
versionIndicator.click()
})
// Wait for announcement modal to appear
await waitFor(() => {
expect(queryByTestId("announcement-modal")).toBeInTheDocument()
})
})
it("version indicator has correct styling classes", () => {
// Mock VersionIndicator to return a button with specific classes
mockVersionIndicator.mockReturnValue(
React.createElement("button", {
"data-testid": "version-indicator",
className: "version-indicator-button absolute top-2 right-2",
}),
)
const { getByTestId } = renderChatView()
// Hydrate state
mockPostMessage({
version: "1.0.0",
clineMessages: [],
})
const versionIndicator = getByTestId("version-indicator")
expect(versionIndicator.className).toContain("version-indicator-button")
expect(versionIndicator.className).toContain("absolute")
expect(versionIndicator.className).toContain("top-2")
expect(versionIndicator.className).toContain("right-2")
})
it("version indicator has proper accessibility attributes", () => {
// Mock VersionIndicator to return a button with aria-label
mockVersionIndicator.mockReturnValue(
React.createElement("button", {
"data-testid": "version-indicator",
"aria-label": "Version 1.0.0",
role: "button",
}),
)
const { getByTestId } = renderChatView()
// Hydrate state
mockPostMessage({
version: "1.0.0",
clineMessages: [],
})
const versionIndicator = getByTestId("version-indicator")
expect(versionIndicator.getAttribute("aria-label")).toBe("Version 1.0.0")
expect(versionIndicator.getAttribute("role")).toBe("button")
})
it("does not display version indicator when there is an active task", () => {
// Mock VersionIndicator to return null (simulating hidden state)
mockVersionIndicator.mockReturnValue(null)
const { queryByTestId } = renderChatView()
// Hydrate state with active task
mockPostMessage({
version: "1.0.0",
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now(),
text: "Active task",
},
],
})
// Should not display version indicator during active task
expect(queryByTestId("version-indicator")).not.toBeInTheDocument()
})
it("displays version indicator only on welcome screen (no task)", () => {
// Mock VersionIndicator to return a button
mockVersionIndicator.mockReturnValue(React.createElement("button", { "data-testid": "version-indicator" }))
const { queryByTestId } = renderChatView()
// Hydrate state with no active task
mockPostMessage({
version: "1.0.0",
clineMessages: [],
})
// Should display version indicator on welcome screen
expect(queryByTestId("version-indicator")).toBeInTheDocument()
})
})
describe("ChatView - Welcome Screen Display Tests", () => {
beforeEach(() => vi.clearAllMocks())
it("shows RooTips on the welcome screen regardless of task history or cloud auth", async () => {
const { getByTestId, queryByTestId } = renderChatView()
mockPostMessage({
cloudIsAuthenticated: false,
taskHistory: [
{ id: "1", ts: Date.now() - 6000 },
{ id: "2", ts: Date.now() - 5000 },
{ id: "3", ts: Date.now() - 4000 },
{ id: "4", ts: Date.now() - 3000 },
{ id: "5", ts: Date.now() - 2000 },
{ id: "6", ts: Date.now() - 1000 },
{ id: "7", ts: Date.now() },
],
clineMessages: [], // No active task
})
await waitFor(() => {
expect(getByTestId("roo-tips")).toBeInTheDocument()
})
expect(queryByTestId("dismissible-upsell")).not.toBeInTheDocument()
})
it("does not show welcome content when there is an active task", async () => {
const { queryByTestId } = renderChatView()
mockPostMessage({
cloudIsAuthenticated: false,
taskHistory: [
{ id: "1", ts: Date.now() - 3000 },
{ id: "2", ts: Date.now() - 2000 },
{ id: "3", ts: Date.now() - 1000 },
{ id: "4", ts: Date.now() },
],
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now(),
text: "Active task",
},
],
})
await waitFor(() => {
expect(queryByTestId("dismissible-upsell")).not.toBeInTheDocument()
expect(queryByTestId("roo-tips")).not.toBeInTheDocument()
expect(queryByTestId("roo-hero")).not.toBeInTheDocument()
})
})
})
describe("ChatView - Message Queueing Tests", () => {
beforeEach(() => {
vi.clearAllMocks()
// Reset the mock to clear any initial calls
vi.mocked(vscode.postMessage).mockClear()
})
it("shows sending is disabled when task is active", async () => {
const { getByTestId } = renderChatView()
// Hydrate state with active task that should disable sending
mockPostMessage({
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 1000,
text: "Task in progress",
},
{
type: "ask",
ask: "tool",
ts: Date.now(),
text: JSON.stringify({ tool: "readFile", path: "test.txt" }),
partial: true, // Partial messages disable sending
},
],
})
// Wait for state to be updated and check that sending is disabled
await waitFor(() => {
const chatTextArea = getByTestId("chat-textarea")
const input = chatTextArea.querySelector("input")!
expect(input.getAttribute("data-sending-disabled")).toBe("true")
})
})
it("shows sending is enabled when no task is active", async () => {
const { getByTestId } = renderChatView()
// Hydrate state with completed task
mockPostMessage({
clineMessages: [
{
type: "ask",
ask: "completion_result",
ts: Date.now(),
text: "Task completed",
partial: false,
},
],
})
// Wait for state to be updated
await waitFor(() => {
expect(getByTestId("chat-textarea")).toBeInTheDocument()
})
// Check that sending is enabled
const chatTextArea = getByTestId("chat-textarea")
const input = chatTextArea.querySelector("input")!
expect(input.getAttribute("data-sending-disabled")).toBe("false")
})
it("queues messages when API request is in progress (spinner visible)", async () => {
const { getByTestId } = renderChatView()
// First hydrate state with initial task
mockPostMessage({
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
],
})
// Clear any initial calls
vi.mocked(vscode.postMessage).mockClear()
// Add api_req_started without cost (spinner state - API request in progress)
mockPostMessage({
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "say",
say: "api_req_started",
ts: Date.now(),
text: JSON.stringify({ apiProtocol: "anthropic" }), // No cost = still streaming
},
],
})
// Wait for state to be updated
await waitFor(() => {
expect(getByTestId("chat-textarea")).toBeInTheDocument()
})
// Clear message calls before simulating user input
vi.mocked(vscode.postMessage).mockClear()
// Simulate user typing and sending a message during the spinner
const chatTextArea = getByTestId("chat-textarea")
const input = chatTextArea.querySelector("input")! as HTMLInputElement
// Trigger message send by simulating typing and Enter key press
await act(async () => {
// Use fireEvent to properly trigger React's onChange handler
fireEvent.change(input, { target: { value: "follow-up question during spinner" } })
// Simulate pressing Enter to send
fireEvent.keyDown(input, { key: "Enter", code: "Enter" })
})
// Verify that the message was queued, not sent as askResponse
await waitFor(() => {
expect(vscode.postMessage).toHaveBeenCalledWith({
type: "queueMessage",
text: "follow-up question during spinner",
images: [],
})
})
// Verify it was NOT sent as a direct askResponse (which would get lost)
expect(vscode.postMessage).not.toHaveBeenCalledWith(
expect.objectContaining({
type: "askResponse",
askResponse: "messageResponse",
}),
)
})
it("sends messages normally when API request is complete (cost present)", async () => {
const { getByTestId } = renderChatView()
// Hydrate state with completed API request (cost present)
mockPostMessage({
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "say",
say: "api_req_started",
ts: Date.now(),
text: JSON.stringify({
apiProtocol: "anthropic",
cost: 0.05, // Cost present = streaming complete
tokensIn: 100,
tokensOut: 50,
}),
},
{
type: "say",
say: "text",
ts: Date.now(),
text: "Response from API",
},
],
})
// Wait for state to be updated
await waitFor(() => {
expect(getByTestId("chat-textarea")).toBeInTheDocument()
})
// Clear message calls before simulating user input
vi.mocked(vscode.postMessage).mockClear()
// Simulate user sending a message when API is done
const chatTextArea = getByTestId("chat-textarea")
const input = chatTextArea.querySelector("input")! as HTMLInputElement
await act(async () => {
// Use fireEvent to properly trigger React's onChange handler
fireEvent.change(input, { target: { value: "follow-up after completion" } })
// Simulate pressing Enter to send
fireEvent.keyDown(input, { key: "Enter", code: "Enter" })
})
// Verify that the message was sent as askResponse, not queued
await waitFor(() => {
expect(vscode.postMessage).toHaveBeenCalledWith({
type: "askResponse",
askResponse: "messageResponse",
text: "follow-up after completion",
images: [],
})
})
// Verify it was NOT queued
expect(vscode.postMessage).not.toHaveBeenCalledWith(
expect.objectContaining({
type: "queueMessage",
}),
)
})
it("preserves message order when messages sent during queue drain", async () => {
const { getByTestId } = renderChatView()
// Hydrate state with API request in progress and existing queue
mockPostMessage({
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "say",
say: "api_req_started",
ts: Date.now(),
text: JSON.stringify({ apiProtocol: "anthropic" }), // No cost = still streaming
},
],
messageQueue: [
{ id: "msg1", text: "queued message 1", images: [] },
{ id: "msg2", text: "queued message 2", images: [] },
],
})
// Wait for state to be updated
await waitFor(() => {
expect(getByTestId("chat-textarea")).toBeInTheDocument()
})
// Clear message calls before simulating user input
vi.mocked(vscode.postMessage).mockClear()
// Simulate user sending a new message while queue has items
const chatTextArea = getByTestId("chat-textarea")
const input = chatTextArea.querySelector("input")! as HTMLInputElement
await act(async () => {
fireEvent.change(input, { target: { value: "message during queue drain" } })
fireEvent.keyDown(input, { key: "Enter", code: "Enter" })
})
// Verify that the new message was queued (not sent directly) to preserve order
await waitFor(() => {