-
Notifications
You must be signed in to change notification settings - Fork 41.9k
Expand file tree
/
Copy pathagentHostChatContribution.test.ts
More file actions
4671 lines (3884 loc) · 214 KB
/
Copy pathagentHostChatContribution.test.ts
File metadata and controls
4671 lines (3884 loc) · 214 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import assert from 'assert';
import { CancellationToken, CancellationTokenSource } from '../../../../../../base/common/cancellation.js';
import { Emitter, Event } from '../../../../../../base/common/event.js';
import { DisposableStore, IReference, toDisposable } from '../../../../../../base/common/lifecycle.js';
import { URI } from '../../../../../../base/common/uri.js';
import { ISettableObservable, observableValue, type IObservable } from '../../../../../../base/common/observable.js';
import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js';
import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js';
import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js';
import { timeout } from '../../../../../../base/common/async.js';
import { Range } from '../../../../../../editor/common/core/range.js';
import { ILogService, NullLogService } from '../../../../../../platform/log/common/log.js';
import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js';
import { IAgentCreateSessionConfig, IAgentHostService, IAgentSessionMetadata, AgentSession } from '../../../../../../platform/agentHost/common/agentService.js';
import { ActionType, isSessionAction, NotificationType, type ActionEnvelope, type IRootConfigChangedAction, type SessionAction, type TerminalAction, type INotification, type IToolCallConfirmedAction, type ITurnStartedAction } from '../../../../../../platform/agentHost/common/state/sessionActions.js';
import type { IStateSnapshot } from '../../../../../../platform/agentHost/common/state/sessionProtocol.js';
import type { CustomizationRef } from '../../../../../../platform/agentHost/common/state/protocol/state.js';
import { SessionInputAnswerState, SessionInputAnswerValueKind, SessionInputQuestionKind, SessionInputResponseKind, SessionLifecycle, SessionStatus, TurnState, ToolCallStatus, ToolCallConfirmationReason, createSessionState, createActiveTurn, ROOT_STATE_URI, PolicyState, ResponsePartKind, StateComponents, buildSubagentSessionUri, ToolResultContentType, MessageAttachmentKind, type SessionState, type SessionSummary, RootState, type ToolCallState, type AgentInfo } from '../../../../../../platform/agentHost/common/state/sessionState.js';
import { CompletionItemKind as AhpCompletionItemKind, type CompletionsParams, type CompletionsResult } from '../../../../../../platform/agentHost/common/state/protocol/commands.js';
import { sessionReducer } from '../../../../../../platform/agentHost/common/state/sessionReducers.js';
import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js';
import { IAuthenticationService } from '../../../../../services/authentication/common/authentication.js';
import { IChatAgentData, IChatAgentImplementation, IChatAgentRequest, IChatAgentService } from '../../../common/participants/chatAgents.js';
import { ChatAgentLocation } from '../../../common/constants.js';
import { ChatRequestQueueKind, ElicitationState, IChatService, IChatMarkdownContent, IChatProgress, IChatTerminalToolInvocationData, IChatToolInputInvocationData, IChatToolInvocation, IChatToolInvocationSerialized, IChatUsage, ToolConfirmKind } from '../../../common/chatService/chatService.js';
import { IChatEditingService } from '../../../common/editing/chatEditingService.js';
import { IMarkdownString } from '../../../../../../base/common/htmlContent.js';
import { ChatSessionStatus, IChatSessionsService, type IChatSessionRequestHistoryItem } from '../../../common/chatSessionsService.js';
import { ILanguageModelsService, type ILanguageModelChatMetadata } from '../../../common/languageModels.js';
import { IProductService } from '../../../../../../platform/product/common/productService.js';
import { IOpenerService } from '../../../../../../platform/opener/common/opener.js';
import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js';
import { IOutputService } from '../../../../../services/output/common/output.js';
import { IWorkspaceContextService } from '../../../../../../platform/workspace/common/workspace.js';
import { AgentHostContribution, AgentHostSessionListController, AgentHostSessionHandler } from '../../../browser/agentSessions/agentHost/agentHostChatContribution.js';
import { AgentHostLanguageModelProvider } from '../../../browser/agentSessions/agentHost/agentHostLanguageModelProvider.js';
import { IFileService } from '../../../../../../platform/files/common/files.js';
import { TestFileService } from '../../../../../test/common/workbenchTestServices.js';
import { ILabelService } from '../../../../../../platform/label/common/label.js';
import { MockLabelService } from '../../../../../services/label/test/common/mockLabelService.js';
import { IAgentHostFileSystemService } from '../../../../../services/agentHost/common/agentHostFileSystemService.js';
import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js';
import { ICustomizationHarnessService } from '../../../common/customizationHarnessService.js';
import { IAgentPluginService } from '../../../common/plugins/agentPluginService.js';
import { IStorageService, InMemoryStorageService } from '../../../../../../platform/storage/common/storage.js';
import { IAgentSubscription } from '../../../../../../platform/agentHost/common/state/agentSubscription.js';
import { ITerminalChatService } from '../../../../terminal/browser/terminal.js';
import { IAgentHostTerminalService } from '../../../../terminal/browser/agentHostTerminalService.js';
import { IAgentHostSessionWorkingDirectoryResolver } from '../../../browser/agentSessions/agentHost/agentHostSessionWorkingDirectoryResolver.js';
import { IAgentHostUntitledProvisionalSessionService } from '../../../browser/agentSessions/agentHost/agentHostUntitledProvisionalSessionService.js';
import { ILanguageModelToolsService } from '../../../common/tools/languageModelToolsService.js';
import { IPromptsService } from '../../../common/promptSyntax/service/promptsService.js';
import { IChatWidgetService } from '../../../browser/chat.js';
import { ChatQuestionCarouselData } from '../../../common/model/chatProgressTypes/chatQuestionCarouselData.js';
import { ChatElicitationRequestPart } from '../../../common/model/chatProgressTypes/chatElicitationRequestPart.js';
import type { IChatModel, IChatPendingRequest, IChatRequestModel } from '../../../common/model/chatModel.js';
// ---- Mock agent host service ------------------------------------------------
class MockAgentHostService extends mock<IAgentHostService>() {
declare readonly _serviceBrand: undefined;
private readonly _onDidAction = new Emitter<ActionEnvelope>();
override readonly onDidAction = this._onDidAction.event;
private readonly _onDidNotification = new Emitter<INotification>();
override readonly onDidNotification = this._onDidNotification.event;
override readonly onAgentHostExit = Event.None;
private readonly _onAgentHostStart = new Emitter<void>();
override readonly onAgentHostStart = this._onAgentHostStart.event;
fireAgentHostStart(): void {
this._onAgentHostStart.fire();
}
private readonly _authenticationPending: ISettableObservable<boolean> = observableValue('authenticationPending', false);
override readonly authenticationPending: IObservable<boolean> = this._authenticationPending;
override setAuthenticationPending(pending: boolean): void {
this._authenticationPending.set(pending, undefined);
}
// Track live subscriptions so fireAction can route to them
private readonly _liveSubscriptions = new Map<string, { state: SessionState; emitter: Emitter<SessionState>; onWillApply: Emitter<ActionEnvelope>; onDidApply: Emitter<ActionEnvelope> }>();
private _nextId = 1;
private readonly _sessions = new Map<string, IAgentSessionMetadata>();
public createSessionCalls: IAgentCreateSessionConfig[] = [];
public disposedSessions: URI[] = [];
public failNextSubscriptionFor = new Set<string>();
public agents = [{ provider: 'copilot' as const, displayName: 'Agent Host - Copilot', description: 'test', requiresAuth: true }];
/**
* If set, the next {@link createSession} call seeds the session summary's
* `workingDirectory` to this URI instead of echoing back
* `config.workingDirectory`. Used to simulate the server resolving the
* working directory to a worktree path that differs from the requested
* directory.
*/
public nextResolvedWorkingDirectory?: URI;
override async listSessions(): Promise<IAgentSessionMetadata[]> {
return [...this._sessions.values()];
}
override async createSession(config?: IAgentCreateSessionConfig): Promise<URI> {
if (config) {
this.createSessionCalls.push(config);
}
const session = config?.session ?? AgentSession.uri('copilot', `sdk-session-${this._nextId++}`);
const id = AgentSession.id(session);
this._sessions.set(id, { session, startTime: Date.now(), modifiedTime: Date.now() });
// Simulate the server's eager active-client claim: if the caller
// provided activeClient, seed the session state so subscribers see it.
if (config?.activeClient) {
const summary: SessionSummary = {
resource: session.toString(),
provider: 'copilot',
title: 'Test',
status: SessionStatus.Idle,
createdAt: Date.now(),
modifiedAt: Date.now(),
workingDirectory: (this.nextResolvedWorkingDirectory ?? config.workingDirectory)?.toString(),
};
const state: SessionState = {
...createSessionState(summary),
lifecycle: SessionLifecycle.Ready,
activeClient: config.activeClient,
};
this.sessionStates.set(session.toString(), state);
}
this.nextResolvedWorkingDirectory = undefined;
return session;
}
override async disposeSession(session: URI): Promise<void> { this.disposedSessions.push(session); }
async shutdown(): Promise<void> { }
override async restartAgentHost(): Promise<void> { }
// Protocol methods
public override readonly clientId = 'test-window-1';
public dispatchedActions: { action: SessionAction | TerminalAction | IRootConfigChangedAction; clientId: string; clientSeq: number }[] = [];
/** Returns dispatched actions filtered to turn-related types only
* (excludes lifecycle actions like activeClientChanged). */
get turnActions() {
return this.dispatchedActions.filter(d => d.action.type === 'session/turnStarted');
}
public sessionStates = new Map<string, SessionState>();
async subscribe(resource: URI): Promise<IStateSnapshot> {
const resourceStr = resource.toString();
const existingState = this.sessionStates.get(resourceStr);
if (existingState) {
return { resource: resourceStr, state: existingState, fromSeq: 0 };
}
// Root state subscription
if (resourceStr === ROOT_STATE_URI) {
return {
resource: resourceStr,
state: {
agents: this.agents.map(a => ({ provider: a.provider, displayName: a.displayName, description: a.description, models: [] })),
activeSessions: 0
},
fromSeq: 0,
};
}
const summary: SessionSummary = {
resource: resourceStr,
provider: 'copilot',
title: 'Test',
status: SessionStatus.Idle,
createdAt: Date.now(),
modifiedAt: Date.now(),
};
return {
resource: resourceStr,
state: { ...createSessionState(summary), lifecycle: SessionLifecycle.Ready },
fromSeq: 0,
};
}
unsubscribe(_resource: URI): void { }
dispatchAction(action: SessionAction | TerminalAction | IRootConfigChangedAction, clientId: string, clientSeq: number): void {
this.dispatchedActions.push({ action, clientId, clientSeq });
}
private _nextSeq = 1;
nextClientSeq(): number {
return this._nextSeq++;
}
private _rootStateValue: RootState | undefined = undefined;
private readonly _rootStateOnDidChange = new Emitter<RootState>();
override readonly rootState: IAgentSubscription<RootState> = (() => {
const onDidChangeEmitter = this._rootStateOnDidChange;
const self = this;
return {
get value() { return self._rootStateValue; },
get verifiedValue() { return self._rootStateValue; },
onDidChange: onDidChangeEmitter.event,
onWillApplyAction: Event.None,
onDidApplyAction: Event.None,
};
})();
/** Test helper: set rootState value and fire onDidChange. */
setRootState(state: RootState): void {
this._rootStateValue = state;
this._rootStateOnDidChange.fire(state);
}
public authenticateCalls: { resource: string; token: string }[] = [];
override async authenticate(params: { resource: string; token: string }): Promise<{ authenticated: boolean }> {
this.authenticateCalls.push({ resource: params.resource, token: params.token });
return { authenticated: true };
}
override getSubscription<T>(_kind: StateComponents, resource: URI): IReference<IAgentSubscription<T>> {
const resourceStr = resource.toString();
const emitter = new Emitter<T>();
const onWillApply = new Emitter<ActionEnvelope>();
const onDidApply = new Emitter<ActionEnvelope>();
if (this.failNextSubscriptionFor.delete(resourceStr)) {
const error = new Error(`Session not found on backend: ${resourceStr}`);
return {
object: {
get value() { return error; },
get verifiedValue() { return undefined; },
onDidChange: emitter.event,
onWillApplyAction: onWillApply.event,
onDidApplyAction: onDidApply.event,
},
dispose: () => {
emitter.dispose();
onWillApply.dispose();
onDidApply.dispose();
},
};
}
// Hydrate synchronously with a default state
const existingState = this.sessionStates.get(resourceStr);
let initialState: SessionState;
if (existingState) {
initialState = existingState;
} else {
const summary: SessionSummary = {
resource: resourceStr,
provider: 'copilot',
title: 'Test',
status: SessionStatus.Idle,
createdAt: Date.now(),
modifiedAt: Date.now(),
};
initialState = { ...createSessionState(summary), lifecycle: SessionLifecycle.Ready };
}
// Register in live subscriptions so fireAction can route to it
const entry = { state: initialState, emitter: emitter as unknown as Emitter<SessionState>, onWillApply, onDidApply };
this._liveSubscriptions.set(resourceStr, entry);
const self = this;
const sub: IAgentSubscription<T> = {
get value() { return self._liveSubscriptions.get(resourceStr)?.state as unknown as T; },
get verifiedValue() { return self._liveSubscriptions.get(resourceStr)?.state as unknown as T; },
onDidChange: emitter.event,
onWillApplyAction: entry.onWillApply.event,
onDidApplyAction: entry.onDidApply.event,
};
return {
object: sub,
dispose: () => {
this._liveSubscriptions.delete(resourceStr);
emitter.dispose();
onWillApply.dispose();
onDidApply.dispose();
},
};
}
override getSubscriptionUnmanaged<T>(_kind: StateComponents, resource: URI): IAgentSubscription<T> | undefined {
const entry = this._liveSubscriptions.get(resource.toString());
if (!entry) {
return undefined;
}
const self = this;
return {
get value() { return self._liveSubscriptions.get(resource.toString())?.state as unknown as T; },
get verifiedValue() { return self._liveSubscriptions.get(resource.toString())?.state as unknown as T; },
onDidChange: entry.emitter.event as unknown as Event<T>,
onWillApplyAction: entry.onWillApply.event,
onDidApplyAction: entry.onDidApply.event,
} satisfies IAgentSubscription<T>;
}
override dispatch(action: SessionAction | TerminalAction | IRootConfigChangedAction): void {
this.dispatchedActions.push({ action, clientId: this.clientId, clientSeq: this._nextSeq++ });
// Apply state-management actions optimistically so state-dependent
// logic (e.g. customization re-dispatch) sees the correct activeClient.
// Turn lifecycle actions (turnStarted, toolCallConfirmed, etc.) are applied
// later via fireAction when the server echoes them back.
if (isSessionAction(action) && action.type === 'session/activeClientChanged') {
const entry = this._liveSubscriptions.get(action.session);
if (entry) {
const noop = () => { };
entry.state = sessionReducer(entry.state, action as Parameters<typeof sessionReducer>[1], noop);
entry.emitter.fire(entry.state);
}
}
}
// Test helpers
fireAction(envelope: ActionEnvelope): void {
this._onDidAction.fire(envelope);
// Route action to matching live subscriptions
if (isSessionAction(envelope.action)) {
const sessionUri = envelope.action.session;
const entry = this._liveSubscriptions.get(sessionUri);
if (entry) {
const noop = () => { };
entry.onWillApply.fire(envelope);
entry.state = sessionReducer(entry.state, envelope.action as Parameters<typeof sessionReducer>[1], noop);
entry.emitter.fire(entry.state);
entry.onDidApply.fire(envelope);
}
}
}
fireNotification(notification: INotification): void {
this._onDidNotification.fire(notification);
}
addSession(meta: IAgentSessionMetadata): void {
this._sessions.set(AgentSession.id(meta.session), meta);
}
dispose(): void {
this._onDidAction.dispose();
this._onDidNotification.dispose();
this._rootStateOnDidChange.dispose();
}
}
// ---- Minimal service mocks --------------------------------------------------
class MockChatAgentService extends mock<IChatAgentService>() {
declare readonly _serviceBrand: undefined;
registeredAgents = new Map<string, { data: IChatAgentData; impl: IChatAgentImplementation }>();
override registerDynamicAgent(data: IChatAgentData, agentImpl: IChatAgentImplementation) {
this.registeredAgents.set(data.id, { data, impl: agentImpl });
return toDisposable(() => this.registeredAgents.delete(data.id));
}
}
class MockChatWidgetService extends mock<IChatWidgetService>() {
declare readonly _serviceBrand: undefined;
readonly clearQuestionCarouselCalls: { sessionResource: URI; responseId: string | undefined; resolveId: string | undefined }[] = [];
private readonly _widgets = new Map<string, ReturnType<IChatWidgetService['getWidgetBySessionResource']>>();
setWidgetForSession(sessionResource: URI): void {
// eslint-disable-next-line local/code-no-any-casts
this._widgets.set(sessionResource.toString(), {
input: {
clearQuestionCarousel: (responseId?: string, resolveId?: string) => {
this.clearQuestionCarouselCalls.push({ sessionResource, responseId, resolveId });
},
},
} as any);
}
override getWidgetBySessionResource(sessionResource: URI): ReturnType<IChatWidgetService['getWidgetBySessionResource']> {
return this._widgets.get(sessionResource.toString());
}
}
// ---- Helpers ----------------------------------------------------------------
function createTestServices(disposables: DisposableStore, workingDirectoryResolver?: { resolve(sessionResource: URI): URI | undefined; isNewSession?: (sessionResource: URI) => boolean }, authServiceOverride?: Partial<IAuthenticationService>, languageModels?: ReadonlyMap<string, ILanguageModelChatMetadata>, provisionalServiceOverride?: Partial<IAgentHostUntitledProvisionalSessionService>) {
const instantiationService = disposables.add(new TestInstantiationService());
const agentHostService = new MockAgentHostService();
disposables.add(toDisposable(() => agentHostService.dispose()));
const chatAgentService = new MockChatAgentService();
const chatWidgetService = new MockChatWidgetService();
const openerService: { openedUrls: (string | URI)[]; openShouldFail: boolean; openResult: boolean } & Partial<IOpenerService> = {
openedUrls: [],
openShouldFail: false,
openResult: true,
async open(target: string | URI) {
this.openedUrls.push(target);
if (this.openShouldFail) {
throw new Error('open failed');
}
return this.openResult;
},
};
instantiationService.stub(IAgentHostService, agentHostService);
instantiationService.stub(ILogService, new NullLogService());
instantiationService.stub(IProductService, { quality: 'insider' });
instantiationService.stub(IChatAgentService, chatAgentService);
instantiationService.stub(IChatWidgetService, chatWidgetService);
instantiationService.stub(IFileService, TestFileService);
instantiationService.stub(ILabelService, MockLabelService);
instantiationService.stub(IChatSessionsService, {
registerChatSessionItemController: () => toDisposable(() => { }),
registerChatSessionContentProvider: () => toDisposable(() => { }),
registerChatSessionContribution: () => toDisposable(() => { }),
});
instantiationService.stub(IDefaultAccountService, { onDidChangeDefaultAccount: Event.None, getDefaultAccount: async () => null });
instantiationService.stub(IAuthenticationService, { onDidChangeSessions: Event.None, ...authServiceOverride });
instantiationService.stub(ILanguageModelsService, {
deltaLanguageModelChatProviderDescriptors: () => { },
registerLanguageModelProvider: () => toDisposable(() => { }),
lookupLanguageModel: (modelId: string) => languageModels?.get(modelId),
});
instantiationService.stub(IConfigurationService, {
onDidChangeConfiguration: Event.None,
getValue: (...args: any[]) => typeof args[0] === 'string' && args[0] === 'chat.agentHost.clientTools' ? [] : true,
});
instantiationService.stub(ILanguageModelToolsService, {
observeTools: () => observableValue('tools', []),
onDidChangeTools: Event.None,
getTools: () => [],
_serviceBrand: undefined,
});
instantiationService.stub(IOutputService, { getChannel: () => undefined });
instantiationService.stub(IWorkspaceContextService, { getWorkspace: () => ({ id: '', folders: [] }), getWorkspaceFolder: () => null });
instantiationService.stub(IChatEditingService, {
registerEditingSessionProvider: () => toDisposable(() => { }),
});
const chatModels = new Map<string, IChatModel>();
const onDidCreateModel = disposables.add(new Emitter<IChatModel>());
const chatService = {
getSession: (sessionResource: URI) => chatModels.get(sessionResource.toString()),
onDidCreateModel: onDidCreateModel.event,
setSession(sessionResource: URI, model: IChatModel) {
chatModels.set(sessionResource.toString(), model);
onDidCreateModel.fire(model);
},
removePendingRequestCalls: [] as { sessionResource: URI; requestId: string }[],
removePendingRequest(sessionResource: URI, requestId: string) {
this.removePendingRequestCalls.push({ sessionResource, requestId });
},
};
instantiationService.stub(IChatService, chatService);
instantiationService.stub(IAgentHostFileSystemService, {
registerAuthority: () => toDisposable(() => { }),
ensureSyncedCustomizationProvider: () => { },
});
instantiationService.stub(IStorageService, disposables.add(new InMemoryStorageService()));
instantiationService.stub(ICustomizationHarnessService, {
registerExternalHarness: () => toDisposable(() => { }),
});
instantiationService.stub(IAgentPluginService, {
plugins: observableValue('plugins', []),
});
instantiationService.stub(IPromptsService, new class extends mock<IPromptsService>() {
override readonly onDidChangeCustomAgents = Event.None;
override readonly onDidChangeSlashCommands = Event.None;
override readonly onDidChangeSkills = Event.None;
override readonly onDidChangeInstructions = Event.None;
override async listPromptFilesForStorage() {
return [];
}
}());
instantiationService.stub(ITerminalChatService, {
onDidContinueInBackground: Event.None,
registerTerminalInstanceWithToolSession: () => { },
getAhpCommandSource: () => undefined,
});
instantiationService.stub(IAgentHostTerminalService, {
reviveTerminal: async () => undefined!,
createTerminalForEntry: async () => undefined,
profiles: observableValue('test', []),
getProfileForConnection: () => undefined,
registerEntry: () => ({ dispose() { } }),
});
instantiationService.stub(IAgentHostSessionWorkingDirectoryResolver, {
registerResolver: () => toDisposable(() => { }),
resolve: sessionResource => workingDirectoryResolver?.resolve(sessionResource),
isNewSession: sessionResource => workingDirectoryResolver?.isNewSession?.(sessionResource) ?? sessionResource.path.substring(1).startsWith('new-'),
});
instantiationService.stub(IWorkbenchEnvironmentService, { isSessionsWindow: false } as Partial<IWorkbenchEnvironmentService>);
instantiationService.stub(IAgentHostUntitledProvisionalSessionService, {
onDidChange: Event.None,
get: () => undefined,
waitForPending: async () => undefined,
getOrCreate: async () => undefined,
tryRebind: async () => undefined,
disposeSession: async () => { },
...provisionalServiceOverride,
} as Partial<IAgentHostUntitledProvisionalSessionService> as IAgentHostUntitledProvisionalSessionService);
instantiationService.stub(IOpenerService, openerService as IOpenerService);
return { instantiationService, agentHostService, chatAgentService, chatWidgetService, chatService, openerService };
}
function createContribution(disposables: DisposableStore, opts?: { authServiceOverride?: Partial<IAuthenticationService>; workingDirectoryResolver?: { resolve(sessionResource: URI): URI | undefined; isNewSession?: (sessionResource: URI) => boolean }; languageModels?: ReadonlyMap<string, ILanguageModelChatMetadata>; provisionalServiceOverride?: Partial<IAgentHostUntitledProvisionalSessionService> }) {
const { instantiationService, agentHostService, chatAgentService, chatWidgetService, chatService, openerService } = createTestServices(disposables, opts?.workingDirectoryResolver, opts?.authServiceOverride, opts?.languageModels, opts?.provisionalServiceOverride);
const listController = disposables.add(instantiationService.createInstance(AgentHostSessionListController, 'agent-host-copilot', 'copilot', agentHostService, undefined, 'local'));
const sessionHandler = disposables.add(instantiationService.createInstance(AgentHostSessionHandler, {
provider: 'copilot' as const,
agentId: 'agent-host-copilot',
sessionType: 'agent-host-copilot',
fullName: 'Agent Host - Copilot',
description: 'Copilot SDK agent running in a dedicated process',
connection: agentHostService,
connectionAuthority: 'local',
isNewSession: sessionResource => listController.isNewSession(sessionResource),
}));
const contribution = disposables.add(instantiationService.createInstance(AgentHostContribution));
return { contribution, listController, sessionHandler, agentHostService, chatAgentService, chatWidgetService, chatService, instantiationService, openerService };
}
function makeRequest(overrides: Partial<{ message: string; sessionResource: URI; variables: IChatAgentRequest['variables']; userSelectedModelId: string; modelConfiguration: Record<string, unknown>; agentHostSessionConfig: Record<string, string>; agentId: string }> = {}): IChatAgentRequest {
return upcastPartial<IChatAgentRequest>({
sessionResource: overrides.sessionResource ?? URI.from({ scheme: 'untitled', path: '/chat-1' }),
requestId: 'req-1',
agentId: overrides.agentId ?? 'agent-host-copilot',
message: overrides.message ?? 'Hello',
variables: overrides.variables ?? { variables: [] },
location: ChatAgentLocation.Chat,
userSelectedModelId: overrides.userSelectedModelId,
modelConfiguration: overrides.modelConfiguration,
agentHostSessionConfig: overrides.agentHostSessionConfig,
});
}
/** Extract the text value from a string or IMarkdownString. */
function textOf(value: string | IMarkdownString | undefined): string | undefined {
if (value === undefined) {
return undefined;
}
return typeof value === 'string' ? value : value.value;
}
/**
* Start a turn through the state-driven flow. Creates a chat session,
* invokes the agent (non-blocking), and waits for the first action
* to be dispatched. Returns helpers to fire server action envelopes.
*/
async function startTurn(
sessionHandler: AgentHostSessionHandler,
agentHostService: MockAgentHostService,
chatAgentService: MockChatAgentService,
ds: DisposableStore,
overrides?: Partial<{
message: string;
sessionResource: URI;
variables: IChatAgentRequest['variables'];
userSelectedModelId: string;
modelConfiguration: Record<string, unknown>;
agentHostSessionConfig: Record<string, string>;
cancellationToken: CancellationToken;
agentId: string;
}>,
) {
const agentId = overrides?.agentId ?? 'agent-host-copilot';
const sessionResource = overrides?.sessionResource ?? URI.from({ scheme: agentId, path: '/new-turntest' });
const chatSession = await sessionHandler.provideChatSessionContent(sessionResource, CancellationToken.None);
ds.add(toDisposable(() => chatSession.dispose()));
// Clear any lifecycle actions (e.g. activeClientChanged from customization setup)
// so tests only see turn-related dispatches.
agentHostService.dispatchedActions.length = 0;
const collected: IChatProgress[][] = [];
const seq = { v: 1 };
const registered = chatAgentService.registeredAgents.get(agentId);
assert.ok(registered, `${agentId} agent should be registered`);
const turnPromise = registered.impl.invoke(
makeRequest({
message: overrides?.message ?? 'Hello',
sessionResource,
variables: overrides?.variables,
userSelectedModelId: overrides?.userSelectedModelId,
modelConfiguration: overrides?.modelConfiguration,
agentHostSessionConfig: overrides?.agentHostSessionConfig,
agentId,
}),
(parts) => collected.push(parts),
[],
overrides?.cancellationToken ?? CancellationToken.None,
);
await timeout(10);
// Filter for turn-related dispatches only (skip activeClientChanged etc.)
const turnDispatches = agentHostService.dispatchedActions.filter(d => d.action.type === 'session/turnStarted');
const lastDispatch = turnDispatches[turnDispatches.length - 1] ?? agentHostService.dispatchedActions[agentHostService.dispatchedActions.length - 1];
const session = (lastDispatch?.action as ITurnStartedAction)?.session;
const turnId = (lastDispatch?.action as ITurnStartedAction)?.turnId;
const fire = (action: SessionAction) => {
agentHostService.fireAction({ action, serverSeq: seq.v++, origin: undefined });
};
// Echo the turnStarted action to clear the pending write-ahead entry.
// Without this, the optimistic state replay would re-add activeTurn after
// the server's turnComplete clears it, preventing the turn from finishing.
if (lastDispatch) {
agentHostService.fireAction({
action: lastDispatch.action,
serverSeq: seq.v++,
origin: { clientId: agentHostService.clientId, clientSeq: lastDispatch.clientSeq },
});
}
return { turnPromise, collected, chatSession, session, turnId, fire };
}
async function startDynamicAgentTurn(
chatAgentService: MockChatAgentService,
agentHostService: MockAgentHostService,
agentId: string,
overrides?: Partial<{
message: string;
sessionResource: URI;
variables: IChatAgentRequest['variables'];
userSelectedModelId: string;
agentHostSessionConfig: Record<string, string>;
cancellationToken: CancellationToken;
}>,
) {
const registered = chatAgentService.registeredAgents.get(agentId);
assert.ok(registered);
const sessionResource = overrides?.sessionResource ?? URI.from({ scheme: agentId, path: '/new-turntest' });
const collected: IChatProgress[][] = [];
const seq = { v: 1 };
agentHostService.dispatchedActions.length = 0;
const turnPromise = registered.impl.invoke(
makeRequest({
message: overrides?.message ?? 'Hello',
sessionResource,
variables: overrides?.variables,
userSelectedModelId: overrides?.userSelectedModelId,
agentHostSessionConfig: overrides?.agentHostSessionConfig,
agentId,
}),
parts => collected.push(parts),
[],
overrides?.cancellationToken ?? CancellationToken.None,
);
await timeout(10);
const turnDispatches = agentHostService.dispatchedActions.filter(d => d.action.type === 'session/turnStarted');
const lastDispatch = turnDispatches[turnDispatches.length - 1] ?? agentHostService.dispatchedActions[agentHostService.dispatchedActions.length - 1];
const session = (lastDispatch?.action as ITurnStartedAction)?.session;
const turnId = (lastDispatch?.action as ITurnStartedAction)?.turnId;
const fire = (action: SessionAction) => {
agentHostService.fireAction({ action, serverSeq: seq.v++, origin: undefined });
};
if (lastDispatch) {
agentHostService.fireAction({
action: lastDispatch.action,
serverSeq: seq.v++,
origin: { clientId: agentHostService.clientId, clientSeq: lastDispatch.clientSeq },
});
}
return { turnPromise, collected, session, turnId, fire };
}
suite('AgentHostChatContribution', () => {
const disposables = new DisposableStore();
teardown(() => disposables.clear());
ensureNoDisposablesAreLeakedInTestSuite();
// ---- Registration ---------------------------------------------------
suite('registration', () => {
test('registers agent', () => {
const { chatAgentService } = createContribution(disposables);
assert.ok(chatAgentService.registeredAgents.has('agent-host-copilot'));
});
});
// ---- Session disposal -----------------------------------------------
suite('disposal', () => {
test('fires onWillDispose before session is disposed', async () => {
const { sessionHandler } = createContribution(disposables);
const sessionResource = URI.from({ scheme: 'agent-host-copilot', path: '/dispose-test' });
const chatSession = await sessionHandler.provideChatSessionContent(sessionResource, CancellationToken.None);
// `onWillDispose` is consumed by `ContributedChatSessionData` in
// `ChatSessionsService` to evict disposed sessions from its cache.
// If this event does not fire (e.g. because the emitter was
// disposed before `.fire()` ran during teardown), the service
// would hand out the disposed `IChatSession` to subsequent
// `getOrCreateChatSession` callers.
let fired = 0;
disposables.add(chatSession.onWillDispose(() => { fired++; }));
chatSession.dispose();
assert.strictEqual(fired, 1, 'onWillDispose should fire exactly once when the session is disposed');
});
});
// ---- Session list (IChatSessionItemController) ----------------------
suite('session list', () => {
test('refresh populates items from agent host', async () => {
const { listController, agentHostService } = createContribution(disposables);
agentHostService.addSession({ session: AgentSession.uri('copilot', 'aaa'), startTime: 1000, modifiedTime: 2000, summary: 'My session' });
agentHostService.addSession({ session: AgentSession.uri('copilot', 'bbb'), startTime: 3000, modifiedTime: 4000 });
await listController.refresh(CancellationToken.None);
assert.strictEqual(listController.items.length, 2);
assert.strictEqual(listController.items[0].label, 'My session');
assert.strictEqual(listController.items[1].label, 'Session bbb');
assert.strictEqual(listController.items[0].resource.scheme, 'agent-host-copilot');
assert.strictEqual(listController.items[0].resource.path, '/aaa');
});
test('refresh fires onDidChangeChatSessionItems', async () => {
const { listController, agentHostService } = createContribution(disposables);
let fired = false;
disposables.add(listController.onDidChangeChatSessionItems(() => { fired = true; }));
agentHostService.addSession({ session: AgentSession.uri('copilot', 'x'), startTime: 1000, modifiedTime: 2000 });
await listController.refresh(CancellationToken.None);
assert.ok(fired);
});
test('refresh handles error gracefully', async () => {
const { listController, agentHostService } = createContribution(disposables);
agentHostService.listSessions = async () => { throw new Error('fail'); };
await listController.refresh(CancellationToken.None);
assert.strictEqual(listController.items.length, 0);
});
test('refresh marks archived sessions as archived items', async () => {
const { listController, agentHostService } = createContribution(disposables);
agentHostService.addSession({
session: AgentSession.uri('copilot', 'archived'),
startTime: 1000,
modifiedTime: 2000,
summary: 'Archived session',
isArchived: true,
});
await listController.refresh(CancellationToken.None);
assert.strictEqual(listController.items.length, 1);
assert.strictEqual(listController.items[0].archived, true);
});
test('refresh skips listSessions RPC after first successful call', async () => {
const { listController, agentHostService } = createContribution(disposables);
agentHostService.addSession({ session: AgentSession.uri('copilot', 'aaa'), startTime: 1000, modifiedTime: 2000, summary: 'My session' });
let listCalls = 0;
const originalListSessions = agentHostService.listSessions.bind(agentHostService);
agentHostService.listSessions = async () => { listCalls++; return originalListSessions(); };
await listController.refresh(CancellationToken.None);
assert.strictEqual(listCalls, 1);
assert.strictEqual(listController.items.length, 1);
// Subsequent refresh should not re-fetch — the cache is kept in
// sync via notify/sessionAdded etc.
await listController.refresh(CancellationToken.None);
await listController.refresh(CancellationToken.None);
assert.strictEqual(listCalls, 1);
assert.strictEqual(listController.items.length, 1);
});
test('refresh retries listSessions if the first call failed', async () => {
const { listController, agentHostService } = createContribution(disposables);
let listCalls = 0;
const originalListSessions = agentHostService.listSessions.bind(agentHostService);
agentHostService.listSessions = async () => {
listCalls++;
if (listCalls === 1) {
throw new Error('fail');
}
return originalListSessions();
};
agentHostService.addSession({ session: AgentSession.uri('copilot', 'aaa'), startTime: 1000, modifiedTime: 2000, summary: 'My session' });
await listController.refresh(CancellationToken.None);
assert.strictEqual(listCalls, 1);
assert.strictEqual(listController.items.length, 0);
// Failure must not mark the cache valid; the next refresh retries.
await listController.refresh(CancellationToken.None);
assert.strictEqual(listCalls, 2);
assert.strictEqual(listController.items.length, 1);
});
test('agent host restart invalidates cache so next refresh re-fetches', async () => {
const { listController, agentHostService } = createContribution(disposables);
agentHostService.addSession({ session: AgentSession.uri('copilot', 'aaa'), startTime: 1000, modifiedTime: 2000, summary: 'Before restart' });
let listCalls = 0;
const originalListSessions = agentHostService.listSessions.bind(agentHostService);
agentHostService.listSessions = async () => { listCalls++; return originalListSessions(); };
await listController.refresh(CancellationToken.None);
assert.strictEqual(listCalls, 1);
// Subsequent refresh uses cache — no new RPC.
await listController.refresh(CancellationToken.None);
assert.strictEqual(listCalls, 1);
// Directly resetting the cache (as onAgentHostStart does) must cause
// the next refresh to re-fetch.
listController.resetCache();
await listController.refresh(CancellationToken.None);
assert.strictEqual(listCalls, 2);
});
test('newChatSessionItem creates final-looking resource used for requested backend session', () => runWithFakedTimers({ useFakeTimers: true }, async () => {
const { listController, sessionHandler, agentHostService, chatAgentService } = createContribution(disposables);
const item = await listController.newChatSessionItem({ prompt: 'Hello from controller' }, CancellationToken.None);
assert.ok(item);
assert.strictEqual(item.resource.scheme, 'agent-host-copilot');
assert.ok(!item.resource.path.substring(1).startsWith('untitled-'));
assert.strictEqual(listController.isNewSession(item.resource), true);
assert.deepStrictEqual(listController.items.map(item => ({ resource: item.resource.toString(), status: item.status })), [{
resource: item.resource.toString(),
status: ChatSessionStatus.InProgress,
}]);
const { turnPromise, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, {
message: 'Hello from controller',
sessionResource: item.resource,
});
const visibleItem = listController.items.find(existing => existing.resource.toString() === item.resource.toString());
assert.ok(visibleItem);
assert.strictEqual(visibleItem.status, ChatSessionStatus.InProgress);
fire({ type: 'session/turnComplete', session, turnId } as SessionAction);
await turnPromise;
assert.strictEqual(agentHostService.createSessionCalls.length, 1);
assert.strictEqual(agentHostService.createSessionCalls[0].session?.toString(), AgentSession.uri('copilot', item.resource.path.substring(1)).toString());
await listController.refresh(CancellationToken.None);
assert.strictEqual(listController.isNewSession(item.resource), false);
assert.strictEqual(listController.items.some(existing => existing.resource.toString() === item.resource.toString()), true);
}));
test('pending new session stays visible across refresh before backend listing', async () => {
const { listController } = createContribution(disposables);
const item = await listController.newChatSessionItem({ prompt: 'Hello from controller' }, CancellationToken.None);
assert.ok(item);
assert.deepStrictEqual(listController.items.map(item => ({ resource: item.resource.toString(), status: item.status })), [{
resource: item.resource.toString(),
status: ChatSessionStatus.InProgress,
}]);
await listController.refresh(CancellationToken.None);
assert.deepStrictEqual(listController.items.map(item => ({ resource: item.resource.toString(), status: item.status })), [{
resource: item.resource.toString(),
status: ChatSessionStatus.InProgress,
}]);
});
test('pending new session stays in progress when refresh sees an idle backend session', async () => {
const { listController, agentHostService } = createContribution(disposables);
const item = await listController.newChatSessionItem({ prompt: 'Hello from controller' }, CancellationToken.None);
assert.ok(item);
const rawId = item.resource.path.substring(1);
agentHostService.addSession({
session: AgentSession.uri('copilot', rawId),
startTime: 1,
modifiedTime: 2,
summary: 'Backend session',
status: SessionStatus.Idle,
});
await listController.refresh(CancellationToken.None);
assert.deepStrictEqual(listController.items.map(item => ({ resource: item.resource.toString(), label: item.label, status: item.status })), [{
resource: item.resource.toString(),
label: 'Backend session',
status: ChatSessionStatus.InProgress,
}]);
assert.strictEqual(listController.isNewSession(item.resource), false);
});
test('pending new session stays in progress when first backend summary is idle', async () => {
const { listController, agentHostService } = createContribution(disposables);
const item = await listController.newChatSessionItem({ prompt: 'Hello from controller' }, CancellationToken.None);
assert.ok(item);
const rawId = item.resource.path.substring(1);
agentHostService.fireNotification({
type: NotificationType.SessionAdded,
summary: {
resource: AgentSession.uri('copilot', rawId).toString(),
provider: 'copilot',
title: 'Backend session',
status: SessionStatus.Idle,
createdAt: 1,
modifiedAt: 2,
}
});
assert.deepStrictEqual(listController.items.map(item => ({ resource: item.resource.toString(), label: item.label, status: item.status })), [{
resource: item.resource.toString(),
label: 'Backend session',
status: ChatSessionStatus.InProgress,
}]);
assert.strictEqual(listController.isNewSession(item.resource), false);
});
test('newChatSessionItem rebinds untitled provisional to real resource so chip-selected config survives first send', () => runWithFakedTimers({ useFakeTimers: true }, async () => {
const { instantiationService, agentHostService } = createTestServices(disposables);
const workspaceFolder = URI.from({ scheme: 'file', path: '/workspace/root' });
instantiationService.stub(IWorkspaceContextService, {
getWorkspace: () => ({ id: '', folders: [{ uri: workspaceFolder, name: 'root', index: 0, toResource: () => workspaceFolder }] }),
getWorkspaceFolder: () => null,
});
const rebindCalls: { oldResource: URI; newResource: URI; provider: string; workingDirectory: URI | undefined }[] = [];
instantiationService.stub(IAgentHostUntitledProvisionalSessionService, {
onDidChange: Event.None,
get: () => undefined,
waitForPending: async () => undefined,
getOrCreate: async () => undefined,
tryRebind: async (oldResource: URI, newResource: URI, provider: string, workingDirectory: URI | undefined) => {
rebindCalls.push({ oldResource, newResource, provider, workingDirectory });
return newResource;
},
disposeSession: async () => { },
} as Partial<IAgentHostUntitledProvisionalSessionService> as IAgentHostUntitledProvisionalSessionService);
const listController = disposables.add(instantiationService.createInstance(AgentHostSessionListController, 'agent-host-copilot', 'copilot', agentHostService, undefined, 'local'));
const untitledResource = URI.from({ scheme: 'agent-host-copilot', path: '/untitled-abc' });
const item = await listController.newChatSessionItem({ prompt: 'Hello', untitledResource }, CancellationToken.None);
assert.ok(item);
assert.deepStrictEqual(rebindCalls, [{
oldResource: untitledResource,
newResource: item.resource,
provider: 'copilot',
workingDirectory: workspaceFolder,
}]);
}));
test('newChatSessionItem skips rebind when no untitled provisional resource is provided', () => runWithFakedTimers({ useFakeTimers: true }, async () => {
const { instantiationService, agentHostService } = createTestServices(disposables);
let rebindCalls = 0;
instantiationService.stub(IAgentHostUntitledProvisionalSessionService, {
onDidChange: Event.None,
get: () => undefined,
waitForPending: async () => undefined,
getOrCreate: async () => undefined,
tryRebind: async () => { rebindCalls++; return undefined; },
disposeSession: async () => { },
} as Partial<IAgentHostUntitledProvisionalSessionService> as IAgentHostUntitledProvisionalSessionService);