Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions surfaces/webview/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ const LAST = 3; // Chat(0) Skills(1) Rank(2) Market(3)
function TabShell() {
const { state, send } = useStore();
const [idx, setIdx] = useState(0);
useEffect(() => { if (state.composerPrefill !== null) setIdx(0); }, [state.composerPrefill]);
// Faint tick whenever the pager lands on a different tab (tap or swipe).
const prevIdx = useRef(0);
useEffect(() => {
Expand Down
11 changes: 10 additions & 1 deletion surfaces/webview/src/chat/Composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,18 @@ function ChipGroup({ label, value, options, onPick, accent = "green" }: {

// Input + engine tabs + model/effort pickers. FROZEN while an approval is pending.
export function Composer() {
const { state, send, selectEngine, switchEngine, queueCount, markCompacting } = useStore();
const { state, send, prefillComposer, selectEngine, switchEngine, queueCount, markCompacting } = useStore();
const limit = state.rateLimits[state.cli];
const [text, setText] = useState("");
const handledPrefill = useRef<string | null>(null);
useEffect(() => {
const incoming = state.composerPrefill;
if (incoming === null) { handledPrefill.current = null; return; }
if (handledPrefill.current === incoming) return;
handledPrefill.current = incoming;
setText(previous => previous ? `${previous}\n\n${incoming}` : incoming);
prefillComposer(null);
}, [state.composerPrefill, prefillComposer]);
const effort = state.effortByCli[state.cli];
const model = state.modelByCli[state.cli];
const [controlsOpen, setControlsOpen] = useState(false);
Expand Down
21 changes: 21 additions & 0 deletions surfaces/webview/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -2250,3 +2250,24 @@ html[data-keyboard="open"] .an-shell-panels::after { display: none; }
from { transform: translateX(-24px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}

/* Market header actions share geometry; drafts use the existing violet accent. */
.an-market-action {
flex-shrink: 0;
align-self: center;
padding: 7px 11px;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--an-term-green);
border: 1px solid var(--an-term-green-line-2);
background: var(--an-term-green-bg);
}
.an-market-action[data-tone="draft"] {
color: var(--an-violet);
border-color: color-mix(in srgb, var(--an-violet) 35%, transparent);
background: color-mix(in srgb, var(--an-violet) 8%, var(--an-bg-1));
}
.an-market-action:active { opacity: 0.8; }
.an-market-action:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
65 changes: 60 additions & 5 deletions surfaces/webview/src/market/MarketScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useRef, useState, type CSSProperties } from "react";
import { skillCardFiring, useStore } from "../state/store";
import { SkillSdCard } from "./SkillSdCard";
import { SkillDetailView } from "./SkillDetailView";
import { readSkillDrafts, type SkillDraft } from "./skillDrafts";
import { PublishForm } from "./PublishForm";
import { AgentDirectory } from "./AgentDirectory";
import { BlogFeed } from "./BlogFeed";
Expand All @@ -14,7 +15,7 @@ import { LockIcon, SolIcon } from "../icons";
import { AlertCard } from "../Alert";
import { haptics } from "../haptics";

type MarketView = "browse" | "publish" | "helius";
type MarketView = "browse" | "publish" | "helius" | "drafts";
export type ShellTab = "market" | "skills" | "profile";

// The market-setup tutorial auto-opens the first time a wallet-less user reaches the market
Expand All @@ -37,6 +38,9 @@ export function MarketScreen({ tab, onBack, onGoMarket }: { tab: ShellTab; onBac
// Search text is LOCAL: keying it into the global store re-rendered the whole app on every
// keystroke. Only MarketScreen reads it, so it lives here (matches AgentDirectory's search).
const [query, setQuery] = useState("");
const [drafts, setDrafts] = useState<SkillDraft[]>([]);
const [draftError, setDraftError] = useState("");
const [editingDraft, setEditingDraft] = useState<SkillDraft>();
const [view, setView] = useState<MarketView>("browse");
// Hide already-owned skills from the market results by default (you came to find NEW ones);
// untick to show them too (muted/greyed).
Expand Down Expand Up @@ -171,12 +175,54 @@ export function MarketScreen({ tab, onBack, onGoMarket }: { tab: ShellTab; onBac
);
}

function openDrafts() {
try { setDrafts(readSkillDrafts()); setDraftError(""); }
catch (error) { setDraftError(error instanceof Error ? error.message : String(error)); }
setView("drafts");
}

if (view === "drafts") return (
<div className="an-screen flex h-full flex-col bg-zinc-950">
<header className="flex shrink-0 items-center gap-3 border-b px-3.5 py-3" style={{ borderColor: "var(--an-term-line)" }}>
<button type="button" className="an-iconbtn shrink-0" aria-label="Back to market" onClick={() => setView("browse")}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="m15 18-6-6 6-6" /></svg>
</button>
<div className="min-w-0 flex-1">
<h1 className="an-term-title text-[18px] leading-none">Drafts</h1>
<p className="mt-1 text-xs" style={{ color: "var(--an-term-fg-3)" }}>Saved on this device</p>
</div>
<button
type="button"
className="an-term-mono an-market-action"
data-tone="draft"
onClick={() => { setEditingDraft(undefined); setMarketTab("skill"); setView("publish"); }}
>+ New draft</button>
</header>
<div className="flex-1 space-y-2 overflow-y-auto p-3.5">
{draftError && <p role="alert" className="text-sm text-red-300">{draftError}</p>}
{!draftError && drafts.length === 0 && <p className="py-8 text-center text-sm" style={{ color: "var(--an-term-fg-3)" }}>No drafts yet</p>}
{!draftError && drafts.map(d => (
<button
type="button"
key={d.id}
className="block w-full border p-3 text-left active:opacity-80"
style={{ borderColor: "var(--an-term-line)", background: "var(--an-bg-1)" }}
onClick={() => { setEditingDraft(d); setView("publish"); }}
>
<span className="an-term-mono block break-words text-sm font-bold" style={{ color: "var(--an-term-fg)" }}>{d.name || "Untitled draft"}</span>
{d.description && <span className="mt-1 block line-clamp-2 text-xs" style={{ color: "var(--an-term-fg-3)" }}>{d.description}</span>}
</button>
))}
</div>
</div>
);

// Publish form (market tab) — opens pre-set to whichever kind you were browsing (skill
// or workflow tab), same as the VSCode builder.
if (view === "publish") {
return (
<div className="an-screen flex flex-col h-full bg-zinc-950">
<PublishForm initialKind={state.marketTab} onBack={() => setView("browse")} />
<PublishForm initialKind={editingDraft ? "skill" : state.marketTab} initialDraft={editingDraft} onBack={() => setView("browse")} />
</div>
);
}
Expand Down Expand Up @@ -244,12 +290,21 @@ export function MarketScreen({ tab, onBack, onGoMarket }: { tab: ShellTab; onBac
{balanceSol} <SolIcon />
</button>
)}
{isMarket && (
<button
type="button"
onClick={openDrafts}
className="an-term-mono an-market-action"
data-tone="draft"
>
Drafts
</button>
)}
{isMarket && (
<LockedGate reason="publish" onUnlocked={() => setView("publish")} className="shrink-0 self-center" badge={false}>
<button
onClick={() => setView("publish")}
className="an-term-mono text-[10px] font-bold uppercase tracking-wider active:opacity-80"
style={{ color: "var(--an-term-green)", border: "1px solid var(--an-term-green-line-2)", background: "var(--an-term-green-bg)", padding: "7px 11px" }}
onClick={() => { setEditingDraft(undefined); setView("publish"); }}
className="an-term-mono an-market-action"
>
+ Publish
</button>
Expand Down
40 changes: 40 additions & 0 deletions surfaces/webview/src/market/PublishForm.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { beforeEach, afterEach, expect, it, vi } from 'vitest';
import { PublishForm } from './PublishForm';
import { readSkillDrafts } from './skillDrafts';
const store = vi.hoisted(() => ({ state: { walletAddress: null as string | null, publishResult: null, publishProgress: null, marketOwned: [], marketOwnedMints: {}, marketOwnedWorkflowMints: [] }, send: vi.fn(), clearPublishResult: vi.fn(), prefillComposer: vi.fn() }));
vi.mock('../state/store', () => ({ useStore: () => store }));
vi.mock('../haptics', () => ({ haptics: { tick: vi.fn(), strong: vi.fn() } }));
let root: Root, host: HTMLDivElement;
const back = vi.fn();
async function render(initialDraft?: ReturnType<typeof readSkillDrafts>[number]) { await act(async () => root.render(<PublishForm onBack={back} initialDraft={initialDraft} />)); }
async function fill(placeholder: string, value: string) {
const field = placeholder.startsWith("# My Skill") ? host.querySelector("textarea")! : host.querySelector<HTMLInputElement>(`[placeholder="${placeholder}"]`)!;
const prototype = field instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
await act(async () => { Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(field, value); field.dispatchEvent(new Event('input', { bubbles: true })); });
}
async function click(text: string) { await act(async () => Array.from(host.querySelectorAll('button')).find(b => b.textContent === text)!.click()); }
beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); localStorage.clear(); vi.clearAllMocks(); host = document.createElement('div'); document.body.append(host); root = createRoot(host); });
afterEach(async () => { await act(async () => root.unmount()); host.remove(); });
it('saves/reopens a local draft with no wallet, chain request or lost form fields', async () => {
await render(); await fill('My Skill', 'qa-skill'); await fill('What does this skill do?', 'Review a local fixture.'); await fill('# My Skill&#10;&#10;## Description&#10;…', 'Read source.');
await click('Save draft');
const saved = readSkillDrafts()[0];
expect(saved.name).toBe('qa-skill'); expect(saved.text).toBe('Read source.'); expect(store.send).not.toHaveBeenCalled();
await act(async () => root.unmount()); root = createRoot(host); await render(saved);
expect(host.querySelector<HTMLInputElement>('[placeholder="My Skill"]')!.value).toBe('qa-skill');
});
it('test only prepares editable chat context; it never sends a message or publishes', async () => {
await render({ id: 'local', name: 'qa-skill', description: 'Read-only test', text: 'Inspect the fixture only.', category: '', hashtags: '', priceSol: '0', imageUrl: '' });
await click('Test in chat');
expect(store.prefillComposer).toHaveBeenCalledWith(expect.stringContaining('Inspect the fixture only.'));
expect(store.prefillComposer.mock.calls[0][0]).toMatch(/Task: $/);
expect(store.send).not.toHaveBeenCalled(); expect(back).toHaveBeenCalled();
});
it('storage failure keeps the editor and does not navigate or send the draft', async () => {
await render({ id: 'local', name: 'qa-skill', description: 'Read-only test', text: 'Inspect.', category: '', hashtags: '', priceSol: '0', imageUrl: '' });
const failure = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw Error('Quota exceeded'); });
try { await click('Test in chat'); expect(host.querySelector('[role=status]')?.textContent).toContain('Quota exceeded'); expect(store.prefillComposer).not.toHaveBeenCalled(); expect(back).not.toHaveBeenCalled(); }
finally { failure.mockRestore(); }
});
51 changes: 42 additions & 9 deletions surfaces/webview/src/market/PublishForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { useStore } from "../state/store";
import { haptics } from "../haptics";
import { saveSkillDraft, type SkillDraft } from "./skillDrafts";
import { ImageIcon, SkillIcon } from "../icons";

// Per-kind tint: skills forge violet, workflows forge amber (matches their card colors).
Expand Down Expand Up @@ -94,28 +95,49 @@ interface Props {
// Which kind the form opens to — e.g. hitting Publish from the Workflow browse tab should
// land straight in workflow mode, same as the VSCode builder. Defaults to "skill".
initialKind?: "skill" | "workflow";
initialDraft?: SkillDraft;
}

// A workflow can require at most 16 skills (MAX_REQUIRED_SKILLS in the agent-workflow-nft
// contract) and at least 1 — the on-chain gate that gives a workflow meaning.
const MAX_REQUIRED_SKILLS = 16;

export function PublishForm({ onBack, initialKind = "skill" }: Props) {
const { send, state, clearPublishResult } = useStore();
export function PublishForm({ onBack, initialKind = "skill", initialDraft }: Props) {
const { send, state, clearPublishResult, prefillComposer } = useStore();
const [kind, setKind] = useState<"skill" | "workflow">(initialKind);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [text, setText] = useState("");
const [category, setCategory] = useState("");
const [hashtags, setHashtags] = useState("");
const [name, setName] = useState(initialDraft?.name ?? "");
const [description, setDescription] = useState(initialDraft?.description ?? "");
const [text, setText] = useState(initialDraft?.text ?? "");
const [category, setCategory] = useState(initialDraft?.category ?? "");
const [hashtags, setHashtags] = useState(initialDraft?.hashtags ?? "");
// Default 0.1 SOL, in lockstep with the CLI form and the make-skill MCP tool — type 0
// explicitly to publish free. A 0 default made every mobile publish silently free.
const [priceSol, setPriceSol] = useState("0.1");
const [imageUrl, setImageUrl] = useState(""); // http/on-chain link only — no file upload
const [priceSol, setPriceSol] = useState(initialDraft?.priceSol ?? "0.1");
const [imageUrl, setImageUrl] = useState(initialDraft?.imageUrl ?? ""); // http/on-chain link only — no file upload
const [submitting, setSubmitting] = useState(false);
// Required-skills picker (workflow mode only): mint -> selected.
const [reqSel, setReqSel] = useState<Record<string, boolean>>({});

const [draftId] = useState(() => initialDraft?.id ?? crypto.randomUUID());
const [draftNotice, setDraftNotice] = useState("");

function saveDraft() {
try {
saveSkillDraft({ id: draftId, name, description, text, category, hashtags, priceSol, imageUrl });
setDraftNotice("Draft saved.");
return true;
} catch (error) {
setDraftNotice(`Could not save draft: ${error instanceof Error ? error.message : String(error)}`);
return false;
}
}

function testDraft() {
if (!saveDraft()) return;
prefillComposer(`Use this local, unpublished skill draft for the task below. It is a test, not a request to publish or mint it.\n\nSkill: ${name}\n${description}\n\n${text}\n\nTask: `);
onBack();
}

const result = state.publishResult;

// Skills the wallet actually owns and can require: must have a resolvable mint, and must
Expand Down Expand Up @@ -187,6 +209,7 @@ export function PublishForm({ onBack, initialKind = "skill" }: Props) {
<SkillIcon className="h-10 w-10" style={{ color: fg.accent }} />
<p className="an-term-mono" style={{ margin: 0, fontWeight: 700, fontSize: 14, letterSpacing: "0.1em", textTransform: "uppercase", color: fg.accent }}>&gt;{kind === "workflow" ? "Workflow_Minted" : "Skill_Minted"}<span className="unlock-cursor">_</span></p>
{result.mint && <p className="font-mono text-[11px]" style={{ color: "var(--an-term-fg-6)", wordBreak: "break-all", maxWidth: 280 }}>{result.mint}</p>}
<p className="max-w-sm text-xs leading-relaxed" style={{ color: "var(--an-term-fg-3)" }}>Published on-chain. It may take a few minutes to appear in Market. No need to publish again.</p>
<button onClick={() => { haptics.tick(); clearPublishResult(); onBack(); }} className="an-term-mono" style={{ marginTop: 6, fontWeight: 700, fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: fg.accent, background: "none", border: 0, cursor: "pointer" }}>&gt; Back_to_Market [&gt;]</button>
</div>
</div>
Expand Down Expand Up @@ -363,6 +386,15 @@ export function PublishForm({ onBack, initialKind = "skill" }: Props) {
</div>

<div className="shrink-0 bg-transparent p-3 an-tabbar-inset">
{kind === "skill" && <div className="mb-3 space-y-2">
<div className="flex gap-2">
<button type="button" className="an-term-field" onClick={saveDraft} disabled={!name.trim()}>Save draft</button>
<button type="button" className="an-term-field" onClick={testDraft} disabled={!name.trim() || !text.trim()}>Test in chat</button>
</div>
<p className="text-xs" style={{ color: "var(--an-fg-mute)" }}>Saved on this device. Test opens in chat; review and add a task before sending.</p>
{draftNotice && <p role="status" className="text-xs">{draftNotice}</p>}
</div>}

{/* Failure surfaces here as a bubble (not a separate page) so the filled-in form stays put. */}
{result && !result.ok && (
<div className="relative mb-3 rounded-lg border border-red-500/40 bg-red-950/60 px-3 py-2 text-xs text-red-300">
Expand All @@ -374,6 +406,7 @@ export function PublishForm({ onBack, initialKind = "skill" }: Props) {
onClick={handleSubmit}
disabled={
submitting ||
!state.walletAddress ||
!name.trim() ||
!imageValid ||
(kind === "skill" ? !text.trim() : chosenReqMints.length === 0 || chosenReqMints.length > MAX_REQUIRED_SKILLS)
Expand Down
19 changes: 19 additions & 0 deletions surfaces/webview/src/market/skillDrafts.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { beforeEach, expect, it } from 'vitest';
import { readSkillDrafts, saveSkillDraft, type SkillDraft } from './skillDrafts';
const draft: SkillDraft = { id: 'local-1', name: 'qa-skill', description: 'Local test skill', text: 'Inspect the fixture only.', category: 'development', hashtags: 'qa', priceSol: '0', imageUrl: '' };
beforeEach(() => localStorage.clear());
it('keeps multiple drafts and updates the same draft without duplicating it', () => {
saveSkillDraft(draft);
saveSkillDraft({ ...draft, id: 'local-2', name: 'second' });
saveSkillDraft({ ...draft, text: 'Revised draft' });
expect(readSkillDrafts()).toEqual([{ ...draft, id: 'local-2', name: 'second' }, { ...draft, text: 'Revised draft' }]);
});
it('preserves malformed stored data instead of replacing it during save', () => {
localStorage.setItem('agentnet:skill-drafts:v1', '{broken');
expect(() => saveSkillDraft(draft)).toThrow();
expect(localStorage.getItem('agentnet:skill-drafts:v1')).toBe('{broken');
});
it('rejects malformed entries without rendering or treating them as skills', () => {
localStorage.setItem('agentnet:skill-drafts:v1', JSON.stringify([{ name: 'incomplete' }]));
expect(() => readSkillDrafts()).toThrow('Existing data was kept');
});
31 changes: 31 additions & 0 deletions surfaces/webview/src/market/skillDrafts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Browser/device-local authoring only. This store never installs or mints a skill.
export interface SkillDraft {
id: string;
name: string;
description: string;
text: string;
category: string;
hashtags: string;
priceSol: string;
imageUrl: string;
}
const KEY = 'agentnet:skill-drafts:v1';
const fields = ['id', 'name', 'description', 'text', 'category', 'hashtags', 'priceSol', 'imageUrl'] as const;

export function readSkillDrafts(): SkillDraft[] {
const raw = localStorage.getItem(KEY);
if (!raw) return [];
const drafts: unknown = JSON.parse(raw);
if (!Array.isArray(drafts) || drafts.some(d => !d || typeof d !== 'object' || fields.some(k => typeof d[k] !== 'string'))) {
throw new Error('Saved drafts could not be read. Existing data was kept.');
}
return drafts as SkillDraft[];
}

export function saveSkillDraft(draft: SkillDraft): void {
const drafts = readSkillDrafts();
const previous = drafts.findIndex(d => d.id === draft.id);
if (previous < 0) drafts.unshift(draft);
else drafts[previous] = draft;
localStorage.setItem(KEY, JSON.stringify(drafts));
}
Loading
Loading