From 9f4e394f17356307bf6f1a3e274b9c597ba13294 Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Wed, 18 Nov 2026 14:55:55 +0100 Subject: [PATCH 01/11] feat(mcp): MCP Apps views behind ZERNIO_MCP_APPS (trial) Interactive views Claude and ChatGPT render in the chat, off unless ZERNIO_MCP_APPS=1 so production is unchanged until it is turned on. A view binds to the tool the host called, and most tools are reached through call_tool, so each view gets its own always-listed show_* display tool that fetches its own data (monday.com's show-* pattern): - show_post_preview: per-platform preview with validation, Publish now / Save as draft via posts_cross_post - show_failed_posts: failed posts with a Retry per post - show_analytics: daily totals and chart, fullscreen platform breakdown - show_account_health: accounts by health, Reconnect link - show_ads_alerts: ads needing attention, Fix / Dismiss / Ask Claude - show_automation_approvals: pending automation changes, Approve / Reject - zernio_overview: the overview card, rebuilt on the runtime ui_dismiss_ads_alert and ui_decide_automation_approval are app-only, for the views' buttons. Views are self-contained HTML (no CDN) on a shared MCP Apps 2026-01-26 bridge, styled with host tokens and the zernio.com accent. Everything lives in late/mcp/apps so the trial can be removed in one go. Co-Authored-By: Claude Opus 5.5 --- src/late/mcp/apps/__init__.py | 119 +++++++ src/late/mcp/apps/account-health.html | 85 +++++ src/late/mcp/apps/ads-alerts.html | 106 ++++++ src/late/mcp/apps/analytics.html | 154 ++++++++ src/late/mcp/apps/automation-approvals.html | 110 ++++++ src/late/mcp/apps/base.css | 110 ++++++ src/late/mcp/apps/failed-posts.html | 92 +++++ src/late/mcp/apps/overview.html | 40 +++ src/late/mcp/apps/post-preview.html | 155 ++++++++ src/late/mcp/apps/runtime.js | 251 +++++++++++++ src/late/mcp/apps/tools.py | 371 ++++++++++++++++++++ src/late/mcp/server.py | 62 ++-- 12 files changed, 1627 insertions(+), 28 deletions(-) create mode 100644 src/late/mcp/apps/__init__.py create mode 100644 src/late/mcp/apps/account-health.html create mode 100644 src/late/mcp/apps/ads-alerts.html create mode 100644 src/late/mcp/apps/analytics.html create mode 100644 src/late/mcp/apps/automation-approvals.html create mode 100644 src/late/mcp/apps/base.css create mode 100644 src/late/mcp/apps/failed-posts.html create mode 100644 src/late/mcp/apps/overview.html create mode 100644 src/late/mcp/apps/post-preview.html create mode 100644 src/late/mcp/apps/runtime.js create mode 100644 src/late/mcp/apps/tools.py diff --git a/src/late/mcp/apps/__init__.py b/src/late/mcp/apps/__init__.py new file mode 100644 index 00000000..4f840fb1 --- /dev/null +++ b/src/late/mcp/apps/__init__.py @@ -0,0 +1,119 @@ +"""MCP Apps: the interactive views Claude and ChatGPT render for tool results. + +A trial, off unless ZERNIO_MCP_APPS=1, kept in this package so it can be +removed in one go: delete it and the apps lines in server.py. + +Each view is one self-contained HTML document under ``ui://zernio/``, built +from a template in this package plus the shared runtime.js (the host bridge) +and base.css (host theme tokens with zernio.com fallbacks). Inline scripts +and styles only, so the host can review the whole document and no CDN sits +in the render path. The show_* tools in tools.py are the views' entry points. +""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import TYPE_CHECKING + +from fastmcp.apps import UI_MIME_TYPE, AppConfig, ResourceCSP, app_config_to_meta_dict +from fastmcp.resources import TextResource +from mcp.types import ToolAnnotations + +from .tools import register_tools + +if TYPE_CHECKING: + from fastmcp import FastMCP + +_DIR = Path(__file__).parent + +# Hosts cache ui:// resources aggressively: bump on a change an old cached view +# could not handle (a new data shape, a renamed tool it calls). +_VERSION = "v1" + +# Images in post previews come from Zernio media storage; Claude serves its +# host fonts from assets.claude.ai. Nothing else is fetched, and views reach +# the API only through the host (tools/call), so connectDomains stays empty. +_CSP = ResourceCSP( + resource_domains=["https://media.zernio.com", "https://assets.claude.ai"], +) + +VIEWS = { + "overview": "Zernio overview card", + "post-preview": "Post preview", + "failed-posts": "Failed posts", + "analytics": "Analytics", + "account-health": "Account health", + "ads-alerts": "Ads alerts", + "automation-approvals": "Automation approvals", +} + +# Listed up front while the trial is on. The ui_* tools are app-only: listed +# so the host lets the views call them, hidden from the model by the host. +APP_TOOLS = [ + "show_post_preview", + "show_failed_posts", + "show_analytics", + "show_account_health", + "show_ads_alerts", + "show_automation_approvals", + "ui_dismiss_ads_alert", + "ui_decide_automation_approval", +] + + +def apps_enabled() -> bool: + return os.getenv("ZERNIO_MCP_APPS", "").lower() in ("1", "true", "yes") + + +def view_uri(name: str) -> str: + return f"ui://zernio/{_VERSION}/{name}.html" + + +def _html(name: str) -> str: + def read(file: str) -> str: + return (_DIR / file).read_text(encoding="utf-8") + + return ( + read(f"{name}.html") + .replace("/*ZERNIO_CSS*/", read("base.css")) + .replace("/*ZERNIO_RUNTIME*/", read("runtime.js")) + ) + + +def register_apps(mcp: FastMCP) -> None: + """Serve every view and register the tools that render them.""" + for name, title in VIEWS.items(): + mcp.add_resource( + TextResource( + uri=view_uri(name), + name=title, + mime_type=UI_MIME_TYPE, + text=_html(name), + meta={"ui": app_config_to_meta_dict(AppConfig(csp=_CSP))}, + ) + ) + register_tools(mcp, view_uri) + _replace_overview(mcp) + + +def _replace_overview(mcp: FastMCP) -> None: + # resources.py's zernio_overview points at the old static card; swap it + # for the same tool on this view, which keeps its text answer. + from late.mcp.resources import _OVERVIEW + + mcp.local_provider.remove_tool("zernio_overview") + + @mcp.tool( + name="zernio_overview", + description="Show an overview of what this Zernio MCP server can do (accounts, posts, analytics, ads, inbox) and how to find the right tool.", + annotations=ToolAnnotations( + title="Zernio server overview", + readOnlyHint=True, + destructiveHint=False, + openWorldHint=False, + ), + app=AppConfig(resource_uri=view_uri("overview"), visibility=["model"]), + ) + def zernio_overview() -> str: + return _OVERVIEW diff --git a/src/late/mcp/apps/account-health.html b/src/late/mcp/apps/account-health.html new file mode 100644 index 00000000..afc8cbd2 --- /dev/null +++ b/src/late/mcp/apps/account-health.html @@ -0,0 +1,85 @@ + + + + + + +Zernio account health + + + +
+
+
+ + + + diff --git a/src/late/mcp/apps/ads-alerts.html b/src/late/mcp/apps/ads-alerts.html new file mode 100644 index 00000000..72374cfa --- /dev/null +++ b/src/late/mcp/apps/ads-alerts.html @@ -0,0 +1,106 @@ + + + + + + +Zernio ads alerts + + + +
+
+
+ + + + diff --git a/src/late/mcp/apps/analytics.html b/src/late/mcp/apps/analytics.html new file mode 100644 index 00000000..0451950b --- /dev/null +++ b/src/late/mcp/apps/analytics.html @@ -0,0 +1,154 @@ + + + + + + +Zernio analytics + + + +
+
+
+ + + + diff --git a/src/late/mcp/apps/automation-approvals.html b/src/late/mcp/apps/automation-approvals.html new file mode 100644 index 00000000..7e5c8be7 --- /dev/null +++ b/src/late/mcp/apps/automation-approvals.html @@ -0,0 +1,110 @@ + + + + + + +Zernio automation approvals + + + +
+
+
+ + + + diff --git a/src/late/mcp/apps/base.css b/src/late/mcp/apps/base.css new file mode 100644 index 00000000..6d66f1b8 --- /dev/null +++ b/src/late/mcp/apps/base.css @@ -0,0 +1,110 @@ +/* Zernio MCP App styles. Structure (text, borders, surfaces, fonts) reads the + host's MCP Apps tokens so a view sits natively in Claude or ChatGPT; each + fallback is the zernio.com value. Zernio's identity lives in the accent, + the square 4px corners and the mono uppercase labels. */ +:root { + color-scheme: light dark; + --z-accent: #eb3514; + --z-accent-hover: #cd2c0e; + --z-accent-subtle: light-dark(#fce9e5, #261614); + --z-on-accent: #fff; + --z-text: var(--color-text-primary, light-dark(#1a1a1a, #fafafa)); + --z-text-2: var(--color-text-secondary, light-dark(#525252, #d4d4d4)); + --z-text-3: var(--color-text-tertiary, light-dark(#6b6b6b, #a3a3a3)); + --z-border: var(--color-border-primary, light-dark(#e4e4e4, #202022)); + --z-border-subtle: var(--color-border-secondary, light-dark(#f2f2f2, #1b1b1d)); + --z-surface: var(--color-background-secondary, light-dark(#faf9f7, #141416)); + --z-success: var(--color-text-success, light-dark(#15803d, #4ade80)); + --z-warning: var(--color-text-warning, light-dark(#b45309, #fbbf24)); + --z-danger: var(--color-text-danger, light-dark(#c0260f, #f87171)); + --z-radius: 4px; + --z-font: var(--font-sans, "Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif); + --z-mono: var(--font-mono, "Geist Mono", Menlo, Consolas, monospace); + --z-tap: 32px; +} +:root[data-theme="light"] { color-scheme: light; } +:root[data-theme="dark"] { color-scheme: dark; } +:root[data-touch] { --z-tap: 44px; } + +* { box-sizing: border-box; } +html, body { margin: 0; background: transparent; } +body { + padding: calc(12px + var(--safe-top, 0px)) calc(12px + var(--safe-right, 0px)) + calc(12px + var(--safe-bottom, 0px)) calc(12px + var(--safe-left, 0px)); + font: 14px/1.45 var(--z-font); + color: var(--z-text); + -webkit-font-smoothing: antialiased; +} +button { font: inherit; } +:focus-visible { outline: 2px solid var(--z-accent); outline-offset: 2px; } + +.eyebrow { + display: flex; align-items: center; gap: 6px; + margin: 0 0 8px; + font: 500 11px/1 var(--z-mono); + letter-spacing: 0.06em; text-transform: uppercase; + color: var(--z-text-3); +} +.eyebrow .mark { width: 8px; height: 8px; border-radius: 2px; background: var(--z-accent); } +h1 { margin: 0 0 4px; font-size: 16px; font-weight: 600; line-height: 1.3; } +.muted { color: var(--z-text-2); } +.small { font-size: 12px; color: var(--z-text-3); } + +.card { + border: 1px solid var(--z-border); + border-radius: var(--z-radius); + padding: 12px; +} +.row { display: flex; align-items: center; gap: 8px; } +.wrap { flex-wrap: wrap; } +.grow { flex: 1; min-width: 0; } +.stack > * + * { margin-top: 10px; } +.divided > * + * { border-top: 1px solid var(--z-border-subtle); } + +.chip { + display: inline-flex; align-items: center; gap: 6px; + height: 24px; padding: 0 8px; + border: 1px solid var(--z-border); border-radius: var(--z-radius); + font-size: 12px; color: var(--z-text-2); white-space: nowrap; +} +.dot { width: 6px; height: 6px; border-radius: 50%; background: var(--z-text-3); flex: none; } +.dot.ok { background: var(--z-success); } +.dot.warn { background: var(--z-warning); } +.dot.bad { background: var(--z-danger); } +.dot.brand { background: var(--z-accent); } + +.actions { display: flex; gap: 8px; margin-top: 12px; } +.btn { + min-height: var(--z-tap); padding: 0 14px; + border: 1px solid var(--z-border); border-radius: var(--z-radius); + background: transparent; color: var(--z-text); + font-size: 13px; font-weight: 500; cursor: pointer; +} +.btn:hover { background: var(--z-surface); } +.btn.primary { background: var(--z-accent); border-color: var(--z-accent); color: var(--z-on-accent); } +.btn.primary:hover { background: var(--z-accent-hover); border-color: var(--z-accent-hover); } +.btn.small { min-height: 28px; padding: 0 10px; font-size: 12px; } +:root[data-touch] .btn.small { min-height: 44px; } +.btn[disabled] { opacity: 0.5; cursor: default; } + +.notice { + padding: 8px 10px; border-radius: var(--z-radius); + border-left: 2px solid var(--z-text-3); + background: var(--z-surface); font-size: 13px; +} +.notice.ok { border-left-color: var(--z-success); } +.notice.warn { border-left-color: var(--z-warning); } +.notice.bad { border-left-color: var(--z-danger); } + +.num { font-variant-numeric: tabular-nums; } +.clamp { display: -webkit-box; -webkit-box-orient: vertical; overflow: hidden; } + +.skeleton { display: grid; gap: 8px; } +.skeleton i { + display: block; height: 12px; border-radius: 2px; + background: linear-gradient(90deg, var(--z-border-subtle), var(--z-border), var(--z-border-subtle)); + background-size: 200% 100%; + animation: shimmer 1.4s ease-in-out infinite; +} +@keyframes shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } } +@media (prefers-reduced-motion: reduce) { .skeleton i { animation: none; } } diff --git a/src/late/mcp/apps/failed-posts.html b/src/late/mcp/apps/failed-posts.html new file mode 100644 index 00000000..744bb45b --- /dev/null +++ b/src/late/mcp/apps/failed-posts.html @@ -0,0 +1,92 @@ + + + + + + +Zernio failed posts + + + +
+
+
+ + + + diff --git a/src/late/mcp/apps/overview.html b/src/late/mcp/apps/overview.html new file mode 100644 index 00000000..f180ba28 --- /dev/null +++ b/src/late/mcp/apps/overview.html @@ -0,0 +1,40 @@ + + + + + + +Zernio + + + +
+

Zernio

+

Social media API for agents

+

Publish, schedule and analyze across 16 platforms, with a unified inbox and ads on 7 networks.

+
+
PublishPost or schedule to many accounts at once
+
InboxDMs and comments in one place
+
AnalyticsDaily metrics across platforms
+
AdsCampaigns on 7 ad networks
+
+
+ + +
+
+ + + + diff --git a/src/late/mcp/apps/post-preview.html b/src/late/mcp/apps/post-preview.html new file mode 100644 index 00000000..83f2ab00 --- /dev/null +++ b/src/late/mcp/apps/post-preview.html @@ -0,0 +1,155 @@ + + + + + + +Zernio post preview + + + +
+
+
+ + + + diff --git a/src/late/mcp/apps/runtime.js b/src/late/mcp/apps/runtime.js new file mode 100644 index 00000000..87294c48 --- /dev/null +++ b/src/late/mcp/apps/runtime.js @@ -0,0 +1,251 @@ +// Zernio MCP App runtime: the MCP Apps (2026-01-26) host bridge every view +// shares. JSON-RPC 2.0 over postMessage with the host window, no dependencies, +// so a view is one self-contained HTML document the host can review. +(function () { + "use strict"; + + var PROTOCOL_VERSION = "2026-01-26"; + var nextId = 1; + var pending = {}; + var listeners = {}; + var context = {}; + + function send(message) { + message.jsonrpc = "2.0"; + window.parent.postMessage(message, "*"); + } + + function request(method, params) { + var id = nextId++; + return new Promise(function (resolve, reject) { + pending[id] = { resolve: resolve, reject: reject }; + send({ id: id, method: method, params: params || {} }); + }); + } + + function notify(method, params) { + send({ method: method, params: params || {} }); + } + + function emit(event, payload) { + (listeners[event] || []).forEach(function (fn) { + try { + fn(payload); + } catch (err) { + console.error(err); + } + }); + } + + // Host notification -> view event. + var EVENTS = { + "ui/notifications/tool-input": "input", + "ui/notifications/tool-input-partial": "partial", + "ui/notifications/tool-result": "result", + "ui/notifications/tool-cancelled": "cancelled", + }; + + function applyContext(changed) { + // host-context-changed carries only the fields that changed. + context = Object.assign({}, context, changed); + var root = document.documentElement; + if (changed.theme === "light" || changed.theme === "dark") { + root.setAttribute("data-theme", changed.theme); + root.style.colorScheme = changed.theme; + } + var styles = changed.styles || {}; + var variables = styles.variables || {}; + Object.keys(variables).forEach(function (name) { + if (variables[name] != null) root.style.setProperty(name, variables[name]); + }); + if (styles.css && styles.css.fonts && !document.getElementById("host-fonts")) { + var fonts = document.createElement("style"); + fonts.id = "host-fonts"; + fonts.textContent = styles.css.fonts; + document.head.appendChild(fonts); + } + var insets = changed.safeAreaInsets; + if (insets) { + ["top", "right", "bottom", "left"].forEach(function (side) { + root.style.setProperty("--safe-" + side, (insets[side] || 0) + "px"); + }); + } + if (changed.displayMode) root.setAttribute("data-display-mode", changed.displayMode); + if (changed.deviceCapabilities && changed.deviceCapabilities.touch) { + root.setAttribute("data-touch", ""); + } + emit("context", context); + } + + window.addEventListener("message", function (event) { + if (event.source !== window.parent) return; + var message = event.data; + if (!message || message.jsonrpc !== "2.0") return; + + if (message.method === undefined) { + var waiting = pending[message.id]; + if (!waiting) return; + delete pending[message.id]; + if (message.error) waiting.reject(new Error(message.error.message || "Request failed")); + else waiting.resolve(message.result || {}); + return; + } + + var params = message.params || {}; + if (message.id !== undefined) { + // Requests from the host: ping and teardown are the only ones a view + // without its own tools receives. + if (message.method === "ui/resource-teardown") emit("teardown", params); + if (message.method === "ping" || message.method === "ui/resource-teardown") { + send({ id: message.id, result: {} }); + } else { + send({ id: message.id, error: { code: -32601, message: "Method not found" } }); + } + return; + } + + if (message.method === "ui/notifications/host-context-changed") applyContext(params); + else if (EVENTS[message.method]) emit(EVENTS[message.method], params); + }); + + // Reports the document height so the host sizes the inline frame to fit, + // the same measurement the official SDK's autoResize makes. + function watchSize() { + var queued = false; + var last = ""; + function measure() { + if (queued) return; + queued = true; + requestAnimationFrame(function () { + queued = false; + var root = document.documentElement; + var previous = root.style.height; + root.style.height = "max-content"; + var height = Math.ceil(root.getBoundingClientRect().height); + root.style.height = previous; + var width = Math.ceil(window.innerWidth); + if (width + "x" + height === last) return; + last = width + "x" + height; + notify("ui/notifications/size-changed", { width: width, height: height }); + }); + } + measure(); + var observer = new ResizeObserver(measure); + observer.observe(document.documentElement); + observer.observe(document.body); + } + + // Tool results reach a view as {structuredContent, content}. Tools that + // return text still carry it as structuredContent.result, and generated + // tools' text is compact JSON, so data() unwraps both shapes. + function textOf(result) { + var structured = result && result.structuredContent; + if (structured && typeof structured.result === "string") return structured.result; + var blocks = (result && result.content) || []; + return blocks + .filter(function (block) { return block.type === "text"; }) + .map(function (block) { return block.text; }) + .join("\n"); + } + + function dataOf(result) { + var structured = result && result.structuredContent; + if (structured && !(Object.keys(structured).length === 1 && "result" in structured)) { + return structured; + } + try { + return JSON.parse(textOf(result)); + } catch (err) { + return null; + } + } + + function el(tag, attrs) { + var node = document.createElement(tag); + Object.keys(attrs || {}).forEach(function (key) { + var value = attrs[key]; + if (value == null || value === false) return; + if (key === "text") node.textContent = value; + else if (key === "class") node.className = value; + else if (key.slice(0, 2) === "on") node.addEventListener(key.slice(2), value); + else node.setAttribute(key, value === true ? "" : value); + }); + for (var i = 2; i < arguments.length; i++) append(node, arguments[i]); + return node; + } + + function append(node, child) { + if (child == null || child === false) return; + if (Array.isArray(child)) child.forEach(function (c) { append(node, c); }); + else node.appendChild(typeof child === "string" ? document.createTextNode(child) : child); + } + + var PLATFORM_NAMES = { + twitter: "X", instagram: "Instagram", facebook: "Facebook", linkedin: "LinkedIn", + tiktok: "TikTok", youtube: "YouTube", threads: "Threads", pinterest: "Pinterest", + reddit: "Reddit", bluesky: "Bluesky", googlebusiness: "Google Business", + telegram: "Telegram", snapchat: "Snapchat", discord: "Discord", slack: "Slack", + whatsapp: "WhatsApp", + }; + + function platformName(platform) { + return PLATFORM_NAMES[platform] || platform || "Unknown"; + } + + function compact(value) { + try { + return new Intl.NumberFormat(context.locale, { notation: "compact", maximumFractionDigits: 1 }).format(value || 0); + } catch (err) { + return String(value || 0); + } + } + + function date(value, options) { + if (!value) return ""; + var parsed = new Date(value); + if (isNaN(parsed)) return String(value); + try { + return parsed.toLocaleString(context.locale, Object.assign({ timeZone: context.timeZone }, options)); + } catch (err) { + return parsed.toLocaleString(); + } + } + + window.Zernio = { + on: function (event, fn) { + (listeners[event] = listeners[event] || []).push(fn); + }, + connect: function (options) { + options = options || {}; + return request("ui/initialize", { + appInfo: { name: "Zernio " + (options.name || "view"), version: "1.0.0" }, + appCapabilities: { availableDisplayModes: options.displayModes || ["inline"] }, + protocolVersion: PROTOCOL_VERSION, + }).then(function (result) { + applyContext(result.hostContext || {}); + notify("ui/notifications/initialized"); + watchSize(); + return result; + }); + }, + context: function () { return context; }, + callTool: function (name, args) { + return request("tools/call", { name: name, arguments: args || {} }); + }, + openLink: function (url) { return request("ui/open-link", { url: url }); }, + requestDisplayMode: function (mode) { return request("ui/request-display-mode", { mode: mode }); }, + // Posts a message into the chat as the user, for Claude to act on. + sendMessage: function (text) { + return request("ui/message", { role: "user", content: [{ type: "text", text: text }] }); + }, + tellModel: function (text) { + return request("ui/update-model-context", { content: [{ type: "text", text: text }] }); + }, + text: textOf, + data: dataOf, + el: el, + platformName: platformName, + compact: compact, + date: date, + }; +})(); diff --git a/src/late/mcp/apps/tools.py b/src/late/mcp/apps/tools.py new file mode 100644 index 00000000..7a9dc096 --- /dev/null +++ b/src/late/mcp/apps/tools.py @@ -0,0 +1,371 @@ +"""Display tools: one per view, always listed, each fetching its own data. + +The data tools stay text-only behind search_tools. A view binds to the tool +the host called, so a view on a tool reached through call_tool never renders; +these show_* tools are the listed entry points instead (monday.com's +show-table / show-board pattern). Each returns a text summary for the model +and clients without MCP Apps, and structured_content for its view. + +The ui_* tools are app-only: the views' buttons call them, the model never +sees them. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from fastmcp.apps import AppConfig +from fastmcp.exceptions import ToolError +from fastmcp.tools import ToolResult +from mcp.types import ToolAnnotations + +from late.client.exceptions import LateError + +if TYPE_CHECKING: + from fastmcp import FastMCP + +_DISPLAY = ( + "UI display tool: renders an interactive view in clients that support MCP Apps, " + "with a text summary for those that do not." +) + +_READ = ToolAnnotations(readOnlyHint=True, destructiveHint=False, openWorldHint=False) + + +def _server() -> Any: + # Imported at call time: server.py registers these tools while it is + # still loading. + from late.mcp import server + + return server + + +def _api(call: Any) -> Any: + try: + return call() + except LateError as e: + raise ToolError(f"Error: {e}") from e + + +def register_tools(mcp: FastMCP, view_uri: Any) -> None: + def show(name: str, view: str, title: str, description: str) -> Any: + return mcp.tool( + name=name, + description=f"{description}\n\n{_DISPLAY}", + annotations=_READ.model_copy(update={"title": title}), + app=AppConfig(resource_uri=view_uri(view)), + ) + + def app_only(name: str, title: str, description: str) -> Any: + return mcp.tool( + name=name, + description=description, + annotations=ToolAnnotations( + title=title, readOnlyHint=False, destructiveHint=True, openWorldHint=True + ), + app=AppConfig(visibility=["app"]), + ) + + @show( + "show_post_preview", + "post-preview", + "Preview a post", + "Show the user how a post will go out on each platform before anything is " + "published: the account each platform resolves to, the text, the media, and " + "validation errors and warnings. Use it when the user wants to see or review a " + "post first. Nothing is published; the view's Publish now and Save as draft " + "buttons call posts_cross_post with these same arguments. For a scheduled post, " + "confirm in chat and call posts_create or posts_cross_post.\n\n" + "Args:\n" + " content: The post text (required)\n" + " platforms: Comma-separated platforms, e.g. 'twitter,linkedin' (required). " + "Repeat a platform to target several of its accounts.\n" + " account_ids: Comma-separated account IDs parallel to platforms. Empty " + "positions resolve automatically.\n" + " profile_id: Scope automatic resolution to one profile.\n" + " media_urls: Comma-separated media URLs to attach.", + ) + def show_post_preview( + content: str, + platforms: str, + account_ids: str = "", + profile_id: str = "", + media_urls: str = "", + ) -> ToolResult: + server = _server() + client = server._get_client() + + target_platforms = [p.strip().lower() for p in platforms.split(",") if p.strip()] + if not target_platforms: + raise ToolError("No platforms specified.") + ids = [i.strip() for i in account_ids.split(",")] if account_ids else [] + ids += [""] * max(0, len(target_platforms) - len(ids)) + + # Resolved the way posts_cross_post resolves them, so the preview names + # the accounts a publish would reach and shows the same ambiguity errors. + targets: list[dict[str, str]] = [] + for plat, acc_id in zip(target_platforms, ids[: len(target_platforms)], strict=True): + try: + acc = server._resolve_account(client, plat, acc_id, profile_id) + except ValueError as e: + targets.append({"platform": plat, "error": str(e)}) + continue + targets.append( + { + "platform": server._platform_str(acc.platform), + "accountId": acc.field_id, + "handle": acc.username or acc.displayName or "", + } + ) + + media = server._media_items(media_urls) + resolved = [ + {"platform": t["platform"], "accountId": t["accountId"]} + for t in targets + if "accountId" in t + ] + validation: dict[str, Any] | None = None + if resolved: + try: + validation = client.validate.validate_post( + resolved, content=content, media_items=media or None + ) + except LateError as e: + validation = {"warnings": [{"warning": f"Validation unavailable: {e}"}]} + + lines = [ + "Preview only, nothing was published.", + "Targets: " + + ", ".join( + f"{t['platform']} (@{t['handle']})" if t.get("handle") else t["platform"] + for t in targets + ), + f"Length: {len(content)} characters" + + (f", {len(media)} media file(s)" if media else ""), + ] + lines += [f"Account ({t['platform']}): {t['error']}" for t in targets if "error" in t] + for issue in (validation or {}).get("errors") or []: + lines.append(f"Error ({issue.get('platform') or 'all'}): {issue.get('error')}") + for issue in (validation or {}).get("warnings") or []: + lines.append(f"Warning ({issue.get('platform') or 'all'}): {issue.get('warning')}") + if len(resolved) == len(targets): + lines.append( + "To publish it as previewed, call posts_cross_post with platforms=" + f"'{','.join(t['platform'] for t in targets)}' and account_ids=" + f"'{','.join(t['accountId'] for t in targets)}'." + ) + + return ToolResult( + content="\n".join(lines), + structured_content={ + "kind": "preview", + "post": { + "content": content, + "media": [ + {"type": getattr(m["type"], "value", m["type"]), "url": m["url"]} + for m in media + ], + "targets": targets, + }, + "validation": validation, + # What the view's buttons send to posts_cross_post, with the + # accounts already resolved. + "request": { + "content": content, + "platforms": ",".join(t["platform"] for t in targets), + "account_ids": ",".join(t.get("accountId", "") for t in targets), + "profile_id": profile_id, + "media_urls": media_urls, + }, + }, + ) + + @show( + "show_failed_posts", + "failed-posts", + "Show failed posts", + "Show the posts that failed to publish, each platform's error, and a Retry button " + "per post. Use it when the user wants to see what failed or fix it.\n\n" + "Args:\n" + " limit: Maximum number of posts to show. Default: 10.", + ) + def show_failed_posts(limit: int = 10) -> ToolResult: + server = _server() + client = server._get_client() + posts = _api(lambda: client.posts.list(status="failed", limit=limit)).posts or [] + + view = [ + { + "id": post.field_id, + "content": (post.content or "")[:280], + "platforms": [t.platform for t in post.platforms or [] if t.platform], + "errors": [ + {"platform": platform, "message": message} + for platform, message in server._failed_targets(post) + ], + } + for post in posts + ] + lines = [f"{len(view)} failed post(s)."] + [ + f"- {p['id']} ({', '.join(p['platforms'])}): " + + ("; ".join(f"{e['platform']}: {e['message']}" for e in p["errors"]) or "Unknown error") + for p in view + ] + return ToolResult(content="\n".join(lines), structured_content={"posts": view}) + + @show( + "show_analytics", + "analytics", + "Show analytics", + "Show daily post analytics as a chart: totals for impressions, engagement, views and " + "posts, a per-day chart of each, and a fullscreen per-platform breakdown. Use it when " + "the user wants to see how their posts perform. Defaults to the last 180 days.\n\n" + "Args:\n" + " platform: Only this platform, e.g. 'instagram'.\n" + " profile_id: Only this profile.\n" + " account_id: Only this account.\n" + " from_date: Inclusive start date (ISO 8601).\n" + " to_date: Inclusive end date (ISO 8601).", + ) + def show_analytics( + platform: str = "", + profile_id: str = "", + account_id: str = "", + from_date: str = "", + to_date: str = "", + ) -> ToolResult: + client = _server()._get_client() + data = _api( + lambda: client.analytics.get_daily_metrics( + platform=platform or None, + profile_id=profile_id or None, + account_id=account_id or None, + from_date=from_date or None, + to_date=to_date or None, + ) + ) + totals = data.get("totals") or {} + days = data.get("dailyData") or [] + text = ( + f"{len(days)} day(s) with posts. Totals: {totals.get('postCount', 0)} posts, " + f"{totals.get('impressions', 0)} impressions, {totals.get('engagement', 0)} " + f"engagements, {totals.get('views', 0)} views." + ) + return ToolResult(content=text, structured_content=data) + + @show( + "show_account_health", + "account-health", + "Show account health", + "Show connected social accounts by health status, the ones that need attention and " + "why, with a link to reconnect. Use it when the user asks whether their accounts " + "work or why posting fails for one.\n\n" + "Args:\n" + " profile_id: Only this profile.\n" + " platform: Only this platform.", + ) + def show_account_health(profile_id: str = "", platform: str = "") -> ToolResult: + client = _server()._get_client() + data = _api( + lambda: client.accounts.get_all_accounts_health( + profile_id=profile_id or None, platform=platform or None + ) + ) + summary = data.get("summary") or {} + unhealthy = [a for a in data.get("accounts") or [] if a.get("status") != "healthy"] + lines = [ + f"{summary.get('total', 0)} account(s): {summary.get('healthy', 0)} healthy, " + f"{summary.get('warning', 0)} warning, {summary.get('error', 0)} error, " + f"{summary.get('needsReconnect', 0)} need reconnecting." + ] + [ + f"- {a.get('platform')} @{a.get('username') or a.get('accountId')}: {a.get('status')}" + + (f" ({(a.get('issues') or [a.get('disconnectReason')])[0]})" if a.get("issues") or a.get("disconnectReason") else "") + for a in unhealthy[:25] + ] + return ToolResult(content="\n".join(lines), structured_content=data) + + @show( + "show_ads_alerts", + "ads-alerts", + "Show ads that need attention", + "Show what needs attention across the user's ads, most severe first: rejected ads, " + "delivery issues, payment problems, campaigns spending without results, capped " + "budgets, lost connections and failing syncs. Each has a link to fix it and can be " + "dismissed for 30 days. Use it when the user asks how their ads are doing or what " + "is wrong with them.\n\n" + "Args:\n" + " account_id: Only alerts of this ads connection.\n" + " profile_id: Only alerts of the ads connections on this profile.", + ) + def show_ads_alerts(account_id: str = "", profile_id: str = "") -> ToolResult: + client = _server()._get_client() + data = _api( + lambda: client.ad_campaigns.list_ads_alerts( + account_id=account_id or None, profile_id=profile_id or None + ) + ) + alerts = data.get("alerts") or [] + lines = [f"{len(alerts)} ads alert(s)."] + [ + f"- [{a.get('severity')}] {a.get('title')}: {a.get('message')} (id: {a.get('id')})" + for a in alerts[:25] + ] + return ToolResult(content="\n".join(lines), structured_content=data) + + @show( + "show_automation_approvals", + "automation-approvals", + "Show automation approvals", + "Show the changes an ads automation is waiting for a person to approve (pauses, " + "budget, bid and target changes), with Approve and Reject buttons. Use it when the " + "user wants to review or decide pending automation approvals. Find automation IDs " + "with search_tools ('list automations').\n\n" + "Args:\n" + " automation_id: The automation (required)\n" + " status: Only requests in this status. Default: pending.", + ) + def show_automation_approvals( + automation_id: str, + status: Literal["pending", "approved", "rejected", "expired", "cancelled"] = "pending", + ) -> ToolResult: + client = _server()._get_client() + data = _api( + lambda: client.automations.list_automation_approvals( + automation_id=automation_id, status=status + ) + ) + approvals = data.get("approvals") or [] + lines = [f"{len(approvals)} {status} approval request(s)."] + [ + f"- {a.get('id')}: {len(a.get('changes') or [])} change(s), expires {a.get('expiresAt')}" + + ("" if a.get("canDecide") else " (you cannot decide it)") + for a in approvals + ] + return ToolResult( + content="\n".join(lines), + structured_content={**data, "automationId": automation_id}, + ) + + @app_only( + "ui_dismiss_ads_alert", + "Dismiss an ads alert", + "Hide an ads alert for 30 days. Called by the ads alerts view.", + ) + def ui_dismiss_ads_alert(alert_id: str) -> dict[str, Any]: + client = _server()._get_client() + return _api(lambda: client.ad_campaigns.dismiss_ads_alert(alert_id)) + + @app_only( + "ui_decide_automation_approval", + "Approve or reject an automation request", + "Approve or reject a pending automation approval request. Called by the automation " + "approvals view.", + ) + def ui_decide_automation_approval( + automation_id: str, approval_id: str, decision: Literal["approve", "reject"] + ) -> dict[str, Any]: + client = _server()._get_client() + decide = ( + client.automations.approve_automation_approval + if decision == "approve" + else client.automations.reject_automation_approval + ) + return _api(lambda: decide(automation_id, approval_id)) diff --git a/src/late/mcp/server.py b/src/late/mcp/server.py index 1229098f..cf1343de 100644 --- a/src/late/mcp/server.py +++ b/src/late/mcp/server.py @@ -48,6 +48,7 @@ from late import Late, MediaType, PostStatus from late.client.exceptions import LateAPIError, LateError, LateRateLimitError +from .apps import APP_TOOLS, apps_enabled, register_apps from .auth import build_auth_provider, forget_rejected_token from .idempotency import same_arguments_key from .middleware import ( @@ -148,6 +149,8 @@ def _api_transport() -> httpx.BaseTransport: "mentions_list_inbox_mentions", # Report bugs and missing features to Zernio FEEDBACK_TOOL, + # MCP Apps display tools, while the ZERNIO_MCP_APPS trial is on + *(APP_TOOLS if apps_enabled() else []), ] _SEARCH_TOOL = "search_tools" @@ -800,8 +803,8 @@ def profiles_delete(profile_id: str) -> str: # ============================================================================ -def _platform_errors(post: Any) -> list[str]: - """One "Error (platform): message" line per platform that did not publish. +def _failed_targets(post: Any) -> list[tuple[str | None, str]]: + """(platform, error message) for each platform that did not publish. A post holds one entry in post.platforms[] per target platform, and each entry tracks its own status and errorMessage. The API never populates @@ -826,10 +829,33 @@ def _platform_errors(post: Any) -> list[str]: continue message = (target.errorMessage or "").strip() if message: - errors.append(f"Error ({target.platform or '?'}): {message}") + errors.append((target.platform, message)) return errors +def _platform_errors(post: Any) -> list[str]: + """One "Error (platform): message" line per platform that did not publish.""" + return [ + f"Error ({platform or '?'}): {message}" + for platform, message in _failed_targets(post) + ] + + +def _media_items(media_urls: str) -> list[dict[str, Any]]: + """Media items for comma-separated URLs, typed by file extension.""" + items = [] + for url in (u.strip() for u in media_urls.split(",")): + if not url: + continue + media_type: MediaType | str = MediaType.IMAGE + if any(ext in url.lower() for ext in [".mp4", ".mov", ".avi", ".webm", ".m4v"]): + media_type = MediaType.VIDEO + elif ".gif" in url.lower(): + media_type = MediaType.GIF + items.append({"type": media_type, "url": url}) + return items + + @tool_def("posts_list") def posts_list(status: str = "", limit: int = 10) -> str: client = _get_client() @@ -926,20 +952,8 @@ def posts_create( if title: params["title"] = title - # Add media items if provided if media_urls: - urls = [u.strip() for u in media_urls.split(",") if u.strip()] - media_items = [] - for url in urls: - media_type: MediaType | str = MediaType.IMAGE - if any( - ext in url.lower() for ext in [".mp4", ".mov", ".avi", ".webm", ".m4v"] - ): - media_type = MediaType.VIDEO - elif any(ext in url.lower() for ext in [".gif"]): - media_type = MediaType.GIF - media_items.append({"type": media_type, "url": url}) - params["media_items"] = media_items + params["media_items"] = _media_items(media_urls) if is_draft: params["is_draft"] = True @@ -1039,18 +1053,7 @@ def posts_cross_post( } if media_urls: - urls = [u.strip() for u in media_urls.split(",") if u.strip()] - media_items = [] - for url in urls: - media_type: MediaType | str = MediaType.IMAGE - if any( - ext in url.lower() for ext in [".mp4", ".mov", ".avi", ".webm", ".m4v"] - ): - media_type = MediaType.VIDEO - elif any(ext in url.lower() for ext in [".gif"]): - media_type = MediaType.GIF - media_items.append({"type": media_type, "url": url}) - params["media_items"] = media_items + params["media_items"] = _media_items(media_urls) if is_draft: params["is_draft"] = True @@ -1464,6 +1467,9 @@ async def support_ask( # generated_tools.py not yet created - run scripts/generate_mcp_tools.py pass +if apps_enabled(): + register_apps(mcp) + # ============================================================================ # MAIN From 238e09eeac4fbe1674b5a4836625f208b8913bc8 Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Wed, 18 Nov 2026 14:56:20 +0100 Subject: [PATCH 02/11] chore(railway): dev tracks feat/mcp-apps with ZERNIO_MCP_APPS=1 Co-Authored-By: Claude Opus 5.5 --- .railway/railway.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/.railway/railway.ts b/.railway/railway.ts index cb1cf7e0..b2c09b7a 100644 --- a/.railway/railway.ts +++ b/.railway/railway.ts @@ -5,10 +5,16 @@ import { defineRailway, github, preserve, project, service } from "railway/iac"; // GitHub source per environment, as connected today. Omitting it disconnects -// the repo, and pushes stop deploying. dev has no repo connected. +// the repo, and pushes stop deploying. dev tracks the MCP Apps trial branch. const SOURCES: Record> = { production: github("zernio-dev/zernio-python", { branch: "develop" }), "zernio-mcp-dev": github("zernio-dev/zernio-mcp", { checkSuites: true }), + dev: github("zernio-dev/zernio-python", { branch: "feat/mcp-apps" }), +}; + +// Values set here rather than kept from Railway. +const SET_VARIABLES: Record> = { + dev: { ZERNIO_MCP_APPS: "1" }, }; // Variables stay managed in Railway; preserve() keeps the current values. @@ -28,9 +34,12 @@ const VARIABLES: Record = { export default defineRailway((ctx) => { const environment = ctx.environment ?? ""; - const env = Object.fromEntries( - (VARIABLES[environment] ?? []).map((name) => [name, preserve()]), - ); + const env = { + ...Object.fromEntries( + (VARIABLES[environment] ?? []).map((name) => [name, preserve()]), + ), + ...SET_VARIABLES[environment], + }; // The service instance itself is set to Railpack with no health check, so // the builder, Dockerfile path and health check must be explicit here. From c18244de26b6f6539611ecd362075b8cc64b0077 Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Wed, 18 Nov 2026 15:22:28 +0100 Subject: [PATCH 03/11] feat(mcp): routed Zernio MCP App in Vite + TypeScript (trial) A first cut of one app instead of separate views, following beel-mcp's structure: apps-src/ is a Vite + TypeScript project on the official ext-apps SDK, built by vite-plugin-singlefile into one self-contained src/late/mcp/apps/bundle/app.html (248 kB, 66 kB gzipped), committed so the Python image needs no Node. zernio_open_app opens it (also listed on Claude's Artifacts page through the openai/ui entry point). The app loads its own data with callServerTool: account health, and failed posts through the unlisted posts_list_posts, which tests whether Claude lets an app call a tool it never listed. Inline it is a compact card with Open Zernio for full screen; it tells Claude what it shows (updateModelContext) and hands fixes to the chat (sendMessage). zernio.com tokens, Lucide icons. Co-Authored-By: Claude Opus 5.5 --- apps-src/.gitignore | 1 + apps-src/app.html | 13 + apps-src/package-lock.json | 1516 +++++++++++++++++++++++++++++ apps-src/package.json | 23 + apps-src/src/client.ts | 41 + apps-src/src/copy.ts | 21 + apps-src/src/dom.ts | 42 + apps-src/src/format.ts | 19 + apps-src/src/main.ts | 113 +++ apps-src/src/model.ts | 34 + apps-src/src/store.ts | 24 + apps-src/src/styles.css | 166 ++++ apps-src/src/views/home.ts | 108 ++ apps-src/src/views/shell.ts | 34 + apps-src/tsconfig.json | 15 + apps-src/vite.config.ts | 15 + src/late/mcp/apps/__init__.py | 46 + src/late/mcp/apps/bundle/app.html | 115 +++ 18 files changed, 2346 insertions(+) create mode 100644 apps-src/.gitignore create mode 100644 apps-src/app.html create mode 100644 apps-src/package-lock.json create mode 100644 apps-src/package.json create mode 100644 apps-src/src/client.ts create mode 100644 apps-src/src/copy.ts create mode 100644 apps-src/src/dom.ts create mode 100644 apps-src/src/format.ts create mode 100644 apps-src/src/main.ts create mode 100644 apps-src/src/model.ts create mode 100644 apps-src/src/store.ts create mode 100644 apps-src/src/styles.css create mode 100644 apps-src/src/views/home.ts create mode 100644 apps-src/src/views/shell.ts create mode 100644 apps-src/tsconfig.json create mode 100644 apps-src/vite.config.ts create mode 100644 src/late/mcp/apps/bundle/app.html diff --git a/apps-src/.gitignore b/apps-src/.gitignore new file mode 100644 index 00000000..c2658d7d --- /dev/null +++ b/apps-src/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/apps-src/app.html b/apps-src/app.html new file mode 100644 index 00000000..ba3b664a --- /dev/null +++ b/apps-src/app.html @@ -0,0 +1,13 @@ + + + + + + + Zernio + + +
+ + + diff --git a/apps-src/package-lock.json b/apps-src/package-lock.json new file mode 100644 index 00000000..0058ffee --- /dev/null +++ b/apps-src/package-lock.json @@ -0,0 +1,1516 @@ +{ + "name": "zernio-mcp-app", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "zernio-mcp-app", + "dependencies": { + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/core": "2.4.0", + "@modelcontextprotocol/ext-apps": "2.0.4", + "lucide": "1.75.0", + "zod": "4.6.7" + }, + "devDependencies": { + "typescript": "7.0.2", + "vite": "8.3.8", + "vite-plugin-singlefile": "2.3.4" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz", + "integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.4.0", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.8", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz", + "integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==", + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/ext-apps": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-2.0.4.tgz", + "integrity": "sha512-B+PcbuGiaf0e5I3uy4iO5tS3Abo+5w8JvZFzHMzQdq9yVwP836zJkw2+KCGOQ0r4TM1fuQi4JdnbuWjkS4aBvg==", + "license": "MIT", + "workspaces": [ + "examples/*" + ], + "dependencies": { + "@standard-schema/spec": "^1.1.0" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/client": "^2.0.0", + "@modelcontextprotocol/core": "^2.0.0", + "@modelcontextprotocol/server": "^2.0.0", + "react": "^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.0 || ^18.0.0 || ^19.0.0", + "zod": "^4.2.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/server": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.17", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.17.tgz", + "integrity": "sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lucide": { + "version": "1.75.0", + "resolved": "https://registry.npmjs.org/lucide/-/lucide-1.75.0.tgz", + "integrity": "sha512-WNKnvz1XU6pcNuldOVx6gQx755isQcx8wWnIq8J6NNlHkqo9NJVLyTXC+0cizbdYEwROBSp/PXpMNqwf3d85XA==", + "license": "ISC" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-plugin-singlefile": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/vite-plugin-singlefile/-/vite-plugin-singlefile-2.3.4.tgz", + "integrity": "sha512-1FAhlTCL6KJDpSUudrVU+gspapvS+tmKCg70vwNaAU6tyXn3E/C6+NnwQIze06byhBRv7VggZ78K0h+J/Rsdrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^4.0.7" + }, + "engines": { + "node": ">18.0.0" + }, + "peerDependencies": { + "rollup": "^4.59.0", + "vite": "^5.4.21 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/apps-src/package.json b/apps-src/package.json new file mode 100644 index 00000000..a59033ad --- /dev/null +++ b/apps-src/package.json @@ -0,0 +1,23 @@ +{ + "name": "zernio-mcp-app", + "private": true, + "type": "module", + "description": "The Zernio MCP App (the interactive view Claude and ChatGPT render). Built into ../src/late/mcp/apps/bundle/app.html, which the Python server serves.", + "scripts": { + "build": "tsc --noEmit && vite build", + "dev": "vite build --watch", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/core": "2.4.0", + "@modelcontextprotocol/ext-apps": "2.0.4", + "lucide": "1.75.0", + "zod": "4.6.7" + }, + "devDependencies": { + "typescript": "7.0.2", + "vite": "8.3.8", + "vite-plugin-singlefile": "2.3.4" + } +} diff --git a/apps-src/src/client.ts b/apps-src/src/client.ts new file mode 100644 index 00000000..ef8deaf8 --- /dev/null +++ b/apps-src/src/client.ts @@ -0,0 +1,41 @@ +/** + * The app's data, read through the server's ordinary tools (callServerTool), + * so the API's validation and the user's scopes apply as they do for Claude. + * Generated tools return compact JSON as their text. + */ +import type { App } from "@modelcontextprotocol/ext-apps"; +import type { AccountsHealth } from "./model"; + +export type CallToolResult = Awaited>; +export type CallTool = (name: string, args: Record) => Promise; + +export class ToolError extends Error {} + +function json(result: CallToolResult): T { + const text = result.content + .filter((block) => block.type === "text") + .map((block) => (block as { text: string }).text) + .join(""); + if (result.isError) throw new ToolError(text || "The tool call failed."); + return JSON.parse(text) as T; +} + +export class ZernioClient { + constructor(private call: CallTool) {} + + async health(): Promise { + return json(await this.call("accounts_get_all_accounts_health", {})); + } + + /** + * How many posts failed. posts_list_posts is not listed up front (it sits + * behind search_tools), so this also tests whether the host lets an app + * call a tool it never received in tools/list. + */ + async failedPosts(): Promise { + const page = json<{ posts?: unknown[]; pagination?: { total?: number } }>( + await this.call("posts_list_posts", { status: "failed", limit: 1 }), + ); + return page.pagination?.total ?? page.posts?.length ?? 0; + } +} diff --git a/apps-src/src/copy.ts b/apps-src/src/copy.ts new file mode 100644 index 00000000..d964d8c8 --- /dev/null +++ b/apps-src/src/copy.ts @@ -0,0 +1,21 @@ +/** Every user-facing string, in one place. */ +export const COPY = { + brand: "Zernio", + title: "Workspace", + stats: { + accounts: "Accounts", + attention: "Need attention", + failed: "Failed posts", + }, + allHealthy: "Every account can post.", + attentionTitle: "Accounts that need attention", + accountsTitle: "All accounts", + open: "Open Zernio", + refresh: "Refresh", + reconnect: "Reconnect in Zernio", + askClaude: "Ask Claude to fix", + unavailable: "—", + loadFailed: "Could not load your workspace.", + sentToClaude: "Sent to Claude. Continue in the chat.", + status: { healthy: "Healthy", warning: "Warning", error: "Error" } as Record, +}; diff --git a/apps-src/src/dom.ts b/apps-src/src/dom.ts new file mode 100644 index 00000000..30c4fb61 --- /dev/null +++ b/apps-src/src/dom.ts @@ -0,0 +1,42 @@ +/** + * A minimal element builder. Text always goes in as text nodes, so nothing an + * API returns can become markup: there is no innerHTML anywhere in the app. + */ +import { createElement, type IconNode } from "lucide"; + +export type Child = Node | string | false | null | undefined; + +type Handlers = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void }; + +interface Props { + class?: string; + /** Attributes; `false` and `undefined` leave one out, `true` sets it empty. */ + attrs?: Record; + on?: Handlers; +} + +export function h( + tag: K, + props: Props = {}, + ...children: Array +): HTMLElementTagNameMap[K] { + const el = document.createElement(tag); + if (props.class) el.className = props.class; + for (const [name, value] of Object.entries(props.attrs ?? {})) { + if (value === undefined || value === false) continue; + el.setAttribute(name, value === true ? "" : String(value)); + } + for (const [type, handler] of Object.entries(props.on ?? {})) { + el.addEventListener(type, handler as EventListener); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + el.appendChild(typeof child === "string" ? document.createTextNode(child) : child); + } + return el; +} + +/** A Lucide icon, sized by CSS and hidden from screen readers. */ +export function icon(node: IconNode, className = "icon"): SVGElement { + return createElement(node, { class: className, "aria-hidden": "true" }); +} diff --git a/apps-src/src/format.ts b/apps-src/src/format.ts new file mode 100644 index 00000000..d5f83498 --- /dev/null +++ b/apps-src/src/format.ts @@ -0,0 +1,19 @@ +/** Number and name formatting. Missing values read "—". */ +import { COPY } from "./copy"; + +const PLATFORMS: Record = { + twitter: "X", instagram: "Instagram", facebook: "Facebook", linkedin: "LinkedIn", + tiktok: "TikTok", youtube: "YouTube", threads: "Threads", pinterest: "Pinterest", + reddit: "Reddit", bluesky: "Bluesky", googlebusiness: "Google Business", + telegram: "Telegram", snapchat: "Snapchat", discord: "Discord", slack: "Slack", + whatsapp: "WhatsApp", +}; + +export function platformName(platform: string | undefined): string { + return (platform && PLATFORMS[platform]) || platform || COPY.unavailable; +} + +export function count(value: number | undefined, locale?: string): string { + if (value === undefined) return COPY.unavailable; + return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(value); +} diff --git a/apps-src/src/main.ts b/apps-src/src/main.ts new file mode 100644 index 00000000..1026d1a1 --- /dev/null +++ b/apps-src/src/main.ts @@ -0,0 +1,113 @@ +/** + * The Zernio MCP App: entry point. Wires the host connection (the official + * ext-apps SDK) to the store, loads the workspace through the server's tools, + * and renders. Opened by the zernio_open_app tool. + */ +import { + App, + applyDocumentTheme, + applyHostFonts, + applyHostStyleVariables, + type McpUiHostContext, +} from "@modelcontextprotocol/ext-apps"; +import { ZernioClient } from "./client"; +import { COPY } from "./copy"; +import { INITIAL_STATE, type Account, type AppState } from "./model"; +import { Store } from "./store"; +import { homeView } from "./views/home"; +import { shell, skeleton } from "./views/shell"; +import "./styles.css"; + +const app = new App({ name: "Zernio", version: "0.1.0" }, { availableDisplayModes: ["inline", "fullscreen"] }); +const client = new ZernioClient((name, args) => app.callServerTool({ name, arguments: args })); +const store = new Store(INITIAL_STATE); +const root = document.getElementById("root") as HTMLElement; + +// A response for a load the user has already replaced is dropped. +let loadSeq = 0; + +async function load(): Promise { + const seq = ++loadSeq; + store.set({ phase: store.get().health ? "loading" : "connecting", error: undefined }); + const [health, failed] = await Promise.allSettled([client.health(), client.failedPosts()]); + if (seq !== loadSeq) return; + if (failed.status === "rejected") console.warn("[zernio-app] failed posts unavailable:", failed.reason); + store.set({ + phase: "ready", + health: health.status === "fulfilled" ? health.value : store.get().health, + failedPosts: failed.status === "fulfilled" ? failed.value : undefined, + error: health.status === "rejected" ? `${COPY.loadFailed} ${String((health.reason as Error).message ?? "")}` : undefined, + }); + void tellModel(); +} + +/** Tells Claude what the panel shows, so "these accounts" resolves to them. */ +async function tellModel(): Promise { + if (!app.getHostCapabilities()?.updateModelContext) return; + const { health, failedPosts } = store.get(); + const attention = (health?.accounts ?? []).filter((a) => a.status !== "healthy"); + const text = + `The Zernio panel shows the workspace: ${health?.summary?.total ?? 0} accounts, ` + + `${attention.length} needing attention` + + (attention.length ? ` (${attention.map((a) => `${a.platform} @${a.username ?? a.accountId}`).join(", ")})` : "") + + (failedPosts !== undefined ? `, ${failedPosts} failed posts.` : "."); + await app.updateModelContext({ + content: [{ type: "text", text }], + structuredContent: { view: "home", attention: attention.map((a) => a.accountId), failedPosts }, + }); +} + +async function ask(account: Account): Promise { + const issue = account.issues?.[0] || account.disconnectReason || account.status; + const result = await app.sendMessage({ + role: "user", + content: [{ type: "text", text: `My ${account.platform} account @${account.username ?? account.accountId} (account_id ${account.accountId}) shows "${issue}" in Zernio. Help me fix it.` }], + }); + store.set({ feedback: result.isError ? { tone: "error", text: "Could not send it to Claude." } : { tone: "ok", text: COPY.sentToClaude } }); +} + +function render(state: AppState): void { + const ctx = app.getHostContext(); + const canExpand = ctx?.displayMode !== "fullscreen" && !!ctx?.availableDisplayModes?.includes("fullscreen"); + const body = + state.phase === "connecting" + ? skeleton() + : homeView({ + state, + compact: ctx?.displayMode !== "fullscreen", + canExpand, + locale: ctx?.locale, + expand: () => void app.requestDisplayMode({ mode: "fullscreen" }).catch(() => undefined), + refresh: () => void load(), + reconnect: () => void app.openLink({ url: "https://zernio.com/dashboard" }), + ask: (account) => void ask(account), + }); + root.replaceChildren(shell(state, body)); +} + +function applyHostContext(ctx: McpUiHostContext): void { + if (ctx.theme) applyDocumentTheme(ctx.theme); + // Host tokens only set the page surface; the brand tokens are prefixed and + // never overridden by them. + if (ctx.styles?.variables) applyHostStyleVariables(ctx.styles.variables); + if (ctx.styles?.css?.fonts) applyHostFonts(ctx.styles.css.fonts); + const doc = document.documentElement; + doc.dataset.display = ctx.displayMode ?? "inline"; + doc.style.setProperty("--safe-bottom", `${ctx.safeAreaInsets?.bottom ?? 0}px`); + render(store.get()); +} + +// Handlers are registered before connect(): the host may send the tool result +// as soon as the handshake completes. +app.onerror = (err) => console.error("[zernio-app]", err); +app.onhostcontextchanged = applyHostContext; +app.ontoolresult = () => void load(); +app.ontoolcancelled = () => store.set({ phase: "ready", error: "Cancelled." }); + +store.subscribe(render); +render(store.get()); + +void app.connect().then(() => { + const ctx = app.getHostContext(); + if (ctx) applyHostContext(ctx); +}); diff --git a/apps-src/src/model.ts b/apps-src/src/model.ts new file mode 100644 index 00000000..2e61c13b --- /dev/null +++ b/apps-src/src/model.ts @@ -0,0 +1,34 @@ +/** The app's state and the shapes of the API data it shows. */ + +export interface Account { + accountId: string; + platform: string; + username?: string; + displayName?: string; + status: "healthy" | "warning" | "error"; + needsReconnect?: boolean; + issues?: string[]; + disconnectReason?: string | null; +} + +export interface AccountsHealth { + summary?: { total?: number; healthy?: number; warning?: number; error?: number; needsReconnect?: number }; + accounts?: Account[]; +} + +export interface Feedback { + tone: "ok" | "error"; + text: string; +} + +export interface AppState { + /** connecting: no data yet (skeleton). loading: refreshing over what is shown. */ + phase: "connecting" | "loading" | "ready"; + health?: AccountsHealth; + /** undefined when the failed-posts call is not reachable from the app. */ + failedPosts?: number; + error?: string; + feedback?: Feedback; +} + +export const INITIAL_STATE: AppState = { phase: "connecting" }; diff --git a/apps-src/src/store.ts b/apps-src/src/store.ts new file mode 100644 index 00000000..56ea01e8 --- /dev/null +++ b/apps-src/src/store.ts @@ -0,0 +1,24 @@ +/** + * The app's state container: one object, replaced by patches, with listeners + * notified after each change. Views render from a snapshot and never write to + * it; only main.ts's loaders do. + */ +export class Store { + private listeners = new Set<(state: S) => void>(); + + constructor(private state: S) {} + + get(): S { + return this.state; + } + + set(patch: Partial): void { + this.state = { ...this.state, ...patch }; + for (const listener of this.listeners) listener(this.state); + } + + subscribe(listener: (state: S) => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } +} diff --git a/apps-src/src/styles.css b/apps-src/src/styles.css new file mode 100644 index 00000000..f204ff1b --- /dev/null +++ b/apps-src/src/styles.css @@ -0,0 +1,166 @@ +/* Zernio MCP App. Raw tokens are zernio.com's, taken from its stylesheet + (--bg-*, --text-*, --border-*, --brand-*); components read only the role + tokens below. The host's surface is the one host token used, so the panel + sits in the conversation; light/dark follows data-theme, which the SDK sets + from the host. One 4px radius, 1px hairlines, two weights, numbers in mono. */ +:root { + --z-brand: #eb3514; + --z-brand-hover: #d22e0e; + --z-brand-subtle: #fce9e4; + --z-raised: #ffffff; + --z-ink: #1a1a1a; + --z-ink-2: #525252; + --z-ink-3: #6b6b6b; + --z-line: #e4e4e4; + --z-line-subtle: #f2f2f2; + --z-hover: rgba(92, 62, 37, 0.03); + --z-ok: #15803d; + --z-ok-bg: #ecfdf3; + --z-warn: #b45309; + --z-warn-bg: #fffbeb; + --z-error: #c0260f; + --z-error-bg: #fef2f0; + --z-radius: 4px; + --z-font: "Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --z-mono: "Geist Mono", ui-monospace, Menlo, Consolas, monospace; + --z-ease: cubic-bezier(0.4, 0, 0.2, 1); + + /* roles */ + --page: var(--color-background-primary, #faf9f7); + --card: var(--z-raised); + --text: var(--z-ink); + --muted: var(--z-ink-3); + --line: var(--z-line); + color-scheme: light; +} +:root[data-theme="dark"] { + --z-brand-subtle: #261614; + --z-raised: #151516; + --z-ink: #fafafa; + --z-ink-2: #d4d4d4; + --z-ink-3: #a3a3a3; + --z-line: #212123; + --z-line-subtle: #1c1c1e; + --z-hover: rgba(255, 255, 255, 0.04); + --z-ok: #4ade80; + --z-ok-bg: rgba(74, 222, 128, 0.1); + --z-warn: #fbbf24; + --z-warn-bg: rgba(251, 191, 36, 0.1); + --z-error: #f87171; + --z-error-bg: rgba(248, 113, 113, 0.1); + --page: var(--color-background-primary, #0f0f10); + color-scheme: dark; +} + +* { box-sizing: border-box; } +html, body { margin: 0; background: transparent; } +body { font: 400 14px/20px var(--z-font); color: var(--text); -webkit-font-smoothing: antialiased; } +button { font: inherit; color: inherit; } +:focus-visible { outline: 2px solid var(--z-brand); outline-offset: 2px; } + +.app { + position: relative; + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--z-radius); + padding: 16px; +} +:root[data-display="fullscreen"] .app { + min-height: 100vh; + border: 0; + border-radius: 0; + background: var(--page); + max-width: 960px; + margin: 0 auto; + padding: 20px 16px calc(var(--safe-bottom, 0px) + 112px); +} + +.header { display: flex; align-items: center; gap: 8px; margin-bottom: 16px; } +.mark { width: 14px; height: 14px; border-radius: 3px; background: var(--z-brand); } +.brand { font-weight: 500; } +.title { color: var(--muted); } +.title::before { content: "/"; margin-right: 8px; color: var(--line); } + +.eyebrow { + font: 500 10.5px/14px var(--z-mono); + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); +} +.muted { color: var(--muted); margin-left: 6px; } + +/* The stats are one card split by hairlines, not three boxes. */ +.stats { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + border: 1px solid var(--line); + border-radius: var(--z-radius); +} +.stat { padding: 12px 14px; } +.stat + .stat { border-left: 1px solid var(--line); } +.stat-value { margin-top: 6px; font: 500 22px/28px var(--z-mono); font-variant-numeric: tabular-nums; letter-spacing: -0.02em; } +.stat-warn .stat-value { color: var(--z-warn); } +.stat-error .stat-value { color: var(--z-error); } + +.section { margin-top: 20px; } +.list { list-style: none; margin: 8px 0 0; padding: 0; } +.row { display: flex; align-items: center; gap: 12px; padding: 10px 0; } +/* Dashed divider drawn as a gradient: a dashed border changes its spacing with the box. */ +.row + .row { + background: linear-gradient(90deg, var(--line) 50%, transparent 0) top left / 6px 1px repeat-x; +} +.row-main { flex: 1; min-width: 0; } +.row-title { font-weight: 500; } +.row-sub { font-size: 13px; color: var(--z-ink-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.empty { display: flex; align-items: center; gap: 8px; margin: 8px 0 0; color: var(--z-ink-2); } +.empty .icon { color: var(--z-ok); } + +.badge { + display: inline-flex; align-items: center; gap: 4px; + height: 24px; padding: 0 8px; + border-radius: var(--z-radius); + font-size: 12px; font-weight: 500; white-space: nowrap; +} +.badge-healthy { color: var(--z-ok); background: var(--z-ok-bg); } +.badge-warning { color: var(--z-warn); background: var(--z-warn-bg); } +.badge-error { color: var(--z-error); background: var(--z-error-bg); } + +.actions { display: flex; align-items: center; gap: 8px; margin-top: 20px; } +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: 6px; + height: 32px; padding: 0 12px; + border: 1px solid var(--line); border-radius: var(--z-radius); + background: transparent; + font-size: 13px; font-weight: 500; cursor: pointer; + transition: background 150ms var(--z-ease), transform 150ms var(--z-ease); +} +.btn:hover { background: var(--z-hover); } +.btn:active { transform: scale(0.97); } +.btn[disabled] { opacity: 0.5; cursor: default; } +.btn-primary { background: var(--z-brand); border-color: var(--z-brand); color: #fff; } +.btn-primary:hover { background: var(--z-brand-hover); border-color: var(--z-brand-hover); } +.btn-ghost { border-color: transparent; } +.btn-icon { width: 32px; padding: 0; margin-left: auto; } +.row .btn-icon { margin-left: 0; } + +.icon { width: 16px; height: 16px; flex: none; } +.icon-sm { width: 14px; height: 14px; } +.spin { animation: spin 1s linear infinite; } + +.notice { margin-bottom: 12px; padding: 8px 12px; border-radius: var(--z-radius); font-size: 13px; } +.notice-ok { color: var(--z-ok); background: var(--z-ok-bg); } +.notice-error { color: var(--z-error); background: var(--z-error-bg); } + +.progress { + position: absolute; top: 0; left: 0; right: 0; height: 2px; overflow: hidden; + background: linear-gradient(90deg, transparent, var(--z-brand), transparent) 0 0 / 40% 100% no-repeat; + animation: progress 1.2s var(--z-ease) infinite; +} +.skeleton { display: grid; gap: 10px; } +.skeleton i { display: block; height: 14px; border-radius: 2px; background: var(--z-line-subtle); animation: pulse 1.4s ease-in-out infinite; } + +@keyframes spin { to { transform: rotate(360deg); } } +@keyframes progress { from { background-position: -40% 0; } to { background-position: 140% 0; } } +@keyframes pulse { 50% { opacity: 0.5; } } +@media (prefers-reduced-motion: reduce) { *, *::before { animation: none !important; transition: none !important; } } +@media (max-width: 420px) { .stat-value { font-size: 18px; } .stat { padding: 10px; } } diff --git a/apps-src/src/views/home.ts b/apps-src/src/views/home.ts new file mode 100644 index 00000000..28bc5ddd --- /dev/null +++ b/apps-src/src/views/home.ts @@ -0,0 +1,108 @@ +/** + * Home: the workspace at a glance. Inline it is a compact card (three stats, + * up to three accounts that need attention, Open Zernio); full screen it lists + * every account. + */ +import { AlertTriangle, CircleCheck, CircleX, Maximize2, RefreshCw, SendHorizontal } from "lucide"; +import { COPY } from "../copy"; +import { h, icon } from "../dom"; +import { count, platformName } from "../format"; +import type { Account, AppState } from "../model"; + +export interface HomeEnv { + state: AppState; + compact: boolean; + canExpand: boolean; + locale?: string; + /** Must run inside the click: the host refuses a mode change without a gesture. */ + expand(): void; + refresh(): void; + reconnect(): void; + ask(account: Account): void; +} + +const RANK = { error: 0, warning: 1, healthy: 2 } as const; + +function issueOf(account: Account): string { + if (account.needsReconnect) return account.disconnectReason || "Needs to be reconnected"; + return account.issues?.[0] || account.disconnectReason || ""; +} + +function badge(status: Account["status"]): HTMLElement { + const glyph = status === "healthy" ? CircleCheck : status === "warning" ? AlertTriangle : CircleX; + return h("span", { class: `badge badge-${status}` }, icon(glyph, "icon icon-sm"), COPY.status[status] ?? status); +} + +function accountRow(env: HomeEnv, account: Account): HTMLElement { + const issue = issueOf(account); + return h( + "li", + { class: "row" }, + h( + "div", + { class: "row-main" }, + h( + "div", + { class: "row-title" }, + platformName(account.platform), + h("span", { class: "muted" }, account.username ? `@${account.username}` : account.displayName ?? ""), + ), + issue ? h("div", { class: "row-sub" }, issue) : null, + ), + badge(account.status), + account.status !== "healthy" + ? h( + "button", + { class: "btn btn-ghost btn-icon", attrs: { "aria-label": `${COPY.askClaude}: ${account.username ?? account.accountId}`, title: COPY.askClaude }, on: { click: () => env.ask(account) } }, + icon(SendHorizontal), + ) + : null, + ); +} + +export function homeView(env: HomeEnv): HTMLElement { + const { state } = env; + const summary = state.health?.summary ?? {}; + const accounts = [...(state.health?.accounts ?? [])].sort((a, b) => RANK[a.status] - RANK[b.status]); + const attention = accounts.filter((a) => a.status !== "healthy"); + const needAttention = (summary.warning ?? 0) + (summary.error ?? 0); + const listed = env.compact ? attention.slice(0, 3) : accounts; + + const stat = (label: string, value: string, tone = "") => + h("div", { class: `stat ${tone}` }, h("div", { class: "eyebrow" }, label), h("div", { class: "stat-value" }, value)); + + return h( + "div", + { class: "home" }, + h( + "div", + { class: "stats" }, + stat(COPY.stats.accounts, count(summary.total, env.locale)), + stat(COPY.stats.attention, count(needAttention, env.locale), needAttention ? "stat-warn" : ""), + stat(COPY.stats.failed, count(state.failedPosts, env.locale), state.failedPosts ? "stat-error" : ""), + ), + h( + "section", + { class: "section" }, + h("div", { class: "eyebrow" }, env.compact ? COPY.attentionTitle : COPY.accountsTitle), + listed.length + ? h("ul", { class: "list" }, listed.map((a) => accountRow(env, a))) + : h("p", { class: "empty" }, icon(CircleCheck), COPY.allHealthy), + ), + h( + "div", + { class: "actions" }, + env.canExpand + ? h("button", { class: "btn btn-primary", on: { click: env.expand } }, icon(Maximize2), COPY.open) + : null, + summary.needsReconnect + ? h("button", { class: "btn", on: { click: env.reconnect } }, COPY.reconnect) + : null, + h( + "button", + { class: "btn btn-ghost btn-icon", attrs: { "aria-label": COPY.refresh, title: COPY.refresh, disabled: state.phase === "loading" }, on: { click: env.refresh } }, + icon(RefreshCw, state.phase === "loading" ? "icon spin" : "icon"), + ), + ), + ); +} diff --git a/apps-src/src/views/shell.ts b/apps-src/src/views/shell.ts new file mode 100644 index 00000000..b7c0cd5b --- /dev/null +++ b/apps-src/src/views/shell.ts @@ -0,0 +1,34 @@ +/** The frame around every screen: brand header, progress line, feedback, body. */ +import { COPY } from "../copy"; +import { h, type Child } from "../dom"; +import type { AppState } from "../model"; + +export function skeleton(): HTMLElement { + return h( + "div", + { class: "skeleton", attrs: { "aria-busy": "true", "aria-label": "Loading" } }, + h("i", { attrs: { style: "width: 100%" } }), + h("i", { attrs: { style: "width: 80%" } }), + h("i", { attrs: { style: "width: 60%" } }), + ); +} + +export function shell(state: AppState, body: Child): HTMLElement { + return h( + "main", + { class: "app" }, + h( + "header", + { class: "header" }, + h("span", { class: "mark", attrs: { "aria-hidden": "true" } }), + h("span", { class: "brand" }, COPY.brand), + h("span", { class: "title" }, COPY.title), + ), + state.phase === "loading" ? h("div", { class: "progress", attrs: { role: "progressbar", "aria-label": "Refreshing" } }) : null, + state.feedback + ? h("div", { class: `notice notice-${state.feedback.tone}`, attrs: { role: state.feedback.tone === "error" ? "alert" : "status" } }, state.feedback.text) + : null, + state.error ? h("div", { class: "notice notice-error", attrs: { role: "alert" } }, state.error) : null, + body, + ); +} diff --git a/apps-src/tsconfig.json b/apps-src/tsconfig.json new file mode 100644 index 00000000..63f04a15 --- /dev/null +++ b/apps-src/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "esnext", + "moduleResolution": "bundler", + "lib": ["es2022", "dom", "dom.iterable"], + "types": ["vite/client"], + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/apps-src/vite.config.ts b/apps-src/vite.config.ts new file mode 100644 index 00000000..5c34b5f8 --- /dev/null +++ b/apps-src/vite.config.ts @@ -0,0 +1,15 @@ +// Builds the app into one self-contained HTML file (scripts and styles +// inlined), the shape an MCP Apps ui:// resource needs: the host reviews the +// whole document and nothing loads from a CDN. +import { defineConfig } from "vite"; +import { viteSingleFile } from "vite-plugin-singlefile"; + +export default defineConfig({ + plugins: [viteSingleFile()], + build: { + outDir: "../src/late/mcp/apps/bundle", + emptyOutDir: true, + target: "es2022", + rollupOptions: { input: "app.html" }, + }, +}); diff --git a/src/late/mcp/apps/__init__.py b/src/late/mcp/apps/__init__.py index 4f840fb1..96f3f8e1 100644 --- a/src/late/mcp/apps/__init__.py +++ b/src/late/mcp/apps/__init__.py @@ -18,6 +18,7 @@ from fastmcp.apps import UI_MIME_TYPE, AppConfig, ResourceCSP, app_config_to_meta_dict from fastmcp.resources import TextResource +from fastmcp.tools import ToolResult from mcp.types import ToolAnnotations from .tools import register_tools @@ -51,6 +52,7 @@ # Listed up front while the trial is on. The ui_* tools are app-only: listed # so the host lets the views call them, hidden from the model by the host. APP_TOOLS = [ + "zernio_open_app", "show_post_preview", "show_failed_posts", "show_analytics", @@ -95,6 +97,50 @@ def register_apps(mcp: FastMCP) -> None: ) register_tools(mcp, view_uri) _replace_overview(mcp) + _register_app(mcp) + + +# The routed app, built from apps-src/ (Vite + TypeScript + the ext-apps SDK) +# into bundle/app.html, committed so the Python image needs no Node. It loads +# its own data through the server's tools, so the opening tool only says which +# screen to show. +APP_URI = f"ui://zernio/{_VERSION}/app.html" + + +def _register_app(mcp: FastMCP) -> None: + mcp.add_resource( + TextResource( + uri=APP_URI, + name="Zernio", + mime_type=UI_MIME_TYPE, + text=(_DIR / "bundle" / "app.html").read_text(encoding="utf-8"), + # The app draws its own frame. + meta={"ui": app_config_to_meta_dict(AppConfig(csp=_CSP, prefers_border=False))}, + ) + ) + + @mcp.tool( + name="zernio_open_app", + title="Open Zernio", + description=( + "Open the Zernio app in the chat: the workspace at a glance (connected " + "accounts, the ones that need attention, failed posts), with a button to " + "open it full screen. Use it when the user wants to see their Zernio " + "workspace or check on their accounts." + ), + annotations=ToolAnnotations( + title="Open Zernio", readOnlyHint=True, destructiveHint=False, openWorldHint=False + ), + app=AppConfig(resource_uri=APP_URI), + # Lists the app on Claude's Artifacts page, where people open and pin it + # without asking Claude (custom and Verified connectors only). + meta={"openai/ui": {"entrypoints": [{"type": "global"}]}}, + ) + def zernio_open_app() -> ToolResult: + return ToolResult( + content="Opened the Zernio app. The user sees it and can act there; do not repeat its contents as text.", + structured_content={"view": "home"}, + ) def _replace_overview(mcp: FastMCP) -> None: diff --git a/src/late/mcp/apps/bundle/app.html b/src/late/mcp/apps/bundle/app.html new file mode 100644 index 00000000..b3d13e6c --- /dev/null +++ b/src/late/mcp/apps/bundle/app.html @@ -0,0 +1,115 @@ + + + + + + + Zernio + + + + +
+ + From cefe04b60ecd4eefb59b94ff95ec195f3a7fb94a Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Wed, 18 Nov 2026 15:31:59 +0100 Subject: [PATCH 04/11] feat(mcp): Zernio app on React and the dashboard's design system v2 Rebuilt on the ext-apps SDK's React pattern (useApp, useHostStyles, as in its basic-server-react example) instead of beel-mcp's structure, and drawn in the dashboard's product look (data-look="v2"): the Theme, Scale and type/* values of Schedule-Posts-API's new-look.ts, Geist, Geist Mono and Geist Pixel Square, pixelarticons, platform app icons from zernio.com, square panels with a grey eyebrow bar, KPIs on one row divided by hairlines, StatusPill with its reason behind the info mark, the fix as an outline button in the row, notices as coloured text and the pixel-rain spinner. MCP Apps take fonts only from declared origins, so the server serves the three woff2 files at /apps/fonts/ (CORS *) and fills its own MCP_PUBLIC_URL into the bundle and into the resource's CSP, with zernio.com for the icons. Co-Authored-By: Claude Opus 5.5 --- apps-src/{app.html => mcp-app.html} | 2 +- apps-src/package-lock.json | 108 ++++++++++++++++- apps-src/package.json | 7 +- apps-src/src/Home.tsx | 148 +++++++++++++++++++++++ apps-src/src/api.ts | 61 ++++++++++ apps-src/src/client.ts | 41 ------- apps-src/src/copy.ts | 21 ---- apps-src/src/dom.ts | 42 ------- apps-src/src/format.ts | 19 --- apps-src/src/global.css | 126 +++++++++++++++++++ apps-src/src/main.ts | 113 ------------------ apps-src/src/mcp-app.tsx | 75 ++++++++++++ apps-src/src/model.ts | 34 ------ apps-src/src/store.ts | 24 ---- apps-src/src/styles.css | 166 -------------------------- apps-src/src/views/home.ts | 108 ----------------- apps-src/src/views/shell.ts | 34 ------ apps-src/tsconfig.json | 18 ++- apps-src/vite.config.ts | 10 +- src/late/mcp/apps/__init__.py | 9 +- src/late/mcp/apps/bundle/app.html | 115 ------------------ src/late/mcp/apps/bundle/mcp-app.html | 123 +++++++++++++++++++ 22 files changed, 666 insertions(+), 738 deletions(-) rename apps-src/{app.html => mcp-app.html} (83%) create mode 100644 apps-src/src/Home.tsx create mode 100644 apps-src/src/api.ts delete mode 100644 apps-src/src/client.ts delete mode 100644 apps-src/src/copy.ts delete mode 100644 apps-src/src/dom.ts delete mode 100644 apps-src/src/format.ts create mode 100644 apps-src/src/global.css delete mode 100644 apps-src/src/main.ts create mode 100644 apps-src/src/mcp-app.tsx delete mode 100644 apps-src/src/model.ts delete mode 100644 apps-src/src/store.ts delete mode 100644 apps-src/src/styles.css delete mode 100644 apps-src/src/views/home.ts delete mode 100644 apps-src/src/views/shell.ts delete mode 100644 src/late/mcp/apps/bundle/app.html create mode 100644 src/late/mcp/apps/bundle/mcp-app.html diff --git a/apps-src/app.html b/apps-src/mcp-app.html similarity index 83% rename from apps-src/app.html rename to apps-src/mcp-app.html index ba3b664a..3a911ef0 100644 --- a/apps-src/app.html +++ b/apps-src/mcp-app.html @@ -8,6 +8,6 @@
- + diff --git a/apps-src/package-lock.json b/apps-src/package-lock.json index 0058ffee..a06cc19c 100644 --- a/apps-src/package-lock.json +++ b/apps-src/package-lock.json @@ -9,10 +9,15 @@ "@modelcontextprotocol/client": "2.4.0", "@modelcontextprotocol/core": "2.4.0", "@modelcontextprotocol/ext-apps": "2.0.4", - "lucide": "1.75.0", + "lucide-react": "1.75.0", + "react": "19.3.1", + "react-dom": "19.3.1", "zod": "4.6.7" }, "devDependencies": { + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "6.3.0", "typescript": "7.0.2", "vite": "8.3.8", "vite-plugin-singlefile": "2.3.4" @@ -464,6 +469,26 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.3.0" + } + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -804,6 +829,36 @@ "node": ">=16.20.0" } }, + "node_modules/@vitejs/plugin-react": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz", + "integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": ">=0.152.0 <0.157.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -818,6 +873,13 @@ "node": ">= 8" } }, + "node_modules/csstype": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", + "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", + "devOptional": true, + "license": "MIT" + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1170,11 +1232,20 @@ "url": "https://opencollective.com/parcel" } }, - "node_modules/lucide": { + "node_modules/lucide-react": { "version": "1.75.0", - "resolved": "https://registry.npmjs.org/lucide/-/lucide-1.75.0.tgz", - "integrity": "sha512-WNKnvz1XU6pcNuldOVx6gQx755isQcx8wWnIq8J6NNlHkqo9NJVLyTXC+0cizbdYEwROBSp/PXpMNqwf3d85XA==", - "license": "ISC" + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.75.0.tgz", + "integrity": "sha512-piesXAZIXru9d5lHBoM6cPHOBs5+QkMx+3EXwG3xWJ7qdViuz92JtYN0u9jMB6jt+2WbQrwhvJGdMwGnL3EOfA==", + "license": "ISC", + "peerDependencies": { + "@types/react": "*", + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } }, "node_modules/nanoid": { "version": "3.3.20", @@ -1262,6 +1333,27 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz", + "integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.1" + } + }, "node_modules/rolldown": { "version": "1.2.19", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", @@ -1297,6 +1389,12 @@ "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/apps-src/package.json b/apps-src/package.json index a59033ad..2bc00e69 100644 --- a/apps-src/package.json +++ b/apps-src/package.json @@ -12,10 +12,15 @@ "@modelcontextprotocol/client": "2.4.0", "@modelcontextprotocol/core": "2.4.0", "@modelcontextprotocol/ext-apps": "2.0.4", - "lucide": "1.75.0", + "lucide-react": "1.75.0", + "react": "19.3.1", + "react-dom": "19.3.1", "zod": "4.6.7" }, "devDependencies": { + "@types/react": "19.3.0", + "@types/react-dom": "19.3.0", + "@vitejs/plugin-react": "6.3.0", "typescript": "7.0.2", "vite": "8.3.8", "vite-plugin-singlefile": "2.3.4" diff --git a/apps-src/src/Home.tsx b/apps-src/src/Home.tsx new file mode 100644 index 00000000..07873c3c --- /dev/null +++ b/apps-src/src/Home.tsx @@ -0,0 +1,148 @@ +/** + * Home: the workspace at a glance. Inline it is a compact card (three + * numbers, up to three accounts that need attention, Open Zernio); full + * screen it lists every account. + */ +import type { App } from "@modelcontextprotocol/ext-apps"; +import { CircleAlert, CircleCheck, Maximize2, RefreshCw, SendHorizontal } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; +import { type Account, type AccountsHealth, getAccountsHealth, getFailedPostCount, platformName } from "./api"; + +interface Props { + app: App; + fullscreen: boolean; + canExpand: boolean; + locale?: string; +} + +const RANK = { error: 0, warning: 1, healthy: 2 } as const; + +export function Home({ app, fullscreen, canExpand, locale }: Props) { + const [health, setHealth] = useState(); + const [failed, setFailed] = useState(); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(); + const [notice, setNotice] = useState(); + + const load = useCallback(async () => { + setLoading(true); + const [h, f] = await Promise.allSettled([getAccountsHealth(app), getFailedPostCount(app)]); + if (h.status === "fulfilled") setHealth(h.value); + setError(h.status === "rejected" ? String(h.reason) : undefined); + setFailed(f.status === "fulfilled" ? f.value : undefined); + if (f.status === "rejected") console.warn("[zernio] failed posts unavailable:", f.reason); + setLoading(false); + }, [app]); + + useEffect(() => { + void load(); + }, [load]); + + const accounts = [...(health?.accounts ?? [])].sort((a, b) => RANK[a.status] - RANK[b.status]); + const attention = accounts.filter((a) => a.status !== "healthy"); + const summary = health?.summary ?? {}; + + // Tell Claude what the panel shows, so "these accounts" resolves to them. + useEffect(() => { + if (!health || !app.getHostCapabilities()?.updateModelContext) return; + const names = attention.map((a) => `${a.platform} @${a.username ?? a.accountId}`).join(", "); + void app.updateModelContext({ + content: [{ + type: "text", + text: `The Zernio panel shows ${summary.total ?? 0} accounts, ${attention.length} needing attention${names ? ` (${names})` : ""}${failed !== undefined ? `, and ${failed} failed posts` : ""}.`, + }], + }); + }, [app, health, failed]); + + const ask = async (account: Account) => { + const issue = account.issues?.[0] || account.disconnectReason || account.status; + const { isError } = await app.sendMessage({ + role: "user", + content: [{ type: "text", text: `My ${platformName(account.platform)} account @${account.username ?? account.accountId} (account_id ${account.accountId}) shows "${issue}" in Zernio. Help me fix it.` }], + }); + setNotice(isError ? "Could not send it to Claude." : "Sent to Claude. Continue in the chat."); + }; + + const fmt = (n?: number) => (n === undefined ? "—" : new Intl.NumberFormat(locale).format(n)); + const listed = fullscreen ? accounts : attention.slice(0, 3); + const needAttention = (summary.warning ?? 0) + (summary.error ?? 0); + + return ( + <> + {loading && health &&
} + {error &&

Could not load your workspace. {error}

} + {notice &&

{notice}

} + +
+ + + +
+ +
+

{fullscreen ? "All accounts" : "Need attention"}

+ {listed.length ? ( +
    + {listed.map((a) => ( + void ask(a)} /> + ))} +
+ ) : ( +

Every account can post.

+ )} +
+ +
+ {canExpand && ( + // requestDisplayMode must run inside the click: the host refuses it otherwise. + + )} + {!!summary.needsReconnect && ( + + )} + +
+ + ); +} + +function Stat({ label, value, tone }: { label: string; value: string; tone?: "warning" | "error" }) { + return ( +
+
{label}
+
{value}
+
+ ); +} + +function AccountRow({ account, onAsk }: { account: Account; onAsk: () => void }) { + const issue = account.needsReconnect + ? account.disconnectReason || "Needs to be reconnected" + : account.issues?.[0] || account.disconnectReason || ""; + const label = { healthy: "Healthy", warning: "Warning", error: "Error" }[account.status]; + return ( +
  • +
    +
    + {platformName(account.platform)} {account.username ? `@${account.username}` : account.displayName} +
    + {issue &&
    {issue}
    } +
    + + {account.status === "healthy" ? : } + {label} + + {account.status !== "healthy" && ( + + )} +
  • + ); +} diff --git a/apps-src/src/api.ts b/apps-src/src/api.ts new file mode 100644 index 00000000..1a62d1d5 --- /dev/null +++ b/apps-src/src/api.ts @@ -0,0 +1,61 @@ +/** + * The app reads its data through the server's ordinary tools + * (app.callServerTool), so the user's scopes and the API's validation apply + * as they do for Claude. Generated tools return compact JSON as their text. + */ +import type { App } from "@modelcontextprotocol/ext-apps"; + +export interface Account { + accountId: string; + platform: string; + username?: string; + displayName?: string; + status: "healthy" | "warning" | "error"; + needsReconnect?: boolean; + issues?: string[]; + disconnectReason?: string | null; +} + +export interface AccountsHealth { + summary?: { total?: number; healthy?: number; warning?: number; error?: number; needsReconnect?: number }; + accounts?: Account[]; +} + +async function callJson(app: App, name: string, args: Record = {}): Promise { + const result = await app.callServerTool({ name, arguments: args }); + const text = result.content + .map((block) => (block.type === "text" ? block.text : "")) + .join(""); + if (result.isError) throw new Error(text || `${name} failed`); + return JSON.parse(text) as T; +} + +export function getAccountsHealth(app: App): Promise { + return callJson(app, "accounts_get_all_accounts_health"); +} + +/** + * How many posts failed. posts_list_posts is not listed up front (it sits + * behind search_tools), so this also shows whether the host lets an app call + * a tool it never received in tools/list. + */ +export async function getFailedPostCount(app: App): Promise { + const page = await callJson<{ posts?: unknown[]; pagination?: { total?: number } }>( + app, + "posts_list_posts", + { status: "failed", limit: 1 }, + ); + return page.pagination?.total ?? page.posts?.length ?? 0; +} + +const PLATFORMS: Record = { + twitter: "X", instagram: "Instagram", facebook: "Facebook", linkedin: "LinkedIn", + tiktok: "TikTok", youtube: "YouTube", threads: "Threads", pinterest: "Pinterest", + reddit: "Reddit", bluesky: "Bluesky", googlebusiness: "Google Business", + telegram: "Telegram", snapchat: "Snapchat", discord: "Discord", slack: "Slack", + whatsapp: "WhatsApp", +}; + +export function platformName(platform: string): string { + return PLATFORMS[platform] ?? platform; +} diff --git a/apps-src/src/client.ts b/apps-src/src/client.ts deleted file mode 100644 index ef8deaf8..00000000 --- a/apps-src/src/client.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * The app's data, read through the server's ordinary tools (callServerTool), - * so the API's validation and the user's scopes apply as they do for Claude. - * Generated tools return compact JSON as their text. - */ -import type { App } from "@modelcontextprotocol/ext-apps"; -import type { AccountsHealth } from "./model"; - -export type CallToolResult = Awaited>; -export type CallTool = (name: string, args: Record) => Promise; - -export class ToolError extends Error {} - -function json(result: CallToolResult): T { - const text = result.content - .filter((block) => block.type === "text") - .map((block) => (block as { text: string }).text) - .join(""); - if (result.isError) throw new ToolError(text || "The tool call failed."); - return JSON.parse(text) as T; -} - -export class ZernioClient { - constructor(private call: CallTool) {} - - async health(): Promise { - return json(await this.call("accounts_get_all_accounts_health", {})); - } - - /** - * How many posts failed. posts_list_posts is not listed up front (it sits - * behind search_tools), so this also tests whether the host lets an app - * call a tool it never received in tools/list. - */ - async failedPosts(): Promise { - const page = json<{ posts?: unknown[]; pagination?: { total?: number } }>( - await this.call("posts_list_posts", { status: "failed", limit: 1 }), - ); - return page.pagination?.total ?? page.posts?.length ?? 0; - } -} diff --git a/apps-src/src/copy.ts b/apps-src/src/copy.ts deleted file mode 100644 index d964d8c8..00000000 --- a/apps-src/src/copy.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** Every user-facing string, in one place. */ -export const COPY = { - brand: "Zernio", - title: "Workspace", - stats: { - accounts: "Accounts", - attention: "Need attention", - failed: "Failed posts", - }, - allHealthy: "Every account can post.", - attentionTitle: "Accounts that need attention", - accountsTitle: "All accounts", - open: "Open Zernio", - refresh: "Refresh", - reconnect: "Reconnect in Zernio", - askClaude: "Ask Claude to fix", - unavailable: "—", - loadFailed: "Could not load your workspace.", - sentToClaude: "Sent to Claude. Continue in the chat.", - status: { healthy: "Healthy", warning: "Warning", error: "Error" } as Record, -}; diff --git a/apps-src/src/dom.ts b/apps-src/src/dom.ts deleted file mode 100644 index 30c4fb61..00000000 --- a/apps-src/src/dom.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** - * A minimal element builder. Text always goes in as text nodes, so nothing an - * API returns can become markup: there is no innerHTML anywhere in the app. - */ -import { createElement, type IconNode } from "lucide"; - -export type Child = Node | string | false | null | undefined; - -type Handlers = { [K in keyof HTMLElementEventMap]?: (event: HTMLElementEventMap[K]) => void }; - -interface Props { - class?: string; - /** Attributes; `false` and `undefined` leave one out, `true` sets it empty. */ - attrs?: Record; - on?: Handlers; -} - -export function h( - tag: K, - props: Props = {}, - ...children: Array -): HTMLElementTagNameMap[K] { - const el = document.createElement(tag); - if (props.class) el.className = props.class; - for (const [name, value] of Object.entries(props.attrs ?? {})) { - if (value === undefined || value === false) continue; - el.setAttribute(name, value === true ? "" : String(value)); - } - for (const [type, handler] of Object.entries(props.on ?? {})) { - el.addEventListener(type, handler as EventListener); - } - for (const child of children.flat()) { - if (child === null || child === undefined || child === false) continue; - el.appendChild(typeof child === "string" ? document.createTextNode(child) : child); - } - return el; -} - -/** A Lucide icon, sized by CSS and hidden from screen readers. */ -export function icon(node: IconNode, className = "icon"): SVGElement { - return createElement(node, { class: className, "aria-hidden": "true" }); -} diff --git a/apps-src/src/format.ts b/apps-src/src/format.ts deleted file mode 100644 index d5f83498..00000000 --- a/apps-src/src/format.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** Number and name formatting. Missing values read "—". */ -import { COPY } from "./copy"; - -const PLATFORMS: Record = { - twitter: "X", instagram: "Instagram", facebook: "Facebook", linkedin: "LinkedIn", - tiktok: "TikTok", youtube: "YouTube", threads: "Threads", pinterest: "Pinterest", - reddit: "Reddit", bluesky: "Bluesky", googlebusiness: "Google Business", - telegram: "Telegram", snapchat: "Snapchat", discord: "Discord", slack: "Slack", - whatsapp: "WhatsApp", -}; - -export function platformName(platform: string | undefined): string { - return (platform && PLATFORMS[platform]) || platform || COPY.unavailable; -} - -export function count(value: number | undefined, locale?: string): string { - if (value === undefined) return COPY.unavailable; - return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(value); -} diff --git a/apps-src/src/global.css b/apps-src/src/global.css new file mode 100644 index 00000000..54c38830 --- /dev/null +++ b/apps-src/src/global.css @@ -0,0 +1,126 @@ +/* + * As in the ext-apps examples: the host's style variables drive structure + * (text, borders, surfaces, fonts, radii) and useHostStyles applies them; the + * values below are fallbacks, taken from zernio.com, for a host that sends + * none. Zernio's own identity is the accent and the mono labels. + */ +:root { + color-scheme: light dark; + + --color-text-primary: light-dark(#1a1a1a, #fafafa); + --color-text-secondary: light-dark(#525252, #d4d4d4); + --color-text-tertiary: light-dark(#6b6b6b, #a3a3a3); + --color-text-success: light-dark(#15803d, #4ade80); + --color-text-warning: light-dark(#b45309, #fbbf24); + --color-text-danger: light-dark(#c0260f, #f87171); + --color-background-secondary: light-dark(#faf9f7, #151516); + --color-background-success: light-dark(#ecfdf3, rgb(74 222 128 / 0.1)); + --color-background-warning: light-dark(#fffbeb, rgb(251 191 36 / 0.1)); + --color-background-danger: light-dark(#fef2f0, rgb(248 113 113 / 0.1)); + --color-border-primary: light-dark(#e4e4e4, rgb(255 255 255 / 0.14)); + --color-border-secondary: light-dark(#f2f2f2, rgb(255 255 255 / 0.08)); + --border-radius-sm: 4px; + --border-radius-md: 6px; + --font-sans: "Geist", ui-sans-serif, system-ui, sans-serif; + --font-mono: "Geist Mono", ui-monospace, Menlo, Consolas, monospace; + + /* Zernio */ + --color-accent: #eb3514; + --color-accent-hover: #d22e0e; + --color-text-on-accent: #ffffff; +} +:root[data-theme="light"] { color-scheme: light; } +:root[data-theme="dark"] { color-scheme: dark; } + +* { box-sizing: border-box; } +html, body { margin: 0; background: transparent; } +body { + font: 400 14px/20px var(--font-sans); + color: var(--color-text-primary); + -webkit-font-smoothing: antialiased; +} +button { font: inherit; color: inherit; } +:focus-visible { outline: 2px solid var(--color-accent); outline-offset: 2px; } + +.app { position: relative; padding: 4px 2px 8px; } +.app-fullscreen { max-width: 960px; margin: 0 auto; padding: 20px 16px 112px; } + +.header { display: flex; align-items: center; gap: 8px; margin-bottom: 14px; } +.mark { width: 14px; height: 14px; border-radius: 3px; background: var(--color-accent); } +.brand { font-weight: 600; } + +.eyebrow { + margin: 0; + font: 500 10.5px/14px var(--font-mono); + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--color-text-tertiary); +} +.muted { color: var(--color-text-tertiary); font-weight: 400; } + +.stats { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + border: 1px solid var(--color-border-primary); + border-radius: var(--border-radius-md); +} +.stat { padding: 12px 14px; } +.stat + .stat { border-left: 1px solid var(--color-border-primary); } +.stat-value { margin-top: 6px; font: 500 22px/28px var(--font-mono); font-variant-numeric: tabular-nums; } +.stat-warning .stat-value { color: var(--color-text-warning); } +.stat-error .stat-value { color: var(--color-text-danger); } + +.section { margin-top: 20px; } +.list { list-style: none; margin: 6px 0 0; padding: 0; } +.row { display: flex; align-items: center; gap: 10px; padding: 10px 0; } +.row + .row { border-top: 1px solid var(--color-border-secondary); } +.row-main { flex: 1; min-width: 0; } +.row-title { font-weight: 500; } +.row-sub { font-size: 13px; color: var(--color-text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.empty { display: flex; align-items: center; gap: 8px; margin: 8px 0 0; color: var(--color-text-secondary); } +.empty svg { color: var(--color-text-success); } + +.badge { + display: inline-flex; align-items: center; gap: 4px; + height: 24px; padding: 0 8px; + border-radius: var(--border-radius-sm); + font-size: 12px; font-weight: 500; white-space: nowrap; +} +.badge-healthy { color: var(--color-text-success); background: var(--color-background-success); } +.badge-warning { color: var(--color-text-warning); background: var(--color-background-warning); } +.badge-error { color: var(--color-text-danger); background: var(--color-background-danger); } + +.actions { display: flex; align-items: center; gap: 8px; margin-top: 18px; } +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: 6px; + height: 32px; padding: 0 12px; + border: 1px solid var(--color-border-primary); + border-radius: var(--border-radius-sm); + background: transparent; + font-size: 13px; font-weight: 500; cursor: pointer; +} +.btn:hover { background: var(--color-background-secondary); } +.btn:disabled { opacity: 0.5; cursor: default; } +.btn-primary { background: var(--color-accent); border-color: var(--color-accent); color: var(--color-text-on-accent); } +.btn-primary:hover { background: var(--color-accent-hover); border-color: var(--color-accent-hover); } +.btn-ghost { border-color: transparent; } +.btn-icon { width: 32px; padding: 0; } +.actions .btn-icon { margin-left: auto; } + +.notice { margin: 0 0 12px; padding: 8px 12px; border-radius: var(--border-radius-sm); font-size: 13px; background: var(--color-background-secondary); } +.notice-error { color: var(--color-text-danger); background: var(--color-background-danger); } + +.progress { + position: absolute; top: 0; left: 0; right: 0; height: 2px; + background: linear-gradient(90deg, transparent, var(--color-accent), transparent) 0 0 / 40% 100% no-repeat; + animation: progress 1.2s ease-in-out infinite; +} +.skeleton { display: grid; gap: 10px; padding: 8px 2px; } +.skeleton i { display: block; height: 14px; border-radius: 2px; background: var(--color-border-secondary); animation: pulse 1.4s ease-in-out infinite; } +.spin { animation: spin 1s linear infinite; } + +@keyframes spin { to { transform: rotate(360deg); } } +@keyframes progress { from { background-position: -40% 0; } to { background-position: 140% 0; } } +@keyframes pulse { 50% { opacity: 0.5; } } +@media (prefers-reduced-motion: reduce) { * { animation: none !important; } } +@media (max-width: 420px) { .stat { padding: 10px; } .stat-value { font-size: 18px; } } diff --git a/apps-src/src/main.ts b/apps-src/src/main.ts deleted file mode 100644 index 1026d1a1..00000000 --- a/apps-src/src/main.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * The Zernio MCP App: entry point. Wires the host connection (the official - * ext-apps SDK) to the store, loads the workspace through the server's tools, - * and renders. Opened by the zernio_open_app tool. - */ -import { - App, - applyDocumentTheme, - applyHostFonts, - applyHostStyleVariables, - type McpUiHostContext, -} from "@modelcontextprotocol/ext-apps"; -import { ZernioClient } from "./client"; -import { COPY } from "./copy"; -import { INITIAL_STATE, type Account, type AppState } from "./model"; -import { Store } from "./store"; -import { homeView } from "./views/home"; -import { shell, skeleton } from "./views/shell"; -import "./styles.css"; - -const app = new App({ name: "Zernio", version: "0.1.0" }, { availableDisplayModes: ["inline", "fullscreen"] }); -const client = new ZernioClient((name, args) => app.callServerTool({ name, arguments: args })); -const store = new Store(INITIAL_STATE); -const root = document.getElementById("root") as HTMLElement; - -// A response for a load the user has already replaced is dropped. -let loadSeq = 0; - -async function load(): Promise { - const seq = ++loadSeq; - store.set({ phase: store.get().health ? "loading" : "connecting", error: undefined }); - const [health, failed] = await Promise.allSettled([client.health(), client.failedPosts()]); - if (seq !== loadSeq) return; - if (failed.status === "rejected") console.warn("[zernio-app] failed posts unavailable:", failed.reason); - store.set({ - phase: "ready", - health: health.status === "fulfilled" ? health.value : store.get().health, - failedPosts: failed.status === "fulfilled" ? failed.value : undefined, - error: health.status === "rejected" ? `${COPY.loadFailed} ${String((health.reason as Error).message ?? "")}` : undefined, - }); - void tellModel(); -} - -/** Tells Claude what the panel shows, so "these accounts" resolves to them. */ -async function tellModel(): Promise { - if (!app.getHostCapabilities()?.updateModelContext) return; - const { health, failedPosts } = store.get(); - const attention = (health?.accounts ?? []).filter((a) => a.status !== "healthy"); - const text = - `The Zernio panel shows the workspace: ${health?.summary?.total ?? 0} accounts, ` + - `${attention.length} needing attention` + - (attention.length ? ` (${attention.map((a) => `${a.platform} @${a.username ?? a.accountId}`).join(", ")})` : "") + - (failedPosts !== undefined ? `, ${failedPosts} failed posts.` : "."); - await app.updateModelContext({ - content: [{ type: "text", text }], - structuredContent: { view: "home", attention: attention.map((a) => a.accountId), failedPosts }, - }); -} - -async function ask(account: Account): Promise { - const issue = account.issues?.[0] || account.disconnectReason || account.status; - const result = await app.sendMessage({ - role: "user", - content: [{ type: "text", text: `My ${account.platform} account @${account.username ?? account.accountId} (account_id ${account.accountId}) shows "${issue}" in Zernio. Help me fix it.` }], - }); - store.set({ feedback: result.isError ? { tone: "error", text: "Could not send it to Claude." } : { tone: "ok", text: COPY.sentToClaude } }); -} - -function render(state: AppState): void { - const ctx = app.getHostContext(); - const canExpand = ctx?.displayMode !== "fullscreen" && !!ctx?.availableDisplayModes?.includes("fullscreen"); - const body = - state.phase === "connecting" - ? skeleton() - : homeView({ - state, - compact: ctx?.displayMode !== "fullscreen", - canExpand, - locale: ctx?.locale, - expand: () => void app.requestDisplayMode({ mode: "fullscreen" }).catch(() => undefined), - refresh: () => void load(), - reconnect: () => void app.openLink({ url: "https://zernio.com/dashboard" }), - ask: (account) => void ask(account), - }); - root.replaceChildren(shell(state, body)); -} - -function applyHostContext(ctx: McpUiHostContext): void { - if (ctx.theme) applyDocumentTheme(ctx.theme); - // Host tokens only set the page surface; the brand tokens are prefixed and - // never overridden by them. - if (ctx.styles?.variables) applyHostStyleVariables(ctx.styles.variables); - if (ctx.styles?.css?.fonts) applyHostFonts(ctx.styles.css.fonts); - const doc = document.documentElement; - doc.dataset.display = ctx.displayMode ?? "inline"; - doc.style.setProperty("--safe-bottom", `${ctx.safeAreaInsets?.bottom ?? 0}px`); - render(store.get()); -} - -// Handlers are registered before connect(): the host may send the tool result -// as soon as the handshake completes. -app.onerror = (err) => console.error("[zernio-app]", err); -app.onhostcontextchanged = applyHostContext; -app.ontoolresult = () => void load(); -app.ontoolcancelled = () => store.set({ phase: "ready", error: "Cancelled." }); - -store.subscribe(render); -render(store.get()); - -void app.connect().then(() => { - const ctx = app.getHostContext(); - if (ctx) applyHostContext(ctx); -}); diff --git a/apps-src/src/mcp-app.tsx b/apps-src/src/mcp-app.tsx new file mode 100644 index 00000000..0f7f305f --- /dev/null +++ b/apps-src/src/mcp-app.tsx @@ -0,0 +1,75 @@ +/** + * The Zernio MCP App, on the ext-apps React hooks (the pattern of the SDK's + * basic-server-react example). Opened by the zernio_open_app tool. + */ +import type { App, McpUiHostContext } from "@modelcontextprotocol/ext-apps"; +import { useApp, useHostStyles } from "@modelcontextprotocol/ext-apps/react"; +import { StrictMode, useEffect, useState } from "react"; +import { createRoot } from "react-dom/client"; +import { Home } from "./Home"; +import "./global.css"; + +function ZernioApp() { + const [hostContext, setHostContext] = useState(); + const [opened, setOpened] = useState(false); + + // useApp creates the App, lets us register handlers, then connects. + const { app, error } = useApp({ + appInfo: { name: "Zernio", version: "0.1.0" }, + capabilities: { availableDisplayModes: ["inline", "fullscreen"] }, + onAppCreated: (app) => { + app.ontoolresult = () => setOpened(true); + app.onhostcontextchanged = (params) => setHostContext((prev) => ({ ...prev, ...params })); + app.onerror = console.error; + }, + }); + + // Theme, host CSS variables and host fonts, kept in sync with the host. + useHostStyles(app, app?.getHostContext()); + + useEffect(() => { + if (app) setHostContext(app.getHostContext()); + }, [app]); + + if (error) return

    {error.message}

    ; + if (!app || !opened) return ; + return ; +} + +function Shell({ app, hostContext }: { app: App; hostContext?: McpUiHostContext }) { + const fullscreen = hostContext?.displayMode === "fullscreen"; + const insets = hostContext?.safeAreaInsets; + return ( +
    +
    +
    + +
    + ); +} + +function Skeleton() { + return ( +
    + + + +
    + ); +} + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/apps-src/src/model.ts b/apps-src/src/model.ts deleted file mode 100644 index 2e61c13b..00000000 --- a/apps-src/src/model.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** The app's state and the shapes of the API data it shows. */ - -export interface Account { - accountId: string; - platform: string; - username?: string; - displayName?: string; - status: "healthy" | "warning" | "error"; - needsReconnect?: boolean; - issues?: string[]; - disconnectReason?: string | null; -} - -export interface AccountsHealth { - summary?: { total?: number; healthy?: number; warning?: number; error?: number; needsReconnect?: number }; - accounts?: Account[]; -} - -export interface Feedback { - tone: "ok" | "error"; - text: string; -} - -export interface AppState { - /** connecting: no data yet (skeleton). loading: refreshing over what is shown. */ - phase: "connecting" | "loading" | "ready"; - health?: AccountsHealth; - /** undefined when the failed-posts call is not reachable from the app. */ - failedPosts?: number; - error?: string; - feedback?: Feedback; -} - -export const INITIAL_STATE: AppState = { phase: "connecting" }; diff --git a/apps-src/src/store.ts b/apps-src/src/store.ts deleted file mode 100644 index 56ea01e8..00000000 --- a/apps-src/src/store.ts +++ /dev/null @@ -1,24 +0,0 @@ -/** - * The app's state container: one object, replaced by patches, with listeners - * notified after each change. Views render from a snapshot and never write to - * it; only main.ts's loaders do. - */ -export class Store { - private listeners = new Set<(state: S) => void>(); - - constructor(private state: S) {} - - get(): S { - return this.state; - } - - set(patch: Partial): void { - this.state = { ...this.state, ...patch }; - for (const listener of this.listeners) listener(this.state); - } - - subscribe(listener: (state: S) => void): () => void { - this.listeners.add(listener); - return () => this.listeners.delete(listener); - } -} diff --git a/apps-src/src/styles.css b/apps-src/src/styles.css deleted file mode 100644 index f204ff1b..00000000 --- a/apps-src/src/styles.css +++ /dev/null @@ -1,166 +0,0 @@ -/* Zernio MCP App. Raw tokens are zernio.com's, taken from its stylesheet - (--bg-*, --text-*, --border-*, --brand-*); components read only the role - tokens below. The host's surface is the one host token used, so the panel - sits in the conversation; light/dark follows data-theme, which the SDK sets - from the host. One 4px radius, 1px hairlines, two weights, numbers in mono. */ -:root { - --z-brand: #eb3514; - --z-brand-hover: #d22e0e; - --z-brand-subtle: #fce9e4; - --z-raised: #ffffff; - --z-ink: #1a1a1a; - --z-ink-2: #525252; - --z-ink-3: #6b6b6b; - --z-line: #e4e4e4; - --z-line-subtle: #f2f2f2; - --z-hover: rgba(92, 62, 37, 0.03); - --z-ok: #15803d; - --z-ok-bg: #ecfdf3; - --z-warn: #b45309; - --z-warn-bg: #fffbeb; - --z-error: #c0260f; - --z-error-bg: #fef2f0; - --z-radius: 4px; - --z-font: "Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; - --z-mono: "Geist Mono", ui-monospace, Menlo, Consolas, monospace; - --z-ease: cubic-bezier(0.4, 0, 0.2, 1); - - /* roles */ - --page: var(--color-background-primary, #faf9f7); - --card: var(--z-raised); - --text: var(--z-ink); - --muted: var(--z-ink-3); - --line: var(--z-line); - color-scheme: light; -} -:root[data-theme="dark"] { - --z-brand-subtle: #261614; - --z-raised: #151516; - --z-ink: #fafafa; - --z-ink-2: #d4d4d4; - --z-ink-3: #a3a3a3; - --z-line: #212123; - --z-line-subtle: #1c1c1e; - --z-hover: rgba(255, 255, 255, 0.04); - --z-ok: #4ade80; - --z-ok-bg: rgba(74, 222, 128, 0.1); - --z-warn: #fbbf24; - --z-warn-bg: rgba(251, 191, 36, 0.1); - --z-error: #f87171; - --z-error-bg: rgba(248, 113, 113, 0.1); - --page: var(--color-background-primary, #0f0f10); - color-scheme: dark; -} - -* { box-sizing: border-box; } -html, body { margin: 0; background: transparent; } -body { font: 400 14px/20px var(--z-font); color: var(--text); -webkit-font-smoothing: antialiased; } -button { font: inherit; color: inherit; } -:focus-visible { outline: 2px solid var(--z-brand); outline-offset: 2px; } - -.app { - position: relative; - background: var(--card); - border: 1px solid var(--line); - border-radius: var(--z-radius); - padding: 16px; -} -:root[data-display="fullscreen"] .app { - min-height: 100vh; - border: 0; - border-radius: 0; - background: var(--page); - max-width: 960px; - margin: 0 auto; - padding: 20px 16px calc(var(--safe-bottom, 0px) + 112px); -} - -.header { display: flex; align-items: center; gap: 8px; margin-bottom: 16px; } -.mark { width: 14px; height: 14px; border-radius: 3px; background: var(--z-brand); } -.brand { font-weight: 500; } -.title { color: var(--muted); } -.title::before { content: "/"; margin-right: 8px; color: var(--line); } - -.eyebrow { - font: 500 10.5px/14px var(--z-mono); - letter-spacing: 0.08em; - text-transform: uppercase; - color: var(--muted); -} -.muted { color: var(--muted); margin-left: 6px; } - -/* The stats are one card split by hairlines, not three boxes. */ -.stats { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - border: 1px solid var(--line); - border-radius: var(--z-radius); -} -.stat { padding: 12px 14px; } -.stat + .stat { border-left: 1px solid var(--line); } -.stat-value { margin-top: 6px; font: 500 22px/28px var(--z-mono); font-variant-numeric: tabular-nums; letter-spacing: -0.02em; } -.stat-warn .stat-value { color: var(--z-warn); } -.stat-error .stat-value { color: var(--z-error); } - -.section { margin-top: 20px; } -.list { list-style: none; margin: 8px 0 0; padding: 0; } -.row { display: flex; align-items: center; gap: 12px; padding: 10px 0; } -/* Dashed divider drawn as a gradient: a dashed border changes its spacing with the box. */ -.row + .row { - background: linear-gradient(90deg, var(--line) 50%, transparent 0) top left / 6px 1px repeat-x; -} -.row-main { flex: 1; min-width: 0; } -.row-title { font-weight: 500; } -.row-sub { font-size: 13px; color: var(--z-ink-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.empty { display: flex; align-items: center; gap: 8px; margin: 8px 0 0; color: var(--z-ink-2); } -.empty .icon { color: var(--z-ok); } - -.badge { - display: inline-flex; align-items: center; gap: 4px; - height: 24px; padding: 0 8px; - border-radius: var(--z-radius); - font-size: 12px; font-weight: 500; white-space: nowrap; -} -.badge-healthy { color: var(--z-ok); background: var(--z-ok-bg); } -.badge-warning { color: var(--z-warn); background: var(--z-warn-bg); } -.badge-error { color: var(--z-error); background: var(--z-error-bg); } - -.actions { display: flex; align-items: center; gap: 8px; margin-top: 20px; } -.btn { - display: inline-flex; align-items: center; justify-content: center; gap: 6px; - height: 32px; padding: 0 12px; - border: 1px solid var(--line); border-radius: var(--z-radius); - background: transparent; - font-size: 13px; font-weight: 500; cursor: pointer; - transition: background 150ms var(--z-ease), transform 150ms var(--z-ease); -} -.btn:hover { background: var(--z-hover); } -.btn:active { transform: scale(0.97); } -.btn[disabled] { opacity: 0.5; cursor: default; } -.btn-primary { background: var(--z-brand); border-color: var(--z-brand); color: #fff; } -.btn-primary:hover { background: var(--z-brand-hover); border-color: var(--z-brand-hover); } -.btn-ghost { border-color: transparent; } -.btn-icon { width: 32px; padding: 0; margin-left: auto; } -.row .btn-icon { margin-left: 0; } - -.icon { width: 16px; height: 16px; flex: none; } -.icon-sm { width: 14px; height: 14px; } -.spin { animation: spin 1s linear infinite; } - -.notice { margin-bottom: 12px; padding: 8px 12px; border-radius: var(--z-radius); font-size: 13px; } -.notice-ok { color: var(--z-ok); background: var(--z-ok-bg); } -.notice-error { color: var(--z-error); background: var(--z-error-bg); } - -.progress { - position: absolute; top: 0; left: 0; right: 0; height: 2px; overflow: hidden; - background: linear-gradient(90deg, transparent, var(--z-brand), transparent) 0 0 / 40% 100% no-repeat; - animation: progress 1.2s var(--z-ease) infinite; -} -.skeleton { display: grid; gap: 10px; } -.skeleton i { display: block; height: 14px; border-radius: 2px; background: var(--z-line-subtle); animation: pulse 1.4s ease-in-out infinite; } - -@keyframes spin { to { transform: rotate(360deg); } } -@keyframes progress { from { background-position: -40% 0; } to { background-position: 140% 0; } } -@keyframes pulse { 50% { opacity: 0.5; } } -@media (prefers-reduced-motion: reduce) { *, *::before { animation: none !important; transition: none !important; } } -@media (max-width: 420px) { .stat-value { font-size: 18px; } .stat { padding: 10px; } } diff --git a/apps-src/src/views/home.ts b/apps-src/src/views/home.ts deleted file mode 100644 index 28bc5ddd..00000000 --- a/apps-src/src/views/home.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Home: the workspace at a glance. Inline it is a compact card (three stats, - * up to three accounts that need attention, Open Zernio); full screen it lists - * every account. - */ -import { AlertTriangle, CircleCheck, CircleX, Maximize2, RefreshCw, SendHorizontal } from "lucide"; -import { COPY } from "../copy"; -import { h, icon } from "../dom"; -import { count, platformName } from "../format"; -import type { Account, AppState } from "../model"; - -export interface HomeEnv { - state: AppState; - compact: boolean; - canExpand: boolean; - locale?: string; - /** Must run inside the click: the host refuses a mode change without a gesture. */ - expand(): void; - refresh(): void; - reconnect(): void; - ask(account: Account): void; -} - -const RANK = { error: 0, warning: 1, healthy: 2 } as const; - -function issueOf(account: Account): string { - if (account.needsReconnect) return account.disconnectReason || "Needs to be reconnected"; - return account.issues?.[0] || account.disconnectReason || ""; -} - -function badge(status: Account["status"]): HTMLElement { - const glyph = status === "healthy" ? CircleCheck : status === "warning" ? AlertTriangle : CircleX; - return h("span", { class: `badge badge-${status}` }, icon(glyph, "icon icon-sm"), COPY.status[status] ?? status); -} - -function accountRow(env: HomeEnv, account: Account): HTMLElement { - const issue = issueOf(account); - return h( - "li", - { class: "row" }, - h( - "div", - { class: "row-main" }, - h( - "div", - { class: "row-title" }, - platformName(account.platform), - h("span", { class: "muted" }, account.username ? `@${account.username}` : account.displayName ?? ""), - ), - issue ? h("div", { class: "row-sub" }, issue) : null, - ), - badge(account.status), - account.status !== "healthy" - ? h( - "button", - { class: "btn btn-ghost btn-icon", attrs: { "aria-label": `${COPY.askClaude}: ${account.username ?? account.accountId}`, title: COPY.askClaude }, on: { click: () => env.ask(account) } }, - icon(SendHorizontal), - ) - : null, - ); -} - -export function homeView(env: HomeEnv): HTMLElement { - const { state } = env; - const summary = state.health?.summary ?? {}; - const accounts = [...(state.health?.accounts ?? [])].sort((a, b) => RANK[a.status] - RANK[b.status]); - const attention = accounts.filter((a) => a.status !== "healthy"); - const needAttention = (summary.warning ?? 0) + (summary.error ?? 0); - const listed = env.compact ? attention.slice(0, 3) : accounts; - - const stat = (label: string, value: string, tone = "") => - h("div", { class: `stat ${tone}` }, h("div", { class: "eyebrow" }, label), h("div", { class: "stat-value" }, value)); - - return h( - "div", - { class: "home" }, - h( - "div", - { class: "stats" }, - stat(COPY.stats.accounts, count(summary.total, env.locale)), - stat(COPY.stats.attention, count(needAttention, env.locale), needAttention ? "stat-warn" : ""), - stat(COPY.stats.failed, count(state.failedPosts, env.locale), state.failedPosts ? "stat-error" : ""), - ), - h( - "section", - { class: "section" }, - h("div", { class: "eyebrow" }, env.compact ? COPY.attentionTitle : COPY.accountsTitle), - listed.length - ? h("ul", { class: "list" }, listed.map((a) => accountRow(env, a))) - : h("p", { class: "empty" }, icon(CircleCheck), COPY.allHealthy), - ), - h( - "div", - { class: "actions" }, - env.canExpand - ? h("button", { class: "btn btn-primary", on: { click: env.expand } }, icon(Maximize2), COPY.open) - : null, - summary.needsReconnect - ? h("button", { class: "btn", on: { click: env.reconnect } }, COPY.reconnect) - : null, - h( - "button", - { class: "btn btn-ghost btn-icon", attrs: { "aria-label": COPY.refresh, title: COPY.refresh, disabled: state.phase === "loading" }, on: { click: env.refresh } }, - icon(RefreshCw, state.phase === "loading" ? "icon spin" : "icon"), - ), - ), - ); -} diff --git a/apps-src/src/views/shell.ts b/apps-src/src/views/shell.ts deleted file mode 100644 index b7c0cd5b..00000000 --- a/apps-src/src/views/shell.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** The frame around every screen: brand header, progress line, feedback, body. */ -import { COPY } from "../copy"; -import { h, type Child } from "../dom"; -import type { AppState } from "../model"; - -export function skeleton(): HTMLElement { - return h( - "div", - { class: "skeleton", attrs: { "aria-busy": "true", "aria-label": "Loading" } }, - h("i", { attrs: { style: "width: 100%" } }), - h("i", { attrs: { style: "width: 80%" } }), - h("i", { attrs: { style: "width: 60%" } }), - ); -} - -export function shell(state: AppState, body: Child): HTMLElement { - return h( - "main", - { class: "app" }, - h( - "header", - { class: "header" }, - h("span", { class: "mark", attrs: { "aria-hidden": "true" } }), - h("span", { class: "brand" }, COPY.brand), - h("span", { class: "title" }, COPY.title), - ), - state.phase === "loading" ? h("div", { class: "progress", attrs: { role: "progressbar", "aria-label": "Refreshing" } }) : null, - state.feedback - ? h("div", { class: `notice notice-${state.feedback.tone}`, attrs: { role: state.feedback.tone === "error" ? "alert" : "status" } }, state.feedback.text) - : null, - state.error ? h("div", { class: "notice notice-error", attrs: { role: "alert" } }, state.error) : null, - body, - ); -} diff --git a/apps-src/tsconfig.json b/apps-src/tsconfig.json index 63f04a15..2fd9744a 100644 --- a/apps-src/tsconfig.json +++ b/apps-src/tsconfig.json @@ -3,13 +3,23 @@ "target": "es2022", "module": "esnext", "moduleResolution": "bundler", - "lib": ["es2022", "dom", "dom.iterable"], - "types": ["vite/client"], + "lib": [ + "es2022", + "dom", + "dom.iterable" + ], + "types": [ + "vite/client" + ], "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noEmit": true, - "skipLibCheck": true + "skipLibCheck": true, + "jsx": "react-jsx" }, - "include": ["src", "vite.config.ts"] + "include": [ + "src", + "vite.config.ts" + ] } diff --git a/apps-src/vite.config.ts b/apps-src/vite.config.ts index 5c34b5f8..2c694ff3 100644 --- a/apps-src/vite.config.ts +++ b/apps-src/vite.config.ts @@ -1,15 +1,15 @@ // Builds the app into one self-contained HTML file (scripts and styles -// inlined), the shape an MCP Apps ui:// resource needs: the host reviews the -// whole document and nothing loads from a CDN. +// inlined), the shape an MCP Apps ui:// resource needs. Same setup as the +// ext-apps basic-server-react example. +import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; import { viteSingleFile } from "vite-plugin-singlefile"; export default defineConfig({ - plugins: [viteSingleFile()], + plugins: [react(), viteSingleFile()], build: { outDir: "../src/late/mcp/apps/bundle", emptyOutDir: true, - target: "es2022", - rollupOptions: { input: "app.html" }, + rollupOptions: { input: "mcp-app.html" }, }, }); diff --git a/src/late/mcp/apps/__init__.py b/src/late/mcp/apps/__init__.py index 96f3f8e1..e80d0f18 100644 --- a/src/late/mcp/apps/__init__.py +++ b/src/late/mcp/apps/__init__.py @@ -100,8 +100,8 @@ def register_apps(mcp: FastMCP) -> None: _register_app(mcp) -# The routed app, built from apps-src/ (Vite + TypeScript + the ext-apps SDK) -# into bundle/app.html, committed so the Python image needs no Node. It loads +# The app, built from apps-src/ (Vite + React + the ext-apps SDK) +# into bundle/mcp-app.html, committed so the Python image needs no Node. It loads # its own data through the server's tools, so the opening tool only says which # screen to show. APP_URI = f"ui://zernio/{_VERSION}/app.html" @@ -113,9 +113,8 @@ def _register_app(mcp: FastMCP) -> None: uri=APP_URI, name="Zernio", mime_type=UI_MIME_TYPE, - text=(_DIR / "bundle" / "app.html").read_text(encoding="utf-8"), - # The app draws its own frame. - meta={"ui": app_config_to_meta_dict(AppConfig(csp=_CSP, prefers_border=False))}, + text=(_DIR / "bundle" / "mcp-app.html").read_text(encoding="utf-8"), + meta={"ui": app_config_to_meta_dict(AppConfig(csp=_CSP))}, ) ) diff --git a/src/late/mcp/apps/bundle/app.html b/src/late/mcp/apps/bundle/app.html deleted file mode 100644 index b3d13e6c..00000000 --- a/src/late/mcp/apps/bundle/app.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - - Zernio - - - - -
    - - diff --git a/src/late/mcp/apps/bundle/mcp-app.html b/src/late/mcp/apps/bundle/mcp-app.html new file mode 100644 index 00000000..200f079b --- /dev/null +++ b/src/late/mcp/apps/bundle/mcp-app.html @@ -0,0 +1,123 @@ + + + + + + + Zernio + + + + +
    + + From c1b1c0b8862e88fda95333e46fa6a0aa34117fe5 Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Wed, 18 Nov 2026 15:32:15 +0100 Subject: [PATCH 05/11] feat(mcp): finish the design system v2 app (fonts route, v2 styles) The previous commit was pushed before these files were staged. Co-Authored-By: Claude Opus 5.5 --- apps-src/package-lock.json | 33 +- apps-src/package.json | 2 +- apps-src/src/Home.tsx | 147 +++++---- apps-src/src/api.ts | 7 + apps-src/src/fonts.ts | 23 ++ apps-src/src/global.css | 303 ++++++++++++------ apps-src/src/mcp-app.tsx | 14 +- apps-src/src/ui.tsx | 76 +++++ src/late/mcp/apps/__init__.py | 45 ++- src/late/mcp/apps/bundle/mcp-app.html | 30 +- src/late/mcp/apps/fonts/Geist-Variable.woff2 | Bin 0 -> 69436 bytes .../mcp/apps/fonts/GeistMono-Variable.woff2 | Bin 0 -> 71004 bytes .../mcp/apps/fonts/GeistPixel-Square.woff2 | Bin 0 -> 28616 bytes src/late/mcp/apps/fonts/LICENSE-geist.txt | 92 ++++++ 14 files changed, 564 insertions(+), 208 deletions(-) create mode 100644 apps-src/src/fonts.ts create mode 100644 apps-src/src/ui.tsx create mode 100644 src/late/mcp/apps/fonts/Geist-Variable.woff2 create mode 100644 src/late/mcp/apps/fonts/GeistMono-Variable.woff2 create mode 100644 src/late/mcp/apps/fonts/GeistPixel-Square.woff2 create mode 100644 src/late/mcp/apps/fonts/LICENSE-geist.txt diff --git a/apps-src/package-lock.json b/apps-src/package-lock.json index a06cc19c..5be3d65a 100644 --- a/apps-src/package-lock.json +++ b/apps-src/package-lock.json @@ -9,7 +9,7 @@ "@modelcontextprotocol/client": "2.4.0", "@modelcontextprotocol/core": "2.4.0", "@modelcontextprotocol/ext-apps": "2.0.4", - "lucide-react": "1.75.0", + "pixelarticons": "2.4.2", "react": "19.3.1", "react-dom": "19.3.1", "zod": "4.6.7" @@ -473,7 +473,7 @@ "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "csstype": "^3.2.2" @@ -877,7 +877,7 @@ "version": "3.2.4", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz", "integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==", - "devOptional": true, + "dev": true, "license": "MIT" }, "node_modules/detect-libc": { @@ -1232,21 +1232,6 @@ "url": "https://opencollective.com/parcel" } }, - "node_modules/lucide-react": { - "version": "1.75.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.75.0.tgz", - "integrity": "sha512-piesXAZIXru9d5lHBoM6cPHOBs5+QkMx+3EXwG3xWJ7qdViuz92JtYN0u9jMB6jt+2WbQrwhvJGdMwGnL3EOfA==", - "license": "ISC", - "peerDependencies": { - "@types/react": "*", - "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - } - }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -1295,6 +1280,18 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/pixelarticons": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/pixelarticons/-/pixelarticons-2.4.2.tgz", + "integrity": "sha512-BZKSU5ckLuioZCzES4fEmdQfnI8XEiQlHljdIVk+N6+KH7vTBQJNtMs+V0LQF7nC7cZbKT0qBXFOsT35sl8uhg==", + "license": "MIT", + "bin": { + "pixelarticons": "bin/upgrade.js" + }, + "peerDependencies": { + "react": ">=16" + } + }, "node_modules/pkce-challenge": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", diff --git a/apps-src/package.json b/apps-src/package.json index 2bc00e69..adfa4928 100644 --- a/apps-src/package.json +++ b/apps-src/package.json @@ -12,7 +12,7 @@ "@modelcontextprotocol/client": "2.4.0", "@modelcontextprotocol/core": "2.4.0", "@modelcontextprotocol/ext-apps": "2.0.4", - "lucide-react": "1.75.0", + "pixelarticons": "2.4.2", "react": "19.3.1", "react-dom": "19.3.1", "zod": "4.6.7" diff --git a/apps-src/src/Home.tsx b/apps-src/src/Home.tsx index 07873c3c..8b536534 100644 --- a/apps-src/src/Home.tsx +++ b/apps-src/src/Home.tsx @@ -1,12 +1,17 @@ /** - * Home: the workspace at a glance. Inline it is a compact card (three - * numbers, up to three accounts that need attention, Open Zernio); full - * screen it lists every account. + * Home: the workspace at a glance. Inline it shows the KPI row and up to + * three accounts that need attention, with Open Zernio; full screen it lists + * every account. */ import type { App } from "@modelcontextprotocol/ext-apps"; -import { CircleAlert, CircleCheck, Maximize2, RefreshCw, SendHorizontal } from "lucide-react"; +import { CheckDouble } from "pixelarticons/react/CheckDouble.js"; +import { Expand } from "pixelarticons/react/Expand.js"; +import { InfoBox } from "pixelarticons/react/InfoBox.js"; +import { Reload } from "pixelarticons/react/Reload.js"; +import { WarningDiamond } from "pixelarticons/react/WarningDiamond.js"; import { useCallback, useEffect, useState } from "react"; import { type Account, type AccountsHealth, getAccountsHealth, getFailedPostCount, platformName } from "./api"; +import { Button, Notice, PlatformTile, Section, Spinner, StatusPill } from "./ui"; interface Props { app: App; @@ -16,6 +21,12 @@ interface Props { } const RANK = { error: 0, warning: 1, healthy: 2 } as const; +/** 48. Green works, amber needs action, red is broken. */ +const STATE = { + healthy: { label: "Healthy", tone: "success" }, + warning: { label: "Needs attention", tone: "warning" }, + error: { label: "Broken", tone: "danger" }, +} as const; export function Home({ app, fullscreen, canExpand, locale }: Props) { const [health, setHealth] = useState(); @@ -28,7 +39,7 @@ export function Home({ app, fullscreen, canExpand, locale }: Props) { setLoading(true); const [h, f] = await Promise.allSettled([getAccountsHealth(app), getFailedPostCount(app)]); if (h.status === "fulfilled") setHealth(h.value); - setError(h.status === "rejected" ? String(h.reason) : undefined); + setError(h.status === "rejected" ? String((h.reason as Error)?.message ?? h.reason) : undefined); setFailed(f.status === "fulfilled" ? f.value : undefined); if (f.status === "rejected") console.warn("[zernio] failed posts unavailable:", f.reason); setLoading(false); @@ -41,6 +52,7 @@ export function Home({ app, fullscreen, canExpand, locale }: Props) { const accounts = [...(health?.accounts ?? [])].sort((a, b) => RANK[a.status] - RANK[b.status]); const attention = accounts.filter((a) => a.status !== "healthy"); const summary = health?.summary ?? {}; + const needAttention = (summary.warning ?? 0) + (summary.error ?? 0); // Tell Claude what the panel shows, so "these accounts" resolves to them. useEffect(() => { @@ -55,7 +67,7 @@ export function Home({ app, fullscreen, canExpand, locale }: Props) { }, [app, health, failed]); const ask = async (account: Account) => { - const issue = account.issues?.[0] || account.disconnectReason || account.status; + const issue = reasonOf(account) || STATE[account.status].label; const { isError } = await app.sendMessage({ role: "user", content: [{ type: "text", text: `My ${platformName(account.platform)} account @${account.username ?? account.accountId} (account_id ${account.accountId}) shows "${issue}" in Zernio. Help me fix it.` }], @@ -65,84 +77,93 @@ export function Home({ app, fullscreen, canExpand, locale }: Props) { const fmt = (n?: number) => (n === undefined ? "—" : new Intl.NumberFormat(locale).format(n)); const listed = fullscreen ? accounts : attention.slice(0, 3); - const needAttention = (summary.warning ?? 0) + (summary.error ?? 0); + + if (loading && !health && !error) { + return
    ; + } return ( - <> - {loading && health &&
    } - {error &&

    Could not load your workspace. {error}

    } - {notice &&

    {notice}

    } - -
    - - - +
    + {error && }>Could not load your workspace. {error}} + {notice && {notice}} + + {/* 20. Every KPI on one row of one panel, divided by hairlines: grey label on top, then the figure. */} +
    + + +
    -
    -

    {fullscreen ? "All accounts" : "Need attention"}

    +
    void load()} disabled={loading} aria-label="Refresh" title="Refresh"> + {loading ? : } + + } + > {listed.length ? ( -
      +
        {listed.map((a) => ( - void ask(a)} /> + void app.openLink({ url: "https://zernio.com/dashboard" })} + onAsk={() => void ask(a)} + /> ))}
      ) : ( -

      Every account can post.

      + // 54. An empty list says what it would hold, with an icon. +
      Every account can post.
      )} -
    - -
    - {canExpand && ( - // requestDisplayMode must run inside the click: the host refuses it otherwise. - - )} - {!!summary.needsReconnect && ( - - )} - -
    - +
    + + {canExpand && ( +
    + {/* requestDisplayMode must run inside the click: the host refuses it otherwise. */} + +
    + )} +
    ); } -function Stat({ label, value, tone }: { label: string; value: string; tone?: "warning" | "error" }) { +function Kpi({ label, value }: { label: string; value: string }) { return ( -
    -
    {label}
    -
    {value}
    +
    +
    {label}
    +
    {value}
    ); } -function AccountRow({ account, onAsk }: { account: Account; onAsk: () => void }) { - const issue = account.needsReconnect - ? account.disconnectReason || "Needs to be reconnected" - : account.issues?.[0] || account.disconnectReason || ""; - const label = { healthy: "Healthy", warning: "Warning", error: "Error" }[account.status]; +function reasonOf(account: Account): string { + if (account.needsReconnect) return account.disconnectReason || "Needs to be reconnected"; + return account.issues?.[0] || account.disconnectReason || ""; +} + +/** 40, 43, 66. One line: tile, name with the handle in grey, the state (its reason behind the info mark), the fix. */ +function AccountRow({ account, onReconnect, onAsk }: { account: Account; onReconnect: () => void; onAsk: () => void }) { + const state = STATE[account.status]; + const reason = reasonOf(account); return (
  • -
    -
    - {platformName(account.platform)} {account.username ? `@${account.username}` : account.displayName} -
    - {issue &&
    {issue}
    } + +
    + {platformName(account.platform)} + {account.username ? `@${account.username}` : account.displayName} +
    + : undefined} /> +
    + {account.needsReconnect ? ( + + ) : account.status !== "healthy" ? ( + + ) : null}
    - - {account.status === "healthy" ? : } - {label} - - {account.status !== "healthy" && ( - - )}
  • ); } diff --git a/apps-src/src/api.ts b/apps-src/src/api.ts index 1a62d1d5..e6428cd3 100644 --- a/apps-src/src/api.ts +++ b/apps-src/src/api.ts @@ -59,3 +59,10 @@ const PLATFORMS: Record = { export function platformName(platform: string): string { return PLATFORMS[platform] ?? platform; } + +/** The platform's full-colour app icon, as the dashboard shows it (zernio.com/platform-logos). */ +const ICON_FILES: Record = { twitter: "x", googlebusiness: "google" }; + +export function platformIcon(platform: string): string { + return `https://zernio.com/platform-logos/${ICON_FILES[platform] ?? platform}-icon.png`; +} diff --git a/apps-src/src/fonts.ts b/apps-src/src/fonts.ts new file mode 100644 index 00000000..c5e15410 --- /dev/null +++ b/apps-src/src/fonts.ts @@ -0,0 +1,23 @@ +/** + * Geist, Geist Mono and Geist Pixel Square, the design system's three faces. + * MCP Apps allow fonts only from declared origins (no data: URLs), so the MCP + * server serves them; it writes its own public URL over ZERNIO_ORIGIN when it + * serves this bundle, and lists that origin in the resource's CSP. + */ +const ORIGIN = "__ZERNIO_ORIGIN__"; + +const FACES = [ + { family: "Geist", file: "Geist-Variable.woff2", weight: "100 900" }, + { family: "Geist Mono", file: "GeistMono-Variable.woff2", weight: "100 900" }, + { family: "Geist Pixel Square", file: "GeistPixel-Square.woff2", weight: "500" }, +]; + +export function installFonts(): void { + if (ORIGIN.startsWith("__")) return; + const style = document.createElement("style"); + style.textContent = FACES.map( + (f) => + `@font-face{font-family:"${f.family}";src:url("${ORIGIN}/apps/fonts/${f.file}") format("woff2");font-weight:${f.weight};font-display:swap}`, + ).join(""); + document.head.appendChild(style); +} diff --git a/apps-src/src/global.css b/apps-src/src/global.css index 54c38830..7d2fc0b4 100644 --- a/apps-src/src/global.css +++ b/apps-src/src/global.css @@ -1,126 +1,227 @@ /* - * As in the ext-apps examples: the host's style variables drive structure - * (text, borders, surfaces, fonts, radii) and useHostStyles applies them; the - * values below are fallbacks, taken from zernio.com, for a host that sends - * none. Zernio's own identity is the accent and the mono labels. + * The Zernio product look (v2), as the dashboard draws it under data-look="v2". + * Values are the Figma `Product` file's, copied from Schedule-Posts-API + * libs/design-system/new-look.ts: `Theme` (light and dark, from `Primitives`), + * `Scale` (sizes, radius, spacing) and the `type/*` text styles. Change them + * there first; this file follows. + * + * In Claude the host's surface shows through: the page is transparent inline, + * the panels are bg/raised. Dark mode follows the host's theme (data-theme, + * which useHostStyles sets from the host context). */ :root { - color-scheme: light dark; - - --color-text-primary: light-dark(#1a1a1a, #fafafa); - --color-text-secondary: light-dark(#525252, #d4d4d4); - --color-text-tertiary: light-dark(#6b6b6b, #a3a3a3); - --color-text-success: light-dark(#15803d, #4ade80); - --color-text-warning: light-dark(#b45309, #fbbf24); - --color-text-danger: light-dark(#c0260f, #f87171); - --color-background-secondary: light-dark(#faf9f7, #151516); - --color-background-success: light-dark(#ecfdf3, rgb(74 222 128 / 0.1)); - --color-background-warning: light-dark(#fffbeb, rgb(251 191 36 / 0.1)); - --color-background-danger: light-dark(#fef2f0, rgb(248 113 113 / 0.1)); - --color-border-primary: light-dark(#e4e4e4, rgb(255 255 255 / 0.14)); - --color-border-secondary: light-dark(#f2f2f2, rgb(255 255 255 / 0.08)); - --border-radius-sm: 4px; - --border-radius-md: 6px; - --font-sans: "Geist", ui-sans-serif, system-ui, sans-serif; - --font-mono: "Geist Mono", ui-monospace, Menlo, Consolas, monospace; - - /* Zernio */ - --color-accent: #eb3514; - --color-accent-hover: #d22e0e; - --color-text-on-accent: #ffffff; + /* Theme, light */ + --bg-base: #faf9f8; + --bg-raised: #ffffff; + --bg-overlay: #ffffff; + --bg-inverse: #1a1a1a; + --fill-primary: #faf9f8; + --fill-hover: rgb(92 68 37 / 0.03); + --fill-selected: rgb(92 68 37 / 0.05); + --fill-active: rgb(92 68 37 / 0.05); + --text-primary: #1a1a1a; + --text-secondary: #525252; + --text-tertiary: #6b6b6b; + --text-placeholder: #a3a3a3; + --text-inverse: #ffffff; + --text-link: #1e4a7c; + --text-disabled: #d4d4d4; + --border-default: #e4e4e4; + --border-subtle: #f2f2f2; + --border-focus: #1a1a1a; + --brand-default: #eb3514; + --brand-hover: #d12c0e; + --brand-subtle: #fbe8e5; + --status-success-fg: #15803d; + --status-success-bg: #e3f4e9; + --status-warning-fg: #7c4a18; + --status-warning-bg: #fff3c5; + --status-danger-fg: #b9342e; + --status-danger-bg: #fbe0e0; + --status-info-fg: #1e4a7c; + --status-info-bg: #e4eefb; + --shadow-color: rgb(0 0 0 / 0.1); + + /* Scale */ + --size-control-sm: 28px; + --size-control-md: 32px; + --size-control-lg: 36px; + --size-icon-sm: 12px; + --size-icon-md: 16px; + --size-row: 40px; + --radius-surface: 0px; + --radius-control: 0px; + --radius-item: 4px; + --radius-item-lg: 6px; + + /* Type families */ + --font-sans: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; + --font-mono: "Geist Mono", ui-monospace, SFMono-Regular, Menlo, monospace; + --font-pixel: "Geist Pixel Square", "Geist Mono", ui-monospace, Menlo, monospace; + + color-scheme: light; +} + +/* Theme, dark */ +:root[data-theme="dark"] { + --bg-base: #0f0f10; + --bg-raised: #151516; + --bg-overlay: #151516; + --bg-inverse: #1a1a1a; + --fill-primary: #0f0f10; + --fill-hover: rgb(255 255 255 / 0.04); + --fill-selected: rgb(255 255 255 / 0.06); + --fill-active: rgb(255 255 255 / 0.06); + --text-primary: #fafafa; + --text-secondary: #d4d4d4; + --text-tertiary: #a3a3a3; + --text-placeholder: #6b6b6b; + --text-inverse: #ffffff; + --text-link: #7ed4fc; + --text-disabled: #333333; + --border-default: #212122; + --border-subtle: #1c1c1d; + --border-focus: #fafafa; + --brand-subtle: #261514; + --status-success-fg: #6ee7b7; + --status-success-bg: #0d2418; + --status-warning-fg: #fcd44f; + --status-warning-bg: #2b1f0a; + --status-danger-fg: #fca6a6; + --status-danger-bg: #2b1414; + --status-info-fg: #7ed4fc; + --status-info-bg: #0e1c2e; + --shadow-color: rgb(0 0 0 / 0.5); + color-scheme: dark; } -:root[data-theme="light"] { color-scheme: light; } -:root[data-theme="dark"] { color-scheme: dark; } * { box-sizing: border-box; } html, body { margin: 0; background: transparent; } body { + /* body/14 */ font: 400 14px/20px var(--font-sans); - color: var(--color-text-primary); + color: var(--text-primary); -webkit-font-smoothing: antialiased; } button { font: inherit; color: inherit; } -:focus-visible { outline: 2px solid var(--color-accent); outline-offset: 2px; } +img { display: block; } -.app { position: relative; padding: 4px 2px 8px; } -.app-fullscreen { max-width: 960px; margin: 0 auto; padding: 20px 16px 112px; } +/* Text styles (type/*), weights 400 and 500 only (11) */ +.type-page-title { font: 500 14px/20px var(--font-pixel); } +.type-eyebrow { margin: 0; font: 500 12px/16px var(--font-pixel); text-transform: uppercase; color: var(--text-tertiary); } +.type-metric { font: 500 24px/32px var(--font-sans); font-variant-numeric: tabular-nums; } +.type-label { font: 500 14px/20px var(--font-sans); } +.icon { width: var(--size-icon-md); height: var(--size-icon-md); flex: none; } +.icon-sm { width: var(--size-icon-sm); height: var(--size-icon-sm); flex: none; } -.header { display: flex; align-items: center; gap: 8px; margin-bottom: 14px; } -.mark { width: 14px; height: 14px; border-radius: 3px; background: var(--color-accent); } -.brand { font-weight: 600; } +.app { padding: 2px 0 4px; } +.app-fullscreen { min-height: 100vh; max-width: 960px; margin: 0 auto; padding: 12px 12px 112px; background: var(--bg-base); } +.header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; } +.logo { width: 18px; height: 18px; border-radius: var(--radius-item); } +.stack { display: flex; flex-direction: column; gap: 8px; } -.eyebrow { - margin: 0; - font: 500 10.5px/14px var(--font-mono); - letter-spacing: 0.08em; - text-transform: uppercase; - color: var(--color-text-tertiary); +/* 18. Panels: white, bordered, square; a list's panel has a grey bar with its eyebrow title. */ +.section, .kpis { + border: 1px solid var(--border-default); + border-radius: var(--radius-surface); + background: var(--bg-raised); +} +.section-bar { + display: flex; align-items: center; justify-content: space-between; gap: 8px; + height: var(--size-control-md); + padding: 0 8px; + border-bottom: 1px solid var(--border-default); + background: var(--fill-primary); } -.muted { color: var(--color-text-tertiary); font-weight: 400; } +.section-actions { display: flex; align-items: center; gap: 4px; } +.section-body { padding: 0 8px; } + +/* 20. KPIs: one row, divided by hairlines, grey label above the figure. */ +.kpis { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); } +.kpi { padding: 12px; } +.kpi + .kpi { border-left: 1px solid var(--border-default); } +.kpi-label { color: var(--text-tertiary); } + +/* Rows: 40px, one line, everything centred (22, 44); one border between rows (23). */ +.rows { list-style: none; margin: 0; padding: 0; } +.row { display: flex; align-items: center; gap: 8px; min-height: var(--size-row); } +.row + .row { border-top: 1px solid var(--border-subtle); } +.row-name { flex: 1; min-width: 0; display: flex; align-items: baseline; gap: 6px; overflow: hidden; white-space: nowrap; } +.row-name > * { overflow: hidden; text-overflow: ellipsis; } +.row-secondary { color: var(--text-tertiary); } +.row-fix { width: 104px; display: flex; justify-content: flex-end; flex: none; } -.stats { - display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - border: 1px solid var(--color-border-primary); - border-radius: var(--border-radius-md); +/* 42. PlatformTile md: the app icon in a 22px bordered tile, radius/item-lg. */ +.platform-tile { + display: inline-flex; align-items: center; justify-content: center; flex: none; + padding: 2px; + border: 1px solid var(--border-default); + border-radius: var(--radius-item-lg); } -.stat { padding: 12px 14px; } -.stat + .stat { border-left: 1px solid var(--color-border-primary); } -.stat-value { margin-top: 6px; font: 500 22px/28px var(--font-mono); font-variant-numeric: tabular-nums; } -.stat-warning .stat-value { color: var(--color-text-warning); } -.stat-error .stat-value { color: var(--color-text-danger); } - -.section { margin-top: 20px; } -.list { list-style: none; margin: 6px 0 0; padding: 0; } -.row { display: flex; align-items: center; gap: 10px; padding: 10px 0; } -.row + .row { border-top: 1px solid var(--color-border-secondary); } -.row-main { flex: 1; min-width: 0; } -.row-title { font-weight: 500; } -.row-sub { font-size: 13px; color: var(--color-text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.empty { display: flex; align-items: center; gap: 8px; margin: 8px 0 0; color: var(--color-text-secondary); } -.empty svg { color: var(--color-text-success); } - -.badge { - display: inline-flex; align-items: center; gap: 4px; - height: 24px; padding: 0 8px; - border-radius: var(--border-radius-sm); - font-size: 12px; font-weight: 500; white-space: nowrap; +.platform-tile img { width: 16px; height: 16px; object-fit: contain; } + +/* 16, 51. StatusPill: 20px, 14px at 400, radius/item, tinted. */ +.status-pill { + display: inline-flex; align-items: center; gap: 2px; flex: none; + height: 20px; padding: 0 4px; + border-radius: var(--radius-item); + font-size: 14px; line-height: 20px; white-space: nowrap; } -.badge-healthy { color: var(--color-text-success); background: var(--color-background-success); } -.badge-warning { color: var(--color-text-warning); background: var(--color-background-warning); } -.badge-error { color: var(--color-text-danger); background: var(--color-background-danger); } +.status-pill-success { color: var(--status-success-fg); background: var(--status-success-bg); } +.status-pill-warning { color: var(--status-warning-fg); background: var(--status-warning-bg); } +.status-pill-danger { color: var(--status-danger-fg); background: var(--status-danger-bg); } +.status-pill-info { color: var(--status-info-fg); background: var(--status-info-bg); } +.status-pill-muted { color: var(--text-tertiary); background: var(--fill-primary); } -.actions { display: flex; align-items: center; gap: 8px; margin-top: 18px; } +/* Buttons: square controls; hover changes colour only (1); focus darkens the border, no ring (13). */ .btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; - height: 32px; padding: 0 12px; - border: 1px solid var(--color-border-primary); - border-radius: var(--border-radius-sm); + border: 1px solid transparent; + border-radius: var(--radius-control); background: transparent; - font-size: 13px; font-weight: 500; cursor: pointer; + font-size: 14px; font-weight: 400; line-height: 20px; + cursor: pointer; white-space: nowrap; } -.btn:hover { background: var(--color-background-secondary); } -.btn:disabled { opacity: 0.5; cursor: default; } -.btn-primary { background: var(--color-accent); border-color: var(--color-accent); color: var(--color-text-on-accent); } -.btn-primary:hover { background: var(--color-accent-hover); border-color: var(--color-accent-hover); } -.btn-ghost { border-color: transparent; } -.btn-icon { width: 32px; padding: 0; } -.actions .btn-icon { margin-left: auto; } - -.notice { margin: 0 0 12px; padding: 8px 12px; border-radius: var(--border-radius-sm); font-size: 13px; background: var(--color-background-secondary); } -.notice-error { color: var(--color-text-danger); background: var(--color-background-danger); } - -.progress { - position: absolute; top: 0; left: 0; right: 0; height: 2px; - background: linear-gradient(90deg, transparent, var(--color-accent), transparent) 0 0 / 40% 100% no-repeat; - animation: progress 1.2s ease-in-out infinite; +.btn-md { height: var(--size-control-md); padding: 0 12px; } +.btn-sm { height: var(--size-control-sm); padding: 0 8px; } +.btn-icon.btn-md { width: var(--size-control-md); padding: 0; } +.btn-icon.btn-sm { width: var(--size-control-sm); padding: 0; } +.btn-primary { background: var(--brand-default); color: var(--text-inverse); } +.btn-primary:hover { background: var(--brand-hover); } +.btn-primary:disabled { background: var(--fill-active); color: var(--text-disabled); } +.btn-outline { border-color: var(--border-default); background: var(--bg-raised); color: var(--text-primary); } +.btn-outline:hover { background: var(--fill-hover); } +.btn-ghost { color: var(--text-primary); } +.btn-ghost:hover { background: var(--fill-hover); } +.btn:disabled { cursor: default; } +.btn:focus-visible { outline: none; border-color: var(--border-focus); } +.btn-primary:focus-visible { background: var(--brand-hover); } + +.actions { display: flex; align-items: center; gap: 8px; } + +/* 15. A notice is coloured text with its icon, no fill, no border. */ +.notice { display: flex; align-items: flex-start; gap: 6px; margin: 0; } +.notice .icon { margin-top: 2px; } +.notice-danger { color: var(--status-danger-fg); } +.notice-success { color: var(--status-success-fg); } +.notice-muted { color: var(--text-tertiary); } + +/* 54. Empty state: icon and what the list would hold. */ +.empty { display: flex; align-items: center; gap: 6px; min-height: var(--size-row); color: var(--text-tertiary); } + +/* 17. Spinner: 3x3 pixel rain, 4px cells, stepping, in the text colour. */ +.loading { display: flex; align-items: center; justify-content: center; min-height: 96px; color: var(--text-tertiary); } +.spinner { display: inline-grid; grid-template-columns: repeat(3, 4px); gap: 2px; color: currentColor; } +.spinner > span { width: 4px; height: 4px; background: currentColor; animation: pixel-rain 600ms steps(1, end) infinite; } +@keyframes pixel-rain { + 0% { opacity: 1; } + 33.333% { opacity: 0.4; } + 66.666%, 100% { opacity: 0.15; } +} +@media (prefers-reduced-motion: reduce) { .spinner > span { animation: none; } } + +@media (max-width: 420px) { + .kpi { padding: 8px; } + .type-metric { font-size: 16px; line-height: 24px; } + .row-fix { width: auto; } } -.skeleton { display: grid; gap: 10px; padding: 8px 2px; } -.skeleton i { display: block; height: 14px; border-radius: 2px; background: var(--color-border-secondary); animation: pulse 1.4s ease-in-out infinite; } -.spin { animation: spin 1s linear infinite; } - -@keyframes spin { to { transform: rotate(360deg); } } -@keyframes progress { from { background-position: -40% 0; } to { background-position: 140% 0; } } -@keyframes pulse { 50% { opacity: 0.5; } } -@media (prefers-reduced-motion: reduce) { * { animation: none !important; } } -@media (max-width: 420px) { .stat { padding: 10px; } .stat-value { font-size: 18px; } } diff --git a/apps-src/src/mcp-app.tsx b/apps-src/src/mcp-app.tsx index 0f7f305f..2515787b 100644 --- a/apps-src/src/mcp-app.tsx +++ b/apps-src/src/mcp-app.tsx @@ -6,9 +6,13 @@ import type { App, McpUiHostContext } from "@modelcontextprotocol/ext-apps"; import { useApp, useHostStyles } from "@modelcontextprotocol/ext-apps/react"; import { StrictMode, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; +import { installFonts } from "./fonts"; import { Home } from "./Home"; +import { Spinner } from "./ui"; import "./global.css"; +installFonts(); + function ZernioApp() { const [hostContext, setHostContext] = useState(); const [opened, setOpened] = useState(false); @@ -45,8 +49,8 @@ function Shell({ app, hostContext }: { app: App; hostContext?: McpUiHostContext style={{ paddingTop: insets?.top, paddingRight: insets?.right, paddingLeft: insets?.left }} >
    -
    - - - +
    +
    ); } diff --git a/apps-src/src/ui.tsx b/apps-src/src/ui.tsx new file mode 100644 index 00000000..9b49e163 --- /dev/null +++ b/apps-src/src/ui.tsx @@ -0,0 +1,76 @@ +/** + * The few dashboard primitives the app needs, drawn as the product look (v2) + * draws them: Section (a panel with its grey bar), StatusPill, PlatformTile, + * Spinner (the pixel rain), Notice and Button. Numbers in comments are the + * design principles they follow (Schedule-Posts-API, design-principles.md). + */ +import type { ButtonHTMLAttributes, ReactNode } from "react"; +import { platformIcon, platformName } from "./api"; + +/** 18. A block is a white panel; a list's panel is headed by a grey bar with its eyebrow title. */ +export function Section({ title, actions, children }: { title: string; actions?: ReactNode; children: ReactNode }) { + return ( +
    +
    +

    {title}

    + {actions &&
    {actions}
    } +
    +
    {children}
    +
    + ); +} + +type Tone = "success" | "warning" | "danger" | "info" | "muted"; + +/** 16, 48. A state is a filled pill in its colour, sentence case, no glyph in its text. */ +export function StatusPill({ label, tone, suffix, title }: { label: string; tone: Tone; suffix?: ReactNode; title?: string }) { + return ( + + {label} + {suffix} + + ); +} + +/** 7, 42. A platform shows as its app icon in a bordered tile (md, 22px). */ +export function PlatformTile({ platform }: { platform: string }) { + return ( + + {platformName(platform)} + + ); +} + +/** 17. Loading is a 3x3 pixel rain in the text colour, stepping between frames. */ +export function Spinner({ label = "Loading" }: { label?: string }) { + return ( + + {Array.from({ length: 9 }, (_, i) => { + const frame = (Math.floor(i / 3) + (i % 3)) % 3; + return ; + })} + + ); +} + +/** 15. A notice is coloured text with its icon, not a box. */ +export function Notice({ tone, icon, children }: { tone: "danger" | "success" | "muted"; icon?: ReactNode; children: ReactNode }) { + return ( +

    + {icon} + {children} +

    + ); +} + +type ButtonProps = ButtonHTMLAttributes & { + variant?: "primary" | "outline" | "ghost"; + size?: "sm" | "md"; + icon?: boolean; +}; + +/** Square controls, 28/32px (size/control-sm, -md); hover changes colour only (1). */ +export function Button({ variant = "outline", size = "md", icon, className, ...props }: ButtonProps) { + const classes = ["btn", `btn-${variant}`, `btn-${size}`, icon ? "btn-icon" : "", className ?? ""].filter(Boolean); + return - } - > - {listed.length ? ( -
      - {listed.map((a) => ( - void app.openLink({ url: "https://zernio.com/dashboard" })} - onAsk={() => void ask(a)} - /> - ))} -
    - ) : ( - // 54. An empty list says what it would hold, with an icon. -
    Every account can post.
    - )} - - - {canExpand && ( -
    - {/* requestDisplayMode must run inside the click: the host refuses it otherwise. */} - -
    - )} -
    - ); -} - -function Kpi({ label, value }: { label: string; value: string }) { - return ( -
    -
    {label}
    -
    {value}
    -
    - ); -} - -function reasonOf(account: Account): string { - if (account.needsReconnect) return account.disconnectReason || "Needs to be reconnected"; - return account.issues?.[0] || account.disconnectReason || ""; -} - -/** 40, 43, 66. One line: tile, name with the handle in grey, the state (its reason behind the info mark), the fix. */ -function AccountRow({ account, onReconnect, onAsk }: { account: Account; onReconnect: () => void; onAsk: () => void }) { - const state = STATE[account.status]; - const reason = reasonOf(account); - return ( -
  • - -
    - {platformName(account.platform)} - {account.username ? `@${account.username}` : account.displayName} -
    - : undefined} /> -
    - {account.needsReconnect ? ( - - ) : account.status !== "healthy" ? ( - - ) : null} -
    -
  • - ); -} diff --git a/apps-src/src/api.ts b/apps-src/src/api.ts index e6428cd3..33a2dddf 100644 --- a/apps-src/src/api.ts +++ b/apps-src/src/api.ts @@ -1,10 +1,60 @@ /** - * The app reads its data through the server's ordinary tools + * The screens, the tool that opens each one, and the shapes of their data. + * + * Every screen comes from one of the server's tools as structuredContent + * `{view, data, args}` (src/late/mcp/apps/tools.py). The app switches screens + * and refreshes by calling those same tools through the host * (app.callServerTool), so the user's scopes and the API's validation apply - * as they do for Claude. Generated tools return compact JSON as their text. + * as they do for Claude. */ import type { App } from "@modelcontextprotocol/ext-apps"; +export type View = "home" | "posts" | "analytics" | "accounts" | "ads" | "preview" | "approvals"; + +export const TOOLS: Record = { + home: "zernio_open_app", + posts: "show_failed_posts", + analytics: "show_analytics", + accounts: "show_account_health", + ads: "show_ads_alerts", + preview: "show_post_preview", + approvals: "show_automation_approvals", +}; + +export const VIEW_TITLES: Record = { + home: "Home", + posts: "Failed posts", + analytics: "Analytics", + accounts: "Accounts", + ads: "Ads", + preview: "Post preview", + approvals: "Approvals", +}; + +/** The screens with a tab; the others open from a tool with their own arguments. */ +export const TABS: View[] = ["home", "posts", "analytics", "accounts", "ads"]; + +export interface Screen { + view: View; + data: D; + args: Record; +} + +export type CallResult = Awaited>; + +export function textOf(result: CallResult): string { + return result.content.map((block) => (block.type === "text" ? block.text : "")).join(""); +} + +/** The screen a tool result carries, or undefined when it is not one of ours. */ +export function screenOf(result: CallResult): Screen | undefined { + const sc = result.structuredContent as Partial | undefined; + if (!sc || typeof sc.view !== "string" || !(sc.view in TOOLS)) return undefined; + return { view: sc.view as View, data: sc.data, args: (sc.args as Record) ?? {} }; +} + +/* Data of each screen */ + export interface Account { accountId: string; platform: string; @@ -21,48 +71,132 @@ export interface AccountsHealth { accounts?: Account[]; } -async function callJson(app: App, name: string, args: Record = {}): Promise { - const result = await app.callServerTool({ name, arguments: args }); - const text = result.content - .map((block) => (block.type === "text" ? block.text : "")) - .join(""); - if (result.isError) throw new Error(text || `${name} failed`); - return JSON.parse(text) as T; +export interface FailedPost { + id: string; + title: string; + content: string; + platforms: string[]; + errors: { platform: string | null; message: string }[]; + updatedAt: string | null; } -export function getAccountsHealth(app: App): Promise { - return callJson(app, "accounts_get_all_accounts_health"); +export interface HomeData { + health: AccountsHealth; + failedPosts: FailedPost[]; + failedTotal: number; } -/** - * How many posts failed. posts_list_posts is not listed up front (it sits - * behind search_tools), so this also shows whether the host lets an app call - * a tool it never received in tools/list. - */ -export async function getFailedPostCount(app: App): Promise { - const page = await callJson<{ posts?: unknown[]; pagination?: { total?: number } }>( - app, - "posts_list_posts", - { status: "failed", limit: 1 }, - ); - return page.pagination?.total ?? page.posts?.length ?? 0; +export interface PostsData { + posts: FailedPost[]; + total: number; +} + +export interface Metrics { + impressions?: number; + reach?: number; + likes?: number; + comments?: number; + shares?: number; + saves?: number; + clicks?: number; + views?: number; +} + +export interface AnalyticsData { + dailyData?: { date: string; postCount?: number; metrics?: Metrics }[]; + platformBreakdown?: (Metrics & { platform: string; postCount?: number })[]; + totals?: Metrics & { postCount?: number; engagement?: number }; } +export interface AdsAlert { + id: string; + kind?: string; + severity: "error" | "warning" | "info"; + title: string; + message?: string; + platform?: string; + entity?: { level?: string; id?: string; name?: string | null }; + fix?: { label?: string; url?: string }; +} + +export interface AdsData { + alerts?: AdsAlert[]; + counts?: { error?: number; warning?: number; info?: number }; +} + +export interface ApprovalChange { + type: string; + subject?: { kind?: string; id?: string; name?: string | null }; + previous?: Record | null; + target?: Record | null; + status?: string; +} + +export interface Approval { + id: string; + status: "pending" | "approved" | "rejected" | "expired" | "cancelled"; + canDecide: boolean; + expiresAt: string; + to?: string[]; + decidedBy?: { email?: string } | null; + changes: ApprovalChange[]; +} + +export interface ApprovalsData { + automationId: string; + approvals: Approval[]; +} + +export interface PreviewData { + content: string; + media: { type: string; url: string }[]; + targets: { platform: string; accountId?: string; handle?: string; error?: string }[]; + validation?: { + valid?: boolean; + errors?: { platform?: string; error: string }[]; + warnings?: { platform?: string; warning: string }[]; + } | null; + request: Record; +} + +/* Platforms */ + const PLATFORMS: Record = { - twitter: "X", instagram: "Instagram", facebook: "Facebook", linkedin: "LinkedIn", + twitter: "X", x: "X", instagram: "Instagram", facebook: "Facebook", linkedin: "LinkedIn", tiktok: "TikTok", youtube: "YouTube", threads: "Threads", pinterest: "Pinterest", reddit: "Reddit", bluesky: "Bluesky", googlebusiness: "Google Business", telegram: "Telegram", snapchat: "Snapchat", discord: "Discord", slack: "Slack", - whatsapp: "WhatsApp", + whatsapp: "WhatsApp", meta: "Meta", google: "Google", microsoft: "Microsoft", + openai: "ChatGPT", linkedinads: "LinkedIn Ads", metaads: "Meta Ads", tiktokads: "TikTok Ads", + googleads: "Google Ads", pinterestads: "Pinterest Ads", xads: "X Ads", redditads: "Reddit Ads", }; -export function platformName(platform: string): string { - return PLATFORMS[platform] ?? platform; +export function platformName(platform: string | null | undefined): string { + if (!platform) return "Unknown"; + return PLATFORMS[platform] ?? platform.charAt(0).toUpperCase() + platform.slice(1); } /** The platform's full-colour app icon, as the dashboard shows it (zernio.com/platform-logos). */ -const ICON_FILES: Record = { twitter: "x", googlebusiness: "google" }; +const ICON_FILES: Record = { + twitter: "x", xads: "x", googlebusiness: "google", google: "googleads", openai: "chatgpt", + metaads: "meta", linkedinads: "linkedin", tiktokads: "tiktok", pinterestads: "pinterest", + redditads: "reddit", googleads: "googleads", +}; export function platformIcon(platform: string): string { return `https://zernio.com/platform-logos/${ICON_FILES[platform] ?? platform}-icon.png`; } + +/* Formatting */ + +export function formatNumber(value: number | undefined, locale?: string, compact = false): string { + if (value === undefined || value === null) return "—"; + return new Intl.NumberFormat(locale, compact ? { notation: "compact", maximumFractionDigits: 1 } : undefined).format(value); +} + +export function formatDate(value: string | null | undefined, locale?: string, options?: Intl.DateTimeFormatOptions): string { + if (!value) return "—"; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return value; + return date.toLocaleDateString(locale, options ?? { month: "short", day: "numeric" }); +} diff --git a/apps-src/src/global.css b/apps-src/src/global.css index 7d2fc0b4..ee05d243 100644 --- a/apps-src/src/global.css +++ b/apps-src/src/global.css @@ -41,6 +41,7 @@ --status-info-fg: #1e4a7c; --status-info-bg: #e4eefb; --shadow-color: rgb(0 0 0 / 0.1); + --chart-3: #1e4a7c; /* Scale */ --size-control-sm: 28px; @@ -92,6 +93,7 @@ --status-info-fg: #7ed4fc; --status-info-bg: #0e1c2e; --shadow-color: rgb(0 0 0 / 0.5); + --chart-3: #7ed4fc; color-scheme: dark; } @@ -111,12 +113,24 @@ img { display: block; } .type-eyebrow { margin: 0; font: 500 12px/16px var(--font-pixel); text-transform: uppercase; color: var(--text-tertiary); } .type-metric { font: 500 24px/32px var(--font-sans); font-variant-numeric: tabular-nums; } .type-label { font: 500 14px/20px var(--font-sans); } +.type-mono { font: 400 14px/20px var(--font-mono); font-variant-numeric: tabular-nums; white-space: nowrap; } +/* 5. A count beside a pixel title: pixel font, light outline. */ +.count { display: inline-block; margin-left: 6px; padding: 0 4px; border: 1px solid var(--border-default); border-radius: var(--radius-item); font: inherit; color: var(--text-tertiary); } .icon { width: var(--size-icon-md); height: var(--size-icon-md); flex: none; } .icon-sm { width: var(--size-icon-sm); height: var(--size-icon-sm); flex: none; } .app { padding: 2px 0 4px; } -.app-fullscreen { min-height: 100vh; max-width: 960px; margin: 0 auto; padding: 12px 12px 112px; background: var(--bg-base); } -.header { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; } +.app-fullscreen { min-height: 100vh; max-width: 960px; margin: 0 auto; padding: 12px 12px calc(var(--safe-bottom, 0px) + 112px); background: var(--bg-base); } +.header { display: flex; align-items: center; gap: 8px; min-height: var(--size-control-md); margin-bottom: 8px; } +.crumb { color: var(--text-tertiary); } +.crumb::before { content: "/"; margin-right: 8px; color: var(--border-default); } +.header-actions { margin-left: auto; display: inline-flex; align-items: center; gap: 4px; color: var(--text-tertiary); } + +/* 28. Underline tabs: the active one marked, the rest grey; hover darkens the text only. */ +.tabs { display: flex; gap: 16px; margin-bottom: 8px; border-bottom: 1px solid var(--border-default); } +.tab { height: var(--size-control-md); padding: 0; border: 0; border-bottom: 1px solid transparent; margin-bottom: -1px; background: none; color: var(--text-tertiary); cursor: pointer; } +.tab:hover { color: var(--text-primary); } +.tab-active { color: var(--text-primary); border-bottom-color: var(--text-primary); } .logo { width: 18px; height: 18px; border-radius: var(--radius-item); } .stack { display: flex; flex-direction: column; gap: 8px; } @@ -135,12 +149,50 @@ img { display: block; } } .section-actions { display: flex; align-items: center; gap: 4px; } .section-body { padding: 0 8px; } +.section-body-flush { padding: 0; } +.section-body > .notice { padding: 8px 0; } +.section-footer { display: flex; gap: 8px; padding: 8px 0; border-top: 1px solid var(--border-subtle); } +.more { display: flex; padding: 4px 0 8px; } /* 20. KPIs: one row, divided by hairlines, grey label above the figure. */ -.kpis { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); } -.kpi { padding: 12px; } +.kpi-row { display: grid; } +.kpi { padding: 12px; text-align: left; border: 0; background: none; color: inherit; } .kpi + .kpi { border-left: 1px solid var(--border-default); } +button.kpi { cursor: pointer; box-shadow: inset 0 -2px 0 transparent; } +button.kpi:hover { background: var(--fill-hover); } +.kpi-selected { box-shadow: inset 0 -2px 0 var(--chart-3) !important; } .kpi-label { color: var(--text-tertiary); } +.kpi-chart { padding: 8px 12px 12px; border-top: 1px solid var(--border-default); } + +/* 20. The chart: the panel's hue, dashed gridlines, dates under it. */ +.chart-readout { display: flex; align-items: baseline; gap: 8px; margin-bottom: 8px; } +.chart-plot { position: relative; } +.chart-plot svg { display: block; width: 100%; touch-action: none; } +.chart-max { position: absolute; top: -2px; right: 0; color: var(--text-tertiary); font: 400 12px/16px var(--font-mono); background: var(--bg-raised); padding-left: 4px; } +.chart-grid { stroke: var(--border-default); stroke-dasharray: 3 3; vector-effect: non-scaling-stroke; } +.chart-axis { stroke: var(--border-default); vector-effect: non-scaling-stroke; } +.chart-line { fill: none; stroke: var(--chart-3); stroke-width: 1.5; vector-effect: non-scaling-stroke; } +.chart-dates { display: flex; justify-content: space-between; margin-top: 4px; color: var(--text-tertiary); font: 400 12px/16px var(--font-mono); } + +/* 24, 51. Tables: eyebrow headers, 14px cells, one line, the share as a grey bar. */ +.table { width: 100%; border-collapse: collapse; } +.table th { height: var(--size-control-md); padding: 0 8px; text-align: left; font: 500 12px/16px var(--font-pixel); text-transform: uppercase; color: var(--text-tertiary); border-bottom: 1px solid var(--border-default); white-space: nowrap; } +.table td { height: var(--size-row); padding: 0 8px; white-space: nowrap; } +.table tr + tr td { border-top: 1px solid var(--border-subtle); } +.table .num { text-align: right; font-variant-numeric: tabular-nums; } +.share-col { width: 25%; } +.share { display: block; height: 6px; background: var(--fill-active); } +.share > span { display: block; height: 100%; background: var(--text-tertiary); } +.cell-lead { display: inline-flex; align-items: center; gap: 8px; } + +/* 16. A label that is not a state: outline chip. */ +.badge { display: inline-flex; align-items: center; height: 20px; padding: 0 4px; border: 1px solid var(--border-default); border-radius: var(--radius-item); color: var(--text-secondary); white-space: nowrap; flex: none; } + +/* Post preview */ +.post-body { margin: 0; padding: 8px 0; white-space: pre-wrap; overflow-wrap: anywhere; } +.media { display: flex; gap: 4px; padding-bottom: 8px; } +.media img, .media-tile { width: 64px; height: 64px; object-fit: cover; border: 1px solid var(--border-default); border-radius: var(--radius-item-lg); } +.media-tile { display: inline-flex; align-items: center; justify-content: center; color: var(--text-tertiary); background: var(--fill-primary); } /* Rows: 40px, one line, everything centred (22, 44); one border between rows (23). */ .rows { list-style: none; margin: 0; padding: 0; } @@ -149,7 +201,9 @@ img { display: block; } .row-name { flex: 1; min-width: 0; display: flex; align-items: baseline; gap: 6px; overflow: hidden; white-space: nowrap; } .row-name > * { overflow: hidden; text-overflow: ellipsis; } .row-secondary { color: var(--text-tertiary); } -.row-fix { width: 104px; display: flex; justify-content: flex-end; flex: none; } +.row-fix { min-width: 96px; display: flex; justify-content: flex-end; flex: none; } +.row-actions { display: inline-flex; align-items: center; gap: 4px; } +.platform-tiles { display: inline-flex; align-items: center; gap: 2px; flex: none; } /* 42. PlatformTile md: the app icon in a 22px bordered tile, radius/item-lg. */ .platform-tile { @@ -193,6 +247,8 @@ img { display: block; } .btn-outline:hover { background: var(--fill-hover); } .btn-ghost { color: var(--text-primary); } .btn-ghost:hover { background: var(--fill-hover); } +.btn-link { padding: 0; height: auto; color: var(--brand-default); } +.btn-link:hover { color: var(--brand-hover); } .btn:disabled { cursor: default; } .btn:focus-visible { outline: none; border-color: var(--border-focus); } .btn-primary:focus-visible { background: var(--brand-hover); } @@ -204,6 +260,7 @@ img { display: block; } .notice .icon { margin-top: 2px; } .notice-danger { color: var(--status-danger-fg); } .notice-success { color: var(--status-success-fg); } +.notice-warning { color: var(--status-warning-fg); } .notice-muted { color: var(--text-tertiary); } /* 54. Empty state: icon and what the list would hold. */ @@ -223,5 +280,7 @@ img { display: block; } @media (max-width: 420px) { .kpi { padding: 8px; } .type-metric { font-size: 16px; line-height: 24px; } - .row-fix { width: auto; } + .row-fix { min-width: 0; } + .row-secondary { display: none; } + .share-col { display: none; } } diff --git a/apps-src/src/mcp-app.tsx b/apps-src/src/mcp-app.tsx index 2515787b..1ccdd323 100644 --- a/apps-src/src/mcp-app.tsx +++ b/apps-src/src/mcp-app.tsx @@ -1,28 +1,88 @@ /** * The Zernio MCP App, on the ext-apps React hooks (the pattern of the SDK's - * basic-server-react example). Opened by the zernio_open_app tool. + * basic-server-react example), drawn in the dashboard's design system v2. + * + * Every tool in src/late/mcp/apps/tools.py opens this app on its screen and + * hands it `{view, data, args}`. The app switches screens and refreshes by + * calling those same tools, so one set of components draws everything. */ -import type { App, McpUiHostContext } from "@modelcontextprotocol/ext-apps"; +import type { McpUiHostContext } from "@modelcontextprotocol/ext-apps"; import { useApp, useHostStyles } from "@modelcontextprotocol/ext-apps/react"; -import { StrictMode, useEffect, useState } from "react"; +import { Expand } from "pixelarticons/react/Expand.js"; +import { Reload } from "pixelarticons/react/Reload.js"; +import { StrictMode, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { createRoot } from "react-dom/client"; +import { + type AccountsHealth, + type AdsData, + type AnalyticsData, + type ApprovalsData, + type CallResult, + type HomeData, + type PostsData, + type PreviewData, + type Screen, + screenOf, + TABS, + textOf, + TOOLS, + type View, + VIEW_TITLES, +} from "./api"; import { installFonts } from "./fonts"; -import { Home } from "./Home"; -import { Spinner } from "./ui"; +import { Accounts } from "./screens/Accounts"; +import { Ads } from "./screens/Ads"; +import { Analytics } from "./screens/Analytics"; +import { Approvals } from "./screens/Approvals"; +import type { ActResult, Ctx } from "./screens/context"; +import { Home } from "./screens/Home"; +import { Posts } from "./screens/Posts"; +import { Preview } from "./screens/Preview"; +import { Button, Notice, Spinner, Tabs } from "./ui"; import "./global.css"; installFonts(); +/** How long to wait for the opening tool's result before loading the screen ourselves. */ +const RESULT_GRACE_MS = 2500; + +const VIEW_OF_TOOL = Object.fromEntries(Object.entries(TOOLS).map(([view, tool]) => [tool, view])) as Record; + function ZernioApp() { const [hostContext, setHostContext] = useState(); - const [opened, setOpened] = useState(false); + const [screen, setScreen] = useState(); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(); + const [notice, setNotice] = useState(); + const toolArgs = useRef>({}); + const gotResult = useRef(false); - // useApp creates the App, lets us register handlers, then connects. - const { app, error } = useApp({ - appInfo: { name: "Zernio", version: "0.1.0" }, + const show = useCallback((result: CallResult) => { + if (result.isError) { + setError(textOf(result) || "The tool call failed."); + return; + } + const next = screenOf(result); + if (!next) { + setError("This result has no screen to show."); + return; + } + setError(undefined); + setScreen(next); + }, []); + + const { app, error: connectError } = useApp({ + appInfo: { name: "Zernio", version: "0.2.0" }, capabilities: { availableDisplayModes: ["inline", "fullscreen"] }, onAppCreated: (app) => { - app.ontoolresult = () => setOpened(true); + app.ontoolinput = ({ arguments: args }) => { + toolArgs.current = args ?? {}; + }; + app.ontoolresult = (result) => { + gotResult.current = true; + show(result); + }; + app.ontoolcancelled = () => setError("Cancelled."); app.onhostcontextchanged = (params) => setHostContext((prev) => ({ ...prev, ...params })); app.onerror = console.error; }, @@ -35,14 +95,84 @@ function ZernioApp() { if (app) setHostContext(app.getHostContext()); }, [app]); - if (error) return

    {error.message}

    ; - if (!app || !opened) return ; - return ; -} + // A screen is a newer request than the one before it: a slow answer for a + // screen the user already left is dropped. + const seq = useRef(0); + const load = useCallback( + async (view: View, args: Record = {}) => { + if (!app) return; + const mine = ++seq.current; + setLoading(true); + setNotice(undefined); + try { + const result = await app.callServerTool({ name: TOOLS[view], arguments: args }); + if (mine === seq.current) show(result); + } catch (e) { + if (mine === seq.current) setError(e instanceof Error ? e.message : String(e)); + } finally { + if (mine === seq.current) setLoading(false); + } + }, + [app, show], + ); + + // Opened without a result (from Claude's Artifacts page, or a host that + // delivers none): load the screen of the tool that opened us, else Home. + useEffect(() => { + if (!app) return; + const timer = setTimeout(() => { + if (gotResult.current) return; + const tool = app.getHostContext()?.toolInfo?.tool?.name; + const view = (tool && VIEW_OF_TOOL[tool]) || "home"; + void load(view, view === "home" ? {} : toolArgs.current); + }, RESULT_GRACE_MS); + return () => clearTimeout(timer); + }, [app, load]); -function Shell({ app, hostContext }: { app: App; hostContext?: McpUiHostContext }) { - const fullscreen = hostContext?.displayMode === "fullscreen"; + // Tell Claude what the app shows, so "these accounts" resolves to them. + useEffect(() => { + if (!app || !screen || !app.getHostCapabilities()?.updateModelContext) return; + void app.updateModelContext({ + content: [{ type: "text", text: `The Zernio app shows ${VIEW_TITLES[screen.view]}.` }], + structuredContent: { view: screen.view, args: screen.args }, + }); + }, [app, screen]); + + const ctx = useMemo(() => { + if (!app) return undefined; + return { + app, + locale: hostContext?.locale, + fullscreen: hostContext?.displayMode === "fullscreen", + navigate: (view, args) => void load(view, args), + async act(tool, args): Promise { + try { + const result = await app.callServerTool({ name: tool, arguments: args }); + return { ok: !result.isError, text: textOf(result), data: result.structuredContent }; + } catch (e) { + return { ok: false, text: e instanceof Error ? e.message : String(e) }; + } + }, + ask(text) { + void app.sendMessage({ role: "user", content: [{ type: "text", text }] }).then(({ isError }) => + setNotice(isError ? "Could not send it to Claude." : "Sent to Claude. Continue in the chat."), + ); + }, + tell(text) { + if (app.getHostCapabilities()?.updateModelContext) { + void app.updateModelContext({ content: [{ type: "text", text }] }); + } + }, + }; + }, [app, hostContext?.locale, hostContext?.displayMode, load]); + + if (connectError) return {connectError.message}; + if (!ctx) return ; + + const fullscreen = ctx.fullscreen; + const canExpand = !fullscreen && !!hostContext?.availableDisplayModes?.includes("fullscreen"); const insets = hostContext?.safeAreaInsets; + return (
    + {/* 35. The breadcrumb is the screen's title. */} Zernio + {screen && {VIEW_TITLES[screen.view]}} + + {loading && screen && } + {screen && ( + + )} + {canExpand && ( + // requestDisplayMode must run inside the click: the host refuses it otherwise. + + )} +
    - + {fullscreen && ( + ({ key, label: VIEW_TITLES[key] }))} + active={screen && TABS.includes(screen.view) ? screen.view : undefined} + onPick={(view) => ctx.navigate(view)} + /> + )} +
    + {error && {error}} + {notice && {notice}} + {screen ? : !error && } +
    ); } -function Skeleton() { +function ScreenView({ ctx, screen }: { ctx: Ctx; screen: Screen }) { + switch (screen.view) { + case "home": + return ; + case "posts": + return ; + case "analytics": + return ; + case "accounts": + return ; + case "ads": + return ; + case "preview": + return ; + case "approvals": + return ; + } +} + +function Loading() { return (
    diff --git a/apps-src/src/screens/Accounts.tsx b/apps-src/src/screens/Accounts.tsx new file mode 100644 index 00000000..acea6571 --- /dev/null +++ b/apps-src/src/screens/Accounts.tsx @@ -0,0 +1,30 @@ +/** Accounts: every connected account by health, the broken ones first. */ +import { Users } from "pixelarticons/react/Users.js"; +import { type AccountsHealth, formatNumber } from "../api"; +import { Empty, Kpis, Rows, Section } from "../ui"; +import type { Ctx } from "./context"; +import { ACCOUNT_RANK, AccountRow } from "./rows"; + +export function Accounts({ ctx, data }: { ctx: Ctx; data: AccountsHealth }) { + const summary = data.summary ?? {}; + const accounts = [...(data.accounts ?? [])].sort((a, b) => ACCOUNT_RANK[a.status] - ACCOUNT_RANK[b.status]); + const n = (v?: number) => formatNumber(v, ctx.locale); + return ( + <> + +
    + {accounts.length ? ( + {accounts.map((a) => )} + ) : ( + }>No connected accounts yet. + )} +
    + + ); +} diff --git a/apps-src/src/screens/Ads.tsx b/apps-src/src/screens/Ads.tsx new file mode 100644 index 00000000..4fe24cd4 --- /dev/null +++ b/apps-src/src/screens/Ads.tsx @@ -0,0 +1,83 @@ +/** Ads: what needs attention across the ads, most severe first, each with its fix. */ +import { Megaphone } from "pixelarticons/react/Megaphone.js"; +import { useState } from "react"; +import { type AdsAlert, type AdsData, formatNumber, platformName } from "../api"; +import { Button, Empty, Kpis, PlatformTile, Row, Rows, Section, StatusPill, type Tone } from "../ui"; +import type { Ctx } from "./context"; + +const SEVERITY: Record = { + error: { label: "Error", tone: "danger" }, + warning: { label: "Warning", tone: "warning" }, + info: { label: "Info", tone: "info" }, +}; + +export function Ads({ ctx, data }: { ctx: Ctx; data: AdsData }) { + const [dismissed, setDismissed] = useState([]); + const alerts = (data.alerts ?? []).filter((a) => !dismissed.includes(a.id)); + const counts = data.counts ?? {}; + const n = (v?: number) => formatNumber(v ?? 0, ctx.locale); + + const dismiss = async (alert: AdsAlert) => { + const result = await ctx.act("ui_dismiss_ads_alert", { alert_id: alert.id }); + if (result.ok) { + setDismissed((d) => [...d, alert.id]); + ctx.tell(`From the Zernio app the user dismissed ads alert ${alert.id} ("${alert.title}") for 30 days.`); + } + }; + + return ( + <> + +
    + {alerts.length ? ( + + {alerts.map((alert) => ( + void dismiss(alert)} /> + ))} + + ) : ( + }>Nothing needs attention in your ads. + )} +
    + + ); +} + +function AlertRow({ ctx, alert, onDismiss }: { ctx: Ctx; alert: AdsAlert; onDismiss: () => void }) { + const severity = SEVERITY[alert.severity] ?? SEVERITY.info; + const url = alert.fix?.url ? (alert.fix.url.startsWith("/") ? `https://zernio.com${alert.fix.url}` : alert.fix.url) : undefined; + const entity = alert.entity?.name ?? undefined; + return ( + : undefined} + name={alert.title} + secondary={entity} + state={} + fix={ + + {url ? ( + + ) : ( + + )} + + + } + /> + ); +} diff --git a/apps-src/src/screens/Analytics.tsx b/apps-src/src/screens/Analytics.tsx new file mode 100644 index 00000000..f0d16f23 --- /dev/null +++ b/apps-src/src/screens/Analytics.tsx @@ -0,0 +1,148 @@ +/** + * Analytics: the KPIs on one row, the picked one's daily chart in the same + * panel (20), and the platforms with each one's share as a grey bar. + */ +import { ChartLine } from "pixelarticons/react/ChartLine.js"; +import { useState } from "react"; +import { type AnalyticsData, formatDate, formatNumber, type Metrics, platformName } from "../api"; +import { Empty, Kpis, PlatformTile, Section } from "../ui"; +import type { Ctx } from "./context"; + +type Key = "impressions" | "engagement" | "views" | "posts"; + +const LABELS: Record = { + impressions: "Impressions", + engagement: "Engagement", + views: "Views", + posts: "Posts", +}; + +function engagement(m: Metrics = {}): number { + return (m.likes ?? 0) + (m.comments ?? 0) + (m.shares ?? 0) + (m.saves ?? 0); +} + +function dayValue(day: NonNullable[number], key: Key): number { + if (key === "posts") return day.postCount ?? 0; + if (key === "engagement") return engagement(day.metrics); + return day.metrics?.[key] ?? 0; +} + +export function Analytics({ ctx, data }: { ctx: Ctx; data: AnalyticsData }) { + const [key, setKey] = useState("impressions"); + const days = [...(data.dailyData ?? [])].sort((a, b) => a.date.localeCompare(b.date)); + const totals = data.totals ?? {}; + const total: Record = { + impressions: totals.impressions ?? 0, + engagement: totals.engagement ?? engagement(totals), + views: totals.views ?? 0, + posts: totals.postCount ?? 0, + }; + const n = (v: number) => formatNumber(v, ctx.locale, true); + const platforms = [...(data.platformBreakdown ?? [])].sort((a, b) => (b.impressions ?? 0) - (a.impressions ?? 0)); + const maxImpressions = Math.max(1, ...platforms.map((p) => p.impressions ?? 0)); + + return ( + <> + ({ key: k, label: LABELS[k], value: n(total[k]) }))} + selected={key} + onSelect={(k) => setKey(k as Key)} + > + {days.length ? ( + ({ date: d.date, value: dayValue(d, key) }))} + label={LABELS[key]} + locale={ctx.locale} + tall={ctx.fullscreen} + /> + ) : ( + }>No posts in this period. + )} + + {platforms.length > 0 && ( +
    + + + + + + + + + + + + {platforms.map((p) => ( + + + + + + + + ))} + +
    PlatformPostsImpressionsEngagementShare
    + {platformName(p.platform)} + {formatNumber(p.postCount, ctx.locale)}{n(p.impressions ?? 0)}{n(engagement(p))} + +
    +
    + )} + + ); +} + +/** A daily line in the panel's hue (chart/3), dashed gridlines, dates at the ends and middle. */ +function Chart({ points, label, locale, tall }: { + points: { date: string; value: number }[]; + label: string; + locale?: string; + tall: boolean; +}) { + const [hover, setHover] = useState(null); + const w = 600; + const h = tall ? 220 : 120; + const max = Math.max(1, ...points.map((p) => p.value)); + const step = points.length > 1 ? w / (points.length - 1) : 0; + const xy = points.map((p, i) => [i * step, h - (p.value / max) * (h - 8) - 4] as const); + const line = xy.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(1)} ${y.toFixed(1)}`).join(""); + const at = hover ?? points.length - 1; + const dates = [0, Math.floor((points.length - 1) / 2), points.length - 1]; + + return ( +
    +
    + {formatDate(points[at].date, locale, { weekday: "short", month: "short", day: "numeric", timeZone: "UTC" })} + {formatNumber(points[at].value, locale)} {label.toLowerCase()} +
    +
    + {formatNumber(max, locale, true)} + { + const box = e.currentTarget.getBoundingClientRect(); + setHover(Math.max(0, Math.min(points.length - 1, Math.round(((e.clientX - box.left) / box.width) * (points.length - 1))))); + }} + onPointerLeave={() => setHover(null)} + > + {[0.5, 1].map((f) => ( + + ))} + + + {hover !== null && } + +
    +
    + {dates.map((i, k) => ( + {formatDate(points[i].date, locale, { month: "short", day: "numeric", timeZone: "UTC" })} + ))} +
    +
    + ); +} diff --git a/apps-src/src/screens/Approvals.tsx b/apps-src/src/screens/Approvals.tsx new file mode 100644 index 00000000..06520c04 --- /dev/null +++ b/apps-src/src/screens/Approvals.tsx @@ -0,0 +1,114 @@ +/** Approvals: the changes an automation waits on, each request with Approve and Reject. */ +import { Clock } from "pixelarticons/react/Clock.js"; +import { useState } from "react"; +import { type Approval, type ApprovalChange, type ApprovalsData, formatDate } from "../api"; +import { Badge, Button, Empty, Notice, Row, Rows, Section, StatusPill, type Tone } from "../ui"; +import type { Ctx } from "./context"; + +const CHANGE: Record = { + "ads.pause": "Pause", + "ads.activate": "Activate", + "ads.set_budget": "Budget", + "ads.duplicate": "Duplicate", + "ads.edit_name": "Rename", + "ads.set_bid": "Bid", + "ads.set_target": "Target", + "ads.reallocate_budget": "Reallocate", +}; + +const STATE: Record = { + pending: { label: "Waiting for you", tone: "warning" }, + approved: { label: "Approved", tone: "success" }, + rejected: { label: "Rejected", tone: "muted" }, + expired: { label: "Expired", tone: "muted" }, + cancelled: { label: "Cancelled", tone: "muted" }, +}; + +function valueOf(v: ApprovalChange["previous"]): string { + if (!v) return ""; + const first = Object.values(v)[0]; + return first === undefined ? "" : String(first); +} + +export function Approvals({ ctx, data }: { ctx: Ctx; data: ApprovalsData }) { + const [approvals, setApprovals] = useState(data.approvals); + if (!approvals.length) { + return ( +
    + }>Nothing is waiting for approval. +
    + ); + } + return ( + <> + {approvals.map((approval) => ( + setApprovals((list) => list.map((a) => (a.id === next.id ? next : a)))} + /> + ))} + + ); +} + +function ApprovalPanel({ ctx, automationId, approval, onDecided }: { + ctx: Ctx; + automationId: string; + approval: Approval; + onDecided: (approval: Approval) => void; +}) { + const [busy, setBusy] = useState<"approve" | "reject" | null>(null); + const [error, setError] = useState(); + const state = STATE[approval.status]; + const pending = approval.status === "pending"; + + const decide = async (decision: "approve" | "reject") => { + setBusy(decision); + setError(undefined); + const result = await ctx.act("ui_decide_automation_approval", { automation_id: automationId, approval_id: approval.id, decision }); + const next = (result.data as { approval?: Approval } | undefined)?.approval; + setBusy(null); + if (!result.ok || !next) { + setError(result.text || "The decision did not go through."); + return; + } + onDecided(next); + ctx.tell(`From the Zernio app the user ${decision === "approve" ? "approved" : "rejected"} automation request ${approval.id} (automation ${automationId}); it is now ${next.status}.`); + }; + + return ( +
    } + > + + {approval.changes.map((change, i) => { + const from = valueOf(change.previous); + const to = valueOf(change.target); + return ( + {CHANGE[change.type] ?? change.type}} + name={change.subject?.name ?? change.subject?.id ?? "—"} + secondary={change.subject?.kind} + state={from || to ? {from} → {to} : undefined} + fix={change.status && change.status !== "pending" ? {change.status} : undefined} + /> + ); + })} + + {error && {error}} + {pending && approval.canDecide && ( +
    + + +
    + )} + {pending && !approval.canDecide && Only {approval.to?.join(", ")} can decide this.} +
    + ); +} diff --git a/apps-src/src/screens/Home.tsx b/apps-src/src/screens/Home.tsx new file mode 100644 index 00000000..e2a55fbf --- /dev/null +++ b/apps-src/src/screens/Home.tsx @@ -0,0 +1,43 @@ +/** Home: the workspace at a glance, with the way to each list. */ +import { CheckDouble } from "pixelarticons/react/CheckDouble.js"; +import { formatNumber, type HomeData } from "../api"; +import { Empty, Kpis, More, Rows, Section } from "../ui"; +import type { Ctx } from "./context"; +import { ACCOUNT_RANK, AccountRow, FailedPostRow } from "./rows"; + +export function Home({ ctx, data }: { ctx: Ctx; data: HomeData }) { + const summary = data.health.summary ?? {}; + const attention = (data.health.accounts ?? []) + .filter((a) => a.status !== "healthy") + .sort((a, b) => ACCOUNT_RANK[a.status] - ACCOUNT_RANK[b.status]); + const shown = ctx.fullscreen ? 5 : 3; + const n = (v?: number) => formatNumber(v, ctx.locale); + + return ( + <> + +
    + {attention.length ? ( + {attention.slice(0, shown).map((a) => )} + ) : ( + }>Every account can post. + )} + {attention.length > shown && ctx.navigate("accounts")} />} +
    +
    + {data.failedPosts.length ? ( + {data.failedPosts.map((p) => )} + ) : ( + }>Nothing failed to publish. + )} + {data.failedTotal > data.failedPosts.length && ctx.navigate("posts")} />} +
    + + ); +} diff --git a/apps-src/src/screens/Posts.tsx b/apps-src/src/screens/Posts.tsx new file mode 100644 index 00000000..530c17b8 --- /dev/null +++ b/apps-src/src/screens/Posts.tsx @@ -0,0 +1,18 @@ +/** Failed posts: every post that did not publish, its reason and Retry. */ +import { CheckDouble } from "pixelarticons/react/CheckDouble.js"; +import type { PostsData } from "../api"; +import { Empty, Rows, Section } from "../ui"; +import type { Ctx } from "./context"; +import { FailedPostRow } from "./rows"; + +export function Posts({ ctx, data }: { ctx: Ctx; data: PostsData }) { + return ( +
    + {data.posts.length ? ( + {data.posts.map((p) => )} + ) : ( + }>Nothing failed to publish. + )} +
    + ); +} diff --git a/apps-src/src/screens/Preview.tsx b/apps-src/src/screens/Preview.tsx new file mode 100644 index 00000000..c0eada55 --- /dev/null +++ b/apps-src/src/screens/Preview.tsx @@ -0,0 +1,103 @@ +/** + * Post preview: the post as it will go out, the account each platform reaches, + * validation, and Publish now (two steps) or Save as draft. + */ +import { Image } from "pixelarticons/react/Image.js"; +import { Video } from "pixelarticons/react/Video.js"; +import { useState } from "react"; +import { platformName, type PreviewData } from "../api"; +import { Button, Notice, PlatformTile, Row, Rows, Section, StatusPill } from "../ui"; +import type { Ctx } from "./context"; + +type Outcome = { ok: boolean; text: string }; + +export function Preview({ ctx, data }: { ctx: Ctx; data: PreviewData }) { + const [confirming, setConfirming] = useState(false); + const [busy, setBusy] = useState<"publish" | "draft" | null>(null); + const [outcome, setOutcome] = useState(); + const errors = data.validation?.errors ?? []; + const warnings = data.validation?.warnings ?? []; + const unresolved = data.targets.filter((t) => t.error); + const blocked = unresolved.length > 0 || data.validation?.valid === false; + const length = Array.from(data.content).length; + + const submit = async (mode: "publish" | "draft") => { + setBusy(mode); + setConfirming(false); + const result = await ctx.act("posts_cross_post", { ...data.request, ...(mode === "publish" ? { publish_now: true } : { is_draft: true }) }); + // posts_cross_post reports account problems as text starting with ❌. + const ok = result.ok && !result.text.trim().startsWith("❌"); + setOutcome({ ok, text: result.text }); + setBusy(null); + ctx.tell( + ok + ? `From the Zernio app the user ${mode === "publish" ? "published" : "saved as a draft"} the previewed post. ${result.text}` + : `Submitting the previewed post from the Zernio app failed. ${result.text}`, + ); + }; + + return ( + <> +
    {length} characters}> +

    {data.content}

    + {data.media.length > 0 && ( +
    + {data.media.slice(0, 4).map((m, i) => + m.type === "image" ? ( + {`Attached + ) : ( + + {m.type === "video" ? + ), + )} +
    + )} +
    + +
    + + {data.targets.map((t, i) => ( + } + name={platformName(t.platform)} + secondary={t.handle ? `@${t.handle}` : undefined} + state={t.error ? : } + fix={ + t.error ? ( + + ) : undefined + } + /> + ))} + +
    + + {errors.map((e, i) => {e.platform ? `${platformName(e.platform)}: ` : ""}{e.error})} + {warnings.map((w, i) => {w.platform ? `${platformName(w.platform)}: ` : ""}{w.warning})} + + {outcome ? ( + {outcome.text} + ) : ( +
    + {confirming ? ( + <> + + + + ) : ( + <> + + + + )} +
    + )} + + ); +} diff --git a/apps-src/src/screens/context.ts b/apps-src/src/screens/context.ts new file mode 100644 index 00000000..bb8c2963 --- /dev/null +++ b/apps-src/src/screens/context.ts @@ -0,0 +1,22 @@ +/** What every screen gets from the app: the host, navigation and actions. */ +import type { App } from "@modelcontextprotocol/ext-apps"; +import type { View } from "../api"; + +export interface ActResult { + ok: boolean; + text: string; + data?: unknown; +} + +export interface Ctx { + app: App; + locale?: string; + fullscreen: boolean; + navigate(view: View, args?: Record): void; + /** Calls a write tool for a button; the host asks the user to approve it. */ + act(tool: string, args: Record): Promise; + /** Hands a task that needs judgement to the chat, in the user's voice. */ + ask(text: string): void; + /** Tells Claude what just happened on screen, without a chat message. */ + tell(text: string): void; +} diff --git a/apps-src/src/screens/rows.tsx b/apps-src/src/screens/rows.tsx new file mode 100644 index 00000000..a13bddb2 --- /dev/null +++ b/apps-src/src/screens/rows.tsx @@ -0,0 +1,95 @@ +/** The rows several screens share: an account and a failed post. */ +import { useState } from "react"; +import { type Account, type FailedPost, formatDate, platformName } from "../api"; +import { Button, PlatformTile, PlatformTiles, Row, StatusPill, type Tone } from "../ui"; +import type { Ctx } from "./context"; + +/** 48. Green works, amber needs action, red is broken. */ +const ACCOUNT_STATE: Record = { + healthy: { label: "Healthy", tone: "success" }, + warning: { label: "Needs attention", tone: "warning" }, + error: { label: "Broken", tone: "danger" }, +}; + +export const ACCOUNT_RANK = { error: 0, warning: 1, healthy: 2 } as const; + +function accountReason(account: Account): string { + if (account.needsReconnect) return account.disconnectReason || "Needs to be reconnected"; + return account.issues?.[0] || account.disconnectReason || ""; +} + +export function AccountRow({ ctx, account }: { ctx: Ctx; account: Account }) { + const state = ACCOUNT_STATE[account.status]; + const reason = accountReason(account); + const handle = account.username ? `@${account.username}` : account.displayName; + return ( + } + name={platformName(account.platform)} + secondary={handle} + state={} + fix={ + account.needsReconnect ? ( + + ) : account.status !== "healthy" ? ( + + ) : null + } + /> + ); +} + +/** A post's name: its title, else its first line, else what it is. */ +function postName(post: FailedPost): string { + const first = post.content.split("\n").find((line) => line.trim()); + return post.title || first || "Post without text"; +} + +export function FailedPostRow({ ctx, post }: { ctx: Ctx; post: FailedPost }) { + const [state, setState] = useState<"idle" | "busy" | "queued" | string>("idle"); + const reason = post.errors.length + ? post.errors.map((e) => (post.platforms.length > 1 ? `${platformName(e.platform)}: ${e.message}` : e.message)).join("\n") + : "No error message recorded"; + + const retry = async () => { + setState("busy"); + const result = await ctx.act("posts_retry", { post_id: post.id }); + // posts_retry answers in text: ✅ when queued, ⚠️ or ❌ when not. + const ok = result.ok && result.text.trim().startsWith("✅"); + setState(ok ? "queued" : result.text || "Retry failed"); + if (ok) ctx.tell(`From the Zernio app the user queued post ${post.id} for retry.`); + }; + + return ( + } + name={postName(post)} + secondary={formatDate(post.updatedAt, ctx.app.getHostContext()?.locale)} + state={ + state === "queued" ? ( + + ) : state !== "idle" && state !== "busy" ? ( + + ) : ( + + ) + } + fix={ + state === "queued" ? null : ( + + ) + } + /> + ); +} diff --git a/apps-src/src/ui.tsx b/apps-src/src/ui.tsx index 9b49e163..8fce6f06 100644 --- a/apps-src/src/ui.tsx +++ b/apps-src/src/ui.tsx @@ -1,46 +1,72 @@ /** - * The few dashboard primitives the app needs, drawn as the product look (v2) - * draws them: Section (a panel with its grey bar), StatusPill, PlatformTile, - * Spinner (the pixel rain), Notice and Button. Numbers in comments are the - * design principles they follow (Schedule-Posts-API, design-principles.md). + * The dashboard primitives the app is built from, drawn as the product look + * (v2) draws them. Every screen uses only these, so they all read alike. + * Numbers in comments are the design principles they follow + * (Schedule-Posts-API, .claude/rules/design-principles.md). */ +import { InfoBox } from "pixelarticons/react/InfoBox.js"; import type { ButtonHTMLAttributes, ReactNode } from "react"; import { platformIcon, platformName } from "./api"; /** 18. A block is a white panel; a list's panel is headed by a grey bar with its eyebrow title. */ -export function Section({ title, actions, children }: { title: string; actions?: ReactNode; children: ReactNode }) { +export function Section({ title, count, actions, children, flush }: { + title: string; + count?: number; + actions?: ReactNode; + children: ReactNode; + /** The body runs edge to edge (a table, a chart). */ + flush?: boolean; +}) { return (
    -

    {title}

    +

    + {title} + {count !== undefined && {count}} +

    {actions &&
    {actions}
    }
    -
    {children}
    +
    {children}
    ); } -type Tone = "success" | "warning" | "danger" | "info" | "muted"; +export type Tone = "success" | "warning" | "danger" | "info" | "muted"; -/** 16, 48. A state is a filled pill in its colour, sentence case, no glyph in its text. */ -export function StatusPill({ label, tone, suffix, title }: { label: string; tone: Tone; suffix?: ReactNode; title?: string }) { +/** 16, 43, 48, 66. A state is a filled pill in its colour; its reason sits behind the info mark. */ +export function StatusPill({ label, tone, reason }: { label: string; tone: Tone; reason?: string }) { return ( - + {label} - {suffix} + {reason && } ); } +/** 16. A label that is not a state: outlined and colourless. */ +export function Badge({ children }: { children: ReactNode }) { + return {children}; +} + /** 7, 42. A platform shows as its app icon in a bordered tile (md, 22px). */ export function PlatformTile({ platform }: { platform: string }) { return ( - + {platformName(platform)} ); } +export function PlatformTiles({ platforms }: { platforms: string[] }) { + const unique = [...new Set(platforms)]; + return ( + + {unique.slice(0, 3).map((p) => )} + {unique.length > 3 && +{unique.length - 3}} + + ); +} + /** 17. Loading is a 3x3 pixel rain in the text colour, stepping between frames. */ export function Spinner({ label = "Loading" }: { label?: string }) { return ( @@ -54,23 +80,121 @@ export function Spinner({ label = "Loading" }: { label?: string }) { } /** 15. A notice is coloured text with its icon, not a box. */ -export function Notice({ tone, icon, children }: { tone: "danger" | "success" | "muted"; icon?: ReactNode; children: ReactNode }) { +export function Notice({ tone, children }: { tone: "danger" | "warning" | "success" | "muted"; children: ReactNode }) { return (

    - {icon} + {tone !== "muted" && } {children}

    ); } type ButtonProps = ButtonHTMLAttributes & { - variant?: "primary" | "outline" | "ghost"; + variant?: "primary" | "outline" | "ghost" | "link"; size?: "sm" | "md"; icon?: boolean; }; -/** Square controls, 28/32px (size/control-sm, -md); hover changes colour only (1). */ +/** Square controls, 28/32px; hover changes colour only (1); focus darkens the border (13). */ export function Button({ variant = "outline", size = "md", icon, className, ...props }: ButtonProps) { const classes = ["btn", `btn-${variant}`, `btn-${size}`, icon ? "btn-icon" : "", className ?? ""].filter(Boolean); return + ) : ( +
    +
    {item.label}
    +
    {item.value}
    +
    + ), + )} +
    + {children &&
    {children}
    } +
    + ); +} + +/** 28. Underline tabs: the active one is marked, the rest grey; hover only darkens the text. */ +export function Tabs({ items, active, onPick }: { + items: { key: K; label: string }[]; + active?: K; + onPick: (key: K) => void; +}) { + return ( + + ); +} + +/** 22, 40, 43, 44. A row is one line: lead, name with its grey secondary fact, state, then the fix. */ +export function Row({ lead, name, secondary, state, fix }: { + lead?: ReactNode; + name: ReactNode; + secondary?: ReactNode; + state?: ReactNode; + fix?: ReactNode; +}) { + return ( +
  • + {lead} +
    + {name} + {secondary && {secondary}} +
    + {state} +
    {fix}
    +
  • + ); +} + +export function Rows({ children }: { children: ReactNode }) { + return
      {children}
    ; +} + +/** 54. An empty list says what it would hold, with an icon. */ +export function Empty({ icon, children }: { icon: ReactNode; children: ReactNode }) { + return
    {icon}{children}
    ; +} + +/** A list cut short says so, with the way to the rest. */ +export function More({ label, onClick }: { label: string; onClick: () => void }) { + return ( +
    + +
    + ); +} diff --git a/src/late/mcp/apps/__init__.py b/src/late/mcp/apps/__init__.py index 5288c557..a68d11bd 100644 --- a/src/late/mcp/apps/__init__.py +++ b/src/late/mcp/apps/__init__.py @@ -1,13 +1,14 @@ -"""MCP Apps: the interactive views Claude and ChatGPT render for tool results. +"""MCP Apps: the Zernio app Claude and ChatGPT render in the chat. A trial, off unless ZERNIO_MCP_APPS=1, kept in this package so it can be -removed in one go: delete it and the apps lines in server.py. - -Each view is one self-contained HTML document under ``ui://zernio/``, built -from a template in this package plus the shared runtime.js (the host bridge) -and base.css (host theme tokens with zernio.com fallbacks). Inline scripts -and styles only, so the host can review the whole document and no CDN sits -in the render path. The show_* tools in tools.py are the views' entry points. +removed in one go: delete it, apps-src/ and the apps lines in server.py. + +One app, every screen in it: apps-src/ (Vite + React + the ext-apps SDK, +drawn in the dashboard's design system v2) builds into bundle/mcp-app.html, +committed so the Python image needs no Node. The tools in tools.py each open +it on one screen (zernio_open_app on Home, show_failed_posts on Failed posts, +...) and hand it that screen's data; the app calls the same tools to switch +screens and refresh, so every screen looks and behaves alike. """ from __future__ import annotations @@ -18,7 +19,6 @@ from fastmcp.apps import UI_MIME_TYPE, AppConfig, ResourceCSP, app_config_to_meta_dict from fastmcp.resources import TextResource -from fastmcp.tools import ToolResult from mcp.types import ToolAnnotations from starlette.responses import Response @@ -31,29 +31,35 @@ _DIR = Path(__file__).parent -# Hosts cache ui:// resources aggressively: bump on a change an old cached view +# Hosts cache ui:// resources aggressively: bump on a change an old cached app # could not handle (a new data shape, a renamed tool it calls). -_VERSION = "v1" +APP_URI = "ui://zernio/v2/app.html" -# Images in post previews come from Zernio media storage; Claude serves its -# host fonts from assets.claude.ai. Nothing else is fetched, and views reach -# the API only through the host (tools/call), so connectDomains stays empty. +# The design system's fonts, served by this server: MCP Apps take fonts only +# from origins the resource declares, never as data: URLs. The bundle names +# its origin as __ZERNIO_ORIGIN__, filled in when it is served. +_FONT_PATH = "/apps/fonts/{name}" +_FONTS = { + name: (_DIR / "fonts" / name).read_bytes() + for name in ("Geist-Variable.woff2", "GeistMono-Variable.woff2", "GeistPixel-Square.woff2") +} + +# This server (fonts), zernio.com (platform app icons, the logo), Zernio media +# storage (post previews) and Claude's host fonts. Built from MCP_PUBLIC_URL, +# so dev and prod each name themselves: a wrong origin fails silently, as a +# blocked font. The app reaches the API only through the host (tools/call), +# so connectDomains stays empty. _CSP = ResourceCSP( - resource_domains=["https://media.zernio.com", "https://assets.claude.ai"], + resource_domains=[ + MCP_PUBLIC_URL, + "https://zernio.com", + "https://media.zernio.com", + "https://assets.claude.ai", + ], ) -VIEWS = { - "overview": "Zernio overview card", - "post-preview": "Post preview", - "failed-posts": "Failed posts", - "analytics": "Analytics", - "account-health": "Account health", - "ads-alerts": "Ads alerts", - "automation-approvals": "Automation approvals", -} - # Listed up front while the trial is on. The ui_* tools are app-only: listed -# so the host lets the views call them, hidden from the model by the host. +# so the host lets the app call them, hidden from the model by the host. APP_TOOLS = [ "zernio_open_app", "show_post_preview", @@ -71,61 +77,6 @@ def apps_enabled() -> bool: return os.getenv("ZERNIO_MCP_APPS", "").lower() in ("1", "true", "yes") -def view_uri(name: str) -> str: - return f"ui://zernio/{_VERSION}/{name}.html" - - -def _html(name: str) -> str: - def read(file: str) -> str: - return (_DIR / file).read_text(encoding="utf-8") - - return ( - read(f"{name}.html") - .replace("/*ZERNIO_CSS*/", read("base.css")) - .replace("/*ZERNIO_RUNTIME*/", read("runtime.js")) - ) - - -def register_apps(mcp: FastMCP) -> None: - """Serve every view and register the tools that render them.""" - for name, title in VIEWS.items(): - mcp.add_resource( - TextResource( - uri=view_uri(name), - name=title, - mime_type=UI_MIME_TYPE, - text=_html(name), - meta={"ui": app_config_to_meta_dict(AppConfig(csp=_CSP))}, - ) - ) - register_tools(mcp, view_uri) - _replace_overview(mcp) - _register_app(mcp) - - -# The app, built from apps-src/ (Vite + React + the ext-apps SDK) into -# bundle/mcp-app.html, committed so the Python image needs no Node. It loads -# its own data through the server's tools, so the opening tool only says which -# screen to show. -APP_URI = f"ui://zernio/{_VERSION}/app.html" - -# The design system's fonts, served by this server: MCP Apps take fonts only -# from origins the resource declares, never as data: URLs. The bundle names -# its origin as __ZERNIO_ORIGIN__, filled in when it is served. -_FONT_PATH = "/apps/fonts/{name}" -_FONTS = { - name: (_DIR / "fonts" / name).read_bytes() - for name in ("Geist-Variable.woff2", "GeistMono-Variable.woff2", "GeistPixel-Square.woff2") -} - -# Its own origin (fonts) and zernio.com (platform app icons, the logo) on top -# of the views' domains. Built from MCP_PUBLIC_URL, so dev and prod each name -# themselves: a wrong origin fails silently, as a blocked font. -_APP_CSP = ResourceCSP( - resource_domains=[MCP_PUBLIC_URL, "https://zernio.com", *(_CSP.resource_domains or [])], -) - - async def _app_font(request: Request) -> Response: body = _FONTS.get(request.path_params["name"]) if body is None: @@ -142,7 +93,8 @@ async def _app_font(request: Request) -> Response: ) -def _register_app(mcp: FastMCP) -> None: +def register_apps(mcp: FastMCP) -> None: + """Serve the app and its fonts, and register the tools that open it.""" html = (_DIR / "bundle" / "mcp-app.html").read_text(encoding="utf-8") mcp.add_resource( TextResource( @@ -150,41 +102,21 @@ def _register_app(mcp: FastMCP) -> None: name="Zernio", mime_type=UI_MIME_TYPE, text=html.replace("__ZERNIO_ORIGIN__", MCP_PUBLIC_URL), - meta={"ui": app_config_to_meta_dict(AppConfig(csp=_APP_CSP))}, + meta={"ui": app_config_to_meta_dict(AppConfig(csp=_CSP))}, ) ) mcp.custom_route(_FONT_PATH, methods=["GET"])(_app_font) - - @mcp.tool( - name="zernio_open_app", - title="Open Zernio", - description=( - "Open the Zernio app in the chat: the workspace at a glance (connected " - "accounts, the ones that need attention, failed posts), with a button to " - "open it full screen. Use it when the user wants to see their Zernio " - "workspace or check on their accounts." - ), - annotations=ToolAnnotations( - title="Open Zernio", readOnlyHint=True, destructiveHint=False, openWorldHint=False - ), - app=AppConfig(resource_uri=APP_URI), - # Lists the app on Claude's Artifacts page, where people open and pin it - # without asking Claude (custom and Verified connectors only). - meta={"openai/ui": {"entrypoints": [{"type": "global"}]}}, - ) - def zernio_open_app() -> ToolResult: - return ToolResult( - content="Opened the Zernio app. The user sees it and can act there; do not repeat its contents as text.", - structured_content={"view": "home"}, - ) + register_tools(mcp, APP_URI) + _plain_overview(mcp) -def _replace_overview(mcp: FastMCP) -> None: - # resources.py's zernio_overview points at the old static card; swap it - # for the same tool on this view, which keeps its text answer. +def _plain_overview(mcp: FastMCP) -> None: + # resources.py's zernio_overview renders the old static card; while the app + # is on, the overview is text and the app is opened by zernio_open_app. from late.mcp.resources import _OVERVIEW mcp.local_provider.remove_tool("zernio_overview") + mcp.local_provider.remove_resource("ui://zernio/overview.html") @mcp.tool( name="zernio_overview", @@ -195,7 +127,6 @@ def _replace_overview(mcp: FastMCP) -> None: destructiveHint=False, openWorldHint=False, ), - app=AppConfig(resource_uri=view_uri("overview"), visibility=["model"]), ) def zernio_overview() -> str: return _OVERVIEW diff --git a/src/late/mcp/apps/account-health.html b/src/late/mcp/apps/account-health.html deleted file mode 100644 index afc8cbd2..00000000 --- a/src/late/mcp/apps/account-health.html +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - -Zernio account health - - - -
    -
    -
    - - - - diff --git a/src/late/mcp/apps/ads-alerts.html b/src/late/mcp/apps/ads-alerts.html deleted file mode 100644 index 72374cfa..00000000 --- a/src/late/mcp/apps/ads-alerts.html +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - -Zernio ads alerts - - - -
    -
    -
    - - - - diff --git a/src/late/mcp/apps/analytics.html b/src/late/mcp/apps/analytics.html deleted file mode 100644 index 0451950b..00000000 --- a/src/late/mcp/apps/analytics.html +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - -Zernio analytics - - - -
    -
    -
    - - - - diff --git a/src/late/mcp/apps/automation-approvals.html b/src/late/mcp/apps/automation-approvals.html deleted file mode 100644 index 7e5c8be7..00000000 --- a/src/late/mcp/apps/automation-approvals.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - -Zernio automation approvals - - - -
    -
    -
    - - - - diff --git a/src/late/mcp/apps/base.css b/src/late/mcp/apps/base.css deleted file mode 100644 index 6d66f1b8..00000000 --- a/src/late/mcp/apps/base.css +++ /dev/null @@ -1,110 +0,0 @@ -/* Zernio MCP App styles. Structure (text, borders, surfaces, fonts) reads the - host's MCP Apps tokens so a view sits natively in Claude or ChatGPT; each - fallback is the zernio.com value. Zernio's identity lives in the accent, - the square 4px corners and the mono uppercase labels. */ -:root { - color-scheme: light dark; - --z-accent: #eb3514; - --z-accent-hover: #cd2c0e; - --z-accent-subtle: light-dark(#fce9e5, #261614); - --z-on-accent: #fff; - --z-text: var(--color-text-primary, light-dark(#1a1a1a, #fafafa)); - --z-text-2: var(--color-text-secondary, light-dark(#525252, #d4d4d4)); - --z-text-3: var(--color-text-tertiary, light-dark(#6b6b6b, #a3a3a3)); - --z-border: var(--color-border-primary, light-dark(#e4e4e4, #202022)); - --z-border-subtle: var(--color-border-secondary, light-dark(#f2f2f2, #1b1b1d)); - --z-surface: var(--color-background-secondary, light-dark(#faf9f7, #141416)); - --z-success: var(--color-text-success, light-dark(#15803d, #4ade80)); - --z-warning: var(--color-text-warning, light-dark(#b45309, #fbbf24)); - --z-danger: var(--color-text-danger, light-dark(#c0260f, #f87171)); - --z-radius: 4px; - --z-font: var(--font-sans, "Geist", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif); - --z-mono: var(--font-mono, "Geist Mono", Menlo, Consolas, monospace); - --z-tap: 32px; -} -:root[data-theme="light"] { color-scheme: light; } -:root[data-theme="dark"] { color-scheme: dark; } -:root[data-touch] { --z-tap: 44px; } - -* { box-sizing: border-box; } -html, body { margin: 0; background: transparent; } -body { - padding: calc(12px + var(--safe-top, 0px)) calc(12px + var(--safe-right, 0px)) - calc(12px + var(--safe-bottom, 0px)) calc(12px + var(--safe-left, 0px)); - font: 14px/1.45 var(--z-font); - color: var(--z-text); - -webkit-font-smoothing: antialiased; -} -button { font: inherit; } -:focus-visible { outline: 2px solid var(--z-accent); outline-offset: 2px; } - -.eyebrow { - display: flex; align-items: center; gap: 6px; - margin: 0 0 8px; - font: 500 11px/1 var(--z-mono); - letter-spacing: 0.06em; text-transform: uppercase; - color: var(--z-text-3); -} -.eyebrow .mark { width: 8px; height: 8px; border-radius: 2px; background: var(--z-accent); } -h1 { margin: 0 0 4px; font-size: 16px; font-weight: 600; line-height: 1.3; } -.muted { color: var(--z-text-2); } -.small { font-size: 12px; color: var(--z-text-3); } - -.card { - border: 1px solid var(--z-border); - border-radius: var(--z-radius); - padding: 12px; -} -.row { display: flex; align-items: center; gap: 8px; } -.wrap { flex-wrap: wrap; } -.grow { flex: 1; min-width: 0; } -.stack > * + * { margin-top: 10px; } -.divided > * + * { border-top: 1px solid var(--z-border-subtle); } - -.chip { - display: inline-flex; align-items: center; gap: 6px; - height: 24px; padding: 0 8px; - border: 1px solid var(--z-border); border-radius: var(--z-radius); - font-size: 12px; color: var(--z-text-2); white-space: nowrap; -} -.dot { width: 6px; height: 6px; border-radius: 50%; background: var(--z-text-3); flex: none; } -.dot.ok { background: var(--z-success); } -.dot.warn { background: var(--z-warning); } -.dot.bad { background: var(--z-danger); } -.dot.brand { background: var(--z-accent); } - -.actions { display: flex; gap: 8px; margin-top: 12px; } -.btn { - min-height: var(--z-tap); padding: 0 14px; - border: 1px solid var(--z-border); border-radius: var(--z-radius); - background: transparent; color: var(--z-text); - font-size: 13px; font-weight: 500; cursor: pointer; -} -.btn:hover { background: var(--z-surface); } -.btn.primary { background: var(--z-accent); border-color: var(--z-accent); color: var(--z-on-accent); } -.btn.primary:hover { background: var(--z-accent-hover); border-color: var(--z-accent-hover); } -.btn.small { min-height: 28px; padding: 0 10px; font-size: 12px; } -:root[data-touch] .btn.small { min-height: 44px; } -.btn[disabled] { opacity: 0.5; cursor: default; } - -.notice { - padding: 8px 10px; border-radius: var(--z-radius); - border-left: 2px solid var(--z-text-3); - background: var(--z-surface); font-size: 13px; -} -.notice.ok { border-left-color: var(--z-success); } -.notice.warn { border-left-color: var(--z-warning); } -.notice.bad { border-left-color: var(--z-danger); } - -.num { font-variant-numeric: tabular-nums; } -.clamp { display: -webkit-box; -webkit-box-orient: vertical; overflow: hidden; } - -.skeleton { display: grid; gap: 8px; } -.skeleton i { - display: block; height: 12px; border-radius: 2px; - background: linear-gradient(90deg, var(--z-border-subtle), var(--z-border), var(--z-border-subtle)); - background-size: 200% 100%; - animation: shimmer 1.4s ease-in-out infinite; -} -@keyframes shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } } -@media (prefers-reduced-motion: reduce) { .skeleton i { animation: none; } } diff --git a/src/late/mcp/apps/bundle/mcp-app.html b/src/late/mcp/apps/bundle/mcp-app.html index 6d9ce5b1..dc09e235 100644 --- a/src/late/mcp/apps/bundle/mcp-app.html +++ b/src/late/mcp/apps/bundle/mcp-app.html @@ -105,7 +105,7 @@ - omitted: host decides border`)}),R({method:U(`ui/request-display-mode`),params:R({mode:Eh.describe(`The display mode being requested.`)})});var Uh=R({mode:Eh.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),Wh=B([U(`model`),U(`app`)]).describe(`Tool visibility scope - who can access the tool.`);R({resourceUri:N().optional(),visibility:L(Wh).optional().describe(`Who can access this tool. Default: ["model", "app"] - "model": Tool visible to and callable by the agent - "app": Tool callable by the app from this server only`),csp:vc().optional(),permissions:vc().optional()}),R({mimeTypes:L(N()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),R({method:U(`ui/download-file`),params:R({contents:L(B([Wu,Gu])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),R({method:U(`ui/message`),params:R({role:U(`user`).describe(`Message role, currently only "user" is supported.`),content:L(Ku).describe(`Message content blocks (text, image, etc.).`)})}),R({method:U(`ui/notifications/sandbox-resource-ready`),params:R({html:N().describe(`HTML content to load into the inner iframe.`),sandbox:N().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:jh.optional().describe(`CSP configuration from resource metadata.`),permissions:Mh.optional().describe(`Sandbox permissions from resource metadata.`)})});var Gh=R({method:U(`ui/notifications/tool-result`),params:Qu.describe(`Standard MCP tool execution result.`)}),Kh=R({toolInfo:R({id:Dl.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Y.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Th.optional().describe(`Current color theme preference.`),styles:Lh.optional().describe(`Style configuration for theming the app.`),displayMode:Eh.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:L(Eh).optional().describe(`Display modes the host supports.`),containerDimensions:B([R({height:P().describe(`Fixed container height in pixels.`)}),R({maxHeight:B([P(),dc()]).optional().describe(`Maximum container height in pixels.`)})]).and(B([R({width:P().describe(`Fixed container width in pixels.`)}),R({maxWidth:B([P(),dc()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other -container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:N().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:N().optional().describe(`User's timezone in IANA format.`),userAgent:N().optional().describe(`Host application identifier.`),platform:B([U(`web`),U(`desktop`),U(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:R({touch:F().optional().describe(`Whether the device supports touch input.`),hover:F().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:R({top:P().describe(`Top safe area inset in pixels.`),right:P().describe(`Right safe area inset in pixels.`),bottom:P().describe(`Bottom safe area inset in pixels.`),left:P().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),qh=R({method:U(`ui/notifications/host-context-changed`),params:Kh.describe(`Partial context update containing only changed fields.`)});R({method:U(`ui/update-model-context`),params:R({content:L(Ku).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:V(N(),I().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),R({method:U(`ui/initialize`),params:R({appInfo:Bl.describe(`App identification (name and version).`),appCapabilities:Hh.describe(`Features and capabilities this app provides.`),protocolVersion:N().describe(`Protocol version this app supports.`)})});var Jh=R({protocolVersion:N().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Bl.describe(`Host application identification and version.`),hostCapabilities:Vh.describe(`Features and capabilities provided by the host.`),hostContext:Kh.describe(`Rich context about the host environment.`)}).passthrough(),Yh={target:`draft-2020-12`};async function Xh(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](Yh);throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function Zh(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function Qh(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function $h(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function eg(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}function tg(e,t){let n={...e,...t};return t.experimental!==void 0&&(n.experimental={...e.experimental,...t.experimental}),t.tools!==void 0&&(n.tools={...e.tools,...t.tools}),n}var ng=class e extends $m{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new vh;_methods=new yh;setRequestHandler=(...e)=>{let[t,...n]=xh(`request`,e)??e;this._methods.claim(t,`setRequestHandler`),super.setRequestHandler.call(this,t,...n)};setNotificationHandler=(...e)=>{let[t,...n]=xh(`notification`,e)??e;this._methods.claim(t,`setNotificationHandler`),super.setNotificationHandler.call(this,t,...n)};removeRequestHandler=e=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=e=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Nh,toolinputpartial:Ph,toolresult:Gh,toolcancelled:Fh,hostcontextchanged:qh};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},t=>{let n=t;e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...n}),this._events.dispatch(e,n)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,n){t&&n&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._appCapabilities=t,this.options=n,this._methods.replace(`notifications/cancelled`),this._methods.replace(`notifications/progress`),n.allowUnsafeEval||rt({jitless:!0}),this.replaceRequestHandler(`ping`,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._appCapabilities=tg(this._appCapabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._appCapabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Zh(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Zh(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Xh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Xh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(`ui/resource-teardown`,{params:Rh.shape.params,result:zh},(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(`tools/call`,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(`tools/list`,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized(`createSamplingMessage`),await this.request({method:`sampling/createMessage`,params:e},t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Ah,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Pl,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Oh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},kh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},Uh,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new wh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1;try{await super.connect(e);let n=await this.request({method:`ui/initialize`,params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:Ch}},Jh,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);this._hostCapabilities=n.hostCapabilities,this._hostInfo=n.hostInfo,this._hostContext=n.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function rg({appInfo:e,capabilities:t,onAppCreated:n,autoResize:i=!0,strict:a}){let[o,s]=(0,r.useState)(null),[c,l]=(0,r.useState)(!1),[u,d]=(0,r.useState)(null);return(0,r.useEffect)(()=>{let r=!0,o;async function c(){try{let c=new wh(window.parent,window.parent);if(o=new ng(e,t,{autoResize:i,strict:a}),n?.(o),await o.connect(c),!r){o.close();return}s(o),l(!0),d(null)}catch(e){r&&(s(null),l(!1),d(e instanceof Error?e:Error(`Failed to connect`)))}}return c(),()=>{r=!1,o?.close()}},[]),{app:o,isConnected:c,error:u}}function ig(e,t){let n=(0,r.useRef)(!1);(0,r.useEffect)(()=>{n.current||(t?.theme&&Qh(t.theme),t?.styles?.variables&&$h(t.styles.variables),(t?.theme||t?.styles?.variables)&&(n.current=!0))},[t]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.theme&&Qh(e.theme),e.styles?.variables&&$h(e.styles.variables)};return e.addEventListener(`hostcontextchanged`,t),()=>e.removeEventListener(`hostcontextchanged`,t)},[e])}function ag(e,t){let n=(0,r.useRef)(!1);(0,r.useEffect)(()=>{n.current||t?.styles?.css?.fonts&&(eg(t.styles.css.fonts),n.current=!0)},[t]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.styles?.css?.fonts&&eg(e.styles.css.fonts)};return e.addEventListener(`hostcontextchanged`,t),()=>e.removeEventListener(`hostcontextchanged`,t)},[e])}function og(e,t){ig(e,t),ag(e,t)}var sg=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,te||(te=!0,oe());else{var t=n(l);t!==null&&le(ee,t.startTime-e)}}}var te=!1,ne=-1,re=5,x=-1;function ie(){return g?!0:!(e.unstable_now()-xt&&ie());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&le(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?oe():te=!1}}}var oe;if(typeof y==`function`)oe=function(){y(ae)};else if(typeof MessageChannel<`u`){var se=new MessageChannel,ce=se.port2;se.port1.onmessage=ae,oe=function(){ce.postMessage(null)}}else oe=function(){_(ae,0)};function le(t,n){ne=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(ne),ne=-1):h=!0,le(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,te||(te=!0,oe()))),r},e.unstable_shouldYield=ie,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),cg=e(((e,t)=>{t.exports=sg()})),lg=e((e=>{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=lg()})),dg=e((e=>{var t=cg(),r=n(),i=ug();function a(e){var t=`https://react.dev/errors/`+e;if(1Oe||(e.current=De[Oe],De[Oe]=null,Oe--)}function T(e,t){Oe++,De[Oe]=e.current,e.current=t}var je=ke(null),Me=ke(null),Ne=ke(null),Pe=ke(null);function Fe(e,t){switch(T(Ne,t),T(Me,e),T(je,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?up(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=up(t),e=dp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}Ae(je),T(je,e)}function Ie(){Ae(je),Ae(Me),Ae(Ne)}function Le(e){var t=e.memoizedState;t!==null&&(oh._currentValue=t.memoizedState,T(Pe,e)),t=je.current;var n=dp(t,e.type);t!==n&&(T(Me,e),T(je,n))}function Re(e){Me.current===e&&(Ae(je),Ae(Me)),Pe.current===e&&(Ae(Pe),oh._currentValue=Ee)}var ze,Be;function Ve(e){if(ze===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ze=t&&t[1]||``,Be=-1{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function Qh(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function $h(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}function eg(e){if(document.getElementById(`__mcp-host-fonts`))return;let t=document.createElement(`style`);t.id=`__mcp-host-fonts`,t.textContent=e,document.head.appendChild(t)}function tg(e,t){let n={...e,...t};return t.experimental!==void 0&&(n.experimental={...e.experimental,...t.experimental}),t.tools!==void 0&&(n.tools={...e.tools,...t.tools}),n}var ng=class e extends $m{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new vh;_methods=new yh;setRequestHandler=(...e)=>{let[t,...n]=xh(`request`,e)??e;this._methods.claim(t,`setRequestHandler`),super.setRequestHandler.call(this,t,...n)};setNotificationHandler=(...e)=>{let[t,...n]=xh(`notification`,e)??e;this._methods.claim(t,`setNotificationHandler`),super.setNotificationHandler.call(this,t,...n)};removeRequestHandler=e=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=e=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Nh,toolinputpartial:Ph,toolresult:Gh,toolcancelled:Fh,hostcontextchanged:qh};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},t=>{let n=t;e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...n}),this._events.dispatch(e,n)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,n){t&&n&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._appCapabilities=t,this.options=n,this._methods.replace(`notifications/cancelled`),this._methods.replace(`notifications/progress`),n.allowUnsafeEval||rt({jitless:!0}),this.replaceRequestHandler(`ping`,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._appCapabilities=tg(this._appCapabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._appCapabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Zh(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Zh(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._appCapabilities.tools&&!this.transport&&this.registerAppCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Xh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Xh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(`ui/resource-teardown`,{params:Rh.shape.params,result:zh},(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(`tools/call`,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(`tools/list`,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized(`createSamplingMessage`),await this.request({method:`sampling/createMessage`,params:e},t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Ah,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},Pl,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Oh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},kh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},Uh,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new wh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1;try{await super.connect(e);let n=await this.request({method:`ui/initialize`,params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:Ch}},Jh,t);if(n===void 0)throw Error(`Server sent invalid initialize result: ${n}`);this._hostCapabilities=n.hostCapabilities,this._hostInfo=n.hostInfo,this._hostContext=n.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function rg({appInfo:e,capabilities:t,onAppCreated:n,autoResize:i=!0,strict:a}){let[o,s]=(0,r.useState)(null),[c,l]=(0,r.useState)(!1),[u,d]=(0,r.useState)(null);return(0,r.useEffect)(()=>{let r=!0,o;async function c(){try{let c=new wh(window.parent,window.parent);if(o=new ng(e,t,{autoResize:i,strict:a}),n?.(o),await o.connect(c),!r){o.close();return}s(o),l(!0),d(null)}catch(e){r&&(s(null),l(!1),d(e instanceof Error?e:Error(`Failed to connect`)))}}return c(),()=>{r=!1,o?.close()}},[]),{app:o,isConnected:c,error:u}}function ig(e,t){let n=(0,r.useRef)(!1);(0,r.useEffect)(()=>{n.current||(t?.theme&&Qh(t.theme),t?.styles?.variables&&$h(t.styles.variables),(t?.theme||t?.styles?.variables)&&(n.current=!0))},[t]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.theme&&Qh(e.theme),e.styles?.variables&&$h(e.styles.variables)};return e.addEventListener(`hostcontextchanged`,t),()=>e.removeEventListener(`hostcontextchanged`,t)},[e])}function ag(e,t){let n=(0,r.useRef)(!1);(0,r.useEffect)(()=>{n.current||t?.styles?.css?.fonts&&(eg(t.styles.css.fonts),n.current=!0)},[t]),(0,r.useEffect)(()=>{if(!e)return;let t=e=>{e.styles?.css?.fonts&&eg(e.styles.css.fonts)};return e.addEventListener(`hostcontextchanged`,t),()=>e.removeEventListener(`hostcontextchanged`,t)},[e])}function og(e,t){ig(e,t),ag(e,t)}var sg=e=>(0,r.createElement)(`svg`,Object.assign({viewBox:`0 0 24 24`,width:`24`,height:`24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`},e),(0,r.createElement)(`path`,{d:`M4 13h16v-2H4zm7-8h2V3h-2zM9 7h4V5H9zm4 0h2V5h-2zm2 2h2V7h-2zM7 9h8V7H7zm4 10h2v2h-2zm-2-2h4v2H9zm4 0h2v2h-2zm2-2h2v2h-2zm-8 0h8v2H7z`})),cg=e=>(0,r.createElement)(`svg`,Object.assign({viewBox:`0 0 24 24`,width:`24`,height:`24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`},e),(0,r.createElement)(`path`,{d:`M16 4h2v6h-2zm-2-2h2v2h-2zm0 2h2v8h-2zM4 8H2v5h2z`}),(0,r.createElement)(`path`,{d:`M4 6h16v2H4zm4 14H6v-6h2zm2 2H8v-2h2zm0-2H8v-8h2zm10-4h2v-5h-2z`}),(0,r.createElement)(`path`,{d:`M20 18H4v-2h16z`})),lg=e((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function ee(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,te||(te=!0,oe());else{var t=n(l);t!==null&&le(ee,t.startTime-e)}}}var te=!1,ne=-1,re=5,x=-1;function ie(){return g?!0:!(e.unstable_now()-xt&&ie());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&le(ee,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?oe():te=!1}}}var oe;if(typeof y==`function`)oe=function(){y(ae)};else if(typeof MessageChannel<`u`){var se=new MessageChannel,ce=se.port2;se.port1.onmessage=ae,oe=function(){ce.postMessage(null)}}else oe=function(){_(ae,0)};function le(t,n){ne=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(ne),ne=-1):h=!0,le(ee,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,te||(te=!0,oe()))),r},e.unstable_shouldYield=ie,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ug=e(((e,t)=>{t.exports=lg()})),dg=e((e=>{var t=n();function r(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=dg()})),pg=e((e=>{var t=ug(),r=n(),i=fg();function a(e){var t=`https://react.dev/errors/`+e;if(1Oe||(e.current=De[Oe],De[Oe]=null,Oe--)}function T(e,t){Oe++,De[Oe]=e.current,e.current=t}var je=ke(null),Me=ke(null),Ne=ke(null),Pe=ke(null);function Fe(e,t){switch(T(Ne,t),T(Me,e),T(je,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?up(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=up(t),e=dp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}Ae(je),T(je,e)}function Ie(){Ae(je),Ae(Me),Ae(Ne)}function Le(e){var t=e.memoizedState;t!==null&&(oh._currentValue=t.memoizedState,T(Pe,e)),t=je.current;var n=dp(t,e.type);t!==n&&(T(Me,e),T(je,n))}function Re(e){Me.current===e&&(Ae(je),Ae(Me)),Pe.current===e&&(Ae(Pe),oh._currentValue=Ee)}var ze,Be;function Ve(e){if(ze===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ze=t&&t[1]||``,Be=-1)`:-1`)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{He=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ve(n):``}function We(e,t){switch(e.tag){case 26:case 27:case 5:return Ve(e.type);case 16:return Ve(`Lazy`);case 13:return e.child!==t&&t!==null?Ve(`Suspense Fallback`):Ve(`Suspense`);case 19:return Ve(`SuspenseList`);case 0:case 15:return Ue(e.type,!1);case 11:return Ue(e.type.render,!1);case 1:return Ue(e.type,!0);case 31:return Ve(`Activity`);case 30:return Ve(`ViewTransition`);default:return``}}function Ge(e){try{var t=``,n=null;do t+=We(e,n),n=e,e=e.return;while(e);return t}catch(e){return` Error generating stack: `+e.message+` `+e.stack}}var E=Object.prototype.hasOwnProperty,Ke=t.unstable_scheduleCallback,qe=t.unstable_cancelCallback,Je=t.unstable_shouldYield,Ye=t.unstable_requestPaint,Xe=t.unstable_now,Ze=t.unstable_getCurrentPriorityLevel,Qe=t.unstable_ImmediatePriority,$e=t.unstable_UserBlockingPriority,D=t.unstable_NormalPriority,et=t.unstable_LowPriority,tt=t.unstable_IdlePriority,nt=t.log,rt=t.unstable_setDisableYieldValue,it=null,at=null;function ot(e){if(typeof nt==`function`&&rt(e),at&&typeof at.setStrictMode==`function`)try{at.setStrictMode(it,e)}catch{}}var st=Math.clz32?Math.clz32:ut,ct=Math.log,lt=Math.LN2;function ut(e){return e>>>=0,e===0?32:31-(ct(e)/lt|0)|0}var dt=256,ft=262144,pt=4194304;function mt(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function ht(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=mt(n))):i=mt(o):i=mt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=mt(n))):i=mt(o)):i=mt(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function gt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function _t(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0n;n++)t.push(e);return t}function xt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function St(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0=xr),wr=` `,Tr=!1;function Er(e,t){switch(e){case`keyup`:return yr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Dr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Or=!1;function kr(e,t){switch(e){case`compositionend`:return Dr(t);case`keypress`:return t.which===32?(Tr=!0,wr):null;case`textInput`:return e=t.data,e===wr&&Tr?null:e;default:return null}}function Ar(e,t){if(Or)return e===`compositionend`||!br&&Er(e,t)?(e=Hn(),Vn=Bn=zn=null,Or=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=$r(n)}}function ti(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ti(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ni(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Qr(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Qr(e.document)}return t}function ri(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var ii=In&&`documentMode`in document&&11>=document.documentMode,ai=null,oi=null,si=null,ci=!1;function li(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ci||ai==null||ai!==Qr(r)||(r=ai,`selectionStart`in r&&ri(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),si&&Zr(si,r)||(si=r,r=qf(oi,`onSelect`),0>=o,i-=o,aa=1<<32-st(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),k&&sa(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),k&&sa(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return k&&sa(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&(_=v.alternate,_!==null&&h.delete(_.key===null?g:_.key)),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),k&&sa(i,g),u}function _(e,r,o,c){if(typeof o==`object`&&o&&o.type===se&&o.key===null&&o.props.ref===void 0&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case ae:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===se){if(r.tag===7){n(e,r.sibling),c=i(r,o.props.children),_o(c,o),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===he&&lo(l)===r.type){n(e,r.sibling),c=i(r,o.props),_o(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===se?(c=Ki(o.props.children,e.mode,c,o.key),_o(c,o),c.return=e,e=c):(c=Gi(o.type,o.key,o.props,null,e.mode,c),_o(c,o),c.return=e,e=c)}return s(e);case oe:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=i(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=Yi(o,e.mode,c),c.return=e,e=c}return s(e);case he:return o=lo(o),_(e,r,o,c)}if(Te(o))return h(e,r,o,c);if(Se(o)){if(l=Se(o),typeof l!=`function`)throw Error(a(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return _(e,r,go(o),c);if(o.$$typeof===de)return _(e,r,Fa(e,o),c);vo(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=i(r,o),c.return=e,e=c):(n(e,r),c=qi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{ho=0;var i=_(e,t,n,r);return mo=null,i}catch(t){if(t===ro||t===ao)throw t;var a=Vi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var bo=yo(!0),xo=yo(!1),So=!1;function Co(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function wo(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function To(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Eo(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,J&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Ri(e),Li(e,null,n),t}return Pi(e,r,t,n),Ri(e)}function Do(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,wt(e,n)}}function Oo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n}else e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var ko=!1;function Ao(){if(ko){var e=A;if(e!==null)throw e}}function jo(e,t,n,r){ko=!1;var i=e.updateQueue;So=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(X&f)===f:(r&f)===f){f!==0&&f===Ja&&(ko=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,h=s;f=t;var g=n;switch(h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(g,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(g,d,f):m,f==null)break a;d=x({},d,f);break a;case 2:So=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),id|=o,e.lanes=o,e.memoizedState=d}}function Mo(e,t){if(typeof e!=`function`)throw Error(a(191,e));e.call(t)}function No(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=C.T,s={};s.types=o===null?null:o.types,C.T=s,gc(e,!1,t,n);try{var c=i(),l=C.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?hc(e,t,Za(c,r),kd(e)):hc(e,t,r,kd(e))}catch(n){hc(e,t,{then:function(){},status:`rejected`,reason:n},kd())}finally{w.p=a,o!==null&&s.types!==null&&(o.types=s.types),C.T=o}}function P(){}function sc(e,t,n,r){if(e.tag!==5)throw Error(a(476));var i=cc(e).queue;oc(e,i,t,Ee,n===null?P:function(){return lc(e),n(r)})}function cc(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:Ee,baseState:Ee,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:bs,lastRenderedState:Ee},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:bs,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function lc(e){var t=cc(e);t.next===null&&(t=e.alternate.memoizedState),hc(e,t.next.queue,{},kd())}function F(){return Pa(oh)}function uc(){return hs().memoizedState}function dc(){return hs().memoizedState}function fc(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=kd();e=To(n);var r=Eo(t,e,n);r!==null&&(Md(r,t,n),Do(r,t,n)),t={cache:Va()},e.payload=t;return}t=t.return}}function pc(e,t,n){var r=kd();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},I(e)?_c(t,n):(n=Fi(e,t,n,r),n!==null&&(Md(n,e,r),vc(n,t,r)))}function mc(e,t,n){hc(e,t,n,kd())}function hc(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(I(e))_c(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Xr(s,o))return Pi(e,t,i,0),Xu===null&&Ni(),!1}catch{}if(n=Fi(e,t,i,r),n!==null)return Md(n,e,r),vc(n,t,r),!0}return!1}function gc(e,t,n,r){if(r={lane:2,revertLane:Nf(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},I(e)){if(t)throw Error(a(479))}else t=Fi(e,n,r,2),t!==null&&Md(t,e,2)}function I(e){var t=e.alternate;return e===j||t!==null&&t===j}function _c(e,t){$o=Qo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function vc(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,wt(e,n)}}var yc={readContext:Pa,use:vs,useCallback:as,useContext:as,useEffect:as,useImperativeHandle:as,useLayoutEffect:as,useInsertionEffect:as,useMemo:as,useReducer:as,useRef:as,useState:as,useDebugValue:as,useDeferredValue:as,useTransition:as,useSyncExternalStore:as,useId:as,useHostTransitionStatus:as,useFormState:as,useActionState:as,useOptimistic:as,useMemoCache:as,useCacheRefresh:as,useEffectEvent:as},L={readContext:Pa,use:vs,useCallback:function(e,t){return ms().memoizedState=[e,t===void 0?null:t],e},useContext:Pa,useEffect:qs,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Gs(4194308,4,$s.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Gs(4194308,4,e,t)},useInsertionEffect:function(e,t){Gs(4,2,e,t)},useMemo:function(e,t){var n=ms();t=t===void 0?null:t;var r=e();if(es){ot(!0);try{e()}finally{ot(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ms();if(n!==void 0){var i=n(t);if(es){ot(!0);try{n(t)}finally{ot(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=pc.bind(null,j,e),[r.memoizedState,e]},useRef:function(e){var t=ms();return e={current:e},t.memoizedState=e},useState:function(e){e=As(e);var t=e.queue,n=mc.bind(null,j,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:tc,useDeferredValue:function(e,t){return ic(ms(),e,t)},useTransition:function(){var e=As(!1);return e=oc.bind(null,j,e.queue,!0,!1),ms().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=j,i=ms();if(k){if(n===void 0)throw Error(a(407));n=n()}else{if(n=t(),Xu===null)throw Error(a(349));X&127||Ts(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,qs(Ds.bind(null,r,o,e),[e]),r.flags|=2048,Us(9,{destroy:void 0},Es.bind(null,r,o,n,t),null),n},useId:function(){var e=ms(),t=Xu.identifierPrefix;if(k){var n=oa,r=aa;n=(r&~(1<<32-st(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=ts++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(i,{is:r.is}):s.createElement(i)}}o[jt]=t,o[Mt]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(np(o,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&ul(t)}}return G(t),t.subtreeFlags&=-33554433,dl(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&ul(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(a(166));if(e=Ne.current,ba(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=fa,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[jt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||$f(e.nodeValue,n)),e||_a(t,!0)}else e=lp(e).createTextNode(r),e[jt]=t,t.stateNode=e}return G(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=ba(t),n!==null){if(e===null){if(!r)throw Error(a(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(a(557));e[jt]=t}else xa(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;G(t),e=!1}else n=Sa(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Go(t),t):(Go(t),null);if(t.flags&128)throw Error(a(558))}return G(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=ba(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(a(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(a(317));i[jt]=t}else xa(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;G(t),i=!1}else i=Sa(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(Go(t),t):(Go(t),null)}return Go(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),pl(t,t.updateQueue),G(t),null);case 4:return Ie(),e===null&&Uf(t.stateNode.containerInfo),t.flags|=67108864,G(t),null;case 10:return Oa(t.type),G(t),null;case 19:if(Jo(t),r=t.memoizedState,r===null)return G(t),null;if(i=!!(t.flags&128),o=r.rendering,o===null){if(i)ml(r,!1);else{if(rd!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=Yo(e),o!==null){for(t.flags|=128,ml(r,!1),e=o.updateQueue,t.updateQueue=e,pl(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Wi(n,e),n=n.sibling;return qo(t,Ko.current&1|2),k&&sa(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Xe()>md&&(t.flags|=128,i=!0,ml(r,!1),t.lanes=4194304)}}else{if(!i){if(e=Yo(o),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,pl(t,e),ml(r,!0),r.tail===null&&r.tailMode!==`collapsed`&&r.tailMode!==`visible`&&!o.alternate&&!k)return G(t),null}else 2*Xe()-r.renderingStartTime>md&&n!==536870912&&(t.flags|=128,i=!0,ml(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}if(r.tail!==null){e=r.tail;a:{for(n=e;n!==null;){if(n.alternate!==null){n=!1;break a}n=n.sibling}n=!0}return r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Xe(),e.sibling=null,o=Ko.current,o=i?o&1|2:o&1,r.tailMode===`visible`||r.tailMode===`collapsed`||!n||k?qo(t,o):(n=o,T(zo,t),T(Ko,n),Bo===null&&(Bo=t)),k&&sa(t,r.treeForkCount),e}return G(t),null;case 22:case 23:return Go(t),Ro(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(G(t),t.subtreeFlags&6&&(t.flags|=8192)):G(t),n=t.updateQueue,n!==null&&pl(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&Ae($a),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Oa(Ba),G(t),null;case 25:return null;case 30:return t.flags|=33554432,G(t),null}throw Error(a(156,t.tag))}function gl(e,t){switch(ua(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Oa(Ba),Ie(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Re(t),null;case 31:if(t.memoizedState!==null){if(Go(t),t.alternate===null)throw Error(a(340));xa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Go(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(a(340));xa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Jo(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return Ie(),null;case 10:return Oa(t.type),null;case 22:case 23:return Go(t),Ro(),e!==null&&Ae($a),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Oa(Ba),null;case 25:return null;default:return null}}function _l(e,t){switch(ua(t),t.tag){case 3:Oa(Ba),Ie();break;case 26:case 27:case 5:Re(t);break;case 4:Ie();break;case 31:t.memoizedState!==null&&Go(t);break;case 13:Go(t);break;case 19:Jo(t);break;case 10:Oa(t.type);break;case 22:case 23:Go(t),Ro(),e!==null&&Ae($a);break;case 24:Oa(Ba)}}function vl(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){ff(t,t.return,e)}}function yl(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){ff(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){ff(t,t.return,e)}}function bl(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{No(t,n)}catch(t){ff(e,e.return,t)}}}function xl(e,t,n){n.props=Cc(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){ff(e,t,n)}}function Sl(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:var i=e.stateNode,a=Ei(e.memoizedProps,i);(i.ref===null||i.ref.name!==a)&&(i.ref=Np(a)),r=i.ref;break;case 7:if(e.stateNode===null){var o=new Pp(e);p(e.child,!1,Zp,o,void 0,void 0),e.stateNode=o}r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){ff(e,t,n)}}function K(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){ff(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){ff(e,t,n)}else n.current=null}}function Cl(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var n=0;n title`))),np(r,t,n),r[jt]=e,Gt(r),t=r;break a;case`link`:if(o=Wm(`link`,`href`,i).get(t+(n.href||``))){for(s=0;sg&&(o=g,g=h,h=o);var _=ei(s,h),v=ei(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,C.T=null,n=Sd,Sd=null;var o=vd,s=bd;if(_d=0,yd=vd=null,bd=0,J&6)throw Error(a(331));var c=J;if(J|=4,Gu(o.current),Lu(o,o.current,s,n),J=c,Ef(0,!1),at&&typeof at.onPostCommitFiberRoot==`function`)try{at.onPostCommitFiberRoot(it,o)}catch{}return!0}finally{w.p=i,C.T=r,cf(e,t)}}function df(e,t,n){t=Zi(n,t),t=H(e.stateNode,t,2),e=Eo(e,t,2),e!==null&&(xt(e,2),Tf(e))}function ff(e,t,n){if(e.tag===3)df(e,e,n);else for(;t!==null;){if(t.tag===3){df(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(gd===null||!gd.has(r))){e=Zi(n,e),n=Oc(2),r=Eo(t,n,2),r!==null&&(U(n,r,t,e),xt(r,2),Tf(r));break}}t=t.return}}function pf(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Yu;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(td=!0,i.add(n),e=mf.bind(null,e,t,n),t.then(e,e))}function mf(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Xu===e&&(X&n)===n&&(rd===4||rd===3&&(X&62914560)===X&&300>Xe()-fd?J&2?od|=n:zd(e,0):od|=n,cd===X&&(cd=0)),Tf(e)}function hf(e,t){t===0&&(t=yt()),e=Ii(e,t),e!==null&&(xt(e,t),Tf(e))}function gf(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),hf(e,n)}function _f(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}r!==null&&r.delete(t),hf(e,n)}function vf(e,t){return Ke(e,t)}var yf=null,bf=null,xf=!1,Sf=!1,Cf=!1,wf=0;function Tf(e){e!==bf&&e.next===null&&(bf===null?yf=bf=e:bf=bf.next=e),Sf=!0,xf||(xf=!0,Mf())}function Ef(e,t){if(!Cf&&Sf){Cf=!0;do for(var n=!1,r=yf;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-st(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,jf(r,a))}else a=X,a=ht(r,r===Xu?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||gt(r,a)||(n=!0,jf(r,a))}r=r.next}while(n);Cf=!1}}function Df(){Of()}function Of(){Sf=xf=!1;var e=0;wf!==0&&hp()&&(e=wf);for(var t=Xe(),n=null,r=yf;r!==null;){var i=r.next,a=kf(r,t);a===0?(r.next=null,n===null?yf=i:n.next=i,i===null&&(bf=n)):(n=r,(e!==0||a&3)&&(Sf=!0)),r=i}_d!==0&&_d!==5||Ef(e,!1),wf!==0&&(wf=0)}function kf(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&ap(d)&&(c=c.responseEnd,o+=u*(cQm){s.length=o;break}f=new Promise(Ap.bind(f)),s.push(f)}}}if(0`u`?null:document;function wm(e,t,n){var r=Cm;if(r&&typeof t==`string`&&t){var i=fn(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),vm.has(i)||(vm.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),np(t,`link`,e),Gt(t),r.head.appendChild(t)))}}function Tm(e){bm.D(e),wm(`dns-prefetch`,e,null)}function Em(e,t){bm.C(e,t),wm(`preconnect`,e,t)}function Dm(e,t,n){bm.L(e,t,n);var r=Cm;if(r&&e&&t){var i=`link[rel="preload"][as="`+fn(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+fn(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+fn(n.imageSizes)+`"]`)):i+=`[href="`+fn(e)+`"]`;var a=i;switch(t){case`style`:a=Nm(e);break;case`script`:a=Lm(e)}if(!(_m.has(a)||(e=x({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),_m.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Pm(a))||t===`script`&&r.querySelector(Rm(a))))){var o=r.createElement(`link`);np(o,`link`,e),t===`style`&&(o[zt]=!0,o.onload=o.onerror=function(){Kt(o)}),Gt(o),r.head.appendChild(o)}}}function Om(e,t){bm.m(e,t);var n=Cm;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+fn(r)+`"][href="`+fn(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Lm(e)}if(!_m.has(a)&&(e=x({rel:`modulepreload`,href:e},t),_m.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Rm(a)))return}r=n.createElement(`link`),np(r,`link`,e),Gt(r),n.head.appendChild(r)}}}function km(e,t,n){bm.S(e,t,n);var r=Cm;if(r&&e){var i=Wt(r).hoistableStyles,a=Nm(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Pm(a)))s.loading=5;else{e=x({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=_m.get(a))&&Vm(e,n);var c=o=r.createElement(`link`);Gt(c),np(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Bm(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Am(e,t){bm.X(e,t);var n=Cm;if(n&&e){var r=Wt(n).hoistableScripts,i=Lm(e),a=r.get(i);a||(a=n.querySelector(Rm(i)),a||(e=x({src:e,async:!0},t),(t=_m.get(i))&&Hm(e,t),a=n.createElement(`script`),Gt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function jm(e,t){bm.M(e,t);var n=Cm;if(n&&e){var r=Wt(n).hoistableScripts,i=Lm(e),a=r.get(i);a||(a=n.querySelector(Rm(i)),a||(e=x({src:e,async:!0,type:`module`},t),(t=_m.get(i))&&Hm(e,t),a=n.createElement(`script`),Gt(a),np(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Mm(e,t,n,r){var i=(i=Ne.current)?ym(i):null;if(!i)throw Error(a(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(n=Nm(n.href),t=Wt(i).hoistableStyles,r=t.get(n),r||(r={type:`style`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Nm(n.href);var o=Wt(i).hoistableStyles,s=o.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=i.querySelector(Pm(e)))?o._p||(s.instance=o,s.state.loading=5):(o=_m.get(e),o||(o={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},_m.set(e,o)),Im(i,e,o,s.state))),t&&r===null)throw Error(a(528,``));return s}if(t&&r!==null)throw Error(a(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(n=Lm(n),t=Wt(i).hoistableScripts,r=t.get(n),r||(r={type:`script`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(a(444,e))}}function Nm(e){return`href="`+fn(e)+`"`}function Pm(e){return`link[rel="stylesheet"][`+e+`]`}function Fm(e){return x({},e,{"data-precedence":e.precedence,precedence:null})}function Im(e,t,n,r){if(t=e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)){if(!0!==t[zt]){r.loading=1;return}}else t=e.createElement(`link`),t[zt]=!0,t.onload=t.onerror=Kt.bind(null,t),np(t,`link`,n),Gt(t),e.head.appendChild(t);r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2})}function Lm(e){return`[src="`+fn(e)+`"]`}function Rm(e){return`script[async]`+e}function zm(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+fn(n.href)+`"]`);if(r)return t.instance=r,Gt(r),r;var i=x({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Gt(r),np(r,`style`,i),Bm(r,n.precedence,e),t.instance=r;case`stylesheet`:i=Nm(n.href);var o=e.querySelector(Pm(i));if(o)return t.state.loading|=4,t.instance=o,Gt(o),o;r=Fm(n),(i=_m.get(i))&&Vm(r,i),o=(e.ownerDocument||e).createElement(`link`),Gt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),np(o,`link`,r),t.state.loading|=4,Bm(o,n.precedence,e),t.instance=o;case`script`:return o=Lm(n.src),(i=e.querySelector(Rm(o)))?(t.instance=i,Gt(i),i):(r=n,(i=_m.get(o))&&(r=x({},n),Hm(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),Gt(i),np(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(a(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Bm(r,n.precedence,e));return t.instance}function Bm(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Km(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function qm(e,t){return e===`img`&&t.src!=null&&t.src!==``&&t.onLoad==null&&t.loading!==`lazy`}function Jm(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Ym(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio==`number`?devicePixelRatio:1)*.25}function Xm(e,t){typeof t.decode==`function`&&(e.imgCount++,t.complete||(e.imgBytes+=Ym(t),e.suspenseyImages.push(t)),e=nh.bind(e),t.decode().then(e,e))}function Zm(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Nm(r.href),a=t.querySelector(Pm(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=th.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Gt(a);return}a=t.ownerDocument||t,r=Fm(r),(i=_m.get(i))&&Vm(r,i),a=a.createElement(`link`),Gt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),np(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=th.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Qm=0;function $m(e,t){return e.stylesheets&&e.count===0&&ih(e,e.stylesheets),0Qm?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function eh(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)ih(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function th(){this.count--,eh(this)}function nh(){this.imgCount--,eh(this)}var rh=null;function ih(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,rh=new Map,t.forEach(ah,e),rh=null,th.call(e))}function ah(e,t){if(!(t.state.loading&4)){var n=rh.get(e);if(n)var r=n.get(null);else{n=new Map,rh.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=dg()}))(),pg=`__ZERNIO_ORIGIN__`,mg=[{family:`Geist`,file:`Geist-Variable.woff2`,weight:`100 900`},{family:`Geist Mono`,file:`GeistMono-Variable.woff2`,weight:`100 900`},{family:`Geist Pixel Square`,file:`GeistPixel-Square.woff2`,weight:`500`}];function hg(){if(pg.startsWith(`__`))return;let e=document.createElement(`style`);e.textContent=mg.map(e=>`@font-face{font-family:"${e.family}";src:url("${pg}/apps/fonts/${e.file}") format("woff2");font-weight:${e.weight};font-display:swap}`).join(``),document.head.appendChild(e)}var gg=e=>(0,r.createElement)(`svg`,Object.assign({viewBox:`0 0 24 24`,width:`24`,height:`24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`},e),(0,r.createElement)(`path`,{d:`M7 18H5v-2h2v2Zm6 0h-2v-2h2v2Zm-8-2H3v-2h2v2Zm4 0H7v-2h2v2Zm6-2v2h-2v-2h2ZM3 14H1v-2h2v2Zm8 0H9v-2h2v2Zm6 0h-2v-2h2v2Zm-4-2h-2v-2h2v2Zm6 0h-2v-2h2v2Zm-4-2h-2V8h2v2Zm6 0h-2V8h2v2Zm-4-2h-2V6h2v2Zm6 0h-2V6h2v2Z`})),_g=e=>(0,r.createElement)(`svg`,Object.assign({viewBox:`0 0 24 24`,width:`24`,height:`24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`},e),(0,r.createElement)(`path`,{d:`M4 13h16v-2H4zm7-8h2V3h-2zM9 7h4V5H9zm4 0h2V5h-2zm2 2h2V7h-2zM7 9h8V7H7zm4 10h2v2h-2zm-2-2h4v2H9zm4 0h2v2h-2zm2-2h2v2h-2zm-8 0h8v2H7z`})),vg=e=>(0,r.createElement)(`svg`,Object.assign({viewBox:`0 0 24 24`,width:`24`,height:`24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`},e),(0,r.createElement)(`path`,{d:`M4 2h16v2H4zm0 18h16v2H4zM2 4h2v16H2zm18 0h2v16h-2zm-9 5h2V7h-2zm0 8h2v-6h-2z`})),yg=e=>(0,r.createElement)(`svg`,Object.assign({viewBox:`0 0 24 24`,width:`24`,height:`24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`},e),(0,r.createElement)(`path`,{d:`M16 4h2v6h-2zm-2-2h2v2h-2zm0 2h2v8h-2zM4 8H2v5h2z`}),(0,r.createElement)(`path`,{d:`M4 6h16v2H4zm4 14H6v-6h2zm2 2H8v-2h2zm0-2H8v-8h2zm10-4h2v-5h-2z`}),(0,r.createElement)(`path`,{d:`M20 18H4v-2h16z`})),bg=e=>(0,r.createElement)(`svg`,Object.assign({viewBox:`0 0 24 24`,width:`24`,height:`24`,fill:`currentColor`,xmlns:`http://www.w3.org/2000/svg`},e),(0,r.createElement)(`path`,{d:`M2 10h2v2H2zm0 4h2v-2H2zm20-4h-2v2h2zm0 4h-2v-2h2zM4 8h2v2H4zm0 8h2v-2H4zm16-8h-2v2h2zm0 8h-2v-2h2zM6 6h2v2H6zm0 12h2v-2H6zM18 6h-2v2h2zm0 12h-2v-2h2zM8 4h2v2H8zm0 16h2v-2H8zm8-16h-2v2h2zm0 16h-2v-2h2zM10 2h2v2h-2zm0 20h2v-2h-2zm4-20h-2v2h2zm0 20h-2v-2h2zm-3-5h2v-2h-2zm0-4h2V7h-2z`}));async function xg(e,t,n={}){let r=await e.callServerTool({name:t,arguments:n}),i=r.content.map(e=>e.type===`text`?e.text:``).join(``);if(r.isError)throw Error(i||`${t} failed`);return JSON.parse(i)}function Sg(e){return xg(e,`accounts_get_all_accounts_health`)}async function Cg(e){let t=await xg(e,`posts_list_posts`,{status:`failed`,limit:1});return t.pagination?.total??t.posts?.length??0}var wg={twitter:`X`,instagram:`Instagram`,facebook:`Facebook`,linkedin:`LinkedIn`,tiktok:`TikTok`,youtube:`YouTube`,threads:`Threads`,pinterest:`Pinterest`,reddit:`Reddit`,bluesky:`Bluesky`,googlebusiness:`Google Business`,telegram:`Telegram`,snapchat:`Snapchat`,discord:`Discord`,slack:`Slack`,whatsapp:`WhatsApp`};function Tg(e){return wg[e]??e}var Eg={twitter:`x`,googlebusiness:`google`};function Dg(e){return`https://zernio.com/platform-logos/${Eg[e]??e}-icon.png`}var Og=e((e=>{var t=Symbol.for(`react.transitional.element`);function n(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.jsx=n,e.jsxs=n})),$=e(((e,t)=>{t.exports=Og()}))();function kg({title:e,actions:t,children:n}){return(0,$.jsxs)(`section`,{className:`section`,children:[(0,$.jsxs)(`div`,{className:`section-bar`,children:[(0,$.jsx)(`h2`,{className:`type-eyebrow`,children:e}),t&&(0,$.jsx)(`div`,{className:`section-actions`,children:t})]}),(0,$.jsx)(`div`,{className:`section-body`,children:n})]})}function Ag({label:e,tone:t,suffix:n,title:r}){return(0,$.jsxs)(`span`,{className:`status-pill status-pill-${t}`,title:r??e,children:[e,n]})}function jg({platform:e}){return(0,$.jsx)(`span`,{className:`platform-tile`,children:(0,$.jsx)(`img`,{src:Dg(e),alt:Tg(e),width:16,height:16})})}function Mg({label:e=`Loading`}){return(0,$.jsx)(`span`,{className:`spinner`,role:`status`,"aria-label":e,children:Array.from({length:9},(e,t)=>{let n=(Math.floor(t/3)+t%3)%3;return(0,$.jsx)(`span`,{style:{animationDelay:`${-((3-n)%3)/3*600}ms`}},t)})})}function Ng({tone:e,icon:t,children:n}){return(0,$.jsxs)(`p`,{className:`notice notice-${e}`,role:e===`danger`?`alert`:`status`,children:[t,(0,$.jsx)(`span`,{children:n})]})}function Pg({variant:e=`outline`,size:t=`md`,icon:n,className:r,...i}){let a=[`btn`,`btn-${e}`,`btn-${t}`,n?`btn-icon`:``,r??``].filter(Boolean);return(0,$.jsx)(`button`,{type:`button`,className:a.join(` `),...i})}var Fg={error:0,warning:1,healthy:2},Ig={healthy:{label:`Healthy`,tone:`success`},warning:{label:`Needs attention`,tone:`warning`},error:{label:`Broken`,tone:`danger`}};function Lg({app:e,fullscreen:t,canExpand:n,locale:i}){let[a,o]=(0,r.useState)(),[s,c]=(0,r.useState)(),[l,u]=(0,r.useState)(!0),[d,f]=(0,r.useState)(),[p,m]=(0,r.useState)(),h=(0,r.useCallback)(async()=>{u(!0);let[t,n]=await Promise.allSettled([Sg(e),Cg(e)]);t.status===`fulfilled`&&o(t.value),f(t.status===`rejected`?String(t.reason?.message??t.reason):void 0),c(n.status===`fulfilled`?n.value:void 0),n.status===`rejected`&&console.warn(`[zernio] failed posts unavailable:`,n.reason),u(!1)},[e]);(0,r.useEffect)(()=>{h()},[h]);let g=[...a?.accounts??[]].sort((e,t)=>Fg[e.status]-Fg[t.status]),_=g.filter(e=>e.status!==`healthy`),v=a?.summary??{},y=(v.warning??0)+(v.error??0);(0,r.useEffect)(()=>{if(!a||!e.getHostCapabilities()?.updateModelContext)return;let t=_.map(e=>`${e.platform} @${e.username??e.accountId}`).join(`, `);e.updateModelContext({content:[{type:`text`,text:`The Zernio panel shows ${v.total??0} accounts, ${_.length} needing attention${t?` (${t})`:``}${s===void 0?``:`, and ${s} failed posts`}.`}]})},[e,a,s]);let b=async t=>{let n=zg(t)||Ig[t.status].label,{isError:r}=await e.sendMessage({role:`user`,content:[{type:`text`,text:`My ${Tg(t.platform)} account @${t.username??t.accountId} (account_id ${t.accountId}) shows "${n}" in Zernio. Help me fix it.`}]});m(r?`Could not send it to Claude.`:`Sent to Claude. Continue in the chat.`)},ee=e=>e===void 0?`—`:new Intl.NumberFormat(i).format(e),te=t?g:_.slice(0,3);return l&&!a&&!d?(0,$.jsx)(`div`,{className:`loading`,children:(0,$.jsx)(Mg,{})}):(0,$.jsxs)(`div`,{className:`stack`,children:[d&&(0,$.jsxs)(Ng,{tone:`danger`,icon:(0,$.jsx)(bg,{className:`icon`}),children:[`Could not load your workspace. `,d]}),p&&(0,$.jsx)(Ng,{tone:`muted`,children:p}),(0,$.jsxs)(`div`,{className:`kpis`,children:[(0,$.jsx)(Rg,{label:`Accounts`,value:ee(v.total)}),(0,$.jsx)(Rg,{label:`Need attention`,value:ee(y)}),(0,$.jsx)(Rg,{label:`Failed posts`,value:ee(s)})]}),(0,$.jsx)(kg,{title:t?`Accounts`:`Accounts that need attention`,actions:(0,$.jsx)(Pg,{variant:`ghost`,size:`sm`,icon:!0,onClick:()=>void h(),disabled:l,"aria-label":`Refresh`,title:`Refresh`,children:l?(0,$.jsx)(Mg,{label:`Refreshing`}):(0,$.jsx)(yg,{className:`icon`})}),children:te.length?(0,$.jsx)(`ul`,{className:`rows`,children:te.map(t=>(0,$.jsx)(Bg,{account:t,onReconnect:()=>void e.openLink({url:`https://zernio.com/dashboard`}),onAsk:()=>void b(t)},t.accountId))}):(0,$.jsxs)(`div`,{className:`empty`,children:[(0,$.jsx)(gg,{className:`icon`}),` Every account can post.`]})}),n&&(0,$.jsx)(`div`,{className:`actions`,children:(0,$.jsxs)(Pg,{variant:`primary`,onClick:()=>void e.requestDisplayMode({mode:`fullscreen`}),children:[(0,$.jsx)(_g,{className:`icon`}),` Open Zernio`]})})]})}function Rg({label:e,value:t}){return(0,$.jsxs)(`div`,{className:`kpi`,children:[(0,$.jsx)(`div`,{className:`kpi-label`,children:e}),(0,$.jsx)(`div`,{className:`type-metric`,children:t})]})}function zg(e){return e.needsReconnect?e.disconnectReason||`Needs to be reconnected`:e.issues?.[0]||e.disconnectReason||``}function Bg({account:e,onReconnect:t,onAsk:n}){let r=Ig[e.status],i=zg(e);return(0,$.jsxs)(`li`,{className:`row`,children:[(0,$.jsx)(jg,{platform:e.platform}),(0,$.jsxs)(`div`,{className:`row-name`,children:[(0,$.jsx)(`span`,{className:`type-label`,children:Tg(e.platform)}),(0,$.jsx)(`span`,{className:`row-secondary`,children:e.username?`@${e.username}`:e.displayName})]}),(0,$.jsx)(Ag,{label:r.label,tone:r.tone,title:i||r.label,suffix:i?(0,$.jsx)(vg,{className:`icon-sm`,"aria-hidden":!0}):void 0}),(0,$.jsx)(`div`,{className:`row-fix`,children:e.needsReconnect?(0,$.jsx)(Pg,{size:`sm`,onClick:t,children:`Reconnect`}):e.status===`healthy`?null:(0,$.jsx)(Pg,{size:`sm`,onClick:n,children:`Ask Claude`})})]})}hg();function Vg(){let[e,t]=(0,r.useState)(),[n,i]=(0,r.useState)(!1),{app:a,error:o}=rg({appInfo:{name:`Zernio`,version:`0.1.0`},capabilities:{availableDisplayModes:[`inline`,`fullscreen`]},onAppCreated:e=>{e.ontoolresult=()=>i(!0),e.onhostcontextchanged=e=>t(t=>({...t,...e})),e.onerror=console.error}});return og(a,a?.getHostContext()),(0,r.useEffect)(()=>{a&&t(a.getHostContext())},[a]),o?(0,$.jsx)(`p`,{className:`notice notice-error`,children:o.message}):!a||!n?(0,$.jsx)(Ug,{}):(0,$.jsx)(Hg,{app:a,hostContext:e})}function Hg({app:e,hostContext:t}){let n=t?.displayMode===`fullscreen`,r=t?.safeAreaInsets;return(0,$.jsxs)(`main`,{className:n?`app app-fullscreen`:`app`,style:{paddingTop:r?.top,paddingRight:r?.right,paddingLeft:r?.left},children:[(0,$.jsxs)(`header`,{className:`header`,children:[(0,$.jsx)(`img`,{className:`logo`,src:`https://zernio.com/icon.svg?v=4`,alt:``,width:18,height:18}),(0,$.jsx)(`span`,{className:`type-page-title`,children:`Zernio`})]}),(0,$.jsx)(Lg,{app:e,fullscreen:n,canExpand:!n&&!!t?.availableDisplayModes?.includes(`fullscreen`),locale:t?.locale})]})}function Ug(){return(0,$.jsx)(`div`,{className:`loading`,children:(0,$.jsx)(Mg,{})})}(0,fg.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(r.StrictMode,{children:(0,$.jsx)(Vg,{})})); - diff --git a/src/late/mcp/apps/failed-posts.html b/src/late/mcp/apps/failed-posts.html deleted file mode 100644 index 744bb45b..00000000 --- a/src/late/mcp/apps/failed-posts.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - -Zernio failed posts - - - -
    -
    -
    - - - - diff --git a/src/late/mcp/apps/overview.html b/src/late/mcp/apps/overview.html deleted file mode 100644 index f180ba28..00000000 --- a/src/late/mcp/apps/overview.html +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - -Zernio - - - -
    -

    Zernio

    -

    Social media API for agents

    -

    Publish, schedule and analyze across 16 platforms, with a unified inbox and ads on 7 networks.

    -
    -
    PublishPost or schedule to many accounts at once
    -
    InboxDMs and comments in one place
    -
    AnalyticsDaily metrics across platforms
    -
    AdsCampaigns on 7 ad networks
    -
    -
    - - -
    -
    - - - - diff --git a/src/late/mcp/apps/post-preview.html b/src/late/mcp/apps/post-preview.html deleted file mode 100644 index 83f2ab00..00000000 --- a/src/late/mcp/apps/post-preview.html +++ /dev/null @@ -1,155 +0,0 @@ - - - - - - -Zernio post preview - - - -
    -
    -
    - - - - diff --git a/src/late/mcp/apps/runtime.js b/src/late/mcp/apps/runtime.js deleted file mode 100644 index 87294c48..00000000 --- a/src/late/mcp/apps/runtime.js +++ /dev/null @@ -1,251 +0,0 @@ -// Zernio MCP App runtime: the MCP Apps (2026-01-26) host bridge every view -// shares. JSON-RPC 2.0 over postMessage with the host window, no dependencies, -// so a view is one self-contained HTML document the host can review. -(function () { - "use strict"; - - var PROTOCOL_VERSION = "2026-01-26"; - var nextId = 1; - var pending = {}; - var listeners = {}; - var context = {}; - - function send(message) { - message.jsonrpc = "2.0"; - window.parent.postMessage(message, "*"); - } - - function request(method, params) { - var id = nextId++; - return new Promise(function (resolve, reject) { - pending[id] = { resolve: resolve, reject: reject }; - send({ id: id, method: method, params: params || {} }); - }); - } - - function notify(method, params) { - send({ method: method, params: params || {} }); - } - - function emit(event, payload) { - (listeners[event] || []).forEach(function (fn) { - try { - fn(payload); - } catch (err) { - console.error(err); - } - }); - } - - // Host notification -> view event. - var EVENTS = { - "ui/notifications/tool-input": "input", - "ui/notifications/tool-input-partial": "partial", - "ui/notifications/tool-result": "result", - "ui/notifications/tool-cancelled": "cancelled", - }; - - function applyContext(changed) { - // host-context-changed carries only the fields that changed. - context = Object.assign({}, context, changed); - var root = document.documentElement; - if (changed.theme === "light" || changed.theme === "dark") { - root.setAttribute("data-theme", changed.theme); - root.style.colorScheme = changed.theme; - } - var styles = changed.styles || {}; - var variables = styles.variables || {}; - Object.keys(variables).forEach(function (name) { - if (variables[name] != null) root.style.setProperty(name, variables[name]); - }); - if (styles.css && styles.css.fonts && !document.getElementById("host-fonts")) { - var fonts = document.createElement("style"); - fonts.id = "host-fonts"; - fonts.textContent = styles.css.fonts; - document.head.appendChild(fonts); - } - var insets = changed.safeAreaInsets; - if (insets) { - ["top", "right", "bottom", "left"].forEach(function (side) { - root.style.setProperty("--safe-" + side, (insets[side] || 0) + "px"); - }); - } - if (changed.displayMode) root.setAttribute("data-display-mode", changed.displayMode); - if (changed.deviceCapabilities && changed.deviceCapabilities.touch) { - root.setAttribute("data-touch", ""); - } - emit("context", context); - } - - window.addEventListener("message", function (event) { - if (event.source !== window.parent) return; - var message = event.data; - if (!message || message.jsonrpc !== "2.0") return; - - if (message.method === undefined) { - var waiting = pending[message.id]; - if (!waiting) return; - delete pending[message.id]; - if (message.error) waiting.reject(new Error(message.error.message || "Request failed")); - else waiting.resolve(message.result || {}); - return; - } - - var params = message.params || {}; - if (message.id !== undefined) { - // Requests from the host: ping and teardown are the only ones a view - // without its own tools receives. - if (message.method === "ui/resource-teardown") emit("teardown", params); - if (message.method === "ping" || message.method === "ui/resource-teardown") { - send({ id: message.id, result: {} }); - } else { - send({ id: message.id, error: { code: -32601, message: "Method not found" } }); - } - return; - } - - if (message.method === "ui/notifications/host-context-changed") applyContext(params); - else if (EVENTS[message.method]) emit(EVENTS[message.method], params); - }); - - // Reports the document height so the host sizes the inline frame to fit, - // the same measurement the official SDK's autoResize makes. - function watchSize() { - var queued = false; - var last = ""; - function measure() { - if (queued) return; - queued = true; - requestAnimationFrame(function () { - queued = false; - var root = document.documentElement; - var previous = root.style.height; - root.style.height = "max-content"; - var height = Math.ceil(root.getBoundingClientRect().height); - root.style.height = previous; - var width = Math.ceil(window.innerWidth); - if (width + "x" + height === last) return; - last = width + "x" + height; - notify("ui/notifications/size-changed", { width: width, height: height }); - }); - } - measure(); - var observer = new ResizeObserver(measure); - observer.observe(document.documentElement); - observer.observe(document.body); - } - - // Tool results reach a view as {structuredContent, content}. Tools that - // return text still carry it as structuredContent.result, and generated - // tools' text is compact JSON, so data() unwraps both shapes. - function textOf(result) { - var structured = result && result.structuredContent; - if (structured && typeof structured.result === "string") return structured.result; - var blocks = (result && result.content) || []; - return blocks - .filter(function (block) { return block.type === "text"; }) - .map(function (block) { return block.text; }) - .join("\n"); - } - - function dataOf(result) { - var structured = result && result.structuredContent; - if (structured && !(Object.keys(structured).length === 1 && "result" in structured)) { - return structured; - } - try { - return JSON.parse(textOf(result)); - } catch (err) { - return null; - } - } - - function el(tag, attrs) { - var node = document.createElement(tag); - Object.keys(attrs || {}).forEach(function (key) { - var value = attrs[key]; - if (value == null || value === false) return; - if (key === "text") node.textContent = value; - else if (key === "class") node.className = value; - else if (key.slice(0, 2) === "on") node.addEventListener(key.slice(2), value); - else node.setAttribute(key, value === true ? "" : value); - }); - for (var i = 2; i < arguments.length; i++) append(node, arguments[i]); - return node; - } - - function append(node, child) { - if (child == null || child === false) return; - if (Array.isArray(child)) child.forEach(function (c) { append(node, c); }); - else node.appendChild(typeof child === "string" ? document.createTextNode(child) : child); - } - - var PLATFORM_NAMES = { - twitter: "X", instagram: "Instagram", facebook: "Facebook", linkedin: "LinkedIn", - tiktok: "TikTok", youtube: "YouTube", threads: "Threads", pinterest: "Pinterest", - reddit: "Reddit", bluesky: "Bluesky", googlebusiness: "Google Business", - telegram: "Telegram", snapchat: "Snapchat", discord: "Discord", slack: "Slack", - whatsapp: "WhatsApp", - }; - - function platformName(platform) { - return PLATFORM_NAMES[platform] || platform || "Unknown"; - } - - function compact(value) { - try { - return new Intl.NumberFormat(context.locale, { notation: "compact", maximumFractionDigits: 1 }).format(value || 0); - } catch (err) { - return String(value || 0); - } - } - - function date(value, options) { - if (!value) return ""; - var parsed = new Date(value); - if (isNaN(parsed)) return String(value); - try { - return parsed.toLocaleString(context.locale, Object.assign({ timeZone: context.timeZone }, options)); - } catch (err) { - return parsed.toLocaleString(); - } - } - - window.Zernio = { - on: function (event, fn) { - (listeners[event] = listeners[event] || []).push(fn); - }, - connect: function (options) { - options = options || {}; - return request("ui/initialize", { - appInfo: { name: "Zernio " + (options.name || "view"), version: "1.0.0" }, - appCapabilities: { availableDisplayModes: options.displayModes || ["inline"] }, - protocolVersion: PROTOCOL_VERSION, - }).then(function (result) { - applyContext(result.hostContext || {}); - notify("ui/notifications/initialized"); - watchSize(); - return result; - }); - }, - context: function () { return context; }, - callTool: function (name, args) { - return request("tools/call", { name: name, arguments: args || {} }); - }, - openLink: function (url) { return request("ui/open-link", { url: url }); }, - requestDisplayMode: function (mode) { return request("ui/request-display-mode", { mode: mode }); }, - // Posts a message into the chat as the user, for Claude to act on. - sendMessage: function (text) { - return request("ui/message", { role: "user", content: [{ type: "text", text: text }] }); - }, - tellModel: function (text) { - return request("ui/update-model-context", { content: [{ type: "text", text: text }] }); - }, - text: textOf, - data: dataOf, - el: el, - platformName: platformName, - compact: compact, - date: date, - }; -})(); diff --git a/src/late/mcp/apps/tools.py b/src/late/mcp/apps/tools.py index 7a9dc096..1127dd89 100644 --- a/src/late/mcp/apps/tools.py +++ b/src/late/mcp/apps/tools.py @@ -1,12 +1,13 @@ -"""Display tools: one per view, always listed, each fetching its own data. +"""The tools that open the Zernio app, one per screen, always listed. -The data tools stay text-only behind search_tools. A view binds to the tool -the host called, so a view on a tool reached through call_tool never renders; -these show_* tools are the listed entry points instead (monday.com's -show-table / show-board pattern). Each returns a text summary for the model -and clients without MCP Apps, and structured_content for its view. +A view binds to the tool the host called, and most tools are reached through +call_tool, so these are the app's listed entry points. Each returns a text +summary for the model and clients without MCP Apps, and structured_content +`{view, data, args}`: the screen to show, its data, and the arguments that +produced it, so the app can refresh the screen or switch to another by +calling these same tools. -The ui_* tools are app-only: the views' buttons call them, the model never +The ui_* tools are app-only: the app's buttons call them, the model never sees them. """ @@ -25,8 +26,9 @@ from fastmcp import FastMCP _DISPLAY = ( - "UI display tool: renders an interactive view in clients that support MCP Apps, " - "with a text summary for those that do not." + "UI display tool: opens the Zernio app on this screen in clients that support " + "MCP Apps, with a text summary for those that do not. The user sees it and can " + "act there; do not repeat its contents as text." ) _READ = ToolAnnotations(readOnlyHint=True, destructiveHint=False, openWorldHint=False) @@ -47,13 +49,67 @@ def _api(call: Any) -> Any: raise ToolError(f"Error: {e}") from e -def register_tools(mcp: FastMCP, view_uri: Any) -> None: - def show(name: str, view: str, title: str, description: str) -> Any: +def _screen(view: str, data: Any, text: str, args: dict[str, Any]) -> ToolResult: + return ToolResult(content=text, structured_content={"view": view, "data": data, "args": args}) + + +def _failed_posts(limit: int) -> tuple[list[dict[str, Any]], int]: + server = _server() + client = server._get_client() + response = _api(lambda: client.posts.list(status="failed", limit=limit)) + posts = [ + { + "id": post.field_id, + "title": post.title or "", + "content": (post.content or "")[:280], + "platforms": [t.platform for t in post.platforms or [] if t.platform], + "errors": [ + {"platform": platform, "message": message} + for platform, message in server._failed_targets(post) + ], + "updatedAt": post.updatedAt.isoformat() if post.updatedAt else None, + } + for post in response.posts or [] + ] + total = getattr(getattr(response, "pagination", None), "total", None) + return posts, total if total is not None else len(posts) + + +def _health(profile_id: str = "", platform: str = "") -> dict[str, Any]: + client = _server()._get_client() + return _api( + lambda: client.accounts.get_all_accounts_health( + profile_id=profile_id or None, platform=platform or None + ) + ) + + +def _health_text(data: dict[str, Any]) -> str: + summary = data.get("summary") or {} + unhealthy = [a for a in data.get("accounts") or [] if a.get("status") != "healthy"] + lines = [ + f"{summary.get('total', 0)} account(s): {summary.get('healthy', 0)} healthy, " + f"{summary.get('warning', 0)} warning, {summary.get('error', 0)} error, " + f"{summary.get('needsReconnect', 0)} need reconnecting." + ] + for a in unhealthy[:25]: + reason = (a.get("issues") or [a.get("disconnectReason")])[0] + lines.append( + f"- {a.get('platform')} @{a.get('username') or a.get('accountId')}: {a.get('status')}" + + (f" ({reason})" if reason else "") + ) + return "\n".join(lines) + + +def register_tools(mcp: FastMCP, app_uri: str) -> None: + def show(name: str, title: str, description: str, meta: dict[str, Any] | None = None) -> Any: return mcp.tool( name=name, + title=title, description=f"{description}\n\n{_DISPLAY}", annotations=_READ.model_copy(update={"title": title}), - app=AppConfig(resource_uri=view_uri(view)), + app=AppConfig(resource_uri=app_uri), + meta=meta, ) def app_only(name: str, title: str, description: str) -> Any: @@ -66,14 +122,34 @@ def app_only(name: str, title: str, description: str) -> Any: app=AppConfig(visibility=["app"]), ) + @show( + "zernio_open_app", + "Open Zernio", + "Open the Zernio app: the workspace at a glance (connected accounts, the ones " + "that need attention, failed posts), with tabs for posts, analytics, accounts " + "and ads. Use it when the user wants to see their Zernio workspace.", + # Lists the app on Claude's Artifacts page, where people open and pin it + # without asking Claude (custom and Verified connectors only). + meta={"openai/ui": {"entrypoints": [{"type": "global"}]}}, + ) + def zernio_open_app() -> ToolResult: + health = _health() + failed, failed_total = _failed_posts(3) + text = _health_text(health) + f"\n{failed_total} failed post(s)." + return _screen( + "home", + {"health": health, "failedPosts": failed, "failedTotal": failed_total}, + text, + {}, + ) + @show( "show_post_preview", - "post-preview", "Preview a post", "Show the user how a post will go out on each platform before anything is " "published: the account each platform resolves to, the text, the media, and " "validation errors and warnings. Use it when the user wants to see or review a " - "post first. Nothing is published; the view's Publish now and Save as draft " + "post first. Nothing is published; the app's Publish now and Save as draft " "buttons call posts_cross_post with these same arguments. For a scheduled post, " "confirm in chat and call posts_create or posts_cross_post.\n\n" "Args:\n" @@ -155,20 +231,17 @@ def show_post_preview( f"'{','.join(t['accountId'] for t in targets)}'." ) - return ToolResult( - content="\n".join(lines), - structured_content={ - "kind": "preview", - "post": { - "content": content, - "media": [ - {"type": getattr(m["type"], "value", m["type"]), "url": m["url"]} - for m in media - ], - "targets": targets, - }, + return _screen( + "preview", + { + "content": content, + "media": [ + {"type": getattr(m["type"], "value", m["type"]), "url": m["url"]} + for m in media + ], + "targets": targets, "validation": validation, - # What the view's buttons send to posts_cross_post, with the + # What the app's buttons send to posts_cross_post, with the # accounts already resolved. "request": { "content": content, @@ -178,47 +251,38 @@ def show_post_preview( "media_urls": media_urls, }, }, + "\n".join(lines), + { + "content": content, + "platforms": platforms, + "account_ids": account_ids, + "profile_id": profile_id, + "media_urls": media_urls, + }, ) @show( "show_failed_posts", - "failed-posts", "Show failed posts", "Show the posts that failed to publish, each platform's error, and a Retry button " "per post. Use it when the user wants to see what failed or fix it.\n\n" "Args:\n" - " limit: Maximum number of posts to show. Default: 10.", + " limit: Maximum number of posts to show. Default: 20.", ) - def show_failed_posts(limit: int = 10) -> ToolResult: - server = _server() - client = server._get_client() - posts = _api(lambda: client.posts.list(status="failed", limit=limit)).posts or [] - - view = [ - { - "id": post.field_id, - "content": (post.content or "")[:280], - "platforms": [t.platform for t in post.platforms or [] if t.platform], - "errors": [ - {"platform": platform, "message": message} - for platform, message in server._failed_targets(post) - ], - } - for post in posts - ] - lines = [f"{len(view)} failed post(s)."] + [ + def show_failed_posts(limit: int = 20) -> ToolResult: + posts, total = _failed_posts(limit) + lines = [f"{total} failed post(s)."] + [ f"- {p['id']} ({', '.join(p['platforms'])}): " + ("; ".join(f"{e['platform']}: {e['message']}" for e in p["errors"]) or "Unknown error") - for p in view + for p in posts ] - return ToolResult(content="\n".join(lines), structured_content={"posts": view}) + return _screen("posts", {"posts": posts, "total": total}, "\n".join(lines), {"limit": limit}) @show( "show_analytics", - "analytics", "Show analytics", - "Show daily post analytics as a chart: totals for impressions, engagement, views and " - "posts, a per-day chart of each, and a fullscreen per-platform breakdown. Use it when " + "Show daily post analytics: totals for impressions, engagement, views and posts, " + "a per-day chart of the one picked, and the breakdown per platform. Use it when " "the user wants to see how their posts perform. Defaults to the last 180 days.\n\n" "Args:\n" " platform: Only this platform, e.g. 'instagram'.\n" @@ -251,48 +315,38 @@ def show_analytics( f"{totals.get('impressions', 0)} impressions, {totals.get('engagement', 0)} " f"engagements, {totals.get('views', 0)} views." ) - return ToolResult(content=text, structured_content=data) + args = { + "platform": platform, + "profile_id": profile_id, + "account_id": account_id, + "from_date": from_date, + "to_date": to_date, + } + return _screen("analytics", data, text, args) @show( "show_account_health", - "account-health", "Show account health", - "Show connected social accounts by health status, the ones that need attention and " - "why, with a link to reconnect. Use it when the user asks whether their accounts " - "work or why posting fails for one.\n\n" + "Show connected social accounts by health state, the ones that need attention " + "and why, with Reconnect where it fixes them. Use it when the user asks whether " + "their accounts work or why posting fails for one.\n\n" "Args:\n" " profile_id: Only this profile.\n" " platform: Only this platform.", ) def show_account_health(profile_id: str = "", platform: str = "") -> ToolResult: - client = _server()._get_client() - data = _api( - lambda: client.accounts.get_all_accounts_health( - profile_id=profile_id or None, platform=platform or None - ) + data = _health(profile_id, platform) + return _screen( + "accounts", data, _health_text(data), {"profile_id": profile_id, "platform": platform} ) - summary = data.get("summary") or {} - unhealthy = [a for a in data.get("accounts") or [] if a.get("status") != "healthy"] - lines = [ - f"{summary.get('total', 0)} account(s): {summary.get('healthy', 0)} healthy, " - f"{summary.get('warning', 0)} warning, {summary.get('error', 0)} error, " - f"{summary.get('needsReconnect', 0)} need reconnecting." - ] + [ - f"- {a.get('platform')} @{a.get('username') or a.get('accountId')}: {a.get('status')}" - + (f" ({(a.get('issues') or [a.get('disconnectReason')])[0]})" if a.get("issues") or a.get("disconnectReason") else "") - for a in unhealthy[:25] - ] - return ToolResult(content="\n".join(lines), structured_content=data) @show( "show_ads_alerts", - "ads-alerts", "Show ads that need attention", "Show what needs attention across the user's ads, most severe first: rejected ads, " "delivery issues, payment problems, campaigns spending without results, capped " - "budgets, lost connections and failing syncs. Each has a link to fix it and can be " - "dismissed for 30 days. Use it when the user asks how their ads are doing or what " - "is wrong with them.\n\n" + "budgets, lost connections and failing syncs, each with its fix. Use it when the " + "user asks how their ads are doing or what is wrong with them.\n\n" "Args:\n" " account_id: Only alerts of this ads connection.\n" " profile_id: Only alerts of the ads connections on this profile.", @@ -309,15 +363,16 @@ def show_ads_alerts(account_id: str = "", profile_id: str = "") -> ToolResult: f"- [{a.get('severity')}] {a.get('title')}: {a.get('message')} (id: {a.get('id')})" for a in alerts[:25] ] - return ToolResult(content="\n".join(lines), structured_content=data) + return _screen( + "ads", data, "\n".join(lines), {"account_id": account_id, "profile_id": profile_id} + ) @show( "show_automation_approvals", - "automation-approvals", "Show automation approvals", "Show the changes an ads automation is waiting for a person to approve (pauses, " - "budget, bid and target changes), with Approve and Reject buttons. Use it when the " - "user wants to review or decide pending automation approvals. Find automation IDs " + "budget, bid and target changes), with Approve and Reject. Use it when the user " + "wants to review or decide pending automation approvals. Find automation IDs " "with search_tools ('list automations').\n\n" "Args:\n" " automation_id: The automation (required)\n" @@ -339,15 +394,17 @@ def show_automation_approvals( + ("" if a.get("canDecide") else " (you cannot decide it)") for a in approvals ] - return ToolResult( - content="\n".join(lines), - structured_content={**data, "automationId": automation_id}, + return _screen( + "approvals", + {**data, "automationId": automation_id}, + "\n".join(lines), + {"automation_id": automation_id, "status": status}, ) @app_only( "ui_dismiss_ads_alert", "Dismiss an ads alert", - "Hide an ads alert for 30 days. Called by the ads alerts view.", + "Hide an ads alert for 30 days. Called by the Zernio app.", ) def ui_dismiss_ads_alert(alert_id: str) -> dict[str, Any]: client = _server()._get_client() @@ -356,8 +413,7 @@ def ui_dismiss_ads_alert(alert_id: str) -> dict[str, Any]: @app_only( "ui_decide_automation_approval", "Approve or reject an automation request", - "Approve or reject a pending automation approval request. Called by the automation " - "approvals view.", + "Approve or reject a pending automation approval request. Called by the Zernio app.", ) def ui_decide_automation_approval( automation_id: str, approval_id: str, decision: Literal["approve", "reject"] From 0e730e711062b30a471a3eca1e6f41d2278822f9 Mon Sep 17 00:00:00 2001 From: Oscar Perez Date: Wed, 18 Nov 2026 15:59:19 +0100 Subject: [PATCH 08/11] feat(apps): Reconnect opens the account's own reconnect link The Reconnect button asked nothing of the account and opened the dashboard. It now gets the account's reconnect link through the app-only ui_reconnect_account (GET /v1/connect/{platform} with reconnectAccountId and the account's profileId), so signing in refreshes that same account, keeping its id and history. A refusal shows on the row's state pill. Co-Authored-By: Claude Opus 5.5 --- apps-src/src/api.ts | 1 + apps-src/src/screens/rows.tsx | 41 +++++++++++++++++++++++++-- src/late/mcp/apps/__init__.py | 1 + src/late/mcp/apps/bundle/mcp-app.html | 6 ++-- src/late/mcp/apps/tools.py | 14 +++++++++ 5 files changed, 58 insertions(+), 5 deletions(-) diff --git a/apps-src/src/api.ts b/apps-src/src/api.ts index 33a2dddf..98fbdde2 100644 --- a/apps-src/src/api.ts +++ b/apps-src/src/api.ts @@ -58,6 +58,7 @@ export function screenOf(result: CallResult): Screen | undefined { export interface Account { accountId: string; platform: string; + profileId?: string; username?: string; displayName?: string; status: "healthy" | "warning" | "error"; diff --git a/apps-src/src/screens/rows.tsx b/apps-src/src/screens/rows.tsx index a13bddb2..9b468b2f 100644 --- a/apps-src/src/screens/rows.tsx +++ b/apps-src/src/screens/rows.tsx @@ -18,7 +18,25 @@ function accountReason(account: Account): string { return account.issues?.[0] || account.disconnectReason || ""; } +/** The account's own reconnect link: signing in there refreshes this account, keeping its id and history. */ +async function reconnect(ctx: Ctx, account: Account): Promise { + if (!account.profileId) return "This account has no profile to reconnect it on."; + const result = await ctx.act("ui_reconnect_account", { + account_id: account.accountId, + platform: account.platform, + profile_id: account.profileId, + }); + const url = (result.data as { authUrl?: string } | undefined)?.authUrl; + if (!result.ok || !url) return result.text || "Could not get the reconnect link."; + const opened = await ctx.app.openLink({ url }); + if (opened.isError) return "The link could not be opened."; + ctx.tell(`From the Zernio app the user opened the reconnect link for ${account.platform} account ${account.accountId}.`); + return undefined; +} + export function AccountRow({ ctx, account }: { ctx: Ctx; account: Account }) { + const [busy, setBusy] = useState(false); + const [failed, setFailed] = useState(); const state = ACCOUNT_STATE[account.status]; const reason = accountReason(account); const handle = account.username ? `@${account.username}` : account.displayName; @@ -27,10 +45,29 @@ export function AccountRow({ ctx, account }: { ctx: Ctx; account: Account }) { lead={} name={platformName(account.platform)} secondary={handle} - state={} + state={ + failed ? ( + + ) : ( + + ) + } fix={ account.needsReconnect ? ( - + ) : account.status !== "healthy" ? ( - -
    - )} - {pending && !approval.canDecide && Only {approval.to?.join(", ")} can decide this.} - - ); -} diff --git a/apps-src/src/screens/Comments.tsx b/apps-src/src/screens/Comments.tsx new file mode 100644 index 00000000..e43fc221 --- /dev/null +++ b/apps-src/src/screens/Comments.tsx @@ -0,0 +1,71 @@ +/** A post's comments: each comment with its own reply box when it can be answered. */ +import { ArrowLeft } from "pixelarticons/react/ArrowLeft.js"; +import { Message } from "pixelarticons/react/Message.js"; +import { useState } from "react"; +import { type Comment, type CommentsData, formatDate } from "../api"; +import { Badge, Button, Empty, Notice, ReplyBox, Section } from "../ui"; +import type { Ctx } from "./context"; + +export function Comments({ ctx, data }: { ctx: Ctx; data: CommentsData }) { + const [open, setOpen] = useState(); + const [replied, setReplied] = useState([]); + const title = (data.post.text || "").split("\n")[0] || "Post"; + + const reply = async (comment: Comment, text: string) => { + const result = await ctx.act("comments_reply_to_inbox_post", { post_id: data.postId, account_id: data.accountId, message: text, comment_id: comment.id }); + if (!result.ok) return result.text || "The reply was not sent."; + setReplied((list) => [...list, comment.id]); + setOpen(undefined); + ctx.tell(`From the Zernio app the user replied to comment ${comment.id} on post ${data.postId}: "${text}"`); + return undefined; + }; + + return ( + <> +
    + +
    +
    void ctx.app.openLink({ url: data.post.permalink! })}>View post : undefined} + > + {data.comments.length ? ( +
      + {data.comments.map((c) => { + const author = c.from.name || (c.from.username ? `@${c.from.username}` : "Someone"); + return ( +
    1. +
      + {author} + {c.from.isOwner && You} + {formatDate(c.createdTime, ctx.locale)} + {!!c.replyCount && · {c.replyCount} replies} + + {replied.includes(c.id) ? ( + Replied + ) : c.canReply !== false && !c.from.isOwner ? ( + + ) : null} + +
      +

      {c.isHidden ? Hidden : c.message || No text}

      + {open === c.id && ( + reply(c, text)} + onDraft={() => ctx.ask(`Draft a reply to ${author}'s comment "${c.message ?? ""}" on my post (post_id ${data.postId}, account_id ${data.accountId}, comment_id ${c.id}).`)} + /> + )} +
    2. + ); + })} +
    + ) : ( + }>No comments on this post yet. + )} +
    + {data.comments.length > 0 && data.comments.every((c) => c.canReply === false) && This platform does not allow replies from the API.} + + ); +} diff --git a/apps-src/src/screens/Conversation.tsx b/apps-src/src/screens/Conversation.tsx new file mode 100644 index 00000000..5c186208 --- /dev/null +++ b/apps-src/src/screens/Conversation.tsx @@ -0,0 +1,58 @@ +/** A conversation: the thread, oldest first, and the reply box under it. */ +import { ArrowLeft } from "pixelarticons/react/ArrowLeft.js"; +import { Mail } from "pixelarticons/react/Mail.js"; +import { useState } from "react"; +import { type ConversationData, type Message } from "../api"; +import { Button, Empty, ReplyBox, Section } from "../ui"; +import type { Ctx } from "./context"; + +function when(value: string | null | undefined, locale?: string): string { + if (!value) return ""; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? "" : date.toLocaleString(locale, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }); +} + +export function ConversationView({ ctx, data }: { ctx: Ctx; data: ConversationData }) { + const [messages, setMessages] = useState(data.messages); + const contact = messages.find((m) => m.direction === "incoming")?.senderName || "this contact"; + + const send = async (text: string) => { + const result = await ctx.act("ui_send_message", { conversation_id: data.conversationId, account_id: data.accountId, message: text }); + if (!result.ok) return result.text || "The message was not sent."; + setMessages((list) => [...list, { id: `sent-${Date.now()}`, message: text, direction: "outgoing", senderName: "You", createdAt: new Date().toISOString(), attachments: 0 }]); + ctx.tell(`From the Zernio app the user replied to ${contact} in conversation ${data.conversationId}: "${text}"`); + return undefined; + }; + + return ( + <> +
    + +
    +
    + {messages.length ? ( +
      + {messages.map((m) => ( +
    1. +
      + {m.direction === "outgoing" ? "You" : m.senderName || "Them"} + {when(m.createdAt, ctx.locale)} +
      +

      + {m.isDeleted ? Deleted : m.message || {m.attachments ? `${m.attachments} attachment${m.attachments > 1 ? "s" : ""}` : "No text"}} +

      +
    2. + ))} +
    + ) : ( + }>No messages in this conversation yet. + )} + ctx.ask(`Draft a reply to ${contact} in my Zernio conversation ${data.conversationId} (account_id ${data.accountId}), based on the last messages.`)} + /> +
    + + ); +} diff --git a/apps-src/src/screens/Inbox.tsx b/apps-src/src/screens/Inbox.tsx new file mode 100644 index 00000000..4e486b10 --- /dev/null +++ b/apps-src/src/screens/Inbox.tsx @@ -0,0 +1,68 @@ +/** Inbox: the latest conversations and the posts with comments, each opening its thread. */ +import { Mail } from "pixelarticons/react/Mail.js"; +import { Message } from "pixelarticons/react/Message.js"; +import { formatDate, formatNumber, type InboxData, platformName } from "../api"; +import { Button, Empty, Kpis, PlatformTile, Row, Rows, Section, StatusPill } from "../ui"; +import type { Ctx } from "./context"; + +export function Inbox({ ctx, data }: { ctx: Ctx; data: InboxData }) { + const unread = data.conversations.reduce((sum, c) => sum + (c.unreadCount ?? 0), 0); + const comments = data.posts.reduce((sum, p) => sum + (p.commentCount ?? 0), 0); + const shown = ctx.fullscreen ? 15 : 5; + const n = (v: number) => formatNumber(v, ctx.locale); + + return ( + <> + +
    + {data.conversations.length ? ( + + {data.conversations.slice(0, shown).map((c) => ( + } + name={c.participantName || (c.isGroup ? "Group" : "Unknown")} + secondary={c.lastMessage || formatDate(c.updatedTime, ctx.locale)} + state={c.unreadCount ? : undefined} + fix={ + + } + /> + ))} + + ) : ( + }>No conversations yet. + )} +
    +
    + {data.posts.length ? ( + + {data.posts.slice(0, shown).map((p) => ( + } + name={(p.content || "").split("\n")[0] || `${platformName(p.platform)} post`} + secondary={`${formatNumber(p.commentCount ?? 0, ctx.locale)} comments · ${formatDate(p.createdTime, ctx.locale)}`} + fix={ + + } + /> + ))} + + ) : ( + }>No comments on your recent posts. + )} +
    + + ); +} diff --git a/apps-src/src/ui.tsx b/apps-src/src/ui.tsx index 8fce6f06..7a7cb22b 100644 --- a/apps-src/src/ui.tsx +++ b/apps-src/src/ui.tsx @@ -5,7 +5,7 @@ * (Schedule-Posts-API, .claude/rules/design-principles.md). */ import { InfoBox } from "pixelarticons/react/InfoBox.js"; -import type { ButtonHTMLAttributes, ReactNode } from "react"; +import { type ButtonHTMLAttributes, type ReactNode, useState } from "react"; import { platformIcon, platformName } from "./api"; /** 18. A block is a white panel; a list's panel is headed by a grey bar with its eyebrow title. */ @@ -198,3 +198,48 @@ export function More({ label, onClick }: { label: string; onClick: () => void })
    ); } + +/** + * 47. A reply box: a bordered field (focus darkens its border, 13) with the + * main action after it. Sending clears the field; a failure keeps the text. + */ +export function ReplyBox({ placeholder, onSend, onDraft }: { + placeholder: string; + onSend: (text: string) => Promise; + /** Hands drafting to Claude. */ + onDraft?: () => void; +}) { + const [text, setText] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(); + const send = async () => { + const value = text.trim(); + if (!value) return; + setBusy(true); + setError(undefined); + const failure = await onSend(value); + setBusy(false); + if (failure) setError(failure); + else setText(""); + }; + return ( +
    +