mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23: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)
|
- **GitHub** - Git repository hosting (with PKCE support)
|
||||||
- **Netlify** - Static site deployment
|
- **Netlify** - Static site deployment
|
||||||
- **Vercel** - Static site deployment
|
- **Vercel** - Static site deployment
|
||||||
|
- **OpenRouter** - AI model routing (with PKCE support)
|
||||||
|
|
||||||
## File Structure
|
## File Structure
|
||||||
|
|
||||||
@@ -24,11 +25,13 @@ src/
|
|||||||
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
|
||||||
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
|
||||||
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
|
||||||
│ └── useVercelOAuth.ts # Vercel-specific configuration
|
│ ├── useVercelOAuth.ts # Vercel-specific configuration
|
||||||
|
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
|
||||||
├── pages/
|
├── pages/
|
||||||
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
|
||||||
│ ├── NetlifyOAuth.tsx # Netlify 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
|
└── AppRouter.tsx # Routes for OAuth callbacks
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -190,6 +193,7 @@ const config: OAuthConfig = {
|
|||||||
- ✅ GitHub - Supports PKCE (enabled)
|
- ✅ GitHub - Supports PKCE (enabled)
|
||||||
- ❌ Netlify - Doesn't support PKCE (disabled)
|
- ❌ Netlify - Doesn't support PKCE (disabled)
|
||||||
- ❌ Vercel - Doesn't support PKCE (disabled)
|
- ❌ Vercel - Doesn't support PKCE (disabled)
|
||||||
|
- ✅ OpenRouter - Requires PKCE (enabled)
|
||||||
|
|
||||||
### Scope Parameter
|
### 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`)
|
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
|
||||||
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
- ❌ Netlify - No scope parameter (permissions set in app settings)
|
||||||
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
|
- ✅ 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
|
## 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": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4502,7 +4501,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4516,7 +4514,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4530,7 +4527,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4544,7 +4540,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4558,7 +4553,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4572,7 +4566,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4586,7 +4579,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4600,7 +4592,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4614,7 +4605,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4628,7 +4618,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"loong64"
|
"loong64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4642,7 +4631,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4656,7 +4644,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4670,7 +4657,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4684,7 +4670,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4698,7 +4683,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4712,7 +4696,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4726,7 +4709,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4740,7 +4722,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ia32"
|
"ia32"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4754,7 +4735,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
|
|||||||
+7
-6
@@ -24,8 +24,13 @@ export default {
|
|||||||
return new Response('Invalid url parameter', { status: 400 });
|
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
|
// 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();
|
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
|
||||||
return new Response(svg.replaceAll('#24292E', '#808080'), {
|
return new Response(svg.replaceAll('#24292E', '#808080'), {
|
||||||
headers: { 'Content-Type': 'image/svg+xml' },
|
headers: { 'Content-Type': 'image/svg+xml' },
|
||||||
@@ -33,20 +38,16 @@ export default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AI-provider-specific hacks
|
// AI-provider-specific hacks
|
||||||
let hostname = url.hostname;
|
|
||||||
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
|
||||||
hostname = 'ollama.com';
|
hostname = 'ollama.com';
|
||||||
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
|
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
|
||||||
hostname = 'claude.ai';
|
hostname = 'claude.ai';
|
||||||
} else if (url.host === 'generativelanguage.googleapis.com') {
|
} else if (url.host === 'generativelanguage.googleapis.com') {
|
||||||
hostname = 'gemini.google.com';
|
hostname = 'gemini.google.com';
|
||||||
} else if (url.host === 'api.z.ai') {
|
} else if (url.host === 'z.ai') {
|
||||||
hostname = 'docs.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
|
// Fetch the favicon from DuckDuckGo's service
|
||||||
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
|
||||||
},
|
},
|
||||||
|
|||||||
+9
-8
@@ -12,16 +12,17 @@ export default {
|
|||||||
return new Response(null, {
|
return new Response(null, {
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: {
|
headers: {
|
||||||
"Access-Control-Allow-Origin": "*",
|
"access-control-allow-origin": "*",
|
||||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
"access-control-allow-headers": "*", // Or specify specific headers
|
||||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
"access-control-max-age": "86400", // Cache preflight for 24 hours
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const headers = new Headers(request.headers);
|
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, {
|
const targetResponse = await fetch(target, {
|
||||||
method: request.method,
|
method: request.method,
|
||||||
@@ -31,9 +32,9 @@ export default {
|
|||||||
|
|
||||||
const response = new Response(targetResponse.body, targetResponse);
|
const response = new Response(targetResponse.body, targetResponse);
|
||||||
|
|
||||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
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-methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
|
||||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
response.headers.set("access-control-allow-headers", "*");
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import AboutSettings from "./pages/AboutSettings";
|
|||||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||||
import VercelOAuth from "./pages/VercelOAuth";
|
import VercelOAuth from "./pages/VercelOAuth";
|
||||||
|
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||||
import { NIP19Page } from "./pages/NIP19Page";
|
import { NIP19Page } from "./pages/NIP19Page";
|
||||||
import NotFound from "./pages/NotFound";
|
import NotFound from "./pages/NotFound";
|
||||||
import { ProjectView } from "./pages/ProjectView";
|
import { ProjectView } from "./pages/ProjectView";
|
||||||
@@ -39,6 +40,7 @@ export function AppRouter() {
|
|||||||
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
<Route path="/oauth/github" element={<GitHubOAuth />} />
|
||||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||||
|
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||||
<Route path="/settings" element={<SettingsLayout />}>
|
<Route path="/settings" element={<SettingsLayout />}>
|
||||||
<Route index element={<Settings />} />
|
<Route index element={<Settings />} />
|
||||||
<Route path="preferences" element={<Preferences />} />
|
<Route path="preferences" element={<Preferences />} />
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Bot } from 'lucide-react';
|
import { Bot, ChevronDown } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
import { ExternalInput } from '@/components/ui/external-input';
|
import { ExternalInput } from '@/components/ui/external-input';
|
||||||
@@ -12,15 +12,31 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
import type { PresetProvider } from '@/lib/aiProviderPresets';
|
import type { PresetProvider } from '@/lib/aiProviderPresets';
|
||||||
|
|
||||||
|
interface OAuthHook {
|
||||||
|
isOAuthConfigured: boolean;
|
||||||
|
isLoading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
initiateOAuth: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
interface AddAIProviderDialogProps {
|
interface AddAIProviderDialogProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
preset: PresetProvider;
|
preset: PresetProvider;
|
||||||
isLoggedIntoNostr: boolean;
|
isLoggedIntoNostr: boolean;
|
||||||
|
oauthHook?: OAuthHook | null;
|
||||||
|
forceManualEntry?: boolean;
|
||||||
|
onSetForceManualEntry?: (force: boolean) => void;
|
||||||
onAdd: (apiKey: string) => void;
|
onAdd: (apiKey: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,6 +45,9 @@ export function AddAIProviderDialog({
|
|||||||
onOpenChange,
|
onOpenChange,
|
||||||
preset,
|
preset,
|
||||||
isLoggedIntoNostr,
|
isLoggedIntoNostr,
|
||||||
|
oauthHook,
|
||||||
|
forceManualEntry = false,
|
||||||
|
onSetForceManualEntry,
|
||||||
onAdd,
|
onAdd,
|
||||||
}: AddAIProviderDialogProps) {
|
}: AddAIProviderDialogProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -36,16 +55,27 @@ export function AddAIProviderDialog({
|
|||||||
const [termsAgreed, setTermsAgreed] = useState(false);
|
const [termsAgreed, setTermsAgreed] = useState(false);
|
||||||
|
|
||||||
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
|
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
|
||||||
|
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
|
||||||
|
const isOAuthLoading = oauthHook?.isLoading ?? false;
|
||||||
|
const oauthError = oauthHook?.error ?? null;
|
||||||
|
|
||||||
const handleAdd = () => {
|
const handleAdd = () => {
|
||||||
onAdd(apiKey);
|
onAdd(apiKey);
|
||||||
setApiKey('');
|
setApiKey('');
|
||||||
setTermsAgreed(false);
|
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Reset state when dialog closes
|
||||||
|
const handleOpenChange = (open: boolean) => {
|
||||||
|
if (!open) {
|
||||||
|
setApiKey('');
|
||||||
|
setTermsAgreed(false);
|
||||||
|
}
|
||||||
|
onOpenChange(open);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
<DialogContent className="max-w-md">
|
<DialogContent className="max-w-md">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@@ -73,6 +103,50 @@ export function AddAIProviderDialog({
|
|||||||
</Link>
|
</Link>
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</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">
|
<div className="space-y-3">
|
||||||
{!preset.nostr && preset.apiKeysURL && (
|
{!preset.nostr && preset.apiKeysURL && (
|
||||||
@@ -123,7 +197,7 @@ export function AddAIProviderDialog({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!showNostrLoginRequired && (
|
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
{t('cancel')}
|
{t('cancel')}
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ interface OAuthHook {
|
|||||||
initiateOAuth: () => void;
|
initiateOAuth: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AddProviderDialogProps {
|
interface AddDeployProviderDialogProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
preset: PresetDeployProvider;
|
preset: PresetDeployProvider;
|
||||||
@@ -39,7 +39,7 @@ interface AddProviderDialogProps {
|
|||||||
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function AddProviderDialog({
|
export function AddDeployProviderDialog({
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
preset,
|
preset,
|
||||||
@@ -48,7 +48,7 @@ export function AddProviderDialog({
|
|||||||
forceManualEntry,
|
forceManualEntry,
|
||||||
onSetForceManualEntry,
|
onSetForceManualEntry,
|
||||||
onAdd,
|
onAdd,
|
||||||
}: AddProviderDialogProps) {
|
}: AddDeployProviderDialogProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [apiKey, setApiKey] = useState('');
|
const [apiKey, setApiKey] = useState('');
|
||||||
const [accountId, setAccountId] = useState('');
|
const [accountId, setAccountId] = useState('');
|
||||||
@@ -112,16 +112,9 @@ export function AddProviderDialog({
|
|||||||
Connecting...
|
Connecting...
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<span className="truncate text-ellipsis overflow-hidden">
|
||||||
<ExternalFavicon
|
Connect to {preset.name}
|
||||||
url={preset.baseURL}
|
</span>
|
||||||
size={16}
|
|
||||||
fallback={<Rocket size={16} />}
|
|
||||||
/>
|
|
||||||
<span className="truncate text-ellipsis overflow-hidden">
|
|
||||||
Connect to {preset.name}
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -84,8 +84,8 @@ export function AddGitCredentialDialog({
|
|||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="space-y-4 py-4">
|
<div className="space-y-4 py-4">
|
||||||
{preset.id === 'github' && isOAuthConfigured && !forceManualEntry ? (
|
{isOAuthConfigured && !forceManualEntry ? (
|
||||||
// Special rendering for GitHub OAuth
|
// Show OAuth button if OAuth is configured and not forced to manual
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="flex gap-0">
|
<div className="flex gap-0">
|
||||||
<Button
|
<Button
|
||||||
@@ -100,16 +100,9 @@ export function AddGitCredentialDialog({
|
|||||||
Connecting...
|
Connecting...
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<span className="truncate text-ellipsis overflow-hidden">
|
||||||
<ExternalFavicon
|
Connect to {preset.name}
|
||||||
url="https://github.com"
|
</span>
|
||||||
size={16}
|
|
||||||
fallback={<GitBranch size={16} />}
|
|
||||||
/>
|
|
||||||
<span className="truncate text-ellipsis overflow-hidden">
|
|
||||||
Connect to GitHub
|
|
||||||
</span>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
@@ -124,7 +117,7 @@ export function AddGitCredentialDialog({
|
|||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
|
||||||
Enter API key
|
Enter token manually
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
@@ -136,7 +129,7 @@ export function AddGitCredentialDialog({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
// Standard token input
|
// Show manual token input
|
||||||
<ExternalInput
|
<ExternalInput
|
||||||
type="password"
|
type="password"
|
||||||
placeholder={t('enterToken')}
|
placeholder={t('enterToken')}
|
||||||
@@ -153,7 +146,7 @@ export function AddGitCredentialDialog({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!(preset.id === 'github' && isOAuthConfigured && !forceManualEntry) && (
|
{!(isOAuthConfigured && !forceManualEntry) && (
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
<Button variant="outline" onClick={() => onOpenChange(false)}>
|
||||||
{t('cancel')}
|
{t('cancel')}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useState, useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { generateSecretKey } from 'nostr-tools';
|
import { generateSecretKey } from 'nostr-tools';
|
||||||
import { nip19 } 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 { useTranslation } from 'react-i18next';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
import { Button } from '@/components/ui/button';
|
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 { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
import { Input } from '@/components/ui/input';
|
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 { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||||
@@ -465,37 +465,28 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
|||||||
{/* API Key Input Section */}
|
{/* API Key Input Section */}
|
||||||
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
||||||
<div className="space-y-3 max-w-md mx-auto">
|
<div className="space-y-3 max-w-md mx-auto">
|
||||||
<div className="text-center">
|
<h3 className="flex justify-center text-lg font-semibold gap-2">
|
||||||
<h3 className="text-lg font-semibold">
|
<ExternalFavicon
|
||||||
|
url={selectedProvider.baseURL}
|
||||||
|
size={16}
|
||||||
|
fallback={<Bot size={16} />}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||||
</h3>
|
</span>
|
||||||
<p className="text-sm text-muted-foreground">
|
</h3>
|
||||||
{selectedProvider.id === 'routstr' ? (
|
<ExternalInput
|
||||||
t('requiresCashuToken', { providerName: selectedProvider.name })
|
type="password"
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
{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
|
|
||||||
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
|
||||||
value={providerApiKey}
|
value={providerApiKey}
|
||||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
|
||||||
handleContinueFromProviderSelection();
|
handleContinueFromProviderSelection();
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
url={selectedProvider.apiKeysURL}
|
||||||
|
urlTitle="Get Key"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ export function ProjectTitleMenu({
|
|||||||
className="gap-2"
|
className="gap-2"
|
||||||
>
|
>
|
||||||
<MessageSquarePlus className="h-4 w-4" />
|
<MessageSquarePlus className="h-4 w-4" />
|
||||||
New Chat
|
{t('newChat')}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<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 { Button } from '@/components/ui/button';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||||
import { ChevronDown, Play } from 'lucide-react';
|
import { ChevronDown, ChevronUp, Play } from 'lucide-react';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useFS } from '@/hooks/useFS';
|
import { useFS } from '@/hooks/useFS';
|
||||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||||
@@ -47,11 +47,12 @@ import OpenAI from 'openai';
|
|||||||
import { useGit } from '@/hooks/useGit';
|
import { useGit } from '@/hooks/useGit';
|
||||||
import { Quilly } from '@/components/Quilly';
|
import { Quilly } from '@/components/Quilly';
|
||||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||||
|
import { SessionDivider } from '@/components/SessionDivider';
|
||||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||||
import { DotAI } from '@/lib/DotAI';
|
import { DotAI } from '@/lib/DotAI';
|
||||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||||
import { AIMessage } from '@/lib/SessionManager';
|
import { AIMessage, DisplayMessage } from '@/lib/SessionManager';
|
||||||
|
|
||||||
// Clean interfaces now handled by proper hooks
|
// Clean interfaces now handled by proper hooks
|
||||||
|
|
||||||
@@ -294,9 +295,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
sessionName,
|
||||||
streamingMessage,
|
streamingMessage,
|
||||||
isLoading: internalIsLoading,
|
isLoading: internalIsLoading,
|
||||||
isLoadingHistory,
|
isLoadingHistory,
|
||||||
|
hasMoreHistory,
|
||||||
|
isLoadingMoreHistory,
|
||||||
totalCost,
|
totalCost,
|
||||||
lastInputTokens,
|
lastInputTokens,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
@@ -305,6 +310,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
startGeneration,
|
startGeneration,
|
||||||
stopGeneration,
|
stopGeneration,
|
||||||
startNewSession: internalStartNewSession,
|
startNewSession: internalStartNewSession,
|
||||||
|
loadMoreHistory,
|
||||||
} = useAIChat({
|
} = useAIChat({
|
||||||
projectId,
|
projectId,
|
||||||
tools,
|
tools,
|
||||||
@@ -318,7 +324,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
const checkTemplateInfo = async () => {
|
const checkTemplateInfo = async () => {
|
||||||
try {
|
try {
|
||||||
// Only check if we have at least 1 message
|
// Only check if we have at least 1 message
|
||||||
if (messages.length === 0) {
|
if (displayMessages.length === 0) {
|
||||||
setShowTemplateInfo(false);
|
setShowTemplateInfo(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -357,7 +363,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
};
|
};
|
||||||
|
|
||||||
checkTemplateInfo();
|
checkTemplateInfo();
|
||||||
}, [fs, projectsPath, projectId, messages.length]);
|
}, [fs, projectsPath, projectId, displayMessages.length]);
|
||||||
|
|
||||||
// Handle console error help requests
|
// Handle console error help requests
|
||||||
const handleConsoleErrorHelp = useCallback(async () => {
|
const handleConsoleErrorHelp = useCallback(async () => {
|
||||||
@@ -436,7 +442,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
// Function to scroll to bottom
|
// Function to scroll to bottom
|
||||||
const scrollToBottom = useCallback(() => {
|
const scrollToBottom = useCallback(() => {
|
||||||
if (scrollAreaRef.current) {
|
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(() => {
|
useEffect(() => {
|
||||||
if (scrollAreaRef.current && (messages || streamingMessage)) {
|
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 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;
|
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
|
||||||
|
|
||||||
// Only auto-scroll if user was already near the bottom
|
// Scroll to bottom if user sent a message or was already near the bottom
|
||||||
if (isNearBottom) {
|
if (isUserMessage || isNearBottom) {
|
||||||
container.scrollTop = container.scrollHeight;
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [messages, streamingMessage, isLoading]);
|
}, [messages, streamingMessage, isLoading, scrollToBottom]);
|
||||||
|
|
||||||
// Scroll to bottom when first visiting a project (including page refresh)
|
// Scroll to bottom when first visiting a project (including page refresh)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -577,8 +590,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
// Add model to recently used when sending a message
|
// Add model to recently used when sending a message
|
||||||
addRecentlyUsedModel(modelToUse);
|
addRecentlyUsedModel(modelToUse);
|
||||||
|
|
||||||
|
// Scroll to bottom when user sends a message
|
||||||
|
scrollToBottom();
|
||||||
|
|
||||||
await sendMessage(messageContent, modelToUse);
|
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
|
// Handle textarea focus - show onboarding if not configured
|
||||||
const handleTextareaFocus = useCallback(() => {
|
const handleTextareaFocus = useCallback(() => {
|
||||||
@@ -757,7 +773,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Empty state when no messages and not loading */}
|
{/* 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="flex-1 flex items-center justify-center min-h-[400px]">
|
||||||
<div className="text-center space-y-4 max-w-md mx-auto">
|
<div className="text-center space-y-4 max-w-md mx-auto">
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
@@ -781,13 +797,49 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
</div>
|
</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
|
// Find the corresponding tool call for tool messages
|
||||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||||
if (message.role === 'tool') {
|
if (message.role === 'tool') {
|
||||||
// Look backwards to find the assistant message with matching tool call
|
// Look backwards to find the assistant message with matching tool call
|
||||||
for (let i = index - 1; i >= 0; i--) {
|
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) {
|
if (prevMessage.role === 'assistant' && 'tool_calls' in prevMessage && prevMessage.tool_calls) {
|
||||||
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
toolCall = prevMessage.tool_calls.find(tc => tc.id === message.tool_call_id);
|
||||||
if (toolCall) break;
|
if (toolCall) break;
|
||||||
@@ -796,14 +848,27 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AIMessageItem
|
<div
|
||||||
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
key={`${index}-${message.role}-${typeof message.content === 'string' ? message.content.slice(0, 50) : 'content'}`}
|
||||||
message={message}
|
className={isOlderSession ? 'opacity-65' : ''}
|
||||||
toolCall={toolCall}
|
>
|
||||||
/>
|
{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()}
|
{!isLoadingHistory && renderStreamingMessage()}
|
||||||
|
|
||||||
{/* Resume button - shown when not loading and finish reason is not "stop" or "length" (or no finish reason) */}
|
{/* 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 { 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 { Button } from '@/components/ui/button';
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||||
@@ -16,6 +16,8 @@ interface GitSyncButtonProps {
|
|||||||
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [syncSuccess, setSyncSuccess] = useState(false);
|
const [syncSuccess, setSyncSuccess] = useState(false);
|
||||||
|
const [showWarningPopover, setShowWarningPopover] = useState(false);
|
||||||
|
const warningDismissed = useRef(false);
|
||||||
|
|
||||||
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
|
||||||
const { getError, getState } = useGitSyncState();
|
const { getError, getState } = useGitSyncState();
|
||||||
@@ -26,6 +28,18 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
const gitSyncState = getState(dir);
|
const gitSyncState = getState(dir);
|
||||||
const isGitActionOccurring = gitSyncState?.isActive ?? false;
|
const isGitActionOccurring = gitSyncState?.isActive ?? false;
|
||||||
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
|
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
|
// Detect when a git action completes successfully
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -38,6 +52,29 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
prevIsGitActionOccurring.current = isGitActionOccurring;
|
prevIsGitActionOccurring.current = isGitActionOccurring;
|
||||||
}, [isGitActionOccurring, hasError]);
|
}, [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)
|
// Determine which indicator to show (only one at a time, in priority order)
|
||||||
const renderIndicator = () => {
|
const renderIndicator = () => {
|
||||||
// Checkmark: sync just completed successfully - highest priority
|
// Checkmark: sync just completed successfully - highest priority
|
||||||
@@ -78,26 +115,61 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
<>
|
||||||
<PopoverTrigger asChild>
|
{/* Warning popover - shown when purple indicator is visible */}
|
||||||
<Button
|
<Popover open={showWarningPopover} modal={false}>
|
||||||
variant="ghost"
|
<PopoverTrigger asChild>
|
||||||
size="sm"
|
<div className="relative">
|
||||||
className={cn("size-8 p-0 group relative", className)}
|
{/* Main Git Sync popover */}
|
||||||
aria-label="Sync with Git"
|
<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")} />
|
<div className="space-y-3 pointer-events-auto">
|
||||||
{renderIndicator()}
|
<div className="flex items-center gap-2">
|
||||||
</Button>
|
<AlertTriangle className="size-5 text-primary shrink-0" />
|
||||||
</PopoverTrigger>
|
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
|
||||||
<PopoverContent
|
</div>
|
||||||
align="start"
|
<p className="text-sm text-muted-foreground">
|
||||||
className="w-96"
|
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
|
||||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
</p>
|
||||||
>
|
<Button
|
||||||
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
|
onClick={handleButtonClick}
|
||||||
</PopoverContent>
|
className="w-full"
|
||||||
</Popover>
|
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 { useSessionManager } from '@/hooks/useSessionManager';
|
||||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||||
import { useAISettings } from '@/hooks/useAISettings';
|
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 OpenAI from 'openai';
|
||||||
import type { Tool } from '@/lib/tools/Tool';
|
import type { Tool } from '@/lib/tools/Tool';
|
||||||
|
|
||||||
@@ -39,12 +39,16 @@ export function useAIChat({
|
|||||||
|
|
||||||
// Split session state into individual variables for efficient updates
|
// Split session state into individual variables for efficient updates
|
||||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||||
|
const [displayMessages, setDisplayMessages] = useState<DisplayMessage[]>([]);
|
||||||
|
const [sessionName, setSessionName] = useState<string>('');
|
||||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||||
const [totalCost, setTotalCost] = useState<number>(0);
|
const [totalCost, setTotalCost] = useState<number>(0);
|
||||||
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
const [lastInputTokens, setLastInputTokens] = useState<number>(0);
|
||||||
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
const [lastFinishReason, setLastFinishReason] = useState<string | null>(null);
|
||||||
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
const [isLoadingHistory, setIsLoadingHistory] = useState<boolean>(true);
|
||||||
|
const [hasMoreHistory, setHasMoreHistory] = useState<boolean>(false);
|
||||||
|
const [isLoadingMoreHistory, setIsLoadingMoreHistory] = useState<boolean>(false);
|
||||||
|
|
||||||
const initSession = useCallback(async () => {
|
const initSession = useCallback(async () => {
|
||||||
setIsLoadingHistory(true);
|
setIsLoadingHistory(true);
|
||||||
@@ -53,11 +57,15 @@ export function useAIChat({
|
|||||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||||
// Initialize individual state variables from existing session
|
// Initialize individual state variables from existing session
|
||||||
setMessages([...session.messages]);
|
setMessages([...session.messages]);
|
||||||
|
setDisplayMessages([...session.displayMessages]);
|
||||||
|
setSessionName(session.sessionName);
|
||||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||||
setIsLoading(session.isLoading);
|
setIsLoading(session.isLoading);
|
||||||
setTotalCost(session.totalCost || 0);
|
setTotalCost(session.totalCost || 0);
|
||||||
setLastInputTokens(session.lastInputTokens || 0);
|
setLastInputTokens(session.lastInputTokens || 0);
|
||||||
setLastFinishReason(session.lastFinishReason ?? null);
|
setLastFinishReason(session.lastFinishReason ?? null);
|
||||||
|
setHasMoreHistory(sessionManager.hasMoreHistory(projectId));
|
||||||
|
setIsLoadingMoreHistory(session.isLoadingMoreHistory || false);
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoadingHistory(false);
|
setIsLoadingHistory(false);
|
||||||
}
|
}
|
||||||
@@ -123,6 +131,25 @@ export function useAIChat({
|
|||||||
}
|
}
|
||||||
}, [projectId]);
|
}, [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
|
// Actions
|
||||||
const sendMessage = useCallback(async (
|
const sendMessage = useCallback(async (
|
||||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||||
@@ -164,7 +191,13 @@ export function useAIChat({
|
|||||||
const startNewSession = useCallback(async () => {
|
const startNewSession = useCallback(async () => {
|
||||||
await sessionManager.startNewSession(projectId);
|
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([]);
|
setMessages([]);
|
||||||
setStreamingMessage(undefined);
|
setStreamingMessage(undefined);
|
||||||
setTotalCost(0);
|
setTotalCost(0);
|
||||||
@@ -177,11 +210,19 @@ export function useAIChat({
|
|||||||
await startNewSession();
|
await startNewSession();
|
||||||
}, [startNewSession]);
|
}, [startNewSession]);
|
||||||
|
|
||||||
|
const loadMoreHistory = useCallback(async () => {
|
||||||
|
await sessionManager.loadOlderSession(projectId);
|
||||||
|
}, [projectId, sessionManager]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
sessionName,
|
||||||
streamingMessage,
|
streamingMessage,
|
||||||
isLoading,
|
isLoading,
|
||||||
isLoadingHistory,
|
isLoadingHistory,
|
||||||
|
hasMoreHistory,
|
||||||
|
isLoadingMoreHistory,
|
||||||
totalCost,
|
totalCost,
|
||||||
lastInputTokens,
|
lastInputTokens,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
@@ -191,6 +232,7 @@ export function useAIChat({
|
|||||||
clearMessages,
|
clearMessages,
|
||||||
startNewSession,
|
startNewSession,
|
||||||
addMessage,
|
addMessage,
|
||||||
|
loadMoreHistory,
|
||||||
isConfigured,
|
isConfigured,
|
||||||
projectId
|
projectId
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
|
|||||||
import { proxyUrl } from '@/lib/proxyUrl';
|
import { proxyUrl } from '@/lib/proxyUrl';
|
||||||
|
|
||||||
export interface OAuthConfig {
|
export interface OAuthConfig {
|
||||||
provider: 'github' | 'netlify' | 'vercel';
|
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
|
||||||
clientId: string;
|
clientId: string;
|
||||||
clientSecret: string;
|
clientSecret: string;
|
||||||
authorizeUrl: 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');
|
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', () => {
|
describe('setHistory', () => {
|
||||||
it('should create history directory if it does not exist', async () => {
|
it('should create history directory if it does not exist', async () => {
|
||||||
// Mock historyDirExists to return false initially
|
// Mock historyDirExists to return false initially
|
||||||
|
|||||||
+34
-50
@@ -216,66 +216,50 @@ export class DotAI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read the most recent session history
|
* List all session names sorted chronologically (oldest first)
|
||||||
* @returns Object containing messages array and session name, or null if no history found
|
* Fast operation - does not load message content
|
||||||
|
* @returns Array of session names (filenames without .jsonl extension)
|
||||||
*/
|
*/
|
||||||
async readLastSessionHistory(): Promise<{
|
async listSessionNames(): Promise<string[]> {
|
||||||
messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
|
||||||
sessionName: string;
|
|
||||||
} | null> {
|
|
||||||
try {
|
try {
|
||||||
// Check if history directory exists
|
|
||||||
if (!(await this.historyDirExists())) {
|
if (!(await this.historyDirExists())) {
|
||||||
return null;
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Find the most recent session file
|
const files = await this.fs.readdir(this.historyDir);
|
||||||
try {
|
return files
|
||||||
const files = await this.fs.readdir(this.historyDir);
|
.filter(file => file.endsWith('.jsonl'))
|
||||||
const sessionFiles = files
|
.map(file => file.replace('.jsonl', ''))
|
||||||
.filter(file => file.endsWith('.jsonl'))
|
.sort(); // Chronological order (oldest first) - filenames contain timestamps
|
||||||
.sort()
|
} catch {
|
||||||
.reverse(); // Most recent first
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (sessionFiles.length === 0) {
|
/**
|
||||||
return null;
|
* 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
|
||||||
const latestSessionFile = sessionFiles[0];
|
*/
|
||||||
const sessionPath = join(this.historyDir, latestSessionFile);
|
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 {
|
try {
|
||||||
const content = await this.fs.readFile(sessionPath, 'utf8');
|
const message = JSON.parse(line) as OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||||
const lines = content.trim().split('\n').filter(line => line.trim());
|
messages.push(message);
|
||||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
} catch {
|
||||||
|
// Skip malformed lines
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
} catch (readdirError) {
|
|
||||||
console.warn('Failed to read history directory:', readdirError);
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
console.warn('Failed to read last session history:', error);
|
return messages;
|
||||||
return null;
|
} catch {
|
||||||
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+140
-24
@@ -24,12 +24,20 @@ export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
|||||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
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 {
|
export interface SessionState {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||||
customTools: Record<string, Tool<unknown>>;
|
customTools: Record<string, Tool<unknown>>;
|
||||||
maxSteps?: number;
|
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?: {
|
streamingMessage?: {
|
||||||
role: 'assistant';
|
role: 'assistant';
|
||||||
content: string;
|
content: string;
|
||||||
@@ -37,6 +45,7 @@ export interface SessionState {
|
|||||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||||
};
|
};
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
|
isLoadingMoreHistory: boolean; // Loading older sessions
|
||||||
sessionName: string;
|
sessionName: string;
|
||||||
lastActivity: Date;
|
lastActivity: Date;
|
||||||
abortController?: AbortController;
|
abortController?: AbortController;
|
||||||
@@ -50,8 +59,11 @@ export interface SessionManagerEvents {
|
|||||||
sessionCreated: (projectId: string) => void;
|
sessionCreated: (projectId: string) => void;
|
||||||
sessionDeleted: (projectId: string) => void;
|
sessionDeleted: (projectId: string) => void;
|
||||||
messageAdded: (projectId: string, message: AIMessage) => 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;
|
streamingUpdate: (projectId: string, content: string, reasoningContent?: string, toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => void;
|
||||||
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
loadingChanged: (projectId: string, isLoading: boolean) => void;
|
||||||
|
loadingMoreHistoryChanged: (projectId: string, isLoading: boolean) => void;
|
||||||
costUpdated: (projectId: string, totalCost: number) => void;
|
costUpdated: (projectId: string, totalCost: number) => void;
|
||||||
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
contextUsageUpdated: (projectId: string, inputTokens: number) => void;
|
||||||
fileChanged: (projectId: string, filePath: string) => 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(
|
async loadSession(
|
||||||
projectId: string,
|
projectId: string,
|
||||||
@@ -105,18 +117,39 @@ export class SessionManager {
|
|||||||
customTools: Record<string, Tool<unknown>>,
|
customTools: Record<string, Tool<unknown>>,
|
||||||
maxSteps?: number
|
maxSteps?: number
|
||||||
): Promise<SessionState> {
|
): Promise<SessionState> {
|
||||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
const messages: AIMessage[] = [];
|
||||||
|
const displayMessages: DisplayMessage[] = [];
|
||||||
let sessionName = DotAI.generateSessionName();
|
let sessionName = DotAI.generateSessionName();
|
||||||
|
let availableSessionNames: string[] = [];
|
||||||
|
let loadedSessionCount = 0;
|
||||||
let lastFinishReason: string | null | undefined;
|
let lastFinishReason: string | null | undefined;
|
||||||
|
|
||||||
// Try to load existing history
|
// Try to load existing history (lazy - only load last session)
|
||||||
try {
|
try {
|
||||||
const config = this.getConfig();
|
const config = this.getConfig();
|
||||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||||
const lastSession = await dotAI.readLastSessionHistory();
|
|
||||||
if (lastSession) {
|
// Get all available session names (fast - no content loading)
|
||||||
messages = lastSession.messages;
|
availableSessionNames = await dotAI.listSessionNames();
|
||||||
sessionName = lastSession.sessionName;
|
|
||||||
|
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
|
// Load last finish reason
|
||||||
@@ -131,21 +164,33 @@ export class SessionManager {
|
|||||||
customTools,
|
customTools,
|
||||||
maxSteps,
|
maxSteps,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
|
isLoadingMoreHistory: false,
|
||||||
lastActivity: new Date(),
|
lastActivity: new Date(),
|
||||||
totalCost: 0,
|
totalCost: 0,
|
||||||
lastInputTokens: 0,
|
lastInputTokens: 0,
|
||||||
lastFinishReason,
|
lastFinishReason,
|
||||||
...this.sessions.get(projectId),
|
...this.sessions.get(projectId),
|
||||||
messages,
|
messages,
|
||||||
|
displayMessages,
|
||||||
|
availableSessionNames,
|
||||||
|
loadedSessionCount,
|
||||||
sessionName,
|
sessionName,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Update session configuration
|
// Update session configuration
|
||||||
session.projectId = projectId;
|
session.projectId = projectId;
|
||||||
session.tools = tools;
|
session.tools = tools;
|
||||||
|
|
||||||
session.customTools = customTools;
|
session.customTools = customTools;
|
||||||
session.maxSteps = maxSteps;
|
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);
|
this.sessions.set(projectId, session);
|
||||||
|
|
||||||
@@ -187,11 +232,69 @@ export class SessionManager {
|
|||||||
const session = this.sessions.get(projectId);
|
const session = this.sessions.get(projectId);
|
||||||
if (!session) return;
|
if (!session) return;
|
||||||
|
|
||||||
|
// Add to current session messages (for AI prompts)
|
||||||
session.messages.push(message);
|
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();
|
session.lastActivity = new Date();
|
||||||
|
|
||||||
await this.saveSessionHistory(projectId);
|
await this.saveSessionHistory(projectId);
|
||||||
this.emit('messageAdded', projectId, message);
|
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 accumulatedContent = '';
|
||||||
let accumulatedReasoningContent = '';
|
let accumulatedReasoningContent = '';
|
||||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
|
||||||
let finishReason: string | null = null;
|
let finishReason: string | null = null;
|
||||||
|
|
||||||
// Process the stream
|
// Process the stream
|
||||||
@@ -491,20 +594,29 @@ export class SessionManager {
|
|||||||
const toolCallDelta = delta.tool_calls[i];
|
const toolCallDelta = delta.tool_calls[i];
|
||||||
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
const index = toolCallDelta.index ?? i; // Fix for Gemini models
|
||||||
|
|
||||||
accumulatedToolCalls[index] ??= {
|
let toolCall = accumulatedToolCalls.get(index);
|
||||||
id: '',
|
|
||||||
type: 'function',
|
if (!toolCall) {
|
||||||
function: { name: '', arguments: '' }
|
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.id) toolCall.id = toolCallDelta.id;
|
||||||
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
|
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
|
||||||
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
|
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
|
||||||
|
|
||||||
|
accumulatedToolCalls.set(index, toolCall);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (session.streamingMessage) {
|
if (session.streamingMessage && accumulatedToolCalls.size > 0) {
|
||||||
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
|
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);
|
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
|
// Fix tool calls with empty arguments or names
|
||||||
for (const toolCall of accumulatedToolCalls) {
|
for (const toolCall of accumulatedToolCalls.values()) {
|
||||||
if (toolCall.type === 'function') {
|
if (toolCall.type === 'function') {
|
||||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||||
|
|
||||||
@@ -549,7 +661,7 @@ export class SessionManager {
|
|||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: accumulatedContent,
|
content: accumulatedContent,
|
||||||
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
|
...(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)
|
// Check if the assistant message is empty (no content, reasoning, or tool calls)
|
||||||
@@ -575,8 +687,8 @@ export class SessionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Handle tool calls
|
// Handle tool calls
|
||||||
if (accumulatedToolCalls?.length) {
|
if (accumulatedToolCalls?.size) {
|
||||||
for (const toolCall of accumulatedToolCalls) {
|
for (const toolCall of accumulatedToolCalls.values()) {
|
||||||
if (toolCall.type !== 'function') continue;
|
if (toolCall.type !== 'function') continue;
|
||||||
|
|
||||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
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> {
|
async startNewSession(projectId: string): Promise<void> {
|
||||||
const session = this.sessions.get(projectId);
|
const session = this.sessions.get(projectId);
|
||||||
@@ -698,9 +810,13 @@ export class SessionManager {
|
|||||||
|
|
||||||
this.stopGeneration(projectId);
|
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.messages = [];
|
||||||
session.streamingMessage = undefined;
|
session.streamingMessage = undefined;
|
||||||
session.sessionName = DotAI.generateSessionName();
|
session.sessionName = newSessionName;
|
||||||
session.lastActivity = new Date();
|
session.lastActivity = new Date();
|
||||||
session.totalCost = 0;
|
session.totalCost = 0;
|
||||||
session.lastInputTokens = 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.bind(openai.chat.completions);
|
||||||
|
|
||||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||||
// OpenRouter usage accounting
|
// OpenRouter-specific hacks
|
||||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
|
||||||
if (provider.id === 'openrouter') {
|
// 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 };
|
(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);
|
return createCompletion(body, options);
|
||||||
}) as typeof createCompletion;
|
}) as typeof createCompletion;
|
||||||
|
|
||||||
return openai;
|
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",
|
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||||
tosURL: "https://openrouter.ai/terms",
|
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",
|
id: "ppq",
|
||||||
name: "PayPerQ",
|
name: "PayPerQ",
|
||||||
|
|||||||
+7
-18
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Anonymous",
|
"anonymous": "Anonymous",
|
||||||
"logIn": "Log in",
|
"logIn": "Log in",
|
||||||
"signUp": "Sign up",
|
"signUp": "Sign up",
|
||||||
|
"newChat": "New Chat",
|
||||||
|
"loadOlderMessages": "Load older messages",
|
||||||
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
"preferencesDescription": "Manage your general application preferences and appearance settings.",
|
||||||
"theme": "Theme",
|
"theme": "Theme",
|
||||||
"themeDescription": "Choose between light, dark, or system theme preference.",
|
"themeDescription": "Choose between light, dark, or system theme preference.",
|
||||||
@@ -54,12 +56,9 @@
|
|||||||
"showcaseModerator": "Showcase Moderator",
|
"showcaseModerator": "Showcase Moderator",
|
||||||
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
|
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
|
||||||
"filesystemPaths": "Filesystem Paths",
|
"filesystemPaths": "Filesystem Paths",
|
||||||
"projectsDirectory": "Projects Directory",
|
"projectsDirectory": "Projects",
|
||||||
"projectsDirectoryDescription": "Filesystem path where projects are stored",
|
"configDirectory": "Config",
|
||||||
"configDirectory": "Config Directory",
|
"temporaryDirectory": "Temporary",
|
||||||
"configDirectoryDescription": "Filesystem path where configuration files are stored",
|
|
||||||
"temporaryDirectory": "Temporary Directory",
|
|
||||||
"temporaryDirectoryDescription": "Filesystem path for temporary files",
|
|
||||||
"sentryDsn": "Sentry DSN",
|
"sentryDsn": "Sentry DSN",
|
||||||
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
||||||
"shareErrorReports": "Share error reports",
|
"shareErrorReports": "Share error reports",
|
||||||
@@ -484,8 +483,7 @@
|
|||||||
"skills": "Skills",
|
"skills": "Skills",
|
||||||
"noSkillsFound": "No skills found in this plugin.",
|
"noSkillsFound": "No skills found in this plugin.",
|
||||||
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
|
||||||
"pluginsDirectory": "Plugins Directory",
|
"pluginsDirectory": "Plugins",
|
||||||
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
|
|
||||||
"discoverPlugins": "Discover Plugins",
|
"discoverPlugins": "Discover Plugins",
|
||||||
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
|
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
|
||||||
"searchPlugins": "Search plugins...",
|
"searchPlugins": "Search plugins...",
|
||||||
@@ -526,21 +524,12 @@
|
|||||||
"discoveringTools": "Discovering tools...",
|
"discoveringTools": "Discovering tools...",
|
||||||
"toolsDiscovered": "{{count}} tool(s) discovered",
|
"toolsDiscovered": "{{count}} tool(s) discovered",
|
||||||
"toolDiscoveryFailed": "Failed to discover tools from this server",
|
"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...",
|
"deleting": "Deleting...",
|
||||||
"modified": "Modified",
|
|
||||||
"restoreToDefault": "Restore to default",
|
"restoreToDefault": "Restore to default",
|
||||||
"restoredToDefault": "Restored to Default",
|
"restoredToDefault": "Restored to Default",
|
||||||
"templateUpdateFailed": "Template Update Failed",
|
"templateUpdateFailed": "Template Update Failed",
|
||||||
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
|
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
|
||||||
"templatesDirectory": "Templates Directory",
|
"templatesDirectory": "Templates",
|
||||||
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
|
|
||||||
"terminal": "Terminal",
|
"terminal": "Terminal",
|
||||||
"templateName": "Template Name",
|
"templateName": "Template Name",
|
||||||
"templateDescription": "Description",
|
"templateDescription": "Description",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Maras Suna",
|
"anonymous": "Maras Suna",
|
||||||
"logIn": "Shiga",
|
"logIn": "Shiga",
|
||||||
"signUp": "Yi Rajista",
|
"signUp": "Yi Rajista",
|
||||||
|
"newChat": "Sabon Tattaunawa",
|
||||||
|
"loadOlderMessages": "Loda saƙonni masu tsufa",
|
||||||
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
"preferencesDescription": "Sarrafa zaɓuɓɓukan aikace-aikacenku da saitunan bayyanar.",
|
||||||
"theme": "Jigogi",
|
"theme": "Jigogi",
|
||||||
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
"themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Onye na-amaghị aha",
|
"anonymous": "Onye na-amaghị aha",
|
||||||
"logIn": "Banye",
|
"logIn": "Banye",
|
||||||
"signUp": "Debanye aha",
|
"signUp": "Debanye aha",
|
||||||
|
"newChat": "Nkata Ọhụrụ",
|
||||||
|
"loadOlderMessages": "Bulite ozi ochie",
|
||||||
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
"preferencesDescription": "Jikwaa nhọrọ ngwa gị na ntọala ngosipụta.",
|
||||||
"theme": "Isiokwu",
|
"theme": "Isiokwu",
|
||||||
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
"themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Anônimo",
|
"anonymous": "Anônimo",
|
||||||
"logIn": "Entrar",
|
"logIn": "Entrar",
|
||||||
"signUp": "Cadastrar",
|
"signUp": "Cadastrar",
|
||||||
|
"newChat": "Nova Conversa",
|
||||||
|
"loadOlderMessages": "Carregar mensagens anteriores",
|
||||||
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
"preferencesDescription": "Gerencie suas preferências gerais da aplicação e configurações de aparência.",
|
||||||
"theme": "Tema",
|
"theme": "Tema",
|
||||||
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
"themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "Alainidamọ",
|
"anonymous": "Alainidamọ",
|
||||||
"logIn": "Wọle",
|
"logIn": "Wọle",
|
||||||
"signUp": "Forukọsilẹ",
|
"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.",
|
"preferencesDescription": "Ṣakoso awọn ayanfẹ ohun elo rẹ ati awọn eto iwoye.",
|
||||||
"theme": "Akori",
|
"theme": "Akori",
|
||||||
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
"themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.",
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
"anonymous": "匿名",
|
"anonymous": "匿名",
|
||||||
"logIn": "登录",
|
"logIn": "登录",
|
||||||
"signUp": "注册",
|
"signUp": "注册",
|
||||||
|
"newChat": "新对话",
|
||||||
|
"loadOlderMessages": "加载更早的消息",
|
||||||
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
"preferencesDescription": "管理您的应用程序偏好设置和外观设置。",
|
||||||
"theme": "主题",
|
"theme": "主题",
|
||||||
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
"themeDescription": "选择浅色、深色或系统主题偏好。",
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { CreditsBadge } from '@/components/CreditsBadge';
|
|||||||
import { useAISettings } from '@/hooks/useAISettings';
|
import { useAISettings } from '@/hooks/useAISettings';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
|
||||||
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
|
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
|
||||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
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 { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
|
||||||
const { user } = useCurrentUser();
|
const { user } = useCurrentUser();
|
||||||
const { config, defaultConfig, updateConfig } = useAppContext();
|
const { config, defaultConfig, updateConfig } = useAppContext();
|
||||||
|
const openRouterOAuth = useOpenRouterOAuth();
|
||||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||||
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
|
||||||
|
|
||||||
@@ -54,6 +56,7 @@ export function AISettings() {
|
|||||||
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
|
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
|
||||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||||
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
|
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
|
||||||
|
const [forceManualEntry, setForceManualEntry] = useState(false);
|
||||||
|
|
||||||
// Drag and drop sensors
|
// Drag and drop sensors
|
||||||
const sensors = useSensors(
|
const sensors = useSensors(
|
||||||
@@ -256,9 +259,18 @@ export function AISettings() {
|
|||||||
{selectedPreset && (
|
{selectedPreset && (
|
||||||
<AddAIProviderDialog
|
<AddAIProviderDialog
|
||||||
open={addDialogOpen}
|
open={addDialogOpen}
|
||||||
onOpenChange={setAddDialogOpen}
|
onOpenChange={(open) => {
|
||||||
|
setAddDialogOpen(open);
|
||||||
|
if (!open) {
|
||||||
|
// Reset force manual entry when dialog closes
|
||||||
|
setForceManualEntry(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
preset={selectedPreset}
|
preset={selectedPreset}
|
||||||
isLoggedIntoNostr={!!user}
|
isLoggedIntoNostr={!!user}
|
||||||
|
oauthHook={selectedPreset.id === 'openrouter' ? openRouterOAuth : null}
|
||||||
|
forceManualEntry={forceManualEntry}
|
||||||
|
onSetForceManualEntry={setForceManualEntry}
|
||||||
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
|
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import type { PresetDeployProvider } from '@/lib/deploy/types';
|
|||||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||||
import { AddProviderDialog } from '@/components/AddProviderDialog';
|
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||||
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
|
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
|
||||||
import {
|
import {
|
||||||
DndContext,
|
DndContext,
|
||||||
@@ -384,7 +384,7 @@ export function DeploySettings() {
|
|||||||
|
|
||||||
{/* Add Preset Provider Dialog */}
|
{/* Add Preset Provider Dialog */}
|
||||||
{selectedPreset && (
|
{selectedPreset && (
|
||||||
<AddProviderDialog
|
<AddDeployProviderDialog
|
||||||
open={addDialogOpen}
|
open={addDialogOpen}
|
||||||
onOpenChange={setAddDialogOpen}
|
onOpenChange={setAddDialogOpen}
|
||||||
preset={selectedPreset}
|
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}
|
icon={Settings}
|
||||||
titleKey="systemSettings"
|
titleKey="systemSettings"
|
||||||
descriptionKey="systemSettingsDescription"
|
descriptionKey="systemSettingsDescription"
|
||||||
|
className="space-y-2"
|
||||||
>
|
>
|
||||||
{/* Service Worker Configuration */}
|
{/* Service Worker Configuration */}
|
||||||
<Accordion type="single" collapsible className="w-full">
|
<Accordion type="single" collapsible className="w-full">
|
||||||
@@ -767,7 +768,7 @@ export function SystemSettings() {
|
|||||||
</div>
|
</div>
|
||||||
</AccordionTrigger>
|
</AccordionTrigger>
|
||||||
<AccordionContent className="px-4 pb-4">
|
<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="space-y-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
|
||||||
@@ -804,9 +805,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('projectsDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -845,9 +843,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('configDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -886,9 +881,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('temporaryDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -927,9 +919,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('pluginsDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
@@ -968,9 +957,6 @@ export function SystemSettings() {
|
|||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('templatesDirectoryDescription')}
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</AccordionContent>
|
</AccordionContent>
|
||||||
|
|||||||
Reference in new issue
Block a user