mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-28 03:02:38 +01:00
Proxy GUI pass (#793)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
96ab0a8a60
commit
e82ffc53ad
73 files changed
+6003
-1257
No files matched your search
@@ -12,7 +12,7 @@ export function ErrorBoundary({ name, children }: { name: string; children: Reac
|
||||
);
|
||||
}
|
||||
|
||||
function showErrorDialog(error: unknown) {
|
||||
export function showErrorDialog(error: unknown) {
|
||||
showDialog({ id: "error-boundary", render: () => <RouteError error={error} /> });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,43 +1,6 @@
|
||||
import { useAtomValue } from "jotai";
|
||||
import { AnimatePresence } from "motion/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { hideToast, toastsAtom } from "../lib/toast";
|
||||
import { Toast, type ToastProps } from "./core/Toast";
|
||||
import { ErrorBoundary } from "./ErrorBoundary";
|
||||
import { Portal } from "@yaakapp-internal/ui";
|
||||
import { Toasts as BaseToasts } from "@yaakapp-internal/ui";
|
||||
import { showErrorDialog } from "./ErrorBoundary";
|
||||
|
||||
export type ToastInstance = {
|
||||
id: string;
|
||||
uniqueKey: string;
|
||||
message: ReactNode;
|
||||
timeout: 3000 | 5000 | 8000 | (number & {}) | null;
|
||||
onClose?: ToastProps["onClose"];
|
||||
} & Omit<ToastProps, "onClose" | "open" | "children" | "timeout">;
|
||||
export type { ToastInstance } from "@yaakapp-internal/ui";
|
||||
|
||||
export const Toasts = () => {
|
||||
const toasts = useAtomValue(toastsAtom);
|
||||
return (
|
||||
<Portal name="toasts">
|
||||
<div className="absolute right-0 bottom-0 z-50">
|
||||
<AnimatePresence>
|
||||
{toasts.map((toast: ToastInstance) => {
|
||||
const { message, uniqueKey, ...props } = toast;
|
||||
return (
|
||||
<ErrorBoundary key={uniqueKey} name={`Toast ${uniqueKey}`}>
|
||||
<Toast
|
||||
open
|
||||
{...props}
|
||||
// We call onClose inside actions.hide instead of passing to toast so that
|
||||
// it gets called from external close calls as well
|
||||
onClose={() => hideToast(toast)}
|
||||
>
|
||||
{message}
|
||||
</Toast>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
})}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</Portal>
|
||||
);
|
||||
};
|
||||
export const Toasts = () => <BaseToasts onShowError={showErrorDialog} />;
|
||||
@@ -1,72 +1,2 @@
|
||||
import { HStack, Icon, IconTooltip } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export interface CheckboxProps {
|
||||
checked: boolean | "indeterminate";
|
||||
title: ReactNode;
|
||||
onChange: (checked: boolean) => void;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
inputWrapperClassName?: string;
|
||||
hideLabel?: boolean;
|
||||
fullWidth?: boolean;
|
||||
help?: ReactNode;
|
||||
size?: "sm" | "md";
|
||||
}
|
||||
|
||||
export function Checkbox({
|
||||
checked,
|
||||
onChange,
|
||||
className,
|
||||
inputWrapperClassName,
|
||||
disabled,
|
||||
title,
|
||||
hideLabel,
|
||||
fullWidth,
|
||||
help,
|
||||
size = "sm",
|
||||
}: CheckboxProps) {
|
||||
return (
|
||||
<HStack
|
||||
as="label"
|
||||
alignItems="center"
|
||||
space={2}
|
||||
className={classNames(className, "text-text mr-auto")}
|
||||
>
|
||||
<div className={classNames(inputWrapperClassName, "x-theme-input", "relative flex mr-0.5")}>
|
||||
<input
|
||||
aria-hidden
|
||||
className={classNames(
|
||||
"appearance-none shrink-0 border border-border",
|
||||
size === "sm" && "w-4 h-4",
|
||||
size === "md" && "w-5 h-5",
|
||||
"rounded-sm outline-hidden ring-0",
|
||||
!disabled && "hocus:border-border-focus hocus:bg-focus/[5%]",
|
||||
disabled && "border-dotted",
|
||||
)}
|
||||
type="checkbox"
|
||||
disabled={disabled}
|
||||
onChange={() => {
|
||||
onChange(checked === "indeterminate" ? true : !checked);
|
||||
}}
|
||||
/>
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Icon
|
||||
size={size}
|
||||
className={classNames(disabled && "opacity-disabled")}
|
||||
icon={checked === "indeterminate" ? "minus" : checked ? "check" : "empty"}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{!hideLabel && (
|
||||
<div
|
||||
className={classNames("text-sm", fullWidth && "w-full", disabled && "opacity-disabled")}
|
||||
>
|
||||
{title}
|
||||
</div>
|
||||
)}
|
||||
{help && <IconTooltip content={help} />}
|
||||
</HStack>
|
||||
);
|
||||
}
|
||||
export type { CheckboxProps } from "@yaakapp-internal/ui";
|
||||
export { Checkbox } from "@yaakapp-internal/ui";
|
||||
@@ -1,200 +1,2 @@
|
||||
import type { DialogSize } from "@yaakapp-internal/plugins";
|
||||
import { Heading, HStack, Overlay } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import * as m from "motion/react-m";
|
||||
import type { ReactNode } from "react";
|
||||
import { createContext, useContext, useMemo, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { Button, type ButtonProps } from "./Button";
|
||||
import { IconButton } from "./IconButton";
|
||||
|
||||
export interface DialogProps {
|
||||
children: ReactNode;
|
||||
open: boolean;
|
||||
onClose?: () => void;
|
||||
/** Block dismissal from the backdrop, Escape key, and built-in close button. */
|
||||
disableClose?: boolean;
|
||||
title?: ReactNode;
|
||||
description?: ReactNode;
|
||||
className?: string;
|
||||
size?: DialogSize;
|
||||
/** Hide the built-in close button without changing backdrop or Escape behavior. */
|
||||
hideX?: boolean;
|
||||
noPadding?: boolean;
|
||||
noScroll?: boolean;
|
||||
vAlign?: "top" | "center";
|
||||
}
|
||||
|
||||
export function Dialog({
|
||||
children,
|
||||
className,
|
||||
size = "full",
|
||||
open,
|
||||
onClose,
|
||||
disableClose,
|
||||
title,
|
||||
description,
|
||||
hideX,
|
||||
noPadding,
|
||||
noScroll,
|
||||
vAlign = "center",
|
||||
}: DialogProps) {
|
||||
const titleId = useMemo(() => Math.random().toString(36).slice(2), []);
|
||||
const [footerEl, setFooterEl] = useState<HTMLDivElement | null>(null);
|
||||
const descriptionId = useMemo(
|
||||
() => (description ? Math.random().toString(36).slice(2) : undefined),
|
||||
[description],
|
||||
);
|
||||
|
||||
return (
|
||||
<Overlay open={open} onClose={disableClose ? undefined : onClose} portalName="dialog">
|
||||
<div
|
||||
role="dialog"
|
||||
className={classNames(
|
||||
"py-4 x-theme-dialog absolute inset-0 pointer-events-none",
|
||||
"h-full flex flex-col items-center justify-center",
|
||||
vAlign === "top" && "justify-start",
|
||||
vAlign === "center" && "justify-center",
|
||||
)}
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={descriptionId}
|
||||
tabIndex={-1}
|
||||
onKeyDown={(e) => {
|
||||
// NOTE: We handle Escape on the element itself so that it doesn't close multiple
|
||||
// dialogs and can be intercepted by children if needed.
|
||||
if (e.key === "Escape") {
|
||||
if (!disableClose) onClose?.();
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<m.div
|
||||
initial={{ top: 5, scale: 0.97 }}
|
||||
animate={{ top: 0, scale: 1 }}
|
||||
className={classNames(
|
||||
className,
|
||||
"grid grid-rows-[auto_auto_minmax(0,1fr)_auto]",
|
||||
"grid-cols-1", // must be here for inline code blocks to correctly break words
|
||||
"relative bg-surface pointer-events-auto",
|
||||
"rounded-lg",
|
||||
"border border-border-subtle shadow-lg shadow-[rgba(0,0,0,0.1)]",
|
||||
"min-h-40",
|
||||
"max-w-[calc(100vw-5rem)] max-h-[calc(100vh-5rem)]",
|
||||
size === "sm" && "w-120",
|
||||
size === "md" && "w-200",
|
||||
size === "lg" && "w-280",
|
||||
size === "full" && "w-screen h-screen",
|
||||
size === "dynamic" && "min-w-80 max-w-[100vw]",
|
||||
)}
|
||||
>
|
||||
{title ? (
|
||||
<Heading className="px-6 mt-4 mb-2" level={1} id={titleId}>
|
||||
{title}
|
||||
</Heading>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
|
||||
{description ? (
|
||||
<div className="min-h-0 px-6 text-text-subtle mb-3" id={descriptionId}>
|
||||
{description}
|
||||
</div>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
|
||||
<div
|
||||
className={classNames(
|
||||
"h-full w-full grid grid-cols-[minmax(0,1fr)] grid-rows-1",
|
||||
!noPadding && "px-6 py-2",
|
||||
!noScroll && "overflow-y-auto overflow-x-hidden",
|
||||
)}
|
||||
>
|
||||
<DialogFooterSlot.Provider value={footerEl}>{children}</DialogFooterSlot.Provider>
|
||||
</div>
|
||||
|
||||
<div ref={setFooterEl} className="contents" />
|
||||
|
||||
{/*Put close at the end so that it's the last thing to be tabbed to*/}
|
||||
{!disableClose && !hideX && (
|
||||
<div className="ml-auto absolute right-1 top-1">
|
||||
<IconButton
|
||||
className="opacity-70 hover:opacity-100"
|
||||
onClick={onClose}
|
||||
title="Close dialog (Esc)"
|
||||
aria-label="Close"
|
||||
size="sm"
|
||||
icon="x"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</m.div>
|
||||
</div>
|
||||
</Overlay>
|
||||
);
|
||||
}
|
||||
|
||||
const DialogFooterSlot = createContext<HTMLDivElement | null>(null);
|
||||
|
||||
export interface DialogFooterAction {
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
/** Submit the form with this id, which can be anywhere in the dialog body */
|
||||
form?: string;
|
||||
color?: ButtonProps["color"];
|
||||
variant?: ButtonProps["variant"];
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
autoFocus?: boolean;
|
||||
leftSlot?: ReactNode;
|
||||
rightSlot?: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* The action row at the bottom of a dialog. Render it anywhere in the dialog's content and it is
|
||||
* placed below the scrolling body, outside its padding. `inline` drops the divider for small
|
||||
* dialogs whose body never scrolls.
|
||||
*/
|
||||
export function DialogFooter({
|
||||
actions,
|
||||
leftSlot,
|
||||
inline,
|
||||
}: {
|
||||
actions: DialogFooterAction[];
|
||||
leftSlot?: ReactNode;
|
||||
inline?: boolean;
|
||||
}) {
|
||||
const slot = useContext(DialogFooterSlot);
|
||||
const footer = (
|
||||
<footer
|
||||
className={classNames(
|
||||
"px-6 flex items-center gap-3",
|
||||
inline ? "pt-1 pb-4" : "py-3 border-t border-border-subtle",
|
||||
)}
|
||||
>
|
||||
{leftSlot != null && <div className="mr-auto min-w-0">{leftSlot}</div>}
|
||||
<HStack space={2} justifyContent="end" className="ml-auto shrink-0">
|
||||
{actions.map((action, i) => (
|
||||
<Button
|
||||
// Labels change with state ("Cloning...", "Apply 3 Changes"), so they can't be keys
|
||||
key={i}
|
||||
type={action.form != null ? "submit" : "button"}
|
||||
form={action.form}
|
||||
color={action.color ?? "secondary"}
|
||||
variant={action.variant ?? (action.color == null ? "border" : "solid")}
|
||||
disabled={action.disabled}
|
||||
isLoading={action.isLoading}
|
||||
autoFocus={action.autoFocus}
|
||||
leftSlot={action.leftSlot}
|
||||
rightSlot={action.rightSlot}
|
||||
onClick={action.onClick}
|
||||
>
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</HStack>
|
||||
</footer>
|
||||
);
|
||||
return slot == null ? footer : createPortal(footer, slot);
|
||||
}
|
||||
export type { DialogFooterAction, DialogProps } from "@yaakapp-internal/ui";
|
||||
export { Dialog, DialogFooter } from "@yaakapp-internal/ui";
|
||||
@@ -1,242 +1,2 @@
|
||||
import { HStack, useStateWithDeps, Label } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import type { FocusEvent, InputHTMLAttributes, ReactNode } from "react";
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useRandomKey } from "../../hooks/useRandomKey";
|
||||
import { IconButton } from "./IconButton";
|
||||
import type { InputProps } from "./Input";
|
||||
import { generateId } from "@yaakapp-internal/lib/generateId";
|
||||
|
||||
export type PlainInputProps = Omit<
|
||||
InputProps,
|
||||
| "wrapLines"
|
||||
| "onKeyDown"
|
||||
| "type"
|
||||
| "stateKey"
|
||||
| "autocompleteVariables"
|
||||
| "autocompleteFunctions"
|
||||
| "autocomplete"
|
||||
| "extraExtensions"
|
||||
| "forcedEnvironmentId"
|
||||
> &
|
||||
Pick<InputHTMLAttributes<HTMLInputElement>, "inputMode" | "onKeyDownCapture" | "step"> & {
|
||||
onFocusRaw?: InputHTMLAttributes<HTMLInputElement>["onFocus"];
|
||||
type?: "text" | "password" | "number";
|
||||
hideObscureToggle?: boolean;
|
||||
labelRightSlot?: ReactNode;
|
||||
};
|
||||
|
||||
export const PlainInput = forwardRef<{ focus: () => void }, PlainInputProps>(function PlainInput(
|
||||
{
|
||||
autoFocus,
|
||||
autoSelect,
|
||||
className,
|
||||
containerClassName,
|
||||
defaultValue,
|
||||
disabled,
|
||||
forceUpdateKey: forceUpdateKeyFromAbove,
|
||||
help,
|
||||
hideLabel,
|
||||
hideObscureToggle,
|
||||
label,
|
||||
labelClassName,
|
||||
labelPosition = "top",
|
||||
labelRightSlot,
|
||||
inputMode,
|
||||
leftSlot,
|
||||
name,
|
||||
onBlur,
|
||||
onChange,
|
||||
onFocus,
|
||||
onFocusRaw,
|
||||
onKeyDownCapture,
|
||||
onPaste,
|
||||
placeholder,
|
||||
required,
|
||||
rightSlot,
|
||||
size = "md",
|
||||
step,
|
||||
tint,
|
||||
type = "text",
|
||||
validate,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
// Track a local key for updates. If the default value is changed when the input is not in focus,
|
||||
// regenerate this to force the field to update.
|
||||
const [focusedUpdateKey, regenerateFocusedUpdateKey] = useRandomKey();
|
||||
const forceUpdateKey = `${forceUpdateKeyFromAbove}::${focusedUpdateKey}`;
|
||||
|
||||
const [obscured, setObscured] = useStateWithDeps(type === "password", [type]);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [hasChanged, setHasChanged] = useStateWithDeps<boolean>(false, [forceUpdateKey]);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useImperativeHandle<{ focus: () => void } | null, { focus: () => void } | null>(
|
||||
ref,
|
||||
() => inputRef.current,
|
||||
);
|
||||
|
||||
const handleFocus = useCallback(
|
||||
(e: FocusEvent<HTMLInputElement>) => {
|
||||
onFocusRaw?.(e);
|
||||
setFocused(true);
|
||||
if (autoSelect) {
|
||||
inputRef.current?.select();
|
||||
textareaRef.current?.select();
|
||||
}
|
||||
onFocus?.();
|
||||
},
|
||||
[autoSelect, onFocus, onFocusRaw],
|
||||
);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setFocused(false);
|
||||
onBlur?.();
|
||||
}, [onBlur]);
|
||||
|
||||
// Force input to update when receiving change and not in focus
|
||||
useLayoutEffect(() => {
|
||||
const isFocused = document.activeElement === inputRef.current;
|
||||
if (defaultValue != null && !isFocused) {
|
||||
regenerateFocusedUpdateKey();
|
||||
}
|
||||
}, [regenerateFocusedUpdateKey, defaultValue]);
|
||||
|
||||
const id = useRef(`input-${generateId()}`);
|
||||
const commonClassName = classNames(
|
||||
className,
|
||||
"bg-transparent! min-w-0 w-full focus:outline-hidden placeholder:text-placeholder",
|
||||
"px-2 text-xs font-mono cursor-text",
|
||||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(value: string) => {
|
||||
onChange?.(value);
|
||||
setHasChanged(true);
|
||||
const isValid = (value: string) => {
|
||||
if (required && !validateRequire(value)) return false;
|
||||
if (typeof validate === "boolean") return validate;
|
||||
if (typeof validate === "function" && !validate(value)) return false;
|
||||
return true;
|
||||
};
|
||||
inputRef.current?.setCustomValidity(isValid(value) ? "" : "Invalid value");
|
||||
},
|
||||
[onChange, required, setHasChanged, validate],
|
||||
);
|
||||
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={wrapperRef}
|
||||
className={classNames(
|
||||
"w-full",
|
||||
"pointer-events-auto", // Just in case we're placing in disabled parent
|
||||
labelPosition === "left" && "flex items-center gap-2",
|
||||
labelPosition === "top" && "flex-row gap-0.5",
|
||||
)}
|
||||
>
|
||||
<Label
|
||||
htmlFor={id.current}
|
||||
className={labelClassName}
|
||||
visuallyHidden={hideLabel}
|
||||
required={required}
|
||||
help={help}
|
||||
rightSlot={labelRightSlot}
|
||||
>
|
||||
{label}
|
||||
</Label>
|
||||
<HStack
|
||||
alignItems="stretch"
|
||||
className={classNames(
|
||||
containerClassName,
|
||||
"x-theme-input",
|
||||
"relative w-full rounded-md text",
|
||||
"border",
|
||||
"overflow-hidden",
|
||||
focused && !disabled ? "border-border-focus" : "border-border-subtle",
|
||||
disabled && "border-dotted",
|
||||
hasChanged && "has-invalid:border-danger", // For built-in HTML validation
|
||||
size === "md" && "min-h-md",
|
||||
size === "sm" && "min-h-sm",
|
||||
size === "xs" && "min-h-xs",
|
||||
size === "2xs" && "min-h-2xs",
|
||||
)}
|
||||
>
|
||||
{tint != null && (
|
||||
<div
|
||||
aria-hidden
|
||||
className={classNames(
|
||||
"absolute inset-0 opacity-5 pointer-events-none",
|
||||
tint === "info" && "bg-info",
|
||||
tint === "warning" && "bg-warning",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{leftSlot}
|
||||
<HStack
|
||||
className={classNames(
|
||||
"w-full min-w-0",
|
||||
leftSlot ? "pl-0.5 -ml-2" : null,
|
||||
rightSlot ? "pr-0.5 -mr-2" : null,
|
||||
)}
|
||||
>
|
||||
<input
|
||||
id={id.current}
|
||||
ref={inputRef}
|
||||
key={forceUpdateKey}
|
||||
type={type === "password" && !obscured ? "text" : type}
|
||||
name={name}
|
||||
// oxlint-disable-next-line jsx-a11y/no-autofocus
|
||||
autoFocus={autoFocus}
|
||||
defaultValue={defaultValue ?? undefined}
|
||||
disabled={disabled}
|
||||
autoComplete="off"
|
||||
autoCapitalize="off"
|
||||
autoCorrect="off"
|
||||
writingsuggestions="false"
|
||||
inputMode={inputMode}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
onPaste={(e) => onPaste?.(e.clipboardData.getData("Text"))}
|
||||
className={classNames(commonClassName, "h-full disabled:opacity-disabled")}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
required={required}
|
||||
step={step}
|
||||
placeholder={placeholder}
|
||||
onKeyDownCapture={onKeyDownCapture}
|
||||
/>
|
||||
</HStack>
|
||||
{type === "password" && !hideObscureToggle && (
|
||||
<IconButton
|
||||
title={
|
||||
obscured
|
||||
? `Show ${typeof label === "string" ? label : "field"}`
|
||||
: `Obscure ${typeof label === "string" ? label : "field"}`
|
||||
}
|
||||
size="xs"
|
||||
className="mr-0.5 group/obscure h-auto! my-0.5"
|
||||
iconClassName="group-hover/obscure:text"
|
||||
iconSize="sm"
|
||||
icon={obscured ? "eye" : "eye_closed"}
|
||||
onClick={() => setObscured((o) => !o)}
|
||||
/>
|
||||
)}
|
||||
{rightSlot}
|
||||
</HStack>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
function validateRequire(v: string) {
|
||||
return v.length > 0;
|
||||
}
|
||||
export type { PlainInputProps } from "@yaakapp-internal/ui";
|
||||
export { PlainInput } from "@yaakapp-internal/ui";
|
||||
@@ -1,148 +1,2 @@
|
||||
import type { ShowToastRequest } from "@yaakapp-internal/plugins";
|
||||
import { Icon, type IconProps, VStack } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import * as m from "motion/react-m";
|
||||
import type { ReactNode } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useKey } from "react-use";
|
||||
import { IconButton } from "./IconButton";
|
||||
|
||||
export interface ToastProps {
|
||||
children: ReactNode;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
className?: string;
|
||||
timeout: number | null;
|
||||
action?: (args: { hide: () => void }) => ReactNode;
|
||||
icon?: ShowToastRequest["icon"] | null;
|
||||
color?: ShowToastRequest["color"];
|
||||
// Grow with the content (up to the viewport) instead of scrolling internally
|
||||
// past the default max height
|
||||
dynamicHeight?: boolean;
|
||||
// Hide the close button, for toasts that render their own dismiss action.
|
||||
// Escape still closes the toast
|
||||
hideDismiss?: boolean;
|
||||
}
|
||||
|
||||
const ICONS: Record<NonNullable<ToastProps["color"] | "custom">, IconProps["icon"] | null> = {
|
||||
custom: null,
|
||||
danger: "alert_triangle",
|
||||
info: "info",
|
||||
notice: "alert_triangle",
|
||||
primary: "info",
|
||||
secondary: "info",
|
||||
success: "check_circle",
|
||||
warning: "alert_triangle",
|
||||
};
|
||||
|
||||
export function Toast({
|
||||
children,
|
||||
open,
|
||||
onClose,
|
||||
timeout,
|
||||
action,
|
||||
icon,
|
||||
color,
|
||||
dynamicHeight,
|
||||
hideDismiss,
|
||||
}: ToastProps) {
|
||||
const onCloseRef = useRef(onClose);
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [autoHideCanceled, setAutoHideCanceled] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
onCloseRef.current = onClose;
|
||||
}, [onClose]);
|
||||
|
||||
const cancelAutoHide = useCallback(() => {
|
||||
if (timeoutRef.current == null) return;
|
||||
clearTimeout(timeoutRef.current);
|
||||
timeoutRef.current = null;
|
||||
setAutoHideCanceled(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || timeout == null || autoHideCanceled) return;
|
||||
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
timeoutRef.current = null;
|
||||
onCloseRef.current();
|
||||
}, timeout);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current == null) return;
|
||||
clearTimeout(timeoutRef.current);
|
||||
timeoutRef.current = null;
|
||||
};
|
||||
}, [autoHideCanceled, open, timeout]);
|
||||
|
||||
useKey(
|
||||
"Escape",
|
||||
() => {
|
||||
if (!open) return;
|
||||
onClose();
|
||||
},
|
||||
{},
|
||||
[open],
|
||||
);
|
||||
|
||||
const toastIcon = icon === null ? null : (icon ?? (color && color in ICONS && ICONS[color]));
|
||||
|
||||
return (
|
||||
<m.div
|
||||
initial={{ opacity: 0, right: "-10%" }}
|
||||
animate={{ opacity: 100, right: 0 }}
|
||||
exit={{ opacity: 0, right: "-100%" }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className={classNames("bg-surface m-2 rounded-lg")}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
`x-theme-toast x-theme-toast--${color}`,
|
||||
"pointer-events-auto overflow-hidden",
|
||||
"relative pointer-events-auto bg-surface text-text rounded-lg",
|
||||
"border border-border shadow-lg w-100",
|
||||
)}
|
||||
onFocusCapture={cancelAutoHide}
|
||||
onKeyDownCapture={cancelAutoHide}
|
||||
onPointerDownCapture={cancelAutoHide}
|
||||
>
|
||||
<div
|
||||
className={classNames(
|
||||
"pl-3 py-3 flex items-start gap-2 w-full overflow-auto",
|
||||
hideDismiss ? "pr-3" : "pr-10",
|
||||
dynamicHeight ? "max-h-[80vh]" : "max-h-44",
|
||||
)}
|
||||
>
|
||||
{toastIcon && <Icon icon={toastIcon} color={color} className="mt-1 shrink-0" />}
|
||||
<VStack space={2} className="w-full min-w-0">
|
||||
<div className="select-auto">{children}</div>
|
||||
{action?.({ hide: onClose })}
|
||||
</VStack>
|
||||
</div>
|
||||
|
||||
{!hideDismiss && (
|
||||
<IconButton
|
||||
color={color}
|
||||
variant="border"
|
||||
className="opacity-60 border-0 absolute! top-2 right-2"
|
||||
title="Dismiss"
|
||||
icon="x"
|
||||
onClick={onClose}
|
||||
/>
|
||||
)}
|
||||
|
||||
{timeout != null && !autoHideCanceled && (
|
||||
<div className="w-full absolute bottom-0 left-0 right-0">
|
||||
<m.div
|
||||
className="bg-surface-highlight h-[3px]"
|
||||
initial={{ width: "100%" }}
|
||||
animate={{ width: "0%", opacity: 0.2 }}
|
||||
transition={{ duration: timeout / 1000, ease: "linear" }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</m.div>
|
||||
);
|
||||
}
|
||||
export type { ToastProps } from "@yaakapp-internal/ui";
|
||||
export { Toast } from "@yaakapp-internal/ui";
|
||||
@@ -1,8 +1 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import { generateId } from "@yaakapp-internal/lib/generateId";
|
||||
|
||||
export function useRandomKey(initialValue?: string) {
|
||||
const [value, setValue] = useState<string>(initialValue ?? generateId());
|
||||
const regenerate = useCallback(() => setValue(generateId()), []);
|
||||
return [value, regenerate] as const;
|
||||
}
|
||||
export { useRandomKey } from "@yaakapp-internal/ui";
|
||||
@@ -1,43 +1,9 @@
|
||||
import type { AnyModel } from "@yaakapp-internal/models";
|
||||
import { foldersAtom } from "@yaakapp-internal/models";
|
||||
import { resolvedModelName } from "@yaakapp-internal/ui/resolvedModelName";
|
||||
import { jotaiStore } from "./jotai";
|
||||
import { replaceTemplateTags } from "./templateTags";
|
||||
|
||||
export function resolvedModelName(r: AnyModel | null): string {
|
||||
if (r == null) return "";
|
||||
|
||||
if (!("url" in r) || r.model === "plugin") {
|
||||
return "name" in r ? r.name : "";
|
||||
}
|
||||
|
||||
// Return name if it has one
|
||||
if ("name" in r && r.name) {
|
||||
return r.name;
|
||||
}
|
||||
|
||||
// Replace variable syntax with variable name
|
||||
const withoutVariables = replaceTemplateTags(r.url, (m) => m.inner.trim());
|
||||
if (withoutVariables.trim() === "") {
|
||||
return r.model === "http_request"
|
||||
? r.bodyType && r.bodyType === "graphql"
|
||||
? "GraphQL Request"
|
||||
: "HTTP Request"
|
||||
: r.model === "websocket_request"
|
||||
? "WebSocket Request"
|
||||
: "gRPC Request";
|
||||
}
|
||||
|
||||
// GRPC gets nice short names
|
||||
if (r.model === "grpc_request" && r.service != null && r.method != null) {
|
||||
const shortService = r.service.split(".").pop();
|
||||
return `${shortService}/${r.method}`;
|
||||
}
|
||||
|
||||
// Strip unnecessary protocol
|
||||
const withoutProto = withoutVariables.replace(/^(http|https|ws|wss):\/\//, "");
|
||||
|
||||
return withoutProto;
|
||||
}
|
||||
export { resolvedModelName };
|
||||
|
||||
export function resolvedModelNameWithFolders(model: AnyModel | null): string {
|
||||
return resolvedModelNameWithFoldersArray(model).join(" / ");
|
||||
|
||||
@@ -1,137 +1,2 @@
|
||||
/*
|
||||
* Finding template tags in text.
|
||||
*
|
||||
* A tag closes at `]}`, but a quoted argument is allowed to contain `]}` of its own — the
|
||||
* printer in `crates/yaak-templates` emits `${[ fn(a='x]}y') ]}` verbatim — so the scan has to
|
||||
* step over quoted strings. It mirrors the Lezer grammar in
|
||||
* `components/core/Editor/twig/twig.grammar`: a terminated `'…'` (where `\` escapes whatever
|
||||
* follows it) is consumed whole, and an unterminated quote is just another character, so a
|
||||
* half-typed tag still closes at the next `]}` instead of swallowing the rest of the document.
|
||||
*
|
||||
* This was a regex until CodeQL flagged it (js/polynomial-redos): matching an unterminated
|
||||
* quote needed a negative lookahead that rescanned to the end of the input at every unpaired
|
||||
* quote, which is quadratic on text an attacker picks. The scan below is linear instead — see
|
||||
* the notes on `closingQuoteTable` and on the dead-end set in `findTemplateTags` for why.
|
||||
*/
|
||||
|
||||
const QUOTE = 0x27; // '
|
||||
const BACKSLASH = 0x5c; // \
|
||||
const CLOSE_BRACKET = 0x5d; // ]
|
||||
const CLOSE_BRACE = 0x7d; // }
|
||||
|
||||
/** The `${[`…`]}` bounds of one tag, and what sits between them. */
|
||||
export interface TemplateTagMatch {
|
||||
/** Index of the `$` that opens the tag. */
|
||||
start: number;
|
||||
/** Index just past the closing `]}`. */
|
||||
end: number;
|
||||
/** Everything between `${[` and `]}`, not trimmed. */
|
||||
inner: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* For every index `i`, the index of the `'` that closes a string whose body starts at `i`, or
|
||||
* `-1` when nothing does.
|
||||
*
|
||||
* Built right to left in a single pass, which is the trick that replaces the regex lookahead:
|
||||
* whether a quote opens a terminated string depends only on the text after it, so the answer
|
||||
* can be computed once for every position instead of re-derived at each quote. Skipping a
|
||||
* string of any length then costs one lookup.
|
||||
*/
|
||||
function closingQuoteTable(text: string): Int32Array {
|
||||
// Two extra slots so a `\` in the last position can read past the end and find `-1`
|
||||
const table = new Int32Array(text.length + 2).fill(-1);
|
||||
for (let i = text.length - 1; i >= 0; i--) {
|
||||
const c = text.charCodeAt(i);
|
||||
// A backslash escapes whatever follows it, including a quote
|
||||
const next = c === BACKSLASH ? table[i + 2] : table[i + 1];
|
||||
table[i] = c === QUOTE ? i : (next ?? -1);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds every template tag in `text`, in order and without overlaps.
|
||||
*
|
||||
* A `${[` with no `]}` after it isn't a tag, and neither is a `${[` nested inside a tag body —
|
||||
* both are ordinary content, same as the regex this replaced treated them.
|
||||
*/
|
||||
export function findTemplateTags(text: string): TemplateTagMatch[] {
|
||||
const matches: TemplateTagMatch[] = [];
|
||||
|
||||
// Both built only once a scan actually needs them, so short values allocate nothing
|
||||
let closingQuotes: Int32Array | null = null;
|
||||
|
||||
/*
|
||||
* Body positions a previous scan already ran off the end of the text from. Where a scan ends
|
||||
* up depends only on where it starts, so a scan that walks into one of these would repeat
|
||||
* that same walk and fail the same way, and can stop right there.
|
||||
*
|
||||
* That bound is what keeps the whole pass linear: every position enters this set at most
|
||||
* once, and every step of every scan either visits a position for the first time or ends
|
||||
* that scan.
|
||||
*/
|
||||
let deadEnds: Set<number> | null = null;
|
||||
|
||||
let searchFrom = 0;
|
||||
while (searchFrom < text.length) {
|
||||
const start = text.indexOf("${[", searchFrom);
|
||||
if (start < 0) break;
|
||||
|
||||
const visited: number[] = [];
|
||||
let end = -1;
|
||||
let i = start + 3;
|
||||
while (i < text.length) {
|
||||
if (deadEnds?.has(i)) break;
|
||||
visited.push(i);
|
||||
|
||||
const c = text.charCodeAt(i);
|
||||
if (c === QUOTE) {
|
||||
closingQuotes ??= closingQuoteTable(text);
|
||||
const close = closingQuotes[i + 1] ?? -1;
|
||||
// An unterminated quote is an ordinary character, so only step over a closed string
|
||||
i = close < 0 ? i + 1 : close + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c === CLOSE_BRACKET && text.charCodeAt(i + 1) === CLOSE_BRACE) {
|
||||
end = i + 2;
|
||||
break;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
if (end < 0) {
|
||||
// Not a tag. Resume past the opener: a real tag may start inside a string this scan
|
||||
// stepped over.
|
||||
deadEnds ??= new Set();
|
||||
for (const position of visited) deadEnds.add(position);
|
||||
searchFrom = start + 3;
|
||||
continue;
|
||||
}
|
||||
|
||||
matches.push({ start, end, inner: text.slice(start + 3, end - 2) });
|
||||
searchFrom = end;
|
||||
}
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
/** Rewrites every template tag in `text` with whatever `replace` returns for it. */
|
||||
export function replaceTemplateTags(
|
||||
text: string,
|
||||
replace: (match: TemplateTagMatch) => string,
|
||||
): string {
|
||||
const matches = findTemplateTags(text);
|
||||
if (matches.length === 0) return text;
|
||||
|
||||
let result = "";
|
||||
let copiedTo = 0;
|
||||
for (const match of matches) {
|
||||
result += text.slice(copiedTo, match.start) + replace(match);
|
||||
copiedTo = match.end;
|
||||
}
|
||||
|
||||
return result + text.slice(copiedTo);
|
||||
}
|
||||
export type { TemplateTagMatch } from "@yaakapp-internal/ui/templateTags";
|
||||
export { findTemplateTags, replaceTemplateTags } from "@yaakapp-internal/ui/templateTags";
|
||||
@@ -1,50 +1,25 @@
|
||||
import { atom } from "jotai";
|
||||
import type { ToastInstance } from "../components/Toasts";
|
||||
import { generateId } from "@yaakapp-internal/lib/generateId";
|
||||
// The toast store alone, without the components, which tests in a plain runtime can't load
|
||||
import {
|
||||
hideToast as hideToastIn,
|
||||
hideToastById as hideToastByIdIn,
|
||||
type ShowToastArgs,
|
||||
showToast as showToastIn,
|
||||
type ToastInstance,
|
||||
} from "@yaakapp-internal/ui/toast";
|
||||
import { jotaiStore } from "./jotai";
|
||||
|
||||
export const toastsAtom = atom<ToastInstance[]>([]);
|
||||
export { toastsAtom } from "@yaakapp-internal/ui/toast";
|
||||
|
||||
export function showToast({
|
||||
id,
|
||||
timeout = 5000,
|
||||
...props
|
||||
}: Omit<ToastInstance, "id" | "timeout" | "uniqueKey"> & {
|
||||
id?: ToastInstance["id"];
|
||||
timeout?: ToastInstance["timeout"];
|
||||
}) {
|
||||
id = id ?? generateId();
|
||||
const uniqueKey = generateId();
|
||||
|
||||
const toasts = jotaiStore.get(toastsAtom);
|
||||
const toastWithSameId = toasts.find((t) => t.id === id);
|
||||
|
||||
let delay = 0;
|
||||
if (toastWithSameId) {
|
||||
hideToast(toastWithSameId);
|
||||
// Allow enough time for old toast to animate out
|
||||
delay = 200;
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
const newToast: ToastInstance = { id, uniqueKey, timeout, ...props };
|
||||
jotaiStore.set(toastsAtom, (prev) => [...prev, newToast]);
|
||||
}, delay);
|
||||
|
||||
return id;
|
||||
export function showToast(args: ShowToastArgs) {
|
||||
return showToastIn(jotaiStore, args);
|
||||
}
|
||||
|
||||
export function hideToastById(id: string) {
|
||||
const toast = jotaiStore.get(toastsAtom).find((t) => t.id === id);
|
||||
if (toast) hideToast(toast);
|
||||
hideToastByIdIn(jotaiStore, id);
|
||||
}
|
||||
|
||||
export function hideToast(toHide: ToastInstance) {
|
||||
jotaiStore.set(toastsAtom, (all) => {
|
||||
const t = all.find((t) => t.uniqueKey === toHide.uniqueKey);
|
||||
t?.onClose?.();
|
||||
return all.filter((t) => t.uniqueKey !== toHide.uniqueKey);
|
||||
});
|
||||
hideToastIn(jotaiStore, toHide);
|
||||
}
|
||||
|
||||
export function showErrorToast<T>({
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import classNames from "classnames";
|
||||
import { useEffect, useState } from "react";
|
||||
import { rpc } from "../lib/rpc";
|
||||
|
||||
/**
|
||||
* Icons by app path, as data URLs once loaded, for the whole session. Plain rather than a query
|
||||
* per icon, since every new row in the list shows one.
|
||||
*/
|
||||
const icons = new Map<string, string | null>();
|
||||
const loading = new Map<string, Promise<string | null>>();
|
||||
|
||||
function loadIcon(path: string): Promise<string | null> {
|
||||
let promise = loading.get(path);
|
||||
if (promise == null) {
|
||||
promise = rpc("app_icon", { path })
|
||||
.then((png) => (png == null ? null : `data:image/png;base64,${png}`))
|
||||
.catch(() => null)
|
||||
.then((url) => {
|
||||
icons.set(path, url);
|
||||
return url;
|
||||
});
|
||||
loading.set(path, promise);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** An app's icon, read once per path for the whole session */
|
||||
export function AppIcon({ path, className }: { path: string; className?: string }) {
|
||||
const [url, setUrl] = useState(() => icons.get(path));
|
||||
useEffect(() => {
|
||||
if (icons.has(path)) {
|
||||
setUrl(icons.get(path));
|
||||
return;
|
||||
}
|
||||
let current = true;
|
||||
void loadIcon(path).then((loaded) => {
|
||||
if (current) setUrl(loaded);
|
||||
});
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [path]);
|
||||
|
||||
return url == null ? (
|
||||
<span aria-hidden className={classNames(className, "inline-block w-4 h-4 shrink-0")} />
|
||||
) : (
|
||||
<img alt="" src={url} className={classNames(className, "w-4 h-4 shrink-0")} />
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import { Button, Icon, LoadingIcon } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import { useAtomValue } from "jotai";
|
||||
import type { ReactNode } from "react";
|
||||
import { useRpcMutation } from "../hooks/useRpcMutation";
|
||||
import { proxyStateAtom } from "../lib/store";
|
||||
import { useCopyEnvironment, useProxySetup, useSystemProxySwitch } from "./ProxyStatus";
|
||||
|
||||
type StepState = "todo" | "next" | "wait" | "done" | "fail";
|
||||
|
||||
/**
|
||||
* The list's empty state until traffic arrives: trust the certificate, turn on the system proxy,
|
||||
* then see traffic. Not dismissable and nothing remembered; the first flow replaces it. Copy
|
||||
* environment beside it serves someone who wants one terminal proxied and nothing system-wide.
|
||||
*/
|
||||
export function FirstRun() {
|
||||
const proxyState = useAtomValue(proxyStateAtom);
|
||||
const setup = useProxySetup();
|
||||
const { caStatus, trust, systemProxy, setSystemProxy } = setup;
|
||||
const systemSwitch = useSystemProxySwitch(setup);
|
||||
const execute = useRpcMutation("execute_action");
|
||||
const retry = useRpcMutation("take_over");
|
||||
const copyEnvironment = useCopyEnvironment();
|
||||
|
||||
const running = proxyState?.state === "running";
|
||||
// Changed only by the process that owns the engine, so not from here while the CLI does.
|
||||
const otherOwner = proxyState?.otherOwner != null;
|
||||
const recording = proxyState?.recording !== false;
|
||||
const trusted = caStatus.data?.trusted === true;
|
||||
const systemSupported = systemProxy.data?.supported !== false;
|
||||
const systemOn = systemProxy.data?.enabled === true;
|
||||
|
||||
const trustState: StepState = trusted
|
||||
? "done"
|
||||
: trust.isPending
|
||||
? "wait"
|
||||
: trust.error != null
|
||||
? "fail"
|
||||
: "next";
|
||||
const systemState: StepState = setSystemProxy.isPending
|
||||
? "wait"
|
||||
: systemOn
|
||||
? "done"
|
||||
: systemSwitch.failed
|
||||
? "fail"
|
||||
: trusted
|
||||
? "next"
|
||||
: "todo";
|
||||
const ready = trusted && (systemOn || !systemSupported);
|
||||
const trafficState: StepState = !running && !otherOwner ? "fail" : ready ? "wait" : "todo";
|
||||
|
||||
return (
|
||||
<div className="grid place-items-center h-full px-10 pb-16 pt-6">
|
||||
<div className="w-full max-w-[40rem]">
|
||||
<div className="text-xl font-semibold mb-1.5">Set up Yaak Proxy</div>
|
||||
<div className="text-text-subtle text-sm leading-relaxed mb-4">
|
||||
Three steps, once. Afterwards every app on this Mac sends its traffic here, and HTTPS
|
||||
reads as plain text.
|
||||
</div>
|
||||
<div className="rounded-lg border border-border-subtle bg-surface divide-y divide-border-subtle">
|
||||
<Step
|
||||
n={1}
|
||||
state={trustState}
|
||||
title={trusted ? "Certificate trusted" : "Trust the certificate"}
|
||||
description={
|
||||
trusted
|
||||
? "Yaak Proxy CA, in your login keychain."
|
||||
: trustState === "wait"
|
||||
? "Waiting for your password in the macOS prompt."
|
||||
: trustState === "fail"
|
||||
? (trust.error?.message ?? "The certificate was not trusted.")
|
||||
: "So HTTPS reads as plain text. macOS asks for your login password once."
|
||||
}
|
||||
action={
|
||||
trustState === "next" || trustState === "fail" ? (
|
||||
<Button
|
||||
size="2xs"
|
||||
variant={trustState === "fail" ? "border" : "solid"}
|
||||
color={trustState === "fail" ? "default" : "primary"}
|
||||
onClick={() => trust.mutate({})}
|
||||
>
|
||||
{trustState === "fail" ? "Try again" : "Trust certificate"}
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
{systemSupported && (
|
||||
<Step
|
||||
n={2}
|
||||
state={systemState}
|
||||
title={systemOn ? "System proxy on" : "Turn on the system proxy"}
|
||||
description={
|
||||
otherOwner && !systemOn
|
||||
? proxyState?.otherOwner?.owner === "cli"
|
||||
? "The CLI owns the proxy. Take over to turn this on from here."
|
||||
: "Another Yaak Proxy window owns the engine. Quit it to use this one."
|
||||
: systemSwitch.description
|
||||
}
|
||||
action={
|
||||
(systemState === "next" || systemState === "fail") && running ? (
|
||||
<Button
|
||||
size="2xs"
|
||||
variant={systemState === "fail" ? "border" : "solid"}
|
||||
color={systemState === "fail" ? "default" : "primary"}
|
||||
onClick={() => setSystemProxy.mutate({ enabled: true })}
|
||||
>
|
||||
{systemState === "fail" ? "Try again" : "Turn on"}
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<Step
|
||||
n={systemSupported ? 3 : 2}
|
||||
state={trafficState}
|
||||
title={trafficState === "wait" ? "Waiting for traffic" : "See traffic"}
|
||||
description={
|
||||
trafficState === "fail"
|
||||
? (retry.error?.message ?? proxyState?.startError ?? "The proxy has not started.")
|
||||
: !recording
|
||||
? "Recording is paused, so traffic passes through without being stored."
|
||||
: trafficState === "wait"
|
||||
? "Open a website or send a request, and its flow appears here."
|
||||
: "Flows appear here as apps send requests."
|
||||
}
|
||||
action={
|
||||
trafficState === "fail" ? (
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
isLoading={retry.isPending}
|
||||
onClick={() => retry.mutate({})}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
) : !recording && running ? (
|
||||
<Button
|
||||
size="2xs"
|
||||
color="primary"
|
||||
onClick={() => execute.mutate({ scope: "global", action: "recording_toggle" })}
|
||||
>
|
||||
Resume recording
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-4 text-sm text-text-subtle">
|
||||
<span>Only need one terminal or one app? Copy the environment instead.</span>
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
className="ml-auto shrink-0"
|
||||
leftSlot={<Icon icon="square_terminal" size="sm" />}
|
||||
onClick={() => void copyEnvironment()}
|
||||
>
|
||||
Copy environment
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Step({
|
||||
n,
|
||||
state,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
}: {
|
||||
n: number;
|
||||
state: StepState;
|
||||
title: string;
|
||||
description: ReactNode;
|
||||
action: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid grid-cols-[1.4rem_minmax(0,1fr)_auto] gap-x-3 items-center px-4 py-3">
|
||||
<StepMark n={n} state={state} />
|
||||
<div className="min-w-0">
|
||||
<div className={classNames("text-sm", state === "todo" ? "text-text-subtle" : "text-text")}>
|
||||
{title}
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
"text-xs mt-0.5",
|
||||
state === "fail" ? "text-danger" : "text-text-subtle",
|
||||
)}
|
||||
>
|
||||
{description}
|
||||
</div>
|
||||
</div>
|
||||
<div>{action}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepMark({ n, state }: { n: number; state: StepState }) {
|
||||
const base = "w-[1.4rem] h-[1.4rem] rounded-full grid place-items-center text-xs";
|
||||
switch (state) {
|
||||
case "done":
|
||||
return (
|
||||
<span className={classNames(base, "bg-success/15 text-success")}>
|
||||
<Icon icon="check" size="sm" />
|
||||
</span>
|
||||
);
|
||||
case "fail":
|
||||
return (
|
||||
<span className={classNames(base, "bg-danger/15 text-danger")}>
|
||||
<Icon icon="x" size="sm" />
|
||||
</span>
|
||||
);
|
||||
case "wait":
|
||||
return (
|
||||
<span className={classNames(base, "text-text-subtle")}>
|
||||
<LoadingIcon size="sm" />
|
||||
</span>
|
||||
);
|
||||
case "next":
|
||||
return <span className={classNames(base, "bg-primary text-white font-semibold")}>{n}</span>;
|
||||
case "todo":
|
||||
return <span className={classNames(base, "border border-border text-text-subtle")}>{n}</span>;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
HStack,
|
||||
HttpStatusTagRaw,
|
||||
Icon,
|
||||
IconButton,
|
||||
SizeTag,
|
||||
type TabButtonRenderProps,
|
||||
type TabItem,
|
||||
@@ -17,11 +18,12 @@ import {
|
||||
Tabs,
|
||||
} from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { useAtomValue, useSetAtom } from "jotai";
|
||||
import type { CSSProperties } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { selectedFlowAtom } from "../lib/atoms";
|
||||
import { findHeader, mimeEssence } from "../lib/body";
|
||||
import { saveDialogFlowAtom, useFlowActions } from "../lib/flowActions";
|
||||
import { statusReason } from "../lib/statusReason";
|
||||
import { EmptyState, FlowBodyViewer, useFlowBody } from "./FlowBodyViewer";
|
||||
import { FlowHeaders, FlowQuery, queryParams } from "./FlowHeaders";
|
||||
@@ -50,10 +52,8 @@ export function FlowDetail({ style, sideBySide }: { style?: CSSProperties; sideB
|
||||
<div className="grid grid-cols-[auto_auto] gap-x-6 gap-y-2 text-left">
|
||||
<span>Select a flow</span>
|
||||
<Keys keys={["↑", "↓"]} />
|
||||
<span>Start the proxy</span>
|
||||
<Keys keys={["⌘", "⇧", "P"]} />
|
||||
<span>Stop the proxy</span>
|
||||
<Keys keys={["⌘", "⇧", "S"]} />
|
||||
<span>Pause or resume recording</span>
|
||||
<Keys keys={["⌘", "R"]} />
|
||||
<span>Clear flows</span>
|
||||
<Keys keys={["⌘", "K"]} />
|
||||
</div>
|
||||
@@ -73,6 +73,8 @@ function FlowPane({ flow }: { flow: Flow }) {
|
||||
const noResponse = flow.error != null && flow.status == null;
|
||||
const mime = mimeEssence(findHeader(flow.responseHeaders, "content-type"));
|
||||
const queryCount = useMemo(() => queryParams(flow.url).length, [flow.url]);
|
||||
const openSave = useSetAtom(saveDialogFlowAtom);
|
||||
const flowActions = useFlowActions();
|
||||
|
||||
const tabs = useMemo<TabItem[]>(
|
||||
() => [
|
||||
@@ -125,7 +127,7 @@ function FlowPane({ flow }: { flow: Flow }) {
|
||||
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1">
|
||||
<div
|
||||
className={classNames(
|
||||
"grid grid-cols-[auto_minmax(4rem,1fr)] items-center h-sm -mb-1.5",
|
||||
"grid grid-cols-[auto_minmax(4rem,1fr)_auto] items-center h-sm -mb-1.5",
|
||||
"cursor-default select-none whitespace-nowrap w-full px-3",
|
||||
"overflow-x-auto font-mono text-sm text-text-subtle hide-scrollbars",
|
||||
)}
|
||||
@@ -172,6 +174,21 @@ function FlowPane({ flow }: { flow: Flow }) {
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<HStack space={1} className="font-sans ml-3">
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
color={flow.savedRequestId == null ? "default" : "primary"}
|
||||
title={flow.savedRequestId == null ? undefined : "Saved to Yaak. Click to save again."}
|
||||
leftSlot={<Icon icon="bookmark" size="xs" />}
|
||||
onClick={() => openSave(flow)}
|
||||
>
|
||||
{flow.savedRequestId == null ? "Save to Yaak" : "Saved"}
|
||||
</Button>
|
||||
<Dropdown items={flowActions(flow).slice(2)}>
|
||||
<IconButton size="xs" icon="ellipsis" iconColor="secondary" title="Copy and export" />
|
||||
</Dropdown>
|
||||
</HStack>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden flex flex-col min-h-0">
|
||||
|
||||
@@ -1,17 +1,34 @@
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { formatSize } from "@yaakapp-internal/lib/formatSize";
|
||||
import type { Flow } from "@yaakapp-internal/proxy-lib";
|
||||
import { formatMillis, HttpMethodTagRaw, HttpStatusTagRaw, Icon } from "@yaakapp-internal/ui";
|
||||
import {
|
||||
ContextMenu,
|
||||
formatMillis,
|
||||
HttpMethodTagRaw,
|
||||
HttpStatusTagRaw,
|
||||
Icon,
|
||||
} from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import { useAtom, useAtomValue, useSetAtom } from "jotai";
|
||||
import type { CSSProperties, KeyboardEvent, WheelEvent } from "react";
|
||||
import type { CSSProperties, KeyboardEvent, MouseEvent, WheelEvent } from "react";
|
||||
import { memo, useCallback, useLayoutEffect, useRef, useState } from "react";
|
||||
import { selectedFlowAtom, selectedFlowIdAtom } from "../lib/atoms";
|
||||
import { shortContentType } from "../lib/body";
|
||||
import { useFlowActions } from "../lib/flowActions";
|
||||
import { compareFlows } from "../lib/flowWindow";
|
||||
import { countNewFlows } from "../lib/follow";
|
||||
import { followAtom, loadOlderFlowsAtom, newestStartedAtAtom, oldestFlowAtom } from "../lib/store";
|
||||
import { filteredExchangesAtom } from "./Sidebar";
|
||||
import {
|
||||
activeQueryAtom,
|
||||
followAtom,
|
||||
hasAppsAtom,
|
||||
loadOlderFlowsAtom,
|
||||
newestStartedAtAtom,
|
||||
oldestFlowAtom,
|
||||
searchWindowAtom,
|
||||
shownFlowsAtom,
|
||||
} from "../lib/store";
|
||||
import { AppIcon } from "./AppIcon";
|
||||
import { SearchBar } from "./SearchBar";
|
||||
|
||||
const ROW_HEIGHT = 24;
|
||||
const BOTTOM_PADDING = 6;
|
||||
@@ -29,7 +46,10 @@ interface Props {
|
||||
* the top loads older flows from the database.
|
||||
*/
|
||||
export function FlowList({ sideBySide, style, className }: Props) {
|
||||
const flows = useAtomValue(filteredExchangesAtom);
|
||||
const flows = useAtomValue(shownFlowsAtom);
|
||||
const hasApps = useAtomValue(hasAppsAtom);
|
||||
const [menu, setMenu] = useState<{ flow: Flow; x: number; y: number } | null>(null);
|
||||
const flowActions = useFlowActions();
|
||||
const selectedId = useAtomValue(selectedFlowIdAtom);
|
||||
const setSelectedFlow = useSetAtom(selectedFlowAtom);
|
||||
const loadOlder = useSetAtom(loadOlderFlowsAtom);
|
||||
@@ -153,17 +173,33 @@ export function FlowList({ sideBySide, style, className }: Props) {
|
||||
[flows, loadOlderHeld, select, selectedId],
|
||||
);
|
||||
|
||||
const openMenu = useCallback(
|
||||
(index: number, e: MouseEvent) => {
|
||||
const flow = latest.current.flows[index];
|
||||
if (flow == null) return;
|
||||
e.preventDefault();
|
||||
select(index);
|
||||
setMenu({ flow, x: e.clientX, y: e.clientY });
|
||||
},
|
||||
[select],
|
||||
);
|
||||
|
||||
const newCount = following ? 0 : countNewFlows(flows, heldAt);
|
||||
|
||||
const columns = sideBySide
|
||||
? "grid-cols-[0.9rem_2.6rem_minmax(0,2fr)_minmax(0,3fr)_2.4rem_3.6rem]"
|
||||
: "grid-cols-[0.9rem_2.6rem_13rem_minmax(0,1fr)_2.4rem_5rem_4.5rem_3.8rem]";
|
||||
? hasApps
|
||||
? "grid-cols-[0.9rem_1rem_2.6rem_minmax(0,2fr)_minmax(0,3fr)_2.4rem_3.6rem]"
|
||||
: "grid-cols-[0.9rem_2.6rem_minmax(0,2fr)_minmax(0,3fr)_2.4rem_3.6rem]"
|
||||
: hasApps
|
||||
? "grid-cols-[0.9rem_8.5rem_2.6rem_13rem_minmax(0,1fr)_2.4rem_5rem_4.5rem_3.8rem]"
|
||||
: "grid-cols-[0.9rem_2.6rem_13rem_minmax(0,1fr)_2.4rem_5rem_4.5rem_3.8rem]";
|
||||
|
||||
return (
|
||||
<div
|
||||
style={style}
|
||||
className={classNames(className, "grid grid-rows-[auto_minmax(0,1fr)] min-h-0 text-sm")}
|
||||
className={classNames(className, "grid grid-rows-[auto_auto_minmax(0,1fr)] min-h-0 text-sm")}
|
||||
>
|
||||
<SearchBar />
|
||||
<div
|
||||
className={classNames(
|
||||
columns,
|
||||
@@ -172,6 +208,7 @@ export function FlowList({ sideBySide, style, className }: Props) {
|
||||
)}
|
||||
>
|
||||
<span />
|
||||
{hasApps && <span>{sideBySide ? "" : "App"}</span>}
|
||||
<span>Method</span>
|
||||
<span>Host</span>
|
||||
<span>Path</span>
|
||||
@@ -192,7 +229,7 @@ export function FlowList({ sideBySide, style, className }: Props) {
|
||||
className="group/flows h-full overflow-y-auto px-1.5 outline-hidden"
|
||||
>
|
||||
{flows.length === 0 ? (
|
||||
<p className="text-text-subtlest text-sm px-3 py-3">No traffic yet</p>
|
||||
<EmptyList />
|
||||
) : (
|
||||
<div className="relative" style={{ height: virtualizer.getTotalSize() }}>
|
||||
{virtualizer.getVirtualItems().map((item) => {
|
||||
@@ -206,8 +243,10 @@ export function FlowList({ sideBySide, style, className }: Props) {
|
||||
start={item.start}
|
||||
columns={columns}
|
||||
sideBySide={sideBySide}
|
||||
showApp={hasApps}
|
||||
selected={flow.id === selectedId}
|
||||
onSelect={select}
|
||||
onContextMenu={openMenu}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
@@ -229,19 +268,38 @@ export function FlowList({ sideBySide, style, className }: Props) {
|
||||
{newCount === 1 ? "1 new flow" : `${newCount} new flows`}
|
||||
</button>
|
||||
)}
|
||||
<ContextMenu
|
||||
triggerPosition={menu}
|
||||
items={menu == null ? [] : flowActions(menu.flow)}
|
||||
onClose={() => setMenu(null)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Nothing to list, or nothing a search matches */
|
||||
function EmptyList() {
|
||||
const query = useAtomValue(activeQueryAtom);
|
||||
const search = useAtomValue(searchWindowAtom);
|
||||
if (search?.loading) return null;
|
||||
return (
|
||||
<p className="text-text-subtlest text-sm px-3 py-3">
|
||||
{query == null ? "No traffic yet" : "No flows match"}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
interface RowProps {
|
||||
flow: Flow;
|
||||
index: number;
|
||||
start: number;
|
||||
columns: string;
|
||||
sideBySide: boolean;
|
||||
showApp: boolean;
|
||||
selected: boolean;
|
||||
onSelect: (index: number) => void;
|
||||
onContextMenu: (index: number, e: MouseEvent) => void;
|
||||
}
|
||||
|
||||
const FlowRow = memo(function FlowRow({
|
||||
@@ -250,8 +308,10 @@ const FlowRow = memo(function FlowRow({
|
||||
start,
|
||||
columns,
|
||||
sideBySide,
|
||||
showApp,
|
||||
selected,
|
||||
onSelect,
|
||||
onContextMenu,
|
||||
}: RowProps) {
|
||||
const { host, path, query } = splitUrl(flow.url);
|
||||
const failed = flow.error != null;
|
||||
@@ -263,7 +323,10 @@ const FlowRow = memo(function FlowRow({
|
||||
<div
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
onMouseDown={() => onSelect(index)}
|
||||
onMouseDown={(e) => {
|
||||
if (e.button === 0) onSelect(index);
|
||||
}}
|
||||
onContextMenu={(e) => onContextMenu(index, e)}
|
||||
style={{ height: ROW_HEIGHT, transform: `translateY(${start}px)` }}
|
||||
className={classNames(
|
||||
columns,
|
||||
@@ -275,12 +338,24 @@ const FlowRow = memo(function FlowRow({
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center justify-center">
|
||||
{failed ? (
|
||||
{flow.savedRequestId != null ? (
|
||||
<Icon icon="bookmark" size="xs" color="primary" title="Saved to Yaak" />
|
||||
) : failed ? (
|
||||
<Icon icon="circle_alert" size="xs" color="danger" />
|
||||
) : flow.responseTruncated ? (
|
||||
<Icon icon="scissors" size="xs" color="notice" title="Body cut at the capture limit" />
|
||||
) : null}
|
||||
</span>
|
||||
{showApp && (
|
||||
<span className="flex items-center gap-1.5" title={flow.clientPath ?? undefined}>
|
||||
{flow.clientPath != null && <AppIcon path={flow.clientPath} />}
|
||||
{!sideBySide && (
|
||||
<span className="truncate text-text-subtle">
|
||||
{flow.clientName ?? <span className="text-text-subtlest">--</span>}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<HttpMethodTagRaw method={flow.method} short colored />
|
||||
<span className="text-text-subtle">{host}</span>
|
||||
<span>
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
import { HeaderSize, IconButton, SidebarLayout, SplitLayout } from "@yaakapp-internal/ui";
|
||||
import {
|
||||
HeaderSize,
|
||||
IconButton,
|
||||
SidebarLayout,
|
||||
SplitLayout,
|
||||
type SplitLayoutLayout,
|
||||
Toasts,
|
||||
} from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import { useState } from "react";
|
||||
import { useLocalStorage } from "react-use";
|
||||
import { flowLayoutAtom } from "../lib/atoms";
|
||||
import { searchWindowAtom, showFirstRunAtom, shownTotalAtom } from "../lib/store";
|
||||
import { getOsType } from "../lib/tauri";
|
||||
import { ClearFlowsButton } from "./ClearFlowsButton";
|
||||
import { FirstRun } from "./FirstRun";
|
||||
import { FlowDetail } from "./FlowDetail";
|
||||
import { FlowList } from "./FlowList";
|
||||
import { ProxyStatus } from "./ProxyStatus";
|
||||
import { filteredCountAtom, selectedSidebarLabelAtom, Sidebar } from "./Sidebar";
|
||||
import { SaveDialog } from "./SaveDialog";
|
||||
import { selectedSidebarLabelAtom, Sidebar } from "./Sidebar";
|
||||
import { TakeOverBanner } from "./TakeOverBanner";
|
||||
|
||||
export function ProxyLayout() {
|
||||
const os = getOsType();
|
||||
@@ -120,27 +131,45 @@ export function ProxyLayout() {
|
||||
)
|
||||
}
|
||||
>
|
||||
<SplitLayout
|
||||
storageKey="proxy_detail"
|
||||
className="gap-1"
|
||||
layout={flowLayout}
|
||||
defaultRatio={0.55}
|
||||
firstSlot={({ style, orientation }) => (
|
||||
<FlowList sideBySide={orientation === "horizontal"} style={style} className="pt-1" />
|
||||
)}
|
||||
secondSlot={({ style, orientation }) => (
|
||||
<FlowDetail style={style} sideBySide={orientation === "horizontal"} />
|
||||
)}
|
||||
/>
|
||||
<div className="h-full flex flex-col min-h-0">
|
||||
<TakeOverBanner />
|
||||
<div className="flex-1 min-h-0 grid grid-rows-[minmax(0,1fr)]">
|
||||
<FlowsOrFirstRun flowLayout={flowLayout} />
|
||||
</div>
|
||||
</div>
|
||||
</SidebarLayout>
|
||||
<SaveDialog />
|
||||
<Toasts />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Its own component, so new traffic re-renders the count rather than the whole layout */
|
||||
function FlowCount() {
|
||||
const count = useAtomValue(filteredCountAtom);
|
||||
const count = useAtomValue(shownTotalAtom);
|
||||
const searching = useAtomValue(searchWindowAtom) != null;
|
||||
const noun = searching ? (count === 1 ? "match" : "matches") : count === 1 ? "flow" : "flows";
|
||||
return <span className="text-text-subtlest shrink-0">{`${count} ${noun}`}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The flow list above the detail pane, or, while the database has no flows at all, the first-run
|
||||
* card across the whole area: it is the empty state until traffic replaces it.
|
||||
*/
|
||||
function FlowsOrFirstRun({ flowLayout }: { flowLayout: SplitLayoutLayout }) {
|
||||
if (useAtomValue(showFirstRunAtom)) return <FirstRun />;
|
||||
return (
|
||||
<span className="text-text-subtlest shrink-0">{count === 1 ? "1 flow" : `${count} flows`}</span>
|
||||
<SplitLayout
|
||||
storageKey="proxy_detail"
|
||||
className="gap-1"
|
||||
layout={flowLayout}
|
||||
defaultRatio={0.55}
|
||||
firstSlot={({ style, orientation }) => (
|
||||
<FlowList sideBySide={orientation === "horizontal"} style={style} className="pt-1" />
|
||||
)}
|
||||
secondSlot={({ style, orientation }) => (
|
||||
<FlowDetail style={style} sideBySide={orientation === "horizontal"} />
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +1,135 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type { CaStatus } from "@yaakapp-internal/proxy-lib";
|
||||
import { Button, Dropdown, type DropdownItem, type DropdownRef, Icon } from "@yaakapp-internal/ui";
|
||||
import type { CaStatus, SystemProxyStatus } from "@yaakapp-internal/proxy-lib";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Dropdown,
|
||||
type DropdownItem,
|
||||
type DropdownRef,
|
||||
Icon,
|
||||
} from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import { useAtomValue, useStore } from "jotai";
|
||||
import type { HTMLAttributes, ReactNode, Ref } from "react";
|
||||
import { useRef } from "react";
|
||||
import { useRpcEvent } from "../hooks/useRpcEvent";
|
||||
import { useRpcMutation } from "../hooks/useRpcMutation";
|
||||
import { useRpcQuery } from "../hooks/useRpcQuery";
|
||||
import { useRpcQueryWithEvent } from "../hooks/useRpcQueryWithEvent";
|
||||
import { environmentExports } from "../lib/env";
|
||||
import { proxyStateAtom, refreshProxyState } from "../lib/store";
|
||||
import { recordingLabel, systemProxySwitch } from "../lib/systemProxy";
|
||||
import { useShowToast } from "../lib/toast";
|
||||
|
||||
/** The header's state pill and its menu, with the certificate stepping out when untrusted */
|
||||
/**
|
||||
* The header's state pill and its menu: recording, the system proxy and the certificate. The
|
||||
* engine runs for as long as the app does, so the pill shows whether flows are being stored. A
|
||||
* certificate that is not trusted steps out of the menu beside the pill until it is.
|
||||
*/
|
||||
export function ProxyStatus() {
|
||||
const queryClient = useQueryClient();
|
||||
const dropdownRef = useRef<DropdownRef>(null);
|
||||
const { data: proxyState } = useRpcQueryWithEvent("get_proxy_state", {}, "proxy_state_changed");
|
||||
const caStatus = useRpcQuery("ca_status", {});
|
||||
const trust = useRpcMutation("ca_trust", {
|
||||
onSuccess: (status) => queryClient.setQueryData<CaStatus>(["ca_status", {}], status),
|
||||
});
|
||||
const proxyState = useAtomValue(proxyStateAtom);
|
||||
const setup = useProxySetup();
|
||||
const execute = useRpcMutation("execute_action");
|
||||
const retry = useRpcMutation("take_over");
|
||||
const setAtLaunch = useSetSystemProxyAtLaunch();
|
||||
const copyEnvironment = useCopyEnvironment();
|
||||
const { caStatus, trust, systemProxy, setSystemProxy } = setup;
|
||||
const systemSwitch = useSystemProxySwitch(setup);
|
||||
|
||||
const running = proxyState?.state === "running";
|
||||
const port = proxyState?.port;
|
||||
const recording = proxyState?.recording !== false;
|
||||
const other = proxyState?.otherOwner ?? null;
|
||||
const port = proxyState?.port ?? other?.proxyPort ?? null;
|
||||
const untrusted = caStatus.data != null && !caStatus.data.trusted;
|
||||
|
||||
const stateRow =
|
||||
other != null ? (
|
||||
<MenuRow
|
||||
icon={<StateDot state="cli" />}
|
||||
title="Running from the CLI"
|
||||
description={`Started by yaak proxy start, pid ${other.pid}, since ${timeOf(other.startedAt)}.${other.proxyPort == null ? "" : ` Port ${other.proxyPort}.`}`}
|
||||
/>
|
||||
) : running ? (
|
||||
<MenuRow
|
||||
icon={<StateDot state={recording ? "recording" : "paused"} />}
|
||||
title={recording ? `Recording on port ${port}` : `Paused on port ${port}`}
|
||||
description={
|
||||
recording
|
||||
? "Listening on 127.0.0.1, and storing every flow."
|
||||
: "Traffic passes through untouched, and no flows are stored."
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<MenuRow
|
||||
icon={<Icon icon="alert_triangle" size="sm" color="warning" />}
|
||||
title="Not running"
|
||||
description={
|
||||
<span className="text-danger">
|
||||
{retry.error?.message ?? proxyState?.startError ?? "The proxy has not started."}
|
||||
</span>
|
||||
}
|
||||
action={
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
isLoading={retry.isPending}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
retry.mutate({});
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
|
||||
const items: DropdownItem[] = [
|
||||
{ type: "content", label: stateRow },
|
||||
{ type: "separator", hidden: systemProxy.data?.supported !== true },
|
||||
{
|
||||
type: "content",
|
||||
hidden: systemProxy.data?.supported !== true,
|
||||
label: (
|
||||
<MenuRow
|
||||
icon={<StateDot running={running} />}
|
||||
title={running && port != null ? `Running on port ${port}` : "Stopped"}
|
||||
icon={<Icon icon="wifi" size="sm" color="secondary" />}
|
||||
title="Override system proxy"
|
||||
description={
|
||||
running
|
||||
? "Listening on 127.0.0.1."
|
||||
: "Start the proxy to capture traffic from apps pointed at it."
|
||||
<span className={classNames(systemSwitch.failed && "text-danger")}>
|
||||
{systemSwitch.description}
|
||||
</span>
|
||||
}
|
||||
action={
|
||||
<KeepMenuOpen>
|
||||
<Checkbox
|
||||
title="Override system proxy"
|
||||
hideLabel
|
||||
checked={systemSwitch.checked}
|
||||
// Only the process that owns the engine routes to it.
|
||||
disabled={!running || other != null || setSystemProxy.isPending}
|
||||
onChange={(enabled) => setSystemProxy.mutate({ enabled })}
|
||||
/>
|
||||
</KeepMenuOpen>
|
||||
}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
type: "content",
|
||||
hidden: systemProxy.data?.supported !== true,
|
||||
label: (
|
||||
<KeepMenuOpen className="block pl-[2.125rem] pr-1.5 pb-1.5">
|
||||
<Checkbox
|
||||
title={
|
||||
<span className="text-xs text-text-subtle">Override system proxy at launch</span>
|
||||
}
|
||||
checked={proxyState?.systemProxyAtLaunch ?? true}
|
||||
disabled={setAtLaunch.isPending}
|
||||
onChange={(enabled) => setAtLaunch.mutate({ enabled })}
|
||||
/>
|
||||
</KeepMenuOpen>
|
||||
),
|
||||
},
|
||||
{
|
||||
type: "content",
|
||||
label: caStatus.data?.trusted ? (
|
||||
@@ -78,13 +170,17 @@ export function ProxyStatus() {
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: running ? "Stop Proxy" : "Start Proxy",
|
||||
icon: running ? "circle_stop" : "circle_play",
|
||||
hotKeyAction: running ? "proxy_stop" : "proxy_start",
|
||||
label: "Copy Environment for a Terminal",
|
||||
icon: "square_terminal",
|
||||
onSelect: copyEnvironment,
|
||||
},
|
||||
{
|
||||
label: recordingLabel(recording),
|
||||
icon: recording ? "circle_pause" : "circle_play",
|
||||
hidden: !running,
|
||||
hotKeyAction: "recording_toggle",
|
||||
hotKeyLabelOnly: true,
|
||||
onSelect: () => {
|
||||
execute.mutate({ scope: "global", action: running ? "proxy_stop" : "proxy_start" });
|
||||
},
|
||||
onSelect: () => execute.mutate({ scope: "global", action: "recording_toggle" }),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -97,17 +193,25 @@ export function ProxyStatus() {
|
||||
</Pill>
|
||||
)}
|
||||
<Dropdown ref={dropdownRef} items={items}>
|
||||
<Pill>
|
||||
{running ? (
|
||||
<Pill color={!running && other == null && proxyState != null ? "warning" : undefined}>
|
||||
{other != null ? (
|
||||
<>
|
||||
<StateDot running />
|
||||
<span className="text-text">Running</span>
|
||||
<StateDot state="cli" />
|
||||
<span className="text-text">CLI</span>
|
||||
{other.proxyPort != null && (
|
||||
<span className="font-mono text-text-subtle">:{other.proxyPort}</span>
|
||||
)}
|
||||
</>
|
||||
) : running ? (
|
||||
<>
|
||||
<StateDot state={recording ? "recording" : "paused"} />
|
||||
<span className="text-text">{recording ? "Recording" : "Paused"}</span>
|
||||
{port != null && <span className="font-mono text-text-subtle">:{port}</span>}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<StateDot running={false} />
|
||||
Stopped
|
||||
<Icon icon="alert_triangle" size="xs" />
|
||||
Not running
|
||||
</>
|
||||
)}
|
||||
<Icon icon="chevron_down" size="xs" className="text-text-subtlest" />
|
||||
@@ -117,6 +221,83 @@ export function ProxyStatus() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The certificate and the system proxy, read once and shared by the header and the first-run
|
||||
* card, with the actions that change them.
|
||||
*/
|
||||
export function useProxySetup() {
|
||||
const queryClient = useQueryClient();
|
||||
const caStatus = useRpcQuery("ca_status", {});
|
||||
const systemProxy = useRpcQuery("system_proxy_status", {});
|
||||
const trust = useRpcMutation("ca_trust", {
|
||||
mutationKey: ["ca_trust"],
|
||||
onSuccess: (status) => queryClient.setQueryData<CaStatus>(["ca_status", {}], status),
|
||||
});
|
||||
const setSystemProxy = useRpcMutation("system_proxy_set", {
|
||||
mutationKey: ["system_proxy_set"],
|
||||
onSuccess: (status) => {
|
||||
queryClient.setQueryData<SystemProxyStatus>(["system_proxy_status", {}], status);
|
||||
},
|
||||
});
|
||||
// The engine turns the system proxy on as it starts, and says so once the prompt is
|
||||
// answered, and turns it off as it stops.
|
||||
useRpcEvent("proxy_state_changed", () => void systemProxy.refetch());
|
||||
return { caStatus, trust, systemProxy, setSystemProxy };
|
||||
}
|
||||
|
||||
/** The system proxy switch's state, from where it points and the change in flight */
|
||||
export function useSystemProxySwitch(setup: ReturnType<typeof useProxySetup>) {
|
||||
const proxyState = useAtomValue(proxyStateAtom);
|
||||
const { systemProxy, setSystemProxy } = setup;
|
||||
return systemProxySwitch({
|
||||
routing: systemProxy.data?.enabled === true,
|
||||
port: proxyState?.port ?? proxyState?.configuredPort ?? null,
|
||||
pending: setSystemProxy.isPending ? (setSystemProxy.variables?.enabled ?? null) : null,
|
||||
error: setSystemProxy.error?.message ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
/** Saves whether the system proxy turns on as the app launches */
|
||||
function useSetSystemProxyAtLaunch() {
|
||||
const store = useStore();
|
||||
return useRpcMutation("set_system_proxy_at_launch", {
|
||||
onSettled: () => void refreshProxyState(store),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCopyEnvironment() {
|
||||
const proxyState = useAtomValue(proxyStateAtom);
|
||||
const caStatus = useRpcQuery("ca_status", {});
|
||||
const showToast = useShowToast();
|
||||
return async () => {
|
||||
const port =
|
||||
proxyState?.port ?? proxyState?.otherOwner?.proxyPort ?? proxyState?.configuredPort;
|
||||
const caPath = caStatus.data?.certPath;
|
||||
if (port == null || caPath == null) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(environmentExports(port, caPath));
|
||||
showToast({
|
||||
message: "Copied the environment. Paste it into a terminal to proxy what runs there.",
|
||||
});
|
||||
} catch (err) {
|
||||
showToast({ message: `Failed to copy: ${String(err)}`, color: "danger" });
|
||||
}
|
||||
};
|
||||
}
|
||||
/** Keeps a click on a control inside a menu row from closing the menu, as a row's click does */
|
||||
function KeepMenuOpen({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return (
|
||||
// oxlint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions -- only stops the click reaching the row
|
||||
<span className={className} onClick={(e) => e.stopPropagation()}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function timeOf(iso: string): string {
|
||||
return new Date(iso).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
|
||||
}
|
||||
|
||||
interface PillProps extends HTMLAttributes<HTMLButtonElement> {
|
||||
color?: "warning";
|
||||
ref?: Ref<HTMLButtonElement>;
|
||||
@@ -141,13 +322,15 @@ function Pill({ children, color, ref, ...props }: PillProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function StateDot({ running }: { running: boolean }) {
|
||||
export function StateDot({ state }: { state: "recording" | "paused" | "cli" }) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className={classNames(
|
||||
"inline-block w-[7px] h-[7px] rounded-full shrink-0",
|
||||
running ? "bg-success ring-3 ring-success/20" : "border-[1.5px] border-text-subtlest",
|
||||
state === "recording" && "bg-success ring-3 ring-success/20",
|
||||
state === "cli" && "bg-info ring-3 ring-info/20",
|
||||
state === "paused" && "border-[1.5px] border-text-subtlest",
|
||||
)}
|
||||
/>
|
||||
);
|
||||
@@ -165,7 +348,7 @@ function MenuRow({
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid grid-cols-[1rem_minmax(0,1fr)_auto] gap-x-3 items-start px-1.5 py-1">
|
||||
<div className="grid grid-cols-[1rem_minmax(0,1fr)_auto] gap-x-3 items-start px-1.5 py-1 w-[24rem] max-w-full">
|
||||
<span className="h-5 flex items-center justify-center">{icon}</span>
|
||||
<div>
|
||||
<div className="text-sm text-text">{title}</div>
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import type {
|
||||
DropReason,
|
||||
Flow,
|
||||
FolderSummary,
|
||||
WorkspaceSummary,
|
||||
} from "@yaakapp-internal/proxy-lib";
|
||||
import {
|
||||
Banner,
|
||||
Dialog,
|
||||
DialogFooter,
|
||||
HttpMethodTagRaw,
|
||||
LoadingIcon,
|
||||
PlainInput,
|
||||
} from "@yaakapp-internal/ui";
|
||||
import { unnamedRequestName } from "@yaakapp-internal/ui/resolvedModelName";
|
||||
import { openUrl } from "@tauri-apps/plugin-opener";
|
||||
import { useAtom } from "jotai";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useLocalStorage } from "react-use";
|
||||
import { useRpcMutation } from "../hooks/useRpcMutation";
|
||||
import { useRpcQuery } from "../hooks/useRpcQuery";
|
||||
import { exportHar, saveDialogFlowAtom } from "../lib/flowActions";
|
||||
import { useShowToast } from "../lib/toast";
|
||||
|
||||
const DOWNLOAD_URL = "https://yaak.app/download";
|
||||
const SAVE_FORM_ID = "save-flow-to-yaak";
|
||||
|
||||
/** Save as Yaak request, for the flow in `saveDialogFlowAtom` */
|
||||
export function SaveDialog() {
|
||||
const [flow, setFlow] = useAtom(saveDialogFlowAtom);
|
||||
const workspaces = useRpcQuery("list_workspaces", {}, { enabled: flow != null, staleTime: 0 });
|
||||
const close = () => setFlow(null);
|
||||
|
||||
if (flow == null) return null;
|
||||
if (workspaces.data?.yaakFound === false) return <NoYaakDialog flow={flow} onClose={close} />;
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={close}
|
||||
size="dynamic"
|
||||
title="Save as Yaak request"
|
||||
description="A new request in Yaak with this flow's method, URL, headers and body."
|
||||
className="w-[36rem]"
|
||||
>
|
||||
{workspaces.error != null ? (
|
||||
<Banner color="danger">{workspaces.error.message}</Banner>
|
||||
) : workspaces.data == null ? (
|
||||
<LoadingIcon />
|
||||
) : (
|
||||
<SaveForm flow={flow} workspaces={workspaces.data.workspaces} onClose={close} />
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function SaveForm({
|
||||
flow,
|
||||
workspaces,
|
||||
onClose,
|
||||
}: {
|
||||
flow: Flow;
|
||||
workspaces: WorkspaceSummary[];
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const showToast = useShowToast();
|
||||
const preview = useRpcQuery("preview_save", { flowId: flow.id }, { staleTime: 0 });
|
||||
const [lastWorkspaceId, setLastWorkspaceId] = useLocalStorage<string>("save_workspace_id");
|
||||
const [workspaceId, setWorkspaceId] = useState(
|
||||
workspaces.find((w) => w.id === lastWorkspaceId)?.id ?? workspaces[0]?.id ?? "",
|
||||
);
|
||||
const [folderId, setFolderId] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const save = useRpcMutation("save_flow");
|
||||
|
||||
const workspace = workspaces.find((w) => w.id === workspaceId);
|
||||
const folders = useMemo(() => folderOptions(workspace?.folders ?? []), [workspace]);
|
||||
useEffect(() => setFolderId(""), [workspaceId]);
|
||||
|
||||
const p = preview.data;
|
||||
// Unnamed unless one is typed, as Yaak leaves a new request, which then shows its URL.
|
||||
const unnamed =
|
||||
p == null
|
||||
? ""
|
||||
: unnamedRequestName({ model: "http_request", url: p.requestUrl, bodyType: p.bodyType });
|
||||
const folderName = folders.find((f) => f.id === folderId)?.name;
|
||||
|
||||
const submit = () => {
|
||||
if (workspace == null) return;
|
||||
save.mutate(
|
||||
{
|
||||
flowId: flow.id,
|
||||
workspaceId: workspace.id,
|
||||
...(folderId === "" ? {} : { folderId }),
|
||||
...(name.trim() === "" ? {} : { name }),
|
||||
},
|
||||
{
|
||||
onSuccess: (saved) => {
|
||||
setLastWorkspaceId(workspace.id);
|
||||
onClose();
|
||||
showToast({
|
||||
message: (
|
||||
<>
|
||||
Saved <b className="font-semibold">{saved.name || unnamed}</b> to {workspace.name}
|
||||
{folderName == null ? "." : `, in ${folderName}.`} Yaak picks it up within a second.
|
||||
</>
|
||||
),
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
if (workspaces.length === 0) {
|
||||
return (
|
||||
<Banner color="notice">
|
||||
Yaak has no workspaces yet. Create one in Yaak, then save here.
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
|
||||
if (p == null) {
|
||||
return preview.error != null ? (
|
||||
<Banner color="danger">{preview.error.message}</Banner>
|
||||
) : (
|
||||
<LoadingIcon />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
id={SAVE_FORM_ID}
|
||||
className="flex flex-col gap-3.5 pb-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3 h-sm px-2.5 rounded-md border border-border-subtle font-mono text-sm min-w-0">
|
||||
<HttpMethodTagRaw method={flow.method} colored />
|
||||
<span className="truncate text-text">{flow.url}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label="Workspace">
|
||||
<select
|
||||
className={inputClasses}
|
||||
value={workspaceId}
|
||||
onChange={(e) => setWorkspaceId(e.target.value)}
|
||||
>
|
||||
{workspaces.map((w) => (
|
||||
<option key={w.id} value={w.id}>
|
||||
{w.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Folder">
|
||||
<select
|
||||
className={inputClasses}
|
||||
value={folderId}
|
||||
onChange={(e) => setFolderId(e.target.value)}
|
||||
>
|
||||
<option value="">No folder</option>
|
||||
{folders.map((f) => (
|
||||
<option key={f.id} value={f.id}>
|
||||
{f.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
<PlainInput label="Name" autoFocus defaultValue="" placeholder={unnamed} onChange={setName} />
|
||||
{p.droppedHeaders.length > 0 && (
|
||||
<div className="rounded-md border border-border-subtle px-3.5 py-2.5">
|
||||
<div className="text-sm text-text">
|
||||
{p.droppedHeaders.length === 1
|
||||
? "1 header left out"
|
||||
: `${p.droppedHeaders.length} headers left out`}{" "}
|
||||
<span className="text-text-subtlest text-xs">
|
||||
{droppedSummary(p.droppedHeaders.map((h) => h.reason))}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5 mt-2">
|
||||
{p.droppedHeaders.map((h) => (
|
||||
<span
|
||||
key={h.name}
|
||||
title={`${h.name}: ${h.value}\n${reasonLabel(h.reason)}`}
|
||||
className="font-mono text-xs leading-[22px] px-1.5 rounded-sm border border-border-subtle text-text-subtle line-through decoration-text-subtlest"
|
||||
>
|
||||
{h.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3.5 gap-y-1.5 text-sm">
|
||||
<span className="text-text-subtle">Kept</span>
|
||||
<span>
|
||||
{p.keptHeaders === 1 ? "1 header" : `${p.keptHeaders} headers`}
|
||||
{p.body == null ? ", and no body" : `, and the body as ${p.body}`}
|
||||
</span>
|
||||
{p.warnings.map((w) => (
|
||||
<NoteRow key={w} warning={w} authorization={p.authorization} />
|
||||
))}
|
||||
</div>
|
||||
{save.error != null && <Banner color="danger">{save.error.message}</Banner>}
|
||||
<DialogFooter
|
||||
leftSlot={
|
||||
<span className="text-xs text-text-subtlest">Yaak picks it up within a second</span>
|
||||
}
|
||||
actions={[
|
||||
{ label: "Cancel", onClick: onClose },
|
||||
{
|
||||
label: "Save request",
|
||||
form: SAVE_FORM_ID,
|
||||
color: "primary",
|
||||
isLoading: save.isPending,
|
||||
disabled: workspace == null,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function NoteRow({ warning, authorization }: { warning: string; authorization: boolean }) {
|
||||
const flagged = authorization && warning.includes("Authorization");
|
||||
return (
|
||||
<>
|
||||
<span className="text-text-subtle">Note</span>
|
||||
<span className={flagged ? "text-notice" : "text-text-subtle"}>{warning}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Without Yaak there is nothing to save into: say so, and offer HAR as a way to keep the flow */
|
||||
function NoYaakDialog({ flow, onClose }: { flow: Flow; onClose: () => void }) {
|
||||
const showToast = useShowToast();
|
||||
return (
|
||||
<Dialog open onClose={onClose} size="dynamic" className="w-[32rem]">
|
||||
<DialogFooter
|
||||
leftSlot={<span className="text-xs text-text-subtlest">Or keep the flow as a file</span>}
|
||||
actions={[
|
||||
{
|
||||
label: "Export HAR",
|
||||
onClick: async () => {
|
||||
try {
|
||||
if ((await exportHar({ ids: [flow.id] }, "flow.har")) != null) {
|
||||
onClose();
|
||||
showToast({ message: "Exported the flow as HAR" });
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({ message: `Failed to export HAR: ${String(err)}`, color: "danger" });
|
||||
}
|
||||
},
|
||||
},
|
||||
{ label: "Download Yaak", color: "primary", onClick: () => void openUrl(DOWNLOAD_URL) },
|
||||
]}
|
||||
/>
|
||||
<div className="pt-6 pb-2">
|
||||
<div className="text-lg font-semibold mb-1.5">Saving needs Yaak</div>
|
||||
<div className="text-sm text-text-subtle leading-relaxed">
|
||||
This flow becomes a request in one of Yaak's workspaces, and Yaak has not been opened on
|
||||
this Mac. Yaak is free for personal use and opens the request with the same viewers you
|
||||
see here.
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
// oxlint-disable-next-line jsx-a11y/label-has-associated-control -- wraps its control
|
||||
<label className="flex flex-col gap-1 min-w-0">
|
||||
<span className="text-xs text-text-subtle">{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
const inputClasses =
|
||||
"h-sm w-full min-w-0 px-2 rounded-md border border-border bg-surface text-text text-sm outline-hidden focus:border-border-focus";
|
||||
|
||||
/** Folders by their path within the workspace, "Stripe / Payments", in path order */
|
||||
function folderOptions(folders: FolderSummary[]): { id: string; name: string }[] {
|
||||
const byId = new Map(folders.map((f) => [f.id, f]));
|
||||
const pathOf = (f: FolderSummary): string => {
|
||||
const names = [f.name];
|
||||
const seen = new Set([f.id]);
|
||||
let parent = f.folderId == null ? undefined : byId.get(f.folderId);
|
||||
while (parent != null && !seen.has(parent.id)) {
|
||||
names.unshift(parent.name);
|
||||
seen.add(parent.id);
|
||||
parent = parent.folderId == null ? undefined : byId.get(parent.folderId);
|
||||
}
|
||||
return names.join(" / ");
|
||||
};
|
||||
return folders
|
||||
.map((f) => ({ id: f.id, name: pathOf(f) }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
function reasonLabel(reason: DropReason): string {
|
||||
switch (reason) {
|
||||
case "set_by_sending":
|
||||
return "Yaak sets it when it sends";
|
||||
case "hop_by_hop":
|
||||
return "Only meant for the proxy";
|
||||
case "body_decoded":
|
||||
return "The body is saved decoded";
|
||||
}
|
||||
}
|
||||
|
||||
function droppedSummary(reasons: DropReason[]): string {
|
||||
const unique = [...new Set(reasons)];
|
||||
if (unique.length === 1 && unique[0] === "set_by_sending") {
|
||||
return "Yaak sets these itself when it sends";
|
||||
}
|
||||
return "Yaak sets these itself, or they only meant something to the proxy";
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Icon, IconButton, PlainInput } from "@yaakapp-internal/ui";
|
||||
import { useAtomValue, useSetAtom } from "jotai";
|
||||
import { memo, useEffect, useRef, useState } from "react";
|
||||
import { exportHar } from "../lib/flowActions";
|
||||
import { searchTerms } from "../lib/search";
|
||||
import { activeQueryAtom, searchTermsAtom } from "../lib/store";
|
||||
import { useShowToast } from "../lib/toast";
|
||||
|
||||
/** How long typing settles before the search runs */
|
||||
const SEARCH_DEBOUNCE_MS = 200;
|
||||
|
||||
/**
|
||||
* Searches every flow in the database by URL, method, status and content type, within the
|
||||
* sidebar's selection. ⌘F focuses it and Escape clears it.
|
||||
*/
|
||||
export const SearchBar = memo(function SearchBar() {
|
||||
const [text, setText] = useState("");
|
||||
const setTerms = useSetAtom(searchTermsAtom);
|
||||
const query = useAtomValue(activeQueryAtom);
|
||||
const showToast = useShowToast();
|
||||
// PlainInput hands back its <input> as the ref
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
// Bumped to empty the field, which only takes a value from outside when this changes
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setTerms(searchTerms(text)), SEARCH_DEBOUNCE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [text, setTerms]);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key.toLowerCase() === "f") {
|
||||
e.preventDefault();
|
||||
inputRef.current?.focus();
|
||||
inputRef.current?.select();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, []);
|
||||
|
||||
// The field is replaced to empty it, so focus moves to the new one.
|
||||
const clear = () => {
|
||||
setText("");
|
||||
setTerms(null);
|
||||
setResetKey((k) => k + 1);
|
||||
requestAnimationFrame(() => inputRef.current?.focus());
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 px-3 pb-1.5">
|
||||
<div className="flex-1 min-w-0">
|
||||
<PlainInput
|
||||
ref={inputRef}
|
||||
label="Search flows"
|
||||
hideLabel
|
||||
size="xs"
|
||||
placeholder="Search flows by URL, method, status or type"
|
||||
defaultValue={text}
|
||||
forceUpdateKey={String(resetKey)}
|
||||
onChange={setText}
|
||||
onKeyDownCapture={(e) => {
|
||||
if (e.key === "Escape" && text !== "") {
|
||||
e.stopPropagation();
|
||||
clear();
|
||||
}
|
||||
}}
|
||||
leftSlot={
|
||||
<Icon icon="search" size="sm" className="ml-2 mr-2.5 self-center text-text-subtlest" />
|
||||
}
|
||||
rightSlot={
|
||||
text === "" ? (
|
||||
<kbd className="self-center mr-2 px-1 rounded-sm border border-border-subtle font-sans text-2xs text-text-subtlest">
|
||||
⌘F
|
||||
</kbd>
|
||||
) : (
|
||||
<IconButton
|
||||
size="xs"
|
||||
icon="x"
|
||||
title="Clear search"
|
||||
iconColor="secondary"
|
||||
className="self-center"
|
||||
onClick={clear}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<IconButton
|
||||
size="xs"
|
||||
icon="download"
|
||||
iconColor="secondary"
|
||||
title={query == null ? "Export every flow as HAR" : "Export the flows shown as HAR"}
|
||||
onClick={async () => {
|
||||
try {
|
||||
const written = await exportHar(query == null ? {} : { filter: query }, "flows.har");
|
||||
if (written != null) {
|
||||
showToast({
|
||||
message:
|
||||
written === 1 ? "Exported 1 flow as HAR" : `Exported ${written} flows as HAR`,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({ message: `Failed to export HAR: ${String(err)}`, color: "danger" });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -4,19 +4,22 @@ import { selectedIdsFamily, Tree } from "@yaakapp-internal/ui";
|
||||
import { atom, useAtomValue } from "jotai";
|
||||
import { atomWithStorage } from "jotai/utils";
|
||||
import { useCallback } from "react";
|
||||
import { SIDEBAR_TREE_ID } from "../lib/atoms";
|
||||
import { appKeyOf, appNodeId, sidebarPath } from "../lib/search";
|
||||
import { applyCollapsed, type CollapsedMap, collapsedMap, folderIds } from "../lib/sidebarCollapse";
|
||||
import { flowsAtom, flowTotalAtom } from "../lib/store";
|
||||
import { AppIcon } from "./AppIcon";
|
||||
|
||||
/** A node in the sidebar tree — either a domain or a path segment. */
|
||||
/** A node in the sidebar tree: a domain, a path segment, or an app. */
|
||||
export type SidebarItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
/** Flows held under this node; for the Domains folder, every flow in the database */
|
||||
count: number;
|
||||
/** An app's path, for its icon */
|
||||
appPath?: string;
|
||||
};
|
||||
|
||||
export const SIDEBAR_TREE_ID = "proxy-sidebar";
|
||||
|
||||
const sidebarTreeAtom = atom<TreeNode<SidebarItem>>((get) => {
|
||||
const exchanges = get(flowsAtom);
|
||||
return buildTree(exchanges, get(flowTotalAtom));
|
||||
@@ -43,34 +46,15 @@ const collapsedAtom = atom(
|
||||
},
|
||||
);
|
||||
|
||||
/** The sidebar nodes selected, or null when the list shows all traffic */
|
||||
const selectedNodeIdsAtom = atom((get) => {
|
||||
const selectedIds = get(selectedIdsFamily(SIDEBAR_TREE_ID));
|
||||
// Nothing selected, or a node holding everything → show all
|
||||
if (selectedIds.length === 0 || selectedIds.includes("root") || selectedIds.includes("domains")) {
|
||||
return null;
|
||||
}
|
||||
return new Set(selectedIds);
|
||||
});
|
||||
|
||||
/** Exchanges filtered by the currently selected sidebar node(s). */
|
||||
export const filteredExchangesAtom = atom((get) => {
|
||||
const exchanges = get(flowsAtom);
|
||||
const selected = get(selectedNodeIdsAtom);
|
||||
if (selected == null) return exchanges;
|
||||
return exchanges.filter((ex) => nodeIdsOf(ex).some((id) => selected.has(id)));
|
||||
});
|
||||
|
||||
/** Flows in the database for all traffic, or those held under the selected nodes */
|
||||
export const filteredCountAtom = atom((get) =>
|
||||
get(selectedNodeIdsAtom) == null ? get(flowTotalAtom) : get(filteredExchangesAtom).length,
|
||||
);
|
||||
|
||||
/** The selected sidebar node's name, for the header */
|
||||
export const selectedSidebarLabelAtom = atom((get) => {
|
||||
const selectedId = get(selectedIdsFamily(SIDEBAR_TREE_ID))[0];
|
||||
if (selectedId?.startsWith("domain:")) return selectedId.slice("domain:".length);
|
||||
if (selectedId?.startsWith("path:")) return selectedId.slice("path:".length);
|
||||
if (selectedId?.startsWith("app:")) {
|
||||
const apps = get(sidebarTreeAtom).children?.find((c) => c.item.id === "apps");
|
||||
return apps?.children?.find((c) => c.item.id === selectedId)?.item.label ?? "All traffic";
|
||||
}
|
||||
return "All traffic";
|
||||
});
|
||||
|
||||
@@ -83,21 +67,15 @@ const nodeIdsByFlow = new WeakMap<Flow, string[]>();
|
||||
function nodeIdsOf(ex: Flow): string[] {
|
||||
let ids = nodeIdsByFlow.get(ex);
|
||||
if (ids != null) return ids;
|
||||
let hostname: string;
|
||||
let segments: string[];
|
||||
try {
|
||||
const url = new URL(ex.url);
|
||||
hostname = url.host;
|
||||
segments = url.pathname.split("/").filter(Boolean);
|
||||
} catch {
|
||||
hostname = ex.url;
|
||||
segments = [];
|
||||
}
|
||||
// By the rules the database filters by, so a node shows the flows it counts.
|
||||
const path = sidebarPath(ex.url);
|
||||
const schemeless = !ex.url.includes("://");
|
||||
const [hostname = "", ...segments] = schemeless ? [path] : path.split("/");
|
||||
ids = [`domain:${hostname}`];
|
||||
let path = `path:${hostname}`;
|
||||
let node = `path:${hostname}`;
|
||||
for (const seg of segments) {
|
||||
path += `/${seg}`;
|
||||
ids.push(path);
|
||||
node += `/${seg}`;
|
||||
ids.push(node);
|
||||
}
|
||||
nodeIdsByFlow.set(ex, ids);
|
||||
return ids;
|
||||
@@ -197,6 +175,34 @@ function buildTree(exchanges: Flow[], total: number): TreeNode<SidebarItem> {
|
||||
domainsFolder.children?.push(toTreeNode(domain, domainsFolder, 2));
|
||||
}
|
||||
|
||||
// The apps flows came from, where the platform can tell; none on others, so no group.
|
||||
const apps = new Map<string, SidebarItem>();
|
||||
for (const ex of exchanges) {
|
||||
const key = appKeyOf(ex);
|
||||
if (key == null) continue;
|
||||
const id = appNodeId(key);
|
||||
const app = apps.get(id);
|
||||
if (app == null) {
|
||||
apps.set(id, { id, label: ex.clientName ?? key, count: 1, appPath: ex.clientPath ?? key });
|
||||
} else {
|
||||
app.count++;
|
||||
}
|
||||
}
|
||||
if (apps.size > 0) {
|
||||
const appsFolder: TreeNode<SidebarItem> = {
|
||||
item: { id: "apps", label: "Apps", count: 0 },
|
||||
parent: rootNode,
|
||||
depth: 1,
|
||||
children: [],
|
||||
draggable: false,
|
||||
};
|
||||
const sortedApps = [...apps.values()].sort((a, b) => collator.compare(a.label, b.label));
|
||||
for (const item of sortedApps) {
|
||||
appsFolder.children?.push({ item, parent: appsFolder, depth: 2, draggable: false });
|
||||
}
|
||||
rootNode.children?.push(appsFolder);
|
||||
}
|
||||
|
||||
rootNode.children?.push(domainsFolder);
|
||||
|
||||
return rootNode;
|
||||
@@ -206,6 +212,7 @@ function ItemInner({ item }: { item: SidebarItem }) {
|
||||
const count = item.count;
|
||||
return (
|
||||
<div className="flex items-center gap-2 w-full min-w-0">
|
||||
{item.appPath != null && <AppIcon path={item.appPath} />}
|
||||
<span className="truncate">{item.label}</span>
|
||||
{count > 0 && <span className="ml-auto text-text-subtlest text-2xs shrink-0">{count}</span>}
|
||||
</div>
|
||||
@@ -214,9 +221,9 @@ function ItemInner({ item }: { item: SidebarItem }) {
|
||||
|
||||
export function Sidebar() {
|
||||
const tree = useAtomValue(sidebarTreeAtom);
|
||||
const treeId = SIDEBAR_TREE_ID;
|
||||
|
||||
const getItemKey = useCallback((item: SidebarItem) => `${item.id}:${item.count}`, []);
|
||||
const treeId = SIDEBAR_TREE_ID;
|
||||
|
||||
return (
|
||||
// The tree scrolls itself, in a row of bounded height, so its virtualizer mounts only the rows
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Button, Icon } from "@yaakapp-internal/ui";
|
||||
import { useAtomValue } from "jotai";
|
||||
import { useRpcMutation } from "../hooks/useRpcMutation";
|
||||
import { proxyStateAtom } from "../lib/store";
|
||||
|
||||
/**
|
||||
* A quiet strip while another process, the CLI daemon, owns the engine: flows still list, read
|
||||
* from the database, and Take over stops that process's proxy and starts this app's. Never done
|
||||
* without the person asking.
|
||||
*/
|
||||
export function TakeOverBanner() {
|
||||
const other = useAtomValue(proxyStateAtom)?.otherOwner;
|
||||
const takeOver = useRpcMutation("take_over");
|
||||
if (other == null) return null;
|
||||
const since = new Date(other.startedAt).toLocaleTimeString([], {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
const cli = other.owner === "cli";
|
||||
const who = cli ? "Running from the CLI" : "Running in another Yaak Proxy";
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2.5 h-[2.2rem] mx-2 mb-1 pl-3 pr-1.5 rounded-md bg-surface-highlight/45 border border-border-subtle text-sm text-text-subtle min-w-0">
|
||||
<Icon icon="square_terminal" size="sm" color="info" className="shrink-0" />
|
||||
<span className="text-text shrink-0">{who}</span>
|
||||
{other.owner === "cli" && (
|
||||
<span className="font-mono text-xs text-text-subtlest shrink-0">yaak proxy start</span>
|
||||
)}
|
||||
<span className="truncate">
|
||||
{!cli ? (
|
||||
// Stopping another app halts its engine without releasing it, so it can't be taken over.
|
||||
"Another Yaak Proxy window owns the engine. Quit it to use this one."
|
||||
) : takeOver.error != null ? (
|
||||
<span className="text-danger">{takeOver.error.message}</span>
|
||||
) : (
|
||||
`pid ${other.pid}, since ${since}. Flows still list here, read from the capture database.`
|
||||
)}
|
||||
</span>
|
||||
{cli && (
|
||||
<Button
|
||||
size="2xs"
|
||||
variant="border"
|
||||
className="ml-auto shrink-0"
|
||||
isLoading={takeOver.isPending}
|
||||
onClick={() => takeOver.mutate({})}
|
||||
>
|
||||
Take over
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,9 @@ import type { SplitLayoutLayout } from "@yaakapp-internal/ui";
|
||||
import { atom } from "jotai";
|
||||
import { atomWithStorage } from "jotai/utils";
|
||||
|
||||
/** The sidebar's tree, whose selection narrows the list */
|
||||
export const SIDEBAR_TREE_ID = "proxy-sidebar";
|
||||
|
||||
/** The selected flow as last seen, kept once the window has dropped it so the detail stays */
|
||||
export const selectedFlowAtom = atom<Flow | null>(null);
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { curlBodyText, shellQuote, toCurl } from "./curl";
|
||||
|
||||
const headers = (...pairs: [string, string][]) => pairs.map(([name, value]) => ({ name, value }));
|
||||
|
||||
describe("toCurl", () => {
|
||||
test("a GET is the URL and its headers, without the ones curl sets itself", () => {
|
||||
const flow = {
|
||||
method: "GET",
|
||||
url: "https://api.github.com/repos/yaak?page=2",
|
||||
requestHeaders: headers(
|
||||
["Host", "api.github.com"],
|
||||
["Accept", "application/json"],
|
||||
["Proxy-Connection", "keep-alive"],
|
||||
["Connection", "keep-alive"],
|
||||
),
|
||||
};
|
||||
expect(toCurl(flow, null)).toBe(
|
||||
"curl 'https://api.github.com/repos/yaak?page=2' \\\n -H 'Accept: application/json'",
|
||||
);
|
||||
});
|
||||
|
||||
test("a POST with a body leaves the method to curl and quotes the body", () => {
|
||||
const flow = {
|
||||
method: "POST",
|
||||
url: "https://api.stripe.com/v1/charges",
|
||||
requestHeaders: headers(
|
||||
["Authorization", "Bearer sk_test_123"],
|
||||
["Content-Type", "application/json"],
|
||||
["Content-Length", "23"],
|
||||
["Accept-Encoding", "gzip, br"],
|
||||
),
|
||||
};
|
||||
expect(toCurl(flow, `{"note":"it's paid"}`)).toBe(
|
||||
[
|
||||
"curl 'https://api.stripe.com/v1/charges'",
|
||||
"-H 'Authorization: Bearer sk_test_123'",
|
||||
"-H 'Content-Type: application/json'",
|
||||
"--compressed",
|
||||
`--data-raw '{"note":"it'\\''s paid"}'`,
|
||||
].join(" \\\n "),
|
||||
);
|
||||
});
|
||||
|
||||
test("quotes a method that is not a plain word, and drops the decoded body's encoding", () => {
|
||||
const flow = {
|
||||
method: "`id`",
|
||||
url: "https://x.test/a",
|
||||
requestHeaders: headers(["Content-Encoding", "gzip"], ["X-Trace", "1"]),
|
||||
};
|
||||
expect(toCurl(flow, "plain")).toBe(
|
||||
"curl -X '`id`' \\\n 'https://x.test/a' \\\n -H 'X-Trace: 1' \\\n --data-raw 'plain'",
|
||||
);
|
||||
});
|
||||
|
||||
test("replays HEAD with --head and leaves brackets in the URL alone", () => {
|
||||
const flow = {
|
||||
method: "HEAD",
|
||||
url: "https://x.test/a?filter[status]=open",
|
||||
requestHeaders: [],
|
||||
};
|
||||
expect(toCurl(flow, null)).toBe(
|
||||
"curl --head \\\n --globoff \\\n 'https://x.test/a?filter[status]=open'",
|
||||
);
|
||||
});
|
||||
|
||||
test("names any other method", () => {
|
||||
const flow = { method: "DELETE", url: "https://x.test/a", requestHeaders: [] };
|
||||
expect(toCurl(flow, null)).toBe("curl -X DELETE \\\n 'https://x.test/a'");
|
||||
expect(toCurl({ ...flow, method: "GET" }, "q=1")).toBe(
|
||||
"curl -X GET \\\n 'https://x.test/a' \\\n --data-raw 'q=1'",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shellQuote", () => {
|
||||
test("closes and reopens the quotes around a quote", () => {
|
||||
expect(shellQuote("a'b")).toBe(`'a'\\''b'`);
|
||||
expect(shellQuote("$HOME `x`")).toBe("'$HOME `x`'");
|
||||
});
|
||||
});
|
||||
|
||||
describe("curlBodyText", () => {
|
||||
test("is the text of a complete UTF-8 body", () => {
|
||||
expect(curlBodyText(new TextEncoder().encode('{"note":"héllo"}'), false)).toBe(
|
||||
'{"note":"héllo"}',
|
||||
);
|
||||
});
|
||||
|
||||
test("refuses a body curl would send different bytes for", () => {
|
||||
expect(curlBodyText(new Uint8Array([0xff, 0x00, 0xfe]), false)).toBeNull();
|
||||
expect(curlBodyText(new TextEncoder().encode("the first part"), true)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { Flow } from "@yaakapp-internal/proxy-lib";
|
||||
|
||||
/** Headers curl works out itself, or that only meant something between the app and the proxy */
|
||||
const LEFT_OUT = new Set([
|
||||
"host",
|
||||
"content-length",
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
]);
|
||||
|
||||
/**
|
||||
* A request body as the text a curl command can carry, or null when it would not send the same
|
||||
* bytes: when it is not valid UTF-8, or only its start was captured.
|
||||
*/
|
||||
export function curlBodyText(bytes: Uint8Array, truncated: boolean): string | null {
|
||||
if (truncated) return null;
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** `value` in single quotes for a POSIX shell */
|
||||
export function shellQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'\\''`)}'`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The flow's request as a curl command: its method, URL, headers and `body`, the request body
|
||||
* decoded. Headers curl sets itself are left out, and an encoded response is asked for with
|
||||
* `--compressed`, as the app did.
|
||||
*/
|
||||
export function toCurl(flow: Pick<Flow, "method" | "url" | "requestHeaders">, body: string | null) {
|
||||
const args: string[] = [];
|
||||
const hasBody = body != null && body !== "";
|
||||
const defaultMethod = hasBody ? "POST" : "GET";
|
||||
if (flow.method.toUpperCase() === "HEAD" && !hasBody) {
|
||||
// So curl expects no body after the headers.
|
||||
args.push("--head");
|
||||
} else if (flow.method.toUpperCase() !== defaultMethod) {
|
||||
// A method is any token, which can hold characters a shell would act on.
|
||||
const plain = /^[A-Za-z0-9_-]+$/.test(flow.method);
|
||||
args.push(`-X ${plain ? flow.method : shellQuote(flow.method)}`);
|
||||
}
|
||||
// curl reads brackets and braces in a URL as ranges and sets unless told not to.
|
||||
if (/[[\]{}]/.test(flow.url)) args.push("--globoff");
|
||||
args.push(shellQuote(flow.url));
|
||||
let compressed = false;
|
||||
for (const { name, value } of flow.requestHeaders) {
|
||||
const lower = name.toLowerCase();
|
||||
if (LEFT_OUT.has(lower) || lower.startsWith("proxy-") || lower.startsWith(":")) continue;
|
||||
// The body is the decoded one, so its encoding no longer applies.
|
||||
if (lower === "content-encoding" && hasBody) continue;
|
||||
if (lower === "accept-encoding") {
|
||||
compressed = true;
|
||||
continue;
|
||||
}
|
||||
args.push(`-H ${shellQuote(`${name}: ${value}`)}`);
|
||||
}
|
||||
if (compressed) args.push("--compressed");
|
||||
if (hasBody) args.push(`--data-raw ${shellQuote(body)}`);
|
||||
return `curl ${args.join(" \\\n ")}`;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { environmentExports } from "./env";
|
||||
|
||||
describe("environmentExports", () => {
|
||||
test("points the proxy variables at the port and the CA variables at the certificate", () => {
|
||||
const path = "/Users/me/Library/Application Support/app.yaak.proxy/ca/ca.pem";
|
||||
expect(environmentExports(9090, path)).toBe(
|
||||
[
|
||||
"export HTTP_PROXY=http://127.0.0.1:9090",
|
||||
"export HTTPS_PROXY=http://127.0.0.1:9090",
|
||||
"export http_proxy=http://127.0.0.1:9090",
|
||||
"export https_proxy=http://127.0.0.1:9090",
|
||||
`export SSL_CERT_FILE='${path}'`,
|
||||
`export NODE_EXTRA_CA_CERTS='${path}'`,
|
||||
`export REQUESTS_CA_BUNDLE='${path}'`,
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { shellQuote } from "./curl";
|
||||
|
||||
/**
|
||||
* Shell exports that send one terminal's traffic through the proxy on `port` and trust its CA at
|
||||
* `caPath`, for tools that read neither the system proxy nor the login keychain: Node, Python,
|
||||
* and anything built on OpenSSL.
|
||||
*/
|
||||
export function environmentExports(port: number, caPath: string): string {
|
||||
const proxy = `http://127.0.0.1:${port}`;
|
||||
const ca = shellQuote(caPath);
|
||||
return [
|
||||
`export HTTP_PROXY=${proxy}`,
|
||||
`export HTTPS_PROXY=${proxy}`,
|
||||
// curl reads only the lowercase name for plain HTTP.
|
||||
`export http_proxy=${proxy}`,
|
||||
`export https_proxy=${proxy}`,
|
||||
`export SSL_CERT_FILE=${ca}`,
|
||||
`export NODE_EXTRA_CA_CERTS=${ca}`,
|
||||
`export REQUESTS_CA_BUNDLE=${ca}`,
|
||||
].join("\n");
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { ExportHarRequest, Flow, FlowBody } from "@yaakapp-internal/proxy-lib";
|
||||
import type { DropdownItem } from "@yaakapp-internal/ui";
|
||||
import { save } from "@tauri-apps/plugin-dialog";
|
||||
import { atom, useSetAtom } from "jotai";
|
||||
import { useCallback } from "react";
|
||||
import { base64ToBytes } from "./body";
|
||||
import { curlBodyText, toCurl } from "./curl";
|
||||
import { rpc } from "./rpc";
|
||||
import { useShowToast } from "./toast";
|
||||
|
||||
/** The flow the save dialog is open for */
|
||||
export const saveDialogFlowAtom = atom<Flow | null>(null);
|
||||
|
||||
/** A body as text, decoding what is not UTF-8 lossily, or null when there is none */
|
||||
async function bodyText(flow: Flow, which: FlowBody): Promise<string | null> {
|
||||
const res = await rpc("get_flow_body", { flowId: flow.id, which });
|
||||
const bytes = base64ToBytes(res.data);
|
||||
return bytes.length === 0 ? null : new TextDecoder().decode(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes flows to a HAR file the person picks: `ids`, or every flow `filter` covers. Returns how
|
||||
* many were written, or null when the save panel was cancelled.
|
||||
*/
|
||||
export async function exportHar(
|
||||
req: Omit<ExportHarRequest, "path">,
|
||||
defaultName: string,
|
||||
): Promise<number | null> {
|
||||
const path = await save({
|
||||
defaultPath: defaultName,
|
||||
filters: [{ name: "HTTP Archive", extensions: ["har"] }],
|
||||
});
|
||||
if (path == null) return null;
|
||||
return rpc("export_har", { ...req, path });
|
||||
}
|
||||
|
||||
/** What a flow's context menu and the detail pane's menu offer */
|
||||
export function useFlowActions(): (flow: Flow) => DropdownItem[] {
|
||||
const showToast = useShowToast();
|
||||
const openSave = useSetAtom(saveDialogFlowAtom);
|
||||
|
||||
return useCallback(
|
||||
(flow: Flow) => {
|
||||
const copy = async (label: string, text: () => Promise<string | null> | string) => {
|
||||
try {
|
||||
const value = await text();
|
||||
if (value == null) {
|
||||
showToast({ message: `There is no ${label} to copy`, color: "info" });
|
||||
return;
|
||||
}
|
||||
await navigator.clipboard.writeText(value);
|
||||
showToast({ message: `Copied ${label}` });
|
||||
} catch (err) {
|
||||
showToast({ message: `Failed to copy ${label}: ${String(err)}`, color: "danger" });
|
||||
}
|
||||
};
|
||||
const noResponse = flow.error != null && flow.status == null;
|
||||
return [
|
||||
{
|
||||
label: flow.savedRequestId == null ? "Save as Yaak Request" : "Save to Yaak Again",
|
||||
icon: "bookmark",
|
||||
onSelect: () => openSave(flow),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Copy as cURL",
|
||||
icon: "square_terminal",
|
||||
onSelect: async () => {
|
||||
let body: string | null = null;
|
||||
if (flow.requestSize > 0) {
|
||||
let res;
|
||||
try {
|
||||
res = await rpc("get_flow_body", { flowId: flow.id, which: "request" });
|
||||
} catch (err) {
|
||||
showToast({ message: `Failed to copy cURL: ${String(err)}`, color: "danger" });
|
||||
return;
|
||||
}
|
||||
body = curlBodyText(base64ToBytes(res.data), res.truncated);
|
||||
// A command that sends other bytes than the app did would mislead.
|
||||
if (body == null) {
|
||||
showToast({
|
||||
message: "Body is binary or truncated; export HAR instead",
|
||||
color: "info",
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
await copy("cURL", () => toCurl(flow, body));
|
||||
},
|
||||
},
|
||||
{ label: "Copy URL", icon: "copy", onSelect: () => copy("URL", () => flow.url) },
|
||||
{
|
||||
label: "Copy Request Body",
|
||||
icon: "copy",
|
||||
disabled: flow.requestSize === 0,
|
||||
onSelect: () => copy("request body", () => bodyText(flow, "request")),
|
||||
},
|
||||
{
|
||||
label: "Copy Response Body",
|
||||
icon: "copy",
|
||||
disabled: noResponse,
|
||||
onSelect: () => copy("response body", () => bodyText(flow, "response")),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Export HAR",
|
||||
icon: "download",
|
||||
onSelect: async () => {
|
||||
try {
|
||||
const written = await exportHar({ ids: [flow.id] }, "flow.har");
|
||||
if (written != null) showToast({ message: "Exported the flow as HAR" });
|
||||
} catch (err) {
|
||||
showToast({ message: `Failed to export HAR: ${String(err)}`, color: "danger" });
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
},
|
||||
[openSave, showToast],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import type { Flow } from "@yaakapp-internal/proxy-lib";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { matchesQuery, searchTerms, selectionQuery, sidebarPath } from "./search";
|
||||
|
||||
function flow(url: string, extra: Partial<Flow> = {}): Flow {
|
||||
return {
|
||||
url,
|
||||
method: "GET",
|
||||
status: 200,
|
||||
contentType: null,
|
||||
clientBundleId: null,
|
||||
clientPath: null,
|
||||
...extra,
|
||||
} as Flow;
|
||||
}
|
||||
|
||||
// The same flows and terms as `search_matches_url_method_status_and_content_type` in
|
||||
// `flows.rs`, so the live matcher and the database agree.
|
||||
const stripe = flow("https://api.stripe.com/v1/charges?customer=cus_9", {
|
||||
method: "POST",
|
||||
contentType: "application/json; charset=utf-8",
|
||||
});
|
||||
const github = flow("https://api.github.com/repos/yaak", {
|
||||
status: 404,
|
||||
contentType: "application/json; charset=utf-8",
|
||||
});
|
||||
const logo = flow("https://images.ctfassets.net/logo.png", { contentType: "image/png" });
|
||||
const health = flow("http://localhost:3000/health", { method: "HEAD", status: 503 });
|
||||
const all = [stripe, github, logo, health];
|
||||
|
||||
const search = (q: string) => all.filter((f) => matchesQuery(f, { q }));
|
||||
|
||||
describe("matchesQuery", () => {
|
||||
test("matches the host, the path and the query, any case", () => {
|
||||
expect(search("STRIPE")).toEqual([stripe]);
|
||||
expect(search("/repos/")).toEqual([github]);
|
||||
expect(search("cus_9")).toEqual([stripe]);
|
||||
});
|
||||
|
||||
test("matches the whole method", () => {
|
||||
expect(search("head")).toEqual([health]);
|
||||
expect(search("ead")).toEqual([]);
|
||||
});
|
||||
|
||||
test("matches a status, its start, or its class", () => {
|
||||
expect(search("404")).toEqual([github]);
|
||||
expect(search("50")).toEqual([health]);
|
||||
expect(search("2xx")).toEqual([stripe, logo]);
|
||||
});
|
||||
|
||||
test("matches the content type", () => {
|
||||
expect(search("png")).toEqual([logo]);
|
||||
expect(search("json")).toEqual([stripe, github]);
|
||||
});
|
||||
|
||||
test("needs every term to match", () => {
|
||||
expect(search("json get")).toEqual([github]);
|
||||
expect(search(" json 2xx ")).toEqual([stripe]);
|
||||
expect(search("json 5xx")).toEqual([]);
|
||||
expect(search("")).toEqual(all);
|
||||
});
|
||||
|
||||
test("keeps flows under a host or path, as the sidebar places them", () => {
|
||||
const under = (node: string, url: string) => matchesQuery(flow(url), { under: [node] });
|
||||
expect(under("api.stripe.com", "https://api.stripe.com/v1/charges")).toBe(true);
|
||||
expect(under("api.stripe.com", "http://api.stripe.com")).toBe(true);
|
||||
// Another port is a host node of its own, as in the sidebar.
|
||||
expect(under("api.stripe.com", "https://api.stripe.com:8443/v1")).toBe(false);
|
||||
// Empty segments and default ports are left out, as the sidebar leaves them.
|
||||
expect(under("example.com/v1/users", "https://example.com/v1//users")).toBe(true);
|
||||
expect(under("x.com/a", "http://x.com:80/a")).toBe(true);
|
||||
expect(under("api.stripe.com", "https://api.stripe.community/")).toBe(false);
|
||||
expect(under("api.stripe.com/v1/charges", "https://api.stripe.com/v1/charges/ch_1?x")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(under("api.stripe.com/v1/charges", "https://api.stripe.com/v1/chargesx")).toBe(false);
|
||||
expect(under("api.stripe.com:8443", "https://api.stripe.com/v1")).toBe(false);
|
||||
// The sidebar lowercases hosts; paths keep their case.
|
||||
expect(under("example.com/A", "http://EXAMPLE.com/A/b")).toBe(true);
|
||||
expect(under("example.com/a", "http://example.com/A")).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps flows from an app, by bundle id or path", () => {
|
||||
const chrome = flow("https://example.com/", {
|
||||
clientBundleId: "com.google.Chrome",
|
||||
clientPath: "/Applications/Google Chrome.app",
|
||||
});
|
||||
const curl = flow("https://example.com/", { clientPath: "/usr/bin/curl" });
|
||||
const unknown = flow("https://example.com/");
|
||||
const from = (app: string[]) => [chrome, curl, unknown].filter((f) => matchesQuery(f, { app }));
|
||||
expect(from(["com.google.Chrome"])).toEqual([chrome]);
|
||||
expect(from(["/usr/bin/curl"])).toEqual([curl]);
|
||||
expect(from(["/Applications/Google Chrome.app"])).toEqual([]);
|
||||
});
|
||||
|
||||
test("combines terms with the sidebar's selection", () => {
|
||||
expect(matchesQuery(stripe, { q: "post", under: ["api.stripe.com"] })).toBe(true);
|
||||
expect(matchesQuery(stripe, { q: "post", under: ["api.github.com"] })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sidebarPath", () => {
|
||||
// The cases `sidebar_path_rules` in `flows.rs` checks, so the two agree.
|
||||
test("is the lowercased host without its default port, then the non-empty segments", () => {
|
||||
for (const [url, path] of [
|
||||
["https://example.com/v1//users", "example.com/v1/users"],
|
||||
["http://x.com:80/a", "x.com/a"],
|
||||
["https://x.com:443/a?q=1#f", "x.com/a"],
|
||||
["http://x.com:443/a", "x.com:443/a"],
|
||||
["https://API.Stripe.com:8443/", "api.stripe.com:8443"],
|
||||
["https://api.stripe.com", "api.stripe.com"],
|
||||
["https://api.stripe.com?x=/y", "api.stripe.com"],
|
||||
["http://[::1]:80/a/B", "[::1]/a/B"],
|
||||
["/api", "/api"],
|
||||
]) {
|
||||
expect(sidebarPath(url ?? ""), url).toBe(path);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("selectionQuery", () => {
|
||||
test("is null for nothing selected or a node holding every flow", () => {
|
||||
expect(selectionQuery([])).toBeNull();
|
||||
expect(selectionQuery(["root"])).toBeNull();
|
||||
expect(selectionQuery(["domain:a.com", "domains"])).toBeNull();
|
||||
expect(selectionQuery(["apps"])).toBeNull();
|
||||
});
|
||||
|
||||
test("splits hosts and paths from apps", () => {
|
||||
expect(selectionQuery(["domain:a.com", "path:b.com/v1", "app:com.apple.Safari"])).toEqual({
|
||||
under: ["a.com", "b.com/v1"],
|
||||
app: ["com.apple.Safari"],
|
||||
});
|
||||
expect(selectionQuery(["app:/usr/bin/curl"])).toEqual({ app: ["/usr/bin/curl"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("searchTerms", () => {
|
||||
test("trims and collapses the box's text, or is null without any", () => {
|
||||
expect(searchTerms(" stripe post ")).toBe("stripe post");
|
||||
expect(searchTerms(" ")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { Flow, FlowFilter } from "@yaakapp-internal/proxy-lib";
|
||||
|
||||
/**
|
||||
* A search over every flow in the database: the search box's terms and the sidebar's selection,
|
||||
* as `list_flows` takes them.
|
||||
*/
|
||||
export type FlowQuery = Pick<FlowFilter, "q" | "under" | "app">;
|
||||
|
||||
/** The sidebar node for all of an app's flows */
|
||||
export function appNodeId(key: string): string {
|
||||
return `app:${key}`;
|
||||
}
|
||||
|
||||
/** What groups an app's flows: its bundle id, or its path for a process outside an app */
|
||||
export function appKeyOf(flow: Flow): string | null {
|
||||
return flow.clientBundleId ?? flow.clientPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sidebar's selection as a query: hosts and paths under `under`, apps under `app`. Null when
|
||||
* the selection holds every flow.
|
||||
*/
|
||||
export function selectionQuery(selectedIds: string[]): FlowQuery | null {
|
||||
const under: string[] = [];
|
||||
const app: string[] = [];
|
||||
for (const id of selectedIds) {
|
||||
if (id === "root" || id === "domains" || id === "apps") return null;
|
||||
if (id.startsWith("domain:")) under.push(id.slice("domain:".length));
|
||||
else if (id.startsWith("path:")) under.push(id.slice("path:".length));
|
||||
else if (id.startsWith("app:")) app.push(id.slice("app:".length));
|
||||
}
|
||||
if (under.length === 0 && app.length === 0) return null;
|
||||
return {
|
||||
...(under.length > 0 ? { under } : {}),
|
||||
...(app.length > 0 ? { app } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `flow` is one `query` covers, as `list_flows` decides it in SQL, so new traffic joins a
|
||||
* search as it arrives. Every term must match the URL, the method, the status or the content type.
|
||||
*/
|
||||
export function matchesQuery(flow: Flow, query: FlowQuery): boolean {
|
||||
for (const term of (query.q ?? "").toLowerCase().split(/\s+/)) {
|
||||
if (term === "") continue;
|
||||
const matched =
|
||||
flow.url.toLowerCase().includes(term) ||
|
||||
flow.method.toLowerCase() === term ||
|
||||
(flow.contentType?.toLowerCase().includes(term) ?? false) ||
|
||||
matchesStatus(flow.status, term);
|
||||
if (!matched) return false;
|
||||
}
|
||||
if (query.under != null && !query.under.some((node) => isUnder(flow.url, node))) return false;
|
||||
if (query.app != null) {
|
||||
const key = appKeyOf(flow);
|
||||
if (key == null || !query.app.includes(key)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** `404` exactly, `40` as the start of one, or a class such as `4xx` */
|
||||
function matchesStatus(status: number | null, term: string): boolean {
|
||||
if (status == null) return false;
|
||||
const klass = /^([1-9])xx$/.exec(term);
|
||||
if (klass != null) return Math.trunc(status / 100) === Number(klass[1]);
|
||||
if (!/^\d{1,3}$/.test(term)) return false;
|
||||
return term.length === 3 ? status === Number(term) : String(status).startsWith(term);
|
||||
}
|
||||
|
||||
/** The URL is the host or path `node` names, or something below it, by the sidebar's rules */
|
||||
function isUnder(url: string, node: string): boolean {
|
||||
const path = sidebarPath(url);
|
||||
const want = normalizeNode(node);
|
||||
return path === want || path.startsWith(`${want}/`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the sidebar places a URL: its host, lowercased and without its scheme's default port,
|
||||
* then its path's non-empty segments, joined by `/`, as in `api.stripe.com/v1/charges`. A URL
|
||||
* without a scheme is a host of its own. `sidebar_path` in `crates-proxy/yaak-proxy-lib`, which
|
||||
* the database filters by, follows the same rules.
|
||||
*/
|
||||
export function sidebarPath(url: string): string {
|
||||
const schemeEnd = url.indexOf("://");
|
||||
if (schemeEnd === -1) return url;
|
||||
const scheme = url.slice(0, schemeEnd).toLowerCase();
|
||||
const rest = url.slice(schemeEnd + 3);
|
||||
const authorityEnd = rest.search(/[/?#]/);
|
||||
let host = (authorityEnd === -1 ? rest : rest.slice(0, authorityEnd)).toLowerCase();
|
||||
const defaultPort =
|
||||
scheme === "http" || scheme === "ws"
|
||||
? ":80"
|
||||
: scheme === "https" || scheme === "wss"
|
||||
? ":443"
|
||||
: null;
|
||||
if (defaultPort != null && host.endsWith(defaultPort)) {
|
||||
host = host.slice(0, -defaultPort.length);
|
||||
}
|
||||
const path = authorityEnd === -1 ? "" : (rest.slice(authorityEnd).split(/[?#]/)[0] ?? "");
|
||||
const segments = path.split("/").filter((s) => s !== "");
|
||||
return [host, ...segments].join("/");
|
||||
}
|
||||
|
||||
/** A sidebar node as `sidebarPath` writes it, its host lowercased */
|
||||
function normalizeNode(node: string): string {
|
||||
const slash = node.indexOf("/");
|
||||
return slash === -1
|
||||
? node.toLowerCase()
|
||||
: `${node.slice(0, slash).toLowerCase()}${node.slice(slash)}`;
|
||||
}
|
||||
|
||||
/** The search box's text as terms for `list_flows`, or null when it has none */
|
||||
export function searchTerms(text: string): string | null {
|
||||
const q = text.trim().replace(/\s+/g, " ");
|
||||
return q === "" ? null : q;
|
||||
}
|
||||
+231
-22
@@ -1,6 +1,7 @@
|
||||
import type { ModelPayload } from "@yaakapp-internal/proxy-lib";
|
||||
import type { GetProxyStateResponse, ModelPayload } from "@yaakapp-internal/proxy-lib";
|
||||
import { selectedIdsFamily } from "@yaakapp-internal/ui";
|
||||
import { atom, type createStore } from "jotai";
|
||||
import { followingAtom, selectedFlowAtom } from "./atoms";
|
||||
import { followingAtom, SIDEBAR_TREE_ID, selectedFlowAtom } from "./atoms";
|
||||
import {
|
||||
applyChanges,
|
||||
emptyWindow,
|
||||
@@ -12,11 +13,18 @@ import {
|
||||
windowFromPage,
|
||||
} from "./flowWindow";
|
||||
import { listen, rpc } from "./rpc";
|
||||
import { type FlowQuery, matchesQuery, selectionQuery } from "./search";
|
||||
|
||||
type Store = ReturnType<typeof createStore>;
|
||||
|
||||
/** How long new flows gather before they reach the list, so a burst renders once */
|
||||
const FLUSH_MS = 100;
|
||||
/** How long after new flows the total is counted again from the database */
|
||||
const RECOUNT_MS = 1000;
|
||||
/** How often the database is read for new flows while another process owns the engine */
|
||||
const POLL_MS = 1000;
|
||||
/** How often the engine's owner is checked while it is another process */
|
||||
const OWNER_POLL_MS = 2000;
|
||||
|
||||
/** The flows in memory: a window onto the database, which keeps them all */
|
||||
export const flowWindowAtom = atom<FlowWindow>(emptyWindow);
|
||||
@@ -27,23 +35,73 @@ export const flowsAtom = atom((get) => get(flowWindowAtom).flows);
|
||||
/** Start of the newest flow held, across all traffic */
|
||||
export const newestStartedAtAtom = atom((get) => get(flowsAtom).at(-1)?.startedAt ?? null);
|
||||
|
||||
/** Start and id of the oldest flow held, which loading older flows moves back */
|
||||
export const oldestFlowAtom = atom((get) => get(flowsAtom)[0] ?? null);
|
||||
|
||||
export const hasOlderFlowsAtom = atom((get) => get(flowWindowAtom).hasOlder);
|
||||
|
||||
/** Flows in the database */
|
||||
export const flowTotalAtom = atom((get) => get(flowWindowAtom).total);
|
||||
|
||||
/** The first page of flows has loaded, so an empty window means an empty database */
|
||||
export const flowsLoadedAtom = atom(false);
|
||||
|
||||
/**
|
||||
* The database has no flows and nothing narrows the list, so the first-run card shows. A boolean
|
||||
* of its own, so new traffic does not re-render what reads it.
|
||||
*/
|
||||
export const showFirstRunAtom = atom(
|
||||
(get) => get(flowsLoadedAtom) && get(flowTotalAtom) === 0 && get(activeQueryAtom) == null,
|
||||
);
|
||||
|
||||
/** Some flow held names the app that sent it, which only some platforms can tell */
|
||||
export const hasAppsAtom = atom((get) => get(flowsAtom).some((f) => f.clientName != null));
|
||||
|
||||
/** The search box's terms, once typing settles, or null */
|
||||
export const searchTermsAtom = atom<string | null>(null);
|
||||
|
||||
/** The search the list shows, from the search box and the sidebar, or null for all traffic */
|
||||
export const activeQueryAtom = atom<FlowQuery | null>((get) => {
|
||||
const q = get(searchTermsAtom);
|
||||
const selection = selectionQuery(get(selectedIdsFamily(SIDEBAR_TREE_ID)));
|
||||
if (q == null && selection == null) return null;
|
||||
return { ...(q == null ? {} : { q }), ...selection };
|
||||
});
|
||||
|
||||
/** A window onto the flows a search covers, loaded from the database as the main one is */
|
||||
export interface SearchWindow {
|
||||
key: string;
|
||||
query: FlowQuery;
|
||||
win: FlowWindow;
|
||||
/** The first page has not arrived yet */
|
||||
loading: boolean;
|
||||
/** Changes that came while the first page loaded, applied once it is in */
|
||||
buffered: ModelPayload[];
|
||||
}
|
||||
|
||||
export const searchWindowAtom = atom<SearchWindow | null>(null);
|
||||
|
||||
/** The window the list shows: the search's, or all traffic's */
|
||||
const shownWindowAtom = atom((get) => get(searchWindowAtom)?.win ?? get(flowWindowAtom));
|
||||
|
||||
/** The flows the list shows, oldest first */
|
||||
export const shownFlowsAtom = atom((get) => get(shownWindowAtom).flows);
|
||||
|
||||
/** Flows in the database the list covers: every one, or those the search matches */
|
||||
export const shownTotalAtom = atom((get) => get(shownWindowAtom).total);
|
||||
|
||||
/** Start and id of the oldest flow shown, which loading older flows moves back */
|
||||
export const oldestFlowAtom = atom((get) => get(shownFlowsAtom)[0] ?? null);
|
||||
|
||||
/** Follows new traffic, dropping the older flows scrolling up loaded, or holds the list */
|
||||
export const followAtom = atom(
|
||||
(get) => get(followingAtom),
|
||||
(_get, set, following: boolean) => {
|
||||
set(followingAtom, following);
|
||||
if (following) set(flowWindowAtom, (win) => trimWindow(win));
|
||||
if (!following) return;
|
||||
set(flowWindowAtom, (win) => trimWindow(win));
|
||||
set(searchWindowAtom, (s) => (s == null ? s : { ...s, win: trimWindow(s.win) }));
|
||||
},
|
||||
);
|
||||
|
||||
/** The engine's state, kept current from its events, and polled while another process has it */
|
||||
export const proxyStateAtom = atom<GetProxyStateResponse | null>(null);
|
||||
|
||||
/**
|
||||
* Changes applied while a page of older flows loads, or null when none is loading. A slow flow
|
||||
* that ends meanwhile may be older than the window, so left out of it, and missing from a page
|
||||
@@ -51,22 +109,29 @@ export const followAtom = atom(
|
||||
*/
|
||||
let changesDuringPage: ModelPayload[] | null = null;
|
||||
|
||||
/** Loads the page of flows before the oldest one held */
|
||||
/** Loads the page of flows before the oldest one shown, from the search's flows when searching */
|
||||
export const loadOlderFlowsAtom = atom(null, async (get, set) => {
|
||||
const { flows, hasOlder } = get(flowWindowAtom);
|
||||
const search = get(searchWindowAtom);
|
||||
const { flows, hasOlder } = search?.win ?? get(flowWindowAtom);
|
||||
const first = flows[0];
|
||||
if (changesDuringPage != null || !hasOlder || first == null) return;
|
||||
const changes: ModelPayload[] = [];
|
||||
changesDuringPage = changes;
|
||||
try {
|
||||
const res = await rpc("list_flows", { before: first.id, limit: PAGE_SIZE });
|
||||
// Dropped when the window moved on meanwhile, trimmed or cleared.
|
||||
set(flowWindowAtom, (win) => {
|
||||
const res = await rpc("list_flows", { ...search?.query, before: first.id, limit: PAGE_SIZE });
|
||||
// Dropped when the window moved on meanwhile, trimmed, cleared or searched again.
|
||||
const merge = (win: FlowWindow) => {
|
||||
if (win.flows[0]?.id !== first.id) return win;
|
||||
const merged = prependOlder(win, res.flows, PAGE_SIZE);
|
||||
const kept = search == null ? changes : changesFor(search.query, changes);
|
||||
// Counted when they first applied.
|
||||
return { ...applyChanges(merged, changes), total: merged.total };
|
||||
});
|
||||
return { ...applyChanges(merged, kept), total: merged.total };
|
||||
};
|
||||
if (search == null) {
|
||||
set(flowWindowAtom, merge);
|
||||
} else {
|
||||
set(searchWindowAtom, (s) => (s?.key === search.key ? { ...s, win: merge(s.win) } : s));
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("Failed to load older flows", err);
|
||||
} finally {
|
||||
@@ -74,16 +139,26 @@ export const loadOlderFlowsAtom = atom(null, async (get, set) => {
|
||||
}
|
||||
});
|
||||
|
||||
/** The changes a search's window takes: flows it matches, and every deletion */
|
||||
function changesFor(query: FlowQuery, changes: ModelPayload[]): ModelPayload[] {
|
||||
return changes.filter((c) => c.change.type === "delete" || matchesQuery(c.model, query));
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the newest flows, then keeps them current with the engine's events. Events gather for
|
||||
* `FLUSH_MS` and apply together, and the window drops its oldest flows while the list follows,
|
||||
* so a new flow costs the same however many the database holds.
|
||||
* Loads the newest flows, then keeps them current with the engine's events, or with reads of the
|
||||
* database while another process owns the engine. Events gather for `FLUSH_MS` and apply
|
||||
* together, and the window drops its oldest flows while the list follows, so a new flow costs the
|
||||
* same however many the database holds. A search gets a window of its own, kept current the same
|
||||
* way.
|
||||
*/
|
||||
export function syncFlows(store: ReturnType<typeof createStore>) {
|
||||
export function syncFlows(store: Store) {
|
||||
let pending: ModelPayload[] = [];
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let loaded = false;
|
||||
let loads = 0;
|
||||
let searchLoads = 0;
|
||||
/** A flow written at or before the newest the app has seen, for reading new ones after it */
|
||||
let seenId: string | null = null;
|
||||
|
||||
function flush() {
|
||||
timer = null;
|
||||
@@ -91,9 +166,17 @@ export function syncFlows(store: ReturnType<typeof createStore>) {
|
||||
const changes = pending;
|
||||
pending = [];
|
||||
changesDuringPage?.push(...changes);
|
||||
const following = store.get(followingAtom);
|
||||
store.set(flowWindowAtom, (win) => {
|
||||
const next = applyChanges(win, changes);
|
||||
return store.get(followingAtom) ? trimWindow(next) : next;
|
||||
return following ? trimWindow(next) : next;
|
||||
});
|
||||
store.set(searchWindowAtom, (s) => {
|
||||
if (s == null) return s;
|
||||
// A matching flow written after the page's snapshot would otherwise be missed.
|
||||
if (s.loading) return { ...s, buffered: [...s.buffered, ...changes] };
|
||||
const next = applyChanges(s.win, changesFor(s.query, changes));
|
||||
return { ...s, win: following ? trimWindow(next) : next };
|
||||
});
|
||||
const selected = store.get(selectedFlowAtom);
|
||||
const change = changes.findLast((c) => c.model.id === selected?.id);
|
||||
@@ -103,6 +186,11 @@ export function syncFlows(store: ReturnType<typeof createStore>) {
|
||||
if (recountTimer == null) recountTimer = setTimeout(recount, RECOUNT_MS);
|
||||
}
|
||||
|
||||
function receive(changes: ModelPayload[]) {
|
||||
pending.push(...changes);
|
||||
if (timer == null) timer = setTimeout(flush, FLUSH_MS);
|
||||
}
|
||||
|
||||
// The total counts each new flow as it comes, which a flow both in a page and in the events
|
||||
// around it can count twice or not at all; a count from the database a moment later settles it.
|
||||
let recountTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -115,11 +203,19 @@ export function syncFlows(store: ReturnType<typeof createStore>) {
|
||||
win.total === res.total ? win : { ...win, total: res.total },
|
||||
);
|
||||
});
|
||||
const search = store.get(searchWindowAtom);
|
||||
if (search == null || search.loading) return;
|
||||
void rpc("list_flows", { ...search.query, limit: 0 }).then((res) => {
|
||||
const total = res.matching ?? res.total;
|
||||
store.set(searchWindowAtom, (s) =>
|
||||
s?.key !== search.key || s.win.total === total ? s : { ...s, win: { ...s.win, total } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
listen("model_write", (payload) => {
|
||||
pending.push(payload);
|
||||
if (timer == null) timer = setTimeout(flush, FLUSH_MS);
|
||||
seenId = payload.model.id;
|
||||
receive([payload]);
|
||||
});
|
||||
|
||||
// Loads again rather than only emptying, for a flow written between the delete and the event.
|
||||
@@ -138,10 +234,123 @@ export function syncFlows(store: ReturnType<typeof createStore>) {
|
||||
// A clear since asked for a newer page.
|
||||
if (thisLoad !== loads) return;
|
||||
store.set(flowWindowAtom, windowFromPage(res.flows, WINDOW_SIZE, res.total));
|
||||
seenId = res.flows[0]?.id ?? null;
|
||||
loaded = true;
|
||||
store.set(flowsLoadedAtom, true);
|
||||
flush();
|
||||
});
|
||||
loadSearch(store.get(activeQueryAtom));
|
||||
}
|
||||
|
||||
/** Loads the first page of `query`'s flows into a window of its own, or drops it for null */
|
||||
function loadSearch(query: FlowQuery | null) {
|
||||
if (query == null) {
|
||||
store.set(searchWindowAtom, null);
|
||||
return;
|
||||
}
|
||||
// Unique to this load, so a slower answer to an earlier one with the same query, such as
|
||||
// one read before a clear, is dropped.
|
||||
const key = `${++searchLoads}:${JSON.stringify(query)}`;
|
||||
store.set(searchWindowAtom, { key, query, win: emptyWindow, loading: true, buffered: [] });
|
||||
const settle = (page: FlowWindow | null) =>
|
||||
store.set(searchWindowAtom, (s) => {
|
||||
if (s?.key !== key) return s;
|
||||
// Applied again over the page: a flow already in it is replaced, not added.
|
||||
const win = applyChanges(page ?? s.win, changesFor(query, s.buffered));
|
||||
return {
|
||||
...s,
|
||||
win: page == null ? win : { ...win, total: page.total },
|
||||
loading: false,
|
||||
buffered: [],
|
||||
};
|
||||
});
|
||||
void rpc("list_flows", { ...query, limit: WINDOW_SIZE })
|
||||
.then((res) => settle(windowFromPage(res.flows, WINDOW_SIZE, res.matching ?? res.total)))
|
||||
.catch((err) => {
|
||||
console.warn("Failed to search flows", err);
|
||||
settle(null);
|
||||
});
|
||||
}
|
||||
|
||||
let activeKey = JSON.stringify(store.get(activeQueryAtom));
|
||||
store.sub(activeQueryAtom, () => {
|
||||
const query = store.get(activeQueryAtom);
|
||||
const key = JSON.stringify(query);
|
||||
if (key === activeKey) return;
|
||||
activeKey = key;
|
||||
loadSearch(query);
|
||||
});
|
||||
|
||||
// While another process owns the engine no events come, so new flows are read from the
|
||||
// database. Reading after a flow that started last can return a slow one already seen, which
|
||||
// applies as an update; it never skips one.
|
||||
let polling = false;
|
||||
function readNewFlows() {
|
||||
if (polling || !loaded) return;
|
||||
polling = true;
|
||||
const after = seenId;
|
||||
const read =
|
||||
after == null
|
||||
? rpc("list_flows", { limit: WINDOW_SIZE })
|
||||
: rpc("list_flows", { after, limit: WINDOW_SIZE });
|
||||
read
|
||||
.then((res) => {
|
||||
if (res.flows.length === 0) return;
|
||||
// More arrived than one read holds: load the newest again rather than leave a gap.
|
||||
if (res.flows.length >= WINDOW_SIZE) {
|
||||
load();
|
||||
return;
|
||||
}
|
||||
if (seenId === after) seenId = res.flows[0]?.id ?? seenId;
|
||||
const known = new Set(store.get(flowsAtom).map((f) => f.id));
|
||||
receive(
|
||||
[...res.flows].reverse().map((model) => ({
|
||||
model,
|
||||
change: { type: "upsert", created: !known.has(model.id) },
|
||||
})),
|
||||
);
|
||||
})
|
||||
// The flow read after was cleared: start again from the newest.
|
||||
.catch(() => {
|
||||
seenId = null;
|
||||
load();
|
||||
})
|
||||
.finally(() => {
|
||||
polling = false;
|
||||
});
|
||||
}
|
||||
setInterval(() => {
|
||||
if (store.get(proxyStateAtom)?.otherOwner != null) readNewFlows();
|
||||
}, POLL_MS);
|
||||
// One last read once another owner lets go, for flows it wrote after the last one.
|
||||
let hadOtherOwner = store.get(proxyStateAtom)?.otherOwner != null;
|
||||
store.sub(proxyStateAtom, () => {
|
||||
const hasOtherOwner = store.get(proxyStateAtom)?.otherOwner != null;
|
||||
if (hadOtherOwner && !hasOtherOwner) readNewFlows();
|
||||
hadOtherOwner = hasOtherOwner;
|
||||
});
|
||||
|
||||
load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps `proxyStateAtom` current: on each state change, and polled while the engine is not
|
||||
* running here, so another process taking it or letting it go shows.
|
||||
*/
|
||||
export function syncProxyState(store: Store) {
|
||||
function refresh() {
|
||||
rpc("get_proxy_state", {})
|
||||
.then((state) => store.set(proxyStateAtom, state))
|
||||
.catch((err) => console.warn("Failed to read the proxy state", err));
|
||||
}
|
||||
listen("proxy_state_changed", refresh);
|
||||
setInterval(() => {
|
||||
if (store.get(proxyStateAtom)?.state !== "running") refresh();
|
||||
}, OWNER_POLL_MS);
|
||||
refresh();
|
||||
}
|
||||
|
||||
/** Reads the proxy state again, after an action that changes it without an event */
|
||||
export async function refreshProxyState(store: Store) {
|
||||
store.set(proxyStateAtom, await rpc("get_proxy_state", {}));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { recordingLabel, type SystemProxyState, systemProxySwitch } from "./systemProxy";
|
||||
|
||||
const off: SystemProxyState = { routing: false, port: 9090, pending: null, error: null };
|
||||
|
||||
describe("systemProxySwitch", () => {
|
||||
test("says whether this Mac's traffic is routed now", () => {
|
||||
expect(systemProxySwitch({ ...off, routing: true })).toEqual({
|
||||
checked: true,
|
||||
description: "Routing this Mac's web traffic through Yaak Proxy",
|
||||
failed: false,
|
||||
});
|
||||
expect(systemProxySwitch(off)).toEqual({
|
||||
checked: false,
|
||||
description: "Not routing. Only apps pointed at port 9090 are captured",
|
||||
failed: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("shows the new value while the password prompt is up", () => {
|
||||
expect(systemProxySwitch({ ...off, pending: true })).toEqual({
|
||||
checked: true,
|
||||
description: "Waiting for your password",
|
||||
failed: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("snaps back on a cancelled prompt and says so", () => {
|
||||
expect(systemProxySwitch({ ...off, error: "Cancelled in the password dialog" })).toEqual({
|
||||
checked: false,
|
||||
description: "Cancelled in the password prompt",
|
||||
failed: true,
|
||||
});
|
||||
expect(systemProxySwitch({ ...off, error: "networksetup failed" }).description).toBe(
|
||||
"networksetup failed",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("recordingLabel", () => {
|
||||
test("offers the opposite of the current state", () => {
|
||||
expect(recordingLabel(true)).toBe("Pause Recording");
|
||||
expect(recordingLabel(false)).toBe("Resume Recording");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* "Override system proxy": this Mac's web traffic pointed at the running engine, changed at once
|
||||
* whenever it is flipped, through the macOS password prompt. Whether it turns on as the app
|
||||
* launches is a separate setting.
|
||||
*/
|
||||
export interface SystemProxyState {
|
||||
/** This Mac's web traffic points at the engine now */
|
||||
routing: boolean;
|
||||
/** The port apps can be pointed at by hand */
|
||||
port: number | null;
|
||||
/** A change is in flight, to this value */
|
||||
pending: boolean | null;
|
||||
/** The last change failed, with this message */
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface SystemProxySwitch {
|
||||
checked: boolean;
|
||||
description: string;
|
||||
/** The description reports a failure */
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
/** What the system proxy switch shows */
|
||||
export function systemProxySwitch(state: SystemProxyState): SystemProxySwitch {
|
||||
if (state.pending != null) {
|
||||
return { checked: state.pending, description: "Waiting for your password", failed: false };
|
||||
}
|
||||
// A failed change leaves the switch where the system proxy actually is.
|
||||
const checked = state.routing;
|
||||
if (state.error != null) {
|
||||
const cancelled = /cancel/i.test(state.error);
|
||||
return {
|
||||
checked,
|
||||
description: cancelled ? "Cancelled in the password prompt" : state.error,
|
||||
failed: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
checked,
|
||||
description: checked
|
||||
? "Routing this Mac's web traffic through Yaak Proxy"
|
||||
: `Not routing. Only apps pointed at port ${state.port ?? 9090} are captured`,
|
||||
failed: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** The menu item that pauses or resumes storing flows */
|
||||
export function recordingLabel(recording: boolean): string {
|
||||
return recording ? "Pause Recording" : "Resume Recording";
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { type ShowToastArgs, showToast } from "@yaakapp-internal/ui";
|
||||
import { useStore } from "jotai";
|
||||
import { useCallback } from "react";
|
||||
|
||||
/** Shows one of the client's toasts from this app's store, a success unless it says otherwise */
|
||||
export function useShowToast() {
|
||||
const store = useStore();
|
||||
return useCallback(
|
||||
(toast: ShowToastArgs) => showToast(store, { color: "success", ...toast }),
|
||||
[store],
|
||||
);
|
||||
}
|
||||
@@ -6,12 +6,13 @@ import { type ReactNode, StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { ProxyLayout } from "./components/ProxyLayout";
|
||||
import { useHotkeyContextValue } from "./lib/hotkeys";
|
||||
import { syncFlows } from "./lib/store";
|
||||
import { syncFlows, syncProxyState } from "./lib/store";
|
||||
import "./main.css";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
const jotaiStore = createStore();
|
||||
|
||||
syncProxyState(jotaiStore);
|
||||
syncFlows(jotaiStore);
|
||||
|
||||
function Hotkeys({ children }: { children: ReactNode }) {
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
"@tanstack/react-query": "^5.104.2",
|
||||
"@tanstack/react-virtual": "^3.14.17",
|
||||
"@tauri-apps/api": "^2.12.3",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.2",
|
||||
"@tauri-apps/plugin-opener": "^2.7.1",
|
||||
"@tauri-apps/plugin-os": "^2.4.0",
|
||||
"@yaakapp-internal/proxy-lib": "^1.0.0",
|
||||
"@yaakapp-internal/theme": "^1.0.0",
|
||||
|
||||
Reference in new issue
Block a user