diff --git a/surfaces/webview/src/App.tsx b/surfaces/webview/src/App.tsx index e3e15775..daf9ebe5 100644 --- a/surfaces/webview/src/App.tsx +++ b/surfaces/webview/src/App.tsx @@ -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(() => { diff --git a/surfaces/webview/src/chat/Composer.tsx b/surfaces/webview/src/chat/Composer.tsx index ce4dc35a..90020798 100644 --- a/surfaces/webview/src/chat/Composer.tsx +++ b/surfaces/webview/src/chat/Composer.tsx @@ -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(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); diff --git a/surfaces/webview/src/index.css b/surfaces/webview/src/index.css index e2ca0892..9d9fe276 100644 --- a/surfaces/webview/src/index.css +++ b/surfaces/webview/src/index.css @@ -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; } diff --git a/surfaces/webview/src/market/MarketScreen.tsx b/surfaces/webview/src/market/MarketScreen.tsx index 7e845b43..0f4f1ca5 100644 --- a/surfaces/webview/src/market/MarketScreen.tsx +++ b/surfaces/webview/src/market/MarketScreen.tsx @@ -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"; @@ -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 @@ -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([]); + const [draftError, setDraftError] = useState(""); + const [editingDraft, setEditingDraft] = useState(); const [view, setView] = useState("browse"); // Hide already-owned skills from the market results by default (you came to find NEW ones); // untick to show them too (muted/greyed). @@ -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 ( +
+
+ +
+

Drafts

+

Saved on this device

+
+ +
+
+ {draftError &&

{draftError}

} + {!draftError && drafts.length === 0 &&

No drafts yet

} + {!draftError && drafts.map(d => ( + + ))} +
+
+ ); + // 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 (
- setView("browse")} /> + setView("browse")} />
); } @@ -244,12 +290,21 @@ export function MarketScreen({ tab, onBack, onGoMarket }: { tab: ShellTab; onBac {balanceSol} )} + {isMarket && ( + + )} {isMarket && ( setView("publish")} className="shrink-0 self-center" badge={false}> diff --git a/surfaces/webview/src/market/PublishForm.spec.tsx b/surfaces/webview/src/market/PublishForm.spec.tsx new file mode 100644 index 00000000..ced5d286 --- /dev/null +++ b/surfaces/webview/src/market/PublishForm.spec.tsx @@ -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[number]) { await act(async () => root.render()); } +async function fill(placeholder: string, value: string) { + const field = placeholder.startsWith("# My Skill") ? host.querySelector("textarea")! : host.querySelector(`[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 ## Description …', '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('[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(); } +}); diff --git a/surfaces/webview/src/market/PublishForm.tsx b/surfaces/webview/src/market/PublishForm.tsx index 756addfb..4d78b539 100644 --- a/surfaces/webview/src/market/PublishForm.tsx +++ b/surfaces/webview/src/market/PublishForm.tsx @@ -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). @@ -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>({}); + 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 @@ -187,6 +209,7 @@ export function PublishForm({ onBack, initialKind = "skill" }: Props) {

>{kind === "workflow" ? "Workflow_Minted" : "Skill_Minted"}_

{result.mint &&

{result.mint}

} +

Published on-chain. It may take a few minutes to appear in Market. No need to publish again.

@@ -363,6 +386,15 @@ export function PublishForm({ onBack, initialKind = "skill" }: Props) {
+ {kind === "skill" &&
+
+ + +
+

Saved on this device. Test opens in chat; review and add a task before sending.

+ {draftNotice &&

{draftNotice}

} +
} + {/* Failure surfaces here as a bubble (not a separate page) so the filled-in form stays put. */} {result && !result.ok && (
@@ -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) diff --git a/surfaces/webview/src/market/skillDrafts.spec.ts b/surfaces/webview/src/market/skillDrafts.spec.ts new file mode 100644 index 00000000..c904fb56 --- /dev/null +++ b/surfaces/webview/src/market/skillDrafts.spec.ts @@ -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'); +}); diff --git a/surfaces/webview/src/market/skillDrafts.ts b/surfaces/webview/src/market/skillDrafts.ts new file mode 100644 index 00000000..638e1da3 --- /dev/null +++ b/surfaces/webview/src/market/skillDrafts.ts @@ -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)); +} diff --git a/surfaces/webview/src/state/store.spec.tsx b/surfaces/webview/src/state/store.spec.tsx index 3b84d55e..3171e506 100644 --- a/surfaces/webview/src/state/store.spec.tsx +++ b/surfaces/webview/src/state/store.spec.tsx @@ -86,3 +86,11 @@ describe("context usage", () => { expect(background.contextWindow).toBe(100_000); }); }); + +it('prefilling a local skill test does not add messages or publish requests', () => { + const next = reducer(initialState, { type: '__prefillComposer', text: 'Local draft test' }); + expect(next.composerPrefill).toBe('Local draft test'); + expect(next.log).toEqual(initialState.log); + expect(next.publishProgress).toBeNull(); + expect(reducer(next, { type: '__prefillComposer', text: null }).composerPrefill).toBeNull(); +}); diff --git a/surfaces/webview/src/state/store.tsx b/surfaces/webview/src/state/store.tsx index d38f3e4b..7c4384fc 100644 --- a/surfaces/webview/src/state/store.tsx +++ b/surfaces/webview/src/state/store.tsx @@ -59,6 +59,8 @@ export interface State { | "codexAuth" | "customAuth" // custom engine picked with no saved endpoint: the AI Connections form, not a login | "chat"; + // One-shot, user-reviewed text handed from the draft editor to chat. + composerPrefill: string | null; // market overlay (accessible from chat phase via "Markets" button) marketOpen: boolean; marketInitialView: "browse" | "agents" | "owned"; @@ -225,6 +227,7 @@ export const initialState: State = { buyCelebrate: false, buyCelebrateLabel: null, lastBuyError: null, + composerPrefill: null, marketOpen: false, marketInitialView: "browse", marketTab: "skill", @@ -326,6 +329,7 @@ type LocalAction = | { type: "__dismissAuth" } | { type: "__savePlan"; text: string } | { type: "__openMarket"; initialView?: "browse" | "agents" | "owned" } + | { type: "__prefillComposer"; text: string | null } | { type: "__closeMarket" } | { type: "__setMarketTab"; tab: "skill" | "workflow" } | { type: "__setMarketQuery"; query: string } @@ -604,6 +608,8 @@ export function reducer(state: State, ev: Action): State { return { ...state, log: [...state.log, { role: "summary" as const, text: `Saved plan\n\n${ev.text}` }] }; case "__openMarket": return { ...state, marketOpen: true, marketInitialView: ev.initialView ?? "browse" }; + case "__prefillComposer": + return { ...state, composerPrefill: ev.text }; case "__closeMarket": return { ...state, marketOpen: false, marketDetail: null, publishResult: null }; case "__setMarketTab": @@ -802,6 +808,7 @@ interface Store { openMarket: () => void; openMarketAgents: () => void; openOwnedSkills: () => void; + prefillComposer: (text: string | null) => void; closeMarket: () => void; setMarketTab: (tab: "skill" | "workflow") => void; setMarketQuery: (q: string) => void; @@ -1169,6 +1176,7 @@ export function StoreProvider({ children }: { children: ReactNode }) { openMarket: () => raw({ type: "__openMarket" }), openMarketAgents: () => raw({ type: "__openMarket", initialView: "agents" }), openOwnedSkills: () => raw({ type: "__openMarket", initialView: "owned" }), + prefillComposer: (text) => raw({ type: "__prefillComposer", text }), closeMarket: () => raw({ type: "__closeMarket" }), setMarketTab: (tab) => raw({ type: "__setMarketTab", tab }), setMarketQuery: (query) => raw({ type: "__setMarketQuery", query }),