Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(api): enhance error handling and rate limiting in chat proxy and conversation completion feat(ui): improve user experience with focus management and error display in chat components fix(dashboard): redirect unauthenticated users to login page in dashboard and settings

nirholased68028253af
diff --git a/CLAUDE.md b/CLAUDE.md
index 66cd1ae7e..5cefbbf57 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,70 +1,127 @@
# CLAUDE.md
-Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
+Behavioral guidelines for agents working in this repo. Bias toward **acting decisively on obvious work** while staying surgical and verifiable.
-**Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
+**North star:** Every turn should move the project forward. Asking the user to confirm something they obviously want is a failure mode, not a safety feature.
-## 1. Think Before Coding
+---
+
+## 1. Act, Don't Ask (the prime directive)
+
+**If the next step is obvious, take it. Show the diff, not a question.**
+
+Default to action when:
+
+- The user reports a bug → fix it.
+- A fix has an obvious follow-up (failing test, broken import, dead reference, type error your change introduced) → do it in the same turn.
+- The user says "this is broken" / "X doesn't work" / "why is Y happening" → diagnose AND fix, then explain.
+- A test fails for a reason directly tied to the task → fix it.
+- You find a typo, wrong path, or stale reference while doing the task → fix it.
+- The user has already approved the approach earlier in the conversation → keep going.
+
+**Banned phrases** (do not send these — just do the thing):
+
+- "Want me to fix this?"
+- "Should I also update X?" (when X is obviously coupled to the change)
+- "Do you want me to run the tests?"
+- "Shall I proceed?"
+- "Let me know if you'd like me to…"
+
+**Only stop and ask when:**
+
+- The action is **destructive and irreversible** (force push, drop table, rm -rf, history rewrite on shared branches).
+- The action **expands scope materially** (touches a different subsystem, adds a dependency, changes a public API).
+- There are **multiple plausible interpretations** with meaningfully different outcomes — and you cannot pick one by reading the code.
+- The user explicitly asked for a plan/review before changes.
+
+If you must ask, ask **once**, with a recommendation: *"I'm going to do X unless you object — alternative is Y."* Then proceed if no objection on the next turn.
+
+---
+
+## 2. Think Before Coding (but think fast)
+
+**Surface real ambiguity. Don't manufacture it.**
-**Don't assume. Don't hide confusion. Surface tradeoffs.**
+- State load-bearing assumptions in one line, then proceed.
+- If multiple interpretations exist AND they diverge meaningfully, present them. If they converge, pick one.
+- If a simpler approach exists, take it and say so in one sentence.
+- "Unclear" is not an excuse to stall. Name the smallest thing you need to unblock yourself, or make a defensible choice and flag it.
-Before implementing:
+The bar: a senior engineer would not have asked the question you're about to ask.
-- State your assumptions explicitly. If uncertain, ask.
-- If multiple interpretations exist, present them - don't pick silently.
-- If a simpler approach exists, say so. Push back when warranted.
-- If something is unclear, stop. Name what's confusing. Ask.
+---
-## 2. Simplicity First
+## 3. Simplicity First
**Minimum code that solves the problem. Nothing speculative.**
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
-- No error handling for impossible scenarios.
-- If you write 200 lines and it could be 50, rewrite it.
-
-Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
+- No error handling for impossible scenarios. Validate at boundaries only.
+- No comments explaining what well-named code already says.
+- If you wrote 200 lines and it could be 50, rewrite before showing.
-## 3. Surgical Changes
+---
-**Touch only what you must. Clean up only your own mess.**
+## 4. Surgical Changes
-When editing existing code:
+**Touch only what the task requires. Clean up only your own mess.**
- Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
-- Match existing style, even if you'd do it differently.
-- If you notice unrelated dead code, mention it - don't delete it.
+- Match existing style even if you'd do it differently.
+- Remove imports/variables/functions **your** change orphaned.
+- Don't delete pre-existing dead code unless asked — mention it instead.
+
+Test: every changed line traces directly to the user's request or to keeping the codebase consistent after your change.
+
+---
+
+## 5. Goal-Driven Execution
-When your changes create orphans:
+**Define success. Loop until verified. Then report.**
-- Remove imports/variables/functions that YOUR changes made unused.
-- Don't remove pre-existing dead code unless asked.
+Translate fuzzy asks into verifiable goals:
-The test: Every changed line should trace directly to the user's request.
+- "Add validation" → write tests for invalid inputs, make them pass.
+- "Fix the bug" → write a test that reproduces it, make it pass.
+- "Refactor X" → tests green before and after.
+- "Make it faster" → measure before, change, measure after.
-## 4. Goal-Driven Execution
+For multi-step work, hold a short plan internally and execute it. Don't narrate steps you haven't done. Don't ask the user to confirm steps inside an already-approved task.
-**Define success criteria. Loop until verified.**
+**Verify before claiming done:**
-Transform tasks into verifiable goals:
+- Code change → run the relevant tests / typecheck / lint.
+- UI change → exercise the path in a browser if possible; if not, say so explicitly.
+- Build/config change → run the build.
-- "Add validation" → "Write tests for invalid inputs, then make them pass"
-- "Fix the bug" → "Write a test that reproduces it, then make it pass"
-- "Refactor X" → "Ensure tests pass before and after"
+If verification fails, fix it. Don't hand back broken work with "tests are failing, want me to look?"
+
+---
+
+## 6. Reporting
+
+**Tight summaries. Diffs over prose.**
+
+- One or two sentences: what changed, what's next (if anything).
+- Reference files as `path:line` so the user can jump.
+- Do not re-list every file you edited — the diff already shows that.
+- Do not end with "let me know if you need anything else."
+
+---
-For multi-step tasks, state a brief plan:
+## 7. Escalation Ladder (when something blocks you)
-```
-1. [Step] → verify: [check]
-2. [Step] → verify: [check]
-3. [Step] → verify: [check]
-```
+In order, before pinging the user:
-Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
+1. **Read more code** — the answer is usually in an adjacent file.
+2. **Run the thing** — tests, the script, the build. Real output beats speculation.
+3. **Search history** — `git log -S`, `git blame`, recent commits.
+4. **Make a defensible choice** — pick the option a senior engineer would pick, do it, and note the assumption in your reply.
+5. **Then, and only then, ask.** Ask with a concrete recommendation, not an open question.
---
-**These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
+**These guidelines are working if:** the user rarely has to say "yes do it" or "of course fix it"; diffs are tight and on-topic; verification happens before the report; and obvious follow-ups land in the same turn as the original fix.
diff --git a/api/chat/proxy.js b/api/chat/proxy.js
index 7cd96ca35..f237489cb 100644
--- a/api/chat/proxy.js
+++ b/api/chat/proxy.js
@@ -1,7 +1,9 @@
import { env } from '../_lib/env.js';
-import { cors, error, method, wrap, readJson } from '../_lib/http.js';
+import { cors, error, json, method, wrap, readJson } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+const UPGRADE_URL = `${env.APP_ORIGIN}/pricing`;
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
@@ -10,7 +12,14 @@ export default wrap(async (req, res) => {
return error(res, 503, 'not_configured', 'Built-in model not available');
const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'Too many requests — try again shortly');
+ if (!rl.success) {
+ const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));
+ res.setHeader('retry-after', String(retryAfter));
+ return error(res, 429, 'rate_limited', 'Too many requests — try again shortly', {
+ retryAfter,
+ scope: 'ip',
+ });
+ }
let body;
try {
@@ -35,6 +44,29 @@ export default wrap(async (req, res) => {
body: JSON.stringify(body),
});
+ if (upstream.status === 402) {
+ const upstreamBody = await upstream.text();
+ const reason = /no_credits|insufficient/i.test(upstreamBody) ? 'no_credits' : 'plan_required';
+ return json(res, 402, {
+ error: 'payment_required',
+ error_description: 'Built-in model requires a funded plan',
+ reason,
+ upgradeUrl: UPGRADE_URL,
+ });
+ }
+
+ if (upstream.status === 429) {
+ const upstreamRetry = parseInt(upstream.headers.get('retry-after') ?? '', 10);
+ const retryAfter = Number.isFinite(upstreamRetry) && upstreamRetry > 0 ? upstreamRetry : 30;
+ res.setHeader('retry-after', String(retryAfter));
+ return json(res, 429, {
+ error: 'rate_limited',
+ error_description: 'Upstream provider rate limited the request',
+ retryAfter,
+ scope: 'agent',
+ });
+ }
+
res.statusCode = upstream.status;
const ct = upstream.headers.get('content-type') ?? 'application/json';
res.setHeader('content-type', ct);
diff --git a/api/skills/index.js b/api/skills/index.js
index 57a06cd6c..d3cc38342 100644
--- a/api/skills/index.js
+++ b/api/skills/index.js
@@ -6,7 +6,9 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const CATEGORY_RE = /^[a-z0-9-]{1,50}$/;
const VALID_SORTS = new Set(['popular', 'new', 'az']);
+const DEFAULT_SORT = 'popular';
const skillSlug = z
.string()
@@ -77,13 +79,37 @@ function toSkill(row, { includeInstalled = false, includeSchema = false } = {})
async function handleList(req, res) {
const url = new URL(req.url, 'http://x');
const q = (url.searchParams.get('q') || '').trim().slice(0, 80) || null;
- const category = url.searchParams.get('category') || null;
+ const categoryRaw = url.searchParams.get('category');
const sortParam = url.searchParams.get('sort') || '';
- const sort = VALID_SORTS.has(sortParam) ? sortParam : 'popular';
const cursor = url.searchParams.get('cursor') || null;
const limit = Math.min(50, Math.max(1, Number(url.searchParams.get('limit')) || 20));
const installedOnly = url.searchParams.get('installed') === 'true';
+ let category = null;
+ if (categoryRaw != null && categoryRaw !== '') {
+ if (!CATEGORY_RE.test(categoryRaw)) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ 'category must be a slug (lowercase letters, digits, hyphens)',
+ );
+ }
+ category = categoryRaw;
+ }
+
+ let sort = DEFAULT_SORT;
+ if (sortParam) {
+ if (VALID_SORTS.has(sortParam)) {
+ sort = sortParam;
+ } else {
+ console.warn('[api/skills] unknown sort, falling back to default', {
+ sort: sortParam,
+ url: req.url,
+ });
+ }
+ }
+
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
@@ -117,34 +143,141 @@ async function handleList(req, res) {
}
}
- // Build sort-specific ORDER BY and cursor condition as sql fragments
- let orderBy;
- let cursorCond;
+ // Neon's tagged-template `sql` does not compose nested fragments — each
+ // interpolation becomes a positional `$N` parameter. So we branch the full
+ // query per sort instead of building it from sql`...` fragments.
+ const rows = await runListQuery({
+ sort,
+ userId,
+ category,
+ qLike,
+ installedOnly,
+ cursor,
+ cursorInstallCount,
+ cursorCreatedAt,
+ cursorName,
+ limit,
+ });
+
+ const hasMore = rows.length > limit;
+ const skills = rows.slice(0, limit).map((r) => toSkill(r, { includeInstalled: userId != null }));
+
+ return json(res, 200, {
+ skills,
+ next_cursor: hasMore ? rows[limit - 1].id : null,
+ });
+}
+
+function runListQuery(p) {
+ const {
+ sort,
+ userId,
+ category,
+ qLike,
+ installedOnly,
+ cursor,
+ cursorInstallCount,
+ cursorCreatedAt,
+ cursorName,
+ limit,
+ } = p;
+
+ const limitPlus = limit + 1;
+
if (sort === 'new') {
- orderBy = sql`ms.created_at DESC, ms.id DESC`;
- cursorCond =
- cursor && cursorCreatedAt != null
- ? sql`AND (ms.created_at < ${cursorCreatedAt} OR (ms.created_at = ${cursorCreatedAt} AND ms.id::text < ${cursor}))`
- : sql``;
- } else if (sort === 'az') {
- orderBy = sql`ms.name ASC, ms.id ASC`;
- cursorCond =
- cursor && cursorName != null
- ? sql`AND (ms.name > ${cursorName} OR (ms.name = ${cursorName} AND ms.id::text > ${cursor}))`
- : sql``;
- } else {
- // popular (default)
- orderBy = sql`ms.install_count DESC, ms.id DESC`;
- cursorCond =
- cursor && cursorInstallCount != null
- ? sql`AND (ms.install_count < ${cursorInstallCount} OR (ms.install_count = ${cursorInstallCount} AND ms.id::text < ${cursor}))`
- : sql``;
+ const cursorActive = cursor && cursorCreatedAt != null;
+ return sql`
+ SELECT
+ ms.id, ms.name, ms.slug, ms.description, ms.category, ms.tags,
+ ms.install_count, ms.created_at, ms.author_id, ms.price_per_call_usd,
+ u.display_name AS author_display_name,
+ ROUND(COALESCE(AVG(sr.rating), 0)::numeric, 1)::float AS avg_rating,
+ COUNT(sr.rating)::int AS rating_count,
+ CASE WHEN ${userId}::uuid IS NOT NULL
+ THEN EXISTS(
+ SELECT 1 FROM skill_installs si
+ WHERE si.skill_id = ms.id AND si.user_id = ${userId}::uuid
+ )
+ ELSE NULL END AS installed
+ FROM marketplace_skills ms
+ LEFT JOIN users u ON u.id = ms.author_id AND u.deleted_at IS NULL
+ LEFT JOIN skill_ratings sr ON sr.skill_id = ms.id
+ WHERE ms.is_public = true
+ AND (
+ NOT ${cursorActive}
+ OR ms.created_at < ${cursorCreatedAt}::timestamptz
+ OR (ms.created_at = ${cursorCreatedAt}::timestamptz AND ms.id::text < ${cursor}::text)
+ )
+ AND (${category}::text IS NULL OR ms.category = ${category})
+ AND (
+ ${qLike}::text IS NULL
+ OR ms.name ILIKE ${qLike}
+ OR ms.description ILIKE ${qLike}
+ OR EXISTS (SELECT 1 FROM unnest(ms.tags) t WHERE t ILIKE ${qLike})
+ )
+ AND (
+ NOT ${installedOnly}
+ OR EXISTS(
+ SELECT 1 FROM skill_installs
+ WHERE skill_id = ms.id AND user_id = ${userId}::uuid
+ )
+ )
+ GROUP BY ms.id, ms.author_id, u.display_name
+ ORDER BY ms.created_at DESC, ms.id DESC
+ LIMIT ${limitPlus}
+ `;
+ }
+
+ if (sort === 'az') {
+ const cursorActive = cursor && cursorName != null;
+ return sql`
+ SELECT
+ ms.id, ms.name, ms.slug, ms.description, ms.category, ms.tags,
+ ms.install_count, ms.created_at, ms.author_id, ms.price_per_call_usd,
+ u.display_name AS author_display_name,
+ ROUND(COALESCE(AVG(sr.rating), 0)::numeric, 1)::float AS avg_rating,
+ COUNT(sr.rating)::int AS rating_count,
+ CASE WHEN ${userId}::uuid IS NOT NULL
+ THEN EXISTS(
+ SELECT 1 FROM skill_installs si
+ WHERE si.skill_id = ms.id AND si.user_id = ${userId}::uuid
+ )
+ ELSE NULL END AS installed
+ FROM marketplace_skills ms
+ LEFT JOIN users u ON u.id = ms.author_id AND u.deleted_at IS NULL
+ LEFT JOIN skill_ratings sr ON sr.skill_id = ms.id
+ WHERE ms.is_public = true
+ AND (
+ NOT ${cursorActive}
+ OR ms.name > ${cursorName}::text
+ OR (ms.name = ${cursorName}::text AND ms.id::text > ${cursor}::text)
+ )
+ AND (${category}::text IS NULL OR ms.category = ${category})
+ AND (
+ ${qLike}::text IS NULL
+ OR ms.name ILIKE ${qLike}
+ OR ms.description ILIKE ${qLike}
+ OR EXISTS (SELECT 1 FROM unnest(ms.tags) t WHERE t ILIKE ${qLike})
+ )
+ AND (
+ NOT ${installedOnly}
+ OR EXISTS(
+ SELECT 1 FROM skill_installs
+ WHERE skill_id = ms.id AND user_id = ${userId}::uuid
+ )
+ )
+ GROUP BY ms.id, ms.author_id, u.display_name
+ ORDER BY ms.name ASC, ms.id ASC
+ LIMIT ${limitPlus}
+ `;
}
- const rows = await sql`
+ // popular (default)
+ const cursorActive = cursor && cursorInstallCount != null;
+ return sql`
SELECT
ms.id, ms.name, ms.slug, ms.description, ms.category, ms.tags,
- ms.install_count, ms.created_at, ms.author_id,
+ ms.install_count, ms.created_at, ms.author_id, ms.price_per_call_usd,
u.display_name AS author_display_name,
ROUND(COALESCE(AVG(sr.rating), 0)::numeric, 1)::float AS avg_rating,
COUNT(sr.rating)::int AS rating_count,
@@ -158,7 +291,11 @@ async function handleList(req, res) {
LEFT JOIN users u ON u.id = ms.author_id AND u.deleted_at IS NULL
LEFT JOIN skill_ratings sr ON sr.skill_id = ms.id
WHERE ms.is_public = true
- ${cursorCond}
+ AND (
+ NOT ${cursorActive}
+ OR ms.install_count < ${cursorInstallCount}::integer
+ OR (ms.install_count = ${cursorInstallCount}::integer AND ms.id::text < ${cursor}::text)
+ )
AND (${category}::text IS NULL OR ms.category = ${category})
AND (
${qLike}::text IS NULL
@@ -174,17 +311,9 @@ async function handleList(req, res) {
)
)
GROUP BY ms.id, ms.author_id, u.display_name
- ORDER BY ${orderBy}
- LIMIT ${limit + 1}
+ ORDER BY ms.install_count DESC, ms.id DESC
+ LIMIT ${limitPlus}
`;
-
- const hasMore = rows.length > limit;
- const skills = rows.slice(0, limit).map((r) => toSkill(r, { includeInstalled: userId != null }));
-
- return json(res, 200, {
- skills,
- next_cursor: hasMore ? rows[limit - 1].id : null,
- });
}
async function handlePublish(req, res) {
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index 2329dfe85..25916fe2d 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -66,7 +66,7 @@
} from './feather.js';
import { defaultToolSchema, agentToolSchema, pumpToolSchema, curatedToolPacks } from './tools.js';
import { debounce, readFileAsDataURL } from './util.js';
- import { flash } from './actions';
+ import { flash, focusOnMount } from './actions';
import Message from './Message.svelte';
import { deleteSingleItem, initEncryption, sendSingleItem, syncPull, syncPush } from './sync.js';
import AgentPicker from './AgentPicker.svelte';
@@ -253,7 +253,9 @@
// Sync:
if ($syncServer.token && $syncServer.password) {
- syncPullPush(conversations, messages, convosMap); // async
+ syncPullPush(conversations, messages, convosMap).catch((e) => {
+ console.warn('[sync] pull/push failed:', e?.message || e);
+ }); // async
}
} catch (error) {
console.error('Error fetching history:', error);
@@ -484,6 +486,8 @@
}
}
+ let rateLimitedUntil = 0;
+
async function submitCompletion(insertUnclosed = true) {
window.speechSynthesis?.cancel();
if (!convo.models?.[0]?.provider) {
@@ -500,6 +504,21 @@
return;
}
+ const remaining = Math.ceil((rateLimitedUntil - Date.now()) / 1000);
+ if (remaining > 0) {
+ const msg = {
+ id: uuidv4(),
+ role: 'assistant',
+ error: `Slow down — try again in ${remaining}s.`,
+ content: '',
+ };
+ saveMessage(msg);
+ convo.messages.push(msg);
+ convo.messages = convo.messages;
+ saveConversation(convo);
+ return;
+ }
+
if (generating) {
$controller.abort();
}
@@ -781,7 +800,23 @@
}
};
- const onabort = () => {
+ const onabort = (err) => {
+ if (err && typeof err === 'object') {
+ if (err.code === 'payment_required') {
+ const url = err.upgradeUrl || '/pricing';
+ convo.messages[i].error = `Out of credits. [Upgrade your plan](${url}) to keep chatting.`;
+ } else if (err.code === 'rate_limited') {
+ const seconds = err.retryAfter ?? 30;
+ rateLimitedUntil = Date.now() + seconds * 1000;
+ convo.messages[i].error = `Slow down — too many requests. Try again in ${seconds}s.`;
+ } else {
+ convo.messages[i].error = err.message || String(err);
+ }
+ saveMessage(convo.messages[i]);
+ } else if (typeof err === 'string') {
+ convo.messages[i].error = err;
+ saveMessage(convo.messages[i]);
+ }
handleAbort();
};
@@ -1031,13 +1066,14 @@
async function shareConversation(event) {
event.currentTarget.dispatchEvent(new CustomEvent('flashSuccess'));
- const sharePromise = new Promise(async (resolve) => {
+ const sharePromise = (async () => {
const encoded = await compressAndEncode({
models: convo.models,
messages: convo.messages,
});
- const share = `${window.location.protocol}//${window.location.host}/?s=${encoded}`;
- if (share.length > 200) {
+ const longShare = `${window.location.protocol}//${window.location.host}/?s=${encoded}`;
+ if (longShare.length <= 200) return longShare;
+ try {
const data = new FormData();
data.append('pwd', 'muie_webshiti');
data.append('f:1', new Blob([encoded], { type: 'text/plain' }), 'content.txt');
@@ -1045,15 +1081,14 @@
method: 'POST',
body: data,
});
-
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
const shortenedLink = await response.text();
- resolve(
- `${window.location.protocol}//${window.location.host}/?sl=${shortenedLink.split('/').reverse()[1]}`
- );
- } else {
- resolve(`${window.location.protocol}//${window.location.host}/?s=${encoded}`);
+ return `${window.location.protocol}//${window.location.host}/?sl=${shortenedLink.split('/').reverse()[1]}`;
+ } catch (e) {
+ console.warn('[share] link shortener unreachable, falling back to long URL:', e?.message || e);
+ return longShare;
}
- });
+ })();
try {
const clipboardItem = new ClipboardItem({
@@ -1118,8 +1153,14 @@
if (params.has('s')) {
share = params.get('s');
} else if (params.has('sl')) {
- const response = await fetch(`https://sync.three.ws/p/${params.get('sl')}/`);
- share = await response.text();
+ try {
+ const response = await fetch(`https://sync.three.ws/p/${params.get('sl')}/`);
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ share = await response.text();
+ } catch (e) {
+ console.warn('[share] could not resolve shortened link:', e?.message || e);
+ return false;
+ }
}
if (!share) {
return false;
@@ -1836,7 +1877,7 @@
bind:value={historyConvo.title}
on:blur={() => { saveConversation(historyConvo); convos = { ...convos }; editingTitleId = null; }}
on:keydown={(e) => e.key === 'Enter' && e.target.blur()}
- autofocus
+ use:focusOnMount
/>
</div>
{:else}
diff --git a/chat/src/MessageContent.svelte b/chat/src/MessageContent.svelte
index 8e7026a7a..4250baa9b 100644
--- a/chat/src/MessageContent.svelte
+++ b/chat/src/MessageContent.svelte
@@ -7,7 +7,9 @@
</script>
{#if message.error}
- <span class="text-slate-600">{message.error}</span>
+ <span class="markdown text-slate-600 prose-a:underline">
+ <Markdown source={message.error} />
+ </span>
{:else if message.content}
<div
bind:clientHeight={contentHeight}
diff --git a/chat/src/SettingsModal.svelte b/chat/src/SettingsModal.svelte
index 84a0270e2..fe5751d47 100644
--- a/chat/src/SettingsModal.svelte
+++ b/chat/src/SettingsModal.svelte
@@ -36,7 +36,7 @@
import ClientTool from './ClientTool.svelte';
import Tooltip from './Tooltip.svelte';
import ModelSelector from './ModelSelector.svelte';
- import { sendSingleItem } from './sync.js';
+ import { sendSingleItem, resetSyncCircuit } from './sync.js';
const dispatch = createEventDispatcher();
@@ -325,14 +325,15 @@
<span class="mb-2 flex items-center">
<span class="ml-[3px]">Sync server address </span>
<Tooltip
- content="Run the three.ws chat sync server to sync your chats and API keys between devices. If you want to use our server instead of self-hosting leave this field as is."
+ content="Run a three.ws chat sync server to sync your chats and API keys between devices, then paste its URL here. There is no hosted server."
class="ml-2"
/>
</span>
<input
type="text"
bind:value={$syncServer.address}
- placeholder="Enter sync server address, or leave as is to use ours"
+ on:change={resetSyncCircuit}
+ placeholder="https://your-sync-server.example.com"
class="rounded-lg border border-slate-300 px-3 py-2 text-sm text-slate-800 transition-colors placeholder:text-gray-500 focus:border-slate-400 focus:outline-none"
/></label
>
diff --git a/chat/src/ToolDropdown.svelte b/chat/src/ToolDropdown.svelte
index 6ed5a9d6b..fef5f8fce 100644
--- a/chat/src/ToolDropdown.svelte
+++ b/chat/src/ToolDropdown.svelte
@@ -83,7 +83,7 @@
type="text"
bind:value={query}
placeholder="Search for tools"
- autofocus
+ use:focusOnMount
class="w-full rounded-lg border border-slate-300 px-3 py-2 text-[10px] text-slate-800 transition-colors placeholder:text-gray-500 focus:border-slate-400 focus:outline-none"
/>
</div>
diff --git a/chat/src/convo.js b/chat/src/convo.js
index 6e3b1b0bd..5bf7e90e5 100644
--- a/chat/src/convo.js
+++ b/chat/src/convo.js
@@ -154,9 +154,23 @@ export async function complete(convo, onupdate, onabort) {
const response = await completions(get(controller).signal);
if (!response.ok) {
- let msg = `API error ${response.status}`;
- try { const e = await response.json(); msg = e?.error_description || e?.error?.message || e?.message || msg; } catch {}
- throw new Error(msg);
+ let body = null;
+ try { body = await response.json(); } catch {}
+ const msg = body?.error_description || body?.error?.message || body?.message || `API error ${response.status}`;
+ const err = new Error(msg);
+ err.status = response.status;
+ if (response.status === 402) {
+ err.code = 'payment_required';
+ err.reason = body?.reason;
+ err.upgradeUrl = body?.upgradeUrl;
+ } else if (response.status === 429) {
+ const headerRetry = parseInt(response.headers.get('retry-after') ?? '', 10);
+ err.code = 'rate_limited';
+ err.retryAfter =
+ body?.retryAfter ?? (Number.isFinite(headerRetry) && headerRetry > 0 ? headerRetry : 30);
+ err.scope = body?.scope;
+ }
+ throw err;
}
if (stream) {
streamResponse(model.provider, response.body, onupdate, onabort);
@@ -166,7 +180,7 @@ export async function complete(convo, onupdate, onabort) {
}
} catch (err) {
if (err.name === 'AbortError') return;
- onabort?.(err.message || String(err));
+ onabort?.(err);
}
}
diff --git a/public/chat/index.html b/public/chat/index.html
index 33d3ffcf1..10bb75879 100644
--- a/public/chat/index.html
+++ b/public/chat/index.html
@@ -43,8 +43,8 @@
}
}
</script>
- <script type="module" crossorigin src="/chat/assets/index-BUlQu0kB.js"></script>
- <link rel="stylesheet" crossorigin href="/chat/assets/index-KKyHCyBB.css">
+ <script type="module" crossorigin src="/chat/assets/index-D0c87u8s.js"></script>
+ <link rel="stylesheet" crossorigin href="/chat/assets/index-BEwZt7nX.css">
</head>
<body>
<div id="app"></div>
diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.js
index 4f6b62910..04fdce579 100644
--- a/public/dashboard/dashboard.js
+++ b/public/dashboard/dashboard.js
@@ -2326,6 +2326,10 @@ async function renderAccount(root) {
wrap.innerHTML = `<div class="err">${esc(err.message)}</div>`;
return;
}
+ if (!user) {
+ location.href = '/login?next=' + encodeURIComponent(location.pathname + location.search);
+ return;
+ }
const profileUrl = user.username
? `${location.origin}/u/${encodeURIComponent(user.username)}`
diff --git a/public/dashboard/embed-policy.html b/public/dashboard/embed-policy.html
index 26d8b1d6f..a3ee42c1f 100644
--- a/public/dashboard/embed-policy.html
+++ b/public/dashboard/embed-policy.html
@@ -438,14 +438,18 @@
}
async function loadMe() {
+ let data;
try {
- await api('GET', '/api/auth/me');
- document.body.removeAttribute('data-auth-pending');
+ data = await api('GET', '/api/auth/me');
} catch {
+ data = null;
+ }
+ if (!data?.user) {
location.href =
'/login?next=' + encodeURIComponent(location.pathname + location.search);
throw new Error('redirecting');
}
+ document.body.removeAttribute('data-auth-pending');
}
async function loadAgent() {
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index 3a4f271e0..16167e358 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1246,15 +1246,19 @@
window.signOut = signOut;
(async () => {
+ let me;
try {
- const me = await api.me();
- state.user = me.user;
- document.getElementById('user-email').textContent = me.user.email;
+ me = await api.me();
} catch {
+ me = null;
+ }
+ if (!me?.user) {
location.href =
'/login?next=' + encodeURIComponent(location.pathname + location.hash);
return;
}
+ state.user = me.user;
+ document.getElementById('user-email').textContent = me.user.email;
navigate(location.hash.slice(1) || 'avatars');
window.addEventListener('hashchange', () =>
navigate(location.hash.slice(1) || 'avatars'),
diff --git a/public/dashboard/storage.html b/public/dashboard/storage.html
index 28da1e14a..cc653d25e 100644
--- a/public/dashboard/storage.html
+++ b/public/dashboard/storage.html
@@ -388,14 +388,18 @@
}
async function loadMe() {
+ let data;
try {
- await api('GET', '/api/auth/me');
- document.body.removeAttribute('data-auth-pending');
+ data = await api('GET', '/api/auth/me');
} catch {
+ data = null;
+ }
+ if (!data?.user) {
location.href =
'/login?next=' + encodeURIComponent(location.pathname + location.search);
throw new Error('redirecting');
}
+ document.body.removeAttribute('data-auth-pending');
}
async function loadAvatar() {
diff --git a/public/settings/index.html b/public/settings/index.html
index 87ca1f0ba..fd3f3f1d7 100644
--- a/public/settings/index.html
+++ b/public/settings/index.html
@@ -561,6 +561,10 @@
async function loadUser() {
const data = await apiJson('/api/auth/me');
+ if (!data.user) {
+ location.href = '/login?next=' + encodeURIComponent(location.pathname + location.hash);
+ throw new Error('unauthenticated');
+ }
user = data.user;
document.getElementById('user-email').textContent = user.email || user.display_name || '';
document.getElementById('inp-display-name').value = user.display_name || '';