Compare commits

...
Author SHA1 Message Date
lemonknowsall c41e87f563 badge issuer key single location 2026-01-07 19:46:01 -08:00
lemonknowsall 14681ff31b update languages for badge progress tracking 2026-01-07 19:46:01 -08:00
lemonknowsall 27e474c16e update badge issuer hardcode to be bech32 2026-01-07 19:46:01 -08:00
lemonknowsall 27d7096cc2 award progress tracker 2026-01-07 19:46:01 -08:00
lemonknowsall 064fba16d0 add fanfare award trumpet 2026-01-07 19:46:01 -08:00
lemonknowsall f9d883d3c4 update languages for badge page 2026-01-07 19:46:01 -08:00
lemonknowsall 94dfe21bac award dates and progress bars 2026-01-07 19:46:00 -08:00
lemonknowsall bc19d08a8a badge notification and modal 2026-01-07 19:46:00 -08:00
lemonknowsall 575536eb35 badge awards 2026-01-07 19:46:00 -08:00
Alex Gleason 22885e0978 Fix z-index of GitSync warning popover 2026-01-07 20:09:07 -06:00
Alex Gleason a988238bb4 Add Continue button to GitSync warning popover 2026-01-07 19:31:39 -06:00
Alex Gleason 11197139f9 Add back totalCommits check 2026-01-07 19:23:51 -06:00
Alex Gleason 9ccad00888 Reset state of GitSyncButton when navigating between projects 2026-01-07 19:18:34 -06:00
Alex Gleason 32ff6570cf Add GitSyncButton popover nag 2026-01-07 19:15:55 -06:00
Alex Gleason 80bb72ef79 Only delete origin header in proxy 2026-01-04 15:56:18 -06:00
Alex Gleason e45f167d2b Drop browser-specific headers from CORS proxy service 2026-01-04 14:35:01 -06:00
Alex Gleason 7e755916c0 Clean up System Settings 2026-01-04 13:06:35 -06:00
Alex Gleason 5915b96d98 Use ExternalInput in OnboardingDialog 2026-01-04 12:53:09 -06:00
Alex Gleason b327607be3 AddProviderDialog -> AddDeployProviderDialog, refactor GitHub OAuth to be less hardcoded 2026-01-04 12:44:27 -06:00
Alex Gleason e23b5031ee Remove favicons from OAuth connect buttons 2026-01-04 12:39:04 -06:00
Alex Gleason 104a08c75a Add OpenRouter OAuth 2026-01-04 12:36:15 -06:00
Alex Gleason ddc23e3800 Fix favicon service hostname logic 2026-01-04 12:10:00 -06:00
Alex Gleason a1959369c5 Don't emit unnecessary streamingUpdate events 2026-01-04 00:46:45 -06:00
Alex Gleason 6c4c1dab3b Fix tool_calls index logic 2026-01-04 00:35:10 -06:00
32 changed files with 1449 additions and 166 deletions

No files matched your search

