mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 16:13:34 +00:00
Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
316ddf284d | ||
|
|
5fc96c9007 | ||
|
|
9352b70df8 | ||
|
|
b4cfc1a5ee | ||
|
|
a07368b190 | ||
|
|
66bfb56694 | ||
|
|
3cb7a8f673 | ||
|
|
6edc623c13 | ||
|
|
027cd819f8 | ||
|
|
ef55e80c35 | ||
|
|
3666aac2a1 | ||
|
|
f58f75ae8b | ||
|
|
22885e0978 | ||
|
|
a988238bb4 | ||
|
|
11197139f9 | ||
|
|
9ccad00888 | ||
|
|
32ff6570cf | ||
|
|
80bb72ef79 | ||
|
|
e45f167d2b | ||
|
|
7e755916c0 | ||
|
|
5915b96d98 | ||
|
|
b327607be3 | ||
|
|
e23b5031ee | ||
|
|
104a08c75a | ||
|
|
ddc23e3800 | ||
|
|
a1959369c5 | ||
|
|
6c4c1dab3b |
No files matched your search
+42
-2
@@ -15,6 +15,7 @@ The OAuth system consists of three main components:
|
||||
- **GitHub** - Git repository hosting (with PKCE support)
|
||||
- **Netlify** - Static site deployment
|
||||
- **Vercel** - Static site deployment
|
||||
- **OpenRouter** - AI model routing (with PKCE support)
|
||||
|
||||
## File Structure
|
||||
|
||||
@@ -24,11 +25,13 @@ src/
|
||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
||||
│ ├── useVercelOAuth.ts # Vercel-specific configuration
|
||||
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
|
||||
├── pages/
|
||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
|
||||
│ └── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
|
||||
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
|
||||
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||
```
|
||||
|
||||
@@ -190,6 +193,7 @@ const config: OAuthConfig = {
|
||||
- ✅ GitHub - Supports PKCE (enabled)
|
||||
- ❌ Netlify - Doesn't support PKCE (disabled)
|
||||
- ❌ Vercel - Doesn't support PKCE (disabled)
|
||||
- ✅ OpenRouter - Requires PKCE (enabled)
|
||||
|
||||
### Scope Parameter
|
||||
|
||||
@@ -199,6 +203,42 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
|
||||
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
|
||||
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
||||
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
|
||||
- ❌ OpenRouter - No scope parameter (uses PKCE for authorization)
|
||||
|
||||
### OpenRouter Custom OAuth Implementation
|
||||
|
||||
OpenRouter uses a custom OAuth flow that differs from the standard OAuth 2.0 specification. Instead of using the generic `useOAuth` hook, it has a dedicated `useOpenRouterOAuth` hook with the following key differences:
|
||||
|
||||
1. **No Client Credentials**: OpenRouter doesn't require client ID or client secret - it uses PKCE only
|
||||
2. **Authorization URL**: Uses `callback_url` parameter instead of `redirect_uri`
|
||||
3. **Token Exchange**: Posts to `/api/v1/auth/keys` with a simplified request body
|
||||
4. **Response Format**: Returns `{ key }` instead of standard `{ access_token }`
|
||||
5. **PKCE Required**: Must use PKCE with S256 code challenge method
|
||||
6. **No User Info**: Doesn't provide a user info endpoint after authentication
|
||||
7. **No Environment Variables**: No configuration needed - works out of the box
|
||||
|
||||
**Authorization URL Format:**
|
||||
```
|
||||
https://openrouter.ai/auth?callback_url=<REDIRECT_URI>&code_challenge=<CHALLENGE>&code_challenge_method=S256
|
||||
```
|
||||
|
||||
**Token Exchange Request:**
|
||||
```json
|
||||
{
|
||||
"code": "<CODE_FROM_QUERY_PARAM>",
|
||||
"code_verifier": "<CODE_VERIFIER>",
|
||||
"code_challenge_method": "S256"
|
||||
}
|
||||
```
|
||||
|
||||
**Token Exchange Response:**
|
||||
```json
|
||||
{
|
||||
"key": "sk-or-v1-..."
|
||||
}
|
||||
```
|
||||
|
||||
This custom implementation is fully contained in `useOpenRouterOAuth.ts` and doesn't rely on the generic OAuth hook. Unlike other providers, OpenRouter's OAuth doesn't require any environment variables or application registration - it works immediately without configuration.
|
||||
|
||||
## Adding a New OAuth Provider
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"nostr": {
|
||||
"type": "local",
|
||||
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
-20
@@ -4488,7 +4488,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4502,7 +4501,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4516,7 +4514,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4530,7 +4527,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4544,7 +4540,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4558,7 +4553,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4572,7 +4566,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4586,7 +4579,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4600,7 +4592,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4614,7 +4605,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4628,7 +4618,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4642,7 +4631,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4656,7 +4644,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4670,7 +4657,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4684,7 +4670,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4698,7 +4683,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4712,7 +4696,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4726,7 +4709,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4740,7 +4722,6 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4754,7 +4735,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
+7
-6
@@ -24,8 +24,13 @@ export default {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
let hostname = url.hostname;
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
// GitHub hack: neutral color for light/dark mode
|
||||
if (url.hostname === 'github.com') {
|
||||
if (hostname === 'github.com') {
|
||||
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
|
||||
return new Response(svg.replaceAll('#24292E', '#808080'), {
|
||||
headers: { 'Content-Type': 'image/svg+xml' },
|
||||
@@ -33,20 +38,16 @@ export default {
|
||||
}
|
||||
|
||||
// AI-provider-specific hacks
|
||||
let hostname = url.hostname;
|
||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||
hostname = 'ollama.com';
|
||||
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
|
||||
hostname = 'claude.ai';
|
||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||
hostname = 'gemini.google.com';
|
||||
} else if (url.host === 'api.z.ai') {
|
||||
} else if (url.host === 'z.ai') {
|
||||
hostname = 'docs.z.ai';
|
||||
}
|
||||
|
||||
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
|
||||
hostname = hostname.replace(/^(ai\.|api\.)/, '');
|
||||
|
||||
// Fetch the favicon from DuckDuckGo's service
|
||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||
},
|
||||
|
||||
+9
-8
@@ -12,16 +12,17 @@ export default {
|
||||
return new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
||||
"access-control-allow-origin": "*",
|
||||
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
"access-control-allow-headers": "*", // Or specify specific headers
|
||||
"access-control-max-age": "86400", // Cache preflight for 24 hours
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
headers.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
headers.delete('origin');
|
||||
|
||||
const targetResponse = await fetch(target, {
|
||||
method: request.method,
|
||||
@@ -31,9 +32,9 @@ export default {
|
||||
|
||||
const response = new Response(targetResponse.body, targetResponse);
|
||||
|
||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
||||
response.headers.set("access-control-allow-origin", "*");
|
||||
response.headers.set("access-control-allow-methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||
response.headers.set("access-control-allow-headers", "*");
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import AboutSettings from "./pages/AboutSettings";
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
@@ -39,6 +40,7 @@ export function AppRouter() {
|
||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot } from 'lucide-react';
|
||||
import { Bot, ChevronDown } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
@@ -12,15 +12,31 @@ import {
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { PresetProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface OAuthHook {
|
||||
isOAuthConfigured: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
initiateOAuth: () => void;
|
||||
}
|
||||
|
||||
interface AddAIProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetProvider;
|
||||
isLoggedIntoNostr: boolean;
|
||||
oauthHook?: OAuthHook | null;
|
||||
forceManualEntry?: boolean;
|
||||
onSetForceManualEntry?: (force: boolean) => void;
|
||||
onAdd: (apiKey: string) => void;
|
||||
}
|
||||
|
||||
@@ -29,6 +45,9 @@ export function AddAIProviderDialog({
|
||||
onOpenChange,
|
||||
preset,
|
||||
isLoggedIntoNostr,
|
||||
oauthHook,
|
||||
forceManualEntry = false,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddAIProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -36,16 +55,27 @@ export function AddAIProviderDialog({
|
||||
const [termsAgreed, setTermsAgreed] = useState(false);
|
||||
|
||||
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
|
||||
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||
const oauthError = oauthHook?.error ?? null;
|
||||
|
||||
const handleAdd = () => {
|
||||
onAdd(apiKey);
|
||||
setApiKey('');
|
||||
setTermsAgreed(false);
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
// Reset state when dialog closes
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (!open) {
|
||||
setApiKey('');
|
||||
setTermsAgreed(false);
|
||||
}
|
||||
onOpenChange(open);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -73,6 +103,50 @@ export function AddAIProviderDialog({
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : isOAuthConfigured && !forceManualEntry ? (
|
||||
// Show OAuth button if OAuth is configured and not forced to manual
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-0">
|
||||
<Button
|
||||
onClick={() => oauthHook?.initiateOAuth()}
|
||||
disabled={isOAuthLoading}
|
||||
className="flex-1 rounded-r-none gap-2"
|
||||
variant="default"
|
||||
>
|
||||
{isOAuthLoading ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="default"
|
||||
className="rounded-l-none border-l border-primary-foreground/20 px-2"
|
||||
disabled={isOAuthLoading}
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry?.(true)}>
|
||||
Enter API key
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{oauthError && (
|
||||
<p className="text-sm text-destructive">
|
||||
{oauthError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{!preset.nostr && preset.apiKeysURL && (
|
||||
@@ -123,7 +197,7 @@ export function AddAIProviderDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!showNostrLoginRequired && (
|
||||
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
|
||||
@@ -28,7 +28,7 @@ interface OAuthHook {
|
||||
initiateOAuth: () => void;
|
||||
}
|
||||
|
||||
interface AddProviderDialogProps {
|
||||
interface AddDeployProviderDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
preset: PresetDeployProvider;
|
||||
@@ -39,7 +39,7 @@ interface AddProviderDialogProps {
|
||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
||||
}
|
||||
|
||||
export function AddProviderDialog({
|
||||
export function AddDeployProviderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
preset,
|
||||
@@ -48,7 +48,7 @@ export function AddProviderDialog({
|
||||
forceManualEntry,
|
||||
onSetForceManualEntry,
|
||||
onAdd,
|
||||
}: AddProviderDialogProps) {
|
||||
}: AddDeployProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [accountId, setAccountId] = useState('');
|
||||
@@ -112,16 +112,9 @@ export function AddProviderDialog({
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ExternalFavicon
|
||||
url={preset.baseURL}
|
||||
size={16}
|
||||
fallback={<Rocket size={16} />}
|
||||
/>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
</>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
@@ -84,8 +84,8 @@ export function AddGitCredentialDialog({
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{preset.id === 'github' && isOAuthConfigured && !forceManualEntry ? (
|
||||
// Special rendering for GitHub OAuth
|
||||
{isOAuthConfigured && !forceManualEntry ? (
|
||||
// Show OAuth button if OAuth is configured and not forced to manual
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-0">
|
||||
<Button
|
||||
@@ -100,16 +100,9 @@ export function AddGitCredentialDialog({
|
||||
Connecting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ExternalFavicon
|
||||
url="https://github.com"
|
||||
size={16}
|
||||
fallback={<GitBranch size={16} />}
|
||||
/>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to GitHub
|
||||
</span>
|
||||
</>
|
||||
<span className="truncate text-ellipsis overflow-hidden">
|
||||
Connect to {preset.name}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
@@ -124,7 +117,7 @@ export function AddGitCredentialDialog({
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
||||
Enter API key
|
||||
Enter token manually
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
@@ -136,7 +129,7 @@ export function AddGitCredentialDialog({
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// Standard token input
|
||||
// Show manual token input
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={t('enterToken')}
|
||||
@@ -153,7 +146,7 @@ export function AddGitCredentialDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!(preset.id === 'github' && isOAuthConfigured && !forceManualEntry) && (
|
||||
{!(isOAuthConfigured && !forceManualEntry) && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||
{t('cancel')}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey } from 'nostr-tools';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, Search, Coins } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -9,7 +9,7 @@ import { Card, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { ExternalInput } from '@/components/ui/external-input';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
@@ -465,37 +465,28 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
{/* API Key Input Section */}
|
||||
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
<h3 className="flex justify-center text-lg font-semibold gap-2">
|
||||
<ExternalFavicon
|
||||
url={selectedProvider.baseURL}
|
||||
size={16}
|
||||
fallback={<Bot size={16} />}
|
||||
/>
|
||||
<span>
|
||||
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedProvider.id === 'routstr' ? (
|
||||
t('requiresCashuToken', { providerName: selectedProvider.name })
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
|
||||
{selectedProvider.apiKeysURL ? (
|
||||
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
|
||||
{t('apiKey')}
|
||||
<ExternalLink className="inline-block h-4 w-4 ml-1" />
|
||||
</a>
|
||||
) : (
|
||||
t('apiKey')
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<PasswordInput
|
||||
</span>
|
||||
</h3>
|
||||
<ExternalInput
|
||||
type="password"
|
||||
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||
value={providerApiKey}
|
||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
||||
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
|
||||
handleContinueFromProviderSelection();
|
||||
}
|
||||
}}
|
||||
url={selectedProvider.apiKeysURL}
|
||||
urlTitle="Get Key"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -115,7 +115,7 @@ export function ProjectTitleMenu({
|
||||
className="gap-2"
|
||||
>
|
||||
<MessageSquarePlus className="h-4 w-4" />
|
||||
New Chat
|
||||
{t('newChat')}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
/** Visual divider between chat sessions */
|
||||
export function SessionDivider() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 text-xs text-muted-foreground py-4">
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
<span className="uppercase tracking-wide">
|
||||
{t('newChat', 'New chat')}
|
||||
</span>
|
||||
<div className="flex-1 h-px bg-border" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { ChevronDown, Play } from 'lucide-react';
|
||||
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
@@ -47,11 +47,12 @@ import OpenAI from 'openai';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { SessionDivider } from '@/components/SessionDivider';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { AIMessage } from '@/lib/SessionManager';
|
||||
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -294,9 +295,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
const {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionName,
|
||||
streamingMessage,
|
||||
isLoading: internalIsLoading,
|
||||
isLoadingHistory,
|
||||
hasMoreHistory,
|
||||
isLoadingMoreHistory,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
lastFinishReason,
|
||||
@@ -305,6 +310,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
startNewSession: internalStartNewSession,
|
||||
loadMoreHistory,
|
||||
} = useAIChat({
|
||||
projectId,
|
||||
tools,
|
||||
@@ -318,7 +324,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const checkTemplateInfo = async () => {
|
||||
try {
|
||||
// Only check if we have at least 1 message
|
||||
if (messages.length === 0) {
|
||||
if (displayMessages.length === 0) {
|
||||
setShowTemplateInfo(false);
|
||||
return;
|
||||
}
|
||||
@@ -357,7 +363,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
};
|
||||
|
||||
checkTemplateInfo();
|
||||
}, [fs, projectsPath, projectId, messages.length]);
|
||||
}, [fs, projectsPath, projectId, displayMessages.length]);
|
||||
|
||||
// Handle console error help requests
|
||||
const handleConsoleErrorHelp = useCallback(async () => {
|
||||
@@ -436,7 +442,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Function to scroll to bottom
|
||||
const scrollToBottom = useCallback(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||
requestAnimationFrame(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||
}
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -489,17 +499,20 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
useEffect(() => {
|
||||
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
||||
// Check if user was already at or near the bottom (within 100px threshold)
|
||||
const threshold = 100;
|
||||
const container = scrollAreaRef.current;
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
const isUserMessage = lastMessage?.role === 'user';
|
||||
|
||||
// Check if user was already near the bottom (within 100px threshold)
|
||||
const threshold = 100;
|
||||
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
||||
|
||||
// Only auto-scroll if user was already near the bottom
|
||||
if (isNearBottom) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
// Scroll to bottom if user sent a message or was already near the bottom
|
||||
if (isUserMessage || isNearBottom) {
|
||||
scrollToBottom();
|
||||
}
|
||||
}
|
||||
}, [messages, streamingMessage, isLoading]);
|
||||
}, [messages, streamingMessage, isLoading, scrollToBottom]);
|
||||
|
||||
// Scroll to bottom when first visiting a project (including page refresh)
|
||||
useEffect(() => {
|
||||
@@ -577,8 +590,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
// Scroll to bottom when user sends a message
|
||||
scrollToBottom();
|
||||
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, scrollToBottom]);
|
||||
|
||||
// Handle textarea focus - show onboarding if not configured
|
||||
const handleTextareaFocus = useCallback(() => {
|
||||
@@ -757,7 +773,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
)}
|
||||
|
||||
{/* Empty state when no messages and not loading */}
|
||||
{!isLoadingHistory && messages.length === 0 && !streamingMessage && !isLoading && (
|
||||
{!isLoadingHistory && displayMessages.length === 0 && !streamingMessage && !isLoading && (
|
||||
<div className="flex-1 flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||
<div className="mb-6">
|
||||
@@ -781,13 +797,49 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoadingHistory && messages.map((message, index) => {
|
||||
{/* Load older messages button */}
|
||||
{!isLoadingHistory && hasMoreHistory && (
|
||||
<div className="flex justify-center py-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
const container = scrollAreaRef.current;
|
||||
const oldScrollHeight = container?.scrollHeight || 0;
|
||||
await loadMoreHistory();
|
||||
// Preserve scroll position after prepending content
|
||||
if (container) {
|
||||
requestAnimationFrame(() => {
|
||||
container.scrollTop += container.scrollHeight - oldScrollHeight;
|
||||
});
|
||||
}
|
||||
}}
|
||||
disabled={isLoadingMoreHistory}
|
||||
className="gap-2 text-muted-foreground"
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
{isLoadingMoreHistory ? t('loading') : t('loadOlderMessages', 'Load older messages')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoadingHistory && displayMessages.map((message, index) => {
|
||||
// Get the current message's session ID and compare to previous
|
||||
const currentSessionId = (message as DisplayMessage).sessionId;
|
||||
const prevSessionId = index > 0 ? (displayMessages[index - 1] as DisplayMessage).sessionId : undefined;
|
||||
|
||||
// Show divider when session changes (not on first message)
|
||||
const showDivider = index > 0 && currentSessionId !== prevSessionId;
|
||||
|
||||
// Dim messages from older sessions (compare against current active session)
|
||||
const isOlderSession = currentSessionId !== sessionName;
|
||||
|
||||
// Find the corresponding tool call for tool messages
|
||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||
if (message.role === 'tool') {
|
||||
// Look backwards to find the assistant message with matching tool call
|
||||
for (let i = index - 1; i >= 0; i--) {
|
||||
const prevMessage = messages[i];
|
||||
const prevMessage = displayMessages[i];
|
||||
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
|
||||
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
||||
if (toolCall) break;
|
||||
@@ -796,14 +848,27 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return (
|
||||
<AIMessageItem
|
||||
<div
|
||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||
message={message}
|
||||
toolCall={toolCall}
|
||||
/>
|
||||
className={isOlderSession ? 'opacity-65' : ''}
|
||||
>
|
||||
{showDivider && <SessionDivider />}
|
||||
<AIMessageItem
|
||||
message={message}
|
||||
toolCall={toolCall}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Trailing session divider - shown when New Chat is clicked before sending a message */}
|
||||
{!isLoadingHistory && displayMessages.length > 0 && (() => {
|
||||
const lastSessionId = (displayMessages[displayMessages.length - 1] as DisplayMessage).sessionId;
|
||||
return sessionName && lastSessionId && sessionName !== lastSessionId ? (
|
||||
<SessionDivider key="trailing-divider" />
|
||||
) : null;
|
||||
})()}
|
||||
|
||||
{!isLoadingHistory && renderStreamingMessage()}
|
||||
|
||||
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { CloudUpload, Loader2, Check } from 'lucide-react';
|
||||
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
@@ -16,6 +16,8 @@ interface GitSyncButtonProps {
|
||||
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [syncSuccess, setSyncSuccess] = useState(false);
|
||||
const [showWarningPopover, setShowWarningPopover] = useState(false);
|
||||
const warningDismissed = useRef(false);
|
||||
|
||||
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
||||
const { getError, getState } = useGitSyncState();
|
||||
@@ -26,6 +28,18 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
const gitSyncState = getState(dir);
|
||||
const isGitActionOccurring = gitSyncState?.isActive ?? false;
|
||||
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
|
||||
const prevProjectId = useRef(projectId);
|
||||
|
||||
// Reset state when projectId changes
|
||||
useEffect(() => {
|
||||
if (prevProjectId.current !== projectId) {
|
||||
setSyncSuccess(false);
|
||||
setShowWarningPopover(false);
|
||||
warningDismissed.current = false;
|
||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||
prevProjectId.current = projectId;
|
||||
}
|
||||
}, [projectId, isGitActionOccurring]);
|
||||
|
||||
// Detect when a git action completes successfully
|
||||
useEffect(() => {
|
||||
@@ -38,6 +52,29 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||
}, [isGitActionOccurring, hasError]);
|
||||
|
||||
// Check if we need to show the warning popover
|
||||
const needsRemote = !isGitStatusLoading && gitStatus &&
|
||||
!gitStatus.remotes.find(r => r.name === 'origin') &&
|
||||
gitStatus.totalCommits > 1;
|
||||
|
||||
// Show warning popover when purple indicator is visible (only if not dismissed)
|
||||
useEffect(() => {
|
||||
if (needsRemote && !warningDismissed.current && gitStatus.totalCommits > 1) {
|
||||
setShowWarningPopover(true);
|
||||
} else {
|
||||
setShowWarningPopover(false);
|
||||
}
|
||||
}, [gitStatus?.totalCommits, needsRemote]);
|
||||
|
||||
// Handle button click - dismiss warning popover permanently
|
||||
const handleButtonClick = () => {
|
||||
if (showWarningPopover) {
|
||||
warningDismissed.current = true;
|
||||
setShowWarningPopover(false);
|
||||
}
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
// Determine which indicator to show (only one at a time, in priority order)
|
||||
const renderIndicator = () => {
|
||||
// Checkmark: sync just completed successfully - highest priority
|
||||
@@ -78,26 +115,61 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("size-8 p-0 group relative", className)}
|
||||
aria-label="Sync with Git"
|
||||
<>
|
||||
{/* Warning popover - shown when purple indicator is visible */}
|
||||
<Popover open={showWarningPopover} modal={false}>
|
||||
<PopoverTrigger asChild>
|
||||
<div className="relative">
|
||||
{/* Main Git Sync popover */}
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn("size-8 p-0 group relative", className)}
|
||||
aria-label="Sync with Git"
|
||||
onClick={handleButtonClick}
|
||||
>
|
||||
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||
{renderIndicator()}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-96"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
side="bottom"
|
||||
align="center"
|
||||
className="w-80 pointer-events-none z-40"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
>
|
||||
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
|
||||
{renderIndicator()}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-96"
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<div className="space-y-3 pointer-events-auto">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="size-5 text-primary shrink-0" />
|
||||
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleButtonClick}
|
||||
className="w-full"
|
||||
size="sm"
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+44
-2
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import type { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
import type { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
@@ -39,12 +39,16 @@ export function useAIChat({
|
||||
|
||||
// Split session state into individual variables for efficient updates
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [displayMessages, setDisplayMessages] = useState<DisplayMessage[]>([]);
|
||||
const [sessionName, setSessionName] = useState<string>('');
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [totalCost, setTotalCost] = useState<number>(0);
|
||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
||||
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
||||
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
|
||||
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
|
||||
|
||||
const initSession = useCallback(async () => {
|
||||
setIsLoadingHistory(true);
|
||||
@@ -53,11 +57,15 @@ export function useAIChat({
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||
// Initialize individual state variables from existing session
|
||||
setMessages([...session.messages]);
|
||||
setDisplayMessages([...session.displayMessages]);
|
||||
setSessionName(session.sessionName);
|
||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||
setIsLoading(session.isLoading);
|
||||
setTotalCost(session.totalCost || 0);
|
||||
setLastInputTokens(session.lastInputTokens || 0);
|
||||
setLastFinishReason(session.lastFinishReason ?? null);
|
||||
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
|
||||
} finally {
|
||||
setIsLoadingHistory(false);
|
||||
}
|
||||
@@ -123,6 +131,25 @@ export function useAIChat({
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('displayMessageAdded', (updatedProjectId: string, message: DisplayMessage) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setDisplayMessages(prev => [...prev, message]);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useSessionSubscription('displayMessagesPrepended', (updatedProjectId: string, newMessages: DisplayMessage[]) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setDisplayMessages(prev => [...newMessages, ...prev]);
|
||||
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||
}
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
useSessionSubscription('loadingMoreHistoryChanged', (updatedProjectId: string, loading: boolean) => {
|
||||
if (updatedProjectId === projectId) {
|
||||
setIsLoadingMoreHistory(loading);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||
@@ -164,7 +191,13 @@ export function useAIChat({
|
||||
const startNewSession = useCallback(async () => {
|
||||
await sessionManager.startNewSession(projectId);
|
||||
|
||||
// Reset individual state variables
|
||||
// Get the updated session to retrieve the new session name
|
||||
const session = sessionManager.getSession(projectId);
|
||||
if (session) {
|
||||
setSessionName(session.sessionName);
|
||||
}
|
||||
|
||||
// Reset only AI prompt state (not display state which is handled via events)
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setTotalCost(0);
|
||||
@@ -177,11 +210,19 @@ export function useAIChat({
|
||||
await startNewSession();
|
||||
}, [startNewSession]);
|
||||
|
||||
const loadMoreHistory = useCallback(async () => {
|
||||
await sessionManager.loadOlderSession(projectId);
|
||||
}, [projectId, sessionManager]);
|
||||
|
||||
return {
|
||||
messages,
|
||||
displayMessages,
|
||||
sessionName,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
isLoadingHistory,
|
||||
hasMoreHistory,
|
||||
isLoadingMoreHistory,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
lastFinishReason,
|
||||
@@ -191,6 +232,7 @@ export function useAIChat({
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
addMessage,
|
||||
loadMoreHistory,
|
||||
isConfigured,
|
||||
projectId
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
export interface OAuthConfig {
|
||||
provider: 'github' | 'netlify' | 'vercel';
|
||||
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
authorizeUrl: string;
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface OpenRouterTokenResponse {
|
||||
key: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for OpenRouter OAuth authentication with PKCE.
|
||||
* OpenRouter uses a custom OAuth flow that differs from standard OAuth 2.0.
|
||||
* It uses PKCE without requiring client credentials.
|
||||
*/
|
||||
export function useOpenRouterOAuth() {
|
||||
const { setProvider, isLoading: isSettingsLoading } = useAISettings();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// OpenRouter doesn't require client credentials - it uses PKCE only
|
||||
const isOAuthConfigured = true;
|
||||
|
||||
// Generate a cryptographically secure random string for PKCE code verifier
|
||||
const generateCodeVerifier = (): string => {
|
||||
const array = new Uint8Array(32);
|
||||
crypto.getRandomValues(array);
|
||||
return btoa(String.fromCharCode(...array))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
// Create SHA-256 hash of the code verifier for PKCE code challenge
|
||||
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => {
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(codeVerifier);
|
||||
const digest = await crypto.subtle.digest('SHA-256', data);
|
||||
return btoa(String.fromCharCode(...new Uint8Array(digest)))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
};
|
||||
|
||||
/**
|
||||
* Initiates the OAuth flow by redirecting to OpenRouter's authorization page.
|
||||
*/
|
||||
const initiateOAuth = useCallback(async () => {
|
||||
try {
|
||||
// Generate a random state parameter for security
|
||||
const state = crypto.randomUUID();
|
||||
const storagePrefix = 'openrouter_oauth';
|
||||
|
||||
// Store state for later verification
|
||||
localStorage.setItem(`${storagePrefix}_state`, state);
|
||||
|
||||
// Generate PKCE parameters
|
||||
const codeVerifier = generateCodeVerifier();
|
||||
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
||||
|
||||
localStorage.setItem(`${storagePrefix}_code_verifier`, codeVerifier);
|
||||
|
||||
// Build authorization URL
|
||||
const redirectUri = window.location.origin + '/oauth/openrouter';
|
||||
const params = new URLSearchParams({
|
||||
callback_url: redirectUri,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
|
||||
// Redirect to OpenRouter's authorization page
|
||||
window.location.href = `https://openrouter.ai/auth?${params.toString()}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to initiate OpenRouter OAuth:', error);
|
||||
setError('Failed to generate PKCE parameters. Please try again.');
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Handles the OAuth callback after the user authorizes the application.
|
||||
* Exchanges the authorization code for an API key.
|
||||
*/
|
||||
const handleCallback = useCallback(async (
|
||||
code: string,
|
||||
_state: string
|
||||
): Promise<boolean> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const storagePrefix = 'openrouter_oauth';
|
||||
|
||||
try {
|
||||
// Get PKCE code verifier
|
||||
const codeVerifier = localStorage.getItem(`${storagePrefix}_code_verifier`);
|
||||
if (!codeVerifier) {
|
||||
throw new Error('PKCE code verifier not found. Please restart the OAuth flow.');
|
||||
}
|
||||
|
||||
// Clean up stored values
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
|
||||
// Exchange code for API key using OpenRouter's custom endpoint
|
||||
const tokenResponse = await fetch('https://openrouter.ai/api/v1/auth/keys', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
code: code,
|
||||
code_verifier: codeVerifier,
|
||||
code_challenge_method: 'S256',
|
||||
}),
|
||||
});
|
||||
|
||||
if (!tokenResponse.ok) {
|
||||
const errorText = await tokenResponse.text();
|
||||
throw new Error(`OpenRouter token exchange failed: ${tokenResponse.statusText} - ${errorText}`);
|
||||
}
|
||||
|
||||
const tokenData: OpenRouterTokenResponse = await tokenResponse.json();
|
||||
|
||||
if (!tokenData.key) {
|
||||
throw new Error('No API key received from OpenRouter');
|
||||
}
|
||||
|
||||
// Wait for settings to be initialized before storing
|
||||
if (isSettingsLoading) {
|
||||
throw new Error('Settings not initialized. Please try again.');
|
||||
}
|
||||
|
||||
// Create a new OpenRouter provider with the OAuth token
|
||||
const newProvider: AIProvider = {
|
||||
id: 'openrouter',
|
||||
name: 'OpenRouter',
|
||||
baseURL: 'https://openrouter.ai/api/v1',
|
||||
apiKey: tokenData.key,
|
||||
};
|
||||
|
||||
// Add or update the OpenRouter provider in settings
|
||||
setProvider(newProvider);
|
||||
|
||||
setIsLoading(false);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('OpenRouter OAuth error:', error);
|
||||
|
||||
// Clean up any remaining OAuth data on error
|
||||
localStorage.removeItem(`${storagePrefix}_state`);
|
||||
localStorage.removeItem(`${storagePrefix}_code_verifier`);
|
||||
|
||||
setError(error instanceof Error ? error.message : 'OAuth authentication failed');
|
||||
setIsLoading(false);
|
||||
return false;
|
||||
}
|
||||
}, [setProvider, isSettingsLoading]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
isOAuthConfigured,
|
||||
initiateOAuth,
|
||||
handleCallback,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -27,73 +27,6 @@ describe('DotAI', () => {
|
||||
dotAI = new DotAI(mockFS, '/test-project');
|
||||
});
|
||||
|
||||
describe('readLastSessionHistory', () => {
|
||||
it('should return null when history directory does not exist', async () => {
|
||||
// Mock historyDirExists to return false
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(false);
|
||||
|
||||
const result = await dotAI.readLastSessionHistory();
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null when no session files exist', async () => {
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
// Mock readdir to return empty array
|
||||
vi.mocked(mockFS.readdir).mockResolvedValue([]);
|
||||
|
||||
const result = await dotAI.readLastSessionHistory();
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should return messages and session name from most recent file', async () => {
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
// Mock readdir to return session files
|
||||
vi.mocked(mockFS.readdir).mockResolvedValue([
|
||||
'2024-08-24T16-30-45Z-abc.jsonl',
|
||||
'2024-08-24T17-15-22Z-def.jsonl', // This should be the most recent
|
||||
'2024-08-24T15-00-00Z-xyz.jsonl'
|
||||
]);
|
||||
|
||||
// Mock readFile to return JSONL content
|
||||
const mockContent = `{"role":"user","content":"Hello"}
|
||||
{"role":"assistant","content":"Hi there!"}`;
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
|
||||
|
||||
const result = await dotAI.readLastSessionHistory();
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.sessionName).toBe('2024-08-24T17-15-22Z-def');
|
||||
expect(result?.messages).toHaveLength(2);
|
||||
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
|
||||
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
|
||||
});
|
||||
|
||||
it('should handle malformed JSON lines gracefully', async () => {
|
||||
// Mock historyDirExists to return true
|
||||
vi.spyOn(dotAI, 'historyDirExists').mockResolvedValue(true);
|
||||
|
||||
// Mock readdir to return session files
|
||||
vi.mocked(mockFS.readdir).mockResolvedValue(['session.jsonl']);
|
||||
|
||||
// Mock readFile to return content with malformed JSON
|
||||
const mockContent = `{"role":"user","content":"Hello"}
|
||||
invalid json line
|
||||
{"role":"assistant","content":"Hi there!"}`;
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(mockContent);
|
||||
|
||||
const result = await dotAI.readLastSessionHistory();
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.messages).toHaveLength(2); // Should skip the malformed line
|
||||
expect(result?.messages[0]).toEqual({ role: 'user', content: 'Hello' });
|
||||
expect(result?.messages[1]).toEqual({ role: 'assistant', content: 'Hi there!' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('setHistory', () => {
|
||||
it('should create history directory if it does not exist', async () => {
|
||||
// Mock historyDirExists to return false initially
|
||||
|
||||
+34
-50
@@ -216,66 +216,50 @@ export class DotAI {
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the most recent session history
|
||||
* @returns Object containing messages array and session name, or null if no history found
|
||||
* List all session names sorted chronologically (oldest first)
|
||||
* Fast operation - does not load message content
|
||||
* @returns Array of session names (filenames without .jsonl extension)
|
||||
*/
|
||||
async readLastSessionHistory(): Promise<{
|
||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||
sessionName: string;
|
||||
} | null> {
|
||||
async listSessionNames(): Promise<string[]> {
|
||||
try {
|
||||
// Check if history directory exists
|
||||
if (!(await this.historyDirExists())) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
|
||||
// Find the most recent session file
|
||||
try {
|
||||
const files = await this.fs.readdir(this.historyDir);
|
||||
const sessionFiles = files
|
||||
.filter(file => file.endsWith('.jsonl'))
|
||||
.sort()
|
||||
.reverse(); // Most recent first
|
||||
const files = await this.fs.readdir(this.historyDir);
|
||||
return files
|
||||
.filter(file => file.endsWith('.jsonl'))
|
||||
.map(file => file.replace('.jsonl', ''))
|
||||
.sort(); // Chronological order (oldest first) - filenames contain timestamps
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
if (sessionFiles.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const latestSessionFile = sessionFiles[0];
|
||||
const sessionPath = join(this.historyDir, latestSessionFile);
|
||||
/**
|
||||
* Read messages for a single session
|
||||
* @param sessionName The session name (filename without .jsonl)
|
||||
* @returns Array of messages, or empty array if session not found
|
||||
*/
|
||||
async readSessionHistory(sessionName: string): Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam[]> {
|
||||
try {
|
||||
const sessionPath = join(this.historyDir, sessionName + '.jsonl');
|
||||
const content = await this.fs.readFile(sessionPath, 'utf8');
|
||||
const lines = content.trim().split('\n').filter(line => line.trim());
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const content = await this.fs.readFile(sessionPath, 'utf8');
|
||||
const lines = content.trim().split('\n').filter(line => line.trim());
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
messages.push(message);
|
||||
} catch (parseError) {
|
||||
console.warn('Failed to parse message from history:', parseError);
|
||||
}
|
||||
}
|
||||
|
||||
// Return session name without .jsonl extension
|
||||
const sessionName = latestSessionFile.replace('.jsonl', '');
|
||||
|
||||
return {
|
||||
messages,
|
||||
sessionName
|
||||
};
|
||||
} catch (readError) {
|
||||
console.warn('Failed to read session file:', readError);
|
||||
return null;
|
||||
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
messages.push(message);
|
||||
} catch {
|
||||
// Skip malformed lines
|
||||
}
|
||||
} catch (readdirError) {
|
||||
console.warn('Failed to read history directory:', readdirError);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to read last session history:', error);
|
||||
return null;
|
||||
|
||||
return messages;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+140
-24
@@ -24,12 +24,20 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
};
|
||||
|
||||
/** AIMessage with session tracking for UI display */
|
||||
export type DisplayMessage = AIMessage & {
|
||||
sessionId?: string; // Session identifier for grouping messages in UI
|
||||
};
|
||||
|
||||
export interface SessionState {
|
||||
projectId: string;
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools: Record<string, Tool<unknown>>;
|
||||
maxSteps?: number;
|
||||
messages: AIMessage[];
|
||||
messages: AIMessage[]; // Current session messages (sent to AI)
|
||||
displayMessages: DisplayMessage[]; // All messages from all sessions (for UI, with sessionId)
|
||||
availableSessionNames: string[]; // All session names (for lazy loading)
|
||||
loadedSessionCount: number; // How many sessions loaded from the end
|
||||
streamingMessage?: {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
@@ -37,6 +45,7 @@ export interface SessionState {
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
};
|
||||
isLoading: boolean;
|
||||
isLoadingMoreHistory: boolean; // Loading older sessions
|
||||
sessionName: string;
|
||||
lastActivity: Date;
|
||||
abortController?: AbortController;
|
||||
@@ -50,8 +59,11 @@ export interface SessionManagerEvents {
|
||||
sessionCreated: (projectId: string) => void;
|
||||
sessionDeleted: (projectId: string) => void;
|
||||
messageAdded: (projectId: string, message: AIMessage) => void;
|
||||
displayMessageAdded: (projectId: string, message: DisplayMessage) => void;
|
||||
displayMessagesPrepended: (projectId: string, messages: DisplayMessage[]) => void;
|
||||
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
|
||||
costUpdated: (projectId: string, totalCost: number) => void;
|
||||
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
||||
fileChanged: (projectId: string, filePath: string) => void;
|
||||
@@ -97,7 +109,7 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session for a project
|
||||
* Create a new session for a project (lazy loading - only loads most recent session)
|
||||
*/
|
||||
async loadSession(
|
||||
projectId: string,
|
||||
@@ -105,18 +117,39 @@ export class SessionManager {
|
||||
customTools: Record<string, Tool<unknown>>,
|
||||
maxSteps?: number
|
||||
): Promise<SessionState> {
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
const messages: AIMessage[] = [];
|
||||
const displayMessages: DisplayMessage[] = [];
|
||||
let sessionName = DotAI.generateSessionName();
|
||||
let availableSessionNames: string[] = [];
|
||||
let loadedSessionCount = 0;
|
||||
let lastFinishReason: string | null | undefined;
|
||||
|
||||
// Try to load existing history
|
||||
// Try to load existing history (lazy - only load last session)
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
messages = lastSession.messages;
|
||||
sessionName = lastSession.sessionName;
|
||||
|
||||
// Get all available session names (fast - no content loading)
|
||||
availableSessionNames = await dotAI.listSessionNames();
|
||||
|
||||
if (availableSessionNames.length > 0) {
|
||||
// Only load the most recent session
|
||||
const lastSessionName = availableSessionNames[availableSessionNames.length - 1];
|
||||
const lastSessionMessages = await dotAI.readSessionHistory(lastSessionName);
|
||||
|
||||
if (lastSessionMessages.length > 0) {
|
||||
// Add messages with sessionId annotation
|
||||
for (const msg of lastSessionMessages) {
|
||||
displayMessages.push({
|
||||
...msg as AIMessage,
|
||||
sessionId: lastSessionName,
|
||||
});
|
||||
}
|
||||
|
||||
messages.push(...lastSessionMessages as AIMessage[]);
|
||||
sessionName = lastSessionName;
|
||||
loadedSessionCount = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Load last finish reason
|
||||
@@ -131,21 +164,33 @@ export class SessionManager {
|
||||
customTools,
|
||||
maxSteps,
|
||||
isLoading: false,
|
||||
isLoadingMoreHistory: false,
|
||||
lastActivity: new Date(),
|
||||
totalCost: 0,
|
||||
lastInputTokens: 0,
|
||||
lastFinishReason,
|
||||
...this.sessions.get(projectId),
|
||||
messages,
|
||||
displayMessages,
|
||||
availableSessionNames,
|
||||
loadedSessionCount,
|
||||
sessionName,
|
||||
};
|
||||
|
||||
// Update session configuration
|
||||
session.projectId = projectId;
|
||||
session.tools = tools;
|
||||
|
||||
session.customTools = customTools;
|
||||
session.maxSteps = maxSteps;
|
||||
|
||||
// Update messages from loaded history if not already set by an existing session
|
||||
if (!this.sessions.has(projectId)) {
|
||||
session.messages = messages;
|
||||
session.displayMessages = displayMessages;
|
||||
session.availableSessionNames = availableSessionNames;
|
||||
session.loadedSessionCount = loadedSessionCount;
|
||||
session.sessionName = sessionName;
|
||||
}
|
||||
|
||||
this.sessions.set(projectId, session);
|
||||
|
||||
@@ -187,11 +232,69 @@ export class SessionManager {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
// Add to current session messages (for AI prompts)
|
||||
session.messages.push(message);
|
||||
|
||||
// Also add to display messages with session ID annotation (for UI)
|
||||
const displayMessage: DisplayMessage = { ...message, sessionId: session.sessionName };
|
||||
session.displayMessages.push(displayMessage);
|
||||
|
||||
session.lastActivity = new Date();
|
||||
|
||||
await this.saveSessionHistory(projectId);
|
||||
this.emit('messageAdded', projectId, message);
|
||||
this.emit('displayMessageAdded', projectId, displayMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there are more historical sessions to load
|
||||
*/
|
||||
hasMoreHistory(projectId: string): boolean {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return false;
|
||||
return session.loadedSessionCount < session.availableSessionNames.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the next older session and prepend to displayMessages
|
||||
*/
|
||||
async loadOlderSession(projectId: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session || !this.hasMoreHistory(projectId) || session.isLoadingMoreHistory) return;
|
||||
|
||||
session.isLoadingMoreHistory = true;
|
||||
this.emit('loadingMoreHistoryChanged', projectId, true);
|
||||
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
|
||||
// Get the next older session (counting from the end)
|
||||
const nextIndex = session.availableSessionNames.length - session.loadedSessionCount - 1;
|
||||
if (nextIndex < 0) return;
|
||||
|
||||
const olderSessionName = session.availableSessionNames[nextIndex];
|
||||
const olderMessages = await dotAI.readSessionHistory(olderSessionName);
|
||||
|
||||
if (olderMessages.length > 0) {
|
||||
// Create display messages with sessionId
|
||||
const newDisplayMessages: DisplayMessage[] = olderMessages.map(msg => ({
|
||||
...msg as AIMessage,
|
||||
sessionId: olderSessionName,
|
||||
}));
|
||||
|
||||
// Prepend to displayMessages
|
||||
session.displayMessages = [...newDisplayMessages, ...session.displayMessages];
|
||||
session.loadedSessionCount++;
|
||||
|
||||
this.emit('displayMessagesPrepended', projectId, newDisplayMessages);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load older session:', error);
|
||||
} finally {
|
||||
session.isLoadingMoreHistory = false;
|
||||
this.emit('loadingMoreHistoryChanged', projectId, false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -450,7 +553,7 @@ export class SessionManager {
|
||||
|
||||
let accumulatedContent = '';
|
||||
let accumulatedReasoningContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
@@ -491,20 +594,29 @@ export class SessionManager {
|
||||
const toolCallDelta = delta.tool_calls[i];
|
||||
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||
|
||||
accumulatedToolCalls[index] ??= {
|
||||
id: '',
|
||||
type: 'function',
|
||||
function: { name: '', arguments: '' }
|
||||
};
|
||||
let toolCall = accumulatedToolCalls.get(index);
|
||||
|
||||
if (!toolCall) {
|
||||
toolCall = {
|
||||
id: '',
|
||||
type: 'function',
|
||||
function: { name: '', arguments: '' },
|
||||
};
|
||||
}
|
||||
|
||||
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
|
||||
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
|
||||
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
|
||||
|
||||
accumulatedToolCalls.set(index, toolCall);
|
||||
}
|
||||
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
||||
if (session.streamingMessage && accumulatedToolCalls.size > 0) {
|
||||
const sortedToolCalls = [...accumulatedToolCalls.entries()]
|
||||
.sort((a, b) => a[0] - b[0])
|
||||
.map(entry => entry[1]);
|
||||
|
||||
session.streamingMessage.tool_calls = sortedToolCalls;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
@@ -528,7 +640,7 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Fix tool calls with empty arguments or names
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
for (const toolCall of accumulatedToolCalls.values()) {
|
||||
if (toolCall.type === 'function') {
|
||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||
|
||||
@@ -549,7 +661,7 @@ export class SessionManager {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
...(accumulatedToolCalls.size > 0 && { tool_calls: [...accumulatedToolCalls.values()] })
|
||||
};
|
||||
|
||||
// Check if the assistant message is empty (no content, reasoning, or tool calls)
|
||||
@@ -575,8 +687,8 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Handle tool calls
|
||||
if (accumulatedToolCalls?.length) {
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (accumulatedToolCalls?.size) {
|
||||
for (const toolCall of accumulatedToolCalls.values()) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
@@ -690,7 +802,7 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new session (clear messages but keep configuration)
|
||||
* Start a new session (clear AI messages but keep display history)
|
||||
*/
|
||||
async startNewSession(projectId: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
@@ -698,9 +810,13 @@ export class SessionManager {
|
||||
|
||||
this.stopGeneration(projectId);
|
||||
|
||||
// Generate new session name - new messages will automatically get this sessionId
|
||||
const newSessionName = DotAI.generateSessionName();
|
||||
|
||||
// Clear only the AI prompt messages (not display messages)
|
||||
session.messages = [];
|
||||
session.streamingMessage = undefined;
|
||||
session.sessionName = DotAI.generateSessionName();
|
||||
session.sessionName = newSessionName;
|
||||
session.lastActivity = new Date();
|
||||
session.totalCost = 0;
|
||||
session.lastInputTokens = 0;
|
||||
|
||||
+41
-4
@@ -58,14 +58,51 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
|
||||
= openai.chat.completions.create.bind(openai.chat.completions);
|
||||
|
||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||
// OpenRouter usage accounting
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
if (provider.id === 'openrouter') {
|
||||
// OpenRouter-specific hacks
|
||||
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||
// Usage accounting field to get token usage and cost per request
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
|
||||
// Prompt caching for Claude models
|
||||
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
|
||||
if (body.model.startsWith("anthropic/")) {
|
||||
// First normalize the message history to use content blocks
|
||||
body.messages = structuredClone(body.messages);
|
||||
body.messages = body.messages.map((m) => {
|
||||
if (m.role !== "function" && typeof m.content === "string") {
|
||||
return { ...m, content: [{ type: "text", text: m.content }] };
|
||||
} else {
|
||||
return m;
|
||||
}
|
||||
});
|
||||
|
||||
const systemMessage = body.messages.find((m) => m.role === "system");
|
||||
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
|
||||
const lastTwoMessages = nonSystemMessages.slice(-2);
|
||||
|
||||
if (systemMessage) {
|
||||
addCacheControl(systemMessage);
|
||||
}
|
||||
for (const msg of lastTwoMessages) {
|
||||
addCacheControl(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return createCompletion(body, options);
|
||||
}) as typeof createCompletion;
|
||||
|
||||
return openai;
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
|
||||
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
|
||||
if (Array.isArray(msg.content)) {
|
||||
const lastTextBlock = msg.content.findLast((b) => b.type === "text");
|
||||
if (lastTextBlock) {
|
||||
(lastTextBlock as { cache_control?: { type: "ephemeral" } })
|
||||
.cache_control = { type: "ephemeral" };
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -23,6 +23,14 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
tosURL: "https://openrouter.ai/terms",
|
||||
},
|
||||
{
|
||||
id: "opencode",
|
||||
name: "OpenCode Zen",
|
||||
baseURL: "https://opencode.ai/zen/v1",
|
||||
apiKeysURL: "https://opencode.ai/auth",
|
||||
tosURL: "https://opencode.ai/legal/terms-of-service",
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
|
||||
+7
-18
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Anonymous",
|
||||
"logIn": "Log in",
|
||||
"signUp": "Sign up",
|
||||
"newChat": "New Chat",
|
||||
"loadOlderMessages": "Load older messages",
|
||||
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
||||
"theme": "Theme",
|
||||
"themeDescription": "Choose between light, dark, or system theme preference.",
|
||||
@@ -54,12 +56,9 @@
|
||||
"showcaseModerator": "Showcase Moderator",
|
||||
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
|
||||
"filesystemPaths": "Filesystem Paths",
|
||||
"projectsDirectory": "Projects Directory",
|
||||
"projectsDirectoryDescription": "Filesystem path where projects are stored",
|
||||
"configDirectory": "Config Directory",
|
||||
"configDirectoryDescription": "Filesystem path where configuration files are stored",
|
||||
"temporaryDirectory": "Temporary Directory",
|
||||
"temporaryDirectoryDescription": "Filesystem path for temporary files",
|
||||
"projectsDirectory": "Projects",
|
||||
"configDirectory": "Config",
|
||||
"temporaryDirectory": "Temporary",
|
||||
"sentryDsn": "Sentry DSN",
|
||||
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
||||
"shareErrorReports": "Share error reports",
|
||||
@@ -484,8 +483,7 @@
|
||||
"skills": "Skills",
|
||||
"noSkillsFound": "No skills found in this plugin.",
|
||||
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
||||
"pluginsDirectory": "Plugins Directory",
|
||||
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
|
||||
"pluginsDirectory": "Plugins",
|
||||
"discoverPlugins": "Discover Plugins",
|
||||
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
|
||||
"searchPlugins": "Search plugins...",
|
||||
@@ -526,21 +524,12 @@
|
||||
"discoveringTools": "Discovering tools...",
|
||||
"toolsDiscovered": "{{count}} tool(s) discovered",
|
||||
"toolDiscoveryFailed": "Failed to discover tools from this server",
|
||||
"filesystemPaths": "Filesystem Paths",
|
||||
"projectsDirectory": "Projects Directory",
|
||||
"projectsDirectoryDescription": "Directory where projects are stored in the virtual filesystem.",
|
||||
"configDirectory": "Config Directory",
|
||||
"configDirectoryDescription": "Directory where configuration files are stored in the virtual filesystem.",
|
||||
"temporaryDirectory": "Temporary Directory",
|
||||
"temporaryDirectoryDescription": "Directory for temporary files in the virtual filesystem.",
|
||||
"deleting": "Deleting...",
|
||||
"modified": "Modified",
|
||||
"restoreToDefault": "Restore to default",
|
||||
"restoredToDefault": "Restored to Default",
|
||||
"templateUpdateFailed": "Template Update Failed",
|
||||
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
|
||||
"templatesDirectory": "Templates Directory",
|
||||
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
|
||||
"templatesDirectory": "Templates",
|
||||
"terminal": "Terminal",
|
||||
"templateName": "Template Name",
|
||||
"templateDescription": "Description",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Maras Suna",
|
||||
"logIn": "Shiga",
|
||||
"signUp": "Yi Rajista",
|
||||
"newChat": "Sabon Tattaunawa",
|
||||
"loadOlderMessages": "Loda saƙonni masu tsufa",
|
||||
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
||||
"theme": "Jigogi",
|
||||
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Onye na-amaghị aha",
|
||||
"logIn": "Banye",
|
||||
"signUp": "Debanye aha",
|
||||
"newChat": "Nkata Ọhụrụ",
|
||||
"loadOlderMessages": "Bulite ozi ochie",
|
||||
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
||||
"theme": "Isiokwu",
|
||||
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Anônimo",
|
||||
"logIn": "Entrar",
|
||||
"signUp": "Cadastrar",
|
||||
"newChat": "Nova Conversa",
|
||||
"loadOlderMessages": "Carregar mensagens anteriores",
|
||||
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
||||
"theme": "Tema",
|
||||
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "Alainidamọ",
|
||||
"logIn": "Wọle",
|
||||
"signUp": "Forukọsilẹ",
|
||||
"newChat": "Ọrọ Tuntun",
|
||||
"loadOlderMessages": "Gbe awọn ifiranṣẹ atijọ",
|
||||
"preferencesDescription": "Ṣakoso awọn ayanfẹ ohun elo rẹ ati awọn eto iwoye.",
|
||||
"theme": "Akori",
|
||||
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
"anonymous": "匿名",
|
||||
"logIn": "登录",
|
||||
"signUp": "注册",
|
||||
"newChat": "新对话",
|
||||
"loadOlderMessages": "加载更早的消息",
|
||||
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
||||
"theme": "主题",
|
||||
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
||||
|
||||
@@ -16,6 +16,7 @@ import { CreditsBadge } from '@/components/CreditsBadge';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
|
||||
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
@@ -45,6 +46,7 @@ export function AISettings() {
|
||||
const { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const { config, defaultConfig, updateConfig } = useAppContext();
|
||||
const openRouterOAuth = useOpenRouterOAuth();
|
||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
||||
|
||||
@@ -54,6 +56,7 @@ export function AISettings() {
|
||||
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
|
||||
const [forceManualEntry, setForceManualEntry] = useState(false);
|
||||
|
||||
// Drag and drop sensors
|
||||
const sensors = useSensors(
|
||||
@@ -256,9 +259,18 @@ export function AISettings() {
|
||||
{selectedPreset && (
|
||||
<AddAIProviderDialog
|
||||
open={addDialogOpen}
|
||||
onOpenChange={setAddDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAddDialogOpen(open);
|
||||
if (!open) {
|
||||
// Reset force manual entry when dialog closes
|
||||
setForceManualEntry(false);
|
||||
}
|
||||
}}
|
||||
preset={selectedPreset}
|
||||
isLoggedIntoNostr={!!user}
|
||||
oauthHook={selectedPreset.id === 'openrouter' ? openRouterOAuth : null}
|
||||
forceManualEntry={forceManualEntry}
|
||||
onSetForceManualEntry={setForceManualEntry}
|
||||
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||
import { AddProviderDialog } from '@/components/AddProviderDialog';
|
||||
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
|
||||
import {
|
||||
DndContext,
|
||||
@@ -384,7 +384,7 @@ export function DeploySettings() {
|
||||
|
||||
{/* Add Preset Provider Dialog */}
|
||||
{selectedPreset && (
|
||||
<AddProviderDialog
|
||||
<AddDeployProviderDialog
|
||||
open={addDialogOpen}
|
||||
onOpenChange={setAddDialogOpen}
|
||||
preset={selectedPreset}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Bot } from 'lucide-react';
|
||||
|
||||
export default function OpenRouterOAuth() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { handleCallback } = useOpenRouterOAuth();
|
||||
const { isLoading: isSettingsLoading } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
// Wait for AI settings to be initialized
|
||||
if (isSettingsLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
const code = searchParams.get('code');
|
||||
const state = searchParams.get('state');
|
||||
const error = searchParams.get('error');
|
||||
const errorDescription = searchParams.get('error_description');
|
||||
const storedCodeVerifier = localStorage.getItem('openrouter_oauth_code_verifier');
|
||||
|
||||
// Handle OAuth errors
|
||||
if (error) {
|
||||
toast({
|
||||
title: "OpenRouter OAuth Error",
|
||||
description: errorDescription || error,
|
||||
variant: "destructive",
|
||||
});
|
||||
navigate('/settings/ai');
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle successful OAuth callback
|
||||
if (code && storedCodeVerifier) {
|
||||
handleCallback(code, state || '').then((success) => {
|
||||
if (success) {
|
||||
toast({
|
||||
title: "OpenRouter Connected",
|
||||
description: "Successfully connected to OpenRouter. You can now use OpenRouter models.",
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Connection Failed",
|
||||
description: "Failed to connect to OpenRouter. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
// Always redirect to AI settings after handling the callback
|
||||
navigate('/settings/ai');
|
||||
});
|
||||
} else if (code && !storedCodeVerifier) {
|
||||
// Missing code verifier - likely an incomplete PKCE flow
|
||||
toast({
|
||||
title: "Authentication Error",
|
||||
description: "OAuth flow is incomplete. Please try connecting to OpenRouter again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
// Clean up any remaining OAuth data
|
||||
localStorage.removeItem('openrouter_oauth_state');
|
||||
localStorage.removeItem('openrouter_oauth_code_verifier');
|
||||
navigate('/settings/ai');
|
||||
} else {
|
||||
// No code parameter - redirect to AI settings
|
||||
navigate('/settings/ai');
|
||||
}
|
||||
}, [searchParams, handleCallback, toast, navigate, isSettingsLoading]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardContent className="py-12 px-8 text-center">
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-center">
|
||||
<Bot className="h-12 w-12 text-primary" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-xl font-semibold">Connecting to OpenRouter</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Processing your OpenRouter authentication...
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex justify-center">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -257,6 +257,7 @@ export function SystemSettings() {
|
||||
icon={Settings}
|
||||
titleKey="systemSettings"
|
||||
descriptionKey="systemSettingsDescription"
|
||||
className="space-y-2"
|
||||
>
|
||||
{/* Service Worker Configuration */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
@@ -767,7 +768,7 @@ export function SystemSettings() {
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="py-1 space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 py-1">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
||||
@@ -804,9 +805,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('projectsDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -845,9 +843,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('configDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -886,9 +881,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('temporaryDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -927,9 +919,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('pluginsDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
@@ -968,9 +957,6 @@ export function SystemSettings() {
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('templatesDirectoryDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
|
||||
Reference in new issue
Block a user