File size: 10,130 Bytes
8ede856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
<template>
    <div>
        <v-list-item
            class="styled-menu-item"
            rounded="md"
            @click="openDialog"
            :disabled="loadingConfigs || saving"
        >
            <template v-slot:prepend>
                <v-icon icon="mdi-cog-outline" size="small"></v-icon>
            </template>
            <v-list-item-title>
                {{ tm('config.title') }}
            </v-list-item-title>
            <v-list-item-subtitle class="text-caption">
                {{ selectedConfigLabel }}
            </v-list-item-subtitle>
            <template v-slot:append>
                <v-icon icon="mdi-chevron-right" size="small" class="text-medium-emphasis"></v-icon>
            </template>
        </v-list-item>

        <v-dialog v-model="dialog" max-width="480">
            <v-card>
                <v-card-title class="d-flex align-center justify-space-between">
                    <span>选择配置文件</span>
                    <v-btn icon variant="text" @click="closeDialog">
                        <v-icon>mdi-close</v-icon>
                    </v-btn>
                </v-card-title>
                <v-card-text>
                    <div v-if="loadingConfigs" class="text-center py-6">
                        <v-progress-circular indeterminate color="primary"></v-progress-circular>
                    </div>

                    <v-list v-else class="config-list" density="comfortable">
                        <v-list-item
                            v-for="config in configOptions"
                            :key="config.id"
                            :active="tempSelectedConfig === config.id"
                            rounded="lg"
                            variant="text"
                            @click="tempSelectedConfig = config.id"
                        >
                            <v-list-item-title>{{ config.name }}</v-list-item-title>
                            <v-list-item-subtitle class="text-caption text-grey">
                                {{ config.id }}
                            </v-list-item-subtitle>
                            <template #append>
                                <v-icon v-if="tempSelectedConfig === config.id" color="primary">mdi-check</v-icon>
                            </template>
                        </v-list-item>
                        <div v-if="configOptions.length === 0" class="text-center text-body-2 text-medium-emphasis">
                            暂无可选配置,请先在配置页创建。
                        </div>
                    </v-list>
                </v-card-text>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn variant="text" @click="closeDialog">取消</v-btn>
                    <v-btn
                        color="primary"
                        @click="confirmSelection"
                        :disabled="!tempSelectedConfig"
                        :loading="saving"
                    >
                        应用
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import { useToast } from '@/utils/toast';
import { useModuleI18n } from '@/i18n/composables';
import {
    getStoredDashboardUsername,
    getStoredSelectedChatConfigId,
    setStoredSelectedChatConfigId
} from '@/utils/chatConfigBinding';

interface ConfigInfo {
    id: string;
    name: string;
}

interface ConfigChangedPayload {
    configId: string;
    agentRunnerType: string;
}

const props = withDefaults(defineProps<{
    sessionId?: string | null;
    platformId?: string;
    isGroup?: boolean;
    initialConfigId?: string | null;
}>(), {
    sessionId: null,
    platformId: 'webchat',
    isGroup: false,
    initialConfigId: null
});

const emit = defineEmits<{ 'config-changed': [ConfigChangedPayload] }>();

const { tm } = useModuleI18n('features/chat');

const configOptions = ref<ConfigInfo[]>([]);
const loadingConfigs = ref(false);
const dialog = ref(false);
const tempSelectedConfig = ref('');
const selectedConfigId = ref('default');
const agentRunnerType = ref('local');
const saving = ref(false);
const pendingSync = ref(false);
const routingEntries = ref<Array<{ pattern: string; confId: string }>>([]);
const configCache = ref<Record<string, string>>({});

const toast = useToast();

const normalizedSessionId = computed(() => {
    const id = props.sessionId?.trim();
    return id ? id : null;
});

const hasActiveSession = computed(() => !!normalizedSessionId.value);

const messageType = computed(() => (props.isGroup ? 'GroupMessage' : 'FriendMessage'));

const username = computed(() => getStoredDashboardUsername());

const sessionKey = computed(() => {
    if (!normalizedSessionId.value) {
        return null;
    }
    return `${props.platformId}!${username.value}!${normalizedSessionId.value}`;
});

const targetUmo = computed(() => {
    if (!sessionKey.value) {
        return null;
    }
    return `${props.platformId}:${messageType.value}:${sessionKey.value}`;
});

const selectedConfigLabel = computed(() => {
    const target = configOptions.value.find((item) => item.id === selectedConfigId.value);
    return target?.name || selectedConfigId.value || 'default';
});

