mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-04-23 17:18:32 +02:00
Show proxy status in UI
This commit is contained in:
@@ -1,95 +1,24 @@
|
|||||||
import type { Color } from '@yaakapp-internal/plugins';
|
import {
|
||||||
import classNames from 'classnames';
|
Button as BaseButton,
|
||||||
import type { HTMLAttributes, ReactNode } from 'react';
|
type ButtonProps as BaseButtonProps,
|
||||||
|
} from '@yaakapp-internal/ui';
|
||||||
import { forwardRef, useImperativeHandle, useRef } from 'react';
|
import { forwardRef, useImperativeHandle, useRef } from 'react';
|
||||||
import type { HotkeyAction } from '../../hooks/useHotKey';
|
import type { HotkeyAction } from '../../hooks/useHotKey';
|
||||||
import { useFormattedHotkey, useHotKey } from '../../hooks/useHotKey';
|
import { useFormattedHotkey, useHotKey } from '../../hooks/useHotKey';
|
||||||
import { Icon, LoadingIcon } from '@yaakapp-internal/ui';
|
|
||||||
|
|
||||||
export type ButtonProps = Omit<HTMLAttributes<HTMLButtonElement>, 'color' | 'onChange'> & {
|
export type ButtonProps = BaseButtonProps & {
|
||||||
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;
|
|
||||||
hotkeyAction?: HotkeyAction;
|
hotkeyAction?: HotkeyAction;
|
||||||
hotkeyLabelOnly?: boolean;
|
hotkeyLabelOnly?: boolean;
|
||||||
hotkeyPriority?: number;
|
hotkeyPriority?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
|
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
|
||||||
{
|
{ hotkeyAction, hotkeyPriority, hotkeyLabelOnly, title, ...props }: ButtonProps,
|
||||||
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,
|
|
||||||
ref,
|
ref,
|
||||||
) {
|
) {
|
||||||
const hotkeyTrigger = useFormattedHotkey(hotkeyAction ?? null)?.join('');
|
const hotkeyTrigger = useFormattedHotkey(hotkeyAction ?? null)?.join('');
|
||||||
const fullTitle = hotkeyTrigger ? `${title ?? ''} ${hotkeyTrigger}`.trim() : title;
|
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);
|
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||||
useImperativeHandle<HTMLButtonElement | null, HTMLButtonElement | null>(
|
useImperativeHandle<HTMLButtonElement | null, HTMLButtonElement | null>(
|
||||||
ref,
|
ref,
|
||||||
@@ -104,43 +33,5 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button
|
|||||||
{ priority: hotkeyPriority, enable: !hotkeyLabelOnly },
|
{ priority: hotkeyPriority, enable: !hotkeyLabelOnly },
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return <BaseButton ref={buttonRef} title={fullTitle} {...props} />;
|
||||||
<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>
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -36,6 +36,19 @@ export function initGlobalListeners() {
|
|||||||
showToast({ ...event.payload });
|
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));
|
listenToTauriEvent("settings", () => openSettings.mutate(null));
|
||||||
|
|
||||||
// Track active dynamic form dialogs so follow-up input updates can reach them
|
// Track active dynamic form dialogs so follow-up input updates can reach them
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ type TauriCmd =
|
|||||||
| 'cmd_new_child_window'
|
| 'cmd_new_child_window'
|
||||||
| 'cmd_new_main_window'
|
| 'cmd_new_main_window'
|
||||||
| 'cmd_plugin_info'
|
| 'cmd_plugin_info'
|
||||||
|
| 'cmd_plugin_init_errors'
|
||||||
| 'cmd_reload_plugins'
|
| 'cmd_reload_plugins'
|
||||||
| 'cmd_render_template'
|
| 'cmd_render_template'
|
||||||
| 'cmd_save_response'
|
| 'cmd_save_response'
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { Button, type ButtonProps } from "@yaakapp-internal/ui";
|
import type { ActionInvocation } from '@yaakapp-internal/proxy-lib';
|
||||||
import { useCallback, useState } from "react";
|
import { Button, type ButtonProps } from '@yaakapp-internal/ui';
|
||||||
import type { ActionInvocation } from "@yaakapp-internal/proxy-lib";
|
import { useCallback } from 'react';
|
||||||
import { useActionMetadata } from "./hooks";
|
import { useActionMetadata } from './hooks';
|
||||||
import { rpc } from "./rpc";
|
import { useRpcMutation } from './rpc-hooks';
|
||||||
|
|
||||||
type ActionButtonProps = Omit<ButtonProps, "onClick" | "children"> & {
|
type ActionButtonProps = Omit<ButtonProps, 'onClick' | 'children'> & {
|
||||||
action: ActionInvocation;
|
action: ActionInvocation;
|
||||||
/** Override the label from metadata */
|
/** Override the label from metadata */
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
@@ -12,20 +12,20 @@ type ActionButtonProps = Omit<ButtonProps, "onClick" | "children"> & {
|
|||||||
|
|
||||||
export function ActionButton({ action, children, ...props }: ActionButtonProps) {
|
export function ActionButton({ action, children, ...props }: ActionButtonProps) {
|
||||||
const meta = useActionMetadata(action);
|
const meta = useActionMetadata(action);
|
||||||
const [busy, setBusy] = useState(false);
|
const { mutate, isPending } = useRpcMutation('execute_action');
|
||||||
|
|
||||||
const onClick = useCallback(async () => {
|
const onClick = useCallback(() => {
|
||||||
setBusy(true);
|
mutate(action);
|
||||||
try {
|
}, [action, mutate]);
|
||||||
await rpc("execute_action", action);
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
}, [action]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Button {...props} disabled={props.disabled || busy} isLoading={busy} onClick={onClick}>
|
<Button
|
||||||
{children ?? meta?.label ?? "…"}
|
{...props}
|
||||||
|
disabled={props.disabled || isPending}
|
||||||
|
isLoading={isPending}
|
||||||
|
onClick={onClick}
|
||||||
|
>
|
||||||
|
{children ?? meta?.label ?? '…'}
|
||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +1,47 @@
|
|||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||||
import { type } from "@tauri-apps/plugin-os";
|
import { type } from '@tauri-apps/plugin-os';
|
||||||
import { HeaderSize } from "@yaakapp-internal/ui";
|
import { HeaderSize } from '@yaakapp-internal/ui';
|
||||||
import { ActionButton } from "./ActionButton";
|
import classNames from 'classnames';
|
||||||
import { Sidebar } from "./Sidebar";
|
import { createStore, Provider, useAtomValue } from 'jotai';
|
||||||
import classNames from "classnames";
|
import { StrictMode } from 'react';
|
||||||
import { createStore, Provider, useAtomValue } from "jotai";
|
import { createRoot } from 'react-dom/client';
|
||||||
import { StrictMode } from "react";
|
import { ActionButton } from './ActionButton';
|
||||||
import { createRoot } from "react-dom/client";
|
import { Sidebar } from './Sidebar';
|
||||||
import "./main.css";
|
import './main.css';
|
||||||
import { initHotkeys } from "./hotkeys";
|
import { initHotkeys } from './hotkeys';
|
||||||
import { listen, rpc } from "./rpc";
|
import { listen, rpc } from './rpc';
|
||||||
import { applyChange, dataAtom, httpExchangesAtom, replaceAll } from "./store";
|
import { useRpcQueryWithEvent } from './rpc-hooks';
|
||||||
|
import { applyChange, dataAtom, httpExchangesAtom, replaceAll } from './store';
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
const jotaiStore = createStore();
|
const jotaiStore = createStore();
|
||||||
|
|
||||||
// Load initial models from the database
|
// Load initial models from the database
|
||||||
rpc("list_models", {}).then((res) => {
|
rpc('list_models', {}).then((res) => {
|
||||||
jotaiStore.set(dataAtom, (prev) =>
|
jotaiStore.set(dataAtom, (prev) => replaceAll(prev, 'http_exchange', res.httpExchanges));
|
||||||
replaceAll(prev, "http_exchange", res.httpExchanges),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Register hotkeys from action metadata
|
// Register hotkeys from action metadata
|
||||||
initHotkeys();
|
initHotkeys();
|
||||||
|
|
||||||
// Subscribe to model change events from the backend
|
// Subscribe to model change events from the backend
|
||||||
listen("model_write", (payload) => {
|
listen('model_write', (payload) => {
|
||||||
jotaiStore.set(dataAtom, (prev) =>
|
jotaiStore.set(dataAtom, (prev) =>
|
||||||
applyChange(prev, "http_exchange", payload.model, payload.change),
|
applyChange(prev, 'http_exchange', payload.model, payload.change),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const osType = type();
|
const osType = type();
|
||||||
const exchanges = useAtomValue(httpExchangesAtom);
|
const exchanges = useAtomValue(httpExchangesAtom);
|
||||||
|
const { data: proxyState } = useRpcQueryWithEvent('get_proxy_state', {}, 'proxy_state_changed');
|
||||||
|
const isRunning = proxyState?.state === 'running';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={classNames(
|
className={classNames(
|
||||||
"h-full w-full grid grid-rows-[auto_1fr]",
|
'h-full w-full grid grid-rows-[auto_1fr]',
|
||||||
osType === "linux" && "border border-border-subtle",
|
osType === 'linux' && 'border border-border-subtle',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<HeaderSize
|
<HeaderSize
|
||||||
@@ -63,15 +64,25 @@ function App() {
|
|||||||
<main className="overflow-auto p-4">
|
<main className="overflow-auto p-4">
|
||||||
<div className="flex items-center gap-3 mb-4">
|
<div className="flex items-center gap-3 mb-4">
|
||||||
<ActionButton
|
<ActionButton
|
||||||
action={{ scope: "global", action: "proxy_start" }}
|
action={{ scope: 'global', action: 'proxy_start' }}
|
||||||
size="sm"
|
size="sm"
|
||||||
tone="primary"
|
tone="primary"
|
||||||
|
disabled={isRunning}
|
||||||
/>
|
/>
|
||||||
<ActionButton
|
<ActionButton
|
||||||
action={{ scope: "global", action: "proxy_stop" }}
|
action={{ scope: 'global', action: 'proxy_stop' }}
|
||||||
size="sm"
|
size="sm"
|
||||||
variant="border"
|
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>
|
||||||
|
|
||||||
<div className="text-xs font-mono">
|
<div className="text-xs font-mono">
|
||||||
@@ -91,7 +102,7 @@ function App() {
|
|||||||
<tr key={ex.id} className="border-b border-border-subtle">
|
<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">{ex.method}</td>
|
||||||
<td className="py-1 pr-3 truncate max-w-md">{ex.url}</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>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -104,7 +115,7 @@ function App() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
createRoot(document.getElementById("root") as HTMLElement).render(
|
createRoot(document.getElementById('root') as HTMLElement).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<Provider store={jotaiStore}>
|
<Provider store={jotaiStore}>
|
||||||
|
|||||||
78
apps/yaak-proxy/rpc-hooks.ts
Normal file
78
apps/yaak-proxy/rpc-hooks.ts
Normal 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;
|
||||||
|
}
|
||||||
12
crates-proxy/yaak-proxy-lib/bindings/gen_rpc.ts
generated
12
crates-proxy/yaak-proxy-lib/bindings/gen_rpc.ts
generated
@@ -5,6 +5,10 @@ export type ActionInvocation = { "scope": "global", action: GlobalAction, };
|
|||||||
|
|
||||||
export type ActionMetadata = { label: string, defaultHotkey: string | null, };
|
export type ActionMetadata = { label: string, defaultHotkey: string | null, };
|
||||||
|
|
||||||
|
export type GetProxyStateRequest = Record<string, never>;
|
||||||
|
|
||||||
|
export type GetProxyStateResponse = { state: ProxyState, };
|
||||||
|
|
||||||
export type GlobalAction = "proxy_start" | "proxy_stop";
|
export type GlobalAction = "proxy_start" | "proxy_stop";
|
||||||
|
|
||||||
export type ListActionsRequest = Record<string, never>;
|
export type ListActionsRequest = Record<string, never>;
|
||||||
@@ -15,6 +19,10 @@ export type ListModelsRequest = Record<string, never>;
|
|||||||
|
|
||||||
export type ListModelsResponse = { httpExchanges: Array<HttpExchange>, };
|
export type ListModelsResponse = { httpExchanges: Array<HttpExchange>, };
|
||||||
|
|
||||||
export type RpcEventSchema = { model_write: ModelPayload, };
|
export type ProxyState = "running" | "stopped";
|
||||||
|
|
||||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], list_actions: [ListActionsRequest, ListActionsResponse], list_models: [ListModelsRequest, ListModelsResponse], };
|
export type ProxyStatePayload = { state: ProxyState, };
|
||||||
|
|
||||||
|
export type RpcEventSchema = { model_write: ModelPayload, proxy_state_changed: ProxyStatePayload, };
|
||||||
|
|
||||||
|
export type RpcSchema = { execute_action: [ActionInvocation, boolean], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], list_actions: [ListActionsRequest, ListActionsResponse], list_models: [ListModelsRequest, ListModelsResponse], };
|
||||||
|
|||||||
@@ -33,6 +33,22 @@ impl ProxyCtx {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// -- Proxy state --
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
#[ts(export, export_to = "gen_rpc.ts")]
|
||||||
|
pub enum ProxyState {
|
||||||
|
Running,
|
||||||
|
Stopped,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, TS)]
|
||||||
|
#[ts(export, export_to = "gen_rpc.ts")]
|
||||||
|
pub struct ProxyStatePayload {
|
||||||
|
pub state: ProxyState,
|
||||||
|
}
|
||||||
|
|
||||||
// -- Request/response types --
|
// -- Request/response types --
|
||||||
|
|
||||||
#[derive(Deserialize, TS)]
|
#[derive(Deserialize, TS)]
|
||||||
@@ -56,6 +72,16 @@ pub struct ListModelsResponse {
|
|||||||
pub http_exchanges: Vec<HttpExchange>,
|
pub http_exchanges: Vec<HttpExchange>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, TS)]
|
||||||
|
#[ts(export, export_to = "gen_rpc.ts")]
|
||||||
|
pub struct GetProxyStateRequest {}
|
||||||
|
|
||||||
|
#[derive(Serialize, TS)]
|
||||||
|
#[ts(export, export_to = "gen_rpc.ts")]
|
||||||
|
pub struct GetProxyStateResponse {
|
||||||
|
pub state: ProxyState,
|
||||||
|
}
|
||||||
|
|
||||||
// -- Handlers --
|
// -- Handlers --
|
||||||
|
|
||||||
fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool, RpcError> {
|
fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool, RpcError> {
|
||||||
@@ -81,6 +107,9 @@ fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool,
|
|||||||
}
|
}
|
||||||
|
|
||||||
*handle = Some(proxy_handle);
|
*handle = Some(proxy_handle);
|
||||||
|
ctx.events.emit("proxy_state_changed", &ProxyStatePayload {
|
||||||
|
state: ProxyState::Running,
|
||||||
|
});
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
GlobalAction::ProxyStop => {
|
GlobalAction::ProxyStop => {
|
||||||
@@ -89,12 +118,28 @@ fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool,
|
|||||||
.lock()
|
.lock()
|
||||||
.map_err(|_| RpcError { message: "lock poisoned".into() })?;
|
.map_err(|_| RpcError { message: "lock poisoned".into() })?;
|
||||||
handle.take();
|
handle.take();
|
||||||
|
ctx.events.emit("proxy_state_changed", &ProxyStatePayload {
|
||||||
|
state: ProxyState::Stopped,
|
||||||
|
});
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_proxy_state(ctx: &ProxyCtx, _req: GetProxyStateRequest) -> Result<GetProxyStateResponse, RpcError> {
|
||||||
|
let handle = ctx
|
||||||
|
.handle
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| RpcError { message: "lock poisoned".into() })?;
|
||||||
|
let state = if handle.is_some() {
|
||||||
|
ProxyState::Running
|
||||||
|
} else {
|
||||||
|
ProxyState::Stopped
|
||||||
|
};
|
||||||
|
Ok(GetProxyStateResponse { state })
|
||||||
|
}
|
||||||
|
|
||||||
fn list_actions(_ctx: &ProxyCtx, _req: ListActionsRequest) -> Result<ListActionsResponse, RpcError> {
|
fn list_actions(_ctx: &ProxyCtx, _req: ListActionsRequest) -> Result<ListActionsResponse, RpcError> {
|
||||||
Ok(ListActionsResponse {
|
Ok(ListActionsResponse {
|
||||||
actions: crate::actions::all_global_actions(),
|
actions: crate::actions::all_global_actions(),
|
||||||
@@ -216,10 +261,12 @@ define_rpc! {
|
|||||||
ProxyCtx;
|
ProxyCtx;
|
||||||
commands {
|
commands {
|
||||||
execute_action(ActionInvocation) -> bool,
|
execute_action(ActionInvocation) -> bool,
|
||||||
|
get_proxy_state(GetProxyStateRequest) -> GetProxyStateResponse,
|
||||||
list_actions(ListActionsRequest) -> ListActionsResponse,
|
list_actions(ListActionsRequest) -> ListActionsResponse,
|
||||||
list_models(ListModelsRequest) -> ListModelsResponse,
|
list_models(ListModelsRequest) -> ListModelsResponse,
|
||||||
}
|
}
|
||||||
events {
|
events {
|
||||||
model_write(ModelPayload),
|
model_write(ModelPayload),
|
||||||
|
proxy_state_changed(ProxyStatePayload),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1450,6 +1450,13 @@ async fn cmd_reload_plugins<R: Runtime>(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn cmd_plugin_init_errors(
|
||||||
|
plugin_manager: State<'_, PluginManager>,
|
||||||
|
) -> YaakResult<Vec<(String, String)>> {
|
||||||
|
Ok(plugin_manager.take_init_errors().await)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn cmd_plugin_info<R: Runtime>(
|
async fn cmd_plugin_info<R: Runtime>(
|
||||||
id: &str,
|
id: &str,
|
||||||
@@ -1728,6 +1735,7 @@ pub fn run() {
|
|||||||
cmd_new_child_window,
|
cmd_new_child_window,
|
||||||
cmd_new_main_window,
|
cmd_new_main_window,
|
||||||
cmd_plugin_info,
|
cmd_plugin_info,
|
||||||
|
cmd_plugin_init_errors,
|
||||||
cmd_reload_plugins,
|
cmd_reload_plugins,
|
||||||
cmd_render_template,
|
cmd_render_template,
|
||||||
cmd_restart,
|
cmd_restart,
|
||||||
|
|||||||
@@ -50,6 +50,8 @@ pub struct PluginManager {
|
|||||||
vendored_plugin_dir: PathBuf,
|
vendored_plugin_dir: PathBuf,
|
||||||
pub(crate) installed_plugin_dir: PathBuf,
|
pub(crate) installed_plugin_dir: PathBuf,
|
||||||
dev_mode: bool,
|
dev_mode: bool,
|
||||||
|
/// Errors from plugin initialization, retrievable once via `take_init_errors`.
|
||||||
|
init_errors: Arc<Mutex<Vec<(String, String)>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Callback for plugin initialization events (e.g., toast notifications)
|
/// Callback for plugin initialization events (e.g., toast notifications)
|
||||||
@@ -93,6 +95,7 @@ impl PluginManager {
|
|||||||
vendored_plugin_dir,
|
vendored_plugin_dir,
|
||||||
installed_plugin_dir,
|
installed_plugin_dir,
|
||||||
dev_mode,
|
dev_mode,
|
||||||
|
init_errors: Default::default(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Forward events to subscribers
|
// Forward events to subscribers
|
||||||
@@ -183,17 +186,21 @@ impl PluginManager {
|
|||||||
|
|
||||||
let init_errors = plugin_manager.initialize_all_plugins(plugins, plugin_context).await;
|
let init_errors = plugin_manager.initialize_all_plugins(plugins, plugin_context).await;
|
||||||
if !init_errors.is_empty() {
|
if !init_errors.is_empty() {
|
||||||
let joined = init_errors
|
for (dir, err) in &init_errors {
|
||||||
.into_iter()
|
error!("Failed to initialize plugin {dir}: {err}");
|
||||||
.map(|(dir, err)| format!("{dir}: {err}"))
|
}
|
||||||
.collect::<Vec<_>>()
|
*plugin_manager.init_errors.lock().await = init_errors;
|
||||||
.join("; ");
|
|
||||||
return Err(PluginErr(format!("Failed to initialize plugin(s): {joined}")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(plugin_manager)
|
Ok(plugin_manager)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Take and clear any plugin initialization errors.
|
||||||
|
/// Returns the errors only once — subsequent calls return an empty list.
|
||||||
|
pub async fn take_init_errors(&self) -> Vec<(String, String)> {
|
||||||
|
std::mem::take(&mut *self.init_errors.lock().await)
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the vendored plugin directory path (resolves dev mode path if applicable)
|
/// Get the vendored plugin directory path (resolves dev mode path if applicable)
|
||||||
pub fn get_plugins_dir(&self) -> PathBuf {
|
pub fn get_plugins_dir(&self) -> PathBuf {
|
||||||
if self.dev_mode {
|
if self.dev_mode {
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import type { Color } from "@yaakapp-internal/plugins";
|
import type { Color } from "@yaakapp-internal/plugins";
|
||||||
|
import classNames from "classnames";
|
||||||
import type { HTMLAttributes, ReactNode } from "react";
|
import type { HTMLAttributes, ReactNode } from "react";
|
||||||
|
import { forwardRef } from "react";
|
||||||
|
import { Icon } from "./Icon";
|
||||||
|
import { LoadingIcon } from "./LoadingIcon";
|
||||||
|
|
||||||
type ButtonVariant = "border" | "solid";
|
type ButtonVariant = "border" | "solid";
|
||||||
type ButtonSize = "2xs" | "xs" | "sm" | "md" | "auto";
|
type ButtonSize = "2xs" | "xs" | "sm" | "md" | "auto";
|
||||||
@@ -16,41 +20,43 @@ export type ButtonProps = Omit<
|
|||||||
size?: ButtonSize;
|
size?: ButtonSize;
|
||||||
justify?: "start" | "center";
|
justify?: "start" | "center";
|
||||||
type?: "button" | "submit";
|
type?: "button" | "submit";
|
||||||
|
forDropdown?: boolean;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
title?: string;
|
title?: string;
|
||||||
leftSlot?: ReactNode;
|
leftSlot?: ReactNode;
|
||||||
rightSlot?: ReactNode;
|
rightSlot?: ReactNode;
|
||||||
};
|
};
|
||||||
|
|
||||||
function cx(...values: Array<string | false | null | undefined>) {
|
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(function Button(
|
||||||
return values.filter(Boolean).join(" ");
|
{
|
||||||
}
|
isLoading,
|
||||||
|
className,
|
||||||
export function Button({
|
innerClassName,
|
||||||
isLoading,
|
children,
|
||||||
className,
|
color,
|
||||||
innerClassName,
|
tone,
|
||||||
children,
|
forDropdown,
|
||||||
color,
|
type = "button",
|
||||||
tone,
|
justify = "center",
|
||||||
type = "button",
|
size = "md",
|
||||||
justify = "center",
|
variant = "solid",
|
||||||
size = "md",
|
leftSlot,
|
||||||
variant = "solid",
|
rightSlot,
|
||||||
leftSlot,
|
disabled,
|
||||||
rightSlot,
|
title,
|
||||||
disabled,
|
onClick,
|
||||||
title,
|
...props
|
||||||
onClick,
|
}: ButtonProps,
|
||||||
...props
|
ref,
|
||||||
}: ButtonProps) {
|
) {
|
||||||
const resolvedColor = color ?? tone ?? "default";
|
const resolvedColor = color ?? tone ?? "default";
|
||||||
const isDisabled = disabled || isLoading;
|
const isDisabled = disabled || isLoading;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
|
ref={ref}
|
||||||
type={type}
|
type={type}
|
||||||
className={cx(
|
className={classNames(
|
||||||
className,
|
className,
|
||||||
"x-theme-button",
|
"x-theme-button",
|
||||||
`x-theme-button--${variant}`,
|
`x-theme-button--${variant}`,
|
||||||
@@ -83,7 +89,8 @@ export function Button({
|
|||||||
variant === "border" && "border",
|
variant === "border" && "border",
|
||||||
variant === "border" &&
|
variant === "border" &&
|
||||||
resolvedColor !== "custom" &&
|
resolvedColor !== "custom" &&
|
||||||
"border-border-subtle text-text-subtle enabled:hocus:border-border enabled:hocus:bg-surface-highlight enabled:hocus:text-text outline-border-subtler",
|
"border-border-subtle text-text-subtle enabled:hocus:border-border " +
|
||||||
|
"enabled:hocus:bg-surface-highlight enabled:hocus:text-text outline-border-subtler",
|
||||||
)}
|
)}
|
||||||
disabled={isDisabled}
|
disabled={isDisabled}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
@@ -94,12 +101,12 @@ export function Button({
|
|||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<div className="mr-1">...</div>
|
<LoadingIcon size={size === "auto" ? "md" : size} className="mr-1" />
|
||||||
) : leftSlot ? (
|
) : leftSlot ? (
|
||||||
<div className="mr-2">{leftSlot}</div>
|
<div className="mr-2">{leftSlot}</div>
|
||||||
) : null}
|
) : null}
|
||||||
<div
|
<div
|
||||||
className={cx(
|
className={classNames(
|
||||||
"truncate w-full",
|
"truncate w-full",
|
||||||
justify === "start" ? "text-left" : "text-center",
|
justify === "start" ? "text-left" : "text-center",
|
||||||
innerClassName,
|
innerClassName,
|
||||||
@@ -107,7 +114,14 @@ export function Button({
|
|||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
{rightSlot ? <div className="ml-1">{rightSlot}</div> : null}
|
{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>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
});
|
||||||
|
|||||||
@@ -16,3 +16,4 @@ export type { TreeHandle, TreeProps } from "./components/tree/Tree";
|
|||||||
export type { TreeNode } from "./components/tree/common";
|
export type { TreeNode } from "./components/tree/common";
|
||||||
export type { TreeItemProps } from "./components/tree/TreeItem";
|
export type { TreeItemProps } from "./components/tree/TreeItem";
|
||||||
export { isSelectedFamily, selectedIdsFamily } from "./components/tree/atoms";
|
export { isSelectedFamily, selectedIdsFamily } from "./components/tree/atoms";
|
||||||
|
export { minPromiseMillis } from "./lib/minPromiseMillis";
|
||||||
|
|||||||
16
packages/ui/src/lib/minPromiseMillis.ts
Normal file
16
packages/ui/src/lib/minPromiseMillis.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export async function minPromiseMillis<T>(promise: Promise<T>, millis = 300): Promise<T> {
|
||||||
|
const start = Date.now();
|
||||||
|
let result: T;
|
||||||
|
|
||||||
|
try {
|
||||||
|
result = await promise;
|
||||||
|
} catch (e) {
|
||||||
|
const remaining = millis - (Date.now() - start);
|
||||||
|
if (remaining > 0) await new Promise((r) => setTimeout(r, remaining));
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remaining = millis - (Date.now() - start);
|
||||||
|
if (remaining > 0) await new Promise((r) => setTimeout(r, remaining));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user