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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { RemoteSessionInvocation } from './remote-session-invocation.js';
import { RemoteSubagentSession } from './remote-subagent-protocol.js';
import {
  type RemoteAgentDefinition,
  type SubagentProgress,
  SubagentState,
} from './types.js';
import { createMockMessageBus } from '../test-utils/mock-message-bus.js';
import type { AgentLoopContext } from '../config/agent-loop-context.js';
import type { Config } from '../config/config.js';
import type { ToolResult } from '../tools/tools.js';
import type { AgentEvent } from '../agent/types.js';

vi.mock('./remote-subagent-protocol.js');

const mockDefinition: RemoteAgentDefinition = {
  name: 'test-agent',
  kind: 'remote',
  agentCardUrl: 'http://test-agent/card',
  displayName: 'Test Agent',
  description: 'A test agent',
  inputConfig: { inputSchema: { type: 'object' } },
};

const mockMessageBus = createMockMessageBus();

interface MockSessionSetupOptions {
  result?: ToolResult;
  error?: Error;
  progress?: SubagentProgress;
  sessionState?: { contextId?: string; taskId?: string };
}

function setupMockSession(options: MockSessionSetupOptions = {}) {
  const {
    result = {
      llmContent: [{ text: 'done' }],
      returnDisplay: {
        isSubagentProgress: true,
        agentName: 'Test Agent',
        state: SubagentState.COMPLETED,
        result: 'done',
        recentActivity: [],
      } satisfies SubagentProgress,
    },
    error,
    progress,
    sessionState = {},
  } = options;

  const subscriberCallbacks: Array<(event: AgentEvent) => void> = [];

  const mockSession = {
    send: vi.fn().mockResolvedValue({ streamId: 'stream-1' }),
    getResult: error
      ? vi.fn().mockRejectedValue(error)
      : vi.fn().mockResolvedValue(result),
    getLatestProgress: vi.fn().mockReturnValue(progress),
    getSessionState: vi.fn().mockReturnValue(sessionState),
    subscribe: vi.fn((cb: (event: AgentEvent) => void) => {
      subscriberCallbacks.push(cb);
      return vi.fn(); // unsubscribe
    }),
    abort: vi.fn(),
  };

  vi.mocked(RemoteSubagentSession).mockImplementation(
    () => mockSession as unknown as RemoteSubagentSession,
  );

  return {
    mockSession,
    subscriberCallbacks,
    /** Fire a message event through all subscribed callbacks. */
    emitEvent(event: AgentEvent) {
      for (const cb of subscriberCallbacks) {
        cb(event);
      }
    },
  };
}