function openDialog() {
    tempSelectedConfig.value = selectedConfigId.value;
    dialog.value = true;
}

function closeDialog() {
    dialog.value = false;
}

async function fetchConfigList() {
    loadingConfigs.value = true;
    try {
        const res = await axios.get('/api/config/abconfs');
        configOptions.value = res.data.data?.info_list || [];
    } catch (error) {
        console.error('加载配置文件列表失败', error);
        configOptions.value = [];
    } finally {
        loadingConfigs.value = false;
    }
}

async function fetchRoutingEntries() {
    try {
        const res = await axios.get('/api/config/umo_abconf_routes');
        const routing = res.data.data?.routing || {};
        routingEntries.value = Object.entries(routing).map(([pattern, confId]) => ({
            pattern,
            confId: confId as string
        }));
    } catch (error) {
        console.error('获取配置路由失败', error);
        routingEntries.value = [];
    }
}

function matchesPattern(pattern: string, target: string): boolean {
    const parts = pattern.split(':');
    const targetParts = target.split(':');
    if (parts.length !== 3 || targetParts.length !== 3) {
        return false;
    }
    return parts.every((part, index) => part === '' || part === '*' || part === targetParts[index]);
}

function resolveConfigId(umo: string | null): string {
    if (!umo) {
        return 'default';
    }
    for (const entry of routingEntries.value) {
        if (matchesPattern(entry.pattern, umo)) {
            return entry.confId;
        }
    }
    return 'default';
}

async function getAgentRunnerType(confId: string): Promise<string> {
    if (configCache.value[confId]) {
        return configCache.value[confId];
    }
    try {
        const res = await axios.get('/api/config/abconf', {
            params: { id: confId }
        });
        const type = res.data.data?.config?.provider_settings?.agent_runner_type || 'local';
        configCache.value[confId] = type;
        return type;
    } catch (error) {
        console.error('获取配置文件详情失败', error);
        return 'local';
    }
}

async function setSelection(confId: string) {
    const normalized = confId || 'default';
    selectedConfigId.value = normalized;
    const runnerType = await getAgentRunnerType(normalized);
    agentRunnerType.value = runnerType;
    emit('config-changed', {
        configId: normalized,
        agentRunnerType: runnerType
    });
}

async function applySelectionToBackend(confId: string): Promise<boolean> {
    if (!targetUmo.value) {
        pendingSync.value = true;
        return true;
    }
    saving.value = true;
    try {
        await axios.post('/api/config/umo_abconf_route/update', {
            umo: targetUmo.value,
            conf_id: confId
        });
        const filtered = routingEntries.value.filter((entry) => entry.pattern !== targetUmo.value);
        filtered.push({ pattern: targetUmo.value, confId });
        routingEntries.value = filtered;
        return true;
    } catch (error) {
        const err = error as any;
        console.error('更新配置文件失败', err);
        toast.error(err?.response?.data?.message || '配置文件应用失败');
        return false;
    } finally {
        saving.value = false;
    }
}

async function confirmSelection() {
    if (!tempSelectedConfig.value) {
        return;
    }
    const previousId = selectedConfigId.value;
    await setSelection(tempSelectedConfig.value);
    setStoredSelectedChatConfigId(tempSelectedConfig.value);
    const applied = await applySelectionToBackend(tempSelectedConfig.value);
    if (!applied) {
        setStoredSelectedChatConfigId(previousId);
        await setSelection(previousId);
    }
    dialog.value = false;
}

async function syncSelectionForSession() {
    if (!targetUmo.value) {
        pendingSync.value = true;
        return;
    }
    if (pendingSync.value) {
        pendingSync.value = false;
        await applySelectionToBackend(selectedConfigId.value);
        return;
    }
    await fetchRoutingEntries();
    const resolved = resolveConfigId(targetUmo.value);
    await setSelection(resolved);
    setStoredSelectedChatConfigId(resolved);
}

watch(
    () => [props.sessionId, props.platformId, props.isGroup],
    async () => {
        await syncSelectionForSession();
    }
);

onMounted(async () => {
    await fetchConfigList();
    const stored = props.initialConfigId || getStoredSelectedChatConfigId();
    selectedConfigId.value = stored;
    await setSelection(stored);
    await syncSelectionForSession();
});
</script>

<style scoped>
.config-list {
    max-height: 360px;
    overflow-y: auto;
}
</style>