Show proxy status in UI

This commit is contained in:
Gregory Schier
2026-03-11 15:09:21 -07:00
parent 90365f0723
commit f51f72a332
13 changed files with 289 additions and 194 deletions

View File

@@ -1,95 +1,24 @@
import type { Color } from '@yaakapp-internal/plugins';
import classNames from 'classnames';
import type { HTMLAttributes, ReactNode } from 'react';
import {
Button as BaseButton,
type ButtonProps as BaseButtonProps,
} from '@yaakapp-internal/ui';
import { forwardRef, useImperativeHandle, useRef } from 'react';
import type { HotkeyAction } from '../../hooks/useHotKey';
import { useFormattedHotkey, useHotKey } from '../../hooks/useHotKey';
import { Icon, LoadingIcon } from '@yaakapp-internal/ui';
export type ButtonProps = Omit<HTMLAttributes<HTMLButtonElement>, 'color' | 'onChange'> & {
innerClassName?: string;
color?: Color | 'custom' | 'default';
variant?: 'border' | 'solid';
isLoading?: boolean;
size?: '2xs' | 'xs' | 'sm' | 'md' | 'auto';
justify?: 'start' | 'center';
type?: 'button' | 'submit';
forDropdown?: boolean;
disabled?: boolean;
title?: string;
leftSlot?: ReactNode;
rightSlot?: ReactNode;
export type ButtonProps = BaseButtonProps & {
hotkeyAction?: HotkeyAction;
hotkeyLabelOnly?: boolean;
hotkeyPriority?: number;
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
{
isLoading,
className,
innerClassName,
children,
forDropdown,
color = 'default',
type = 'button',
justify = 'center',
size = 'md',
variant = 'solid',
leftSlot,
rightSlot,
disabled,
hotkeyAction,
hotkeyPriority,
hotkeyLabelOnly,
title,
onClick,
...props
}: ButtonProps,
{ hotkeyAction, hotkeyPriority, hotkeyLabelOnly, title, ...props }: ButtonProps,
ref,
) {
const hotkeyTrigger = useFormattedHotkey(hotkeyAction ?? null)?.join('');
const fullTitle = hotkeyTrigger ? `${title ?? ''} ${hotkeyTrigger}`.trim() : title;
if (isLoading) {
disabled = true;
}
const classes = classNames(
className,
'x-theme-button',
`x-theme-button--${variant}`,
`x-theme-button--${variant}--${color}`,
'border', // They all have borders to ensure the same width
'max-w-full min-w-0', // Help with truncation
'hocus:opacity-100', // Force opacity for certain hover effects
'whitespace-nowrap outline-none',
'flex-shrink-0 flex items-center',
'outline-0',
disabled ? 'pointer-events-none opacity-disabled' : 'pointer-events-auto',
justify === 'start' && 'justify-start',
justify === 'center' && 'justify-center',
size === 'md' && 'h-md px-3 rounded-md',
size === 'sm' && 'h-sm px-2.5 rounded-md',
size === 'xs' && 'h-xs px-2 text-sm rounded-md',
size === '2xs' && 'h-2xs px-2 text-xs rounded',
// Solids
variant === 'solid' && 'border-transparent',
variant === 'solid' && color === 'custom' && 'focus-visible:outline-2 outline-border-focus',
variant === 'solid' &&
color !== 'custom' &&
'text-text enabled:hocus:text-text enabled:hocus:bg-surface-highlight outline-border-subtle',
variant === 'solid' && color !== 'custom' && color !== 'default' && 'bg-surface',
// Borders
variant === 'border' && 'border',
variant === 'border' &&
color !== 'custom' &&
'border-border-subtle text-text-subtle enabled:hocus:border-border ' +
'enabled:hocus:bg-surface-highlight enabled:hocus:text-text outline-border-subtler',
);
const buttonRef = useRef<HTMLButtonElement>(null);
useImperativeHandle<HTMLButtonElement | null, HTMLButtonElement | null>(
ref,
@@ -104,43 +33,5 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
{ priority: hotkeyPriority, enable: !hotkeyLabelOnly },
);
return (
<button
ref={buttonRef}
type={type}
className={classes}
disabled={disabled}
onClick={onClick}
onDoubleClick={(e) => {
// Kind of a hack? This prevents double-clicks from going through buttons. For example, when
// double-clicking the workspace header to toggle window maximization
e.stopPropagation();
}}
title={fullTitle}
{...props}
>
{isLoading ? (
<LoadingIcon size={size === 'auto' ? 'md' : size} className="mr-1" />
) : leftSlot ? (
<div className="mr-2">{leftSlot}</div>
) : null}
<div
className={classNames(
'truncate w-full',
justify === 'start' ? 'text-left' : 'text-center',
innerClassName,
)}
>
{children}
</div>
{rightSlot && <div className="ml-1">{rightSlot}</div>}
{forDropdown && (
<Icon
icon="chevron_down"
size={size === 'auto' ? 'md' : size}
className="ml-1 -mr-1 relative top-[0.1em]"
/>
)}
</button>
);
return <BaseButton ref={buttonRef} title={fullTitle} {...props} />;
});

