const DEFAULT_STATE = {
    phase: "idle",
    step: 0,
    maxSteps: 50,
    inputTokens: 0,
    outputTokens: 0,
    contextTokens: 0,
    maxContextTokens: 0,
    model: "",
    workspaceRoot: "",
    indexStatus: "",
    items: [],
    errorMessage: null,
    pendingPermission: null,
    autoAllowMode: "none",
};
export class UiStore {
    state = { ...DEFAULT_STATE };
    listeners = new Set();
    getState() {
        return { ...this.state };
    }
    subscribe(listener) {
        this.listeners.add(listener);
        return () => {
            this.listeners.delete(listener);
        };
    }
    notify() {
        for (const listener of this.listeners) {
            listener();
        }
    }
    update(partial) {
        this.state = { ...this.state, ...partial };
        this.notify();
    }
    setConfig(config) {
        this.update(config);
    }
    setPhase(phase) {
        this.update({ phase });
    }
    setStep(step) {
        this.update({ step });
    }
    setTokenUsage(inputTokens, outputTokens) {
        this.update({ inputTokens, outputTokens });
    }
    setContextStatus(contextTokens, maxContextTokens) {
        this.update({ contextTokens, maxContextTokens });
    }
    addItem(item) {
        this.update({
            items: [...this.state.items, item],
        });
    }
    updateLastToolCall(update) {
        const items = [...this.state.items];
        for (let i = items.length - 1; i >= 0; i--) {
            const it = items[i];
            if (it && it.type === "tool_call") {
                items[i] = { ...it, ...update };
                this.update({ items });
                return;
            }
        }
    }
    appendToStreamingContent(chunk) {
        const items = [...this.state.items];
        const last = items[items.length - 1];
        if (last?.type === "assistant") {
            items[items.length - 1] = {
                ...last,
                content: last.content + chunk,
            };
        }
        else {
            items.push({ type: "assistant", content: chunk });
        }
        this.update({ items });
    }
    setError(message) {
        this.update({
            errorMessage: message,
            ...(message !== null ? { phase: "error" } : { phase: "idle" }),
        });
    }
    clearAll() {
        this.update({ items: [] });
    }
    reset() {
        this.state = { ...DEFAULT_STATE };
        this.notify();
    }
    setPendingPermission(prompt) {
        this.update({ pendingPermission: prompt });
    }
    setAutoAllowMode(mode) {
        if (this.state.autoAllowMode === mode)
            return;
        this.update({ autoAllowMode: mode });
    }
    getAutoAllowMode() {
        return this.state.autoAllowMode;
    }
}
