/**
 * Coalesces rapid terminal assistant stream updates so Ink renders the newest
 * cumulative text instead of replaying stale partial chunks.
 */
export class AssistantStreamBufferService {
    options;
    pendingUpdate;
    flushTimer;
    lastAppliedAt = 0;
    constructor(options) {
        this.options = options;
    }
    push(update) {
        if (!this.options.canApply(update)) {
            return;
        }
        if (update.done || this.shouldApplyNow()) {
            this.clearPendingFlush();
            this.apply(update);
            return;
        }
        this.pendingUpdate = update;
        this.scheduleFlush();
    }
    flush() {
        const update = this.pendingUpdate;
        this.clearPendingFlush();
        if (!update || !this.options.canApply(update)) {
            return;
        }
        this.apply(update);
    }
    reset() {
        this.clearPendingFlush();
        this.lastAppliedAt = 0;
    }
    dispose() {
        this.reset();
    }
    shouldApplyNow() {
        const nowMs = Date.now();
        if (!this.lastAppliedAt || nowMs - this.lastAppliedAt >= this.options.renderIntervalMs) {
            this.lastAppliedAt = nowMs;
            return true;
        }
        return false;
    }
    scheduleFlush() {
        if (this.flushTimer) {
            return;
        }
        const elapsedMs = Date.now() - this.lastAppliedAt;
        const delayMs = Math.max(0, this.options.renderIntervalMs - elapsedMs);
        this.flushTimer = setTimeout(() => this.flush(), delayMs);
    }
    clearPendingFlush() {
        if (this.flushTimer) {
            clearTimeout(this.flushTimer);
        }
        this.flushTimer = undefined;
        this.pendingUpdate = undefined;
    }
    apply(update) {
        this.lastAppliedAt = Date.now();
        this.options.apply(update);
    }
}
//# sourceMappingURL=assistant-stream-buffer-service.js.map