File size: 10,276 Bytes
430354e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createStore } from "/js/AlpineStore.js";
import { fetchApi } from "/js/api.js";
import { store as settingsStore } from "/components/plugins/plugin-settings-store.js";

const model = {
    pluginName: null,
    
    // Context selectors
    projects: [],
    agentProfiles: [],
    projectName: "",
    agentProfileKey: "",

    // State
    isLoading: false,
    isSaving: false,
    error: null,
    
    // Status: 'enabled' | 'disabled'
    status: 'enabled',
    alwaysEnabled: false,
    perProjectConfig: true,
    perAgentConfig: true,
    hasExplicitRuleForScope: false,
    hasConfigScreen: false,

    // Where the effective toggle was actually resolved (mirrors plugin-settings-store loadedXxx fields)
    loadedPath: "",
    loadedProjectName: "",
    loadedAgentProfile: "",

    configs: [],

    async open(plugin, { projectName = "", agentProfileKey = "" } = {}) {
        this.isLoading = true;
        this.error = null;
        this.projects = [];
        this.agentProfiles = [];
        this.projectName = projectName || "";
        this.agentProfileKey = agentProfileKey || "";
        this.configs = [];
        this.status = 'enabled';
        this.hasExplicitRuleForScope = false;
        this.loadedPath = "";
        this.loadedProjectName = "";
        this.loadedAgentProfile = "";

        const pluginName = typeof plugin === 'string' ? plugin : plugin?.name;
        this.pluginName = pluginName;
        this.alwaysEnabled = typeof plugin === 'object' ? !!plugin.always_enabled : false;
        this.perProjectConfig = typeof plugin === 'object' ? !!plugin.per_project_config : true;
        this.perAgentConfig = typeof plugin === 'object' ? !!plugin.per_agent_config : true;
        this.hasConfigScreen = typeof plugin === 'object' ? !!plugin.has_config_screen : false;

        try {
            await Promise.all([this.loadProjects(), this.loadAgentProfiles()]);
            await this.loadConfigs();
        } finally {
            this.isLoading = false;
        }
    },

    cleanup() {
        this.pluginName = null;
        this.projectName = "";
        this.agentProfileKey = "";
        this.error = null;
        this.configs = [];
        this.perProjectConfig = true;
        this.perAgentConfig = true;
        this.alwaysEnabled = false;
        this.hasConfigScreen = false;
        this.hasExplicitRuleForScope = false;
        this.loadedPath = "";
        this.loadedProjectName = "";
        this.loadedAgentProfile = "";
        this.isLoading = false;
        this.isSaving = false;
    },

    async loadProjects() {
        try {
            const response = await fetchApi("/projects", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "list_options" }),
            });
            const data = await response.json().catch(() => ({}));
            this.projects = data.ok ? (data.data || []) : [];
        } catch {
            this.projects = [];
        }
    },

    async loadAgentProfiles() {
        try {
            const response = await fetchApi("/agents", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "list" }),
            });
            const data = await response.json().catch(() => ({}));
            this.agentProfiles = data.ok ? (data.data || []) : [];
        } catch {
            this.agentProfiles = [];
        }
    },

    async loadConfigs() {
        if (!this.pluginName) return;
        this.isLoading = true;
        try {
            const response = await fetchApi("/plugins", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    action: "list_configs",
                    plugin_name: this.pluginName,
                    asset_type: "toggle"
                }),
            });
            const result = await response.json().catch(() => ({}));
            this.configs = result.ok ? (result.data || []) : [];
            await this.loadToggleStatus();
        } catch (e) {
            this.error = e?.message || "Failed to load configurations";
        } finally {
            this.isLoading = false;
        }
    },

    async loadToggleStatus() {
        if (!this.pluginName) return;

        if (this.alwaysEnabled) {
            this.status = 'enabled';
            this.hasExplicitRuleForScope = true;
            this.loadedPath = "";
            this.loadedProjectName = this.projectName || "";
            this.loadedAgentProfile = this.agentProfileKey || "";
            return;
        }

        try {
            const response = await fetchApi("/plugins", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    action: "get_toggle_status",
                    plugin_name: this.pluginName,
                    project_name: this.projectName || "",
                    agent_profile: this.agentProfileKey || "",
                }),
            });
            const result = await response.json().catch(() => ({}));
            if (result.ok) {
                this.status = result.status || 'enabled';
                this.loadedPath = result.loaded_path || "";
                this.loadedProjectName = result.loaded_project_name || "";
                this.loadedAgentProfile = result.loaded_agent_profile || "";
                const p = this.projectName || "";
                const a = this.agentProfileKey || "";
                this.hasExplicitRuleForScope = !!(this.loadedPath) &&
                    this.loadedProjectName === p &&
                    this.loadedAgentProfile === a;
            }
        } catch (e) {
            this.error = e?.message || "Failed to load toggle status";
        }
    },

    async switchToConfig(projectName, agentProfile) {
        this.projectName = projectName || "";
        this.agentProfileKey = agentProfile || "";
        await this.onScopeChanged();
        await window.closeModal?.();
    },

    async deleteConfig(path) {
        if (!this.pluginName || !path) return;
        this.isLoading = true;
        try {
            const response = await fetchApi("/plugins", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    action: "delete_config",
                    plugin_name: this.pluginName,
                    path: path
                }),
            });
            const result = await response.json();
            if (!result.ok) throw new Error(result.error);
            await this.loadConfigs();
        } catch (e) {
            this.error = e.message || "Delete failed";
        } finally {
            this.isLoading = false;
        }
    },

    async setEnabled(enabled, { projectName = this.projectName, agentProfileKey = this.agentProfileKey } = {}) {
        if (!this.pluginName || this.alwaysEnabled) return;
        const previousStatus = this.status;
        const previousProjectName = this.projectName;
        const previousAgentProfileKey = this.agentProfileKey;
        this.projectName = projectName || "";
        this.agentProfileKey = agentProfileKey || "";
        this.status = enabled ? 'enabled' : 'disabled';
        this.isSaving = true;
        try {
            const response = await fetchApi("/plugins", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    action: "toggle_plugin",
                    plugin_name: this.pluginName,
                    project_name: this.projectName || "",
                    agent_profile: this.agentProfileKey || "",
                    enabled: enabled
                }),
            });
            const result = await response.json();
            if (!result.ok) throw new Error(result.error);
            await new Promise(r => setTimeout(r, 100));
            await this.loadConfigs();
        } catch (e) {
            this.status = previousStatus;
            this.projectName = previousProjectName;
            this.agentProfileKey = previousAgentProfileKey;
            this.error = e.message || "Failed to save";
            throw e;
        } finally {
            this.isSaving = false;
        }
    },

    async onScopeChanged() {
        await this.loadToggleStatus();

        // Sync scope with settings store so its loadSettings picks up the right context
        settingsStore.projectName = this.projectName || "";
        settingsStore.agentProfileKey = this.agentProfileKey || "";
        await settingsStore.loadSettings();
    },

    async addRule() {
        await this.setEnabled(this.status === 'enabled');
    },

    projectLabel(key) {
        if (!key) return "Global";
        const found = (this.projects || []).find(p => p.key === key);
        return found?.label || key;
    },

    agentProfileLabel(key) {
        if (!key) return "All profiles";
        const found = (this.agentProfiles || []).find(p => p.key === key);
        return found?.label || key;
    },

    get statusLabel() {
        return this.status === 'enabled' ? 'ON' : 'OFF';
    },

    get noScopeRuleMessage() {
        if (this.alwaysEnabled || this.isLoading) return "";
        if (this.hasExplicitRuleForScope) return "";

        if (!this.loadedPath) {
            return this.configs.length === 0
                ? "No activation rule exists yet. This plugin is currently ON by default."
                : "No activation rule exists for this scope yet. This scope is currently ON by default.";
        }

        // Inherited from a parent scope - mirrors plugin-settings-store scopeMismatchMessage
        const pLabel = this.projectLabel(this.loadedProjectName || "");
        const aLabel = this.agentProfileLabel(this.loadedAgentProfile || "");
        const state = this.status === 'enabled' ? 'ON' : 'OFF';
        return `No rule for this scope. Inheriting from ${pLabel}, ${aLabel}: ${state}.`;
    }
};

export const store = createStore("pluginToggle", model);