import { describe, it, expect } from 'vitest';
import {
  armAbortGuard,
  noteTurnActivity,
  consumeTerminal,
  type AbortTerminalGuard,
} from '../turn-guard.js';

describe('post-abort terminal guard (F.1)', () => {
  it('swallows the orphan terminal that follows an abort, then settles the next real one', () => {
    // Reproduces the v2.6.5 Stop-button bug: abort turn A, then opencode emits a
    // trailing session.idle for A. That orphan must NOT settle the next turn.
    const g: AbortTerminalGuard = { swallowNextTerminal: false };

    armAbortGuard(g); // user aborts turn A
    expect(consumeTerminal(g)).toBe('swallow'); // opencode's orphan idle for A → dropped
    expect(consumeTerminal(g)).toBe('settle'); // turn B's real idle → settles B
  });

  it('settles a terminal when no abort happened', () => {
    const g: AbortTerminalGuard = { swallowNextTerminal: false };
    expect(consumeTerminal(g)).toBe('settle');
  });

  it('self-heals if the orphan never arrives: new-turn activity clears the guard', () => {
    // If opencode emits no orphan idle (e.g. abort-before-prompt), the next turn's
    // real terminal must still settle rather than being swallowed forever.
    const g: AbortTerminalGuard = { swallowNextTerminal: false };

    armAbortGuard(g); // abort A, but no orphan idle arrives
    noteTurnActivity(g); // turn B produces its first delta
    expect(consumeTerminal(g)).toBe('settle'); // turn B's idle settles, not swallowed
  });
});
