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(portfolio): enhance portfolio styling and add allocation visualization

fudjia3afc8ba7e865
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e90410927..47c202cb0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **2,800+ new motion-capture animations in the library** — The animation library just grew from around 100 curated clips to more than 2,800 — the full professional motion-capture set, including complete themed movement packs (breakdance, sword-and-shield combat, capoeira, zombie, rifle and pistol sets, and more), every one retargeted to the universal three.ws skeleton so it plays on any humanoid avatar. Walks, runs, dances, combat, idles, reactions, sports, and hundreds more are all searchable in the animations gallery, previewable on a live avatar, and one click away from the pose studio or any embed. The clips are served from the CDN, so the site stays fast no matter how big the library gets. (`/animations`) `[feature, improvement]`
- **Agent creation now tells you what to do when your avatar library is full** — If you hit your plan's avatar limit while creating an agent, the wizard used to fail with a bare error and leave you stuck. It now explains what happened and gives you three ways forward, right in the form: connect an avatar you already own (one click jumps you to your library), free up a slot by deleting an old avatar, or upgrade your plan. Oversized model files get a clearer message too. (`/create-agent`) `[fix, improvement]`
- **Animation Gallery rebuilt — see every clip before you use it** — The animation gallery at three.ws/animations got a ground-up upgrade. All 2,100+ clips now show a real poster image of the avatar mid-motion instead of a blank tile, and hovering any card plays the full animation live in 3D. Clips are organized into 16 browsable categories (dance, combat, weapons, sports, and more) with search, sorting, and loop filters, and every clip has its own shareable link with playback controls — scrub the timeline, change the speed, then send it straight to the Animation Studio or copy an embed snippet for your own site. (`/animations`) `[feature, improvement]`
+- **Animation Studio — avatars no longer crumple when you preview a motion** — Loading your own avatar and playing a preset like Facepalm sometimes folded the whole character into a heap on the floor — even though the studio reported a clean "100% retargeted." The baked motion clips carry a per-bone scale and length channel from the character they were authored on, and those were being stamped onto your avatar, overwriting its own proportions. The Animation Studio now drives only what's actually motion — the joint rotations and the root's travel — and leaves every rig's bone lengths and scale untouched, so any avatar (tall, short, generated, Mixamo) plays every clip standing up in its own body. The "retargeted" percentage now counts only those real motion channels, so it reflects what you see. (`/pose`) `[fix]`
- **Faster, steadier pages under load — cache now compresses what it stores** — Behind the scenes, three.ws caches heavy data (live money flows, trending snapshots, leaderboards) in a shared store so pages stay fast without re-crunching everything on every visit. When that store sits far from our servers, the largest of those writes were timing out and quietly falling back to a per-server memory copy that vanishes on restart — so under traffic, pages kept hitting the origin and slowed down. Those payloads are now gzip-compressed before they're stored, shrinking them 5–10×, which lets them land in the shared cache instead of timing out. The result is fewer cache misses, less origin load, and steadier response times on data-heavy pages during busy periods. No action needed — it just works. `[fix, infra]`
- **Go Live: a real path to activate your agent even when the welcome grant is paused** — When the one-tap welcome grant is temporarily paused, the Go Live tab used to show a bare dead-end card. It's now a proper self-fund path: it explains that depositing your own SOL does the exact same thing — funds your agent and lands it on the live Money Pulse — shows how much is enough to go live, and reassures you the deposit stays yours and is withdrawable anytime. The grant reopens on its own when the treasury is back online. `[improvement]`
- **Go Pro with SOL or $THREE — 20% off in the platform coin** — The Pro plan is now a real self-serve upgrade you can buy on-chain. The pricing page checkout accepts USDC, SOL, or $THREE on Solana: pick your asset, scan a Solana Pay QR (or open it straight in your wallet), and your account upgrades the moment the payment finalizes. SOL and $THREE amounts are quoted at the live market price and pinned for the session, and paying in $THREE takes 20% off the sticker price — holding the coin already earns discounts, and now spending it does too. (`/pricing`) `[feature]`
diff --git a/api/agents/copilot.js b/api/agents/copilot.js
index 47137d69e..5264ca03b 100644
--- a/api/agents/copilot.js
+++ b/api/agents/copilot.js
@@ -365,9 +365,10 @@ function buildSystemPrompt({ agentName, persona, network }) {
`You are the in-world CONVERSATIONAL TRADING COPILOT for the three.ws agent "${agentName}" and its self-custodied Solana wallet (network: ${network}).`,
`Your job: help the owner snipe, trade, and manage risk by talking. You have real tools — use them; never invent numbers, prices, balances, safety verdicts, or smart-money counts. If a tool returns no data, say so plainly.`,
`RULES:`,
+ `• ACT, don't ask. The read-only tools (get_portfolio, get_coin_intel, get_smart_money, assess_safety, get_quote, get_trade_limits) are free and instant — CALL them immediately to answer. NEVER ask the owner for permission to read their own wallet or check a coin ("would you like me to check…?" is forbidden). If they ask "how's my portfolio?", call get_portfolio right away and answer with the real numbers. Only the propose_* actions need confirmation.`,
`• You NEVER execute or sign anything. To buy, sell, or change risk limits you MUST call the matching propose_* tool, which surfaces a confirm card. The owner confirms; a guarded server endpoint then enforces spend caps, the firewall, and the kill switch and signs. Never say a trade is done — say you've prepared it for confirmation.`,
`• Before proposing OR recommending a buy, ground it: call assess_safety (firewall) and get_quote, and mention the safety verdict and price impact. If the firewall verdict is "block", refuse the buy and explain why.`,
- `• Keep answers tight and conversational (2-5 sentences) — this may be read aloud. Use plain language, no markdown tables, no code blocks.`,
+ `• Keep answers tight and conversational (2-5 sentences) — this may be read aloud. Light markdown is fine (bold, short bullet lists) but no tables or code blocks. The UI already shows the raw numbers as cards, so narrate the takeaway — don't re-list every figure.`,
`• The only coin three.ws promotes is $THREE. You may trade any mint the owner explicitly names (that is their call), but never suggest, shill, or name a specific other token on your own initiative.`,
`• When the owner is vague ("buy the safe one"), ask one brief clarifying question or have them paste a mint — do not guess a mint address.`,
].join('\n');
@@ -439,33 +440,57 @@ export default async function handler(req, res, id) {
if (name === 'get_portfolio') {
const p = await loadPortfolio(id, address, network);
citations.push({ kind: 'portfolio', sol: p.sol_balance, holdings: p.holdings.length, positions: p.open_positions.length });
- return { result: p, summary: address ? `Portfolio: ${p.sol_balance != null ? p.sol_balance.toFixed(4) + ' SOL' : 'balance unavailable'}, ${p.holdings.length} token(s), ${p.open_positions.length} open position(s)` : 'No wallet provisioned yet' };
+ return {
+ result: p,
+ summary: address ? `Portfolio: ${p.sol_balance != null ? p.sol_balance.toFixed(4) + ' SOL' : 'balance unavailable'}, ${p.holdings.length} token(s), ${p.open_positions.length} open position(s)` : 'No wallet provisioned yet',
+ card: { kind: 'portfolio', wallet: p.wallet, sol_balance: p.sol_balance, holdings: p.holdings, open_positions: p.open_positions, network },
+ };
}
if (name === 'get_coin_intel') {
const intel = await loadIntel(args.mint, network);
citations.push({ kind: 'intel', mint: args.mint, quality: intel.quality_score ?? null });
- return { result: intel, summary: intel.found ? `Intel ${intel.symbol || ''}: quality ${intel.quality_score ?? '—'}/100, ${(intel.risk_flags || []).length} risk flag(s)${intel.outcome ? `, outcome ${intel.outcome}` : ''}` : 'No intel on this mint' };
+ return {
+ result: intel,
+ summary: intel.found ? `Intel ${intel.symbol || ''}: quality ${intel.quality_score ?? '—'}/100, ${(intel.risk_flags || []).length} risk flag(s)${intel.outcome ? `, outcome ${intel.outcome}` : ''}` : 'No intel on this mint',
+ card: { kind: 'intel', ...intel },
+ };
}
if (name === 'get_smart_money') {
const sm = await getSmartMoneyForMint(args.mint, network);
citations.push({ kind: 'smart_money', mint: args.mint, score: sm.smart_money_score, count: sm.count });
- return { result: sm, summary: `Smart money: ${sm.count} reputable wallet(s), score ${sm.smart_money_score}/100${sm.sybil_flag ? ' (sybil-dominated)' : ''}` };
+ return {
+ result: sm,
+ summary: `Smart money: ${sm.count} reputable wallet(s), score ${sm.smart_money_score}/100${sm.sybil_flag ? ' (sybil-dominated)' : ''}`,
+ card: { kind: 'smart_money', mint: args.mint, count: sm.count, score: sm.smart_money_score, sybil: !!sm.sybil_flag },
+ };
}
if (name === 'assess_safety') {
const conn = solanaPublicConnection(network);
const quoteLamports = args.sol_amount > 0 ? BigInt(Math.floor(Number(args.sol_amount) * LAMPORTS_PER_SOL)) : null;
const a = await assessTradeSafety({ network, mint: args.mint, side: 'buy', payer: address, quoteAmount: quoteLamports, connection: conn });
citations.push({ kind: 'safety', mint: args.mint, verdict: a.verdict, score: a.score });
- return { result: { verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated }, summary: `Firewall: ${a.verdict.toUpperCase()} (${a.score}/100)${a.reasons?.[0] ? ' — ' + a.reasons[0] : ''}` };
+ return {
+ result: { verdict: a.verdict, score: a.score, reasons: a.reasons, simulated: a.simulated },
+ summary: `Firewall: ${a.verdict.toUpperCase()} (${a.score}/100)${a.reasons?.[0] ? ' — ' + a.reasons[0] : ''}`,
+ card: { kind: 'safety', mint: args.mint, verdict: a.verdict, score: a.score, reasons: a.reasons || [], simulated: !!a.simulated },
+ };
}
if (name === 'get_quote') {
const q = await runQuote({ side: args.side, mint: args.mint, solAmount: args.sol_amount, tokenAmount: args.token_amount, slippageBps: args.slippage_bps || 300, network });
citations.push({ kind: 'quote', mint: args.mint, side: args.side, impact: q.price_impact_pct });
- return { result: q, summary: `Quote ${args.side}: ${q.expected_out != null ? q.expected_out.toLocaleString(undefined, { maximumFractionDigits: 4 }) : '—'} ${q.out_asset}, ${q.price_impact_pct != null ? q.price_impact_pct.toFixed(2) + '% impact' : 'impact n/a'}` };
+ return {
+ result: q,
+ summary: `Quote ${args.side}: ${q.expected_out != null ? q.expected_out.toLocaleString(undefined, { maximumFractionDigits: 4 }) : '—'} ${q.out_asset}, ${q.price_impact_pct != null ? q.price_impact_pct.toFixed(2) + '% impact' : 'impact n/a'}`,
+ card: { kind: 'quote', mint: args.mint, side: q.side, in_asset: q.in_asset, in_amount: q.in_amount, out_asset: q.out_asset, expected_out: q.expected_out, price_impact_pct: q.price_impact_pct, min_received: q.min_received },
+ };
}
if (name === 'get_trade_limits') {
const lim = getTradeLimits(meta);
- return { result: lim, summary: `Limits: per-trade ${lim.per_trade_sol ?? '∞'} SOL, daily ${lim.daily_budget_sol ?? '∞'} SOL, kill switch ${lim.kill_switch ? 'ON' : 'off'}` };
+ return {
+ result: lim,
+ summary: `Limits: per-trade ${lim.per_trade_sol ?? '∞'} SOL, daily ${lim.daily_budget_sol ?? '∞'} SOL, kill switch ${lim.kill_switch ? 'ON' : 'off'}`,
+ card: { kind: 'limits', ...lim },
+ };
}
return { result: { error: 'unknown_tool' }, summary: 'unknown tool' };
}
@@ -591,7 +616,7 @@ export default async function handler(req, res, id) {
progressed = true; // a genuine failure is new information, not a spin
}
// Surface read activity once per distinct read — never re-paint a cached repeat.
- if (!isPropose && !cached) send('tool', { name: tc.name, summary: outcome.summary });
+ if (!isPropose && !cached) send('tool', { name: tc.name, summary: outcome.summary, data: outcome.card || null });
messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(outcome.result).slice(0, 6000) });
}
if (!progressed) break; // model looped on data it already has — go answer.
diff --git a/data/changelog.json b/data/changelog.json
index 5fb8927b8..9d6070e4c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-05",
+ "title": "Animation Studio — avatars no longer crumple when you preview a motion",
+ "summary": "Loading your own avatar and playing a preset like Facepalm sometimes folded the whole character into a heap on the floor — even though the studio reported a clean \"100% retargeted.\" The baked motion clips carry a per-bone scale and length channel from the character they were authored on, and those were being stamped onto your avatar, overwriting its own proportions. The Animation Studio now drives only what's actually motion — the joint rotations and the root's travel — and leaves every rig's bone lengths and scale untouched, so any avatar (tall, short, generated, Mixamo) plays every clip standing up in its own body. The \"retargeted\" percentage now counts only those real motion channels, so it reflects what you see.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/pose"
+ },
{
"date": "2026-07-05",
"title": "Trading Copilot no longer freezes after reading your wallet",
diff --git a/public/changelog.json b/public/changelog.json
index 234d4e388..5da7c5aee 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-05T11:42:03.833Z",
+ "generated_at": "2026-07-05T12:40:04.902Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -70,6 +70,16 @@
"improvement"
]
},
+ {
+ "date": "2026-07-05",
+ "type": "update",
+ "title": "Animation Studio — avatars no longer crumple when you preview a motion",
+ "summary": "Loading your own avatar and playing a preset like Facepalm sometimes folded the whole character into a heap on the floor — even though the studio reported a clean \"100% retargeted.\" The baked motion clips carry a per-bone scale and length channel from the character they were authored on, and those were being stamped onto your avatar, overwriting its own proportions. The Animation Studio now drives only what's actually motion — the joint rotations and the root's travel — and leaves every rig's bone lengths and scale untouched, so any avatar (tall, short, generated, Mixamo) plays every clip standing up in its own body. The \"retargeted\" percentage now counts only those real motion channels, so it reflects what you see.",
+ "link": "/pose",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-07-05",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 2256f58e9..6162e5da6 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -54,6 +54,14 @@
<category>feature</category>
<description>The animation gallery at three.ws/animations got a ground-up upgrade. All 2,100+ clips now show a real poster image of the avatar mid-motion instead of a blank tile, and hovering any card plays the full animation live in 3D. Clips are organized into 16 browsable categories (dance, combat, weapons, sports, and more) with search, sorting, and loop filters, and every clip has its own shareable link with playback controls — scrub the timeline, change the speed, then send it straight to the Animation Studio or copy an embed snippet for your own site.</description>
</item>
+ <item>
+ <title>Animation Studio — avatars no longer crumple when you preview a motion</title>
+ <link>https://three.ws/pose</link>
+ <guid isPermaLink="false">2026-07-05:Animation Studio — avatars no longer crumple when you preview a motion</guid>
+ <pubDate>Sun, 05 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Loading your own avatar and playing a preset like Facepalm sometimes folded the whole character into a heap on the floor — even though the studio reported a clean &quot;100% retargeted.&quot; The baked motion clips carry a per-bone scale and length channel from the character they were authored on, and those were being stamped onto your avatar, overwriting its own proportions. The Animation Studio now drives only what's actually motion — the joint rotations and the root's travel — and leaves every rig's bone lengths and scale untouched, so any avatar (tall, short, generated, Mixamo) plays every clip standing up in its own body. The &quot;retargeted&quot; percentage now counts only those real motion channels, so it reflects what you see.</description>
+ </item>
<item>
<title>Faster, steadier pages under load — cache now compresses what it stores</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 383ed534f..f8e14ea65 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-05T11:42:03.821Z",
+ "generated_at": "2026-07-05T12:40:04.887Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-copilot.js b/src/agent-copilot.js
index c7d6ae343..6e9df3882 100644
--- a/src/agent-copilot.js
+++ b/src/agent-copilot.js
@@ -31,6 +31,7 @@
import { executeAgentTrade, TradeError } from './agent-solana-wallet.js';
import { createSafetyPanel } from './shared/safety-panel.js';
import { consumeCsrfToken } from './api.js';
+import { mdToHtml } from './md.js';
const STYLE_ID = 'awh-copilot-style';
const STYLE = `
@@ -124,8 +125,70 @@ const STYLE = `
.awh-cop-error { color: var(--danger,#f87171); font-size: var(--text-sm,.764rem); display: flex; gap: 8px; align-items: center; }
.awh-cop-error button { font: inherit; font-size: var(--text-sm,.764rem); color: var(--accent,#fff); background: none; border: none; cursor: pointer; text-decoration: underline; padding: 0; }
-@media (prefers-reduced-motion: reduce) { .awh-cop-typing span, .awh-cop-iconbtn.is-listening, .awh-cop-prop { animation: none; } .awh-cop-thread { scroll-behavior: auto; } }
-@media (max-width: 520px) { .awh-cop-msg { max-width: 100%; } }
+/* Rendered markdown inside an agent bubble. */
+.awh-cop-md { white-space: normal; }
+.awh-cop-md > :first-child { margin-top: 0; } .awh-cop-md > :last-child { margin-bottom: 0; }
+.awh-cop-md p { margin: 0 0 8px; } .awh-cop-md p:last-child { margin-bottom: 0; }
+.awh-cop-md ul, .awh-cop-md ol { margin: 6px 0; padding-left: 18px; } .awh-cop-md li { margin: 2px 0; }
+.awh-cop-md h3, .awh-cop-md h4, .awh-cop-md h5, .awh-cop-md h6 { margin: 10px 0 6px; font-size: var(--text-md,.8125rem); color: var(--ink-bright,#fff); }
+.awh-cop-md strong { color: var(--ink-bright,#fff); font-weight: 600; }
+.awh-cop-md a { color: var(--accent,#fff); text-decoration: underline; text-underline-offset: 2px; }
+.awh-cop-md code { font-family: var(--font-mono,ui-monospace,monospace); font-size: .92em; background: var(--surface-3, rgba(255,255,255,.08)); padding: 1px 5px; border-radius: 5px; }
+.awh-cop-md blockquote { margin: 6px 0; padding-left: 10px; border-left: 2px solid var(--stroke-strong, rgba(255,255,255,.14)); color: var(--ink-dim,#888); }
+
+/* Structured tool-result cards (data-grounded, non-interactive). */
+.awh-cop-cards { display: flex; flex-direction: column; gap: 8px; }
+.awh-cop-card { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.03)); padding: 10px 12px; animation: awh-cop-fade var(--duration-base,220ms) var(--ease-out,ease); }
+.awh-cop-card-h { display: flex; align-items: center; gap: 7px; font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim,#888); margin-bottom: 8px; }
+.awh-cop-card-h .awh-cop-card-ic { font-size: .95rem; }
+.awh-cop-card-h .awh-cop-card-mint { margin-left: auto; text-transform: none; letter-spacing: 0; font-family: var(--font-mono,ui-monospace,monospace); }
+.awh-cop-stat { display: flex; align-items: baseline; gap: 8px; }
+.awh-cop-stat-big { font-size: 1.2rem; font-weight: 600; color: var(--ink-bright,#fff); font-variant-numeric: tabular-nums; }
+.awh-cop-stat-sub { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+.awh-cop-hold { display: flex; justify-content: space-between; gap: 10px; font-size: var(--text-sm,.764rem); padding: 4px 0; border-top: 1px solid var(--stroke, rgba(255,255,255,.05)); }
+.awh-cop-hold:first-of-type { border-top: none; }
+.awh-cop-hold-mint { font-family: var(--font-mono,ui-monospace,monospace); color: var(--ink,#e8e8e8); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.awh-cop-hold-amt { color: var(--ink-bright,#fff); font-variant-numeric: tabular-nums; flex: none; }
+.awh-cop-hold-pnl.is-up { color: var(--success,#4ade80); } .awh-cop-hold-pnl.is-down { color: var(--danger,#f87171); }
+.awh-cop-card-empty { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
+.awh-cop-verdict { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-2xs,.6875rem); font-weight: 700; text-transform: uppercase; letter-spacing: .04em; padding: 3px 9px; border-radius: var(--radius-pill,999px); }
+.awh-cop-verdict.is-allow { color: var(--success,#4ade80); background: color-mix(in srgb, var(--success,#4ade80) 14%, transparent); }
+.awh-cop-verdict.is-warn { color: var(--warn,#fbbf24); background: color-mix(in srgb, var(--warn,#fbbf24) 14%, transparent); }
+.awh-cop-verdict.is-block { color: var(--danger,#f87171); background: color-mix(in srgb, var(--danger,#f87171) 14%, transparent); }
+.awh-cop-reasons { margin: 8px 0 0; padding-left: 16px; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); } .awh-cop-reasons li { margin: 2px 0; }
+.awh-cop-meter { height: 5px; border-radius: 3px; background: var(--surface-3, rgba(255,255,255,.08)); overflow: hidden; margin-top: 8px; }
+.awh-cop-meter > i { display: block; height: 100%; border-radius: 3px; }
+.awh-cop-chips { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 8px; }
+.awh-cop-chip { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); background: var(--surface-2, rgba(255,255,255,.05)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill,999px); padding: 2px 8px; }
+.awh-cop-chip.is-flag { color: var(--warn,#fbbf24); border-color: color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); }
+
+/* Collapsible "activity" disclosure that groups a turn's tool reads. */
+.awh-cop-activity { border: 1px solid var(--stroke, rgba(255,255,255,.06)); border-radius: var(--radius-md,10px); background: var(--surface-1, rgba(255,255,255,.02)); }
+.awh-cop-activity > summary { cursor: pointer; padding: 7px 11px; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); list-style: none; display: flex; align-items: center; gap: 7px; }
+.awh-cop-activity > summary::-webkit-details-marker { display: none; }
+.awh-cop-activity > summary::before { content: '▸'; font-size: .7em; transition: transform var(--duration-fast,140ms); }
+.awh-cop-activity[open] > summary::before { transform: rotate(90deg); }
+.awh-cop-activity-body { padding: 0 11px 10px; display: flex; flex-direction: column; gap: 8px; }
+
+/* Per-message hover actions (copy / regenerate). */
+.awh-cop-msg-actions { display: flex; gap: 2px; opacity: 0; transition: opacity var(--duration-fast,140ms); padding: 0 2px; }
+.awh-cop-msg.is-agent:hover .awh-cop-msg-actions, .awh-cop-msg-actions:focus-within { opacity: 1; }
+.awh-cop-msg-act { appearance: none; border: none; background: none; cursor: pointer; color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); display: inline-flex; align-items: center; gap: 4px; padding: 3px 7px; border-radius: var(--radius-sm,7px); font: inherit; font-size: var(--text-2xs,.6875rem); }
+.awh-cop-msg-act:hover { color: var(--ink-bright,#fff); background: var(--surface-2, rgba(255,255,255,.05)); }
+.awh-cop-msg-act:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset: 1px; }
+.awh-cop-msg-act.is-done { color: var(--success,#4ade80); }
+
+/* Slash-command menu above the composer. */
+.awh-cop-slash { position: absolute; left: 0; right: 52px; bottom: calc(100% + 6px); background: var(--surface-1, #141414); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); border-radius: var(--radius-md,10px); box-shadow: 0 10px 30px rgba(0,0,0,.4); overflow: hidden; z-index: 5; }
+.awh-cop-slash-item { display: flex; align-items: baseline; gap: 9px; padding: 8px 12px; cursor: pointer; font-size: var(--text-sm,.764rem); }
+.awh-cop-slash-item[aria-selected="true"], .awh-cop-slash-item:hover { background: var(--surface-2, rgba(255,255,255,.06)); }
+.awh-cop-slash-cmd { color: var(--ink-bright,#fff); font-weight: 600; font-family: var(--font-mono,ui-monospace,monospace); }
+.awh-cop-slash-desc { color: var(--ink-dim,#888); }
+.awh-cop-composer { position: relative; }
+.awh-cop-iconbtn.is-stop { background: var(--danger,#f87171); color: #0a0a0a; border-color: var(--danger,#f87171); }
+
+@media (prefers-reduced-motion: reduce) { .awh-cop-typing span, .awh-cop-iconbtn.is-listening, .awh-cop-prop, .awh-cop-card { animation: none; } .awh-cop-thread { scroll-behavior: auto; } }
+@media (max-width: 520px) { .awh-cop-msg { max-width: 100%; } .awh-cop-slash { right: 0; } }
`;
function injectStyle() {
@@ -163,11 +226,52 @@ const SUGGESTIONS = [
'Is this coin safe to buy?',
];
+// Slash commands — a `/chat`-style quick palette. Each maps to a message the
+// copilot already understands, so typing `/portfolio` is just a fast path to the
+// same tool-grounded answer. `local` commands act on the client without a turn.
+const SLASH_COMMANDS = [
+ { cmd: '/portfolio', desc: 'Show my live balance, holdings & positions', send: "How's my portfolio?" },
+ { cmd: '/limits', desc: 'Read my current risk guardrails', send: 'What are my current risk limits?' },
+ { cmd: '/safety', desc: 'Run the firewall on a mint — /safety <mint>', template: 'Is this coin safe to buy: ' },
+ { cmd: '/buy', desc: 'Propose a buy — /buy 0.2 <mint>', template: 'Buy ' },
+ { cmd: '/sell', desc: 'Propose a sell — /sell 50% <mint>', template: 'Sell ' },
+ { cmd: '/clear', desc: 'Clear this conversation', local: 'clear' },
+ { cmd: '/help', desc: 'What can the copilot do?', local: 'help' },
+];
+
+const STORAGE_VERSION = 2;
+function storageKey(agentId, network) { return `awh.copilot.${agentId}.${network}`; }
+// Persist only what re-renders cleanly: message text, tool cards, and executed
+// action log. Live proposals (quotes go stale, safety panels hold DOM refs) and
+// in-flight streaming state are deliberately dropped so a reload never resurrects
+// a confirmable trade card grounded on a stale quote.
+function loadHistory(agentId, network) {
+ try {
+ const raw = localStorage.getItem(storageKey(agentId, network));
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ if (parsed?.v !== STORAGE_VERSION || !Array.isArray(parsed.messages)) return null;
+ return parsed;
+ } catch { return null; }
+}
+function saveHistory(agentId, network, messages, actionLog) {
+ try {
+ const clean = messages
+ .filter((m) => (m.role === 'user' && m.content) || (m.role === 'agent' && (m.content || (m.tools || []).length)))
+ .slice(-40)
+ .map((m) => m.role === 'user'
+ ? { role: 'user', content: m.content }
+ : { role: 'agent', content: m.content, tools: (m.tools || []).map((t) => ({ name: t.name, summary: t.summary, data: t.data })) });
+ localStorage.setItem(storageKey(agentId, network), JSON.stringify({ v: STORAGE_VERSION, messages: clean, actionLog: actionLog.slice(0, 30) }));
+ } catch { /* storage full / disabled — persistence is best-effort */ }
+}
+
export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isOwner, getNetwork, onNetworkChange, toast = () => {} }) {
injectStyle();
let destroyed = false;
let detachNet = null;
let streaming = false;
+ let stopped = false; // set when the owner presses Stop, so the abort reads as intentional
let currentTurn = null; // AbortController for the in-flight SSE turn, if any
const STREAM_STALL_MS = 45_000; // no SSE bytes for this long ⇒ dead stream (server heartbeats every 15s)
let recognition = null;
@@ -175,11 +279,22 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
let voiceOut = false;
let voiceConfig = null; // { provider, voiceId } once loaded
let currentAudio = null;
+ let slashIdx = -1; // highlighted row in the slash menu, -1 when closed
// Conversation: {role:'user'|'agent', content, tools:[], proposals:[], streaming, error}
const messages = [];
const actionLog = []; // executed trades/limit changes
+ // Restore the prior conversation for this wallet+network (text + tool cards +
+ // executed-action log). Live proposals are intentionally not persisted.
+ const restored = loadHistory(agentId, getNetwork());
+ if (restored) {
+ restored.messages.forEach((m) => messages.push(m.role === 'user'
+ ? { role: 'user', content: m.content }
+ : { role: 'agent', content: m.content || '', tools: m.tools || [], proposals: [], streaming: false }));
+ (restored.actionLog || []).forEach((a) => actionLog.push(a));
+ }
+
if (!isOwner) {
panel.innerHTML = `<div class="awh-card"><div class="awh-cop-intro" role="note"><span aria-hidden="true">🔒</span> The trading copilot is private to <strong>${esc(agentName)}</strong>'s owner — it can read this wallet's positions and place guarded trades from it, so only the owner can talk to it.</div></div>`;
return { destroy() {} };
@@ -196,7 +311,8 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
<div class="awh-cop-thread" data-host="thread" role="log" aria-live="polite" aria-label="Copilot conversation" tabindex="0"></div>
<div data-host="error"></div>
<div class="awh-cop-composer">
- <textarea class="awh-cop-input" data-host="input" rows="1" placeholder="Ask, or say “buy 0.2 SOL of …”" aria-label="Message the trading copilot"></textarea>
+ <div class="awh-cop-slash" data-host="slash" role="listbox" aria-label="Slash commands" hidden></div>
+ <textarea class="awh-cop-input" data-host="input" rows="1" placeholder="Ask, say “buy 0.2 SOL of …”, or type / for commands" aria-label="Message the trading copilot"></textarea>
<button class="awh-cop-iconbtn" type="button" data-act="mic" aria-label="Talk to the copilot" title="Voice input">🎙</button>
<button class="awh-cop-iconbtn awh-cop-send" type="button" data-act="send" aria-label="Send message" title="Send">➤</button>
</div>
@@ -213,10 +329,12 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
const elIntro = panel.querySelector('[data-host="intro"]');
const elLogWrap = panel.querySelector('[data-host="logwrap"]');
const elLogList = panel.querySelector('[data-host="loglist"]');
+ const elSlash = panel.querySelector('[data-host="slash"]');
+ const elSend = panel.querySelector('[data-act="send"]');
function introHtml() {
return `<div class="awh-cop-intro">
- <strong>Talk to ${esc(agentName)} to trade.</strong> Ask about safety, smart money, or your positions — or say “buy 0.25 SOL of &lt;mint&gt;”. Every trade comes back as a card you confirm; it runs through the same spend guards, firewall, and audit as the Trade tab. The copilot never trades on its own.
+ <strong>Talk to ${esc(agentName)} to trade.</strong> Ask about safety, smart money, or your positions — or say “buy 0.25 SOL of &lt;mint&gt;”. Answers come back as live data cards; every trade is a card you confirm, running through the same spend guards, firewall, and audit as the Trade tab. The copilot never trades on its own. Type <strong>/</strong> for commands.
<div class="awh-cop-suggest" data-host="suggest">${SUGGESTIONS.map((s, i) => `<button type="button" data-suggest="${i}">${esc(s)}</button>`).join('')}</div>
</div>`;
}
@@ -245,20 +363,121 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
if (m.role === 'user') {
return `<div class="awh-cop-msg is-user"><div class="awh-cop-bubble">${esc(m.content)}</div></div>`;
}
- const tools = (m.tools || []).length
- ? `<div class="awh-cop-tools">${m.tools.map((t) => `<span class="awh-cop-tool">${esc(t)}</span>`).join('')}</div>` : '';
+ const tools = m.tools || [];
+ // Cards carry the grounded numbers; the reply narrates them. A tool with no
+ // card (e.g. a failed read) shows as a compact activity line instead.
+ const cards = tools.filter((t) => t && t.data).map((t) => toolCardHtml(t.data));
+ const bare = tools.filter((t) => t && !t.data);
+ const activity = tools.length
+ ? `<details class="awh-cop-activity"${m.streaming ? ' open' : ''}>
+ <summary>${m.streaming ? 'Reading live data' : `Looked at ${tools.length} source${tools.length > 1 ? 's' : ''}`}</summary>
+ <div class="awh-cop-activity-body">
+ ${cards.join('')}
+ ${bare.map((t) => `<div class="awh-cop-tool">${esc(t.summary)}</div>`).join('')}
+ </div>
+ </details>` : '';
const body = m.content
- ? `<div class="awh-cop-bubble">${esc(m.content)}</div>`
+ ? `<div class="awh-cop-bubble"><div class="awh-cop-md">${mdToHtml(m.content)}</div></div>`
: m.streaming
? `<div class="awh-cop-bubble is-empty"><span class="awh-cop-typing"><span></span><span></span><span></span></span></div>`
- : `<div class="awh-cop-bubble is-empty">…</div>`;
+ : tools.length ? '' /* cards already answer; no empty bubble */
+ : `<div class="awh-cop-bubble is-empty">…</div>`;
const props = (m.proposals || []).map((p, pi) => `<div data-prop="${i}-${pi}"></div>`).join('');
+ // Copy / regenerate appear on a settled agent reply that has text.
+ const actions = (!m.streaming && m.content)
+ ? `<div class="awh-cop-msg-actions">
+ <button class="awh-cop-msg-act" type="button" data-msgact="copy" data-mi="${i}" title="Copy reply">⧉ Copy</button>
+ ${i === lastAgentIndex() ? `<button class="awh-cop-msg-act" type="button" data-msgact="regen" title="Regenerate">↻ Retry</button>` : ''}
+ </div>` : '';
return `<div class="awh-cop-msg is-agent">
<div class="awh-cop-name">${esc(agentName)}</div>
- ${tools}${body}${props}
+ ${activity}${body}${props}${actions}
</div>`;
}
+ function lastAgentIndex() {
+ for (let k = messages.length - 1; k >= 0; k--) if (messages[k].role === 'agent') return k;
+ return -1;
+ }
+
+ // ── grounded tool-result cards ──────────────────────────────────────────────
+ function meter(pct, color) {
+ const w = Math.max(0, Math.min(100, Number(pct) || 0));
+ return `<div class="awh-cop-meter"><i style="width:${w}%;background:${color}"></i></div>`;
+ }
+ function scoreColor(s) { return s == null ? 'var(--ink-dim,#888)' : s >= 70 ? 'var(--success,#4ade80)' : s >= 40 ? 'var(--warn,#fbbf24)' : 'var(--danger,#f87171)'; }
+
+ function toolCardHtml(d) {
+ if (!d || !d.kind) return '';
+ const mintTag = d.mint ? `<span class="awh-cop-card-mint">${esc(short(d.mint, 4, 4))}</span>` : '';
+ if (d.kind === 'portfolio') {
+ const holds = (d.holdings || []).slice(0, 8);
+ const pos = d.open_positions || [];
+ const holdRows = holds.length
+ ? holds.map((h) => `<div class="awh-cop-hold"><span class="awh-cop-hold-mint">${esc(short(h.mint, 5, 5))}</span><span class="awh-cop-hold-amt">${fmtTok(h.ui_amount)}</span></div>`).join('')
+ : `<div class="awh-cop-card-empty">No SPL token holdings.</div>`;
+ const posRows = pos.length
+ ? `<div class="awh-cop-card-h" style="margin-top:10px">Open positions</div>${pos.slice(0, 6).map((p) => {
+ const up = p.unrealized_pnl_pct != null && p.unrealized_pnl_pct >= 0;
+ return `<div class="awh-cop-hold"><span class="awh-cop-hold-mint">${esc(p.symbol || short(p.mint, 4, 4))}</span><span class="awh-cop-hold-pnl ${p.unrealized_pnl_pct == null ? '' : up ? 'is-up' : 'is-down'}">${p.unrealized_pnl_pct == null ? '—' : `${up ? '+' : ''}${p.unrealized_pnl_pct.toFixed(1)}%`}</span></div>`;
+ }).join('')}` : '';
+ return `<div class="awh-cop-card">
+ <div class="awh-cop-card-h"><span class="awh-cop-card-ic" aria-hidden="true">👛</span> Portfolio ${mintTag}</div>
+ <div class="awh-cop-stat"><span class="awh-cop-stat-big">◎${fmtSol(d.sol_balance)}</span><span class="awh-cop-stat-sub">SOL${d.holdings ? ` · ${d.holdings.length} token${d.holdings.length === 1 ? '' : 's'}` : ''}</span></div>
+ <div style="margin-top:8px">${holdRows}</div>${posRows}
+ </div>`;
+ }
+ if (d.kind === 'safety') {
+ const v = (d.verdict || 'warn').toLowerCase();
+ const reasons = (d.reasons || []).slice(0, 4);
+ return `<div class="awh-cop-card">
+ <div class="awh-cop-card-h"><span class="awh-cop-card-ic" aria-hidden="true">🛡️</span> Firewall ${mintTag}</div>
+ <div class="awh-cop-stat"><span class="awh-cop-verdict is-${v}">${esc(v)}</span><span class="awh-cop-stat-sub">${d.score != null ? `${d.score}/100 safety${d.simulated ? ' · simulated' : ''}` : ''}</span></div>
+ ${d.score != null ? meter(d.score, scoreColor(d.score)) : ''}
+ ${reasons.length ? `<ul class="awh-cop-reasons">${reasons.map((r) => `<li>${esc(r)}</li>`).join('')}</ul>` : ''}
+ </div>`;
+ }
+ if (d.kind === 'quote') {
+ const isBuy = d.side === 'buy';
+ const impact = d.price_impact_pct;
+ const impCol = impact == null ? 'var(--ink-dim,#888)' : impact >= 15 ? 'var(--danger,#f87171)' : impact >= 5 ? 'var(--warn,#fbbf24)' : 'var(--success,#4ade80)';
+ return `<div class="awh-cop-card">
+ <div class="awh-cop-card-h"><span class="awh-cop-card-ic" aria-hidden="true">📊</span> ${isBuy ? 'Buy' : 'Sell'} quote ${mintTag}</div>
+ <div class="awh-cop-hold"><span class="awh-cop-hold-mint">You ${isBuy ? 'pay' : 'sell'}</span><span class="awh-cop-hold-amt">${d.in_amount != null ? `${fmtTok(d.in_amount)} ${esc(d.in_asset || '')}` : '—'}</span></div>
+ <div class="awh-cop-hold"><span class="awh-cop-hold-mint">Expected out</span><span class="awh-cop-hold-amt">${d.expected_out != null ? `${fmtTok(d.expected_out)} ${esc(d.out_asset || '')}` : '—'}</span></div>
+ <div class="awh-cop-hold"><span class="awh-cop-hold-mint">Price impact</span><span class="awh-cop-hold-amt" style="color:${impCol}">${impact != null ? `${impact.toFixed(2)}%` : 'n/a'}</span></div>
+ </div>`;
+ }
+ if (d.kind === 'smart_money') {
+ return `<div class="awh-cop-card">
+ <div class="awh-cop-card-h"><span class="awh-cop-card-ic" aria-hidden="true">🧠</span> Smart money ${mintTag}</div>
+ <div class="awh-cop-stat"><span class="awh-cop-stat-big">${d.score ?? '—'}</span><span class="awh-cop-stat-sub">/100 · ${d.count ?? 0} reputable wallet${d.count === 1 ? '' : 's'}${d.sybil ? ' · sybil-flagged' : ''}</span></div>
+ ${d.score != null ? meter(d.score, scoreColor(d.score)) : ''}
+ </div>`;
+ }
+ if (d.kind === 'intel') {
+ if (d.found === false) return `<div class="awh-cop-card"><div class="awh-cop-card-h"><span class="awh-cop-card-ic" aria-hidden="true">🔎</span> Coin intel ${mintTag}</div><div class="awh-cop-card-empty">No intelligence on this mint yet.</div></div>`;
+ const flags = (d.risk_flags || []).slice(0, 6);
+ return `<div class="awh-cop-card">
+ <div class="awh-cop-card-h"><span class="awh-cop-card-ic" aria-hidden="true">🔎</span> ${esc(d.symbol || d.name || 'Coin intel')} ${mintTag}</div>
+ <div class="awh-cop-stat"><span class="awh-cop-stat-big">${d.quality_score ?? '—'}</span><span class="awh-cop-stat-sub">/100 quality${d.outcome ? ` · ${esc(d.outcome)}` : ''}${d.ath_multiple ? ` · ${d.ath_multiple}× ATH` : ''}</span></div>
+ ${d.quality_score != null ? meter(d.quality_score, scoreColor(d.quality_score)) : ''}
+ ${flags.length ? `<div class="awh-cop-chips">${flags.map((f) => `<span class="awh-cop-chip is-flag">${esc(String(f).replace(/_/g, ' '))}</span>`).join('')}</div>` : ''}
+ </div>`;
+ }
+ if (d.kind === 'limits') {
+ const row = (label, val) => `<div class="awh-cop-hold"><span class="awh-cop-hold-mint">${label}</span><span class="awh-cop-hold-amt">${val}</span></div>`;
+ return `<div class="awh-cop-card">
+ <div class="awh-cop-card-h"><span class="awh-cop-card-ic" aria-hidden="true">🛟</span> Risk limits</div>
+ ${row('Per-trade cap', d.per_trade_sol != null ? `${d.per_trade_sol} SOL` : '∞')}
+ ${row('Daily budget', d.daily_budget_sol != null ? `${d.daily_budget_sol} SOL` : '∞')}
+ ${row('Max price impact', d.max_price_impact_pct != null ? `${d.max_price_impact_pct}%` : '—')}
+ ${row('Kill switch', d.kill_switch ? '🔴 ON (halted)' : 'off')}
+ </div>`;
+ }
+ return '';
+ }
+
function mountProposal(host, p) {
if (p.kind === 'limits') return mountLimitsProposal(host, p);
const isBuy = p.kind === 'buy';
@@ -414,6 +633,7 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
function logAction(entry) {
actionLog.unshift({ ...entry, at: Date.now() });
renderLog();
+ persist();
}
function renderLog() {
if (!actionLog.length) { elLogWrap.hidden = true; return; }
@@ -429,18 +649,68 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
}
// ── conversation turn (SSE) ─────────────────────────────────────────────────
+ function persist() { saveHistory(agentId, getNetwork(), messages, actionLog); }
+
+ // Resolve a slash command. Returns { local } for a client-side action,
+ // { send } for the text to actually send, or null when it's plain text.
+ function resolveSlash(raw) {
+ if (raw[0] !== '/') return null;
+ const [word, ...rest] = raw.split(/\s+/);
+ const def = SLASH_COMMANDS.find((c) => c.cmd === word.toLowerCase());
+ if (!def) return null;
+ if (def.local) return { local: def.local };
+ const tail = rest.join(' ').trim();
+ if (def.template) return { send: (def.template + tail).trim() };
+ return { send: def.send };
+ }
+
+ function clearConversation() {
+ if (streaming) currentTurn?.abort();
+ messages.forEach((m) => (m.proposals || []).forEach((p) => p._safetyPanel?.destroy?.()));
+ messages.length = 0;
+ actionLog.length = 0;
+ try { localStorage.removeItem(storageKey(agentId, getNetwork())); } catch { /* noop */ }
+ elError.innerHTML = '';
+ render();
+ toast('Conversation cleared');
+ }
+
+ function showHelp() {
+ messages.push({ role: 'user', content: '/help' });
+ messages.push({ role: 'agent', streaming: false, tools: [], proposals: [], content:
+ `**I'm ${agentName}, your trading copilot.** I read live data and prepare guarded trades you confirm — I never sign on my own.\n\n`
+ + `Ask me things like *"how's my portfolio?"*, *"is <mint> safe?"*, or *"buy 0.25 SOL of <mint>"*. Or use a slash command:\n\n`
+ + SLASH_COMMANDS.map((c) => `- \`${c.cmd}\` — ${c.desc}`).join('\n') });
+ render();
+ persist();
+ }
+
+ // Public entry: called from the composer, suggestion chips, and slash menu.
async function sendMessage(text) {
- const content = (text ?? elInput.value).trim();
- if (!content || streaming) return;
+ const raw = (text ?? elInput.value).trim();
+ if (!raw || streaming) return;
+ const slash = resolveSlash(raw);
+ if (slash?.local === 'clear') { elInput.value = ''; autoSize(); hideSlash(); clearConversation(); return; }
+ if (slash?.local === 'help') { elInput.value = ''; autoSize(); hideSlash(); showHelp(); return; }
+ const content = slash?.send ?? raw;
stopSpeaking();
elInput.value = '';
autoSize();
+ hideSlash();
elError.innerHTML = '';
messages.push({ role: 'user', content });
+ await runTurn(content);
+ }
+
+ // Run one copilot turn against the current message history (whose last entry
+ // must be the user turn). Split out so Regenerate can re-run without appending
+ // a duplicate user message.
+ async function runTurn(retryText) {
const agentMsg = { role: 'agent', content: '', tools: [], proposals: [], streaming: true };
messages.push(agentMsg);
streaming = true;
setStatus('Thinking…');
+ updateComposerMode();
render();
const payload = {
@@ -470,21 +740,44 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
if (!agentMsg.content) agentMsg.error = true;
if (!destroyed) {
// A watchdog/destroy abort surfaces as an AbortError with no useful
- // message — translate it into a recoverable prompt so the owner is
- // never left staring at a frozen typing indicator.
+ // message. A user-initiated Stop is a deliberate abort — say so quietly
+ // instead of nagging with a Retry the owner didn't ask for.
const stalled = ctrl.signal.aborted;
- showError(stalled ? 'The copilot stopped responding. Try again.' : (e?.message || 'The copilot hit an error.'), content);
+ if (stopped) { /* user pressed Stop — leave whatever streamed, no error */ }
+ else showError(stalled ? 'The copilot stopped responding. Try again.' : (e?.message || 'The copilot hit an error.'), retryText || null);
}
} finally {
+ stopped = false;
if (currentTurn === ctrl) currentTurn = null;
streaming = false;
agentMsg.streaming = false;
setStatus('');
+ updateComposerMode();
render();
+ persist();
if (voiceOut && agentMsg.content && !agentMsg.error) speak(agentMsg.content);
}
}
+ // Regenerate: drop the last agent reply and re-run the preceding user turn.
+ function regenerate() {
+ if (streaming) return;
+ const li = lastAgentIndex();
+ if (li < 0) return;
+ const prevUser = messages.slice(0, li).reverse().find((m) => m.role === 'user');
+ if (!prevUser) return;
+ messages.splice(li, 1);
+ render();
+ runTurn(prevUser.content);
+ }
+
+ // Stop the in-flight turn on the owner's request (keeps whatever streamed).
+ function stopTurn() {
+ if (!streaming) return;
+ stopped = true;
+ currentTurn?.abort();
+ }
+
async function consumeSse(stream, agentMsg, ctrl) {
const reader = stream.getReader();
const decoder = new TextDecoder();
@@ -526,7 +819,7 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
if (event === 'status') {
setStatus(payload.phase === 'finalizing' ? 'Summarizing…' : payload.phase === 'continuing' ? 'Analyzing…' : 'Thinking…');
} else if (event === 'tool') {
- agentMsg.tools.push(payload.summary || payload.name);
+ agentMsg.tools.push({ name: payload.name, summary: payload.summary || payload.name, data: payload.data || null });
setStatus(payload.summary || 'Reading live data…');
render();
} else if (event === 'proposal') {
@@ -552,7 +845,9 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
function showError(msg, retryText) {
elError.innerHTML = `<div class="awh-cop-error" role="alert"><span aria-hidden="true">⚠</span><span>${esc(msg)}</span>${retryText ? ' <button type="button" data-act="retry">Retry</button>' : ''}</div>`;
const r = elError.querySelector('[data-act="retry"]');
- if (r) r.addEventListener('click', () => { elError.innerHTML = ''; sendMessage(retryText); });
+ // Retry re-runs the last user turn in place (regenerate drops the errored
+ // reply) rather than appending a duplicate user message.
+ if (r) r.addEventListener('click', () => { elError.innerHTML = ''; regenerate(); });
}
// ── voice in (SpeechRecognition) ────────────────────────────────────────────
@@ -662,19 +957,80 @@ export function mountTradingCopilot({ panel, agentId, agentName = 'Copilot', isO
panel.querySelectorAll('[data-suggest]').forEach((b) => b.addEventListener('click', () => sendMessage(SUGGESTIONS[Number(b.dataset.suggest)])));
}
- panel.querySelector('[data-act="send"]').addEventListener('click', () => sendMessage());
+ // The send button doubles as Stop while a turn streams.
+ function updateComposerMode() {
+ if (!elSend) return;
+ elSend.classList.toggle('is-stop', streaming);
+ elSend.textContent = streaming ? '■' : '➤';
+ elSend.setAttribute('aria-label', streaming ? 'Stop generating' : 'Send message');
+ elSend.title = streaming ? 'Stop' : 'Send';
+ }
+
+ // ── slash-command menu ──────────────────────────────────────────────────────
+ function slashMatches() {
+ const v = elInput.value;
+ if (v[0] !== '/' || /\s/.test(v)) return []; // only while typing the command word
+ const q = v.toLowerCase();
+ return SLASH_COMMANDS.filter((c) => c.cmd.startsWith(q));
+ }
+ function renderSlash() {
+ const matches = slashMatches();
+ if (!matches.length) { hideSlash(); return; }
+ if (slashIdx < 0 || slashIdx >= matches.length) slashIdx = 0;
+ elSlash.hidden = false;
+ elSlash.innerHTML = matches.map((c, i) => `<div class="awh-cop-slash-item" role="option" data-slash="${esc(c.cmd)}" aria-selected="${i === slashIdx}"><span class="awh-cop-slash-cmd">${esc(c.cmd)}</span><span class="awh-cop-slash-desc">${esc(c.desc)}</span></div>`).join('');
+ elSlash.querySelectorAll('[data-slash]').forEach((el) => el.addEventListener('mousedown', (e) => { e.preventDefault(); pickSlash(el.dataset.slash); }));
+ }
+ function hideSlash() { elSlash.hidden = true; slashIdx = -1; }
+ function pickSlash(cmd) {
+ const def = SLASH_COMMANDS.find((c) => c.cmd === cmd);
+ if (!def) return;
+ if (def.template) { elInput.value = def.cmd + ' '; hideSlash(); autoSize(); elInput.focus(); return; }
+ sendMessage(def.cmd);
+ }
+ function slashKeydown(e) {
+ if (elSlash.hidden) return false;
+ const matches = slashMatches();
+ if (!matches.length) return false;
+ if (e.key === 'ArrowDown') { e.preventDefault(); slashIdx = (slashIdx + 1) % matches.length; renderSlash(); return true; }
+ if (e.key === 'ArrowUp') { e.preventDefault(); slashIdx = (slashIdx - 1 + matches.length) % matches.length; renderSlash(); return true; }
+ if (e.key === 'Escape') { e.preventDefault(); hideSlash(); return true; }
+ if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); pickSlash(matches[Math.max(0, slashIdx)].cmd); return true; }
+ return false;
+ }
+
+ elSend.addEventListener('click', () => { if (streaming) stopTurn(); else sendMessage(); });
panel.querySelector('[data-act="mic"]').addEventListener('click', toggleMic);
panel.querySelector('[data-act="voiceout"]').addEventListener('click', toggleVoiceOut);
if (!micSupported()) {
const mic = panel.querySelector('[data-act="mic"]');
mic.disabled = true; mic.title = 'Voice input not supported in this browser';
}
- elInput.addEventListener('input', autoSize);
+ elInput.addEventListener('input', () => { autoSize(); renderSlash(); });
+ elInput.addEventListener('blur', () => setTimeout(hideSlash, 120));
elInput.addEventListener('keydown', (e) => {
+ if (slashKeydown(e)) return;
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
});
+ // Per-message actions (copy / regenerate) via delegation — survives re-render.
+ elThread.addEventListener('click', (e) => {
+ const act = e.target.closest('[data-msgact]');
+ if (!act) return;
+ if (act.dataset.msgact === 'regen') { regenerate(); return; }
+ if (act.dataset.msgact === 'copy') {
+ const m = messages[Number(act.dataset.mi)];
+ if (!m?.content) return;
+ navigator.clipboard?.writeText(m.content).then(() => {
+ act.classList.add('is-done'); const t = act.textContent; act.textContent = '✓ Copied';
+ setTimeout(() => { act.classList.remove('is-done'); act.textContent = t; }, 1400);
+ }).catch(() => toast('Copy failed'));
+ }
+ });
+
wireIntroEvents();
+ updateComposerMode();
+ if (messages.length) render(); // paint restored history
if (onNetworkChange) {
detachNet = onNetworkChange(() => { /* network is read live per turn; nothing to reset */ });
diff --git a/src/agent-wallet-hub/tabs/portfolio.js b/src/agent-wallet-hub/tabs/portfolio.js
index 3fee45a2d..d9497fd7a 100644
--- a/src/agent-wallet-hub/tabs/portfolio.js
+++ b/src/agent-wallet-hub/tabs/portfolio.js
@@ -25,13 +25,26 @@ const PORT_STYLE = `
.awh-port-nw { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--space-4,16px); flex-wrap: wrap; }
.awh-port-nw-main { min-width: 0; }
.awh-port-nw-label { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim,#888); }
-.awh-port-nw-usd { font-family: var(--font-display, system-ui); font-size: var(--text-xl, 1.618rem); font-weight: 700; color: var(--ink-bright,#fff); line-height: 1.1; margin-top: 4px; }
-.awh-port-nw-sol { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top: 4px; }
-.awh-port-spark { flex: 0 0 auto; }
-.awh-port-spark svg { display: block; }
-.awh-port-pnl-row { display: flex; gap: var(--space-4,16px); flex-wrap: wrap; margin-top: var(--space-3,12px); }
-.awh-port-pnl { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); }
-.awh-port-pnl b { font-family: var(--font-mono, ui-monospace, monospace); font-weight: 600; }
+.awh-port-nw-usd { font-family: var(--font-display, system-ui); font-size: clamp(2rem, 6vw, 2.6rem); font-weight: 800; letter-spacing: -.02em; color: var(--ink-bright,#fff); line-height: 1.05; margin-top: 6px; font-variant-numeric: tabular-nums; }
+.awh-port-nw-sol { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top: 6px; font-variant-numeric: tabular-nums; }
+.awh-port-spark { flex: 0 0 auto; align-self: center; }
+.awh-port-spark svg { display: block; overflow: visible; }
+.awh-port-pnl-row { display: flex; gap: 8px; flex-wrap: wrap; margin-top: var(--space-4,16px); }
+.awh-port-pnl { display: inline-flex; align-items: center; gap: 7px; font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim,#888); background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-pill,999px); padding: 5px 11px; }
+.awh-port-pnl b { font-family: var(--font-mono, ui-monospace, monospace); font-weight: 700; font-size: var(--text-sm,.764rem); letter-spacing: 0; text-transform: none; }
+
+/* Allocation — portfolio composition at a glance. */
+.awh-alloc { margin-top: var(--space-4,16px); }
+.awh-alloc-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 9px; }
+.awh-alloc-head .k { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .06em; color: var(--ink-dim,#888); }
+.awh-alloc-head .v { font-size: var(--text-2xs,.6875rem); color: var(--ink-faint,#666); font-family: var(--font-mono, ui-monospace, monospace); }
+.awh-alloc-bar { display: flex; height: 12px; border-radius: var(--radius-pill,999px); overflow: hidden; background: var(--surface-2, rgba(255,255,255,.05)); box-shadow: inset 0 0 0 1px var(--stroke, rgba(255,255,255,.06)); }
+.awh-alloc-seg { flex: 0 0 auto; min-width: 2px; background: var(--c,#888); }
+.awh-alloc-seg:not(:last-child) { box-shadow: inset -1.5px 0 0 rgba(0,0,0,.45); }
+.awh-alloc-legend { display: flex; flex-wrap: wrap; gap: 7px 16px; margin-top: 12px; }
+.awh-alloc-key { display: inline-flex; align-items: center; gap: 7px; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
+.awh-alloc-key i { width: 9px; height: 9px; border-radius: 3px; background: var(--c,#888); flex: none; }
+.awh-alloc-key b { color: var(--ink-bright,#fff); font-family: var(--font-mono, ui-monospace, monospace); font-weight: 600; font-size: var(--text-2xs,.6875rem); }
.awh-pos { color: var(--success,#4ade80); }
.awh-neg { color: var(--danger,#f87171); }
.awh-live { display: inline-flex; align-items: center; gap: 5px; font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); }
@@ -66,10 +79,27 @@ const PORT_STYLE = `
.awh-attr-val { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-sm,.764rem); }
.awh-attr-sub { font-size: var(--text-2xs,.6875rem); color: var(--ink-dim,#888); font-family: var(--font-mono, ui-monospace, monospace); }
-.awh-risk-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: var(--space-3,12px); }
-.awh-risk-cell { background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: var(--space-3,12px); }
+.awh-risk-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(124px, 1fr)); gap: var(--space-3,12px); }
+.awh-risk-cell { position: relative; overflow: hidden; background: var(--surface-1, rgba(255,255,255,.03)); border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md,10px); padding: var(--space-3,12px); transition: border-color var(--duration-fast,140ms), transform var(--duration-fast,140ms), background var(--duration-fast,140ms); }
+.awh-risk-cell::before { content: ''; position: absolute; inset: 0 auto 0 0; width: 3px; background: var(--accent, transparent); opacity: .8; }
+.awh-risk-cell:hover { transform: translateY(-2px); border-color: color-mix(in srgb, var(--accent, #fff) 45%, var(--stroke, rgba(255,255,255,.12))); background: var(--surface-2, rgba(255,255,255,.05)); }
.awh-risk-k { font-size: var(--text-2xs,.6875rem); text-transform: uppercase; letter-spacing: .04em; color: var(--ink-dim,#888); }
-.awh-risk-v { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-lg,1.236rem); font-weight: 700; color: var(--ink-bright,#fff); margin-top: 4px; }
+.awh-risk-v { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-lg,1.236rem); font-weight: 700; color: var(--ink-bright,#fff); margin-top: 4px; font-variant-numeric: tabular-nums; }
+.awh-risk-meter { height: 4px; border-radius: var(--radius-pill,999px); background: var(--surface-2, rgba(255,255,255,.06)); margin-top: 10px; overflow: hidden; }
+.awh-risk-meter > span { display: block; height: 100%; border-radius: inherit; background: var(--accent, #888); }
+
+/* Staggered entrance — first paint only (gated by .awh-anim-in on the panel). */
+.awh-anim-in > .awh-card { animation: awh-rise .5s cubic-bezier(.2,.7,.2,1) both; }
+.awh-anim-in > .awh-card:nth-child(1) { animation-delay: .02s; }
+.awh-anim-in > .awh-card:nth-child(2) { animation-delay: .09s; }
+.awh-anim-in > .awh-card:nth-child(3) { animation-delay: .16s; }
+.awh-anim-in > .awh-card:nth-child(4) { animation-delay: .23s; }
+.awh-anim-in .awh-alloc-bar { animation: awh-wipe .8s .18s cubic-bezier(.2,.7,.2,1) both; }
+.awh-anim-in .awh-risk-meter > span { animation: awh-meter .8s .12s cubic-bezier(.2,.7,.2,1) both; }
+@keyframes awh-rise { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
+@keyframes awh-wipe { from { clip-path: inset(0 100% 0 0); } to { clip-path: inset(0 0 0 0); } }
+@keyframes awh-meter { from { transform: scaleX(0); transform-origin: left; } to { transform: scaleX(1); } }
+@media (prefers-reduced-motion: reduce) { .awh-anim-in > .awh-card, .awh-anim-in .awh-alloc-bar, .awh-anim-in .awh-risk-meter > span { animation: none; } }
.awh-flags { list-style: none; margin: var(--space-3,12px) 0 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
.awh-flag { display: flex; gap: 9px; align-items: flex-start; font-size: var(--text-sm,.764rem); padding: 9px 11px; border-radius: var(--radius-md,10px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); background: var(--surface-1, rgba(255,255,255,.03)); }
.awh-flag::before { content: '•'; flex: none; }
@@ -107,25 +137,56 @@ function fmtSolSigned(sol) {
}
function pnlClass(n) { return n > 0 ? 'awh-pos' : n < 0 ? 'awh-neg' : ''; }
-function sparkline(points, w = 132, h = 38) {
+function sparkline(points, w = 150, h = 46) {
const vals = points.filter((v) => Number.isFinite(v));
if (vals.length < 2) return '';
const min = Math.min(...vals);
const max = Math.max(...vals);
const span = max - min || 1;
+ const pad = 3;
const stepX = w / (vals.length - 1);
- const pts = vals.map((v, i) => {
+ const xy = vals.map((v, i) => {
const x = i * stepX;
- const y = h - ((v - min) / span) * (h - 4) - 2;
- return `${x.toFixed(1)},${y.toFixed(1)}`;
+ const y = h - pad - ((v - min) / span) * (h - pad * 2);
+ return [x, y];
});
+ const line = xy.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');
+ const area = `${line} L${w},${h} L0,${h} Z`;
+ const [ex, ey] = xy[xy.length - 1];
const up = vals[vals.length - 1] >= vals[0];
const stroke = up ? 'var(--success,#4ade80)' : 'var(--danger,#f87171)';
return `<svg width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="Net worth trend">
- <polyline fill="none" stroke="${stroke}" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" points="${pts.join(' ')}" />
+ <defs><linearGradient id="awhSparkFill" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0" stop-color="${stroke}" stop-opacity=".26" />
+ <stop offset="1" stop-color="${stroke}" stop-opacity="0" />
+ </linearGradient></defs>
+ <path d="${area}" fill="url(#awhSparkFill)" stroke="none" />
+ <path d="${line}" fill="none" stroke="${stroke}" stroke-width="1.75" stroke-linejoin="round" stroke-linecap="round" />
+ <circle cx="${ex.toFixed(1)}" cy="${ey.toFixed(1)}" r="3.5" fill="${stroke}" fill-opacity=".22" />
+ <circle cx="${ex.toFixed(1)}" cy="${ey.toFixed(1)}" r="1.9" fill="${stroke}" />
</svg>`;
}
+// Allocation-segment colour: SOL (Solana violet), $THREE (platform green), stables
+// (teal), and a rotating warm palette for volatile positions. Gradients read richer
+// than flats in the composition bar.
+const ALLOC_RISK_PALETTE = ['#fb923c', '#f472b6', '#facc15', '#c084fc', '#38bdf8', '#f87171'];
+function allocColor(h, riskIndex) {
+ if (h.isNative) return 'linear-gradient(90deg,#9945FF,#8752F3)';
+ if (h.is_three) return 'linear-gradient(90deg,#34d399,#10b981)';
+ if (h.stable) return 'linear-gradient(90deg,#2dd4bf,#14b8a6)';
+ return ALLOC_RISK_PALETTE[riskIndex % ALLOC_RISK_PALETTE.length];
+}
+
+// Heat colour for a 0..100 "more is worse" share (concentration, exposure).
+function heatColor(pct) {
+ if (pct == null || !Number.isFinite(pct)) return 'var(--ink-faint,#666)';
+ if (pct >= 75) return 'var(--danger,#f87171)';
+ if (pct >= 50) return 'var(--warn,#fbbf24)';
+ if (pct >= 25) return '#a3e635';
+ return 'var(--success,#4ade80)';
+}
+
registerWalletTab({
id: 'portfolio',
label: 'Portfolio',
@@ -146,6 +207,7 @@ registerWalletTab({
spark: [], // net-worth USD history for the sparkline
live: false,
streamDown: false, // SSE permanently closed → live updates paused
+ animated: false, // entrance animation plays once, not on every live tick
};
function pushSpark(usd) {
@@ -199,6 +261,10 @@ registerWalletTab({
${renderAttribution(d)}
${renderRisk(d)}
`;
+ // Entrance animation runs on the first populated paint only — live stream
+ // re-renders (every few seconds) must not replay it.
+ if (!state.animated) { panel.classList.add('awh-anim-in'); state.animated = true; }
+ else panel.classList.remove('awh-anim-in');
wire();
}
@@ -225,6 +291,44 @@ registerWalletTab({
<span class="awh-port-pnl">Realized <b class="${pnlClass(realized)}">${escapeHtml(fmtSolSigned(realized))}</b></span>
<span class="awh-port-pnl">Unrealized <b class="${pnlClass(unrealized)}">${escapeHtml(fmtSolSigned(unrealized))}</b></span>
</div>
+ ${renderAllocation(d)}
+ </div>`;
+ }
+
+ function renderAllocation(d) {
+ const valued = (d.holdings || []).filter((h) => Number.isFinite(h.usd_value) && h.usd_value > 0);
+ const total = valued.reduce((s, h) => s + h.usd_value, 0);
+ if (!valued.length || total <= 0) return '';
+
+ // Cap segments so the bar stays legible; fold the tail into "Other".
+ const MAX_SEG = 7;
+ let segs = valued.slice();
+ if (valued.length > MAX_SEG) {
+ const head = valued.slice(0, MAX_SEG - 1);
+ const tail = valued.slice(MAX_SEG - 1);
+ const otherUsd = tail.reduce((s, h) => s + h.usd_value, 0);
+ segs = [...head, { symbol: `+${tail.length} more`, usd_value: otherUsd, _other: true }];
+ }
+
+ let riskI = 0;
+ const parts = segs.map((h) => {
+ const pct = (h.usd_value / total) * 100;
+ const color = h._other ? 'var(--surface-3, rgba(255,255,255,.14))' : allocColor(h, h.isNative || h.stable || h.is_three ? 0 : riskI++);
+ const sym = escapeHtml(h.symbol || '?');
+ const label = `${sym} · ${pct.toFixed(pct < 10 ? 1 : 0)}% · ${formatUsd(h.usd_value) || ''}`;
+ return {
+ seg: `<span class="awh-alloc-seg" style="flex-basis:${pct.toFixed(2)}%; --c:${color};" title="${escapeHtml(label)}"></span>`,
+ key: `<span class="awh-alloc-key"><i style="--c:${color};"></i>${sym} <b>${pct.toFixed(pct < 10 ? 1 : 0)}%</b></span>`,
+ };
+ });
+ const summary = segs.map((h) => `${h.symbol} ${((h.usd_value / total) * 100).toFixed(0)}%`).join(', ');
+ return `<div class="awh-alloc">
+ <div class="awh-alloc-head">
+ <span class="k">Allocation</span>
+ <span class="v">${valued.length} priced asset${valued.length === 1 ? '' : 's'}</span>
+ </div>
+ <div class="awh-alloc-bar" role="img" aria-label="Allocation: ${escapeHtml(summary)}">${parts.map((p) => p.seg).join('')}</div>
+ <div class="awh-alloc-legend">${parts.map((p) => p.key).join('')}</div>
</div>`;
}
@@ -321,18 +425,27 @@ registerWalletTab({
// Concentration is the largest *volatile* position — holding SOL/stables
// is reserve, not a risk bet. "None" when nothing is at tape risk.
const hasRisk = (r.risk_assets_count ?? 0) > 0;
+ const topRisk = hasRisk ? (r.top_risk_position_pct ?? 0) : 0;
const conc = !hasRisk ? 'None' : (r.top_risk_position_pct != null ? `${r.top_risk_position_pct}%` : '—');
+ const dd = r.max_drawdown_pct;
+ // [label, value, help, meter fraction 0..1 | null, accent colour]
const cells = [
- ['Reserve', r.reserve_pct != null ? `${r.reserve_pct}%` : '—', 'SOL + stables — dry powder ready to deploy, no tape risk'],
- ['Concentration', conc, 'Largest single memecoin position, as a share of net worth'],
- ['Tape exposure', r.exposure_pct != null ? `${r.exposure_pct}%` : '—', 'Share of net worth in volatile memecoins'],
- ['Max drawdown', r.max_drawdown_pct != null ? `${r.max_drawdown_pct}%` : '—', 'Largest realized drop from a net-worth peak'],
- ['Realized vol', r.realized_volatility_pct != null ? `${r.realized_volatility_pct}%` : '—', 'Standard deviation of per-trade returns'],
+ ['Reserve', r.reserve_pct != null ? `${r.reserve_pct}%` : '—', 'SOL + stables — dry powder ready to deploy, no tape risk',
+ r.reserve_pct != null ? r.reserve_pct / 100 : null, 'var(--success,#4ade80)'],
+ ['Concentration', conc, 'Largest single memecoin position, as a share of net worth',
+ hasRisk ? topRisk / 100 : 0, heatColor(hasRisk ? topRisk : 0)],
+ ['Tape exposure', r.exposure_pct != null ? `${r.exposure_pct}%` : '—', 'Share of net worth in volatile memecoins',
+ r.exposure_pct != null ? r.exposure_pct / 100 : null, heatColor(r.exposure_pct)],
+ ['Max drawdown', dd != null ? `${dd}%` : '—', 'Largest realized drop from a net-worth peak',
+ dd != null ? Math.min(dd, 100) / 100 : null, heatColor(dd)],
+ ['Realized vol', r.realized_volatility_pct != null ? `${r.realized_volatility_pct}%` : '—', 'Standard deviation of per-trade returns',
+ null, 'var(--ink-faint,#666)'],
];
- const grid = cells.map(([k, v, help]) =>
- `<div class="awh-risk-cell" title="${escapeHtml(help)}">
+ const grid = cells.map(([k, v, help, frac, accent]) =>
+ `<div class="awh-risk-cell" style="--accent:${accent};" title="${escapeHtml(help)}">
<div class="awh-risk-k">${escapeHtml(k)}</div>
<div class="awh-risk-v">${escapeHtml(v)}</div>
+ ${frac != null ? `<div class="awh-risk-meter"><span style="width:${(Math.max(0, Math.min(1, frac)) * 100).toFixed(1)}%;"></span></div>` : ''}
</div>`).join('');
const flags = (d.risk_flags || []).map((f) =>
`<li class="awh-flag is-${escapeHtml(f.level)}">${escapeHtml(f.text)}</li>`).join('');
diff --git a/src/animation-retarget.js b/src/animation-retarget.js
index b06457fb2..7f9d67792 100644
--- a/src/animation-retarget.js
+++ b/src/animation-retarget.js
@@ -8,8 +8,11 @@
// (and export) that rig we rewrite each track's bone name to the *actual* node
// name on the target, drop tracks the rig has no bone for, and rescale the hip
// translation so root motion lands at the new rig's height instead of the
-// authoring rig's. The result binds cleanly in both THREE.AnimationMixer
-// (preview) and THREE.GLTFExporter (animated-GLB export).
+// authoring rig's. We retarget only the true-motion channels — joint rotations
+// and the root (Hips) translation — and skip the clips' per-bone position/scale
+// channels, which encode the *authoring* rig's bone lengths and would crush a
+// differently-proportioned avatar into a heap. The result binds cleanly in both
+// THREE.AnimationMixer (preview) and THREE.GLTFExporter (animated-GLB export).
//
// Pure module — three + the canonicalizer only — so it runs unchanged in the
// browser (the /pose gallery) and in Node (the apply_animation MCP tool, vitest).
@@ -423,9 +426,11 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {
const minCoverage = opts.minCoverage ?? MIN_COVERAGE;
const corrections = bindCorrections(opts.targetRest, opts.targetWorldRest);
const hipsPosCorrection = hipPositionCorrection(opts.hipsParentWorldQuat, corrections);
- const total = clip.tracks.length;
const dropped = [];
const tracks = [];
+ // Denominator counts only *retargetable* tracks (see below), so a clip baked
+ // with per-bone position/scale channels still reports honest coverage.
+ let total = 0;
for (const track of clip.tracks) {
const dot = track.name.indexOf('.');
@@ -433,6 +438,21 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {
const boneRaw = track.name.slice(0, dot);
const property = track.name.slice(dot + 1);
const canonical = canonicalizeBoneName(boneRaw) || boneRaw;
+
+ // The clips are baked from cz with a full position/quaternion/scale channel
+ // per bone. A bone's local scale and its local position (its fixed offset
+ // from its parent — i.e. the skeleton's bone lengths) are *structure of the
+ // authoring rig*, not motion. Rewriting them onto a differently-proportioned
+ // or differently-scaled avatar overwrites that rig's own bone lengths with
+ // cz's centimetre-vs-metre offsets and folds the whole skeleton into a heap —
+ // even though every bone "matches", so coverage lies at 100%. Only joint
+ // rotations and the root (Hips) translation are true motion; retarget those
+ // and skip the structural channels so every rig keeps its own proportions.
+ const retargetable =
+ property === 'quaternion' || (property === 'position' && canonical === 'Hips');
+ if (!retargetable) continue;
+
+ total++;
const nodeName = canonicalToNode.get(canonical);
if (!nodeName) {
dropped.push(canonical);
@@ -448,10 +468,11 @@ export function retargetClip(clip, canonicalToNode, opts = {}) {
// down") without skewing limbs.
const correction = corrections.get(canonical);
if (correction) correctQuaternionTrack(next.values, correction);
- } else if (property === 'position' && canonical === 'Hips') {
- // Root motion: the clip authors hip translation in the authoring rig's
- // world-Y-up frame; re-express it in the target's hips-parent frame so it
- // travels the same world direction on any rig, then scale for height.
+ } else {
+ // Root motion (Hips.position): the clip authors hip translation in the
+ // authoring rig's world-Y-up frame; re-express it in the target's
+ // hips-parent frame so it travels the same world direction on any rig,
+ // then scale for height.
if (hipsPosCorrection) rotateVectorTrack(next.values, hipsPosCorrection);
if (hipScale !== 1) {
for (let i = 0; i < next.values.length; i++) next.values[i] *= hipScale;
diff --git a/tests/animation-retarget.test.js b/tests/animation-retarget.test.js
index d1791d67a..4aaff7d47 100644
--- a/tests/animation-retarget.test.js
+++ b/tests/animation-retarget.test.js
@@ -159,6 +159,42 @@ describe('retargetClip', () => {
expect(clip.tracks.map((t) => t.name)).toEqual(before);
expect(clip.tracks.find((t) => t.name === 'Hips.position').values[1]).toBe(1);
});
+
+ // The baked library carries a position + quaternion + scale channel per bone.
+ // A limb bone's local position (its offset from its parent) and its scale are
+ // the *authoring* rig's structure, not motion — replaying them verbatim on a
+ // differently-proportioned avatar overwrites its bone lengths and collapses it
+ // into a heap while every bone still "matches" (coverage lies at 100%). The
+ // retargeter must drop those structural channels and keep only rotations + the
+ // root (Hips) translation, and coverage must be computed over just those.
+ it('drops non-Hips position and all scale channels (keeps rotations + root)', () => {
+ const q = new QuaternionKeyframeTrack('LeftArm.quaternion', [0], [0, 0, 0, 1]);
+ const hipsQ = new QuaternionKeyframeTrack('Hips.quaternion', [0], [0, 0, 0, 1]);
+ const hipsPos = new VectorKeyframeTrack('Hips.position', [0], [0, 1, 0]);
+ // Structural channels that must NOT survive: a limb bone offset + scales.
+ const armPos = new VectorKeyframeTrack('LeftArm.position', [0], [0.09, -0.015, 0]);
+ const armScale = new VectorKeyframeTrack('LeftArm.scale', [0], [1, 1, 1]);
+ const hipsScale = new VectorKeyframeTrack('Hips.scale', [0], [1, 1, 1]);
+ const clip = new AnimationClip('struct', 1, [
+ hipsQ,
+ hipsPos,
+ q,
+ armPos,
+ armScale,
+ hipsScale,
+ ]);
+ const map = canonicalNodeMapFromObject(makeRig(CANONICAL_RIG));
+ const r = retargetClip(clip, map, { hipScale: 1 });
+
+ const names = r.clip.tracks.map((t) => t.name).sort();
+ expect(names).toEqual(['Hips.position', 'Hips.quaternion', 'LeftArm.quaternion'].sort());
+ expect(r.clip.tracks.some((t) => t.name === 'LeftArm.position')).toBe(false);
+ expect(r.clip.tracks.some((t) => t.name.endsWith('.scale'))).toBe(false);
+ // Coverage is over the 3 retargetable channels, not all 6 → honest 100%.
+ expect(r.total).toBe(3);
+ expect(r.matched).toBe(3);
+ expect(r.coverage).toBe(1);
+ });
});
describe('bind-rotation correction', () => {