Enhance chat handling.

This commit is contained in:
decolua
2026-01-14 15:42:38 +07:00
parent c39eca6d4e
commit c208f244ee
7 changed files with 145 additions and 137 deletions
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect } from "react";
import { Card, Button, ModelSelectModal } from "@/shared/components";
import { Card, Button, ModelSelectModal, ManualConfigModal } from "@/shared/components";
import Image from "next/image";
const CLOUD_URL = process.env.NEXT_PUBLIC_CLOUD_URL;
@@ -27,8 +27,8 @@ export default function ClaudeToolCard({
const [modalOpen, setModalOpen] = useState(false);
const [currentEditingAlias, setCurrentEditingAlias] = useState(null);
const [selectedApiKey, setSelectedApiKey] = useState("");
const [copiedConfig, setCopiedConfig] = useState(false);
const [modelAliases, setModelAliases] = useState({});
const [showManualConfigModal, setShowManualConfigModal] = useState(false);
const getConfigStatus = () => {
if (!claudeStatus?.installed) return null;
@@ -163,7 +163,7 @@ export default function ClaudeToolCard({
};
// Generate settings.json content for manual copy
const getSettingsContent = () => {
const getManualConfigs = () => {
const keyToUse = (selectedApiKey && selectedApiKey.trim())
? selectedApiKey
: (!cloudEnabled ? "sk_9router" : "<API_KEY_FROM_DASHBOARD>");
@@ -172,17 +172,13 @@ export default function ClaudeToolCard({
const targetModel = modelMappings[model.alias];
if (targetModel && model.envKey) env[model.envKey] = targetModel;
});
return JSON.stringify({ env }, null, 2);
};
const copyToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text);
setCopiedConfig(true);
setTimeout(() => setCopiedConfig(false), 2000);
} catch (err) {
console.log("Failed to copy:", err);
}
return [
{
filename: "~/.claude/settings.json",
content: JSON.stringify({ env }, null, 2),
},
];
};
return (
@@ -289,31 +285,23 @@ export default function ClaudeToolCard({
<Button variant="outline" size="sm" onClick={handleResetSettings} disabled={!claudeStatus?.has9Router} loading={restoring}>
<span className="material-symbols-outlined text-[14px] mr-1">restore</span>Reset
</Button>
<Button variant="ghost" size="sm" onClick={checkClaudeStatus}>
<span className="material-symbols-outlined text-[14px]">refresh</span>
<Button variant="ghost" size="sm" onClick={() => setShowManualConfigModal(true)}>
<span className="material-symbols-outlined text-[14px] mr-1">content_copy</span>Manual Config
</Button>
</div>
{/* Manual Config Section */}
<div className="pt-4 border-t border-border flex flex-col gap-3">
<p className="text-xs text-text-muted">Or copy config manually:</p>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-text-main">~/.claude/settings.json</span>
<Button variant="ghost" size="sm" onClick={() => copyToClipboard(getSettingsContent())}>
<span className="material-symbols-outlined text-[14px] mr-1">{copiedConfig ? "check" : "content_copy"}</span>
{copiedConfig ? "Copied!" : "Copy"}
</Button>
</div>
<pre className="px-3 py-2 bg-black/5 dark:bg-white/5 rounded font-mono text-xs overflow-x-auto whitespace-pre-wrap break-all max-h-40 overflow-y-auto">{getSettingsContent()}</pre>
</div>
</div>
</>
)}
</div>
)}
<ModelSelectModal isOpen={modalOpen} onClose={() => setModalOpen(false)} onSelect={handleModelSelect} selectedModel={currentEditingAlias ? modelMappings[currentEditingAlias] : null} activeProviders={activeProviders} modelAliases={modelAliases} title={`Select model for ${currentEditingAlias}`} />
<ManualConfigModal
isOpen={showManualConfigModal}
onClose={() => setShowManualConfigModal(false)}
title="Claude CLI - Manual Configuration"
configs={getManualConfigs()}
/>
</Card>
);
}
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect } from "react";
import { Card, Button, ModelSelectModal } from "@/shared/components";
import { Card, Button, ModelSelectModal, ManualConfigModal } from "@/shared/components";
import Image from "next/image";
export default function CodexToolCard({ tool, isExpanded, onToggle, baseUrl, apiKeys, activeProviders, cloudEnabled }) {
@@ -13,9 +13,9 @@ export default function CodexToolCard({ tool, isExpanded, onToggle, baseUrl, api
const [showInstallGuide, setShowInstallGuide] = useState(false);
const [selectedApiKey, setSelectedApiKey] = useState("");
const [selectedModel, setSelectedModel] = useState("");
const [copiedConfig, setCopiedConfig] = useState(false);
const [modalOpen, setModalOpen] = useState(false);
const [modelAliases, setModelAliases] = useState({});
const [showManualConfigModal, setShowManualConfigModal] = useState(false);
useEffect(() => {
if (apiKeys?.length > 0 && !selectedApiKey) {
@@ -123,7 +123,12 @@ export default function CodexToolCard({ tool, isExpanded, onToggle, baseUrl, api
setModalOpen(false);
};
const configContent = `# 9Router Configuration for Codex CLI
const getManualConfigs = () => {
const keyToUse = (selectedApiKey && selectedApiKey.trim())
? selectedApiKey
: (!cloudEnabled ? "sk_9router" : "<API_KEY_FROM_DASHBOARD>");
const configContent = `# 9Router Configuration for Codex CLI
model = "${selectedModel}"
model_provider = "9router"
@@ -133,22 +138,20 @@ base_url = "${baseUrl}/v1"
wire_api = "responses"
`;
const keyToUse = (selectedApiKey && selectedApiKey.trim())
? selectedApiKey
: (!cloudEnabled ? "sk_9router" : "<API_KEY_FROM_DASHBOARD>");
const authContent = JSON.stringify({
OPENAI_API_KEY: keyToUse
}, null, 2);
const authContent = JSON.stringify({
OPENAI_API_KEY: keyToUse
}, null, 2);
const copyToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text);
setCopiedConfig(true);
setTimeout(() => setCopiedConfig(false), 2000);
} catch (err) {
console.log("Failed to copy:", err);
}
return [
{
filename: "~/.codex/config.toml",
content: configContent,
},
{
filename: "~/.codex/auth.json",
content: authContent,
},
];
};
return (
@@ -257,39 +260,12 @@ wire_api = "responses"
<Button variant="outline" size="sm" onClick={handleResetSettings} disabled={!codexStatus.has9Router} loading={restoring}>
<span className="material-symbols-outlined text-[14px] mr-1">restore</span>Reset
</Button>
<Button variant="ghost" size="sm" onClick={checkCodexStatus}>
<span className="material-symbols-outlined text-[14px]">refresh</span>
<Button variant="ghost" size="sm" onClick={() => setShowManualConfigModal(true)}>
<span className="material-symbols-outlined text-[14px] mr-1">content_copy</span>Manual Config
</Button>
</div>
</>
)}
{/* Manual Config Section */}
<div className="pt-4 border-t border-border flex flex-col gap-3">
<p className="text-xs text-text-muted">Or copy config manually:</p>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-text-main">~/.codex/config.toml</span>
<Button variant="ghost" size="sm" onClick={() => copyToClipboard(configContent)}>
<span className="material-symbols-outlined text-[14px] mr-1">{copiedConfig ? "check" : "content_copy"}</span>
{copiedConfig ? "Copied!" : "Copy"}
</Button>
</div>
<pre className="px-3 py-2 bg-black/5 dark:bg-white/5 rounded font-mono text-xs overflow-x-auto whitespace-pre-wrap break-all max-h-32 overflow-y-auto">{configContent}</pre>
</div>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-text-main">~/.codex/auth.json</span>
<Button variant="ghost" size="sm" onClick={() => copyToClipboard(authContent)}>
<span className="material-symbols-outlined text-[14px] mr-1">{copiedConfig ? "check" : "content_copy"}</span>
{copiedConfig ? "Copied!" : "Copy"}
</Button>
</div>
<pre className="px-3 py-2 bg-black/5 dark:bg-white/5 rounded font-mono text-xs overflow-x-auto whitespace-pre-wrap break-all max-h-32 overflow-y-auto">{authContent}</pre>
</div>
</div>
</div>
)}
@@ -302,6 +278,13 @@ wire_api = "responses"
modelAliases={modelAliases}
title="Select Model for Codex"
/>
<ManualConfigModal
isOpen={showManualConfigModal}
onClose={() => setShowManualConfigModal(false)}
title="Codex CLI - Manual Configuration"
configs={getManualConfigs()}
/>
</Card>
);
}
@@ -0,0 +1,46 @@
"use client";
import { useState } from "react";
import Modal from "./Modal";
import Button from "./Button";
export default function ManualConfigModal({ isOpen, onClose, title = "Manual Configuration", configs = [] }) {
const [copiedIndex, setCopiedIndex] = useState(null);
const copyToClipboard = async (text, index) => {
try {
await navigator.clipboard.writeText(text);
setCopiedIndex(index);
setTimeout(() => setCopiedIndex(null), 2000);
} catch (err) {
console.log("Failed to copy:", err);
}
};
return (
<Modal isOpen={isOpen} onClose={onClose} title={title} size="xl">
<div className="flex flex-col gap-4">
{configs.map((config, index) => (
<div key={index} className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-text-main">{config.filename}</span>
<Button
variant="ghost"
size="sm"
onClick={() => copyToClipboard(config.content, index)}
>
<span className="material-symbols-outlined text-[14px] mr-1">
{copiedIndex === index ? "check" : "content_copy"}
</span>
{copiedIndex === index ? "Copied!" : "Copy"}
</Button>
</div>
<pre className="px-3 py-2 bg-black/5 dark:bg-white/5 rounded font-mono text-xs overflow-x-auto whitespace-pre-wrap break-all max-h-60 overflow-y-auto border border-border">
{config.content}
</pre>
</div>
))}
</div>
</Modal>
);
}
+1
View File
@@ -15,6 +15,7 @@ export { default as Header } from "./Header";
export { default as Footer } from "./Footer";
export { default as OAuthModal } from "./OAuthModal";
export { default as ModelSelectModal } from "./ModelSelectModal";
export { default as ManualConfigModal } from "./ManualConfigModal";
export { default as UsageStats } from "./UsageStats";
export { default as RequestLogger } from "./RequestLogger";
+7 -3
View File
@@ -61,19 +61,19 @@ export async function handleChat(request, clientRawRequest = null) {
return handleComboChat({
body,
models: comboModels,
handleSingleModel: (b, m) => handleSingleModelChat(b, m, clientRawRequest),
handleSingleModel: (b, m) => handleSingleModelChat(b, m, clientRawRequest, request),
log
});
}
// Single model request
return handleSingleModelChat(body, modelStr, clientRawRequest);
return handleSingleModelChat(body, modelStr, clientRawRequest, request);
}
/**
* Handle single model chat request
*/
async function handleSingleModelChat(body, modelStr, clientRawRequest = null) {
async function handleSingleModelChat(body, modelStr, clientRawRequest = null, request = null) {
const modelInfo = await getModelInfo(modelStr);
if (!modelInfo.provider) {
log.warn("CHAT", "Invalid model format", { model: modelStr });
@@ -89,6 +89,9 @@ async function handleSingleModelChat(body, modelStr, clientRawRequest = null) {
log.info("ROUTING", `Provider: ${provider}, Model: ${model}`);
}
// Extract userAgent from request
const userAgent = request?.headers?.get("user-agent") || "";
// Try with available accounts (fallback on errors)
let excludeConnectionId = null;
let lastError = null;
@@ -121,6 +124,7 @@ async function handleSingleModelChat(body, modelStr, clientRawRequest = null) {
log,
clientRawRequest,
connectionId: credentials.connectionId,
userAgent,
onCredentialsRefreshed: async (newCreds) => {
await updateProviderCredentials(credentials.connectionId, {
accessToken: newCreds.accessToken,