+42 -2
View File
@@ -15,6 +15,7 @@ The OAuth system consists of three main components:
- **GitHub** - Git repository hosting (with PKCE support)
- **Netlify** - Static site deployment
- **Vercel** - Static site deployment
- **OpenRouter** - AI model routing (with PKCE support)
## File Structure
@@ -24,11 +25,13 @@ src/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
│ └── useVercelOAuth.ts # Vercel-specific configuration
│ ├── useVercelOAuth.ts # Vercel-specific configuration
│ └── useOpenRouterOAuth.ts # OpenRouter-specific configuration
├── pages/
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
│ └── VercelOAuth.tsx # Vercel OAuth callback page
│ ├── VercelOAuth.tsx # Vercel OAuth callback page
│ └── OpenRouterOAuth.tsx # OpenRouter OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
```
@@ -190,6 +193,7 @@ const config: OAuthConfig = {
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
- ✅ OpenRouter - Requires PKCE (enabled)
### Scope Parameter
@@ -199,6 +203,42 @@ The `scope` parameter is optional in the OAuth configuration. Some providers (li
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
- ❌ Netlify - No scope parameter (permissions set in app settings)
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
- ❌ OpenRouter - No scope parameter (uses PKCE for authorization)
### OpenRouter Custom OAuth Implementation
OpenRouter uses a custom OAuth flow that differs from the standard OAuth 2.0 specification. Instead of using the generic `useOAuth` hook, it has a dedicated `useOpenRouterOAuth` hook with the following key differences:
1. **No Client Credentials**: OpenRouter doesn't require client ID or client secret - it uses PKCE only
2. **Authorization URL**: Uses `callback_url` parameter instead of `redirect_uri`
3. **Token Exchange**: Posts to `/api/v1/auth/keys` with a simplified request body
4. **Response Format**: Returns `{ key }` instead of standard `{ access_token }`
5. **PKCE Required**: Must use PKCE with S256 code challenge method
6. **No User Info**: Doesn't provide a user info endpoint after authentication
7. **No Environment Variables**: No configuration needed - works out of the box
**Authorization URL Format:**
```
https://openrouter.ai/auth?callback_url=<REDIRECT_URI>&code_challenge=<CHALLENGE>&code_challenge_method=S256
```
**Token Exchange Request:**
```json
{
"code": "<CODE_FROM_QUERY_PARAM>",
"code_verifier": "<CODE_VERIFIER>",
"code_challenge_method": "S256"
}
```
**Token Exchange Response:**
```json
{
"key": "sk-or-v1-..."
}
```
This custom implementation is fully contained in `useOpenRouterOAuth.ts` and doesn't rely on the generic OAuth hook. Unlike other providers, OpenRouter's OAuth doesn't require any environment variables or application registration - it works immediately without configuration.
## Adding a New OAuth Provider
+33 -11
View File
@@ -195,6 +195,7 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5",
@@ -1830,6 +1831,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@@ -1853,6 +1855,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
}
@@ -1874,6 +1877,7 @@
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
@@ -5442,8 +5446,7 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@types/chrome": {
"version": "0.0.74",
@@ -5655,6 +5658,7 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.0.2"
@@ -5666,6 +5670,7 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^18.0.0"
}
@@ -5749,6 +5754,7 @@
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.31.1",
"@typescript-eslint/types": "8.31.1",
@@ -6108,6 +6114,7 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -6622,6 +6629,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -6851,6 +6859,7 @@
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"license": "MIT",
"peer": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
@@ -7610,8 +7619,7 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/dom-helpers": {
"version": "5.2.1",
@@ -7676,7 +7684,8 @@
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/embla-carousel-react": {
"version": "8.6.0",
@@ -7962,6 +7971,7 @@
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -8227,6 +8237,7 @@
"resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz",
"integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==",
"license": "MIT",
"peer": true,
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.2.0",
@@ -9324,6 +9335,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.27.6"
},
@@ -10117,6 +10129,7 @@
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"cssstyle": "^4.2.1",
"data-urls": "^5.0.0",
@@ -10501,7 +10514,6 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@@ -12255,6 +12267,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
@@ -12422,7 +12435,6 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@@ -12438,7 +12450,6 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
@@ -12449,7 +12460,6 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@@ -12462,8 +12472,7 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/prismjs": {
"version": "1.30.0",
@@ -12637,6 +12646,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -12663,6 +12673,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -12688,6 +12699,7 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -12736,6 +12748,7 @@
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0",
@@ -13278,6 +13291,7 @@
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.7"
},
@@ -14332,6 +14346,7 @@
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT",
"peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -14535,6 +14550,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -14830,6 +14846,7 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -15357,6 +15374,7 @@
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@@ -15501,6 +15519,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15972,6 +15991,7 @@
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
@@ -16048,6 +16068,7 @@
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"rollup": "dist/bin/rollup"
},
@@ -16496,6 +16517,7 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
Binary file not shown.
+7 -6
View File
@@ -24,8 +24,13 @@ export default {
return new Response('Invalid url parameter', { status: 400 });
}
let hostname = url.hostname;
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
hostname = hostname.replace(/^(ai\.|api\.)/, '');
// GitHub hack: neutral color for light/dark mode
if (url.hostname === 'github.com') {
if (hostname === 'github.com') {
const svg = await (await fetch('https://github.githubassets.com/favicons/favicon.svg')).text();
return new Response(svg.replaceAll('#24292E', '#808080'), {
headers: { 'Content-Type': 'image/svg+xml' },
@@ -33,20 +38,16 @@ export default {
}
// AI-provider-specific hacks
let hostname = url.hostname;
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
hostname = 'ollama.com';
} else if (url.host === 'localhost:45554' || url.origin === '127.0.0.1:45554') {
hostname = 'claude.ai';
} else if (url.host === 'generativelanguage.googleapis.com') {
hostname = 'gemini.google.com';
} else if (url.host === 'api.z.ai') {
} else if (url.host === 'z.ai') {
hostname = 'docs.z.ai';
}
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
hostname = hostname.replace(/^(ai\.|api\.)/, '');
// Fetch the favicon from DuckDuckGo's service
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
},
+9 -8
View File
@@ -12,16 +12,17 @@ export default {
return new Response(null, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
"Access-Control-Allow-Headers": "*", // Or specify specific headers
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
"access-control-allow-origin": "*",
"access-control-allow-methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
"access-control-allow-headers": "*", // Or specify specific headers
"access-control-max-age": "86400", // Cache preflight for 24 hours
}
});
}
const headers = new Headers(request.headers);
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
headers.set('user-agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
headers.delete('origin');
const targetResponse = await fetch(target, {
method: request.method,
@@ -31,9 +32,9 @@ export default {
const response = new Response(targetResponse.body, targetResponse);
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
response.headers.set("Access-Control-Allow-Headers", "*");
response.headers.set("access-control-allow-origin", "*");
response.headers.set("access-control-allow-methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
response.headers.set("access-control-allow-headers", "*");
return response;
}
+2
View File
@@ -28,6 +28,7 @@ import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { BadgeAwardNotification } from '@/components/BadgeAwardNotification';
import AppRouter from './AppRouter';
@@ -152,6 +153,7 @@ export function App() {
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<BadgeAwardNotification />
<Suspense>
<AppRouter />
</Suspense>
+4
View File
@@ -14,10 +14,12 @@ import DeploySettings from "./pages/DeploySettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import AboutSettings from "./pages/AboutSettings";
import BadgesSettings from "./pages/BadgesSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -39,6 +41,7 @@ export function AppRouter() {
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
@@ -49,6 +52,7 @@ export function AppRouter() {
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="about" element={<AboutSettings />} />
<Route path="badges" element={<BadgesSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
+78 -4
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Bot } from 'lucide-react';
import { Bot, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { ExternalInput } from '@/components/ui/external-input';
@@ -12,15 +12,31 @@ import {
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { Link } from 'react-router-dom';
import type { PresetProvider } from '@/lib/aiProviderPresets';
interface OAuthHook {
isOAuthConfigured: boolean;
isLoading: boolean;
error: string | null;
initiateOAuth: () => void;
}
interface AddAIProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetProvider;
isLoggedIntoNostr: boolean;
oauthHook?: OAuthHook | null;
forceManualEntry?: boolean;
onSetForceManualEntry?: (force: boolean) => void;
onAdd: (apiKey: string) => void;
}
@@ -29,6 +45,9 @@ export function AddAIProviderDialog({
onOpenChange,
preset,
isLoggedIntoNostr,
oauthHook,
forceManualEntry = false,
onSetForceManualEntry,
onAdd,
}: AddAIProviderDialogProps) {
const { t } = useTranslation();
@@ -36,16 +55,27 @@ export function AddAIProviderDialog({
const [termsAgreed, setTermsAgreed] = useState(false);
const showNostrLoginRequired = preset.nostr && !isLoggedIntoNostr;
const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false;
const isOAuthLoading = oauthHook?.isLoading ?? false;
const oauthError = oauthHook?.error ?? null;
const handleAdd = () => {
onAdd(apiKey);
setApiKey('');
setTermsAgreed(false);
onOpenChange(false);
};
// Reset state when dialog closes
const handleOpenChange = (open: boolean) => {
if (!open) {
setApiKey('');
setTermsAgreed(false);
}
onOpenChange(open);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<div className="flex items-center gap-2">
@@ -73,6 +103,50 @@ export function AddAIProviderDialog({
</Link>
</Button>
</div>
) : isOAuthConfigured && !forceManualEntry ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onSetForceManualEntry?.(true)}>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
<div className="space-y-3">
{!preset.nostr && preset.apiKeysURL && (
@@ -123,7 +197,7 @@ export function AddAIProviderDialog({
)}
</div>
{!showNostrLoginRequired && (
{!showNostrLoginRequired && !(isOAuthConfigured && !forceManualEntry) && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
@@ -28,7 +28,7 @@ interface OAuthHook {
initiateOAuth: () => void;
}
interface AddProviderDialogProps {
interface AddDeployProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
preset: PresetDeployProvider;
@@ -39,7 +39,7 @@ interface AddProviderDialogProps {
onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void;
}
export function AddProviderDialog({
export function AddDeployProviderDialog({
open,
onOpenChange,
preset,
@@ -48,7 +48,7 @@ export function AddProviderDialog({
forceManualEntry,
onSetForceManualEntry,
onAdd,
}: AddProviderDialogProps) {
}: AddDeployProviderDialogProps) {
const { t } = useTranslation();
const [apiKey, setApiKey] = useState('');
const [accountId, setAccountId] = useState('');
@@ -112,16 +112,9 @@ export function AddProviderDialog({
Connecting...
</>
) : (
<>
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Rocket size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
</>
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
)}
</Button>
<DropdownMenu>
+8 -15
View File
@@ -84,8 +84,8 @@ export function AddGitCredentialDialog({
</DialogHeader>
<div className="space-y-4 py-4">
{preset.id === 'github' && isOAuthConfigured && !forceManualEntry ? (
// Special rendering for GitHub OAuth
{isOAuthConfigured && !forceManualEntry ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
@@ -100,16 +100,9 @@ export function AddGitCredentialDialog({
Connecting...
</>
) : (
<>
<ExternalFavicon
url="https://github.com"
size={16}
fallback={<GitBranch size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to GitHub
</span>
</>
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
)}
</Button>
<DropdownMenu>
@@ -124,7 +117,7 @@ export function AddGitCredentialDialog({
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onSetForceManualEntry(true)}>
Enter API key
Enter token manually
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -136,7 +129,7 @@ export function AddGitCredentialDialog({
)}
</div>
) : (
// Standard token input
// Show manual token input
<ExternalInput
type="password"
placeholder={t('enterToken')}
@@ -153,7 +146,7 @@ export function AddGitCredentialDialog({
)}
</div>
{!(preset.id === 'github' && isOAuthConfigured && !forceManualEntry) && (
{!(isOAuthConfigured && !forceManualEntry) && (
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
{t('cancel')}
+135
View File
@@ -0,0 +1,135 @@
import { useEffect, useRef } from 'react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Award } from "lucide-react";
import type { NostrEvent } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { Skeleton } from "@/components/ui/skeleton";
import { BADGE_ISSUER_PUBKEY } from '@/pages/BadgesSettings';
interface BadgeAwardModalProps {
award?: NostrEvent | null;
badgeDefinition?: NostrEvent | null;
onClose: () => void;
}
export function BadgeAwardModal({ award, badgeDefinition: providedBadgeDefinition, onClose }: BadgeAwardModalProps) {
const { nostr } = useNostr();
const audioRef = useRef<HTMLAudioElement | null>(null);
// If we have a badge definition directly, use it
// Otherwise, extract from award event
let dTag: string | undefined;
if (providedBadgeDefinition) {
dTag = providedBadgeDefinition.tags.find(([t]) => t === "d")?.[1];
} else if (award) {
const aTag = award.tags.find(([t]) => t === "a")?.[1];
if (aTag) {
const [kindStr, pubkey, parsedDTag] = aTag.split(':');
if (kindStr === '30009' && pubkey === BADGE_ISSUER_PUBKEY && parsedDTag) {
dTag = parsedDTag;
}
}
}
// Fetch badge definition if we don't have it directly
const { data: fetchedBadgeDefinition, isLoading } = useQuery({
queryKey: ['badge-definition', BADGE_ISSUER_PUBKEY, dTag],
queryFn: async (c) => {
if (!dTag) return null;
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const events = await nostr.query([{
kinds: [30009],
authors: [BADGE_ISSUER_PUBKEY],
"#d": [dTag],
limit: 1,
}], { signal });
return events[0] || null;
},
enabled: !!dTag && !providedBadgeDefinition,
});
const badgeDefinition = providedBadgeDefinition || fetchedBadgeDefinition;
const isModalOpen = !!award || !!providedBadgeDefinition;
// Play sound when badge is awarded (only when award is present, not just viewing badge definition)
useEffect(() => {
if (award && badgeDefinition && isModalOpen && !isLoading) {
// Create audio element if it doesn't exist
if (!audioRef.current) {
audioRef.current = new Audio('/badgeAwarded.mp3');
audioRef.current.volume = 0.5; // Set volume to 50%
}
// Reset to beginning and play the sound
audioRef.current.currentTime = 0;
audioRef.current.play().catch((error) => {
// Silently handle autoplay restrictions
console.debug('Audio playback failed:', error);
});
}
}, [award, badgeDefinition, isModalOpen, isLoading]);
// Return null after all hooks if we don't have a badge definition
if (!badgeDefinition) return null;
const nameTag = badgeDefinition?.tags?.find(([t]) => t === "name")?.[1];
const descriptionTag = badgeDefinition?.tags?.find(([t]) => t === "description")?.[1];
const imageTag = badgeDefinition?.tags?.find(([t]) => t === "image")?.[1];
const thumbTags = badgeDefinition?.tags?.filter(([t]) => t === "thumb") || [];
const badgeName = nameTag || dTag || "Unnamed Badge";
const description = descriptionTag || "";
const imageUrl = imageTag || (thumbTags.length > 0 ? thumbTags[thumbTags.length - 1]?.[1] : null);
return (
<Dialog open={isModalOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="w-[min(90vw,600px)] aspect-square bg-transparent [&>button]:hidden border-0 ring-0 outline-none shadow-none flex items-center justify-center p-[min(4vw,2rem)]">
<DialogTitle className="sr-only">
{award ? `Badge Awarded: ${badgeName}` : badgeName}
</DialogTitle>
<DialogDescription className="sr-only">
{description || `Badge: ${badgeName}`}
</DialogDescription>
<div className="flex flex-col items-center justify-center space-y-[min(4vw,2rem)] w-full h-full">
{isLoading ? (
<>
<Skeleton className="w-[min(60vw,384px)] aspect-square rounded-lg" />
<div className="space-y-2 text-center w-full">
<Skeleton className="h-[clamp(1.5rem,4vw,2rem)] w-[min(80%,16rem)] mx-auto" />
<Skeleton className="h-[clamp(1rem,3vw,1.25rem)] w-[min(90%,20rem)] mx-auto" />
</div>
</>
) : (
<>
{/* Badge image */}
<div className="relative aspect-square w-[min(60vw,384px)] before:absolute before:inset-0 before:rounded-lg before:bg-white/30 before:blur-2xl before:animate-pulse before:-z-10">
{imageUrl ? (
<img
src={imageUrl}
alt={badgeName}
className="h-full w-full rounded-lg object-cover shadow-2xl"
/>
) : (
<Award className="h-full w-full text-primary drop-shadow-lg" />
)}
</div>
{/* Title */}
<div className="text-center space-y-[min(1vw,0.75rem)] w-full px-4">
<p className="text-[clamp(1.25rem,5vw,1.5rem)] font-semibold">{badgeName}</p>
{description && (
<p className="text-[clamp(0.875rem,3vw,1rem)] text-muted-foreground max-w-md mx-auto">
{description}
</p>
)}
</div>
</>
)}
</div>
</DialogContent>
</Dialog>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { useBadgeAwardNotifications } from '@/hooks/useBadgeAwardNotifications';
import { BadgeAwardModal } from './BadgeAwardModal';
/**
* Global badge award notification component.
* Listens for badge awards and displays a modal when a new badge is received.
* This component should be placed at the App level to work globally.
*/
export function BadgeAwardNotification() {
const { newAward, clearNewAward } = useBadgeAwardNotifications();
return <BadgeAwardModal award={newAward} onClose={clearNewAward} />;
}
+16 -25
View File
@@ -1,7 +1,7 @@
import { useState, useEffect, useRef } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, Search, Coins } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
@@ -9,7 +9,7 @@ import { Card, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { ExternalInput } from '@/components/ui/external-input';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions';
@@ -465,37 +465,28 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
{/* API Key Input Section */}
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
<div className="space-y-3 max-w-md mx-auto">
<div className="text-center">
<h3 className="text-lg font-semibold">
<h3 className="flex justify-center text-lg font-semibold gap-2">
<ExternalFavicon
url={selectedProvider.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<span>
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
</h3>
<p className="text-sm text-muted-foreground">
{selectedProvider.id === 'routstr' ? (
t('requiresCashuToken', { providerName: selectedProvider.name })
) : (
<>
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
{selectedProvider.apiKeysURL ? (
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
{t('apiKey')}
<ExternalLink className="inline-block h-4 w-4 ml-1" />
</a>
) : (
t('apiKey')
)}
</>
)}
</p>
</div>
<PasswordInput
</span>
</h3>
<ExternalInput
type="password"
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
value={providerApiKey}
onChange={(e) => setProviderApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && providerApiKey.trim()) {
if (e.key === 'Enter' && providerApiKey.trim() && agreedToProviderTerms) {
handleContinueFromProviderSelection();
}
}}
url={selectedProvider.apiKeysURL}
urlTitle="Get Key"
/>
</div>
)}
+8 -3
View File
@@ -17,6 +17,8 @@ interface SettingsPageLayoutProps {
children: ReactNode;
/** Optional className for the content container */
className?: string;
/** Optional element to render next to the title */
titleSuffix?: ReactNode;
}
/**
@@ -28,7 +30,8 @@ export function SettingsPageLayout({
titleKey,
descriptionKey,
children,
className,
className = 'space-y-6',
titleSuffix,
}: SettingsPageLayoutProps) {
const { t } = useTranslation();
const isMobile = useIsMobile();
@@ -48,9 +51,10 @@ export function SettingsPageLayout({
{t('backToSettings')}
</Button>
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<h1 className="text-2xl font-bold flex flex-wrap items-center gap-3">
<Icon className="h-6 w-6 text-primary" />
{t(titleKey)}
{titleSuffix}
</h1>
<p className="text-muted-foreground">
{t(descriptionKey)}
@@ -61,9 +65,10 @@ export function SettingsPageLayout({
{!isMobile && (
<div className="space-y-2">
<h1 className="text-2xl font-bold flex items-center gap-3">
<h1 className="text-2xl font-bold flex flex-wrap items-center gap-3">
<Icon className="h-6 w-6 text-primary" />
{t(titleKey)}
{titleSuffix}
</h1>
<p className="text-muted-foreground">
{t(descriptionKey)}
+92 -20
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef } from 'react';
import { CloudUpload, Loader2, Check } from 'lucide-react';
import { CloudUpload, Loader2, Check, AlertTriangle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useGitStatus } from '@/hooks/useGitStatus';
@@ -16,6 +16,8 @@ interface GitSyncButtonProps {
export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [open, setOpen] = useState(false);
const [syncSuccess, setSyncSuccess] = useState(false);
const [showWarningPopover, setShowWarningPopover] = useState(false);
const warningDismissed = useRef(false);
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
const { getError, getState } = useGitSyncState();
@@ -26,6 +28,18 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const gitSyncState = getState(dir);
const isGitActionOccurring = gitSyncState?.isActive ?? false;
const prevIsGitActionOccurring = useRef(isGitActionOccurring);
const prevProjectId = useRef(projectId);
// Reset state when projectId changes
useEffect(() => {
if (prevProjectId.current !== projectId) {
setSyncSuccess(false);
setShowWarningPopover(false);
warningDismissed.current = false;
prevIsGitActionOccurring.current = isGitActionOccurring;
prevProjectId.current = projectId;
}
}, [projectId, isGitActionOccurring]);
// Detect when a git action completes successfully
useEffect(() => {
@@ -38,6 +52,29 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
prevIsGitActionOccurring.current = isGitActionOccurring;
}, [isGitActionOccurring, hasError]);
// Check if we need to show the warning popover
const needsRemote = !isGitStatusLoading && gitStatus &&
!gitStatus.remotes.find(r => r.name === 'origin') &&
gitStatus.totalCommits > 1;
// Show warning popover when purple indicator is visible (only if not dismissed)
useEffect(() => {
if (needsRemote && !warningDismissed.current && gitStatus.totalCommits > 1) {
setShowWarningPopover(true);
} else {
setShowWarningPopover(false);
}
}, [gitStatus?.totalCommits, needsRemote]);
// Handle button click - dismiss warning popover permanently
const handleButtonClick = () => {
if (showWarningPopover) {
warningDismissed.current = true;
setShowWarningPopover(false);
}
setOpen(true);
};
// Determine which indicator to show (only one at a time, in priority order)
const renderIndicator = () => {
// Checkmark: sync just completed successfully - highest priority
@@ -78,26 +115,61 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
<>
{/* Warning popover - shown when purple indicator is visible */}
<Popover open={showWarningPopover} modal={false}>
<PopoverTrigger asChild>
<div className="relative">
{/* Main Git Sync popover */}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="sm"
className={cn("size-8 p-0 group relative", className)}
aria-label="Sync with Git"
onClick={handleButtonClick}
>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
</div>
</PopoverTrigger>
<PopoverContent
side="bottom"
align="center"
className="w-80 pointer-events-none z-40"
onOpenAutoFocus={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
>
<CloudUpload className={cn("size-5 group-hover:text-foreground", open ? "text-foreground" : "text-muted-foreground")} />
{renderIndicator()}
</Button>
</PopoverTrigger>
<PopoverContent
align="start"
className="w-96"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<GitSyncSteps projectId={projectId} onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
<div className="space-y-3 pointer-events-auto">
<div className="flex items-center gap-2">
<AlertTriangle className="size-5 text-primary shrink-0" />
<h4 className="font-semibold text-sm">Your project files are not safe</h4>
</div>
<p className="text-sm text-muted-foreground">
Your project files are stored in your browser session and could be deleted. Sync with git to back up your project.
</p>
<Button
onClick={handleButtonClick}
className="w-full"
size="sm"
>
Continue
</Button>
</div>
</PopoverContent>
</Popover>
</>
);
}
+105
View File
@@ -0,0 +1,105 @@
import { useEffect, useRef, useState } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from './useCurrentUser';
import type { NostrEvent } from '@nostrify/nostrify';
import { BADGE_ISSUER_PUBKEY } from '@/pages/BadgesSettings';
export function useBadgeAwardNotifications() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const [newAward, setNewAward] = useState<NostrEvent | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const isMountedRef = useRef(true);
const subscriptionStartTimeRef = useRef<number | null>(null);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
useEffect(() => {
if (!user?.pubkey) {
// Clear subscription if user logs out
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
return;
}
// Create abort controller for this subscription
const abortController = new AbortController();
abortControllerRef.current = abortController;
// Set the subscription start time to now, so we only get new events
const subscriptionStartTime = Math.floor(Date.now() / 1000);
subscriptionStartTimeRef.current = subscriptionStartTime;
// Set up subscription for new badge awards
const setupSubscription = async () => {
try {
const subscription = nostr.req([{
kinds: [8],
authors: [BADGE_ISSUER_PUBKEY],
"#p": [user.pubkey],
since: subscriptionStartTime, // Only get events from now onwards
}]);
// Process messages from the subscription
// Messages are in format: [type, subscriptionId, event]
for await (const msg of subscription) {
// Check if subscription was aborted or component unmounted
if (abortController.signal.aborted || !isMountedRef.current) {
break;
}
// Handle EVENT messages (msg[0] === 'EVENT')
if (msg[0] === 'EVENT') {
const event = msg[2] as NostrEvent;
// Only show if component is still mounted and not aborted
if (isMountedRef.current && !abortController.signal.aborted) {
setNewAward(event);
}
}
// EOSE (End of Stored Events) - subscription is complete for initial query
// We continue listening for new events, so we don't break here
if (msg[0] === 'EOSE') {
// Initial query complete, now listening for new events
continue;
}
}
} catch (error) {
// Subscription closed or error - this is normal on cleanup
// Ignore errors if we aborted or unmounted
if (abortController.signal.aborted || !isMountedRef.current) {
return;
}
console.error('Error in badge award subscription:', error);
}
};
setupSubscription();
// Cleanup on unmount or user change
return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
};
}, [nostr, user?.pubkey]);
const clearNewAward = () => {
setNewAward(null);
};
return {
newAward,
clearNewAward,
};
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { useAppContext } from './useAppContext';
import { proxyUrl } from '@/lib/proxyUrl';
export interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel';
provider: 'github' | 'netlify' | 'vercel' | 'openrouter';
clientId: string;
clientSecret: string;
authorizeUrl: string;
+164
View File
@@ -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,
};
}
+22 -13
View File
@@ -450,7 +450,7 @@ export class SessionManager {
let accumulatedContent = '';
let accumulatedReasoningContent = '';
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
const accumulatedToolCalls: Map<number, OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall> = new Map();
let finishReason: string | null = null;
// Process the stream
@@ -491,20 +491,29 @@ export class SessionManager {
const toolCallDelta = delta.tool_calls[i];
const index = toolCallDelta.index ?? i; // Fix for Gemini models
accumulatedToolCalls[index] ??= {
id: '',
type: 'function',
function: { name: '', arguments: '' }
};
let toolCall = accumulatedToolCalls.get(index);
if (!toolCall) {
toolCall = {
id: '',
type: 'function',
function: { name: '', arguments: '' },
};
}
const toolCall = accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
if (toolCallDelta.id) toolCall.id = toolCallDelta.id;
if (toolCallDelta.function?.name) toolCall.function.name = toolCallDelta.function.name;
if (toolCallDelta.function?.arguments) toolCall.function.arguments += toolCallDelta.function.arguments;
accumulatedToolCalls.set(index, toolCall);
}
if (session.streamingMessage) {
session.streamingMessage.tool_calls = accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined;
if (session.streamingMessage && accumulatedToolCalls.size > 0) {
const sortedToolCalls = [...accumulatedToolCalls.entries()]
.sort((a, b) => a[0] - b[0])
.map(entry => entry[1]);
session.streamingMessage.tool_calls = sortedToolCalls;
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
}
}
@@ -528,7 +537,7 @@ export class SessionManager {
}
// Fix tool calls with empty arguments or names
for (const toolCall of accumulatedToolCalls) {
for (const toolCall of accumulatedToolCalls.values()) {
if (toolCall.type === 'function') {
toolCall.function.arguments = toolCall.function.arguments || '{}';
@@ -549,7 +558,7 @@ export class SessionManager {
role: 'assistant',
content: accumulatedContent,
...(accumulatedReasoningContent && { reasoning_content: accumulatedReasoningContent }),
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
...(accumulatedToolCalls.size > 0 && { tool_calls: [...accumulatedToolCalls.values()] })
};
// Check if the assistant message is empty (no content, reasoning, or tool calls)
@@ -575,8 +584,8 @@ export class SessionManager {
}
// Handle tool calls
if (accumulatedToolCalls?.length) {
for (const toolCall of accumulatedToolCalls) {
if (accumulatedToolCalls?.size) {
for (const toolCall of accumulatedToolCalls.values()) {
if (toolCall.type !== 'function') continue;
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
+7 -1
View File
@@ -1,4 +1,4 @@
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } from 'lucide-react';
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket, Award } from 'lucide-react';
export interface SettingsItem {
id: string;
@@ -29,6 +29,12 @@ export const getSettingsCategories = (t: (key: string) => string): SettingsCateg
title: t('preferences'),
href: '/settings/preferences',
},
{
id: 'badges',
icon: Award,
title: t('badges'),
href: '/settings/badges',
},
],
},
{
+12 -19
View File
@@ -54,12 +54,9 @@
"showcaseModerator": "Showcase Moderator",
"showcaseModeratorDescription": "Nostr public key (npub) of the user who can moderate showcase submissions",
"filesystemPaths": "Filesystem Paths",
"projectsDirectory": "Projects Directory",
"projectsDirectoryDescription": "Filesystem path where projects are stored",
"configDirectory": "Config Directory",
"configDirectoryDescription": "Filesystem path where configuration files are stored",
"temporaryDirectory": "Temporary Directory",
"temporaryDirectoryDescription": "Filesystem path for temporary files",
"projectsDirectory": "Projects",
"configDirectory": "Config",
"temporaryDirectory": "Temporary",
"sentryDsn": "Sentry DSN",
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
"shareErrorReports": "Share error reports",
@@ -484,8 +481,7 @@
"skills": "Skills",
"noSkillsFound": "No skills found in this plugin.",
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
"pluginsDirectory": "Plugins Directory",
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
"pluginsDirectory": "Plugins",
"discoverPlugins": "Discover Plugins",
"discoverPluginsDescription": "Browse and install Shakespeare plugins shared on the Nostr network.",
"searchPlugins": "Search plugins...",
@@ -526,21 +522,12 @@
"discoveringTools": "Discovering tools...",
"toolsDiscovered": "{{count}} tool(s) discovered",
"toolDiscoveryFailed": "Failed to discover tools from this server",
"filesystemPaths": "Filesystem Paths",
"projectsDirectory": "Projects Directory",
"projectsDirectoryDescription": "Directory where projects are stored in the virtual filesystem.",
"configDirectory": "Config Directory",
"configDirectoryDescription": "Directory where configuration files are stored in the virtual filesystem.",
"temporaryDirectory": "Temporary Directory",
"temporaryDirectoryDescription": "Directory for temporary files in the virtual filesystem.",
"deleting": "Deleting...",
"modified": "Modified",
"restoreToDefault": "Restore to default",
"restoredToDefault": "Restored to Default",
"templateUpdateFailed": "Template Update Failed",
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
"templatesDirectory": "Templates Directory",
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
"templatesDirectory": "Templates",
"terminal": "Terminal",
"templateName": "Template Name",
"templateDescription": "Description",
@@ -574,5 +561,11 @@
"failedToDuplicateProject": "Failed to duplicate project",
"newProjectName": "New Project Name",
"duplicateProjectDescription": "Create a copy of this project with a new name",
"resume": "Resume"
"resume": "Resume",
"badges": "Badges",
"badgesDescription": "View and manage your earned badges and achievements",
"noBadgesFound": "No badges found",
"tokenProgress": "Tokens",
"imageProgress": "Images",
"nextBadgeAt": "Next badge at {{milestone}}"
}
+7 -1
View File
@@ -477,5 +477,11 @@
"failedToDuplicateProject": "An kasa kwafin aikin",
"newProjectName": "Sunan Sabon Aikin",
"duplicateProjectDescription": "Ƙirƙiri kwafin wannan aikin da sabon suna",
"resume": "Ci gaba"
"resume": "Ci gaba",
"badges": "Tambari",
"badgesDescription": "Duba da sarrafa tambarin da kuka samu da nasarorin",
"noBadgesFound": "Ba a sami tambari ba",
"tokenProgress": "Tokens",
"imageProgress": "Hotuna",
"nextBadgeAt": "Tambari na gaba a {{milestone}}"
}
+7 -1
View File
@@ -474,5 +474,11 @@
"failedToDuplicateProject": "Ọ dara ada imepụta ọrụ",
"newProjectName": "Aha Ọrụ Ọhụrụ",
"duplicateProjectDescription": "Mepụta oyiri nke ọrụ a na aha ọhụrụ",
"resume": "Gaa n'ihu"
"resume": "Gaa n'ihu",
"badges": "Baajị",
"badgesDescription": "Lelee ma jikwaa baajị na mmeri gị",
"noBadgesFound": "Achọtaghị baajị",
"tokenProgress": "Tokens",
"imageProgress": "Foto",
"nextBadgeAt": "Baajị ọzọ na {{milestone}}"
}
+7 -1
View File
@@ -486,5 +486,11 @@
"failedToDuplicateProject": "Falha ao duplicar projeto",
"newProjectName": "Nome do Novo Projeto",
"duplicateProjectDescription": "Criar uma cópia deste projeto com um novo nome",
"resume": "Retomar"
"resume": "Retomar",
"badges": "Distintivos",
"badgesDescription": "Visualizar e gerenciar seus distintivos e conquistas",
"noBadgesFound": "Nenhum distintivo encontrado",
"tokenProgress": "Tokens",
"imageProgress": "Imagens",
"nextBadgeAt": "Próximo distintivo em {{milestone}}"
}
+7 -1
View File
@@ -474,5 +474,11 @@
"failedToDuplicateProject": "O kuna lati ṣe ẹda iṣẹ akanṣe",
"newProjectName": "Orukọ Iṣẹ Akanṣe Tuntun",
"duplicateProjectDescription": "Ṣẹda ẹda ti iṣẹ akanṣe yii pẹlu orukọ tuntun",
"resume": "Tẹsiwaju"
"resume": "Tẹsiwaju",
"badges": "Àmì-ẹ̀yẹ",
"badgesDescription": "Wo ati ṣakoso àmì-ẹ̀yẹ àti àwọn àṣeyọrí rẹ",
"noBadgesFound": "Ko ri àmì-ẹ̀yẹ",
"tokenProgress": "Àwọn tókẹ̀n",
"imageProgress": "Àwọn àwòrán",
"nextBadgeAt": "Àmì-ẹ̀yẹ tó kàn ní {{milestone}}"
}
+7 -1
View File
@@ -486,5 +486,11 @@
"failedToDuplicateProject": "复制项目失败",
"newProjectName": "新项目名称",
"duplicateProjectDescription": "使用新名称创建此项目的副本",
"resume": "继续"
"resume": "继续",
"badges": "徽章",
"badgesDescription": "查看和管理您获得的徽章和成就",
"noBadgesFound": "未找到徽章",
"tokenProgress": "代币",
"imageProgress": "图片",
"nextBadgeAt": "下一个徽章需要 {{milestone}}"
}
+13 -1
View File
@@ -16,6 +16,7 @@ import { CreditsBadge } from '@/components/CreditsBadge';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useOpenRouterOAuth } from '@/hooks/useOpenRouterOAuth';
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
@@ -45,6 +46,7 @@ export function AISettings() {
const { settings, updateSettings, setProvider, removeProvider, setProviders, isLoading } = useAISettings();
const { user } = useCurrentUser();
const { config, defaultConfig, updateConfig } = useAppContext();
const openRouterOAuth = useOpenRouterOAuth();
const [showAdvanced, setShowAdvanced] = useState(false);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
@@ -54,6 +56,7 @@ export function AISettings() {
const [selectedPreset, setSelectedPreset] = useState<PresetProvider | null>(null);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
const [forceManualEntry, setForceManualEntry] = useState(false);
// Drag and drop sensors
const sensors = useSensors(
@@ -256,9 +259,18 @@ export function AISettings() {
{selectedPreset && (
<AddAIProviderDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
onOpenChange={(open) => {
setAddDialogOpen(open);
if (!open) {
// Reset force manual entry when dialog closes
setForceManualEntry(false);
}
}}
preset={selectedPreset}
isLoggedIntoNostr={!!user}
oauthHook={selectedPreset.id === 'openrouter' ? openRouterOAuth : null}
forceManualEntry={forceManualEntry}
onSetForceManualEntry={setForceManualEntry}
onAdd={(apiKey) => handleAddPresetProvider(selectedPreset, apiKey)}
/>
)}
+535
View File
@@ -0,0 +1,535 @@
import { Award, Lock } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { SettingsPageLayout } from '@/components/SettingsPageLayout';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { useNostr } from '@nostrify/react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Skeleton } from "@/components/ui/skeleton";
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAISettings } from '@/hooks/useAISettings';
import { useAppContext } from '@/hooks/useAppContext';
import { BadgeAwardModal } from '@/components/BadgeAwardModal';
import { cn } from '@/lib/utils';
import { useState, useMemo } from 'react';
import type { NostrEvent } from '@nostrify/nostrify';
import { createAIClient } from '@/lib/ai-client';
import { nip19 } from 'nostr-tools';
export const BADGE_ISSUER_NPUB = "npub1e0u5dfurw3dmd0n5lul873c5g3p89et6x372sa35spajcxjh4f6svcvahk";
export const BADGE_ISSUER_PUBKEY = nip19.decode(BADGE_ISSUER_NPUB).data as string;
// Badge sync response from the server
interface BadgeSyncResponse {
object: 'badge_sync';
synced: string[];
stats: {
generation_count: number;
total_tokens: number;
image_count: number;
has_lightning_payment: boolean;
giftcards_sent: number;
max_giftcard_amount: number;
};
milestones?: {
tokenMilestones: Array<{ threshold: number; type: 'generation' | 'tokens'; creditReward?: number }>;
imageMilestones: Array<{ count: number; creditReward?: number }>;
giftcardMilestones: Array<{ threshold: number; type: 'count' | 'amount'; creditReward?: number }>;
};
}
function formatNumber(num: number): string {
if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)}B`;
if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(1)}M`;
if (num >= 1_000) return `${(num / 1_000).toFixed(1)}K`;
return num.toString();
}
interface TokenMilestone {
threshold: number;
type: 'generation' | 'tokens';
creditReward?: number;
}
interface TokenProgressResult {
progress: number;
current: number;
next: number;
type: 'generation' | 'tokens';
}
function getTokenMilestoneProgress(
generationCount: number,
totalTokens: number,
milestones: TokenMilestone[]
): TokenProgressResult | null {
// Find the first uncompleted milestone
for (let i = 0; i < milestones.length; i++) {
const milestone = milestones[i];
const currentValue = milestone.type === 'generation' ? generationCount : totalTokens;
if (currentValue < milestone.threshold) {
// This is the next milestone to achieve
const prevMilestone = i > 0 ? milestones[i - 1] : null;
const prevThreshold = prevMilestone
? (prevMilestone.type === milestone.type ? prevMilestone.threshold : 0)
: 0;
const range = milestone.threshold - prevThreshold;
const progressInRange = currentValue - prevThreshold;
const progress = Math.min(100, Math.max(0, (progressInRange / range) * 100));
return {
progress,
current: currentValue,
next: milestone.threshold,
type: milestone.type,
};
}
}
// All milestones achieved
return null;
}
function getImageMilestoneProgress(
imageCount: number,
milestones: number[]
): { progress: number; current: number; next: number } | null {
// Find the first uncompleted milestone
for (let i = 0; i < milestones.length; i++) {
const milestone = milestones[i];
if (imageCount < milestone) {
const prevThreshold = i > 0 ? milestones[i - 1] : 0;
const range = milestone - prevThreshold;
const progressInRange = imageCount - prevThreshold;
const progress = Math.min(100, Math.max(0, (progressInRange / range) * 100));
return { progress, current: imageCount, next: milestone };
}
}
// All milestones achieved
return null;
}
function isCreditMilestone(milestone: number | null, creditMilestones: number[]): boolean {
return milestone !== null && creditMilestones.includes(milestone);
}
function BadgeCard({
event,
awarded,
unlockDate,
onClick
}: {
event: NostrEvent;
awarded: boolean;
unlockDate?: number | null;
onClick?: () => void;
}) {
const dTag = event.tags.find(([t]) => t === "d")?.[1];
const nameTag = event.tags.find(([t]) => t === "name")?.[1];
const descriptionTag = event.tags.find(([t]) => t === "description")?.[1];
const imageTag = event.tags.find(([t]) => t === "image")?.[1];
const thumbTags = event.tags.filter(([t]) => t === "thumb");
const badgeName = nameTag || dTag || "Unnamed Badge";
const description = descriptionTag || "";
const imageUrl = imageTag || (thumbTags.length > 0 ? thumbTags[thumbTags.length - 1]?.[1] : null);
const formattedDate = unlockDate
? new Date(unlockDate * 1000).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
})
: null;
return (
<Card
className={cn(
"transition-all bg-transparent border-none shadow-none h-full",
awarded ? "cursor-pointer hover:scale-105" : ""
)}
onClick={awarded ? onClick : undefined}
>
<CardHeader className="text-center p-0 h-full flex flex-col">
<div className="flex justify-center">
{imageUrl ? (
<img
src={imageUrl}
alt={badgeName}
className={cn(
"w-32 h-32 rounded-lg object-cover",
awarded ? "" : "opacity-50 grayscale blur-md"
)}
/>
) : null}
</div>
<div className="flex flex-col flex-1 mt-4">
{/* Title area - fixed height for 2 lines */}
<div className="min-h-[3.5rem] flex items-start justify-center">
{awarded ? (
<CardTitle className="text-lg leading-tight line-clamp-2">
{badgeName}
</CardTitle>
) : (
<Lock className="h-5 w-5 text-muted-foreground mt-1" />
)}
</div>
{/* Description area - fixed height for 2 lines */}
{description && (
<p className={cn(
"text-sm min-h-[2.5rem] line-clamp-2 mt-1",
awarded ? "text-muted-foreground" : "text-muted-foreground/70"
)}>
{description}
</p>
)}
{/* Unlock date - pushed to bottom */}
<div className="mt-auto pt-2">
{awarded && formattedDate && (
<p className="text-xs text-muted-foreground/70">
Unlocked {formattedDate}
</p>
)}
</div>
</div>
</CardHeader>
</Card>
);
}
export function BadgesSettings() {
const { t } = useTranslation();
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { settings } = useAISettings();
const { config } = useAppContext();
const queryClient = useQueryClient();
const userPubkey = user?.pubkey;
const [selectedBadge, setSelectedBadge] = useState<NostrEvent | null>(null);
const [progressIndex, setProgressIndex] = useState(0);
// Find a Shakespeare provider (one with nostr auth) for badge sync
const shakespeareProvider = useMemo(
() => settings.providers.find(p => p.nostr),
[settings.providers]
);
// Badge sync query - calls the server to sync badges and get stats
const { data: syncData } = useQuery({
queryKey: ['badge-sync', userPubkey, shakespeareProvider?.id],
queryFn: async (): Promise<BadgeSyncResponse> => {
if (!shakespeareProvider || !user) {
throw new Error('No provider or user available');
}
const ai = createAIClient(shakespeareProvider, user, config.corsProxy);
const response = await ai.post('/badges/sync', {}) as BadgeSyncResponse;
// If any badges were synced, invalidate the badge awards query
if (response.synced.length > 0) {
queryClient.invalidateQueries({ queryKey: ['badge-awards', BADGE_ISSUER_PUBKEY, userPubkey] });
}
return response;
},
enabled: !!user && !!shakespeareProvider,
staleTime: 0, // Always refetch on mount for fresh progress
gcTime: 5 * 60 * 1000, // Keep in cache for 5 min
retry: 1,
});
// Get stats from sync response
const stats = syncData?.stats;
// Get milestones from server (no fallbacks - if server doesn't provide, use empty arrays)
const tokenMilestones = useMemo((): TokenMilestone[] => {
return syncData?.milestones?.tokenMilestones || [];
}, [syncData?.milestones]);
const imageMilestones = useMemo(() => {
return syncData?.milestones?.imageMilestones.map(m => m.count) || [];
}, [syncData?.milestones]);
// Get credit milestones (thresholds with credit rewards)
const creditMilestones = useMemo(() => {
return syncData?.milestones?.tokenMilestones
.filter(m => m.creditReward !== undefined)
.map(m => m.threshold) || [];
}, [syncData?.milestones]);
const tokenProgress = stats
? getTokenMilestoneProgress(stats.generation_count, stats.total_tokens, tokenMilestones)
: null;
const imageProgress = stats
? getImageMilestoneProgress(stats.image_count, imageMilestones)
: null;
const { data: badgeDefinitions, isLoading: isLoadingDefinitions } = useQuery({
queryKey: ['badge-definitions', BADGE_ISSUER_PUBKEY],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const events = await nostr.query([{
kinds: [30009],
authors: [BADGE_ISSUER_PUBKEY],
limit: 100,
}], { signal });
return events;
},
});
// Query for badge awards if user is logged in
const { data: badgeAwards, isLoading: isLoadingAwards } = useQuery({
queryKey: ['badge-awards', BADGE_ISSUER_PUBKEY, userPubkey],
queryFn: async (c) => {
if (!userPubkey) return [];
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const events = await nostr.query([{
kinds: [8],
authors: [BADGE_ISSUER_PUBKEY],
"#p": [userPubkey],
limit: 100,
}], { signal });
return events;
},
enabled: !!userPubkey,
});
// Create a map of awarded badges (a-tag -> first award date)
const awardedBadges = new Map<string, number>();
if (badgeAwards) {
for (const award of badgeAwards) {
const aTag = award.tags.find(([t]) => t === "a")?.[1];
if (aTag) {
// Store the earliest award date for this badge
const existingDate = awardedBadges.get(aTag);
if (!existingDate || award.created_at < existingDate) {
awardedBadges.set(aTag, award.created_at);
}
}
}
}
// Helper to check if a badge is awarded
const isBadgeAwarded = (badgeDefinition: NostrEvent): boolean => {
if (!userPubkey) return false;
const dTag = badgeDefinition.tags.find(([t]) => t === "d")?.[1];
if (!dTag) return false;
const aTag = `30009:${BADGE_ISSUER_PUBKEY}:${dTag}`;
return awardedBadges.has(aTag);
};
// Helper to get first award date for a badge
const getFirstAwardDate = (badgeDefinition: NostrEvent): number | null => {
if (!userPubkey) return null;
const dTag = badgeDefinition.tags.find(([t]) => t === "d")?.[1];
if (!dTag) return null;
const aTag = `30009:${BADGE_ISSUER_PUBKEY}:${dTag}`;
return awardedBadges.get(aTag) || null;
};
// Sort badges: unlocked by first award date (earliest first), then locked badges
const sortedBadgeDefinitions = badgeDefinitions ? [...badgeDefinitions].sort((a, b) => {
const aAwarded = isBadgeAwarded(a);
const bAwarded = isBadgeAwarded(b);
// If both are awarded, sort by first award date (earliest first)
if (aAwarded && bAwarded) {
const aDate = getFirstAwardDate(a) || 0;
const bDate = getFirstAwardDate(b) || 0;
return aDate - bDate;
}
// If only one is awarded, awarded comes first
if (aAwarded && !bAwarded) return -1;
if (!aAwarded && bAwarded) return 1;
// Both are locked, maintain original order
return 0;
}) : [];
const isLoading = isLoadingDefinitions || (userPubkey && isLoadingAwards);
// Calculate badge counts
const totalBadges = sortedBadgeDefinitions.length;
const unlockedBadges = sortedBadgeDefinitions.filter(badge => isBadgeAwarded(badge)).length;
const progressPercentage = totalBadges > 0 ? (unlockedBadges / totalBadges) * 100 : 0;
return (
<SettingsPageLayout
icon={Award}
titleKey="badges"
descriptionKey="badgesDescription"
titleSuffix={
!isLoading && totalBadges > 0 ? (
<div className="flex flex-wrap items-center gap-3 ml-3">
<Card className="bg-muted/50 border">
<CardContent className="py-1.5 px-4">
<p className="text-sm font-medium">
<span className="text-foreground">{unlockedBadges}</span>
<span className="text-muted-foreground"> / </span>
<span className="text-foreground">{totalBadges}</span>
<span className="text-muted-foreground"> unlocked</span>
</p>
</CardContent>
</Card>
<Card className="bg-muted/50 border">
<CardContent className="py-1.5 px-4">
<div className="flex items-center gap-2">
<Progress value={progressPercentage} className="h-1.5 w-24" />
<span className="text-sm font-medium">{Math.round(progressPercentage)}%</span>
</div>
</CardContent>
</Card>
</div>
) : undefined
}
>
<BadgeAwardModal
badgeDefinition={selectedBadge}
onClose={() => setSelectedBadge(null)}
/>
{/* Progress Tracking Section */}
{stats && (() => {
type ProgressItem =
| { category: 'token'; progress: TokenProgressResult }
| { category: 'image'; progress: { progress: number; current: number; next: number } };
const progressItems: ProgressItem[] = [];
if (tokenProgress) {
progressItems.push({ category: 'token', progress: tokenProgress });
}
if (imageProgress) {
progressItems.push({ category: 'image', progress: imageProgress });
}
if (progressItems.length === 0) return null;
const currentIndex = progressIndex % progressItems.length;
const current = progressItems[currentIndex];
// Format progress display based on milestone type
const formatProgress = () => {
if (current.category === 'token') {
const tokenProg = current.progress as TokenProgressResult;
const next = tokenProg.next ?? 0;
// For generation-based milestones, show simple numbers
if (tokenProg.type === 'generation') {
return `${tokenProg.current} / ${next}`;
}
// For token-based milestones, format large numbers
return `${formatNumber(tokenProg.current)} / ${formatNumber(next)}`;
}
// Image progress - simple numbers
return `${current.progress.current} / ${current.progress.next}`;
};
return (
<Card
className="mb-6 cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => setProgressIndex(prev => prev + 1)}
>
<CardContent className="py-4">
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-sm font-medium">
{current.category === 'token' ? t('tokenProgress') : t('imageProgress')}
</span>
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
{formatProgress()}
</span>
{current.category === 'token' && current.progress.next && isCreditMilestone(current.progress.next, creditMilestones) && (() => {
const milestone = syncData?.milestones?.tokenMilestones.find(m => m.threshold === current.progress.next);
const creditAmount = milestone?.creditReward ?? 0;
// Only show badge if credit amount is greater than 0
if (creditAmount <= 0) return null;
return (
<Badge variant="default" className="text-xs">
${creditAmount} Credit
</Badge>
);
})()}
</div>
</div>
<Progress value={current.progress.progress} className="h-2" />
<div className="flex justify-between items-center">
<p className="text-xs text-muted-foreground">
{t('nextBadgeAt', { milestone: formatNumber(current.progress.next ?? 0) })}
</p>
{progressItems.length > 1 && (
<div className="flex gap-1">
{progressItems.map((_, i) => (
<div
key={i}
className={cn(
"w-1.5 h-1.5 rounded-full transition-colors",
i === currentIndex ? "bg-primary" : "bg-muted-foreground/30"
)}
/>
))}
</div>
)}
</div>
</div>
</CardContent>
</Card>
);
})()}
<div className="space-y-4">
{isLoading ? (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{[1, 2, 3].map((i) => (
<Card key={i}>
<CardHeader className="text-center space-y-4">
<div className="flex justify-center">
<Skeleton className="w-32 h-32 rounded-lg" />
</div>
<div className="space-y-2">
<Skeleton className="h-5 w-32 mx-auto" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4 mx-auto" />
</div>
</CardHeader>
</Card>
))}
</div>
) : sortedBadgeDefinitions && sortedBadgeDefinitions.length > 0 ? (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{sortedBadgeDefinitions.map((event) => (
<BadgeCard
key={event.id}
event={event}
awarded={isBadgeAwarded(event)}
unlockDate={getFirstAwardDate(event)}
onClick={isBadgeAwarded(event) ? () => setSelectedBadge(event) : undefined}
/>
))}
</div>
) : (
<Card>
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<Award className="h-12 w-12 mx-auto text-muted-foreground" />
<p className="text-muted-foreground">
{t('noBadgesFound')}
</p>
</div>
</CardContent>
</Card>
)}
</div>
</SettingsPageLayout>
);
}
export default BadgesSettings;
+2 -2
View File
@@ -12,7 +12,7 @@ import type { PresetDeployProvider } from '@/lib/deploy/types';
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
import { AddProviderDialog } from '@/components/AddProviderDialog';
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
import {
DndContext,
@@ -384,7 +384,7 @@ export function DeploySettings() {
{/* Add Preset Provider Dialog */}
{selectedPreset && (
<AddProviderDialog
<AddDeployProviderDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
preset={selectedPreset}
+96
View File
@@ -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>
);
}
+2 -16
View File
@@ -257,6 +257,7 @@ export function SystemSettings() {
icon={Settings}
titleKey="systemSettings"
descriptionKey="systemSettingsDescription"
className="space-y-2"
>
{/* Service Worker Configuration */}
<Accordion type="single" collapsible className="w-full">
@@ -767,7 +768,7 @@ export function SystemSettings() {
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 py-1">
<div className="space-y-2">
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
@@ -804,9 +805,6 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('projectsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -845,9 +843,6 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('configDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -886,9 +881,6 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('temporaryDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -927,9 +919,6 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('pluginsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
@@ -968,9 +957,6 @@ export function SystemSettings() {
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('templatesDirectoryDescription')}
</p>
</div>
</div>
</AccordionContent>
+1 -1
View File
@@ -29,7 +29,7 @@ export default defineConfig(() => ({
plugins: [
react(),
VitePWA({
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3'],
includeAssets: ['shakespeare.svg', 'shakespeare-192x192.png', 'shakespeare-512x512.png', 'sine.mp3', 'badgeAwarded.mp3'],
manifest: false, // Use existing manifest.webmanifest from public folder
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],