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

import {
  describe,
  it,
  expect,
  vi,
  beforeEach,
  afterEach,
  type Mocked,
  type Mock,
} from 'vitest';
import { EventEmitter } from 'node:events';
import { resolveConfirmation } from './confirmation.js';
import {
  MessageBusType,
  type ToolConfirmationResponse,
} from '../confirmation-bus/types.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import {
  ToolConfirmationOutcome,
  type AnyToolInvocation,
  type AnyDeclarativeTool,
} from '../tools/tools.js';
import type { SchedulerStateManager } from './state-manager.js';
import type { ToolModificationHandler } from './tool-modifier.js';
import {
  ROOT_SCHEDULER_ID,
  type ValidatingToolCall,
  type WaitingToolCall,
} from './types.js';
import type { Config } from '../config/config.js';
import { type EditorType } from '../utils/editor.js';
import { randomUUID } from 'node:crypto';

// Mock Dependencies
vi.mock('node:crypto', () => ({
  randomUUID: vi.fn(),
}));

vi.mock('../utils/editor.js', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../utils/editor.js')>();
  return {
    ...actual,
    resolveEditorAsync: () => Promise.resolve('vim'),
  };
});

describe('confirmation.ts', () => {
  let mockMessageBus: MessageBus;

  beforeEach(() => {
    vi.stubEnv('SANDBOX', '');
    mockMessageBus = new EventEmitter() as unknown as MessageBus;
    mockMessageBus.publish = vi.fn().mockResolvedValue(undefined);
    vi.spyOn(mockMessageBus, 'on');
    vi.spyOn(mockMessageBus, 'removeListener');
    vi.mocked(randomUUID).mockReturnValue(
      '123e4567-e89b-12d3-a456-426614174000',
    );
  });

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

  const emitResponse = (response: ToolConfirmationResponse) => {
    mockMessageBus.emit(MessageBusType.TOOL_CONFIRMATION_RESPONSE, response);
  };

  /**
   * Helper to wait for a listener to be attached to the bus.
   * This is more robust than setTimeout for synchronizing with the async iterator.
   */
  const waitForListener = (eventName: string | symbol): Promise<void> =>
    new Promise((resolve) => {
      const handler = (event: string | symbol) => {
        if (event === eventName) {
          mockMessageBus.off('newListener', handler);
          resolve();
        }
      };
      mockMessageBus.on('newListener', handler);
    });

  describe('resolveConfirmation', () => {
    let mockState: Mocked<SchedulerStateManager>;
    let mockModifier: Mocked<ToolModificationHandler>;
    let mockConfig: Mocked<Config>;
    let getPreferredEditor: Mock<() => EditorType | undefined>;
    let signal: AbortSignal;
    let toolCall: ValidatingToolCall;
    let invocationMock: Mocked<AnyToolInvocation>;
    let toolMock: Mocked<AnyDeclarativeTool>;

    beforeEach(() => {
      signal = new AbortController().signal;

      mockState = {
        getToolCall: vi.fn(),
        updateStatus: vi.fn(),
        updateArgs: vi.fn(),
      } as unknown as Mocked<SchedulerStateManager>;
      // Mock accessors via defineProperty
      Object.defineProperty(mockState, 'firstActiveCall', {
        get: vi.fn(),
        configurable: true,
      });

      const mockHookSystem = {
        fireToolNotificationEvent: vi.fn().mockResolvedValue(undefined),
      };
      mockConfig = {
        getEnableHooks: vi.fn().mockReturnValue(true),
        getHookSystem: vi.fn().mockReturnValue(mockHookSystem),
      } as unknown as Mocked<Config>;

      mockModifier = {
        handleModifyWithEditor: vi.fn(),
        applyInlineModify: vi.fn(),
      } as unknown as Mocked<ToolModificationHandler>;

      getPreferredEditor = vi.fn().mockReturnValue('vim');

      invocationMock = {
        shouldConfirmExecute: vi.fn(),
      } as unknown as Mocked<AnyToolInvocation>;

      toolMock = {
        build: vi.fn(),
      } as unknown as Mocked<AnyDeclarativeTool>;

      toolCall = {
        status: 'validating',
        request: {
          callId: 'call-1',
          name: 'tool',
          args: {},
          isClientInitiated: false,
          prompt_id: 'prompt-1',
        },
        invocation: invocationMock,
        tool: toolMock,
      } as ValidatingToolCall;

      // Default: state returns the current call
      mockState.getToolCall.mockReturnValue(toolCall);
      // Default: define firstActiveCall for modifiers
      vi.spyOn(mockState, 'firstActiveCall', 'get').mockReturnValue(
        toolCall as unknown as WaitingToolCall,
      );
    });

    it('should return ProceedOnce immediately if no confirmation needed', async () => {
      invocationMock.shouldConfirmExecute.mockResolvedValue(false);

      const result = await resolveConfirmation(toolCall, signal, {
        config: mockConfig,
        messageBus: mockMessageBus,
        state: mockState,
        modifier: mockModifier,
        getPreferredEditor,
        schedulerId: ROOT_SCHEDULER_ID,
      });

      expect(result.outcome).toBe(ToolConfirmationOutcome.ProceedOnce);
      expect(mockState.updateStatus).not.toHaveBeenCalledWith(
        expect.anything(),
        'awaiting_approval',
        expect.anything(),
      );
    });

    it('should return ProceedOnce after successful user confirmation', async () => {
      const details = {
        type: 'info' as const,
        prompt: 'Confirm?',
        title: 'Title',
        onConfirm: vi.fn(),
      };
      invocationMock.shouldConfirmExecute.mockResolvedValue(details);

      // Wait for listener to attach
      const listenerPromise = waitForListener(
        MessageBusType.TOOL_CONFIRMATION_RESPONSE,
      );
      const promise = resolveConfirmation(toolCall, signal, {
        config: mockConfig,
        messageBus: mockMessageBus,
        state: mockState,
        modifier: mockModifier,
        getPreferredEditor,
        schedulerId: ROOT_SCHEDULER_ID,
      });
      await listenerPromise;

      emitResponse({
        type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
        correlationId: '123e4567-e89b-12d3-a456-426614174000',
        confirmed: true,
      });

      const result = await promise;
      expect(result.outcome).toBe(ToolConfirmationOutcome.ProceedOnce);
      expect(mockState.updateStatus).toHaveBeenCalledWith(
        'call-1',
        'awaiting_approval',
        expect.objectContaining({
          correlationId: '123e4567-e89b-12d3-a456-426614174000',
        }),
      );
    });

    it('should fire hooks if enabled', async () => {
      const details = {
        type: 'info' as const,
        prompt: 'Confirm?',
        title: 'Title',
        onConfirm: vi.fn(),
      };
      invocationMock.shouldConfirmExecute.mockResolvedValue(details);

      const promise = resolveConfirmation(toolCall, signal, {
        config: mockConfig,
        messageBus: mockMessageBus,
        state: mockState,
        modifier: mockModifier,
        getPreferredEditor,
        schedulerId: ROOT_SCHEDULER_ID,
      });

      await waitForListener(MessageBusType.TOOL_CONFIRMATION_RESPONSE);
      emitResponse({
        type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
        correlationId: '123e4567-e89b-12d3-a456-426614174000',
        confirmed: true,
      });
      await promise;

      expect(
        mockConfig.getHookSystem()?.fireToolNotificationEvent,
      ).toHaveBeenCalledWith(
        expect.objectContaining({
          type: details.type,
          prompt: details.prompt,
          title: details.title,
        }),
      );
    });

    it('should handle ModifyWithEditor loop', async () => {
      const details = {
        type: 'info' as const,
        prompt: 'Confirm?',
        title: 'Title',
        onConfirm: vi.fn(),
      };
      invocationMock.shouldConfirmExecute.mockResolvedValue(details);

      // Set up modifier mock before starting the flow
      mockModifier.handleModifyWithEditor.mockResolvedValue({
        updatedParams: { foo: 'bar' },
      });
      toolMock.build.mockReturnValue({} as unknown as AnyToolInvocation);

      // Start the confirmation flow
      const listenerPromise1 = waitForListener(
        MessageBusType.TOOL_CONFIRMATION_RESPONSE,
      );
      const promise = resolveConfirmation(toolCall, signal, {
        config: mockConfig,
        messageBus: mockMessageBus,
        state: mockState,
        modifier: mockModifier,
        getPreferredEditor,
        schedulerId: ROOT_SCHEDULER_ID,
      });

      await listenerPromise1;

      // Prepare to detect when the loop re-subscribes after modification
      const listenerPromise2 = waitForListener(
        MessageBusType.TOOL_CONFIRMATION_RESPONSE,
      );

      // First response: User chooses to modify with editor
      emitResponse({
        type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
        correlationId: '123e4567-e89b-12d3-a456-426614174000',
        confirmed: true,
        outcome: ToolConfirmationOutcome.ModifyWithEditor,
      });

      // Wait for the loop to process the modification and re-subscribe
      await listenerPromise2;

      expect(mockState.updateArgs).toHaveBeenCalled();

      // Second response: User approves the modified params
      emitResponse({
        type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
        correlationId: '123e4567-e89b-12d3-a456-426614174000',
        confirmed: true,
        outcome: ToolConfirmationOutcome.ProceedOnce,
      });

      const result = await promise;
      expect(result.outcome).toBe(ToolConfirmationOutcome.ProceedOnce);
      expect(mockModifier.handleModifyWithEditor).toHaveBeenCalled();
    });

    it('should handle inline modification (payload)', async () => {
      const details = {
        type: 'info' as const,
        prompt: 'Confirm?',
        title: 'Title',
        onConfirm: vi.fn(),
      };
      invocationMock.shouldConfirmExecute.mockResolvedValue(details);

      const listenerPromise = waitForListener(
        MessageBusType.TOOL_CONFIRMATION_RESPONSE,
      );
      const promise = resolveConfirmation(toolCall, signal, {
        config: mockConfig,
        messageBus: mockMessageBus,
        state: mockState,
        modifier: mockModifier,
        getPreferredEditor,
        schedulerId: ROOT_SCHEDULER_ID,
      });

      await listenerPromise;

      // Response with payload
      emitResponse({
        type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
        correlationId: '123e4567-e89b-12d3-a456-426614174000',
        confirmed: true,
        outcome: ToolConfirmationOutcome.ProceedOnce, // Ignored if payload present
        payload: { newContent: 'inline' },
      });

      mockModifier.applyInlineModify.mockResolvedValue({
        updatedParams: { inline: 'true' },
      });
      toolMock.build.mockReturnValue({} as unknown as AnyToolInvocation);

      const result = await promise;
      expect(result.outcome).toBe(ToolConfirmationOutcome.ProceedOnce);
      expect(mockModifier.applyInlineModify).toHaveBeenCalled();
      expect(mockState.updateArgs).toHaveBeenCalled();
    });

    it('should pass payload to onConfirm callback', async () => {
      const details = {
        type: 'ask_user' as const,
        questions: [],
        title: 'Title',
        onConfirm: vi.fn(),
      };
      invocationMock.shouldConfirmExecute.mockResolvedValue(details);

      const listenerPromise = waitForListener(
        MessageBusType.TOOL_CONFIRMATION_RESPONSE,
      );
      const promise = resolveConfirmation(toolCall, signal, {
        config: mockConfig,
        messageBus: mockMessageBus,
        state: mockState,
        modifier: mockModifier,
        getPreferredEditor,
        schedulerId: ROOT_SCHEDULER_ID,
      });

      await listenerPromise;

      const payload = { answers: { '0': 'user choice' } };
      emitResponse({
        type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
        correlationId: '123e4567-e89b-12d3-a456-426614174000',
        confirmed: true,
        outcome: ToolConfirmationOutcome.ProceedOnce,
        payload,
      });

      await promise;
      expect(details.onConfirm).toHaveBeenCalledWith(
        ToolConfirmationOutcome.ProceedOnce,
        payload,
      );
    });

    it('should resolve immediately if IDE confirmation resolves first', async () => {
      const idePromise = Promise.resolve({
        status: 'accepted' as const,
        content: 'ide-content',
      });

      const details = {
        type: 'info' as const,
        prompt: 'Confirm?',
        title: 'Title',
        onConfirm: vi.fn(),
        ideConfirmation: idePromise,
      };
      invocationMock.shouldConfirmExecute.mockResolvedValue(details);

      // We don't strictly need to wait for the listener because the race might finish instantly
      const promise = resolveConfirmation(toolCall, signal, {
        config: mockConfig,
        messageBus: mockMessageBus,
        state: mockState,
        modifier: mockModifier,
        getPreferredEditor,
        schedulerId: ROOT_SCHEDULER_ID,
      });

      const result = await promise;
      expect(result.outcome).toBe(ToolConfirmationOutcome.ProceedOnce);
    });

    it('should throw if tool call is lost from state during loop', async () => {
      invocationMock.shouldConfirmExecute.mockResolvedValue({
        type: 'info' as const,
        title: 'Title',
        onConfirm: vi.fn(),
        prompt: 'Prompt',
      });
      // Simulate state losing the call (undefined)
      mockState.getToolCall.mockReturnValue(undefined);

      await expect(
        resolveConfirmation(toolCall, signal, {
          config: mockConfig,
          messageBus: mockMessageBus,
          state: mockState,
          modifier: mockModifier,
          getPreferredEditor,
          schedulerId: ROOT_SCHEDULER_ID,
        }),
      ).rejects.toThrow(/lost during confirmation loop/);
    });
  });
});