View File

@@ -36,6 +36,19 @@ export function initGlobalListeners() {
showToast({ ...event.payload });
});
// Show errors for any plugins that failed to load during startup
invokeCmd<[string, string][]>("cmd_plugin_init_errors").then((errors) => {
for (const [dir, err] of errors) {
const name = dir.split(/[/\\]/).pop() ?? dir;
showToast({
id: `plugin-init-error-${name}`,
color: "danger",
timeout: null,
message: `Failed to load plugin "${name}": ${err}`,
});
}
});
listenToTauriEvent("settings", () => openSettings.mutate(null));
// Track active dynamic form dialogs so follow-up input updates can reach them

View File

@@ -41,6 +41,7 @@ type TauriCmd =
| 'cmd_new_child_window'
| 'cmd_new_main_window'
| 'cmd_plugin_info'
| 'cmd_plugin_init_errors'
| 'cmd_reload_plugins'
| 'cmd_render_template'
| 'cmd_save_response'

View File

@@ -1,10 +1,10 @@
import { Button, type ButtonProps } from "@yaakapp-internal/ui";
import { useCallback, useState } from "react";
import type { ActionInvocation } from "@yaakapp-internal/proxy-lib";
import { useActionMetadata } from "./hooks";
import { rpc } from "./rpc";
import type { ActionInvocation } from '@yaakapp-internal/proxy-lib';
import { Button, type ButtonProps } from '@yaakapp-internal/ui';
import { useCallback } from 'react';
import { useActionMetadata } from './hooks';
import { useRpcMutation } from './rpc-hooks';
type ActionButtonProps = Omit<ButtonProps, "onClick" | "children"> & {
type ActionButtonProps = Omit<ButtonProps, 'onClick' | 'children'> & {
action: ActionInvocation;
/** Override the label from metadata */
children?: React.ReactNode;
@@ -12,20 +12,20 @@ type ActionButtonProps = Omit<ButtonProps, "onClick" | "children"> & {
export function ActionButton({ action, children, ...props }: ActionButtonProps) {
const meta = useActionMetadata(action);
const [busy, setBusy] = useState(false);
const { mutate, isPending } = useRpcMutation('execute_action');
const onClick = useCallback(async () => {
setBusy(true);
try {
await rpc("execute_action", action);
} finally {
setBusy(false);
}
}, [action]);
const onClick = useCallback(() => {
mutate(action);
}, [action, mutate]);
return (
<Button {...props} disabled={props.disabled || busy} isLoading={busy} onClick={onClick}>
{children ?? meta?.label ?? "…"}
<Button
{...props}
disabled={props.disabled || isPending}
isLoading={isPending}
onClick={onClick}
>
{children ?? meta?.label ?? '…'}
</Button>
);
}

View File

@@ -1,46 +1,47 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { type } from "@tauri-apps/plugin-os";
import { HeaderSize } from "@yaakapp-internal/ui";
import { ActionButton } from "./ActionButton";
import { Sidebar } from "./Sidebar";
import classNames from "classnames";
import { createStore, Provider, useAtomValue } from "jotai";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./main.css";
import { initHotkeys } from "./hotkeys";
import { listen, rpc } from "./rpc";
import { applyChange, dataAtom, httpExchangesAtom, replaceAll } from "./store";
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { type } from '@tauri-apps/plugin-os';
import { HeaderSize } from '@yaakapp-internal/ui';
import classNames from 'classnames';
import { createStore, Provider, useAtomValue } from 'jotai';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { ActionButton } from './ActionButton';
import { Sidebar } from './Sidebar';
import './main.css';
import { initHotkeys } from './hotkeys';
import { listen, rpc } from './rpc';
import { useRpcQueryWithEvent } from './rpc-hooks';
import { applyChange, dataAtom, httpExchangesAtom, replaceAll } from './store';
const queryClient = new QueryClient();
const jotaiStore = createStore();
// Load initial models from the database
rpc("list_models", {}).then((res) => {
jotaiStore.set(dataAtom, (prev) =>
replaceAll(prev, "http_exchange", res.httpExchanges),
);
rpc('list_models', {}).then((res) => {
jotaiStore.set(dataAtom, (prev) => replaceAll(prev, 'http_exchange', res.httpExchanges));
});
// Register hotkeys from action metadata
initHotkeys();
// Subscribe to model change events from the backend
listen("model_write", (payload) => {
listen('model_write', (payload) => {
jotaiStore.set(dataAtom, (prev) =>
applyChange(prev, "http_exchange", payload.model, payload.change),
applyChange(prev, 'http_exchange', payload.model, payload.change),
);
});
function App() {
const osType = type();
const exchanges = useAtomValue(httpExchangesAtom);
const { data: proxyState } = useRpcQueryWithEvent('get_proxy_state', {}, 'proxy_state_changed');
const isRunning = proxyState?.state === 'running';
return (
<div
className={classNames(
"h-full w-full grid grid-rows-[auto_1fr]",
osType === "linux" && "border border-border-subtle",
'h-full w-full grid grid-rows-[auto_1fr]',
osType === 'linux' && 'border border-border-subtle',
)}
>
<HeaderSize
@@ -63,15 +64,25 @@ function App() {
<main className="overflow-auto p-4">
<div className="flex items-center gap-3 mb-4">
<ActionButton
action={{ scope: "global", action: "proxy_start" }}
action={{ scope: 'global', action: 'proxy_start' }}
size="sm"
tone="primary"
disabled={isRunning}
/>
<ActionButton
action={{ scope: "global", action: "proxy_stop" }}
action={{ scope: 'global', action: 'proxy_stop' }}
size="sm"
variant="border"
disabled={!isRunning}
/>
<span
className={classNames(
'text-xs font-medium',
isRunning ? 'text-success' : 'text-text-subtlest',
)}
>
{isRunning ? 'Running on :9090' : 'Stopped'}
</span>
</div>
<div className="text-xs font-mono">
@@ -91,7 +102,7 @@ function App() {
<tr key={ex.id} className="border-b border-border-subtle">
<td className="py-1 pr-3">{ex.method}</td>
<td className="py-1 pr-3 truncate max-w-md">{ex.url}</td>
<td className="py-1 pr-3">{ex.resStatus ?? "—"}</td>
<td className="py-1 pr-3">{ex.resStatus ?? '—'}</td>
</tr>
))}
</tbody>
@@ -104,7 +115,7 @@ function App() {
);
}
createRoot(document.getElementById("root") as HTMLElement).render(
createRoot(document.getElementById('root') as HTMLElement).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<Provider store={jotaiStore}>

View File

@@ -0,0 +1,78 @@
import {
useQuery,
useQueryClient,
useMutation,
type UseQueryOptions,
type UseMutationOptions,
} from "@tanstack/react-query";
import { useEffect } from "react";
import type { RpcEventSchema, RpcSchema } from "@yaakapp-internal/proxy-lib";
import { minPromiseMillis } from "@yaakapp-internal/ui";
import { listen, rpc } from "./rpc";
type Req<K extends keyof RpcSchema> = RpcSchema[K][0];
type Res<K extends keyof RpcSchema> = RpcSchema[K][1];
/**
* React Query wrapper for RPC commands.
* Automatically caches by [cmd, payload] and supports all useQuery options.
*/
export function useRpcQuery<K extends keyof RpcSchema>(
cmd: K,
payload: Req<K>,
opts?: Omit<UseQueryOptions<Res<K>>, "queryKey" | "queryFn">,
) {
return useQuery<Res<K>>({
queryKey: [cmd, payload],
queryFn: () => rpc(cmd, payload),
...opts,
});
}
/**
* React Query mutation wrapper for RPC commands.
*/
export function useRpcMutation<K extends keyof RpcSchema>(
cmd: K,
opts?: Omit<UseMutationOptions<Res<K>, Error, Req<K>>, "mutationFn">,
) {
return useMutation<Res<K>, Error, Req<K>>({
mutationFn: (payload) => minPromiseMillis(rpc(cmd, payload)),
...opts,
});
}
/**
* Subscribe to an RPC event. Cleans up automatically on unmount.
*/
export function useRpcEvent<K extends keyof RpcEventSchema>(
event: K & string,
callback: (payload: RpcEventSchema[K]) => void,
) {
useEffect(() => {
return listen(event, callback);
}, [event, callback]);
}
/**
* Combines useRpcQuery with an event listener that invalidates the query
* whenever the specified event fires, keeping data fresh automatically.
*/
export function useRpcQueryWithEvent<
K extends keyof RpcSchema,
E extends keyof RpcEventSchema & string,
>(
cmd: K,
payload: Req<K>,
event: E,
opts?: Omit<UseQueryOptions<Res<K>>, "queryKey" | "queryFn">,
) {
const queryClient = useQueryClient();
const query = useRpcQuery(cmd, payload, opts);
useRpcEvent(event, () => {
queryClient.invalidateQueries({ queryKey: [cmd, payload] });
});
return query;
}