describe('RemoteSessionInvocation', () => {
  let mockContext: AgentLoopContext;

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

    const mockConfig = {
      getA2AClientManager: vi.fn().mockReturnValue({}),
      injectionService: {
        getLatestInjectionIndex: vi.fn().mockReturnValue(0),
      },
    } as unknown as Config;

    mockContext = { config: mockConfig } as unknown as AgentLoopContext;

    // Clear the static sessionState map between tests
    (
      RemoteSessionInvocation as unknown as {
        sessionState?: Map<string, unknown>;
      }
    ).sessionState?.clear();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  // ---------------------------------------------------------------------------
  // Constructor Validation
  // ---------------------------------------------------------------------------

  describe('Constructor Validation', () => {
    it('accepts valid input with string query', () => {
      expect(() => {
        new RemoteSessionInvocation(
          mockDefinition,
          mockContext,
          { query: 'hello' },
          mockMessageBus,
        );
      }).not.toThrow();
    });

    it('accepts missing query (defaults to "Get Started!")', () => {
      expect(() => {
        new RemoteSessionInvocation(
          mockDefinition,
          mockContext,
          {},
          mockMessageBus,
        );
      }).not.toThrow();
    });

    it('throws if query is not a string', () => {
      expect(() => {
        new RemoteSessionInvocation(
          mockDefinition,
          mockContext,
          { query: 123 },
          mockMessageBus,
        );
      }).toThrow("requires a string 'query' input");
    });

    it('throws if A2AClientManager is not available', () => {
      const noA2AConfig = {
        getA2AClientManager: vi.fn().mockReturnValue(undefined),
        injectionService: {
          getLatestInjectionIndex: vi.fn().mockReturnValue(0),
        },
      } as unknown as Config;
      const noA2AContext = {
        config: noA2AConfig,
      } as unknown as AgentLoopContext;

      expect(() => {
        new RemoteSessionInvocation(
          mockDefinition,
          noA2AContext,
          { query: 'hi' },
          mockMessageBus,
        );
      }).toThrow('A2AClientManager is not available');
    });
  });

  // ---------------------------------------------------------------------------
  // Execution Logic
  // ---------------------------------------------------------------------------

  describe('Execution Logic', () => {
    it('should create session and return result', async () => {
      const completedProgress: SubagentProgress = {
        isSubagentProgress: true,
        agentName: 'Test Agent',
        state: SubagentState.COMPLETED,
        result: 'Agent output',
        recentActivity: [],
      };
      const expectedResult: ToolResult = {
        llmContent: [{ text: 'Agent output' }],
        returnDisplay: completedProgress,
      };

      setupMockSession({
        result: expectedResult,
        progress: completedProgress,
      });

      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'do stuff' },
        mockMessageBus,
      );

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(RemoteSubagentSession).toHaveBeenCalledOnce();
      expect(result).toBe(expectedResult);
    });

    it('should pass initial state from static map to session', async () => {
      const priorState = { contextId: 'ctx-42', taskId: 'task-42' };

      // Seed the static map before constructing the invocation
      (
        RemoteSessionInvocation as unknown as {
          sessionState: Map<string, unknown>;
        }
      ).sessionState.set('test-agent::http://test-agent/card', priorState);

      setupMockSession();

      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );
      await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      // Verify the session constructor received the prior state
      expect(RemoteSubagentSession).toHaveBeenCalledWith(
        mockDefinition,
        mockContext,
        mockMessageBus,
        priorState,
      );
    });

    it('should persist session state in finally block', async () => {
      const newState = { contextId: 'ctx-new', taskId: 'task-new' };
      setupMockSession({ sessionState: newState });

      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );
      await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      // Verify the state was persisted in the static map
      const storedState = (
        RemoteSessionInvocation as unknown as {
          sessionState: Map<string, { contextId?: string; taskId?: string }>;
        }
      ).sessionState.get('test-agent::http://test-agent/card');
      expect(storedState).toEqual(newState);
    });

    it('should persist session state across invocations', async () => {
      // First invocation returns state
      const firstState = { contextId: 'ctx-1', taskId: 'task-1' };
      setupMockSession({ sessionState: firstState });

      const invocation1 = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'first' },
        mockMessageBus,
      );
      await invocation1.execute({
        abortSignal: new AbortController().signal,
      });

      // Second invocation — the mock constructor should receive firstState
      const secondState = { contextId: 'ctx-2', taskId: 'task-2' };
      setupMockSession({ sessionState: secondState });

      const invocation2 = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'second' },
        mockMessageBus,
      );
      await invocation2.execute({
        abortSignal: new AbortController().signal,
      });

      // The second invocation should have received the first's state
      const secondCallArgs = vi.mocked(RemoteSubagentSession).mock.calls[1];
      expect(secondCallArgs[3]).toEqual(firstState);
    });

    it('should subscribe for progress updates', async () => {
      const completedProgress: SubagentProgress = {
        isSubagentProgress: true,
        agentName: 'Test Agent',
        state: SubagentState.RUNNING,
        result: 'partial',
        recentActivity: [],
      };
      const { mockSession, emitEvent } = setupMockSession({
        progress: completedProgress,
      });

      const updateOutput = vi.fn();
      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );

      // Override getResult to emit a message event mid-execution
      mockSession.getResult.mockImplementation(async () => {
        emitEvent({
          type: 'message',
          id: 'e1',
          timestamp: new Date().toISOString(),
          streamId: 's1',
          role: 'agent',
          content: [{ type: 'text', text: 'hello' }],
        });
        return {
          llmContent: [{ text: 'done' }],
          returnDisplay: completedProgress,
        };
      });

      await invocation.execute({
        abortSignal: new AbortController().signal,
        updateOutput,
      });

      // subscribe should have been called (at least once for progress, possibly for parent)
      expect(mockSession.subscribe).toHaveBeenCalled();
      // updateOutput should have been called with the progress from getLatestProgress
      expect(updateOutput).toHaveBeenCalledWith(
        expect.objectContaining({
          isSubagentProgress: true,
        }),
      );
    });

    it('should handle abort gracefully', async () => {
      const controller = new AbortController();

      const partialProgress: SubagentProgress = {
        isSubagentProgress: true,
        agentName: 'Test Agent',
        state: SubagentState.RUNNING,
        result: '',
        recentActivity: [
          {
            id: 'a1',
            type: 'thought',
            content: 'Thinking...',
            status: SubagentState.RUNNING,
          },
        ],
      };

      const { mockSession } = setupMockSession({ progress: partialProgress });

      // When getResult resolves, the signal will already be aborted
      mockSession.getResult.mockImplementation(async () => {
        controller.abort();
        return {
          llmContent: [{ text: '' }],
          returnDisplay: '',
        };
      });

      const updateOutput = vi.fn();
      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );

      const result = await invocation.execute({
        abortSignal: controller.signal,
        updateOutput,
      });

      expect(result.returnDisplay).toMatchObject({ state: 'cancelled' });
      expect(
        (result.returnDisplay as SubagentProgress).recentActivity[0].status,
      ).toBe(SubagentState.CANCELLED);
      expect(result.llmContent).toEqual([
        { text: 'Operation cancelled by user' },
      ]);
    });
  });

  // ---------------------------------------------------------------------------
  // Error Handling
  // ---------------------------------------------------------------------------

  describe('Error Handling', () => {
    it('should handle execution errors gracefully', async () => {
      setupMockSession({ error: new Error('Network failure') });

      const updateOutput = vi.fn();
      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
        updateOutput,
      });

      expect(result.returnDisplay).toMatchObject({ state: 'error' });
      expect((result.returnDisplay as SubagentProgress).result).toContain(
        'Network failure',
      );
      // updateOutput should be called with error progress
      expect(updateOutput).toHaveBeenCalledWith(
        expect.objectContaining({ state: 'error' }),
      );
    });

    it('should include partial output in error display', async () => {
      const partialProgress: SubagentProgress = {
        isSubagentProgress: true,
        agentName: 'Test Agent',
        state: SubagentState.RUNNING,
        result: 'Partial work so far',
        recentActivity: [
          {
            id: 'a1',
            type: 'thought',
            content: 'Thinking...',
            status: SubagentState.RUNNING,
          },
        ],
      };

      setupMockSession({
        error: new Error('mid-stream error'),
        progress: partialProgress,
      });

      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      const display = result.returnDisplay as SubagentProgress;
      // Should contain both the partial output and the error
      expect(display.result).toContain('Partial work so far');
      expect(display.result).toContain('mid-stream error');
      // Should preserve and update partial activity status to ERROR
      expect(display.recentActivity).toHaveLength(1);
      expect(display.recentActivity[0].content).toBe('Thinking...');
      expect(display.recentActivity[0].status).toBe(SubagentState.ERROR);
    });

    it('should clean up listeners in finally', async () => {
      const { mockSession } = setupMockSession();

      const controller = new AbortController();
      const removeEventListenerSpy = vi.spyOn(
        controller.signal,
        'removeEventListener',
      );

      const onAgentEvent = vi.fn();
      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
        { onAgentEvent },
      );

      await invocation.execute({
        abortSignal: controller.signal,
      });

      // removeEventListener should have been called for the abort listener
      expect(removeEventListenerSpy).toHaveBeenCalledWith(
        'abort',
        expect.any(Function),
      );

      // All unsubscribe functions returned by subscribe during execute should be called
      const postExecuteUnsubscribes = mockSession.subscribe.mock.results.map(
        (r) => r.value,
      );
      for (const unsub of postExecuteUnsubscribes) {
        expect(unsub).toHaveBeenCalled();
      }
    });
  });

  // ---------------------------------------------------------------------------
  // SessionState Management
  // ---------------------------------------------------------------------------

  describe('SessionState Management', () => {
    it('should use composite name::url as session state key', async () => {
      const secondDefinition: RemoteAgentDefinition = {
        ...mockDefinition,
        name: 'other-agent',
        displayName: 'Other Agent',
        agentCardUrl: 'http://other-agent/card',
      };

      // First agent
      setupMockSession({
        sessionState: { contextId: 'ctx-a' },
      });
      const inv1 = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );
      await inv1.execute({ abortSignal: new AbortController().signal });

      // Second agent
      setupMockSession({
        sessionState: { contextId: 'ctx-b' },
      });
      const inv2 = new RemoteSessionInvocation(
        secondDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );
      await inv2.execute({ abortSignal: new AbortController().signal });

      const stateMap = (
        RemoteSessionInvocation as unknown as {
          sessionState: Map<string, { contextId?: string; taskId?: string }>;
        }
      ).sessionState;

      // Each agent should have its own entry keyed by name::url
      expect(stateMap.get('test-agent::http://test-agent/card')).toEqual({
        contextId: 'ctx-a',
      });
      expect(stateMap.get('other-agent::http://other-agent/card')).toEqual({
        contextId: 'ctx-b',
      });
    });

    it('should isolate same-name agents with different URLs', async () => {
      const defA: RemoteAgentDefinition = {
        ...mockDefinition,
        agentCardUrl: 'http://host-a/card',
      };
      const defB: RemoteAgentDefinition = {
        ...mockDefinition,
        agentCardUrl: 'http://host-b/card',
      };

      // Agent A
      setupMockSession({ sessionState: { contextId: 'ctx-a' } });
      const invA = new RemoteSessionInvocation(
        defA,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );
      await invA.execute({ abortSignal: new AbortController().signal });

      // Agent B (same name, different URL)
      setupMockSession({ sessionState: { contextId: 'ctx-b' } });
      const invB = new RemoteSessionInvocation(
        defB,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );
      await invB.execute({ abortSignal: new AbortController().signal });

      const stateMap = (
        RemoteSessionInvocation as unknown as {
          sessionState: Map<string, { contextId?: string; taskId?: string }>;
        }
      ).sessionState;

      expect(stateMap.get('test-agent::http://host-a/card')).toEqual({
        contextId: 'ctx-a',
      });
      expect(stateMap.get('test-agent::http://host-b/card')).toEqual({
        contextId: 'ctx-b',
      });
    });

    it('should fall back to name-only key when URL is unavailable', async () => {
      const noUrlDef: RemoteAgentDefinition = {
        ...mockDefinition,
        agentCardUrl: undefined,
      };

      setupMockSession({ sessionState: { contextId: 'ctx-no-url' } });
      const inv = new RemoteSessionInvocation(
        noUrlDef,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );
      await inv.execute({ abortSignal: new AbortController().signal });

      const stateMap = (
        RemoteSessionInvocation as unknown as {
          sessionState: Map<string, { contextId?: string; taskId?: string }>;
        }
      ).sessionState;

      expect(stateMap.get('test-agent')).toEqual({ contextId: 'ctx-no-url' });
    });

    it('should persist state even on error', async () => {
      const stateOnError = { contextId: 'ctx-err', taskId: 'task-err' };
      setupMockSession({
        error: new Error('boom'),
        sessionState: stateOnError,
      });

      const invocation = new RemoteSessionInvocation(
        mockDefinition,
        mockContext,
        { query: 'hi' },
        mockMessageBus,
      );

      await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      const stateMap = (
        RemoteSessionInvocation as unknown as {
          sessionState: Map<string, { contextId?: string; taskId?: string }>;
        }
      ).sessionState;

      expect(stateMap.get('test-agent::http://test-agent/card')).toEqual(
        stateOnError,
      );
    });
  });
});