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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion packages/web-ui/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2867,11 +2867,32 @@ export function ensureHubAuth(methodOrOpts?: string | EnsureHubAuthOpts): Promis
return p;
}

// ─── Preview-mode hub cache ─────────────────────────────────────────────
// In landing/preview mode we want the store demo to render instantly when the
// user scrolls to it, not after a fetch starts. A long-lived cache (10 min) on
// successful GETs means a single prefetch at page load is enough — any later
// mount of StoreDiscovery (or other hub consumers) hits memory instantly.
// This cache is ONLY used when __MARKUS_PREVIEW__ is set, so the real desktop /
// web client keeps its existing no-cache (fresh fetch) behavior.
const PREVIEW_CACHE_TTL_MS = 10 * 60 * 1000;
const _previewCache = new Map<string, { data: unknown; ts: number }>();

async function hubRequest<T>(path: string, init?: RequestInit): Promise<T> {
const token = getHubToken();
const headers: Record<string, string> = { 'Content-Type': 'application/json', ...init?.headers as Record<string, string> };
if (token) headers['Authorization'] = `Bearer ${token}`;
const res = await fetch(`${BASE}/hub${path}`, {
// In landing/preview mode there is no local backend proxy for /api/hub/* —
// talk to the Hub origin directly (HUB_URL from window.__MARKUS_HUB_URL__).
const preview = !!(window as unknown as Record<string, boolean>).__MARKUS_PREVIEW__;
const isGet = !init?.method || init.method === 'GET';
if (preview && isGet) {
const hit = _previewCache.get(path);
if (hit && Date.now() - hit.ts < PREVIEW_CACHE_TTL_MS) return hit.data as T;
}
const url = preview
? `${HUB_URL}/api${path}`
: `${BASE}/hub${path}`;
const res = await fetch(url, {
...init,
headers,
credentials: 'include',
Expand All @@ -2891,6 +2912,10 @@ async function hubRequest<T>(path: string, init?: RequestInit): Promise<T> {
err.status = res.status;
throw err;
}
if (preview && isGet) {
// Only successful payloads are cached.
_previewCache.set(path, { data: data as unknown, ts: Date.now() });
}
return data as T;
}

Expand Down
69 changes: 51 additions & 18 deletions packages/web-ui/src/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export interface HomePreviewData {
requirements?: RequirementInfo[];
projects?: ProjectInfo[];
deliverableTotal?: number;
recentDeliverables?: DeliverableInfo[];
storageInfo?: StorageInfo | null;
usageInfo?: { llmTokens: number; storageBytes: number } | null;
}
Expand All @@ -67,7 +68,7 @@ export function HomePage({ authUser, previewMode, previewData }: { authUser?: {
const [allRequirements, setAllRequirements] = useState<RequirementInfo[]>(previewData?.requirements ?? []);
const [projects, setProjects] = useState<ProjectInfo[]>(previewData?.projects ?? []);
const [deliverableTotal, setDeliverableTotal] = useState(previewData?.deliverableTotal ?? 0);
const [recentDeliverables, setRecentDeliverables] = useState<DeliverableInfo[]>([]);
const [recentDeliverables, setRecentDeliverables] = useState<DeliverableInfo[]>(previewData?.recentDeliverables ?? []);
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(previewData?.storageInfo ?? null);
const [usageInfo, setUsageInfo] = useState<{ llmTokens: number; storageBytes: number } | null>(previewData?.usageInfo ?? null);
const [cuQuota, setCuQuota] = useState<{ available: boolean; cuRemaining: number; cuLimit: number; cuUsedToday?: number } | null>(null);
Expand Down Expand Up @@ -119,6 +120,7 @@ export function HomePage({ authUser, previewMode, previewData }: { authUser?: {
setAllRequirements(previewData.requirements ?? []);
setProjects(previewData.projects ?? []);
setDeliverableTotal(previewData.deliverableTotal ?? 0);
if (previewData.recentDeliverables) setRecentDeliverables(previewData.recentDeliverables);
if (previewData.storageInfo) setStorageInfo(previewData.storageInfo);
if (previewData.usageInfo) setUsageInfo(previewData.usageInfo);
}, [previewMode, previewData]);
Expand Down Expand Up @@ -362,16 +364,16 @@ export function HomePage({ authUser, previewMode, previewData }: { authUser?: {
<div className={`px-4 sm:px-6 lg:px-8 pb-8 space-y-6 ${previewMode ? '' : 'max-w-7xl mx-auto'} w-full`}>

{/* ── Metric Cards ── */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
<div className={`grid grid-cols-2 lg:grid-cols-4 gap-4 ${previewMode ? 'preview-stagger' : ''}`}>
<MetricCard label={t('metricCards.working')} value={String(workingAgents)} sub={`/${agents.length}`}
icon={<MetricIcon type="working" />} pulse={workingAgents > 0} onClick={() => setShowWorkingModal(true)} />
icon={<MetricIcon type="working" />} pulse={workingAgents > 0} onClick={() => setShowWorkingModal(true)} animateCount={previewMode} />
<MetricCard label={t('metricCards.tasksDone')} value={`${completed}`} sub={`/${totalRootTasks}`}
icon={<MetricIcon type="tasks" />} onClick={() => navBus.navigate(PAGE.WORK)} />
icon={<MetricIcon type="tasks" />} onClick={() => navBus.navigate(PAGE.WORK)} />
<MetricCard label={t('metricCards.projects')} value={String(activeProjects)}
icon={<MetricIcon type="projects" />} onClick={() => navBus.navigate(PAGE.WORK)} />
icon={<MetricIcon type="projects" />} onClick={() => navBus.navigate(PAGE.WORK)} animateCount={previewMode} />
<MetricCard label={t('metricCards.health')} value={`${llmConfigured === false ? 100 : ops?.systemHealth.overallScore ?? '—'}`} sub={llmConfigured === false || ops ? '%' : undefined}
icon={<MetricIcon type="health" />} color={llmConfigured === false ? 'green' : !ops ? undefined : ops.systemHealth.overallScore >= 80 ? 'green' : ops.systemHealth.overallScore >= 50 ? 'amber' : 'red'}
onClick={() => setShowHealthModal(true)} />
onClick={() => setShowHealthModal(true)} animateCount={previewMode} />
</div>

{/* ── Needs Your Attention ── */}
Expand Down Expand Up @@ -476,10 +478,16 @@ export function HomePage({ authUser, previewMode, previewData }: { authUser?: {
</div>
)}

{/* ── Onboarding Checklist ──
No loading placeholder: the card only renders once it is ready and
has real content, so it never flashes an empty "loading" box. */}
{checklistReady && (() => {
{/* ── Onboarding Checklist ── */}
{!previewMode && !checklistDismissed && !checklistReady && (
<div className="bg-gradient-to-br from-brand-600/10 via-surface-secondary to-surface-secondary border border-brand-500/20 rounded-2xl p-5 sm:p-6">
<div className="flex items-center justify-center py-10 gap-3 text-fg-tertiary">
<div className="w-5 h-5 border-2 border-brand-500 border-t-transparent rounded-full animate-spin" />
<span className="text-sm">{t('common:loading')}</span>
</div>
</div>
)}
{!previewMode && !checklistDismissed && checklistReady && (() => {
const navigateToSecretary = (prompt: string) => {
const secretary = agents.find(a => a.role === 'secretary') ?? agents.find(a => a.name?.toLowerCase().includes('secretary'));
navBus.navigate(PAGE.TEAM, {
Expand Down Expand Up @@ -626,7 +634,7 @@ export function HomePage({ authUser, previewMode, previewData }: { authUser?: {

{/* Tasks with donut */}
<div className="px-5 py-4 flex flex-col sm:flex-row items-center gap-6 border-t border-border-subtle/50">
<DonutChart statusCounts={rootStatusCounts} total={totalRootTasks} completionRate={completionRate} completed={completed} />
<DonutChart statusCounts={rootStatusCounts} total={totalRootTasks} completionRate={completionRate} completed={completed} animate={previewMode} />
<div className="flex-1 min-w-0">
<div className="grid grid-cols-2 gap-x-5 gap-y-2.5">
{sortedStatusEntries.map(({ status, count }) => (
Expand Down Expand Up @@ -794,16 +802,32 @@ export function HomePage({ authUser, previewMode, previewData }: { authUser?: {
// Sub-components
// ═════════════════════════════════════════════════════════════════════════════

function MetricCard({ label, value, sub, icon, pulse, color, badge, onClick }: {
label: string; value: string; sub?: string; icon: React.ReactNode; pulse?: boolean; color?: 'green' | 'amber' | 'red'; badge?: string; onClick?: () => void;
function MetricCard({ label, value, sub, icon, pulse, color, badge, onClick, animateCount }: {
label: string; value: string; sub?: string; icon: React.ReactNode; pulse?: boolean; color?: 'green' | 'amber' | 'red'; badge?: string; onClick?: () => void; animateCount?: boolean;
}) {
const colorClass = color === 'green' ? 'text-green-500' : color === 'amber' ? 'text-amber-500' : color === 'red' ? 'text-red-500' : 'text-fg-primary';
const numericValue = parseInt(value, 10);
const [displayValue, setDisplayValue] = useState(animateCount ? '0' : value);
useEffect(() => {
if (!animateCount || isNaN(numericValue)) { setDisplayValue(value); return; }
let frame: number;
const duration = 1200;
const start = performance.now();
const tick = (now: number) => {
const progress = Math.min((now - start) / duration, 1);
const eased = 1 - Math.pow(1 - progress, 3);
setDisplayValue(String(Math.round(numericValue * eased)));
if (progress < 1) frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}, [animateCount, numericValue, value]);
return (
<div onClick={onClick} className="bg-surface-elevated shadow-sm rounded-2xl p-4 sm:p-5 flex items-start justify-between cursor-pointer hover:shadow-md transition-shadow">
<div>
<div className="text-[11px] text-fg-tertiary mb-2">{label}</div>
<div className="flex items-baseline gap-0.5">
<span className={`text-2xl sm:text-3xl font-bold ${colorClass} leading-none`}>{value}</span>
<span className={`text-2xl sm:text-3xl font-bold ${colorClass} leading-none`}>{displayValue}</span>
{sub && <span className="text-sm text-fg-muted font-medium">{sub}</span>}
</div>
{badge && <div className="text-[10px] text-amber-500 font-medium mt-1.5">{badge}</div>}
Expand Down Expand Up @@ -856,8 +880,8 @@ function EntityIcon({ type }: { type: 'folder' | 'edit' | 'book' }) {

// ── Donut Chart ─────────────────────────────────────────────────────────────

function DonutChart({ statusCounts, total, completionRate, completed }: {
statusCounts: Record<string, number>; total: number; completionRate: number; completed: number;
function DonutChart({ statusCounts, total, completionRate, completed, animate }: {
statusCounts: Record<string, number>; total: number; completionRate: number; completed: number; animate?: boolean;
}) {
const size = 120;
const r = 42;
Expand All @@ -871,14 +895,23 @@ function DonutChart({ statusCounts, total, completionRate, completed }: {
offset += len;
return arc;
});
const [revealed, setRevealed] = useState(!animate);
useEffect(() => {
if (!animate) return;
const t = setTimeout(() => setRevealed(true), 100);
return () => clearTimeout(t);
}, [animate]);

return (
<div className="relative shrink-0" style={{ width: size, height: size }}>
<svg width={size} height={size} viewBox="0 0 120 120">
{arcs.map((arc, i) => (
<circle key={i} cx="60" cy="60" r={r} fill="none" stroke={arc.color} strokeWidth={strokeW}
strokeDasharray={`${arc.len} ${c - arc.len}`} strokeDashoffset={-arc.offset}
transform="rotate(-90 60 60)" className="transition-all duration-500 cursor-pointer"
strokeDasharray={revealed ? `${arc.len} ${c - arc.len}` : `0 ${c}`}
strokeDashoffset={revealed ? -arc.offset : 0}
transform="rotate(-90 60 60)"
style={{ transition: `stroke-dasharray 1s cubic-bezier(0.4,0,0.2,1) ${i * 100}ms, stroke-dashoffset 1s cubic-bezier(0.4,0,0.2,1) ${i * 100}ms` }}
className="cursor-pointer"
onClick={() => navBus.navigate(PAGE.WORK, { statusFilter: arc.status })} />
))}
</svg>
Expand Down
66 changes: 36 additions & 30 deletions packages/web-ui/src/pages/Team.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -830,35 +830,41 @@ export function TeamPage({ initialAgentId, authUser, previewMode, previewData }:

type EntityMentionItem = { id: string; name: string; entityType: 'workflow' | 'project' | 'requirement' | 'task' | 'deliverable'; role?: string };
const [entityMentionItems, setEntityMentionItems] = useState<EntityMentionItem[]>([]);
const entityMentionLoadedRef = useRef(false);
const loadEntityMentions = useCallback(() => {
if (entityMentionLoadedRef.current) return;
entityMentionLoadedRef.current = true;
(async () => {
const entityMentionsLoadedRef = useRef(false);
// Load entities (projects / requirements / tasks / deliverables / workflows) for
// @mention. Kept in a useCallback so @-typing in the composer can refresh it on
// demand (handleInputChange → loadEntityMentions) without duplicating the fetch.
const loadEntityMentions = useCallback(async () => {
if (entityMentionsLoadedRef.current) return;
entityMentionsLoadedRef.current = true;
try {
const items: EntityMentionItem[] = [];
try {
const [projRes, reqRes, taskRes, delRes, teamsRes] = await Promise.all([
api.projects.list().catch(() => ({ projects: [] as Array<{ id: string; name: string; status: string }> })),
api.requirements.list().catch(() => ({ requirements: [] as Array<{ id: string; title: string; priority: string }> })),
api.tasks.list({ pageSize: 100 }).catch(() => ({ tasks: [] as Array<{ id: string; title: string; status: string }> })),
api.deliverables.search({ limit: 100 }).catch(() => ({ results: [] as Array<{ id: string; title: string; type: string }> })),
api.teams.list().catch(() => ({ teams: [] as TeamInfo[], ungrouped: [] })),
]);
for (const p of projRes.projects) items.push({ id: p.id, name: p.name, entityType: 'project', role: p.status });
for (const r of reqRes.requirements) items.push({ id: r.id, name: r.title, entityType: 'requirement', role: r.priority });
for (const tk of taskRes.tasks) items.push({ id: tk.id, name: tk.title, entityType: 'task', role: tk.status });
for (const d of delRes.results) items.push({ id: d.id, name: d.title, entityType: 'deliverable', role: d.type });
for (const team of teamsRes.teams) {
try {
const wfRes = await api.workflows.list(team.id);
for (const wf of wfRes.workflows) items.push({ id: wf.name, name: wf.displayName || wf.name, entityType: 'workflow', role: `v${wf.version}` });
} catch { /* skip */ }
}
} catch { /* ignore */ }
const [projRes, reqRes, taskRes, delRes, teamsRes] = await Promise.all([
api.projects.list().catch(() => ({ projects: [] as Array<{ id: string; name: string; status: string }> })),
api.requirements.list().catch(() => ({ requirements: [] as Array<{ id: string; title: string; priority: string }> })),
api.tasks.list({ pageSize: 100 }).catch(() => ({ tasks: [] as Array<{ id: string; title: string; status: string }> })),
api.deliverables.search({ limit: 100 }).catch(() => ({ results: [] as Array<{ id: string; title: string; type: string }> })),
api.teams.list().catch(() => ({ teams: [] as TeamInfo[], ungrouped: [] })),
]);
for (const p of projRes.projects) items.push({ id: p.id, name: p.name, entityType: 'project', role: p.status });
for (const r of reqRes.requirements) items.push({ id: r.id, name: r.title, entityType: 'requirement', role: r.priority });
for (const tk of taskRes.tasks) items.push({ id: tk.id, name: tk.title, entityType: 'task', role: tk.status });
for (const d of delRes.results) items.push({ id: d.id, name: d.title, entityType: 'deliverable', role: d.type });
for (const team of teamsRes.teams) {
try {
const wfRes = await api.workflows.list(team.id);
for (const wf of wfRes.workflows) items.push({ id: wf.name, name: wf.displayName || wf.name, entityType: 'workflow', role: `v${wf.version}` });
} catch { /* skip */ }
}
setEntityMentionItems(items);
})();
} catch { /* ignore */ }
}, []);

useEffect(() => {
if (previewMode) return;
void loadEntityMentions();
}, [previewMode, loadEntityMentions]);

const activeTeamId = chatMode === 'channel'
? groupChats.find(gc => gc.channelKey === activeChannel)?.teamId
: undefined;
Expand Down Expand Up @@ -1000,7 +1006,7 @@ export function TeamPage({ initialAgentId, authUser, previewMode, previewData }:
setHumans(previewData.humans ?? []);
setTeams(previewData.teams ?? []);
setGroupChats(previewData.groupChats ?? []);
if (previewData.channelMessages) {
if (previewData.channelMessages && !previewData.streamLastMessage) {
const ch = previewData.activeChannel ?? 'custom:general';
setMessages(previewData.channelMessages.filter(m => m.channel === ch).map(m => channelMsgToChat(m)));
}
Expand Down Expand Up @@ -4825,8 +4831,8 @@ export function TeamPage({ initialAgentId, authUser, previewMode, previewData }:
<div ref={chatScrollRef} className={`${isEmptyChat ? 'hidden' : 'flex-1'} overflow-y-auto scrollbar-thin ${isMobile ? 'p-2.5' : `p-5 ${chatRightReserve}`}`} onScroll={handleChatScroll} onTouchStart={isMobile ? mainTabSwipe.onTouchStart : undefined} onTouchEnd={isMobile ? mainTabSwipe.onTouchEnd : undefined}>

{visibleMessages.length > 0 && (
<div style={{ height: chatVirtualizer.getTotalSize(), width: '100%', position: 'relative' }}>
{chatVirtualizer.getVirtualItems().map(virtualRow => {
<div style={previewMode ? undefined : { height: chatVirtualizer.getTotalSize(), width: '100%', position: 'relative' }}>
{(previewMode ? (() => { const start = Math.max(0, visibleMessages.length - 6); return visibleMessages.slice(start).map((_, i) => ({ index: start + i, start: 0 })); })() : chatVirtualizer.getVirtualItems()).map(virtualRow => {
const vIdx = virtualRow.index;
const msg = visibleMessages[vIdx]!;
const prevMsg = vIdx > 0 ? visibleMessages[vIdx - 1] : null;
Expand All @@ -4845,8 +4851,8 @@ export function TeamPage({ initialAgentId, authUser, previewMode, previewData }:
<div
key={msg.id}
data-index={vIdx}
ref={chatVirtualizer.measureElement}
style={{ position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${virtualRow.start}px)` }}
ref={previewMode ? undefined : chatVirtualizer.measureElement}
style={previewMode ? undefined : { position: 'absolute', top: 0, left: 0, width: '100%', transform: `translateY(${virtualRow.start}px)` }}
>
<div className="pb-3">
{showDateSep && (
Expand Down
10 changes: 10 additions & 0 deletions packages/web-ui/src/showcase/ShowcaseProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,16 @@ function ShowcaseContent({ children, lang }: ShowcaseProviderProps) {
}

export function ShowcaseProvider({ children, lang }: ShowcaseProviderProps) {
// Force the embedded web-ui demo to use the dark theme regardless of the
// host OS light/dark preference. The hub landing page itself is dark, so a
// light-mode OS would otherwise flip the in-page product demos to light and
// make them clash ("刺眼") against the dark page. `html.dark` only affects
// the `--color-*` tokens consumed by web-ui, not the hub's own CSS vars.
useEffect(() => {
const root = document.documentElement;
if (!root.classList.contains('dark')) root.classList.add('dark');
}, []);

return (
<ForceDesktopContext.Provider value={true}>
<I18nextProvider i18n={i18n}>
Expand Down
Loading
Loading