diff --git a/.gitignore b/.gitignore index 1beb88f89..f4d96a8bc 100644 --- a/.gitignore +++ b/.gitignore @@ -59,3 +59,6 @@ flatpak/node-sources.json # Claude Code local settings .claude/settings.local.json .claude/worktrees/ + +# Headless screenshots taken while working +.shots/ diff --git a/Cargo.lock b/Cargo.lock index 9ff5f085a..2ba6a2725 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4156,6 +4156,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95b4103cffefa72eb8428cb6b47d6627161e51c2739fc5e3b734584157bc642a" dependencies = [ "cc", + "openssl-sys", "pkg-config", "vcpkg", ] @@ -6480,6 +6481,70 @@ dependencies = [ "prost", ] +[[package]] +name = "protoc-bin-vendored" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8760a25b6ff9c620324822737e468478fa092234190d2e449760344354896ed9" +dependencies = [ + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", +] + +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73fa2624782ca04cd44f51554566717377acd240e4c0016d757dd74fccc9324f" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2417e9817fa237dab803ad4dda7357a111656e242959cc6b8f9a1a583367d42" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d189c34636356a46a7ed3188233dc8a88c431278cc54d4a19b096a2d270e985" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "171e39f1e846e5f322ced1ac3b8d4cd3a3833ca24b6e5d58b3632574fe6204fa" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "873cdcc097593432086661aa432b8078f1cd87bfb02847c332e98ae2c119e966" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb72df001783b8297847fe8f5f874ee400fd742c843d60583e8c23d96977c7f" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b04652167eca899dda05f32f5481adeaf25c623a98ce2fc146a001cc59a2add7" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263a3f48f01e7309e857138bd47f785585b4a005e8e56c6d2824ce91195999c3" + [[package]] name = "quick-error" version = "1.2.3" @@ -11512,6 +11577,7 @@ dependencies = [ name = "yaak-commands" version = "0.0.0" dependencies = [ + "rusqlite", "serde_json", "tempfile", "thiserror 2.0.21", @@ -11548,9 +11614,11 @@ dependencies = [ "base32", "base64 0.23.1", "chacha20poly1305", + "dbus-secret-service", "keyring", "log 0.4.34", "serde", + "tempfile", "thiserror 2.0.21", "yaak-models", ] @@ -11564,6 +11632,7 @@ dependencies = [ "include_dir", "log 0.4.34", "nanoid", + "openssl-sys", "r2d2", "r2d2_sqlite", "rusqlite", @@ -11571,6 +11640,7 @@ dependencies = [ "sea-query-rusqlite", "serde", "serde_json", + "tempfile", "thiserror 2.0.21", "ts-rs", "uuid", @@ -11813,12 +11883,17 @@ dependencies = [ name = "yaak-proxy" version = "0.1.0" dependencies = [ + "base64 0.23.1", + "block2 0.6.1", "bytes", + "dispatch2", + "flate2", "futures-util", "http", "http-body-util", "hyper", "hyper-util", + "libc", "log 0.4.34", "pem", "rcgen", @@ -11830,6 +11905,7 @@ dependencies = [ "tokio", "tokio-rustls", "tokio-tungstenite", + "tower-service", ] [[package]] @@ -11852,8 +11928,10 @@ dependencies = [ "base64 0.23.1", "bytes", "chrono", + "core-foundation 0.9.4", "encoding_rs", "flate2", + "futures-util", "http-body-util", "hyper", "hyper-util", @@ -11865,6 +11943,7 @@ dependencies = [ "objc2-foundation 0.3.2", "objc2-service-management", "plist", + "protoc-bin-vendored", "r2d2", "r2d2_sqlite", "reqwest", @@ -11872,22 +11951,39 @@ dependencies = [ "sea-query", "serde", "serde_json", + "system-configuration", "tempfile", "tokio", + "tonic", + "tonic-reflection", "ts-rs", "url", "yaak-common", + "yaak-crypto", "yaak-database", "yaak-filter", + "yaak-grpc", "yaak-http", "yaak-lifecycle", "yaak-models", "yaak-proxy", "yaak-proxy-helper", + "yaak-query", "yaak-rpc", "yaak-templates", ] +[[package]] +name = "yaak-query" +version = "0.1.0" +dependencies = [ + "serde", + "serde-wasm-bindgen", + "serde_json", + "ts-rs", + "wasm-bindgen", +] + [[package]] name = "yaak-rpc" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index 40557a8ea..5e29d0da6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ members = [ "crates/yaak-mcp", "crates/yaak-models", "crates/yaak-plugins", + "crates/yaak-query", "crates/yaak-sse", "crates/yaak-sync", "crates/yaak-templates", @@ -96,6 +97,7 @@ yaak-lifecycle = { path = "crates/yaak-lifecycle" } yaak-mcp = { path = "crates/yaak-mcp" } yaak-models = { path = "crates/yaak-models" } yaak-plugins = { path = "crates/yaak-plugins" } +yaak-query = { path = "crates/yaak-query" } yaak-sse = { path = "crates/yaak-sse" } yaak-sync = { path = "crates/yaak-sync" } yaak-templates = { path = "crates/yaak-templates" } diff --git a/apps/yaak-client/components/HttpAuthenticationEditor.tsx b/apps/yaak-client/components/HttpAuthenticationEditor.tsx index 0da989bcc..159ceb16b 100644 --- a/apps/yaak-client/components/HttpAuthenticationEditor.tsx +++ b/apps/yaak-client/components/HttpAuthenticationEditor.tsx @@ -6,7 +6,7 @@ import type { Workspace, } from "@yaakapp-internal/models"; import { patchModel } from "@yaakapp-internal/models"; -import { HStack, Icon, InlineCode } from "@yaakapp-internal/ui"; +import { HStack, Icon, InlineCode, SegmentedControl } from "@yaakapp-internal/ui"; import { useCallback } from "react"; import { openFolderSettings } from "../commands/openFolderSettings"; import { openWorkspaceSettings } from "../commands/openWorkspaceSettings"; @@ -21,7 +21,6 @@ import { IconButton } from "./core/IconButton"; import { Input, type InputProps } from "./core/Input"; import { Link } from "./core/Link"; import { RadioDropdown } from "./core/RadioDropdown"; -import { SegmentedControl } from "./core/SegmentedControl"; import { DynamicForm } from "./DynamicForm"; import { EmptyStateText } from "./EmptyStateText"; diff --git a/apps/yaak-client/components/ImportDataDialog.tsx b/apps/yaak-client/components/ImportDataDialog.tsx index 43e698e06..50d1f6e9e 100644 --- a/apps/yaak-client/components/ImportDataDialog.tsx +++ b/apps/yaak-client/components/ImportDataDialog.tsx @@ -5,7 +5,15 @@ import { type ImportSource, type Workspace, } from "@yaakapp-internal/models"; -import { Banner, FormattedError, HStack, Icon, VStack, IconTooltip } from "@yaakapp-internal/ui"; +import { + Banner, + FormattedError, + HStack, + Icon, + VStack, + IconTooltip, + SegmentedControl, +} from "@yaakapp-internal/ui"; import classNames from "classnames"; import { type ComponentProps, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { errorMessage } from "../lib/errorMessage"; @@ -22,7 +30,6 @@ import { CheckboxTree } from "./core/CheckboxTree"; import { Chip } from "./core/Chip"; import { DialogFooter } from "./core/Dialog"; import { Select } from "./core/Select"; -import { SegmentedControl } from "./core/SegmentedControl"; import { pluralize } from "@yaakapp-internal/lib/pluralize"; interface Props { diff --git a/apps/yaak-client/components/MarkdownEditor.tsx b/apps/yaak-client/components/MarkdownEditor.tsx index be31570f2..80f540c55 100644 --- a/apps/yaak-client/components/MarkdownEditor.tsx +++ b/apps/yaak-client/components/MarkdownEditor.tsx @@ -1,8 +1,8 @@ +import { SegmentedControl } from "@yaakapp-internal/ui"; import classNames from "classnames"; import { useRef, useState } from "react"; import type { EditorProps } from "./core/Editor/Editor"; import { Editor } from "./core/Editor/LazyEditor"; -import { SegmentedControl } from "./core/SegmentedControl"; import { Markdown } from "./Markdown"; type ViewMode = "edit" | "preview"; diff --git a/apps/yaak-client/components/Settings/Settings.tsx b/apps/yaak-client/components/Settings/Settings.tsx index 1039ce74f..6ab3bed9d 100644 --- a/apps/yaak-client/components/Settings/Settings.tsx +++ b/apps/yaak-client/components/Settings/Settings.tsx @@ -1,13 +1,19 @@ import { platform } from "@yaakapp-internal/platform"; import { useLicense } from "@yaakapp-internal/license"; import { pluginsAtom, settingsAtom } from "@yaakapp-internal/models"; -import { HeaderSize, HStack, Icon, CountBadge } from "@yaakapp-internal/ui"; -import classNames from "classnames"; +import { + CountBadge, + SETTINGS_TAB_GENERAL, + SETTINGS_TAB_INTERFACE, + SETTINGS_TAB_LICENSE, + SETTINGS_TAB_THEME, + SettingsDialog, + type SettingsTabDef, +} from "@yaakapp-internal/ui"; import { useAtomValue } from "jotai"; import { useKeyPressEvent } from "react-use"; import { appInfo } from "../../lib/appInfo"; import { capitalize } from "../../lib/capitalize"; -import { TabContent, type TabItem, Tabs } from "../core/Tabs/Tabs"; import { SettingsAgents } from "./SettingsAgents"; import { SettingsCertificates } from "./SettingsCertificates"; import { SettingsGeneral } from "./SettingsGeneral"; @@ -24,15 +30,15 @@ interface Props { hide?: () => void; } -const TAB_GENERAL = "general"; -const TAB_INTERFACE = "interface"; -const TAB_THEME = "theme"; +const TAB_GENERAL = SETTINGS_TAB_GENERAL; +const TAB_INTERFACE = SETTINGS_TAB_INTERFACE; +const TAB_THEME = SETTINGS_TAB_THEME; const TAB_SHORTCUTS = "shortcuts"; const TAB_PROXY = "proxy"; const TAB_CERTIFICATES = "certificates"; const TAB_PLUGINS = "plugins"; const TAB_AGENTS = "agents"; -const TAB_LICENSE = "license"; +const TAB_LICENSE = SETTINGS_TAB_LICENSE; const tabs = [ TAB_GENERAL, TAB_THEME, @@ -60,105 +66,57 @@ export default function Settings({ tab, hide }: Props) { if (hide == null) await platform.window.close(); }); + const tabDefs: Record> = { + [TAB_GENERAL]: { icon: "settings", content: }, + [TAB_THEME]: { icon: "palette", content: }, + [TAB_INTERFACE]: { icon: "columns_2", content: }, + [TAB_SHORTCUTS]: { icon: "keyboard", content: }, + [TAB_PLUGINS]: { + icon: "puzzle", + rightSlot: p.source !== "bundled").length} />, + content: , + contentClassName: "h-full grid grid-rows-1", + }, + [TAB_AGENTS]: { + icon: "sparkles", + hidden: !platform.capabilities.agents, + content: , + }, + [TAB_CERTIFICATES]: { + icon: "shield_check", + rightSlot: , + content: , + }, + [TAB_PROXY]: { + icon: "wifi", + rightSlot: settings.proxy?.type === "enabled" ? : null, + content: , + }, + [TAB_LICENSE]: { + icon: "key_round", + hidden: !appInfo.featureLicense, + rightSlot: + licenseCheck.check.data?.status === "personal_use" ? ( + + ) : null, + content: , + }, + }; + return ( -
- {hide ? ( - - ) : ( - - -
Settings
-
-
- )} - ({ - value, - label: capitalize(value), - hidden: - (!appInfo.featureLicense && value === TAB_LICENSE) || - (!platform.capabilities.agents && value === TAB_AGENTS), - leftSlot: - value === TAB_GENERAL ? ( - - ) : value === TAB_THEME ? ( - - ) : value === TAB_INTERFACE ? ( - - ) : value === TAB_SHORTCUTS ? ( - - ) : value === TAB_CERTIFICATES ? ( - - ) : value === TAB_PROXY ? ( - - ) : value === TAB_PLUGINS ? ( - - ) : value === TAB_AGENTS ? ( - - ) : value === TAB_LICENSE ? ( - - ) : null, - rightSlot: - value === TAB_CERTIFICATES ? ( - - ) : value === TAB_PLUGINS ? ( - p.source !== "bundled").length} /> - ) : value === TAB_PROXY && settings.proxy?.type === "enabled" ? ( - - ) : value === TAB_LICENSE && licenseCheck.check.data?.status === "personal_use" ? ( - - ) : null, - }), - )} - > - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ ({ value, label: capitalize(value), ...tabDefs[value] }))} + /> ); } diff --git a/apps/yaak-client/components/Settings/SettingsAgents.tsx b/apps/yaak-client/components/Settings/SettingsAgents.tsx index 4ba04091c..bdc0f629f 100644 --- a/apps/yaak-client/components/Settings/SettingsAgents.tsx +++ b/apps/yaak-client/components/Settings/SettingsAgents.tsx @@ -1,7 +1,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query"; import { platform } from "@yaakapp-internal/platform"; import type { AgentSetupStatus, AppMetaData } from "@yaakapp-internal/rpc-schema"; -import { Banner, Heading, Icon, InlineCode, VStack } from "@yaakapp-internal/ui"; +import { Banner, Heading, Icon, InlineCode, SegmentedControl, VStack } from "@yaakapp-internal/ui"; import { useEffect } from "react"; import { useKeyValue } from "../../hooks/useKeyValue"; import { usePluginInfos } from "../../hooks/usePluginInfo"; @@ -14,7 +14,6 @@ import { import { appInfo } from "../../lib/appInfo"; import { rpc } from "../../lib/rpc"; import { Link } from "../core/Link"; -import { SegmentedControl } from "../core/SegmentedControl"; import { SettingCommand, SettingSnippet, diff --git a/apps/yaak-client/components/Settings/SettingsGeneral.tsx b/apps/yaak-client/components/Settings/SettingsGeneral.tsx index d36758f9b..9b022b644 100644 --- a/apps/yaak-client/components/Settings/SettingsGeneral.tsx +++ b/apps/yaak-client/components/Settings/SettingsGeneral.tsx @@ -1,32 +1,17 @@ -import { patchModel, settingsAtom } from "@yaakapp-internal/models"; -import { Heading, VStack } from "@yaakapp-internal/ui"; +import { settingsAtom } from "@yaakapp-internal/models"; +import { SettingsGeneral as SharedSettingsGeneral } from "@yaakapp-internal/ui"; import { useAtomValue } from "jotai"; -import { useCheckForUpdates } from "../../hooks/useCheckForUpdates"; -import { appInfo } from "../../lib/appInfo"; -import { revealInFinderText } from "../../lib/reveal"; -import { CargoFeature } from "../CargoFeature"; +import { useSettingsView } from "../../hooks/useSettingsView"; import { CommercialUseBanner } from "../CommercialUseBanner"; import { DismissibleBanner } from "../core/DismissibleBanner"; -import { IconButton } from "../core/IconButton"; -import { platform } from "@yaakapp-internal/platform"; -import { - ModelSettingRowBoolean, - ModelSettingSelectControl, - SettingValue, - SettingRow, - SettingRowBoolean, - SettingRowSelect, - SettingsList, - SettingsSection, -} from "../core/SettingRow"; const WORKSPACE_SETTINGS_MOVED_AT = "2026-06-30"; export function SettingsGeneral() { const settings = useAtomValue(settingsAtom); - const checkForUpdates = useCheckForUpdates(); + const bound = useSettingsView(); - if (settings == null) { + if (settings == null || bound == null) { return null; } @@ -34,147 +19,24 @@ export function SettingsGeneral() { settings.createdAt.slice(0, 10) < WORKSPACE_SETTINGS_MOVED_AT; return ( - -
- General -

- Configure general settings for update behavior and more. -

-
-
- -
- - - - -
- - checkForUpdates.mutateAsync()} - /> -
-
- - - patchModel(settings, { autoupdate: v === "auto" }) - } - options={[ - { label: "Automatic", value: "auto" }, - { label: "Manual", value: "manual" }, - ]} - /> - - - - - - {}} - /> -
-
- - - - patchModel(settings, { promptFeedback })} - /> - - - - {showWorkspaceSettingsMovedBanner && ( + } + extraSections={ + showWorkspaceSettingsMovedBanner && (

- Workspace specific settings have moved to{" "} - Workspace Settings, accessible from the workspace switcher - menu. + Workspace specific settings have moved to Workspace Settings, accessible from + the workspace switcher menu.

- )} - - - - - - - platform.revealItemInDir(appInfo.appDataDir), - }, - ]} - /> - - - platform.revealItemInDir(appInfo.appLogDir), - }, - ]} - /> - - -
-
+ ) + } + /> ); } diff --git a/apps/yaak-client/components/Settings/SettingsInterface.tsx b/apps/yaak-client/components/Settings/SettingsInterface.tsx index baffa2738..6952ab511 100644 --- a/apps/yaak-client/components/Settings/SettingsInterface.tsx +++ b/apps/yaak-client/components/Settings/SettingsInterface.tsx @@ -1,59 +1,30 @@ -import { platform } from "@yaakapp-internal/platform"; -import { useFonts } from "@yaakapp-internal/fonts"; import { useLicense } from "@yaakapp-internal/license"; -import type { EditorKeymap, Settings } from "@yaakapp-internal/models"; +import type { Settings } from "@yaakapp-internal/models"; import { patchModel, settingsAtom } from "@yaakapp-internal/models"; -import { clamp, Heading, VStack } from "@yaakapp-internal/ui"; +import { SettingsInterface as SharedSettingsInterface, VStack } from "@yaakapp-internal/ui"; import { useAtomValue } from "jotai"; -import { useState } from "react"; import { activeWorkspaceAtom } from "../../hooks/useActiveWorkspace"; +import { useSettingsView } from "../../hooks/useSettingsView"; import { showConfirm } from "../../lib/confirm"; import { pricingUrl } from "../../lib/pricingUrl"; -import { rpc } from "../../lib/rpc"; import { CargoFeature } from "../CargoFeature"; -import { Button } from "../core/Button"; -import { Checkbox } from "../core/Checkbox"; import { Link } from "../core/Link"; -import { - ModelSettingRowBoolean, - ModelSettingRowSelect, - SettingRow, - SettingRowBoolean, - SettingRowSelect, - SettingSelectControl, - SettingsList, - SettingsSection, -} from "../core/SettingRow"; - -const NULL_FONT_VALUE = "__NULL_FONT__"; - -const fontSizeOptions = [ - 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, -].map((n) => ({ label: `${n}`, value: `${n}` })); - -const keymaps: { value: EditorKeymap; label: string }[] = [ - { value: "default", label: "Default" }, - { value: "vim", label: "Vim" }, - { value: "vscode", label: "VSCode" }, - { value: "emacs", label: "Emacs" }, -]; +import { SettingRowBoolean, SettingRowSelect, SettingsSection } from "../core/SettingRow"; export function SettingsInterface() { const workspace = useAtomValue(activeWorkspaceAtom); const settings = useAtomValue(settingsAtom); - const fonts = useFonts(); + const bound = useSettingsView(); - if (settings == null || workspace == null) { + if (settings == null || workspace == null || bound == null) { return null; } return ( - -
- Interface -

Tweak settings related to the user interface.

-
- + - - - - {fonts.data && ( - ({ label: f, value: f })), - ...fonts.data.editorFonts.map((f) => ({ label: f, value: f })), - ]} - onChange={async (v) => { - const interfaceFont = v === NULL_FONT_VALUE ? null : v; - await patchModel(settings, { interfaceFont }); - }} - /> - )} - patchModel(settings, { interfaceFontSize: Number.parseInt(v, 10) })} - /> - - - - {fonts.data && ( - ({ label: f, value: f })), - ]} - onChange={async (v) => { - const editorFont = v === NULL_FONT_VALUE ? null : v; - await patchModel(settings, { editorFont }); - }} - /> - )} - - patchModel(settings, { - editorFontSize: clamp(Number.parseInt(v, 10) || 14, 8, 30), - }) - } - /> - - - - - - - - - - - - {platform.osType() !== "macos" && ( - - )} - - + } + trailingSections={ - -
- ); -} - -function NativeTitlebarSetting({ settings }: { settings: Settings }) { - const [nativeTitlebar, setNativeTitlebar] = useState(settings.useNativeTitlebar); - - return ( - - - {settings.useNativeTitlebar !== nativeTitlebar && ( - - )} - + } + /> ); } diff --git a/apps/yaak-client/components/Settings/SettingsLicense.tsx b/apps/yaak-client/components/Settings/SettingsLicense.tsx index 9e72d481c..3853bd21c 100644 --- a/apps/yaak-client/components/Settings/SettingsLicense.tsx +++ b/apps/yaak-client/components/Settings/SettingsLicense.tsx @@ -1,17 +1,6 @@ -import { useLicense } from "@yaakapp-internal/license"; -import { Banner, HStack, Icon, VStack } from "@yaakapp-internal/ui"; -import { differenceInDays } from "date-fns"; -import { formatDate } from "date-fns/format"; -import { useState } from "react"; -import { useToggle } from "../../hooks/useToggle"; -import { pricingUrl } from "../../lib/pricingUrl"; +import { SettingsLicense as SharedSettingsLicense } from "@yaakapp-internal/ui"; +import { useSettingsView } from "../../hooks/useSettingsView"; import { CargoFeature } from "../CargoFeature"; -import { Button } from "../core/Button"; -import { Link } from "../core/Link"; -import { PlainInput } from "../core/PlainInput"; -import { Separator } from "../core/Separator"; -import { platform } from "@yaakapp-internal/platform"; -import { pluralizeCount } from "@yaakapp-internal/lib/pluralize"; export function SettingsLicense() { return ( @@ -22,166 +11,7 @@ export function SettingsLicense() { } function SettingsLicenseCmp() { - const { check, activate, deactivate } = useLicense(); - const [key, setKey] = useState(""); - const [activateFormVisible, toggleActivateFormVisible] = useToggle(false); - - if (check.isPending) { - return null; - } - - const renderBanner = () => { - if (!check.data) return null; - - switch (check.data.status) { - case "active": - return Your license is active 🥳; - - case "trialing": - return ( - -

- - {pluralizeCount("day", differenceInDays(check.data.data.end, new Date()))} - {" "} - left to evaluate Yaak for commercial use. -
- Personal use is always free, forever. - -

- - Learn More - -
-

-
- ); - - case "personal_use": - return ( - -

- Your commercial-use trial has ended. -
- - You may continue using Yaak for personal use only. -
A license is required for commercial use. -
- -

- - Learn More - -
-

-
- ); - - case "inactive": - return ( - - Your license is invalid. Please Sign In{" "} - for more details - - ); - - case "expired": - return ( - - Your license expired{" "} - {formatDate(check.data.data.periodEnd, "MMMM dd, yyyy")}. Please{" "} - Resubscribe to continue receiving - updates. - {check.data.data.changesUrl && ( - <> -
- What's new in latest builds - - )} -
- ); - - case "past_due": - return ( - - Your payment method needs attention. -
- To re-activate your license, please{" "} - update your billing info. -
- ); - - case "error": - return ( - - License check failed: {check.data.data.message} (Code: {check.data.data.code}) - - ); - } - }; - - return ( -
- {renderBanner()} - - {check.error && {check.error}} - {activate.error && {activate.error}} - - {check.data?.status === "active" ? ( - - - - - ) : ( - - - - - )} - - {activateFormVisible && ( - { - e.preventDefault(); - await activate.mutateAsync({ licenseKey: key }); - toggleActivateFormVisible(); - }} - > - - - - )} -
- ); + const bound = useSettingsView(); + if (bound == null) return null; + return ; } diff --git a/apps/yaak-client/components/Settings/SettingsTheme.tsx b/apps/yaak-client/components/Settings/SettingsTheme.tsx index 268109045..d71e3113e 100644 --- a/apps/yaak-client/components/Settings/SettingsTheme.tsx +++ b/apps/yaak-client/components/Settings/SettingsTheme.tsx @@ -1,173 +1,15 @@ -import { patchModel, settingsAtom } from "@yaakapp-internal/models"; -import { Heading, HStack, Icon, type IconProps, VStack } from "@yaakapp-internal/ui"; +import { SettingsTheme as SharedSettingsTheme } from "@yaakapp-internal/ui"; import { useAtomValue } from "jotai"; -import { lazy, Suspense } from "react"; import { activeWorkspaceAtom } from "../../hooks/useActiveWorkspace"; -import { useResolvedAppearance } from "../../hooks/useResolvedAppearance"; -import { useResolvedTheme } from "../../hooks/useResolvedTheme"; -import type { ButtonProps } from "../core/Button"; -import { IconButton } from "../core/IconButton"; -import { Link } from "../core/Link"; -import type { SelectProps } from "../core/Select"; -import { - ModelSettingRowSelect, - SettingRowSelect, - SettingsList, - SettingsSection, -} from "../core/SettingRow"; - -const Editor = lazy(() => import("../core/Editor/Editor").then((m) => ({ default: m.Editor }))); - -const buttonColors: ButtonProps["color"][] = [ - "primary", - "info", - "success", - "notice", - "warning", - "danger", - "secondary", - "default", -]; - -const icons: IconProps["icon"][] = [ - "info", - "box", - "update", - "alert_triangle", - "arrow_big_right_dash", - "download", - "copy", - "magic_wand", - "settings", - "trash", - "sparkles", - "pencil", - "paste", - "search", - "send_horizontal", -]; +import { useSettingsView } from "../../hooks/useSettingsView"; export function SettingsTheme() { const workspace = useAtomValue(activeWorkspaceAtom); - const settings = useAtomValue(settingsAtom); - const appearance = useResolvedAppearance(); - const activeTheme = useResolvedTheme(); + const bound = useSettingsView(); - if (settings == null || workspace == null || activeTheme.data == null) { + if (workspace == null || bound == null) { return null; } - const lightThemes: SelectProps["options"] = activeTheme.data.themes - .filter((theme) => !theme.dark) - .map((theme) => ({ - label: theme.label, - value: theme.id, - })); - - const darkThemes: SelectProps["options"] = activeTheme.data.themes - .filter((theme) => theme.dark) - .map((theme) => ({ - label: theme.label, - value: theme.id, - })); - - return ( - -
- Theme -

- Make Yaak your own by selecting a theme, or{" "} - - Create Your Own - -

-
- - - - {(settings.appearance === "system" || settings.appearance === "light") && ( - patchModel(settings, { themeLight })} - /> - )} - {(settings.appearance === "system" || settings.appearance === "dark") && ( - patchModel(settings, { themeDark })} - /> - )} - - - - - - - {activeTheme.data.active.label} - (preview) - - - {buttonColors.map((c, i) => ( - - ))} - {buttonColors.map((c, i) => ( - - ))} - - - - - - - -
- ); + return ; } diff --git a/apps/yaak-client/components/Sidebar.tsx b/apps/yaak-client/components/Sidebar.tsx index b072b148a..0a94f5426 100644 --- a/apps/yaak-client/components/Sidebar.tsx +++ b/apps/yaak-client/components/Sidebar.tsx @@ -63,11 +63,9 @@ import { isSidebarFocused } from "../lib/scopes"; import { navigateToRequestOrFolderOrWorkspace } from "../lib/setWorkspaceSearchParams"; import type { ContextMenuProps, DropdownItem } from "./core/Dropdown"; import { ContextMenu, Dropdown } from "./core/Dropdown"; -import type { FieldDef } from "./core/Editor/filter/extension"; -import { filter } from "./core/Editor/filter/extension"; -import type { Ast } from "./core/Editor/filter/query"; -import { evaluate, parseQuery } from "./core/Editor/filter/query"; -import { formatFieldFilter } from "./core/Editor/filter/format"; +import type { Node as QueryNode, Schema } from "@yaakapp-internal/query"; +import { formatField, parseQuery, QueryMatcher } from "@yaakapp-internal/query"; +import { queryFilter } from "@yaakapp-internal/ui/editor"; import { HttpMethodTag } from "./core/HttpMethodTag"; import { Icon, @@ -112,7 +110,7 @@ function Sidebar({ className }: { className?: string }) { const activeWorkspaceId = useAtomValue(activeWorkspaceAtom)?.id; const treeId = `tree.${activeWorkspaceId ?? "unknown"}`; const filterText = useAtomValue(sidebarFilterAtom); - const [tree, allFields, emptyFilterSuggestions] = useAtomValue(sidebarTreeAtom) ?? []; + const [tree, fieldValues, emptyFilterSuggestions] = useAtomValue(sidebarTreeAtom) ?? []; const wrapperRef = useRef(null); const treeRef = useRef(null); @@ -553,18 +551,18 @@ function Sidebar({ className }: { className?: string }) { const filterCompartmentMountExtRef = useRef(null); if (filterCompartmentMountExtRef.current == null) { filterCompartmentMountExtRef.current = filterLanguageCompartmentRef.current.of( - filter({ fields: allFields ?? [] }), + queryFilter({ schema: sidebarFilterSchema, values: fieldValues }), ); } useEffect(() => { const view = filterRef.current; if (!view) return; - const ext = filter({ fields: allFields ?? [] }); + const ext = queryFilter({ schema: sidebarFilterSchema, values: fieldValues }); view.dispatch({ effects: filterLanguageCompartmentRef.current.reconfigure(ext), }); - }, [allFields]); + }, [fieldValues]); if (tree == null || hidden) { return null; @@ -852,16 +850,44 @@ function setSidebarFilterText(text: string) { jotaiStore.set(sidebarFilterAtom, { text, key: `${Math.random()}` }); } -function getSidebarSuggestionValue(ast: Ast | null) { +/** + * The fields `getItemFields` fills in, each with what it is and a term using it, as completion + * shows them. Bare words match `getItemText` by word prefix + */ +const sidebarFilterFields: [name: string, info: string, example: string][] = [ + ["method", "GET, POST, …", "@method:post"], + ["url", "Request URL", "@url:*/users*"], + ["name", "Request name", '@name:"Get user"'], + ["type", "http, grpc or ws", "@type:grpc"], + ["folder", "Parent folder", "@folder:auth"], + ["grpc_service", "gRPC service", "@grpc_service:*Greeter"], + ["grpc_method", "gRPC method", "@grpc_method:SayHello"], +]; +const sidebarFilterColumns = sidebarFilterFields.map(([name]) => name); +const sidebarFilterSchema: Schema = { + fields: sidebarFilterFields.map(([name, info, example]) => ({ + name, + kind: { type: "text" }, + info, + example, + })), + freeText: "fuzzy", +}; + +function getSidebarSuggestionValue(ast: QueryNode | null, query: string) { if (ast == null) return null; if (ast.type === "Term" || ast.type === "Phrase") { - const value = ast.value.trim(); + const value = ast.text.trim(); return value.length > 0 ? value : null; } if (ast.type === "Field") { - const value = ast.value.trim(); + const raw = + ast.value.type === "text" + ? ast.value.text + : query.slice(ast.valueSpan.start, ast.valueSpan.end); + const value = raw.trim(); return value.length > 0 ? value : null; } @@ -883,7 +909,7 @@ const sidebarSuggestionFieldOrder = [ ]; const sidebarTreeAtom = atom< - [TreeNode, FieldDef[], SidebarFilterSuggestion[]] | null + [TreeNode, Record, SidebarFilterSuggestion[]] | null >((get) => { const allModels = get(memoAllPotentialChildrenAtom); const activeWorkspace = get(activeWorkspaceAtom); @@ -904,15 +930,18 @@ const sidebarTreeAtom = atom< return null; } - const queryAst = parseQuery(filter.text); - const suggestionValue = getSidebarSuggestionValue(queryAst); + const suggestionValue = getSidebarSuggestionValue(parseQuery(filter.text), filter.text); + const matcher = new QueryMatcher(filter.text, sidebarFilterSchema); + + // Every request goes into one flat table (its text, then a cell per column), matched in a + // single call after the tree is built + const leaves: TreeNode[] = []; + const cells: (string | null)[] = []; - // returns true if this node OR any child matches the filter const allFields: Record> = {}; const suggestionFields = new Set(); - const build = (node: TreeNode, depth: number): boolean => { + const build = (node: TreeNode, depth: number) => { const childItems = childrenMap[node.item.id] ?? []; - let matchesSelf = true; const fields = getItemFields(node); const model = node.item.model; const isLeafNode = !(model === "folder" || model === "workspace"); @@ -930,12 +959,12 @@ const sidebarTreeAtom = atom< } } - if (queryAst != null) { - matchesSelf = isLeafNode && evaluate(queryAst, { text: getItemText(node.item), fields }); + if (isLeafNode && !matcher.isEmpty) { + leaves.push(node); + cells.push(getItemText(node.item)); + for (const column of sidebarFilterColumns) cells.push(fields[column] ?? null); } - let matchesChild = false; - // Recurse to children node.children = !isLeafNode ? [] : undefined; @@ -953,19 +982,21 @@ const sidebarTreeAtom = atom< for (const item of childItems) { const childNode = { item, parent: node, depth }; - const childMatches = build(childNode, depth + 1); - if (childMatches) { - matchesChild = true; - } + build(childNode, depth + 1); node.children.push(childNode); } } + }; - // hide node IFF nothing in its subtree matches - const anyMatch = matchesSelf || matchesChild; - node.hidden = !anyMatch; - - return anyMatch; + // Hide a node IFF nothing in its subtree matches; with no query, nothing is hidden + let matched: Set> | null = null; + const markHidden = (node: TreeNode): boolean => { + let visible = matched == null || matched.has(node); + for (const child of node.children ?? []) { + if (markHidden(child)) visible = true; + } + node.hidden = !visible; + return visible; }; const root: TreeNode = { @@ -975,15 +1006,20 @@ const sidebarTreeAtom = atom< depth: 0, }; - // Build tree and mark visibility in one pass build(root, 1); + if (!matcher.isEmpty) { + const rows = matcher.matchingRows(sidebarFilterColumns, cells); + matched = new Set(Array.from(rows, (i) => leaves[i]!)); + } + matcher.free(); + markHidden(root); - const fields: FieldDef[] = []; + // Values offered after `@field:`. URLs and names are left out: nearly every one is unique, + // so a list of them is noise rather than a shortcut. + const fieldValues: Record = {}; for (const [name, values] of Object.entries(allFields)) { - fields.push({ - name, - values: Array.from(values).filter((v) => v.length < 20), - }); + if (name === "url" || name === "name") continue; + fieldValues[name] = Array.from(values); } const suggestions = Array.from(suggestionFields) .sort((a, b) => { @@ -994,9 +1030,9 @@ const sidebarTreeAtom = atom< }) .map((field) => ({ field, - filterText: formatFieldFilter(field, suggestionValue ?? ""), + filterText: formatField(field, suggestionValue ?? ""), })); - return [root, fields, suggestions] as const; + return [root, fieldValues, suggestions] as const; }); const sidebarGitStatusByModelIdAtom = atom>((get) => { diff --git a/apps/yaak-client/components/Workspace.tsx b/apps/yaak-client/components/Workspace.tsx index 1e6d22cef..9728244b2 100644 --- a/apps/yaak-client/components/Workspace.tsx +++ b/apps/yaak-client/components/Workspace.tsx @@ -1,10 +1,10 @@ import { platform } from "@yaakapp-internal/platform"; import { settingsAtom, workspacesAtom } from "@yaakapp-internal/models"; -import { Banner, HeaderSize, HStack, SidebarLayout } from "@yaakapp-internal/ui"; +import { Banner, HeaderSize, HeaderTint, HStack, SidebarLayout } from "@yaakapp-internal/ui"; import classNames from "classnames"; import { useAtomValue } from "jotai"; import * as m from "motion/react-m"; -import { useMemo, useState } from "react"; +import { useState } from "react"; import { getActiveCookieJar, useEnsureActiveCookieJar, @@ -61,12 +61,6 @@ export function Workspace() { const activeEnvironment = useAtomValue(activeEnvironmentAtom); const [floating, setFloating] = useState(false); - const environmentBgStyle = useMemo(() => { - if (activeEnvironment?.color == null) return undefined; - const background = `linear-gradient(to right, ${activeEnvironment.color} 15%, transparent 40%)`; - return { background }; - }, [activeEnvironment?.color]); - if (workspaces.length === 0) { return ; } @@ -81,13 +75,7 @@ export function Workspace() { useNativeTitlebar={settings.useNativeTitlebar} interfaceScale={settings.interfaceScale} > -
-
-
-
+ ); diff --git a/apps/yaak-client/components/WorkspaceSettingsDialog.test.tsx b/apps/yaak-client/components/WorkspaceSettingsDialog.test.tsx new file mode 100644 index 000000000..17a437d6c --- /dev/null +++ b/apps/yaak-client/components/WorkspaceSettingsDialog.test.tsx @@ -0,0 +1,177 @@ +// @vitest-environment happy-dom +import type { Workspace, WorkspaceMeta } from "@yaakapp-internal/models"; +import { workspaceMetasAtom } from "@yaakapp-internal/models"; +import { getDefaultStore, type PrimitiveAtom } from "jotai"; +import { act, type ReactNode } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; +import { WorkspaceSettingsDialog } from "./WorkspaceSettingsDialog"; + +const mocks = vi.hoisted(() => ({ + rpc: vi.fn<(cmd: string, payload: unknown) => Promise>(), + mergeModelsInStore: vi.fn(), + deleteModelWithConfirm: vi.fn<(model: unknown) => Promise>(), + workspace: { + id: "wk_test", + model: "workspace", + name: "Broken", + settingDnsOverrides: [], + } as unknown as Workspace, + workspaceMeta: { + id: "wm_test", + model: "workspace_meta", + workspaceId: "wk_test", + settingSyncDir: "/sync/broken", + encryptionKey: null, + } as WorkspaceMeta, +})); +const { workspace, workspaceMeta } = mocks; + +vi.mock("@yaakapp-internal/models", async () => { + const { atom } = await import("jotai"); + return { + workspacesAtom: atom([mocks.workspace]), + // Starts empty in each test: the workspace failed to load, so the store has no meta for it + workspaceMetasAtom: atom([]), + mergeModelsInStore: mocks.mergeModelsInStore, + patchModel: vi.fn(), + }; +}); +vi.mock("@yaakapp-internal/ui", () => ({ + Banner: ({ children }: { children: ReactNode }) =>
{children}
, + CountBadge: () => null, + HStack: ({ children }: { children: ReactNode }) =>
{children}
, + InlineCode: ({ children }: { children: ReactNode }) => {children}, +})); +vi.mock("../hooks/useAuthTab", () => ({ useAuthTab: () => [] })); +vi.mock("../hooks/useHeadersTab", () => ({ useHeadersTab: () => [] })); +vi.mock("../hooks/useInheritedHeaders", () => ({ useInheritedHeaders: () => [] })); +vi.mock("../lib/deleteModelWithConfirm", () => ({ + deleteModelWithConfirm: mocks.deleteModelWithConfirm, +})); +vi.mock("../lib/dialog", () => ({ showDialog: vi.fn() })); +vi.mock("../lib/router", () => ({ router: { navigate: vi.fn() } })); +vi.mock("../lib/rpc", () => ({ rpc: mocks.rpc })); +vi.mock("./CopyIconButton", () => ({ CopyIconButton: () => null })); +vi.mock("./core/Button", () => ({ + Button: ({ children, onClick }: { children: ReactNode; onClick: () => void }) => ( + + ), +})); +vi.mock("./core/PlainInput", () => ({ + PlainInput: ({ label, defaultValue }: { label: string; defaultValue: string }) => ( + + ), +})); +vi.mock("./core/SettingRow", () => ({ + SettingsList: ({ children }: { children: ReactNode }) =>
{children}
, + SettingsSection: ({ children }: { children: ReactNode }) =>
{children}
, +})); +// Render every tab at once so the test can see all of them +vi.mock("./core/Tabs/Tabs", () => ({ + Tabs: ({ children }: { children: ReactNode }) =>
{children}
, + TabContent: ({ children, value }: { children: ReactNode; value: string }) => ( +
{children}
+ ), +})); +vi.mock("./DnsOverridesEditor", () => ({ DnsOverridesEditor: () => null })); +vi.mock("./HeadersEditor", () => ({ HeadersEditor: () => null })); +vi.mock("./HttpAuthenticationEditor", () => ({ HttpAuthenticationEditor: () => null })); +vi.mock("./MarkdownEditor", () => ({ MarkdownEditor: () => null })); +vi.mock("./ModelSettingsEditor", () => ({ ModelSettingsEditor: () => null })); +vi.mock("./SyncToFilesystemSetting", () => ({ + SyncToFilesystemSetting: ({ value }: { value: { filePath: string | null } }) => ( +
{value.filePath}
+ ), +})); +vi.mock("./WorkspaceEncryptionSetting", () => ({ + WorkspaceEncryptionSetting: () =>
, +})); + +let root: Root; +let host: HTMLDivElement; +beforeEach(() => { + vi.clearAllMocks(); + // Behave like the real store: merged models land in the atom the dialog reads + const store = getDefaultStore(); + const metasAtom = workspaceMetasAtom as unknown as PrimitiveAtom; + store.set(metasAtom, []); + mocks.mergeModelsInStore.mockImplementation((_model: string, models: WorkspaceMeta[]) => + store.set(metasAtom, (prev) => [...prev, ...models]), + ); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +async function render() { + await act(async () => + root.render( {}} />), + ); +} + +function tab(value: string) { + const el = host.querySelector(`[data-tab="${value}"]`); + if (el == null) throw new Error(`No ${value} tab`); + return el; +} + +function deleteButton() { + return Array.from(host.querySelectorAll("button")).find( + (b) => b.textContent === "Delete Workspace", + ); +} + +test("a workspace with no meta in the store still offers Delete", async () => { + mocks.rpc.mockReturnValue(new Promise(() => {})); + mocks.deleteModelWithConfirm.mockResolvedValue(false); + await render(); + + expect(host.textContent).not.toContain("not found"); + const button = deleteButton(); + expect(button).toBeDefined(); + + await act(async () => button?.click()); + expect(mocks.deleteModelWithConfirm).toHaveBeenCalledWith(workspace, { confirmName: "Broken" }); +}); + +test("a missing meta is fetched, put in the store, and its settings rendered", async () => { + mocks.rpc.mockResolvedValue(workspaceMeta); + await render(); + + expect(mocks.rpc).toHaveBeenCalledWith("cmd_get_workspace_meta", { workspaceId: "wk_test" }); + expect(mocks.mergeModelsInStore).toHaveBeenCalledWith("workspace_meta", [workspaceMeta]); + + const settings = tab("settings"); + expect(settings.querySelector('[data-testid="sync-setting"]')?.textContent).toBe("/sync/broken"); + expect(settings.querySelector('[data-testid="encryption-setting"]')).not.toBeNull(); + expect(host.querySelector('[role="alert"]')).toBeNull(); +}); + +test("a meta that cannot be loaded shows the error only where sync and encryption go", async () => { + mocks.rpc.mockRejectedValue("database is locked"); + await render(); + + // The error is the one banner, inside the Settings tab, in place of sync and encryption + const banners = host.querySelectorAll('[role="alert"]'); + expect(banners).toHaveLength(1); + expect(tab("settings").contains(banners[0] ?? null)).toBe(true); + expect(banners[0]?.textContent).toContain("database is locked"); + expect(host.querySelector('[data-testid="sync-setting"]')).toBeNull(); + expect(host.querySelector('[data-testid="encryption-setting"]')).toBeNull(); + expect(mocks.mergeModelsInStore).not.toHaveBeenCalled(); + + // The workspace's own settings and Delete still render + const general = tab("general"); + expect(general.querySelector('input[aria-label="Name"]')?.value).toBe("Broken"); + expect(general.contains(deleteButton() ?? null)).toBe(true); +}); diff --git a/apps/yaak-client/components/WorkspaceSettingsDialog.tsx b/apps/yaak-client/components/WorkspaceSettingsDialog.tsx index a0cddc2af..b40763524 100644 --- a/apps/yaak-client/components/WorkspaceSettingsDialog.tsx +++ b/apps/yaak-client/components/WorkspaceSettingsDialog.tsx @@ -1,12 +1,20 @@ -import { patchModel, workspaceMetasAtom, workspacesAtom } from "@yaakapp-internal/models"; +import type { WorkspaceMeta } from "@yaakapp-internal/models"; +import { + mergeModelsInStore, + patchModel, + workspaceMetasAtom, + workspacesAtom, +} from "@yaakapp-internal/models"; import { Banner, HStack, InlineCode, CountBadge } from "@yaakapp-internal/ui"; import { useAtomValue } from "jotai"; +import { useEffect, useState } from "react"; import { useAuthTab } from "../hooks/useAuthTab"; import { useHeadersTab } from "../hooks/useHeadersTab"; import { useInheritedHeaders } from "../hooks/useInheritedHeaders"; import { deleteModelWithConfirm } from "../lib/deleteModelWithConfirm"; import { showDialog } from "../lib/dialog"; import { router } from "../lib/router"; +import { rpc } from "../lib/rpc"; import { CopyIconButton } from "./CopyIconButton"; import { Button } from "./core/Button"; import { PlainInput } from "./core/PlainInput"; @@ -47,6 +55,10 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) { const authTab = useAuthTab(TAB_AUTH, workspace ?? null); const headersTab = useHeadersTab(TAB_HEADERS, workspace ?? null); const inheritedHeaders = useInheritedHeaders(workspace ?? null); + const workspaceMetaError = useEnsureWorkspaceMeta( + workspaceId, + workspace != null && workspaceMeta == null, + ); if (workspace == null) { return ( @@ -56,13 +68,6 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) { ); } - if (workspaceMeta == null) - return ( - - WorkspaceMeta not found for workspace - - ); - return ( - patchModel(workspaceMeta, { settingSyncDir: filePath })} - /> -
- -
+ {workspaceMeta != null ? ( + <> + + patchModel(workspaceMeta, { settingSyncDir: filePath }) + } + /> +
+ +
+ + ) : workspaceMetaError != null ? ( + + Sync and encryption settings are unavailable because{" "} + WorkspaceMeta could not be loaded: {workspaceMetaError} + + ) : null}
@@ -177,6 +193,34 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) { ); } +/** + * The meta row normally reaches the store when the workspace loads, which also creates it if it + * is missing. If that load failed (for example on a corrupt row elsewhere in the workspace), the + * store never gets it, so ask for it directly. Returns the error if that fails too. + */ +function useEnsureWorkspaceMeta(workspaceId: string, missing: boolean): string | null { + const [error, setError] = useState(null); + + useEffect(() => { + if (!missing) return; + let cancelled = false; + setError(null); + rpc("cmd_get_workspace_meta", { workspaceId }).then( + (meta) => { + if (!cancelled) mergeModelsInStore("workspace_meta", [meta]); + }, + (err) => { + if (!cancelled) setError(String(err)); + }, + ); + return () => { + cancelled = true; + }; + }, [workspaceId, missing]); + + return error; +} + WorkspaceSettingsDialog.show = (workspaceId: string, tab?: WorkspaceSettingsTab) => { showDialog({ id: "workspace-settings", diff --git a/apps/yaak-client/components/core/Editor/filter/filter.grammar b/apps/yaak-client/components/core/Editor/filter/filter.grammar deleted file mode 100644 index dcf8b81ec..000000000 --- a/apps/yaak-client/components/core/Editor/filter/filter.grammar +++ /dev/null @@ -1,78 +0,0 @@ -@top Query { Expr } - -@skip { space+ } -@tokens { - space { $[ \t\r\n]+ } - - LParen { "(" } - RParen { ")" } - At { "@" } - Colon { ":" } - Not { "-" | "NOT" } - - // Keywords (case-insensitive) - And { "AND" } - Or { "OR" } - - // "quoted phrase" with simple escapes: \" and \\ - Phrase { '"' (!["\\] | "\\" _)* '"' } - - // Bare words run until filter syntax or whitespace. Leading '-' remains unary - // negation, but '-' may appear after the first character. - Word { ![ \t\r\n():"@-] ![ \t\r\n():"@]* } - FieldValueWord { ![ \t\r\n"] ![ \t\r\n]* } - - @precedence { Not, And, Or, Word } -} - -@detectDelim - -// Precedence: NOT (highest) > AND > OR (lowest) -// We also allow implicit AND in your parser/evaluator, but for highlighting, -// this grammar parses explicit AND/OR/NOT + adjacency as a sequence (Seq). -Expr { - OrExpr -} - -OrExpr { - AndExpr (Or AndExpr)* -} - -AndExpr { - Unary (And Unary | Unary)* // allow implicit AND by adjacency: Unary Unary -} - -Unary { - Not Unary -| Primary -} - -Primary { - Group -| Field -| Phrase -| Term -} - -Group { - LParen Expr RParen -} - -Field { - FieldName Colon FieldValue -} - -FieldName { - At? Word -} - -FieldValue { - Phrase -| FieldValueWord -} - -Term { - Word -} - -@external propSource highlight from "./highlight" diff --git a/apps/yaak-client/components/core/Editor/filter/filter.test.ts b/apps/yaak-client/components/core/Editor/filter/filter.test.ts deleted file mode 100644 index 6002175f6..000000000 --- a/apps/yaak-client/components/core/Editor/filter/filter.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, test } from "vite-plus/test"; -import { parser } from "./filter"; - -function getNodeNames(input: string): string[] { - const tree = parser.parse(input); - const nodes: string[] = []; - const cursor = tree.cursor(); - do { - if (cursor.name !== "Query") { - nodes.push(cursor.name); - } - } while (cursor.next()); - return nodes; -} - -describe("filter grammar", () => { - test("parses URL-like field values as one value", () => { - const nodes = getNodeNames("@url:yaak.app/foo-bar"); - - expect(nodes).not.toContain("⚠"); - expect(nodes).toContain("FieldValue"); - expect(nodes).toContain("FieldValueWord"); - }); - - test("parses punctuation-heavy field values as one value", () => { - const nodes = getNodeNames("@url:yaa$&#*@tsrna(*)"); - - expect(nodes).not.toContain("⚠"); - expect(nodes).toContain("FieldValue"); - expect(nodes).toContain("FieldValueWord"); - }); - - test("parses operator-looking field values as one value", () => { - const negativeValueNodes = getNodeNames("@url:-foo"); - const operatorWordNodes = getNodeNames("@url:AND"); - - expect(negativeValueNodes).not.toContain("⚠"); - expect(negativeValueNodes).toContain("FieldValueWord"); - expect(operatorWordNodes).not.toContain("⚠"); - expect(operatorWordNodes).toContain("FieldValueWord"); - }); -}); diff --git a/apps/yaak-client/components/core/Editor/filter/filter.ts b/apps/yaak-client/components/core/Editor/filter/filter.ts deleted file mode 100644 index 717a6daa4..000000000 --- a/apps/yaak-client/components/core/Editor/filter/filter.ts +++ /dev/null @@ -1,22 +0,0 @@ -// This file was generated by lezer-generator. You probably shouldn't edit it. -import {LRParser} from "@lezer/lr" -import {highlight} from "./highlight" -export const parser = LRParser.deserialize({ - version: 14, - states: "%WOVQPOOPhOPOOOVQPO'#CfOmQPO'#ChO!_QPO'#ChO!dQPO'#CgOOQO'#Cc'#CcOVQPO'#CaOOQO'#Ca'#CaO!iQPO'#C`O!yQPO'#C_OOQO'#C^'#C^QOQPOOPOOO'#Cr'#CrP#UOPO)C>lO#]QPO,59QOOQO,59S,59SO#bQQO,59ROOQO,58{,58{OVQPO'#CsOOQO'#Cs'#CsO#jQPO,58zOVQPO'#CtO#zQPO,58yPOOO-E6p-E6pOOQO1G.l1G.lOOQO'#Cl'#ClOOQO1G.m1G.mOOQO,59_,59_OOQO-E6q-E6qOOQO,59`,59`OOQO-E6r-E6r", - stateData: "$]~OkPQ~OUVOXQO]SO^ROaUO~Ok]O~OUcXXcX]cX^cX_[XacXdcXecXicXWcX~O^`O~O_aO~OdcOeSXiSXWSX~PVOefOiRXWRX~Ok]O~Qj]WiO~OajObjO~OdcOeSaiSaWSa~PVOefOiRaWRa~OUde^e~", - goto: "#^iPPjpt{P![PP!e!e!nPPP!wPP!ePP!z#Q#WQ[OR_QTZOQSYOQRnfUXOQfQbVSdXeRlc_WOQVXcef_UOQVXcef_TOQVXcefRkaQ^PRh^QeXRmeQgYRog", - nodeNames: "⚠ Query Expr OrExpr AndExpr Unary Not Primary RParen LParen Group Field FieldName At Word Colon FieldValue Phrase FieldValueWord Term And Or", - maxTerm: 27, - nodeProps: [ - ["openedBy", 8,"LParen"], - ["closedBy", 9,"RParen"] - ], - propSources: [highlight], - skippedNodes: [0,22], - repeatNodeCount: 3, - tokenData: "2h~RiOX!pXY$hYZ$hZ]!p]^$h^p!ppq$hqr!prs$ysx!pxy&gyz'Qz}!p}!O'k!O![!p![!](U!]!b!p!b!c(o!c!d)Y!d!p!p!p!q,q!q!r0Y!r;'S!p;'S;=`$b<%lO!pR!w^bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pQ#xUbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sQ$_P;=`<%l#sR$eP;=`<%l!p~$mSk~XY$hYZ$h]^$hpq$h~$|VOr$yrs%cs#O$y#O#P%h#P;'S$y;'S;=`&a<%lO$y~%hOa~~%kRO;'S$y;'S;=`%t;=`O$y~%wWOr$yrs%cs#O$y#O#P%h#P;'S$y;'S;=`&a;=`<%l$y<%lO$y~&dP;=`<%l$yR&nUbQXPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR'XUbQWPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR'rUbQUPOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR(]U_PbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR(vU]PbQOX#sZ]#s^p#sq;'S#s;'S;=`$[<%lO#sR)a`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!p!p!p!q*c!q;'S!p;'S;=`$b<%lO!pR*j`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!f!p!f!g+l!g;'S!p;'S;=`$b<%lO!pR+u^bQdP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pR,x`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!q!p!q!r-z!r;'S!p;'S;=`$b<%lO!pR.R`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!v!p!v!w/T!w;'S!p;'S;=`$b<%lO!pR/^^bQUP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!pR0a`bQ^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c!t!p!t!u1c!u;'S!p;'S;=`$b<%lO!pR1l^bQeP^POX!pZ]!p^p!pqr!prs#ssx!pxz#sz![!p![!]#s!]!b!p!b!c#s!c;'S!p;'S;=`$b<%lO!p", - tokenizers: [0, 1], - topRules: {"Query":[0,1]}, - tokenPrec: 145 -}) diff --git a/apps/yaak-client/components/core/Editor/filter/format.test.ts b/apps/yaak-client/components/core/Editor/filter/format.test.ts deleted file mode 100644 index 07ba7afe6..000000000 --- a/apps/yaak-client/components/core/Editor/filter/format.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, test } from "vite-plus/test"; -import { formatFieldFilter } from "./format"; -import { evaluate, parseQuery } from "./query"; - -function matchesFormattedUrl(value: string) { - return evaluate(parseQuery(formatFieldFilter("url", value)), { - fields: { url: value }, - }); -} - -describe("formatFieldFilter", () => { - test("keeps URL-like values bare", () => { - expect(formatFieldFilter("url", "yaak.app/foo-bar")).toBe("@url:yaak.app/foo-bar"); - expect(matchesFormattedUrl("yaak.app/foo-bar")).toBe(true); - }); - - test("keeps non-syntax punctuation bare", () => { - expect(formatFieldFilter("url", "yaa$&#*@tsrna(*)")).toBe("@url:yaa$&#*@tsrna(*)"); - expect(matchesFormattedUrl("yaa$&#*@tsrna(*)")).toBe(true); - }); - - test("keeps values that start with an operator token bare", () => { - expect(formatFieldFilter("url", "-foo")).toBe("@url:-foo"); - expect(matchesFormattedUrl("-foo")).toBe(true); - }); - - test("keeps boolean operator words bare", () => { - expect(formatFieldFilter("url", "AND")).toBe("@url:AND"); - expect(formatFieldFilter("url", "or")).toBe("@url:or"); - expect(formatFieldFilter("url", "Not")).toBe("@url:Not"); - expect(matchesFormattedUrl("AND")).toBe(true); - }); - - test("escapes quoted values", () => { - expect(formatFieldFilter("url", 'say "hi"')).toBe('@url:"say \\"hi\\""'); - expect(matchesFormattedUrl('say "hi"')).toBe(true); - }); - - test("quotes values that start with a quote", () => { - expect(formatFieldFilter("url", '"hi"')).toBe('@url:"\\"hi\\""'); - expect(matchesFormattedUrl('"hi"')).toBe(true); - }); -}); diff --git a/apps/yaak-client/components/core/Editor/filter/format.ts b/apps/yaak-client/components/core/Editor/filter/format.ts deleted file mode 100644 index f1fc7215e..000000000 --- a/apps/yaak-client/components/core/Editor/filter/format.ts +++ /dev/null @@ -1,7 +0,0 @@ -const bareFieldValue = /^[^\s"]\S*$/; - -export function formatFieldFilter(field: string, value: string) { - const escapedValue = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); - const filterValue = bareFieldValue.test(value) ? value : `"${escapedValue}"`; - return `@${field}:${filterValue}`; -} diff --git a/apps/yaak-client/components/core/Editor/filter/highlight.ts b/apps/yaak-client/components/core/Editor/filter/highlight.ts deleted file mode 100644 index 9c05d7267..000000000 --- a/apps/yaak-client/components/core/Editor/filter/highlight.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { styleTags, tags as t } from "@lezer/highlight"; - -export const highlight = styleTags({ - // Boolean operators - And: t.operatorKeyword, - Or: t.operatorKeyword, - Not: t.operatorKeyword, - - // Structural punctuation - LParen: t.paren, - RParen: t.paren, - Colon: t.punctuation, - Minus: t.operator, - - // Literals - Phrase: t.string, // "quoted string" - - // Fields - "FieldName/At": t.attributeName, - "FieldName/Word": t.attributeName, - "FieldValue/FieldValueWord": t.attributeValue, -}); diff --git a/apps/yaak-client/components/core/Editor/filter/query.ts b/apps/yaak-client/components/core/Editor/filter/query.ts deleted file mode 100644 index 12bf4a4bb..000000000 --- a/apps/yaak-client/components/core/Editor/filter/query.ts +++ /dev/null @@ -1,308 +0,0 @@ -// query.ts -// A tiny query language parser with NOT/AND/OR, parentheses, phrases, negation, and field:value. - -import { fuzzyMatch } from "fuzzbunny"; -///////////////////////// -// AST -///////////////////////// - -export type Ast = - | { type: "Term"; value: string } // foo - | { type: "Phrase"; value: string } // "hi there" - | { type: "Field"; field: string; value: string } // method:POST or title:"exact phrase" - | { type: "Not"; node: Ast } // -foo or NOT foo - | { type: "And"; left: Ast; right: Ast } // a AND b - | { type: "Or"; left: Ast; right: Ast }; // a OR b - -///////////////////////// -// Tokenizer -///////////////////////// -type Tok = - | { kind: "LPAREN" } - | { kind: "RPAREN" } - | { kind: "AND" } - | { kind: "OR" } - | { kind: "NOT" } // explicit NOT - | { kind: "MINUS" } // unary minus before term/phrase/paren group - | { kind: "COLON" } - | { kind: "WORD"; text: string } // bareword (unquoted) - | { kind: "PHRASE"; text: string } // "quoted phrase" - | { kind: "EOF" }; - -const isSpace = (c: string) => /\s/.test(c); -const isWordStart = (c: string) => c !== "" && !isSpace(c) && !/[():"@-]/.test(c); -const isWordChar = (c: string) => c !== "" && !isSpace(c) && !/[():"@]/.test(c); - -export function tokenize(input: string): Tok[] { - const toks: Tok[] = []; - let i = 0; - const n = input.length; - - const peek = () => input[i] ?? ""; - const advance = () => input[i++]; - - const readWord = () => { - let s = ""; - while (i < n && isWordChar(peek())) s += advance(); - return s; - }; - - const readFieldValue = () => { - let s = ""; - while (i < n && !isSpace(peek())) s += advance(); - return s; - }; - - const readPhrase = () => { - // assumes current char is opening quote - advance(); // consume opening " - let s = ""; - while (i < n) { - const c = advance(); - if (c === `"`) break; - if (c === "\\" && i < n) { - // escape \" and \\ (simple) - const next = advance(); - s += next; - } else { - s += c; - } - } - return s; - }; - - while (i < n) { - const c = peek(); - - if (isSpace(c)) { - i++; - continue; - } - - if (c === "(") { - toks.push({ kind: "LPAREN" }); - i++; - continue; - } - if (c === ")") { - toks.push({ kind: "RPAREN" }); - i++; - continue; - } - if (c === ":") { - toks.push({ kind: "COLON" }); - i++; - if (peek() && !isSpace(peek()) && peek() !== `"`) { - toks.push({ kind: "WORD", text: readFieldValue() }); - } - continue; - } - if (c === `"`) { - const text = readPhrase(); - toks.push({ kind: "PHRASE", text }); - continue; - } - if (c === "-") { - toks.push({ kind: "MINUS" }); - i++; - continue; - } - - // WORD / AND / OR / NOT - if (isWordStart(c)) { - const w = readWord(); - const upper = w.toUpperCase(); - if (upper === "AND") toks.push({ kind: "AND" }); - else if (upper === "OR") toks.push({ kind: "OR" }); - else if (upper === "NOT") toks.push({ kind: "NOT" }); - else toks.push({ kind: "WORD", text: w }); - continue; - } - - // Unknown char—skip to be forgiving - i++; - } - - toks.push({ kind: "EOF" }); - return toks; -} - -class Parser { - private i = 0; - constructor(private toks: Tok[]) {} - - private peek(): Tok { - return this.toks[this.i] ?? { kind: "EOF" }; - } - private advance(): Tok { - return this.toks[this.i++] ?? { kind: "EOF" }; - } - private at(kind: Tok["kind"]) { - return this.peek().kind === kind; - } - - // Top-level: parse OR-precedence chain, allowing implicit AND. - parse(): Ast | null { - if (this.at("EOF")) return null; - const expr = this.parseOr(); - if (!this.at("EOF")) { - // Optionally, consume remaining tokens or throw - } - return expr; - } - - // Precedence: NOT (highest), AND, OR (lowest) - private parseOr(): Ast { - let node = this.parseAnd(); - while (this.at("OR")) { - this.advance(); - const rhs = this.parseAnd(); - node = { type: "Or", left: node, right: rhs }; - } - return node; - } - - private parseAnd(): Ast { - let node = this.parseUnary(); - // Implicit AND: if next token starts a primary, treat as AND. - while (this.at("AND") || this.startsPrimary()) { - if (this.at("AND")) this.advance(); - const rhs = this.parseUnary(); - node = { type: "And", left: node, right: rhs }; - } - return node; - } - - private parseUnary(): Ast { - if (this.at("NOT") || this.at("MINUS")) { - this.advance(); - const node = this.parseUnary(); - return { type: "Not", node }; - } - return this.parsePrimaryOrField(); - } - - private startsPrimary(): boolean { - const k = this.peek().kind; - return k === "WORD" || k === "PHRASE" || k === "LPAREN" || k === "MINUS" || k === "NOT"; - } - - private parsePrimaryOrField(): Ast { - // Parenthesized group - if (this.at("LPAREN")) { - this.advance(); - const inside = this.parseOr(); - // if (!this.at('RPAREN')) throw new Error("Missing closing ')'"); - this.advance(); - return inside; - } - - // Phrase - if (this.at("PHRASE")) { - const t = this.advance() as Extract; - return { type: "Phrase", value: t.text }; - } - - // Field or bare word - if (this.at("WORD")) { - const wordTok = this.advance() as Extract; - - if (this.at("COLON")) { - // field:value or field:"phrase" - this.advance(); // : - let value: string; - if (this.at("PHRASE")) { - const p = this.advance() as Extract; - value = p.text; - } else if (this.at("WORD")) { - const w = this.advance() as Extract; - value = w.text; - } else { - // Anything else after colon is treated literally as a single Term token. - const t = this.advance(); - value = tokText(t); - } - return { type: "Field", field: wordTok.text, value }; - } - - // plain term - return { type: "Term", value: wordTok.text }; - } - - const w = this.advance() as Extract; - return { type: "Phrase", value: "text" in w ? w.text : "" }; - } -} - -function tokText(t: Tok): string { - if ("text" in t) return t.text; - - switch (t.kind) { - case "COLON": - return ":"; - case "LPAREN": - return "("; - case "RPAREN": - return ")"; - default: - return ""; - } -} - -export function parseQuery(q: string): Ast | null { - if (q.trim() === "") return null; - const toks = tokenize(q); - const parser = new Parser(toks); - return parser.parse(); -} - -export type Doc = { - text?: string; - fields?: Record; -}; - -type Technique = "substring" | "fuzzy" | "strict"; - -function includes(hay: string | undefined, needle: string, technique: Technique): boolean { - if (!hay || !needle) return false; - if (technique === "strict") return hay === needle; - if (technique === "fuzzy") return !!fuzzyMatch(hay, needle); - return hay.indexOf(needle) !== -1; -} - -export function evaluate(ast: Ast | null, doc: Doc): boolean { - if (!ast) return true; // Match everything if no query is provided - - const text = (doc.text ?? "").toLowerCase(); - const fieldsNorm: Record = {}; - - for (const [k, v] of Object.entries(doc.fields ?? {})) { - if (!(typeof v === "string" || Array.isArray(v))) continue; - fieldsNorm[k.toLowerCase()] = Array.isArray(v) - ? v.filter((v) => typeof v === "string").map((s) => s.toLowerCase()) - : [String(v ?? "").toLowerCase()]; - } - - const evalNode = (node: Ast): boolean => { - switch (node.type) { - case "Term": - return includes(text, node.value.toLowerCase(), "fuzzy"); - case "Phrase": - // Quoted phrases match exactly - return includes(text, node.value.toLowerCase(), "substring"); - case "Field": { - const vals = fieldsNorm[node.field.toLowerCase()] ?? []; - if (vals.length === 0) return false; - return vals.some((v) => includes(v, node.value.toLowerCase(), "substring")); - } - case "Not": - return !evalNode(node.node); - case "And": - return evalNode(node.left) && evalNode(node.right); - case "Or": - return evalNode(node.left) || evalNode(node.right); - } - }; - - return evalNode(ast); -} diff --git a/apps/yaak-client/components/core/EventViewer.tsx b/apps/yaak-client/components/core/EventViewer.tsx index 77ecfc95f..7d7f5f2a7 100644 --- a/apps/yaak-client/components/core/EventViewer.tsx +++ b/apps/yaak-client/components/core/EventViewer.tsx @@ -1,312 +1,2 @@ -import type { Virtualizer } from "@tanstack/react-virtual"; -import { Banner, HStack, SplitLayout } from "@yaakapp-internal/ui"; -import classNames from "classnames"; -import { format } from "date-fns"; -import type { ReactNode } from "react"; -import { useCallback, useMemo, useRef, useState } from "react"; -import { useEventViewerKeyboard } from "../../hooks/useEventViewerKeyboard"; -import { CopyIconButton } from "../CopyIconButton"; -import { AutoScroller } from "./AutoScroller"; -import { Button } from "./Button"; -import { IconButton } from "./IconButton"; -import type { SelectProps } from "./Select"; -import { Select } from "./Select"; -import { Separator } from "./Separator"; - -interface EventViewerProps { - /** Array of events to display */ - events: T[]; - - /** Get unique key for each event */ - getEventKey: (event: T, index: number) => string; - - /** Render the event row - receives event, index, isActive, and onClick */ - renderRow: (props: { - event: T; - index: number; - isActive: boolean; - onClick: () => void; - }) => ReactNode; - - /** Render the detail pane for the selected event */ - renderDetail?: (props: { event: T; index: number; onClose: () => void }) => ReactNode; - - /** Optional header above the event list (e.g., connection status) */ - header?: ReactNode; - - /** Error message to display as a banner */ - error?: string | null; - - /** Key for SplitLayout state persistence */ - splitLayoutStorageKey: string; - - /** Default ratio for the split (0.0 - 1.0) */ - defaultRatio?: number; - - /** Enable keyboard navigation (arrow keys) */ - enableKeyboardNav?: boolean; - - /** Loading state */ - isLoading?: boolean; - - /** Message to show while loading */ - loadingMessage?: string; - - /** Message to show when no events */ - emptyMessage?: string; - - /** Callback when active index changes (for controlled state in parent) */ - onActiveIndexChange?: (index: number | null) => void; -} - -export function EventViewer({ - events, - getEventKey, - renderRow, - renderDetail, - header, - error, - splitLayoutStorageKey, - defaultRatio = 0.4, - enableKeyboardNav = true, - isLoading = false, - loadingMessage = "Loading events...", - emptyMessage = "No events recorded", - onActiveIndexChange, -}: EventViewerProps) { - const [activeIndex, setActiveIndexInternal] = useState(null); - const [isPanelOpen, setIsPanelOpen] = useState(false); - - // Wrap setActiveIndex to notify parent - const setActiveIndex = useCallback( - (indexOrUpdater: number | null | ((prev: number | null) => number | null)) => { - setActiveIndexInternal((prev) => { - const newIndex = - typeof indexOrUpdater === "function" ? indexOrUpdater(prev) : indexOrUpdater; - onActiveIndexChange?.(newIndex); - return newIndex; - }); - }, - [onActiveIndexChange], - ); - const containerRef = useRef(null); - const virtualizerRef = useRef | null>(null); - - const activeEvent = useMemo( - () => (activeIndex != null ? events[activeIndex] : null), - [activeIndex, events], - ); - - // Check if the event list container is focused - const isContainerFocused = useCallback(() => { - return containerRef.current?.contains(document.activeElement) ?? false; - }, []); - - // Keyboard navigation - useEventViewerKeyboard({ - totalCount: events.length, - activeIndex, - setActiveIndex, - virtualizer: virtualizerRef.current, - isContainerFocused, - enabled: enableKeyboardNav, - closePanel: () => setIsPanelOpen(false), - openPanel: () => setIsPanelOpen(true), - }); - - // Handle virtualizer ready callback - const handleVirtualizerReady = useCallback( - (virtualizer: Virtualizer) => { - virtualizerRef.current = virtualizer; - }, - [], - ); - - // Handle row click - select and open panel, scroll into view - const handleRowClick = useCallback( - (index: number) => { - setActiveIndex(index); - setIsPanelOpen(true); - // Scroll to ensure selected item is visible after panel opens - requestAnimationFrame(() => { - virtualizerRef.current?.scrollToIndex(index, { align: "auto" }); - }); - }, - [setActiveIndex], - ); - - const handleClose = useCallback(() => { - setIsPanelOpen(false); - }, []); - - if (isLoading) { - return
{loadingMessage}
; - } - - if (events.length === 0 && !error) { - return
{emptyMessage}
; - } - - return ( -
- ( -
- {header ?? } - - {error} - - ) - } - render={(event, index) => ( -
- {renderRow({ - event, - index, - isActive: index === activeIndex, - onClick: () => handleRowClick(index), - })} -
- )} - /> -
- )} - secondSlot={ - activeEvent != null && renderDetail && isPanelOpen - ? ({ style }) => ( -
-
- -
-
- {renderDetail({ - event: activeEvent, - index: activeIndex ?? 0, - onClose: handleClose, - })} -
-
- ) - : null - } - /> -
- ); -} - -export type EventDetailAction = - | { - type?: "button"; - /** Unique key for React */ - key: string; - /** Button label */ - label: string; - /** Optional icon */ - icon?: ReactNode; - /** Click handler */ - onClick: () => void; - } - | { - type: "select"; - /** Unique key for React */ - key: string; - /** Select label */ - label: string; - /** Selected value */ - value: string; - /** Select options */ - options: SelectProps["options"]; - /** Change handler */ - onChange: (value: string) => void; - }; - -interface EventDetailHeaderProps { - title: string; - prefix?: ReactNode; - timestamp?: string; - actions?: EventDetailAction[]; - copyText?: string | (() => Promise); - onClose?: () => void; -} - -export function EventDetailHeader({ - title, - prefix, - timestamp, - actions, - copyText, - onClose, -}: EventDetailHeaderProps) { - const formattedTime = timestamp ? format(new Date(`${timestamp}Z`), "HH:mm:ss.SSS") : null; - - return ( -
- - {prefix} -

{title}

-
- - {actions?.map((action) => - action.type === "select" ? ( -
- handleChange(e.target.value as T)} - onFocus={() => setFocused(true)} - onBlur={() => setFocused(false)} - disabled={disabled} - className={classNames( - "pr-7 w-full outline-hidden bg-transparent disabled:opacity-disabled", - "leading-none rounded-none", // Center the text better vertically - )} - > - {isInvalidSelection && } - {options.map((o) => { - if (o.type === "separator") return null; - return ( - - ); - })} - - - ) : ( - // Use custom "select" component until Tauri can be configured to have select menus not always appear in - // light mode - - o.type === "separator" || o.value !== defaultValue - ? o - : { ...o, label: <>{o.label} (default) }, - )} - > - - - )} -
- ); -} - -const selectBackgroundStyles: CSSProperties = { - backgroundImage: `url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e")`, - backgroundPosition: "right 0.3rem center", - backgroundRepeat: "no-repeat", - backgroundSize: "1.5em 1.5em", - appearance: "none", - printColorAdjust: "exact", -}; +export type { SelectProps } from "@yaakapp-internal/ui"; +export { Select } from "@yaakapp-internal/ui"; diff --git a/apps/yaak-client/components/core/SettingRow.tsx b/apps/yaak-client/components/core/SettingRow.tsx index a3c6f6c63..d912d04d3 100644 --- a/apps/yaak-client/components/core/SettingRow.tsx +++ b/apps/yaak-client/components/core/SettingRow.tsx @@ -1,260 +1,36 @@ import type { AnyModel } from "@yaakapp-internal/models"; import { patchModel } from "@yaakapp-internal/models"; -import { Icon } from "@yaakapp-internal/ui"; -import classNames from "classnames"; -import type { ReactNode } from "react"; -import { CopyIconButton } from "../CopyIconButton"; -import { Checkbox } from "./Checkbox"; -import { IconButton, type IconButtonProps } from "./IconButton"; -import { PlainInput } from "./PlainInput"; -import type { RadioDropdownItem } from "./RadioDropdown"; -import { Select } from "./Select"; +import { + SettingRow, + type SettingRowBaseProps, + SettingRowBoolean, + SettingRowNumber, + SettingRowSelect, + SettingRowText, + SettingSelectControl, +} from "@yaakapp-internal/ui"; import { SelectFile } from "../SelectFile"; +export type { SettingRowBaseProps, SettingSnippetLanguage } from "@yaakapp-internal/ui"; +export { + SettingCommand, + SettingOverrideRow, + SettingRow, + SettingRowBoolean, + SettingRowNumber, + SettingRowSelect, + SettingRowText, + SettingSelectControl, + SettingSnippet, + SettingsList, + SettingsSection, + SettingValue, +} from "@yaakapp-internal/ui"; + type ModelKeyOfValue = { [K in keyof T]-?: T[K] extends V ? K : never; }[keyof T]; -type SettingRowBaseProps = { - className?: string; - controlClassName?: string; - description?: ReactNode; - disabled?: boolean; - title: ReactNode; -}; - -export function SettingsList({ children, className }: { children: ReactNode; className?: string }) { - return
{children}
; -} - -export function SettingsSection({ - children, - className, - description, - title, -}: { - children: ReactNode; - className?: string; - description?: ReactNode; - title: ReactNode | null; -}) { - const showHeader = title != null || description != null; - - return ( -
- {showHeader && ( -
- {title != null &&
{title}
} - {description != null &&

{description}

} -
- )} -
{children}
-
- ); -} - -export function SettingRow({ - children, - className, - controlClassName, - description, - disabled, - title, -}: { - children: ReactNode; -} & SettingRowBaseProps) { - return ( -
-
-
-
{title}
- {description != null && ( -
{description}
- )} -
-
- {children} -
-
-
- ); -} - -export function SettingValue({ - actions, - className, - copyText, - enableCopy = true, - value, -}: { - actions?: SettingValueAction[]; - className?: string; - copyText?: string; - enableCopy?: boolean; - value: ReactNode; -}) { - const textValue = typeof value === "string" || typeof value === "number" ? `${value}` : null; - const textToCopy = copyText ?? textValue; - - return ( - <> - - {value} - - {actions?.map((action) => ( - - ))} - {enableCopy && textToCopy != null && ( - - )} - - ); -} - -/** - * A command or config to copy, set as a block: its title, an optional line - * saying which file it goes in, then the snippet at full width with the copy - * button on it. One-line shell commands and multi-line JSON get the same block. - */ -export function SettingCommand({ - className, - description, - disabled, - done, - language, - snippet, - title, -}: { - description?: ReactNode; - disabled?: boolean; - /** A short word shown with a check beside the title once the step is detected as done */ - done?: ReactNode; - language: SettingSnippetLanguage; - snippet: string; - title: ReactNode; -} & Pick) { - return ( -
-
- {title} - {done != null && done !== false && ( - - - {done} - - )} -
- {description != null && ( -
{description}
- )} - -
- ); -} - -export type SettingSnippetLanguage = "shell" | "json" | "text"; - -/** The snippet half of a `SettingCommand`, for places with their own title, like a banner. */ -export function SettingSnippet({ - className, - language, - snippet, -}: { - className?: string; - language: SettingSnippetLanguage; - snippet: string; -}) { - const prompt = language === "shell"; - - return ( -
-
- - {prompt && ( - - $ - - )} - {snippet} - -
- -
- ); -} - -type SettingValueAction = { - icon: IconButtonProps["icon"]; - onClick: () => void; - title: string; -}; - -export function SettingRowBoolean({ - checked, - checkboxSize = "md", - onChange, - title, - ...props -}: { - checked: boolean; - checkboxSize?: "sm" | "md"; - onChange: (checked: boolean) => void; -} & SettingRowBaseProps) { - return ( - - - - ); -} - export function ModelSettingRowBoolean>({ model, modelKey, @@ -272,50 +48,6 @@ export function ModelSettingRowBoolean void; - placeholder?: string; - required?: boolean; - type?: "number"; - validate?: (value: string) => boolean; - value: number; -} & SettingRowBaseProps) { - return ( - - onChange(Number.parseInt(value, 10) || 0)} - type={type} - className={inputClassName} - containerClassName={inputWidthClassName} - disabled={props.disabled} - /> - - ); -} - export function ModelSettingRowNumber>({ model, modelKey, @@ -334,47 +66,6 @@ export function ModelSettingRowNumber void; - placeholder?: string; - required?: boolean; - type?: "text" | "password"; - value: string; -} & SettingRowBaseProps) { - return ( - - - - ); -} - export function ModelSettingRowText>({ model, modelKey, @@ -438,74 +129,6 @@ export function SettingRowDirectory({ return ; } -export function SettingRowSelect({ - defaultValue, - name, - onChange, - options, - selectClassName = "w-48!", - title, - value, - ...props -}: { - defaultValue?: T; - name: string; - onChange: (value: T) => void; - options: RadioDropdownItem[]; - selectClassName?: string; - value: T; -} & SettingRowBaseProps) { - return ( - - - - ); -} - -export function SettingSelectControl({ - defaultValue, - disabled, - label, - name, - onChange, - options, - selectClassName = "w-48!", - value, -}: { - defaultValue?: T; - disabled?: boolean; - label: string; - name: string; - onChange: (value: T) => void; - options: RadioDropdownItem[]; - selectClassName?: string; - value: T; -}) { - return ( - } + setRef={(h) => { + handleRef.current = h; + }} + label="Field" + autoFocus + className="font-mono text-xs" + stateKey={null} + language={null} + placeholder="@header.x-request-id" + defaultValue="" + onChange={setText} + validate={problem == null} + extensions={extensions} + onKeyDown={(e) => { + if (e.key === "Enter" && !e.defaultPrevented) { + e.preventDefault(); + submit(); + } + }} + /> +
{problem}
+ + + + ); +} diff --git a/apps/yaak-proxy/components/AppIcon.tsx b/apps/yaak-proxy/components/AppIcon.tsx index e132ee021..c90b0a824 100644 --- a/apps/yaak-proxy/components/AppIcon.tsx +++ b/apps/yaak-proxy/components/AppIcon.tsx @@ -24,8 +24,8 @@ function loadIcon(path: string): Promise { return promise; } -/** An app's icon, read once per path for the whole session */ -export function AppIcon({ path, className }: { path: string; className?: string }) { +/** An app's icon, read once per path for the whole session; `className` sets its size */ +export function AppIcon({ path, className = "size-4" }: { path: string; className?: string }) { const [url, setUrl] = useState(() => icons.get(path)); useEffect(() => { if (icons.has(path)) { @@ -42,8 +42,8 @@ export function AppIcon({ path, className }: { path: string; className?: string }, [path]); return url == null ? ( - + ) : ( - + ); } diff --git a/apps/yaak-proxy/components/ClearFlowsButton.tsx b/apps/yaak-proxy/components/ClearFlowsButton.tsx index eb7cbdf25..5e83dbffb 100644 --- a/apps/yaak-proxy/components/ClearFlowsButton.tsx +++ b/apps/yaak-proxy/components/ClearFlowsButton.tsx @@ -1,49 +1,119 @@ -import { Dropdown, type DropdownItem, IconButton } from "@yaakapp-internal/ui"; -import { useAtomValue } from "jotai"; -import { useRpcMutation } from "../hooks/useRpcMutation"; -import { flowTotalAtom } from "../lib/store"; +import { + Checkbox, + Dialog, + DialogFooter, + IconButton, + useFormattedHotkey, + useHotKey, +} from "@yaakapp-internal/ui"; +import { useAtom, useAtomValue, useSetAtom } from "jotai"; +import { type FormEvent, useCallback, useId, useState } from "react"; +import { clearFlowsAction, confirmClearFlowsAtom } from "../lib/clearFlows"; +import { clearFlowsAtom, flowTotalAtom, lockedAtom } from "../lib/store"; +import { useShowToast } from "../lib/toast"; -/** Deletes every flow, once confirmed in its menu, which its hotkey opens too */ +/** + * Clears every flow, from its button or hotkey, once confirmed in a dialog unless "Don't ask + * again" was checked there. The list empties at once; the flows are deleted in the background. + * Disabled with none to clear, or while captured traffic is locked. + */ export function ClearFlowsButton() { const total = useAtomValue(flowTotalAtom); - const clear = useRpcMutation("clear_flows"); + const locked = useAtomValue(lockedAtom); + const [confirm, setConfirm] = useAtom(confirmClearFlowsAtom); + const clearFlows = useSetAtom(clearFlowsAtom); + const showToast = useShowToast(); + const [confirming, setConfirming] = useState(false); + const action = clearFlowsAction({ total, locked: locked != null, confirm }); + const hotkey = useFormattedHotkey("flows_clear")?.join(""); - const items: DropdownItem[] = [ - { - type: "content", - label: ( -
-
- {total === 1 ? "Clear 1 flow?" : `Clear all ${total} flows?`} -
-
- {clear.error != null ? ( - {clear.error.message} - ) : ( - "They are deleted from disk with their bodies, for good." - )} -
-
- ), - }, - { type: "separator" }, - { - label: "Clear", - icon: "trash", - color: "danger", - onSelect: () => clear.mutate({}), - }, - ]; + const clear = useCallback(() => { + clearFlows().catch((err: unknown) => { + const message = (err as { message?: unknown } | null)?.message; + showToast({ message: typeof message === "string" ? message : String(err), color: "danger" }); + }); + }, [clearFlows, showToast]); + + const start = useCallback(() => { + if (action === "confirm") setConfirming(true); + else if (action === "clear") clear(); + }, [action, clear]); + + // Bound even when disabled, so the key never falls through to the backend's clear unasked + useHotKey("flows_clear", start); return ( - + <> - + setConfirming(false)} + size="sm" + title="Clear traffic?" + > + {confirming && ( + setConfirming(false)} + onClear={(dontAskAgain) => { + setConfirming(false); + if (dontAskAgain) setConfirm(false); + clear(); + }} + /> + )} + + + ); +} + +function ConfirmClear({ + total, + onCancel, + onClear, +}: { + total: number; + onCancel: () => void; + onClear: (dontAskAgain: boolean) => void; +}) { + const formId = useId(); + const [dontAskAgain, setDontAskAgain] = useState(false); + const handleSubmit = (e: FormEvent) => { + e.preventDefault(); + onClear(dontAskAgain); + }; + return ( +
+

+ {total === 1 + ? "1 flow will be removed." + : `${total.toLocaleString()} flows will be removed.`} +

+ + + ); } diff --git a/apps/yaak-proxy/components/DecryptListEditor.tsx b/apps/yaak-proxy/components/DecryptListEditor.tsx new file mode 100644 index 000000000..779b4d323 --- /dev/null +++ b/apps/yaak-proxy/components/DecryptListEditor.tsx @@ -0,0 +1,171 @@ +import { Prec } from "@codemirror/state"; +import { type EditorView, keymap } from "@codemirror/view"; +import type { DecryptListEntry, SeenTargets } from "@yaakapp-internal/proxy-lib"; +import { CONTROL_TOOLTIP_DELAY, Icon, IconButton, Input, Tooltip } from "@yaakapp-internal/ui"; +import { filterAutocomplete } from "@yaakapp-internal/ui/editor"; +import classNames from "classnames"; +import { useMemo, useRef, useState } from "react"; +import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList"; +import { useRpcQuery } from "../hooks/useRpcQuery"; +import { decryptFilterOptions, entryLabel, normalizeEntry } from "../lib/decrypt"; + +/** + * What HTTPS is decrypted: one row per entry, the user's in order and then the built-in + * exclusions, each removable, and an input that adds one, suggesting `host:`, `app:` and `!`, + * then the hosts and apps seen in the capture. Saves as it changes. Placed by Settings' Proxy + * tab. + */ +export function DecryptListEditor({ className }: { className?: string }) { + const list = useDecryptList(); + const save = useEditDecryptList(); + // Read when the input opens its suggestions, so new traffic shows without rebuilding it. + const seen = useRpcQuery("list_seen", {}, { staleTime: 0, refetchOnMount: "always" }); + const seenRef = useRef(seen.data); + seenRef.current = seen.data; + + // Each change replaces the whole list, so one waits for the last to land rather than undo it. + const remove = (entry: string) => { + if (save.isPending) return; + save.mutate({ add: [], remove: [entry] }); + }; + + return ( +
+ save.mutate({ add: [entry], remove: [] })} + /> +
+ {list.length === 0 && ( +
Nothing decrypted
+ )} + {list.map((e) => ( + remove(e.entry)} + /> + ))} +
+
+ ); +} + +function EntryRow({ + entry, + disabled, + onRemove, +}: { + entry: DecryptListEntry; + disabled: boolean; + onRemove: () => void; +}) { + const negated = entry.entry.startsWith("!"); + return ( +
+ + + + + {entryLabel(entry.entry)} + + {entry.builtIn && ( + + + built-in + + + )} + +
+ ); +} + +/** The input that adds an entry on Enter, once the suggestions are closed or none is picked */ +function EntryInput({ + seenRef, + list, + disabled, + onAdd, +}: { + seenRef: React.RefObject; + list: DecryptListEntry[]; + /** A change is being saved; Enter waits for it, keeping what was typed */ + disabled: boolean; + onAdd: (entry: string) => void; +}) { + const [error, setError] = useState(null); + const onAddRef = useRef(onAdd); + onAddRef.current = onAdd; + const listRef = useRef(list); + listRef.current = list; + const disabledRef = useRef(disabled); + disabledRef.current = disabled; + + const extensions = useMemo(() => { + const options = decryptFilterOptions(null); + // The suggestions read the capture as they open, not as the input was made. + for (const field of options.fields ?? []) { + field.values = () => { + const fresh = decryptFilterOptions(seenRef.current).fields ?? []; + const values = fresh.find((f) => f.name === field.name)?.values; + return Array.isArray(values) ? values : []; + }; + } + const add = (view: EditorView) => { + const text = view.state.doc.toString(); + if (text.trim() === "") return false; + if (disabledRef.current) return true; + const entry = normalizeEntry(text); + if (entry == null) { + setError("Not a host or app"); + return true; + } + setError(null); + if (!listRef.current.some((e) => e.entry === entry)) onAddRef.current(entry); + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "" } }); + return true; + }; + // Low, so Enter picks a suggestion while they are open. + return [filterAutocomplete(options), Prec.low(keymap.of([{ key: "Enter", run: add }]))]; + }, [seenRef]); + + return ( + +
+ setError(null)} + /> + {error != null &&
{error}
} +
+
+ ); +} diff --git a/apps/yaak-proxy/components/FirstRun.tsx b/apps/yaak-proxy/components/FirstRun.tsx index 987bb07b4..f6efbc927 100644 --- a/apps/yaak-proxy/components/FirstRun.tsx +++ b/apps/yaak-proxy/components/FirstRun.tsx @@ -1,8 +1,19 @@ -import { Button, Icon, LoadingIcon } from "@yaakapp-internal/ui"; +import { + Button, + CONTROL_TOOLTIP_DELAY, + Icon, + InlineCode, + LoadingIcon, + Tooltip, +} from "@yaakapp-internal/ui"; import classNames from "classnames"; import { useAtomValue } from "jotai"; import type { ReactNode } from "react"; +import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList"; import { useRpcMutation } from "../hooks/useRpcMutation"; +import { everythingEdit } from "../lib/decrypt"; +import { decryptStep } from "../lib/firstRun"; +import { encryptingPercent } from "../lib/encrypting"; import { proxyStateAtom } from "../lib/store"; import { useCopyEnvironment, useProxySetup, useSystemProxySwitch } from "./ProxyStatus"; @@ -10,7 +21,7 @@ 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 + * choose what to decrypt, 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() { @@ -21,6 +32,8 @@ export function FirstRun() { const execute = useRpcMutation("execute_action"); const retry = useRpcMutation("take_over"); const copyEnvironment = useCopyEnvironment(); + const decryptList = useDecryptList(); + const saveDecryptList = useEditDecryptList(); const running = proxyState?.state === "running"; // Changed only by the process that owns the engine, so not from here while the CLI does. @@ -46,16 +59,21 @@ export function FirstRun() { : trusted ? "next" : "todo"; + const decrypt = decryptStep(decryptList, trusted); + const everything = decrypt.choice === "everything"; + const setEverything = (on: boolean) => saveDecryptList.mutate(everythingEdit(on)); const ready = trusted && (systemOn || !systemSupported); - const trafficState: StepState = !running && !otherOwner ? "fail" : ready ? "wait" : "todo"; + const encrypting = !running && !otherOwner ? encryptingPercent(proxyState) : null; + const trafficState: StepState = + encrypting != null ? "wait" : !running && !otherOwner ? "fail" : ready ? "wait" : "todo"; return (
Set up Yaak Proxy
- Three steps, once. Afterwards every app on this Mac sends its traffic here, and HTTPS - reads as plain text. + {systemSupported ? "Four" : "Three"} steps, once. Then every app on this Mac sends its + traffic here.
trust.mutate({})} > - {trustState === "fail" ? "Try again" : "Trust certificate"} + {trustState === "fail" ? "Try Again" : "Trust Certificate"} ) : null } @@ -104,7 +122,7 @@ export function FirstRun() { color={systemState === "fail" ? "default" : "primary"} onClick={() => setSystemProxy.mutate({ enabled: true })} > - {systemState === "fail" ? "Try again" : "Turn on"} + {systemState === "fail" ? "Try Again" : "Turn On"} ) : null } @@ -112,10 +130,60 @@ export function FirstRun() { )} + Everything + + ) : ( + + Pick as they appear + + ) + } + action={ + everything ? ( + + ) : ( + + ) + } + /> + execute.mutate({ scope: "global", action: "recording_toggle" })} > - Resume recording + Resume Recording ) : null } @@ -154,9 +222,17 @@ export function FirstRun() { leftSlot={} onClick={() => void copyEnvironment()} > - Copy environment + Copy Environment
+
+ Working with an agent? yaak mcp gives it the proxy's flows and + actions. +
+
+ Captured traffic is encrypted on disk with a key kept in your keychain, so macOS may ask + to let Yaak Proxy use it. +
); diff --git a/apps/yaak-proxy/components/FlowBodyViewer.test.tsx b/apps/yaak-proxy/components/FlowBodyViewer.test.tsx new file mode 100644 index 000000000..f7b9f63da --- /dev/null +++ b/apps/yaak-proxy/components/FlowBodyViewer.test.tsx @@ -0,0 +1,80 @@ +import { describe, expect, test, vi } from "vite-plus/test"; +import { flowPrettyView, shownViewMode } from "./FlowBodyViewer"; + +// The package's index reaches for the window as it loads; the view rule is all this needs. +vi.mock("@yaakapp-internal/ui", async () => { + const { prettyViewFor } = await vi.importActual< + typeof import("../../../packages/ui/src/components/http/BodyViewModeSwitch") + >("../../../packages/ui/src/components/http/BodyViewModeSwitch"); + return { prettyViewFor, LARGE_BODY_BYTES: 2_000_000 }; +}); + +const text = (mime: string, language: string | null, which: "request" | "response" = "response") => + flowPrettyView({ + which, + mime, + text: "x", + binary: false, + language: language as never, + hasForm: false, + }); + +describe("flowPrettyView", () => { + test("names the formatted view per format, the same on both halves", () => { + for (const which of ["request", "response"] as const) { + expect(text("application/json", "json", which)).toBe("formatted"); + expect(text("text/csv", "text", which)).toBe("table"); + expect(text("image/svg+xml", "xml", which)).toBe("preview"); + } + expect(text("text/plain", "text")).toBeNull(); + }); + + test("HTML previews as a response and formats as a request", () => { + expect(text("text/html", "html", "response")).toBe("preview"); + expect(text("text/html", "html", "request")).toBe("formatted"); + }); + + test("multipart has parts whether or not it reads as text", () => { + const base = { which: "request" as const, mime: "multipart/form-data", language: null }; + expect(flowPrettyView({ ...base, text: null, binary: false, hasForm: false })).toBe("parts"); + }); + + test("a URL-encoded form's fields are its formatted view, where the tab has them", () => { + const base = { + which: "request" as const, + mime: "application/x-www-form-urlencoded", + text: "a=1", + binary: false, + language: "text" as const, + }; + expect(flowPrettyView({ ...base, hasForm: true })).toBe("form"); + expect(flowPrettyView({ ...base, hasForm: false })).toBeNull(); + }); + + test("images, binary and undecodable bodies have one view", () => { + const base = { which: "response" as const, language: null, hasForm: false }; + expect(flowPrettyView({ ...base, mime: "image/png", text: null, binary: true })).toBeNull(); + expect( + flowPrettyView({ ...base, mime: "application/json", text: null, binary: true }), + ).toBeNull(); + expect( + flowPrettyView({ ...base, mime: "application/octet-stream", text: null, binary: false }), + ).toBeNull(); + }); +}); + +describe("shownViewMode", () => { + test("follows the preference", () => { + expect(shownViewMode({ key: "a", large: false, preferred: "pretty", chosen: null })).toBe( + "pretty", + ); + expect(shownViewMode({ key: "a", large: false, preferred: "raw", chosen: null })).toBe("raw"); + }); + + test("a large body opens raw, and formats once asked, for that body alone", () => { + expect(shownViewMode({ key: "a", large: true, preferred: "pretty", chosen: null })).toBe("raw"); + const chosen = { key: "a", mode: "pretty" as const }; + expect(shownViewMode({ key: "a", large: true, preferred: "pretty", chosen })).toBe("pretty"); + expect(shownViewMode({ key: "b", large: true, preferred: "pretty", chosen })).toBe("raw"); + }); +}); diff --git a/apps/yaak-proxy/components/FlowBodyViewer.tsx b/apps/yaak-proxy/components/FlowBodyViewer.tsx index b86c7e2b8..8e687c3ab 100644 --- a/apps/yaak-proxy/components/FlowBodyViewer.tsx +++ b/apps/yaak-proxy/components/FlowBodyViewer.tsx @@ -2,27 +2,38 @@ import { useQuery } from "@tanstack/react-query"; import { formatSize } from "@yaakapp-internal/lib/formatSize"; import type { Flow, FlowBody } from "@yaakapp-internal/proxy-lib"; import { + ACTIONS_BAR_CONTAINER, + ActionsBar, Banner, + BodyViewModeSwitch, Button, CsvViewer, HexdumpViewer, Icon, ImageViewer, + LARGE_BODY_BYTES, languageFromContentType, LoadingIcon, MultipartViewer, + type PrettyView, + prettyViewFor, + type ResponseViewMode, SvgViewer, TextViewer, WebPageViewer, } from "@yaakapp-internal/ui"; import type { CodeEditorProps } from "@yaakapp-internal/ui/editor"; +import classNames from "classnames"; +import { useAtom } from "jotai"; import type { ReactNode } from "react"; import { useCallback, useEffect, useMemo, useState } from "react"; +import { bodyViewModeAtom } from "../lib/atoms"; import { bodyAsText, bodyImageType, filterText, findHeader, + emptyBodyText, flowBodyQueryOptions, formatText, mimeEssence, @@ -32,15 +43,97 @@ import { useSaveFlowBody } from "../lib/flowActions"; interface Props { flow: Flow; which: FlowBody; - pretty: boolean; + /** A URL-encoded body's fields, its formatted view, with the switch in the fields' own bar */ + form?: (actions: ReactNode) => ReactNode; + /** Leaves saying the body was cut short to the tab, which says it its own way */ + hideCutNote?: boolean; } export function useFlowBody(flow: Flow, which: FlowBody, enabled = true) { return useQuery({ ...flowBodyQueryOptions(flow, which), enabled }); } -export function FlowBodyViewer({ flow, which, pretty }: Props) { +/** A mode chosen for one large body, which holds for it alone */ +interface ChosenViewMode { + key: string; + mode: ResponseViewMode; +} + +/** The mode a body shows in: the preference, except raw for a large one until chosen for it */ +export function shownViewMode({ + key, + large, + preferred, + chosen, +}: { + key: string; + large: boolean; + preferred: ResponseViewMode; + chosen: ChosenViewMode | null; +}): ResponseViewMode { + if (chosen?.key === key) return chosen.mode; + return large ? "raw" : preferred; +} + +/** + * Formatted or raw, as last chosen, except that a body big enough to slow the card opens raw, + * and choosing for it holds for that body alone + */ +export function useBodyViewMode( + key: string, + large: boolean, +): [ResponseViewMode, (mode: ResponseViewMode) => void] { + const [preferred, setPreferred] = useAtom(bodyViewModeAtom); + const [chosen, setChosen] = useState(null); + const mode = shownViewMode({ key, large, preferred, chosen }); + const setMode = useCallback( + (next: ResponseViewMode) => { + if (large) { + setChosen({ key, mode: next }); + } else { + setChosen(null); + setPreferred(next); + } + }, + [key, large, setPreferred], + ); + return [mode, setMode]; +} + +/** + * The formatted view a body has, or null when it has only the one: parts for multipart, the + * fields for a URL-encoded form, or else what the shared rule gives its text. Images and binary + * bodies have only their one view. + */ +export function flowPrettyView({ + which, + mime, + text, + binary, + language, + hasForm, +}: { + which: FlowBody; + mime: string; + text: string | null; + /** An image, or what failed to decode */ + binary: boolean; + language: CodeEditorProps["language"] | null; + hasForm: boolean; +}): PrettyView | null { + if (binary) return null; + if (mime.startsWith("multipart/")) return "parts"; + if (text == null) return null; + if (hasForm && mime === "application/x-www-form-urlencoded") return "form"; + return prettyViewFor({ mimeType: mime, language, previewHtml: which === "response" }); +} + +export function FlowBodyViewer({ flow, which, form, hideCutNote = false }: Props) { const body = useFlowBody(flow, which); + const [mode, setMode] = useBodyViewMode( + `${flow.id}.${which}`, + (body.data?.bytes.length ?? 0) > LARGE_BODY_BYTES, + ); if (body.isPending) { return ( @@ -53,9 +146,9 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) { return {body.error.message}; } - const { bytes, truncated, storedSize, decodeError } = body.data; + const { bytes, truncated, storedSize, decodeError, note } = body.data; if (bytes.length === 0 && decodeError == null) { - return {which === "request" ? "No request body" : "Empty"}; + return {emptyBodyText(which, note)}; } const headers = which === "request" ? flow.requestHeaders : flow.responseHeaders; @@ -68,12 +161,28 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) { const imageType = decodeError == null ? bodyImageType(bytes, truncated, contentType) : null; const text = decodeError == null && imageType == null ? bodyAsText(bytes, truncated, contentType) : null; + const language = text == null ? null : languageFromContentType(contentType, text); + const prettyView = flowPrettyView({ + which, + mime, + text, + binary: decodeError != null || imageType != null, + language, + hasForm: form != null, + }); + // The one view a body without a formatted one has is its raw one + const pretty = prettyView != null && mode === "pretty"; + const modeSwitch = + prettyView == null ? null : ( + + ); let viewer: ReactNode; + let ownsBar = false; if (decodeError != null) { // What failed to decode is as it was on the wire, compressed, so never text. viewer = ; - } else if (mime.startsWith("multipart/") && pretty) { + } else if (prettyView === "parts" && pretty) { const boundary = contentType?.match(/;\s*boundary="?([^";]+)"?/i)?.[1] ?? "unknown"; viewer = ( ; } else if (text == null) { viewer = ; - } else if (mime.startsWith("image/svg")) { - viewer = ; - } else if (/csv|tab-separated/.test(mime) && pretty) { + } else if (prettyView === "form" && pretty && form != null) { + ownsBar = true; + viewer = form(modeSwitch); + } else if (prettyView === "table" && pretty) { viewer = ; + } else if (prettyView === "preview" && pretty) { + viewer = mime.startsWith("image/svg") ? ( + + ) : ( + + ); } else { - const language = languageFromContentType(contentType, text); - if (language === "html" && pretty && which === "response") { - viewer = ; - } else { - viewer = ( - - ); - } + ownsBar = true; + viewer = ( + + ); } - if (!truncated && decodeError == null) return viewer; + // The text viewer and the form draw the switch in their own bar, beside their own actions; the + // rest get a bar here. Each fills the tab content, so every bar has the same inset. + if (modeSwitch != null && !ownsBar) { + viewer = ( +
+ {viewer} + {modeSwitch} +
+ ); + } + + if ((!truncated || hideCutNote) && decodeError == null) return viewer; return (
@@ -111,7 +241,7 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) { {decodeError}. Showing the body as it was on the wire. )} - {truncated && ( + {truncated && !hideCutNote && ( {wireTruncated || decodeError != null ? `Showing the first ${formatSize(storedSize)} of ${formatSize(wireSize)}, the capture limit. The app received all of it.` @@ -167,7 +297,16 @@ function FlowTextViewer({ text, language, pretty, -}: Props & { text: string; language: CodeEditorProps["language"] }) { + modeSwitch, +}: { + flow: Flow; + which: FlowBody; + text: string; + language: CodeEditorProps["language"]; + pretty: boolean; + /** Formatted or raw, in the viewer's bar after its filter; null for a body with one view */ + modeSwitch: ReactNode; +}) { const runFilter = useCallback( (expression: string) => filterText(flow.id, which, expression, language), [flow.id, which, language], @@ -182,6 +321,8 @@ function FlowTextViewer({ className="-mr-2 bg-surface" formatText={formatText} filterText={runFilter} + ownActionsBar + pinnedActions={modeSwitch} /> ); } diff --git a/apps/yaak-proxy/components/FlowCard.tsx b/apps/yaak-proxy/components/FlowCard.tsx new file mode 100644 index 000000000..fbdc7340a --- /dev/null +++ b/apps/yaak-proxy/components/FlowCard.tsx @@ -0,0 +1,333 @@ +import { formatSize } from "@yaakapp-internal/lib/formatSize"; +import type { Flow, FlowBody } from "@yaakapp-internal/proxy-lib"; +import { + CONTROL_TOOLTIP_DELAY, + CountBadge, + Dropdown, + EmptyStateText, + type ExtraPaneTab, + FormUrlencodedEditor, + type HttpBodyResult, + HttpRequestPaneView, + HttpResponsePaneView, + Icon, + IconButton, + parseCookieHeaders, + ResponseCookies, + SplitLayout, + Tooltip, +} from "@yaakapp-internal/ui"; +import classNames from "classnames"; +import { useAtomValue, useSetAtom, useStore } from "jotai"; +import { useCallback, useMemo } from "react"; +import { BODY_TYPE_FORM_URLENCODED } from "@yaakapp-internal/ui/httpTypes"; +import { placeTabsAtom } from "../lib/atoms"; +import { findHeader } from "../lib/body"; +import { + browserTabMemory, + defaultTabFor, + type FlowPane, + learnTab, + REQUEST_TAB_AUTH, + REQUEST_TAB_BODY, + REQUEST_TAB_COOKIES, + REQUEST_TAB_HEADERS, + REQUEST_TAB_PARAMS, + RESPONSE_TAB_BODY, + RESPONSE_TAB_COOKIES, + RESPONSE_TAB_HEADERS, + RESPONSE_TAB_INFO, + RESPONSE_TAB_MESSAGES, + RESPONSE_TAB_TIMELINE, +} from "../lib/defaultTab"; +import { saveDialogFlowAtom, useFlowActions } from "../lib/flowActions"; +import { + type FlowBodyData, + flowBodyLoader, + flowCookiesView, + flowRequestToView, + flowResponseToView, +} from "../lib/flowViews"; +import { messagesTabLabel } from "../lib/messages"; +import { goToPlace } from "../lib/navigation"; +import { FlowBodyViewer, useFlowBody } from "./FlowBodyViewer"; +import { FlowInfo } from "./FlowInfo"; +import { FlowRequestBody } from "./FlowRequestBody"; +import { FlowMessages } from "./FlowMessages"; +import { FlowTimeline } from "./FlowTimeline"; +import { ProxyEditorHost } from "./ProxyEditorHost"; + +/** + * One card for a flow: the request half (its URL line and tabs), a hairline, and the response + * half (its status line and tabs). The halves sit perpendicular to the list: stacked when the + * list is beside the card, side by side when it is above. + */ +export function FlowCard({ flow, listBeside }: { flow: Flow; listBeside: boolean }) { + return ( + + ( +
+ +
+ )} + secondSlot={({ style, orientation }) => ( +
+ +
+ )} + /> +
+ ); +} + +/** + * The tab a half opens on, and learning from the ones chosen by hand. The tab chosen is part of + * the window's place, so going back to it, or reloading, opens it again. + */ +function useShapeTab(pane: FlowPane, flow: Flow, available: string[]) { + const store = useStore(); + const memory = browserTabMemory(); + const activeTab = useAtomValue(placeTabsAtom)[pane]; + // Read again for every flow, so a tab learned on one opens the next of its shape + const defaultTab = defaultTabFor(pane, flow, available, memory); + const onTabChange = useCallback( + (tab: string) => { + learnTab(pane, flow, tab, memory); + goToPlace(store, "update", { tabs: { ...store.get(placeTabsAtom), [pane]: tab } }); + }, + [pane, flow, memory, store], + ); + return { activeTab, defaultTab, onTabChange }; +} + +/** A body read through the engine's body RPC, as the shared panes' loaders ask for it */ +function useLoadedBody( + flow: Flow, + which: FlowBody, + enabled = true, +): HttpBodyResult { + const size = which === "request" ? flow.requestSize : flow.responseSize; + const load = enabled && size > 0; + const body = useFlowBody(flow, which, load); + if (!load) return { data: null, isLoading: false, error: null }; + return { data: body.data ?? undefined, isLoading: body.isLoading, error: body.error }; +} + +function FlowRequestHalf({ flow }: { flow: Flow }) { + const body = useLoadedBody(flow, "request"); + const request = useMemo(() => flowRequestToView(flow, body.data ?? null), [flow, body.data]); + const loader = useMemo( + () => + flowBodyLoader({ + useBody: () => useLoadedBody(flow, "request"), + contentType: findHeader(flow.requestHeaders, "content-type"), + }), + [flow], + ); + const cookies = useMemo(() => flowCookiesView(flow), [flow]); + const sentCount = useMemo( + () => parseCookieHeaders(cookies.cookieHeaders).sentCookies.length, + [cookies], + ); + const extraTabs = useMemo( + () => [ + { + tab: { + value: REQUEST_TAB_COOKIES, + label: "Cookies", + rightSlot: , + }, + content: , + }, + ], + [cookies, sentCount], + ); + const available = [ + REQUEST_TAB_BODY, + REQUEST_TAB_PARAMS, + REQUEST_TAB_HEADERS, + ...(request.auth == null ? [] : [REQUEST_TAB_AUTH]), + REQUEST_TAB_COOKIES, + ]; + const { activeTab, defaultTab, onTabChange } = useShapeTab("request", flow, available); + + const forceUpdateKey = `${flow.updatedAt}.${body.data == null ? "" : "loaded"}`; + + return ( + } + renderBody={() => ( + ( + + ) + : undefined + } + hideCutNote + /> + } + requestSize={flow.requestSize} + /> + )} + /> + ); +} + +/** The method and URL, at the status line's height so the two header lines align */ +function UrlLine({ flow }: { flow: Flow }) { + return ( + // The whole URL on hover, when it runs past the card + +
+ {flow.method} + {flow.url} +
+
+ ); +} + +function FlowResponseHalf({ flow, className }: { flow: Flow; className: string }) { + // A stream's body is its messages, read by the Messages tab; reading it whole again on every + // message would only hold copies of it + const loadBody = flow.streamKind == null; + const body = useLoadedBody(flow, "response", loadBody); + const response = useMemo(() => flowResponseToView(flow, body.data ?? null), [flow, body.data]); + const loader = useMemo( + () => + flowBodyLoader({ + useBody: () => useLoadedBody(flow, "response", loadBody), + contentType: findHeader(flow.responseHeaders, "content-type"), + }), + [flow, loadBody], + ); + const openSave = useSetAtom(saveDialogFlowAtom); + const flowActions = useFlowActions(); + const messagesLabel = messagesTabLabel(flow); + + const extraTabs = useMemo( + () => [ + { + tab: { value: RESPONSE_TAB_TIMELINE, label: "Timeline" }, + content: , + }, + { tab: { value: RESPONSE_TAB_INFO, label: "Info" }, content: }, + ...(messagesLabel == null + ? [] + : [ + { + tab: { + value: RESPONSE_TAB_MESSAGES, + label: messagesLabel, + rightSlot: ( + + ), + }, + content: , + }, + ]), + ], + [flow, messagesLabel], + ); + const available = [ + RESPONSE_TAB_BODY, + RESPONSE_TAB_HEADERS, + RESPONSE_TAB_COOKIES, + RESPONSE_TAB_TIMELINE, + RESPONSE_TAB_INFO, + ...(messagesLabel == null ? [] : [RESPONSE_TAB_MESSAGES]), + ]; + const { activeTab, defaultTab, onTabChange } = useShapeTab("response", flow, available); + const saved = flow.savedRequestId != null; + + return ( + Waiting for a response} + tabsStorageKey="proxy_response_tabs" + activeTabKey={flow.id} + defaultTab={defaultTab} + activeTab={activeTab} + onTabChange={onTabChange} + extraTabs={extraTabs} + renderBodyViewer={() => } + statusLineCenter={ + flow.responseTruncated ? ( + + + {body.data == null ? "Body cut" : `First ${formatSize(body.data.storedSize)} kept`} + + ) : undefined + } + statusLineRight={ +
+ openSave(flow)} + /> + + + +
+ } + /> + ); +} diff --git a/apps/yaak-proxy/components/FlowDetail.tsx b/apps/yaak-proxy/components/FlowDetail.tsx index 5cb5e818d..3a2edbf90 100644 --- a/apps/yaak-proxy/components/FlowDetail.tsx +++ b/apps/yaak-proxy/components/FlowDetail.tsx @@ -1,45 +1,22 @@ -import { formatSize } from "@yaakapp-internal/lib/formatSize"; -import type { Flow } from "@yaakapp-internal/proxy-lib"; -import { - Banner, - Button, - CountBadge, - Dropdown, - type DropdownItem, - formatMillis, - HStack, - HttpStatusTagRaw, - Icon, - IconButton, - SizeTag, - type TabButtonRenderProps, - type TabItem, - TabContent, - Tabs, -} from "@yaakapp-internal/ui"; import classNames from "classnames"; -import { useAtomValue, useSetAtom } from "jotai"; +import { useAtomValue } 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"; - -const TAB_RESPONSE = "response"; -const TAB_REQUEST = "request"; -const TAB_HEADERS = "headers"; -const TAB_QUERY = "query"; +import { EmptyState } from "./FlowBodyViewer"; +import { FlowCard } from "./FlowCard"; +import { NotDecrypted } from "./NotDecrypted"; +/** + * The detail pane: the selected flow's card, or what the pane holds before one is selected. The + * split's gutter separates it from the list; side by side it sits a little under the header. + */ export function FlowDetail({ style, sideBySide }: { style?: CSSProperties; sideBySide: boolean }) { const flow = useAtomValue(selectedFlowAtom); return (
Pause or resume recording Clear flows - +
+ ) : flow.tunnelled ? ( + ) : ( - + )}
); } -function FlowPane({ flow }: { flow: Flow }) { - const [pretty, setPretty] = useState(true); - const responseBody = useFlowBody(flow, "response", flow.responseTruncated); - // Failed or cancelled before any response; after the headers, the body was cut short mid-way. - const noResponse = (flow.error != null || flow.cancelled) && 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( - () => [ - { - value: TAB_RESPONSE, - renderButton: ({ buttonProps, isActive }) => ( - - ), - }, - { - value: TAB_REQUEST, - label: "Request", - rightSlot: flow.requestSize > 0 ? : null, - }, - { - value: TAB_HEADERS, - label: "Headers", - rightSlot: ( - - ), - }, - { - value: TAB_QUERY, - label: "Query", - rightSlot: , - }, - ], - [ - pretty, - mime, - flow.requestSize, - flow.requestHeaders.length, - flow.responseHeaders.length, - queryCount, - ], - ); - - return ( -
-
- - {flow.cancelled && flow.status == null ? ( - Cancelled - ) : ( - - )} - {flow.elapsedMs != null && ( - <> - • - - {formatMillis(flow.elapsedMs)} - - - )} - {!noResponse && ( - <> - • - - - )} - - {flow.responseTruncated ? ( - - - {responseBody.data == null - ? "Body cut" - : `First ${formatSize(responseBody.data.storedSize)} kept`} - - ) : ( - - )} - - - - - - -
- -
- {flow.error != null && ( - - {flow.error} - - )} - {flow.cancelled && ( - - {flow.status == null - ? "The app cancelled the request before a response came back." - : "The app cancelled the request before the response finished."} - - )} - - - {noResponse ? ( - -
- {flow.cancelled ? "Cancelled" : "No response"} -
-
- {flow.cancelled - ? "The app cancelled the request before a response came back." - : "The request never got a response."}{" "} - The Request tab has what the app sent. -
-
- ) : ( - - )} -
- - - - - - - - - -
-
-
- ); -} - -interface ViewModeButtonProps { - buttonProps: TabButtonRenderProps["buttonProps"]; - isActive: boolean; - pretty: boolean; - onChangePretty: (pretty: boolean) => void; - prettyLabel: string; - allowRaw: boolean; -} - -/** The client's Response tab: a click on the active tab opens its view menu */ -function ViewModeButton({ - buttonProps, - isActive, - pretty, - onChangePretty, - prettyLabel, - allowRaw, -}: ViewModeButtonProps) { - const showPretty = pretty || !allowRaw; - const items: DropdownItem[] = [ - { - label: prettyLabel, - leftSlot: , - onSelect: () => onChangePretty(true), - }, - { - label: `${prettyLabel} (Raw)`, - hidden: !allowRaw, - leftSlot: , - onSelect: () => onChangePretty(false), - }, - ]; - - return ( - - - - ); -} - -function CheckMark({ visible }: { visible: boolean }) { - return ; -} - function Keys({ keys }: { keys: string[] }) { return ( diff --git a/apps/yaak-proxy/components/FlowHeaders.tsx b/apps/yaak-proxy/components/FlowHeaders.tsx deleted file mode 100644 index 01d8c7496..000000000 --- a/apps/yaak-proxy/components/FlowHeaders.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { formatSize } from "@yaakapp-internal/lib/formatSize"; -import type { Flow } from "@yaakapp-internal/proxy-lib"; -import { - DetailsBanner, - formatMillis, - HeadersTable, - KeyValueRow, - KeyValueRows, -} from "@yaakapp-internal/ui"; -import { useMemo } from "react"; -import { EmptyState } from "./FlowBodyViewer"; - -const startedFormat = new Intl.DateTimeFormat("en-US", { - month: "short", - day: "numeric", - year: "numeric", - hour: "numeric", - minute: "2-digit", - second: "2-digit", - fractionalSecondDigits: 3, - timeZoneName: "short", -}); - -const bytesFormat = new Intl.NumberFormat("en-US"); - -export function FlowHeaders({ flow }: { flow: Flow }) { - const versions = - flow.upstreamHttpVersion == null - ? `${flow.clientHttpVersion} from the app` - : `${flow.clientHttpVersion} from the app, ${flow.upstreamHttpVersion} to the server`; - - return ( -
- Info}> - - - {startedFormat.format(new Date(`${flow.startedAt}Z`))} - - {flow.url} - {flow.remoteAddr ?? } - {versions} - - {flow.elapsedMs == null ? ( - - ) : flow.elapsedHeadersMs == null ? ( - `${formatMillis(flow.elapsedMs)} in all` - ) : ( - `${formatMillis(flow.elapsedMs)} in all, headers after ${formatMillis(flow.elapsedHeadersMs)}` - )} - - - - {formatSize(flow.requestSize)} sent, {formatSize(flow.responseSize)} received{" "} - - ({bytesFormat.format(flow.responseSize)} B) - - - - - - - -
- ); -} - -export function FlowQuery({ flow }: { flow: Flow }) { - const params = useMemo(() => queryParams(flow.url), [flow.url]); - - if (params.length === 0) { - return No query parameters; - } - - return ( -
- - {params.map(([name, value], i) => ( - // oxlint-disable-next-line react/no-array-index-key -- a name can repeat - - {value} - - ))} - -
- ); -} - -export function queryParams(url: string): [string, string][] { - try { - return [...new URL(url).searchParams.entries()]; - } catch { - return []; - } -} - -function Missing() { - return --; -} diff --git a/apps/yaak-proxy/components/FlowInfo.tsx b/apps/yaak-proxy/components/FlowInfo.tsx new file mode 100644 index 000000000..7286729d9 --- /dev/null +++ b/apps/yaak-proxy/components/FlowInfo.tsx @@ -0,0 +1,125 @@ +import { formatSize } from "@yaakapp-internal/lib/formatSize"; +import type { Flow } from "@yaakapp-internal/proxy-lib"; +import { DetailsBanner, formatMillis, KeyValueRow, KeyValueRows } from "@yaakapp-internal/ui"; +import { format } from "date-fns"; +import type { HTMLAttributes, ReactElement, ReactNode } from "react"; +import { utcTimestamp } from "../lib/flowViews"; +import { folderOf } from "../lib/search"; +import { AppIcon } from "./AppIcon"; + +/** + * Where a flow came from and how it travelled: in a proxy you didn't send the request, so the + * connection on each leg, the app and its process, timing, sizes and the flow's record are part + * of the answer. + */ +export function FlowInfo({ flow }: { flow: Flow }) { + const folder = folderOf(flow); + const clientPort = portOf(flow.clientAddr); + + return ( +
+
+ {[ + row("remote", "Remote Address", flow.remoteAddr, { copy: true }), + row("client_version", "Client Version", flow.clientHttpVersion), + row("server_version", "Server Version", flow.upstreamHttpVersion), + row("tls", "TLS", flow.upstreamTlsVersion), + row("cipher", "Cipher", flow.upstreamTlsCipher), + row("client_port", "Client Port", clientPort), + ]} +
+
+ {[ + row( + "app", + "Name", + flow.clientName == null ? null : ( + + {flow.clientPath != null && } + {flow.clientName} + {folder != null && {folder}} + + ), + ), + flow.clientBundleId != null + ? row("bundle", "Bundle ID", flow.clientBundleId, { copy: true }) + : row("path", "Path", flow.clientPath, { copy: true }), + row("pid", "PID", flow.clientPid == null ? null : `${flow.clientPid}`), + row("cwd", "Directory", flow.clientCwd, { copy: true }), + ]} +
+
+ {[ + row( + "started", + "Started", + format(utcTimestamp(flow.startedAt), "MMM d, yyyy, h:mm:ss.SSS a"), + ), + row("headers", "Headers", ms(flow.elapsedHeadersMs)), + row("total", "Total", ms(flow.elapsedMs)), + ]} +
+
+ {[ + row("request_size", "Request", formatSize(flow.requestSize)), + row("response_size", "Response", formatSize(flow.responseSize)), + ]} +
+
+ {[ + row("number", "Number", `#${flow.number}`, { copy: true }), + row("id", "ID", flow.id, { copy: true }), + row("saved", "Saved As", flow.savedRequestId, { copy: true }), + ]} +
+
+ ); +} + +/** A row as `KeyValueRows` takes it */ +type Row = ReactElement>; + +function Section({ title, children }: { title: string; children: (Row | null)[] }) { + const rows = children.filter((r): r is Row => r != null); + if (rows.length === 0) return null; + return ( + {title}}> + {rows} + + ); +} + +/** A row, or nothing when there's no value for it */ +function row( + key: string, + label: string, + value: ReactNode | null | undefined, + opts: { copy?: boolean } = {}, +): Row | null { + if (value == null || value === "") return null; + return ( + + {value} + + ); +} + +function ms(value: number | null): string | null { + return value == null ? null : formatMillis(value); +} + +/** The port of `127.0.0.1:54321` or `[::1]:54321` */ +export function portOf(addr: string | null | undefined): string | null { + const port = addr?.match(/:(\d+)$/)?.[1]; + return port ?? null; +} + +function copyText(text: string) { + navigator.clipboard.writeText(text).catch(console.error); +} diff --git a/apps/yaak-proxy/components/FlowList.tsx b/apps/yaak-proxy/components/FlowList.tsx index 9308e7e6d..6a79643a1 100644 --- a/apps/yaak-proxy/components/FlowList.tsx +++ b/apps/yaak-proxy/components/FlowList.tsx @@ -1,77 +1,170 @@ import { useVirtualizer } from "@tanstack/react-virtual"; import { formatSize } from "@yaakapp-internal/lib/formatSize"; -import type { Flow } from "@yaakapp-internal/proxy-lib"; +import type { Flow, FlowSortKey } from "@yaakapp-internal/proxy-lib"; import { ContextMenu, + CONTROL_TOOLTIP_DELAY, + CountBadge, + type DropdownItem, formatMillis, HttpMethodTagRaw, HttpStatusTagRaw, Icon, + Tooltip, } from "@yaakapp-internal/ui"; import classNames from "classnames"; -import { useAtom, useAtomValue, useSetAtom } from "jotai"; -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 { useAtom, useAtomValue, useSetAtom, useStore } from "jotai"; +import type { + CSSProperties, + KeyboardEvent, + MouseEvent, + ReactElement, + RefObject, + WheelEvent, +} from "react"; +import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { - activeQueryAtom, - followAtom, + appliedFilterAtom, + placeSelectionAtom, + revealFlowAtom, + selectedFlowIdAtom, +} from "../lib/atoms"; +import { shortContentType } from "../lib/body"; +import { utcTimestamp } from "../lib/flowViews"; +import { + type Column, + type ColumnId, + cellFilterTerm, + columnShifts, + customValue, + gridTemplate, + gridWidth, + hostOf, + isCustomColumn, + nextSort, + operationOf, + showOperationFor, + shownColumns, + tlsVersionOf, + toggleSortKey, + unavailableColumns, + urlParts, +} from "../lib/columns"; +import { useExportShownHar, useFlowActions } from "../lib/flowActions"; +import { compareFlows } from "../lib/flowWindow"; +import { countNewFlows, isAtEnd, resumesFollowing } from "../lib/follow"; +import { applyFilter, goToPlace } from "../lib/navigation"; +import { asOneTerm } from "../lib/query"; +import { folderOf } from "../lib/search"; +import { + columnPrefsAtom, hasAppsAtom, + flowSortAtom, + followAtom, + loadMoreSortedAtom, loadOlderFlowsAtom, newestStartedAtAtom, oldestFlowAtom, - searchWindowAtom, + proxyStateAtom, + searchLoadingAtom, + flowsAtom, shownFlowsAtom, } from "../lib/store"; +import { useShowToast } from "../lib/toast"; import { AppIcon } from "./AppIcon"; -import { SearchBar } from "./SearchBar"; +import { FlowListEmpty, PausedRow } from "./FlowListEmpty"; +import { type ColumnDragEvent, FlowListHeader } from "./FlowListHeader"; -const ROW_HEIGHT = 24; const BOTTOM_PADDING = 6; -/** Rows from the top at which older flows start loading */ +/** Rows from the top at which older flows start loading, or from the bottom, sorted, more */ const LOAD_OLDER_ROWS = 20; +/** How long a row that arrives while following stays tinted */ +const ARRIVAL_MS = 1400; +/** Most flows arriving together that still tint; more is a burst */ +const ARRIVAL_MAX_BATCH = 5; + +/** `h-xs`, the height of Yaak's event rows and menu items, in pixels at the root font size */ +function rowHeight(): number { + const root = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 15; + return Math.round(1.8 * root); +} interface Props { - sideBySide: boolean; style?: CSSProperties; className?: string; } /** * Follows new traffic until a flow is selected or the list is scrolled, then holds. Scrolling to - * the top loads older flows from the database. + * the top loads older flows from the database. Catching up leaves a divider where the hold + * began. Sorting by columns reads the flows from the database in that order, a page at a time on + * scrolling down, and stops following. The columns keep their widths, and the list scrolls + * sideways when they are wider than it, the header with it. */ -export function FlowList({ sideBySide, style, className }: Props) { +export function FlowList({ style, className }: Props) { const flows = useAtomValue(shownFlowsAtom); - const hasApps = useAtomValue(hasAppsAtom); - const [menu, setMenu] = useState<{ flow: Flow; x: number; y: number } | null>(null); + const [menu, setMenu] = useState<{ + flow: Flow; + column: ColumnId | null; + x: number; + y: number; + } | null>(null); const flowActions = useFlowActions(); + const cellActions = useCellActions(); + const exportShown = useExportShownHar(); + const store = useStore(); const selectedId = useAtomValue(selectedFlowIdAtom); - const setSelectedFlow = useSetAtom(selectedFlowAtom); const loadOlder = useSetAtom(loadOlderFlowsAtom); + const loadMoreSorted = useSetAtom(loadMoreSortedAtom); const oldestFlow = useAtomValue(oldestFlowAtom); + const [prefs, setPrefs] = useAtom(columnPrefsAtom); + const [sort, setSort] = useAtom(flowSortAtom); + const sorted = sort.length > 0; + const allFlows = useAtomValue(flowsAtom); + + // Operation shows itself the first time a flow has one, unless the person set it already. + useEffect(() => { + if (prefs.visible.operation !== undefined) return; + const next = showOperationFor(prefs, allFlows); + if (next !== prefs) setPrefs(next); + }, [prefs, allFlows, setPrefs]); + const proxyState = useAtomValue(proxyStateAtom); + const paused = proxyState?.state === "running" && proxyState.recording === false; const scrollRef = useRef(null); + const headerScrollRef = useRef(null); + const lastScrollTop = useRef(0); + // The list's vertical scrollbar, which the header leaves room for so the two scroll as far + const [scrollbarWidth, setScrollbarWidth] = useState(0); + // The list's visible height, so a resize that leaves it at its end follows again + const [viewportHeight, setViewportHeight] = useState(0); const ignoreScroll = useRef(false); const [following, setFollowing] = useAtom(followAtom); const [heldAt, setHeldAt] = useState(null); + /** The first flow after the last catch-up's hold, and how many came after it */ + const [divider, setDivider] = useState<{ id: string; count: number } | null>(null); // The newest flow across all traffic, not just this list, so a filter change keeps the hold const newestStartedAt = useAtomValue(newestStartedAtAtom); + const ROW_HEIGHT = useMemo(rowHeight, []); // Read by the callbacks below, which stay the same across new traffic so rows don't re-render - const latest = useRef({ flows, following, newestStartedAt }); + const latest = useRef({ flows, following, newestStartedAt, heldAt, sort }); useLayoutEffect(() => { - latest.current = { flows, following, newestStartedAt }; + latest.current = { flows, following, newestStartedAt, heldAt, sort }; }); + // Where the platform cannot tell which app sent a flow, there is no App column. + const hasApps = useAtomValue(hasAppsAtom); + const columns = useMemo(() => shownColumns(prefs, unavailableColumns(hasApps)), [prefs, hasApps]); + const template = useMemo(() => gridTemplate(columns), [columns]); + // A row's grid, its padding and the list's margins: `px-1.5` and `left-1.5 right-1.5` + const contentWidth = useMemo(() => `calc(${gridWidth(columns)} + 1.5rem)`, [columns]); + const arrivals = useArrivals(flows, following && !sorted); + const virtualizer = useVirtualizer({ count: flows.length, getScrollElement: () => scrollRef.current, estimateSize: () => ROW_HEIGHT, getItemKey: (index) => flows[index]?.id ?? index, - paddingEnd: BOTTOM_PADDING, + paddingEnd: BOTTOM_PADDING + (paused && flows.length > 0 ? ROW_HEIGHT + 8 : 0), overscan: 40, }); @@ -92,48 +185,138 @@ export function FlowList({ sideBySide, style, className }: Props) { }, [setFollowing]); const follow = useCallback(() => { + const { flows, heldAt, following, sort } = latest.current; + // Catching up from a hold marks where it began. + if (!following && sort.length === 0) { + const count = countNewFlows(flows, heldAt); + const first = flows[flows.length - count]; + setDivider(count > 0 && first != null ? { id: first.id, count } : null); + } + setSort([]); setFollowing(true); setHeldAt(null); setScrollTop(Number.MAX_SAFE_INTEGER); - }, [setFollowing, setScrollTop]); + }, [setFollowing, setScrollTop, setSort]); + + // A sorted list never follows, whether the sort was just set, kept from the last launch, or + // kept through a clear. + useLayoutEffect(() => { + if (sorted && following) setFollowing(false); + }, [sorted, following, setFollowing]); + + // A held list follows again once it is at its end, not only when scrolled there: a sidebar row, + // search or resize can leave it there with no scroll to make, as one that fits its viewport + // always is, and its flows would otherwise count as new while all are on screen. Judged when + // which flows are listed changes, or the list's height, not when one listed is updated or + // `following` itself changes, so selecting a row at the end still holds; and not while a + // search's first page loads, as its empty list is at its end only until the page is in. + const searchLoading = useAtomValue(searchLoadingAtom); + const listed = `${flows.length}:${flows[0]?.id ?? ""}:${flows.at(-1)?.id ?? ""}`; + useLayoutEffect(() => { + const el = scrollRef.current; + if (el == null || searchLoading) return; + if (!resumesFollowing({ following: latest.current.following, sorted, el })) return; + setFollowing(true); + setHeldAt(null); + }, [listed, sorted, searchLoading, viewportHeight, setFollowing]); useLayoutEffect(() => { - if (following) setScrollTop(Number.MAX_SAFE_INTEGER); - }, [following, flows, setScrollTop]); + if (following && !sorted) setScrollTop(Number.MAX_SAFE_INTEGER); + }, [following, sorted, flows, paused, setScrollTop]); + + // Sorted, rows that leave, deleted or moved past what is read, can leave the end of the list + // in view with no scroll to load the next page; it loads as they go. + useEffect(() => { + const el = scrollRef.current; + if (!sorted || el == null) return; + const toEnd = el.scrollHeight - el.scrollTop - el.clientHeight; + if (toEnd < LOAD_OLDER_ROWS * ROW_HEIGHT) void loadMoreSorted(); + }, [sorted, flows, loadMoreSorted, ROW_HEIGHT]); + + // A new sort starts from its top. + const sortKey = JSON.stringify(sort); + useLayoutEffect(() => { + if (sortKey !== "[]") setScrollTop(0); + }, [sortKey, setScrollTop]); // Older flows that loaded in above push the rows down; scroll by as much, so they stay put. const anchor = useRef(null); useLayoutEffect(() => { const previous = anchor.current; anchor.current = oldestFlow; - if (following || previous == null || oldestFlow == null) return; + if (following || sorted || previous == null || oldestFlow == null) return; if (compareFlows(oldestFlow, previous) >= 0) return; const added = flows.findIndex((f) => compareFlows(f, previous) >= 0); const el = scrollRef.current; if (added > 0 && el != null) setScrollTop(el.scrollTop + added * ROW_HEIGHT); - }, [oldestFlow, flows, following, setScrollTop]); + }, [oldestFlow, flows, following, sorted, setScrollTop, ROW_HEIGHT]); + // Sorted, the flows loaded are what is sorted; older ones would land anywhere. const loadOlderHeld = useCallback(() => { hold(); - void loadOlder(); + if (latest.current.sort.length === 0) void loadOlder(); }, [hold, loadOlder]); + useEffect(() => { + const el = scrollRef.current; + if (el == null) return; + const measure = () => { + setScrollbarWidth(el.offsetWidth - el.clientWidth); + setViewportHeight(el.clientHeight); + }; + measure(); + const observer = new ResizeObserver(measure); + observer.observe(el); + return () => observer.disconnect(); + }, []); + const handleScroll = useCallback(() => { + const el = scrollRef.current; + if (el == null) return; + if (headerScrollRef.current != null) headerScrollRef.current.scrollLeft = el.scrollLeft; + // Sideways only: following and holding go by the vertical position. + const top = el.scrollTop; + const moved = top !== lastScrollTop.current; + lastScrollTop.current = top; if (ignoreScroll.current) { ignoreScroll.current = false; return; } - const el = scrollRef.current; - if (el == null) return; - const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 2; - if (atEnd) { + if (!moved) return; + const sortedNow = latest.current.sort.length > 0; + if (isAtEnd(el) && !sortedNow) { setFollowing(true); setHeldAt(null); } else { hold(); - if (el.scrollTop < LOAD_OLDER_ROWS * ROW_HEIGHT) void loadOlder(); + if (el.scrollTop < LOAD_OLDER_ROWS * ROW_HEIGHT && !sortedNow) { + void loadOlder(); + } } - }, [hold, loadOlder, setFollowing]); + // Sorted, the next page of the sort loads near the bottom. + const toEnd = el.scrollHeight - el.scrollTop - el.clientHeight; + if (sortedNow && toEnd < LOAD_OLDER_ROWS * ROW_HEIGHT) void loadMoreSorted(); + }, [hold, loadOlder, loadMoreSorted, setFollowing, ROW_HEIGHT]); + + // Focus moving to a sort button out of view scrolls the header itself; the rows follow. + const handleHeaderScroll = useCallback(() => { + const header = headerScrollRef.current; + const el = scrollRef.current; + if (header == null || el == null || header.scrollLeft === el.scrollLeft) return; + el.scrollLeft = header.scrollLeft; + }, []); + + // The header scrolls the list sideways, as it has no scrollbar of its own. + const handleHeaderWheel = useCallback((e: WheelEvent) => { + const el = scrollRef.current; + if (el == null || e.deltaX === 0) return; + el.scrollLeft += e.deltaX; + }, []); + + // A dragged column: its ghost, and the others sliding aside to make room for it + const rootRef = useRef(null); + const getScrollElement = useCallback(() => scrollRef.current, []); + const onColumnDrag = useColumnDragView(rootRef, headerScrollRef, scrollRef); // A list too short to scroll still loads older flows on scrolling up. const handleWheel = useCallback( @@ -143,34 +326,71 @@ export function FlowList({ sideBySide, style, className }: Props) { [loadOlderHeld], ); - const select = useCallback( - (index: number) => { - const flow = latest.current.flows[index]; - if (flow == null) return; - setSelectedFlow(flow); - hold(); + /** Scrolls a row into view, to its middle when `center` and it is out of view */ + const scrollToRow = useCallback( + (index: number, center = false) => { const el = scrollRef.current; if (el == null) return; const top = index * ROW_HEIGHT; - if (top < el.scrollTop) setScrollTop(top); - else if (top + ROW_HEIGHT > el.scrollTop + el.clientHeight) { - setScrollTop(top + ROW_HEIGHT - el.clientHeight); - } + const above = top < el.scrollTop; + const below = top + ROW_HEIGHT > el.scrollTop + el.clientHeight; + if (center && (above || below)) setScrollTop(top - (el.clientHeight - ROW_HEIGHT) / 2); + else if (above) setScrollTop(top); + else if (below) setScrollTop(top + ROW_HEIGHT - el.clientHeight); }, - [hold, setSelectedFlow, setScrollTop], + [setScrollTop, ROW_HEIGHT], ); + // A click is a place of its own to go back to; the arrow keys move the current place along. + const select = useCallback( + (index: number, move: "add" | "update") => { + const flow = latest.current.flows[index]; + if (flow == null) return; + goToPlace(store, move, { selection: [flow.id], flow }); + hold(); + scrollToRow(index); + }, + [store, hold, scrollToRow], + ); + const clickRow = useCallback((index: number) => select(index, "add"), [select]); + + // A place gone back to scrolls its flow into view once the list has it. + const [reveal, setReveal] = useAtom(revealFlowAtom); + const placeSelection = useAtomValue(placeSelectionAtom); + useLayoutEffect(() => { + if (reveal == null) return; + // Selected elsewhere since + if (!placeSelection.has(reveal.id)) { + setReveal(null); + return; + } + const index = flows.findIndex((f) => f.id === reveal.id); + if (index === -1) return; + setReveal(null); + hold(); + scrollToRow(index, true); + }, [reveal, placeSelection, flows, hold, scrollToRow, setReveal]); + const handleKeyDown = useCallback( (e: KeyboardEvent) => { + // ⌘↓ catches up, as the pill does. + if (e.metaKey && !e.shiftKey && !e.altKey && e.key === "ArrowDown") { + e.preventDefault(); + follow(); + return; + } if (e.metaKey || e.ctrlKey || e.altKey) return; if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; e.preventDefault(); const index = flows.findIndex((f) => f.id === selectedId); - if (index === -1) select(e.key === "ArrowDown" ? 0 : flows.length - 1); + if (index === -1) select(e.key === "ArrowDown" ? 0 : flows.length - 1, "update"); else if (index === 0 && e.key === "ArrowUp") loadOlderHeld(); - else select(e.key === "ArrowDown" ? index + 1 : index - 1); + else { + if (sorted && index >= flows.length - 2 && e.key === "ArrowDown") void loadMoreSorted(); + select(e.key === "ArrowDown" ? index + 1 : index - 1, "update"); + } }, - [flows, loadOlderHeld, select, selectedId], + [flows, follow, loadOlderHeld, loadMoreSorted, select, selectedId, sorted], ); const openMenu = useCallback( @@ -178,60 +398,109 @@ export function FlowList({ sideBySide, style, className }: Props) { const flow = latest.current.flows[index]; if (flow == null) return; e.preventDefault(); - select(index); - setMenu({ flow, x: e.clientX, y: e.clientY }); + select(index, "add"); + // The cell under the pointer, for the menu's items on its value + const cellEl = (e.target as HTMLElement).closest("[data-column]"); + const column = (cellEl?.dataset.column as ColumnId | undefined) ?? null; + setMenu({ flow, column, x: e.clientX, y: e.clientY }); }, [select], ); - const newCount = following ? 0 : countNewFlows(flows, heldAt); + // A click sorts by the column alone; a third goes back to arrival order, following as Reset + // Sort does. Option-click adds the column to the sort, reverses it, then takes it out. + const handleSort = useCallback( + (column: ColumnId, add: boolean) => { + const current = latest.current.sort; + const next = add ? toggleSortKey(current, column) : nextSort(current, column); + if (next.length === 0) { + follow(); + return; + } + hold(); + setSort(next); + }, + [follow, hold, setSort], + ); - const columns = sideBySide - ? 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]"; + const handleSetSort = useCallback( + (next: FlowSortKey[]) => { + if (next.length === 0) { + follow(); + return; + } + hold(); + setSort(next); + }, + [follow, hold, setSort], + ); + + const menuItems = useMemo((): DropdownItem[] => { + if (menu == null) return []; + // The cell's value first, as it is what was right-clicked + const cell = menu.column == null ? [] : cellActions(menu.flow, menu.column); + return [ + ...(cell.length > 0 ? [...cell, { type: "separator" } as const] : []), + ...flowActions(menu.flow), + exportShown(), + ]; + }, [menu, flowActions, cellActions, exportShown]); + + const newCount = following || sorted ? 0 : countNewFlows(flows, heldAt); + const dividerIndex = divider == null ? -1 : flows.findIndex((f) => f.id === divider.id); + const totalSize = virtualizer.getTotalSize(); return (
- + {/* oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- scrolls the list sideways */}
- - {hasApps && {sideBySide ? "" : "App"}} - Method - Host - Path - Status - {!sideBySide && Type} - {!sideBySide && Size} - Time +
{flows.length === 0 ? ( - +
+ +
) : ( -
+
{virtualizer.getVirtualItems().map((item) => { const flow = flows[item.index]; if (flow == null) return null; @@ -241,15 +510,28 @@ export function FlowList({ sideBySide, style, className }: Props) { flow={flow} index={item.index} start={item.start} + height={ROW_HEIGHT} columns={columns} - sideBySide={sideBySide} - showApp={hasApps} + template={template} selected={flow.id === selectedId} - onSelect={select} + arrivedAt={arrivals.get(flow.id) ?? null} + onSelect={clickRow} onContextMenu={openMenu} /> ); })} + {dividerIndex > 0 && divider != null && ( +
+ + {divider.count === 1 ? "1 new" : `${divider.count} new`} + +
+ )} + {paused && }
)}
@@ -260,7 +542,7 @@ export function FlowList({ sideBySide, style, className }: Props) { className={classNames( "absolute bottom-3 left-1/2 -translate-x-1/2", "flex items-center gap-1.5 h-6 px-3 rounded-full", - "bg-surface border border-border shadow-lg text-text text-xs", + "bg-surface border border-border shadow-lg text-text text-xs tabular-nums", "hover:bg-surface-highlight", )} > @@ -268,36 +550,286 @@ export function FlowList({ sideBySide, style, className }: Props) { {newCount === 1 ? "1 new flow" : `${newCount} new flows`} )} - setMenu(null)} - /> + setMenu(null)} />
); } -/** Nothing to list, or nothing a search matches */ -function EmptyList() { - const query = useAtomValue(activeQueryAtom); - const search = useAtomValue(searchWindowAtom); - if (search?.loading) return null; - return ( -

- {query == null ? "No traffic yet" : "No flows match"} -

+/** + * When each flow that arrived while following came in, for the tint that fades over + * `ARRIVAL_MS`. Only the newest end of the list is checked, back to the first flow already + * known, so a new flow costs the same however many are held. + */ +function useArrivals(flows: Flow[], following: boolean): Map { + const seen = useRef<{ known: Set | null; arrivals: Map }>({ + known: null, + arrivals: new Map(), + }); + // Worked out in the render the new flows cause, rather than in a second one after it. + return useMemo(() => { + const s = seen.current; + if (s.known == null || !following) { + s.known = new Set(flows.map((f) => f.id)); + return s.arrivals; + } + const now = Date.now(); + const arrived: string[] = []; + for (let i = flows.length - 1; i >= 0; i--) { + const flow = flows[i]; + if (flow == null || s.known.has(flow.id)) break; + s.known.add(flow.id); + arrived.push(flow.id); + } + // Kept to the flows held, which the window trims. + if (s.known.size > flows.length * 2) s.known = new Set(flows.map((f) => f.id)); + // A burst renews every row in view, so tinting it says nothing and costs a layer a row. + if (arrived.length === 0 || arrived.length > ARRIVAL_MAX_BATCH) return s.arrivals; + const next = new Map(); + for (const [id, at] of s.arrivals) if (now - at < ARRIVAL_MS) next.set(id, at); + for (const id of arrived) next.set(id, now); + s.arrivals = next; + return next; + }, [flows, following]); +} + +/** How long the columns take to slide aside for a dragged column, or back */ +const SLIDE_MS = 150; + +/** + * Shows a column's drag without rendering a row. Its ghost is its header and the cells of the + * rows in view, copied once when the drag starts and following the pointer sideways. The column + * hides where it is, and the columns between it and where it would drop slide aside by its width + * to leave a gap there, all by one style element: a rule a column, header and cells together, + * which rows arriving meanwhile follow too. Dropped, the rules go as the order changes, in the + * same task, so nothing animates or jumps; put back, the columns slide home first. + */ +function useColumnDragView( + rootRef: RefObject, + headerRef: RefObject, + listRef: RefObject, +): (event: ColumnDragEvent) => void { + const drag = useRef(null); + // Columns sliding home after a drag was put back, until they are there + const settling = useRef<{ style: HTMLStyleElement; timer: number } | null>(null); + + const settle = useCallback(() => { + const s = settling.current; + settling.current = null; + if (s == null) return; + clearTimeout(s.timer); + s.style.remove(); + }, []); + + const onColumnDrag = useCallback( + (event: ColumnDragEvent) => { + const d = drag.current; + switch (event.type) { + case "move": + d?.ghost?.move(event.x); + return; + case "target": + if (d == null) return; + d.to = event.to; + d.style.textContent = columnDragCss(d); + return; + case "end": { + drag.current = null; + if (d == null) return; + d.ghost?.remove(); + if (event.dropped || d.to == null) { + d.style.remove(); + return; + } + d.to = null; + d.style.textContent = columnDragCss(d); + settling.current = { style: d.style, timer: window.setTimeout(settle, SLIDE_MS) }; + return; + } + case "start": { + settle(); + d?.ghost?.remove(); + d?.style.remove(); + drag.current = null; + const root = rootRef.current; + const header = headerRef.current; + const list = listRef.current; + if (root == null || header == null || list == null) return; + const cells = Array.from( + header.querySelectorAll("[data-flow-header] > [data-column]"), + ); + const ids = cells.map((c) => c.dataset.column as ColumnId); + const from = ids.indexOf(event.id); + if (from === -1) return; + // Copied before it hides + const ghost = snapshotColumn(event.id, event.x, root, header, list); + const style = document.createElement("style"); + document.head.append(style); + const widths = cells.map((c) => c.getBoundingClientRect().width); + drag.current = { ghost, ids, widths, from, to: null, style }; + style.textContent = columnDragCss(drag.current); + } + } + }, + [rootRef, headerRef, listRef, settle], ); + + useEffect( + () => () => { + settle(); + drag.current?.ghost?.remove(); + drag.current?.style.remove(); + drag.current = null; + }, + [settle], + ); + return onColumnDrag; +} + +interface ColumnDragView { + ghost: ColumnGhost | null; + /** The columns shown and their widths, the dragged one's place among them, and its target */ + ids: ColumnId[]; + widths: number[]; + from: number; + to: number | null; + style: HTMLStyleElement; +} + +/** The rules for a drag: the column hidden, and those it passes slid aside */ +function columnDragCss({ ids, widths, from, to }: ColumnDragView): string { + // A row's cell is the box in its grid: the column's child, or inside the `contents` span a + // tooltip wraps it in, as a box that is only its contents can't move + const cells = (is: string) => + `[data-flow-rows] ${is} > :not(.contents), [data-flow-rows] ${is} > .contents > *`; + const column = (id: ColumnId) => { + const is = `[data-column="${CSS.escape(id)}"]`; + return `[data-flow-header] > ${is}, ${cells(is)}`; + }; + const rules = [ + `[data-flow-header] > [data-column], ${cells("[data-column]")} { transition: transform ${SLIDE_MS}ms ease; }`, + ]; + const dragged = ids[from]; + if (dragged != null) rules.push(`${column(dragged)} { visibility: hidden; }`); + const shifts = columnShifts(ids.length, from, widths[from] ?? 0, to); + shifts.forEach((dx, i) => { + const id = ids[i]; + if (dx !== 0 && id != null) rules.push(`${column(id)} { transform: translateX(${dx}px); }`); + }); + // A failed flow's reason spans Type and Size together; while they part, it keeps to Type's + // width, so it doesn't slide over the column past Size. + const type = ids.indexOf("type"); + if (type !== -1 && ids[type + 1] === "size") { + const size = type + 1; + if (from === size || shifts[type] !== shifts[size]) { + const is = '[data-flow-rows] [data-column="type"]'; + rules.push( + `${is} > .col-span-2, ${is} > .contents > .col-span-2 { width: ${widths[type] ?? 0}px; }`, + ); + } + } + return rules.join("\n"); +} + +interface ColumnGhost { + /** Follows the pointer, across the window */ + move: (x: number) => void; + remove: () => void; +} + +function snapshotColumn( + id: ColumnId, + startX: number, + root: HTMLElement, + header: HTMLElement, + list: HTMLElement, +): ColumnGhost | null { + const cell = header.querySelector(`[data-column="${id}"]`); + if (cell == null) return null; + const rootBox = root.getBoundingClientRect(); + const cellBox = cell.getBoundingClientRect(); + const listBox = list.getBoundingClientRect(); + const listHeight = list.clientHeight; + + const el = document.createElement("div"); + el.setAttribute("aria-hidden", "true"); + el.className = classNames( + "pointer-events-none absolute top-0 z-20 overflow-hidden rounded-sm", + // Lifted: a shadow, and just enough opacity to read as held, not enough to show text through + "bg-surface border border-border-subtle shadow-lg opacity-95", + ); + Object.assign(el.style, { + left: `${cellBox.left - rootBox.left}px`, + width: `${cellBox.width}px`, + height: `${rootBox.height}px`, + willChange: "transform", + }); + + // The header's label, without its resize handle + const head = place(cellBox.top - rootBox.top, cellBox.height, "text-xs text-text-subtlest"); + const label = cell.cloneNode(true) as HTMLElement; + for (const handle of label.querySelectorAll(".cursor-col-resize")) handle.remove(); + label.style.width = "100%"; + head.append(label); + el.append(head); + + // The rows in view, clipped to the list as it shows them + const rows = document.createElement("div"); + rows.className = "absolute left-0 right-0 overflow-hidden"; + Object.assign(rows.style, { top: `${listBox.top - rootBox.top}px`, height: `${listHeight}px` }); + for (const row of list.querySelectorAll('[role="option"]')) { + const rowBox = row.getBoundingClientRect(); + if (rowBox.bottom <= listBox.top || rowBox.top >= listBox.top + listHeight) continue; + const source = row.querySelector(`[data-column="${id}"]`); + if (source == null) continue; + const copy = place( + rowBox.top - listBox.top, + rowBox.height, + classNames( + "whitespace-nowrap tabular-nums", + row.getAttribute("aria-selected") === "true" && "text-text bg-surface-highlight", + row.classList.contains("text-text-subtlest") && "text-text-subtlest", + ), + ); + for (const child of source.children) { + const clone = child.cloneNode(true) as HTMLElement; + clone.style.width = "100%"; + copy.append(clone); + } + rows.append(copy); + } + el.append(rows); + root.append(el); + + // Kept within the list's visible width + const min = listBox.left; + const max = Math.max(min, listBox.left + list.clientWidth - cellBox.width); + const move = (x: number) => { + const left = Math.min(max, Math.max(min, cellBox.left + x - startX)); + el.style.transform = `translateX(${left - cellBox.left}px)`; + }; + move(startX); + return { move, remove: () => el.remove() }; +} + +/** A line of the ghost, `top` pixels down its box */ +function place(top: number, height: number, className: string): HTMLElement { + const el = document.createElement("div"); + el.className = classNames("absolute left-0 right-0 flex items-center", className); + Object.assign(el.style, { top: `${top}px`, height: `${height}px` }); + return el; } interface RowProps { flow: Flow; index: number; start: number; - columns: string; - sideBySide: boolean; - showApp: boolean; + height: number; + columns: Column[]; + template: string; selected: boolean; + /** When it arrived while following, for its tint, or null */ + arrivedAt: number | null; onSelect: (index: number) => void; onContextMenu: (index: number, e: MouseEvent) => void; } @@ -306,18 +838,22 @@ const FlowRow = memo(function FlowRow({ flow, index, start, + height, columns, - sideBySide, - showApp, + template, selected, + arrivedAt, onSelect, onContextMenu, }: RowProps) { - const { host, path, query } = splitUrl(flow.url); const failed = flow.error != null; // Failed or cancelled before any response; after the headers, the body was cut short mid-way. const noResponse = (failed || flow.cancelled) && flow.status == null; - const type = shortContentType(flow.contentType); + const ids = columns.map((c) => c.id); + // A failure's reason, or Cancelled, takes the type and size cells together, side by side. + const typeAt = ids.indexOf("type"); + const spanReason = noResponse && typeAt !== -1 && ids[typeAt + 1] === "size"; + const sinceArrival = arrivedAt == null ? null : Date.now() - arrivedAt; return (
onContextMenu(index, e)} - style={{ height: ROW_HEIGHT, transform: `translateY(${start}px)` }} + style={{ + height, + transform: `translateY(${start}px)`, + gridTemplateColumns: template, + // Continues the fade where it was when a row scrolls back into view. + ...(sinceArrival != null && sinceArrival < ARRIVAL_MS + ? { animationDelay: `-${sinceArrival}ms` } + : {}), + }} className={classNames( - columns, - "absolute top-0 inset-x-0 grid items-center gap-x-3 px-1.5 rounded-md whitespace-nowrap", - "[&>*]:overflow-hidden [&>*]:text-ellipsis [&>*]:min-w-0", + "absolute top-0 left-1.5 right-1.5 grid items-center px-1.5 rounded-md whitespace-nowrap", + "tabular-nums", + flow.cancelled && "text-text-subtlest", selected ? "text-text bg-surface-highlight group-focus-within/flows:bg-surface-active" - : index % 2 === 1 && "bg-surface-highlight/30", + : "hover:bg-surface-highlight/50", + sinceArrival != null && sinceArrival < ARRIVAL_MS && !selected && "flow-arrived", )} > - - {flow.savedRequestId != null ? ( - - ) : failed ? ( - - ) : flow.cancelled ? ( - - ) : flow.responseTruncated ? ( - - ) : null} - - {showApp && ( - - {flow.clientPath != null && } - {!sideBySide && ( - - {flow.clientName ?? --} - - )} - - )} - - {host} - - {path} - {query} - - {flow.cancelled && flow.status == null ? ( - -- - ) : ( - - )} - {!sideBySide && - (failed ? ( - - {flow.error} - - ) : flow.cancelled ? ( - Cancelled - ) : ( - - {type ?? --} - - ))} - {!sideBySide && ( - - {noResponse ? ( - -- - ) : ( - formatSize(flow.responseSize) - )} - - )} - - {flow.elapsedMs == null ? "--" : formatMillis(flow.elapsedMs)} - + + {columns.map((c) => { + if (spanReason && c.id === "size") return null; + return ( + // Names the cell's column for its menu, without a box of its own in the row's grid +
+ +
+ ); + })}
); }); -function splitUrl(url: string): { host: string; path: string; query: string } { - try { - const u = new URL(url); - return { host: u.host, path: u.pathname, query: u.search }; - } catch { - return { host: "", path: url, query: "" }; +/** + * One mark per row, by a fixed priority: failed, cancelled, not decrypted, streaming, cut, saved. + * Its tooltip lists every state the flow has. Agent reads join it once the engine records them. + */ +function FlowMark({ flow }: { flow: Flow }) { + const open = isOpenStream(flow); + const states: string[] = []; + if (flow.error != null) states.push(`Failed: ${flow.error}`); + if (flow.cancelled) states.push("Cancelled by the app"); + if (flow.tunnelled) states.push("Not decrypted"); + if (open) states.push("Streaming"); + if (flow.responseTruncated) states.push("Body cut at the capture limit"); + if (flow.savedRequestId != null) states.push("Saved to Yaak"); + const mark = ( + + {flow.error != null ? ( + + ) : flow.cancelled ? ( + + ) : flow.tunnelled ? ( + + ) : open ? ( + + ) : flow.responseTruncated ? ( + + ) : flow.savedRequestId != null ? ( + + ) : null} + + ); + if (states.length === 0) return mark; + return ( + + {mark} + + ); +} + +const mono = "font-mono text-xs"; + +/** Every cell: its padding matching the header's, and its text cut short at its width */ +const cell = "min-w-0 px-1.5 overflow-hidden text-ellipsis"; + +/** A cell with its full text in a tooltip, shown when the cell cuts it short */ +function Truncated({ text, children }: { text: string; children: ReactElement }) { + return ( + + {children} + + ); +} + +/** An undecrypted tunnel still open: written as it opens, done once it closes */ +function isOpenTunnel(flow: Flow): boolean { + return flow.tunnelled && flow.elapsedMs == null && flow.error == null; +} + +/** A WebSocket, event stream or gRPC call still open: written as it opens, done once it ends */ +function isOpenStream(flow: Flow): boolean { + return flow.streamKind != null && flow.elapsedMs == null && flow.error == null && !flow.cancelled; +} + +function FlowCell({ column, flow, span }: { column: ColumnId; flow: Flow; span: boolean }) { + const failed = flow.error != null; + const noResponse = (failed || flow.cancelled) && flow.status == null; + switch (column) { + case "number": + return ( + {flow.number || ""} + ); + case "app": { + if (flow.clientPath == null) return ; + const name = flow.clientName ?? flow.clientPath; + // A program outside an app says which folder it ran in, in full. + const folder = folderOf(flow) == null ? null : flow.clientCwd; + return ( + + + + + + ); + } + case "method": + return ( + + ); + case "host": { + const host = hostOf(flow.url); + // Cut from the front, so the part that names the service stays. + return ( + + + {host} + + + ); + } + case "path": { + // A tunnel's only path is its host; what it carried is unread. + if (flow.tunnelled) { + return Not decrypted; + } + const path = pathOf(flow.url); + if (flow.streamKind == null) { + return ( + + {path} + + ); + } + // A stream's message count rides the end of the path, so it survives the narrow width, + // ticking while the stream is open. + return ( + + + {path} + + + + ); + } + case "status": + return (flow.cancelled || flow.tunnelled) && flow.status == null ? ( + -- + ) : ( + + ); + case "type": + return failed && noResponse ? ( + + + {flow.error} + + + ) : flow.cancelled && noResponse ? ( + Cancelled + ) : ( + + {shortContentType(flow.contentType) ?? "--"} + + ); + case "size": + return ( + + {noResponse ? "--" : formatSize(flow.responseSize)} + + ); + case "time": + // An open stream or tunnel shows how long it has been open, quietly, as its messages land. + if (isOpenStream(flow) || isOpenTunnel(flow)) { + const open = Date.now() - Date.parse(utcTimestamp(flow.startedAt)); + return ( + + {Number.isFinite(open) ? formatMillis(Math.max(0, open)) : "--"} + + ); + } + return ( + = 1000 && !flow.cancelled + ? "text-text" + : "text-text-subtle", + )} + > + {flow.elapsedMs == null ? "--" : formatMillis(flow.elapsedMs)} + + ); + case "remote": + return ( + + {flow.remoteAddr ?? "--"} + + ); + case "version": + return ( + + {flow.upstreamHttpVersion ?? flow.clientHttpVersion} + + ); + case "query": { + const query = flow.tunnelled ? "" : (urlParts(flow.url).query ?? ""); + return ( + + {query} + + ); + } + case "started": { + const at = new Date(utcTimestamp(flow.startedAt)); + if (Number.isNaN(at.getTime())) return ; + return ( + + {clockTime(at)} + + ); + } + case "requestSize": + return ( + + {flow.requestSize === 0 ? "--" : formatSize(flow.requestSize)} + + ); + case "latency": + return ( + + {flow.elapsedHeadersMs == null ? "--" : formatMillis(flow.elapsedHeadersMs)} + + ); + case "tls": + return ( + {tlsVersionOf(flow)} + ); + case "operation": { + const operation = operationOf(flow) ?? ""; + return ( + + {operation} + + ); + } + default: { + if (!isCustomColumn(column)) return ; + const value = customValue(flow, column.slice("field:".length)) ?? ""; + return ( + + {value} + + ); + } + } +} + +/** The URL's path as the browser reads it, `/` for none, without the query */ +function pathOf(url: string): string { + try { + return new URL(url).pathname; + } catch { + return url; + } +} + +/** `14:03:27.481`, in local time */ +function clockTime(at: Date): string { + const two = (n: number) => String(n).padStart(2, "0"); + const ms = String(at.getMilliseconds()).padStart(3, "0"); + return `${two(at.getHours())}:${two(at.getMinutes())}:${two(at.getSeconds())}.${ms}`; +} + +/** + * The items a cell's menu adds for its value: a search term for it, either way, where its column + * has a field to match it by, applied at once, and copying it + */ +function useCellActions(): (flow: Flow, column: ColumnId) => DropdownItem[] { + const store = useStore(); + const showToast = useShowToast(); + return useCallback( + (flow: Flow, column: ColumnId) => { + const add = (term: string) => { + // A search with `OR` at its top is grouped first, so the term narrows all of it. + const text = store.get(appliedFilterAtom).trim(); + applyFilter(store, text === "" ? term : `${asOneTerm(text)} ${term}`); + }; + const include = cellFilterTerm(flow, column, false); + const exclude = cellFilterTerm(flow, column, true); + const value = cellText(flow, column); + const items: DropdownItem[] = []; + if (include != null && exclude != null) { + items.push( + { label: "Filter by This Value", icon: "filter", onSelect: () => add(include) }, + { label: "Exclude This Value", icon: "minus_circle", onSelect: () => add(exclude) }, + ); + } + if (value !== "") { + items.push({ + label: "Copy Value", + icon: "copy", + onSelect: async () => { + try { + await navigator.clipboard.writeText(value); + showToast({ message: "Copied value" }); + } catch (err) { + showToast({ message: `Failed to copy value: ${String(err)}`, color: "danger" }); + } + }, + }); + } + return items; + }, + [store, showToast], + ); +} + +/** A cell's value as text, as it shows it, for copying */ +function cellText(flow: Flow, column: ColumnId): string { + if (isCustomColumn(column)) return customValue(flow, column.slice("field:".length)) ?? ""; + switch (column) { + case "number": + return flow.number ? String(flow.number) : ""; + case "app": + return flow.clientName ?? flow.clientPath ?? ""; + case "method": + return flow.method; + case "host": + return hostOf(flow.url); + case "path": + return flow.tunnelled ? "" : pathOf(flow.url); + case "query": + return flow.tunnelled ? "" : (urlParts(flow.url).query ?? ""); + case "status": + return flow.status == null ? "" : String(flow.status); + case "type": + return flow.contentType ?? ""; + case "size": + return String(flow.responseSize); + case "requestSize": + return String(flow.requestSize); + case "time": + return flow.elapsedMs == null ? "" : String(flow.elapsedMs); + case "latency": + return flow.elapsedHeadersMs == null ? "" : String(flow.elapsedHeadersMs); + case "started": { + const at = new Date(utcTimestamp(flow.startedAt)); + return Number.isNaN(at.getTime()) ? "" : at.toISOString(); + } + case "remote": + return flow.remoteAddr ?? ""; + case "version": + return flow.upstreamHttpVersion ?? flow.clientHttpVersion; + case "tls": + return tlsVersionOf(flow); + case "operation": + return operationOf(flow) ?? ""; } } diff --git a/apps/yaak-proxy/components/FlowListEmpty.tsx b/apps/yaak-proxy/components/FlowListEmpty.tsx new file mode 100644 index 000000000..1b71d059f --- /dev/null +++ b/apps/yaak-proxy/components/FlowListEmpty.tsx @@ -0,0 +1,116 @@ +import { EmptyStateText, Hotkey, Icon, InlineCode } from "@yaakapp-internal/ui"; +import classNames from "classnames"; +import { useAtomValue, useStore } from "jotai"; +import { useEffect, useState } from "react"; +import { appliedFilterAtom } from "../lib/atoms"; +import { applyFilter } from "../lib/navigation"; +import { rpc } from "../lib/rpc"; +import { activeQuery, widerQueries } from "../lib/query"; +import { hideSystemAtom, pausedAtAtom, proxyStateAtom, searchWindowAtom } from "../lib/store"; + +/** Nothing to list: no flows yet, recording paused, or a query nothing matches */ +export function FlowListEmpty() { + const text = useAtomValue(appliedFilterAtom); + const search = useAtomValue(searchWindowAtom); + const proxyState = useAtomValue(proxyStateAtom); + if (search?.loading) return null; + if (text.trim() !== "") return ; + + const other = proxyState?.otherOwner ?? null; + const port = proxyState?.port ?? other?.proxyPort ?? null; + const running = proxyState?.state === "running" || other != null; + const recording = proxyState?.recording !== false; + return ( + +
{recording ? "No flows yet" : "Recording is paused"}
+
+ {!running + ? "The proxy is not running. Retry from the menu by the state." + : !recording + ? "Traffic passes through without being stored." + : `Recording on port ${port ?? "--"}. Flows appear as apps send requests.`} +
+
+ ); +} + +/** + * The list's last row while recording is paused, where the next flow would appear: since when, + * and that nothing is stored. + */ +export function PausedRow({ style }: { style?: React.CSSProperties }) { + const pausedAt = useAtomValue(pausedAtAtom); + return ( +
+ + + {pausedAt == null ? "Paused." : `Paused at ${timeOf(pausedAt)}.`} Traffic passes through + without being stored. + + +
+ ); +} + +/** + * A query nothing matches: wider ones that do, each the query with one term left out, as Yaak's + * sidebar answers, with how many each would match. + */ +function NoResults({ text }: { text: string }) { + const hideSystem = useAtomValue(hideSystemAtom); + const store = useStore(); + const setText = (wider: string) => applyFilter(store, wider); + const [wider, setWider] = useState<{ text: string; count: number }[]>([]); + + useEffect(() => { + let current = true; + const candidates = widerQueries(text); + void Promise.all( + candidates.map(async (candidate) => { + const query = activeQuery(candidate, hideSystem); + const res = await rpc("list_flows", { ...query, limit: 0 }); + return { text: candidate, count: query == null ? res.total : (res.matching ?? res.total) }; + }), + ) + .then((found) => { + if (current) setWider(found.filter((f) => f.count > 0).slice(0, 3)); + }) + .catch(() => { + if (current) setWider([]); + }); + return () => { + current = false; + }; + }, [text, hideSystem]); + + return ( + +
+ No flows match. + {wider.length > 0 && " Found matches for "} + {wider.map((w, i) => ( + + {i > 0 && (i === wider.length - 1 ? ", or " : ", ")} + {" "} + ({w.count.toLocaleString()}) + + ))} +
+
+ ); +} + +function timeOf(ms: number): string { + return new Date(ms).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }); +} diff --git a/apps/yaak-proxy/components/FlowListHeader.tsx b/apps/yaak-proxy/components/FlowListHeader.tsx new file mode 100644 index 000000000..869cc7805 --- /dev/null +++ b/apps/yaak-proxy/components/FlowListHeader.tsx @@ -0,0 +1,541 @@ +import { + DndContext, + type DragStartEvent, + PointerSensor, + useDraggable, + useSensor, + useSensors, +} from "@dnd-kit/core"; +import type { FlowSortKey } from "@yaakapp-internal/proxy-lib"; +import { + ContextMenu, + Dropdown, + type DropdownItem, + Icon, + IconButton, + ResizeHandle, +} from "@yaakapp-internal/ui"; +import classNames from "classnames"; +import { useAtomValue, useSetAtom } from "jotai"; +import { + memo, + type MouseEvent, + type PointerEvent as ReactPointerEvent, + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, +} from "react"; +import { + addSortKey, + allColumns, + type Column, + type ColumnDef, + type ColumnId, + type ColumnPrefs, + type CustomColumnId, + canHide, + dropBoundary, + hideOtherColumns, + isCustomColumn, + moveColumn, + moveColumnBy, + removeCustomColumn, + resetOrder, + resetWidth, + resetWidths, + resizeColumn, + toggleColumn, + unavailableColumns, +} from "../lib/columns"; +import { columnPrefsAtom, hasAppsAtom } from "../lib/store"; +import { addColumnDialogAtom } from "./AddColumnDialog"; + +/** Pixels a press on a label moves before it drags the column rather than sorting by it */ +const DRAG_DISTANCE = 4; +/** How near the list's side edge, in pixels, a dragged column scrolls the list that way */ +const EDGE = 40; +/** The most the list scrolls sideways a frame, at the very edge */ +const EDGE_SPEED = 18; + +interface Props { + columns: Column[]; + template: string; + /** The rows' width, as CSS, so the header scrolls sideways with them */ + width: string; + prefs: ColumnPrefs; + sort: FlowSortKey[]; + /** A click on a label, or with `add`, an Option-click */ + onSort: (column: ColumnId, add: boolean) => void; + /** Sets the sort from the menus; empty goes back to arrival order */ + onSetSort: (sort: FlowSortKey[]) => void; + onResetSort: () => void; + /** The rows' scrolling element, which a column dragged to its edge scrolls sideways */ + scrollElement: () => HTMLElement | null; + /** A column's drag, for the list to show: its ghost, and the columns making room for it */ + onColumnDrag: (event: ColumnDragEvent) => void; +} + +/** + * A column's drag: its start, the pointer's moves (`x`, across the window), the boundary it + * would drop at when that changes (`to`, null where it would stay), and its end, dropped there + * or put back + */ +export type ColumnDragEvent = + | { type: "start"; id: ColumnId; x: number } + | { type: "move"; x: number } + | { type: "target"; to: number | null } + | { type: "end"; dropped: boolean }; + +/** + * The list's only control surface: a click on a label sorts by it alone, a second reverses it + * and a third goes back to arrival order; Option-click adds it to the sort as a further key. + * Dragging a label moves its column, and Escape puts it back. Dragging the edge after a label + * resizes its column and a double-click on it resets it. A right-click on a label opens the + * column's menu; the picker sits in the empty corner on hover. + */ +export const FlowListHeader = memo(function FlowListHeader({ + columns, + template, + width, + prefs, + sort, + onSort, + onSetSort: setSort, + onResetSort, + scrollElement, + onColumnDrag, +}: Props) { + const setPrefs = useSetAtom(columnPrefsAtom); + const unavailable = unavailableColumns(useAtomValue(hasAppsAtom)); + const openAddColumn = useSetAtom(addColumnDialogAtom); + const [menu, setMenu] = useState<{ x: number; y: number; column: ColumnDef | null } | null>(null); + // Widths when a drag began, so each move sets the width from where it started. + const startWidth = useRef(0); + const { sensors, dndHandlers, gridRef, onPointerDownCapture } = useColumnDrag({ + columns, + scrollElement, + onColumnDrag, + onDrop: (id, to) => setPrefs((p) => moveColumn(p, id, to, unavailable)), + }); + + // Taking out the sort's only key goes back to arrival order, as Reset Sort does + const removeColumn = (id: CustomColumnId) => { + if (sort.length > 0 && sort.every((k) => k.column === id)) onResetSort(); + setPrefs((p) => removeCustomColumn(p, id)); + }; + + const pickerItems: DropdownItem[] = [ + { + type: "content", + label:
Columns
, + }, + ...allColumns(prefs).map((c): DropdownItem => { + const shown = prefs.visible[c.id] ?? c.defaultVisible; + return { + label: c.label, + keepOpenOnSelect: true, + disabled: shown && !canHide(prefs, c.id, unavailable), + leftSlot: shown ? ( + + ) : ( + + ), + onSelect: () => setPrefs((p) => toggleColumn(p, c.id, unavailable)), + ...(isCustomColumn(c.id) + ? { + submenuTrigger: "button" as const, + submenu: [ + { + label: "Remove Column", + icon: "trash" as const, + color: "danger" as const, + onSelect: () => removeColumn(c.id as CustomColumnId), + }, + ], + } + : {}), + }; + }), + { label: "Add Column…", icon: "plus", onSelect: () => openAddColumn(true) }, + { type: "separator" }, + { label: "Reset Sort", disabled: sort.length === 0, onSelect: onResetSort }, + { label: "Reset Column Widths", onSelect: () => setPrefs((p) => resetWidths(p)) }, + { + label: "Reset Column Order", + disabled: prefs.order.length === 0, + onSelect: () => setPrefs((p) => resetOrder(p)), + }, + ]; + + const columnItems = (c: ColumnDef): DropdownItem[] => { + const sortBy = (descending: boolean) => setSort([{ column: c.id, descending }]); + const addTo = (descending: boolean) => setSort(addSortKey(sort, c.id, descending)); + const at = columns.findIndex((col) => col.id === c.id); + return [ + { label: "Sort Ascending", onSelect: () => sortBy(false) }, + { label: "Sort Descending", onSelect: () => sortBy(true) }, + { label: "Add to Sort Ascending", onSelect: () => addTo(false) }, + { label: "Add to Sort Descending", onSelect: () => addTo(true) }, + { label: "Clear Sorting", disabled: sort.length === 0, onSelect: onResetSort }, + { type: "separator" }, + { + label: "Move Left", + disabled: at <= 0, + onSelect: () => setPrefs((p) => moveColumnBy(p, c.id, -1, unavailable)), + }, + { + label: "Move Right", + disabled: at === -1 || at >= columns.length - 1, + onSelect: () => setPrefs((p) => moveColumnBy(p, c.id, 1, unavailable)), + }, + { type: "separator" }, + { + label: "Hide Column", + disabled: !canHide(prefs, c.id, unavailable), + onSelect: () => setPrefs((p) => toggleColumn(p, c.id, unavailable)), + }, + { + label: "Hide Other Columns", + disabled: columns.length <= 1, + onSelect: () => setPrefs((p) => hideOtherColumns(p, c.id)), + }, + ...(isCustomColumn(c.id) + ? [ + { + label: "Remove Column", + color: "danger" as const, + onSelect: () => removeColumn(c.id as CustomColumnId), + }, + ] + : []), + { type: "separator" }, + { label: "Reset Column Widths", onSelect: () => setPrefs((p) => resetWidths(p)) }, + ]; + }; + + // A right-click on a label is for its column; anywhere else in the header, the picker. + const openMenu = useCallback( + (e: MouseEvent) => { + e.preventDefault(); + const el = (e.target as HTMLElement).closest("[data-column]"); + const id = el?.dataset.column as ColumnId | undefined; + const column = columns.find((c) => c.id === id) ?? null; + setMenu({ x: e.clientX, y: e.clientY, column }); + }, + [columns], + ); + + return ( + // The same margins and padding as the rows, so each label sits over its cells. +
+ {/* oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- a right-click opens the column's menu */} +
+ + + + + + + {columns.map((c) => ( + { + startWidth.current = c.current; + }} + onResizeMove={(dx) => setPrefs((p) => resizeColumn(p, c.id, startWidth.current + dx))} + onResetWidth={() => setPrefs((p) => resetWidth(p, c.id))} + /> + ))} + + setMenu(null)} + /> +
+
+ ); +}); + +interface HeaderCellProps { + column: Column; + sort: FlowSortKey[]; + onSort: (column: ColumnId, add: boolean) => void; + onResizeStart: () => void; + /** How far the edge moved since the resize began */ + onResizeMove: (dx: number) => void; + onResetWidth: () => void; +} + +function HeaderCell({ + column: c, + sort, + onSort, + onResizeStart, + onResizeMove, + onResetWidth, +}: HeaderCellProps) { + // The label drags the column; the resize handle beside it is outside it, so it still resizes. + const { listeners, setNodeRef } = useDraggable({ id: c.id }); + const sorted = sort.some((k) => k.column === c.id); + return ( + + + {/* On the column's right edge, the boundary with the next, resizing this one */} + onResizeMove(e.x - e.xStart)} + onReset={onResetWidth} + /> + + ); +} + +/** A column's name, after its sort direction and, sorted by several, its place in the sort */ +function ColumnLabel({ column: c, sort }: { column: Column; sort: FlowSortKey[] }) { + const at = sort.findIndex((k) => k.column === c.id); + const key = sort[at]; + return ( + <> + {key != null && ( + + )} + {key != null && sort.length > 1 && ( + {at + 1} + )} + {c.id === "app" ? "" : c.label} + + ); +} + +/** + * Dragging a column's label: where it would drop, the boundary between the labels nearest the + * pointer as they were laid out when the drag began, and the list scrolling sideways while the + * pointer is near its edge. The list shows the drag; the columns only change order on the drop, + * so the rows lay out once. + */ +function useColumnDrag({ + columns, + scrollElement, + onColumnDrag, + onDrop, +}: { + columns: Column[]; + scrollElement: () => HTMLElement | null; + onColumnDrag: (event: ColumnDragEvent) => void; + /** Moves the column to the boundary `to` between those shown */ + onDrop: (id: ColumnId, to: number) => void; +}) { + const sensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: DRAG_DISTANCE } }), + ); + const gridRef = useRef(null); + // Live while dragging, read each frame + const state = useRef<{ + /** The column dragged, and its place among those shown */ + id: ColumnId; + from: number; + /** The labels' edges when the drag began, from the header's left, as the columns slide */ + cells: { left: number; right: number }[]; + /** The columns shown when it began, which the edges and `from` describe */ + shown: string; + /** The pointer, across the window */ + x: number; + /** The boundary it would move to, null where it would stay */ + to: number | null; + /** The pointer the ghost was last moved to */ + ghostX: number; + frame: number; + } | null>(null); + const latest = useRef({ columns, scrollElement, onColumnDrag, onDrop }); + useLayoutEffect(() => { + latest.current = { columns, scrollElement, onColumnDrag, onDrop }; + }); + + /** Ends the drag, dropped or put back */ + const stop = useCallback((dropped: boolean) => { + const s = state.current; + state.current = null; + if (s == null) return null; + cancelAnimationFrame(s.frame); + latest.current.onColumnDrag({ type: "end", dropped }); + return s; + }, []); + + const onDragStart = useCallback((e: DragStartEvent) => { + const grid = gridRef.current; + const from = latest.current.columns.findIndex((c) => c.id === e.active.id); + if (grid == null || from === -1) return; + const id = e.active.id as ColumnId; + const x = pointer.current; + // First, as it ends the last drag's columns sliding home, so the edges read below are where + // the columns are laid out, not where they were sliding + latest.current.onColumnDrag({ type: "start", id, x }); + const gridLeft = grid.getBoundingClientRect().left; + const cells = Array.from(grid.querySelectorAll(":scope > [data-column]")).map( + (el) => { + const box = el.getBoundingClientRect(); + return { left: box.left - gridLeft, right: box.right - gridLeft }; + }, + ); + const shown = shownKey(latest.current.columns); + state.current = { id, from, cells, shown, x, to: null, ghostX: x, frame: 0 }; + target(state.current); + + const tick = () => { + const s = state.current; + if (s == null) return; + // Near an edge, the list scrolls that way, faster the nearer; the header follows it. + const list = latest.current.scrollElement(); + if (list != null) { + const { left, right } = list.getBoundingClientRect(); + const near = + s.x < left + EDGE ? s.x - left - EDGE : s.x > right - EDGE ? s.x - right + EDGE : 0; + if (near !== 0) { + const speed = Math.min(1, Math.abs(near) / EDGE) * EDGE_SPEED; + list.scrollLeft += Math.sign(near) * Math.max(1, speed); + } + } + target(s); + if (s.x !== s.ghostX) { + s.ghostX = s.x; + latest.current.onColumnDrag({ type: "move", x: s.x }); + } + s.frame = requestAnimationFrame(tick); + }; + state.current.frame = requestAnimationFrame(tick); + // oxlint-disable-next-line react-hooks/exhaustive-deps -- `target` reads only refs + }, []); + + /** Drops the column where the pointer is, once; a second call finds no drag */ + const drop = useCallback(() => { + // Where the pointer is now, as a release can come before the next frame reads it + if (state.current != null) target(state.current); + // The list lets go of the drag and the order changes in the same task, so nothing jumps. + const s = stop(true); + if (s?.to != null) latest.current.onDrop(s.id, s.to); + // oxlint-disable-next-line react-hooks/exhaustive-deps -- `target` reads only refs + }, [stop]); + const cancel = useCallback(() => { + stop(false); + }, [stop]); + + // Columns shown or hidden under a drag, as App is when the first flow with an app arrives, + // leave its edges and target describing columns that are gone; it is put back instead. + const shown = shownKey(columns); + useEffect(() => { + if (state.current != null && state.current.shown !== shown) cancel(); + }, [shown, cancel]); + + // The pointer from a press on the header until its release, read before dnd-kit sees it. + // dnd-kit starts a drag on the move that crosses `DRAG_DISTANCE` and reports moves and the + // release only once it has rendered the drag, so a release right after a move would drop + // where the pointer was a frame before, or not at all. The release drops it here instead. + const pointer = useRef(0); + const track = useCallback((e: PointerEvent) => { + pointer.current = e.clientX; + if (state.current != null) state.current.x = e.clientX; + }, []); + const unlisten = useRef<(() => void) | null>(null); + const onPointerDownCapture = useCallback( + (e: ReactPointerEvent) => { + unlisten.current?.(); + pointer.current = e.clientX; + const up = (e: PointerEvent) => { + unlisten.current?.(); + track(e); + drop(); + }; + const lost = () => { + unlisten.current?.(); + cancel(); + }; + window.addEventListener("pointermove", track, true); + window.addEventListener("pointerup", up, true); + window.addEventListener("pointercancel", lost, true); + unlisten.current = () => { + unlisten.current = null; + window.removeEventListener("pointermove", track, true); + window.removeEventListener("pointerup", up, true); + window.removeEventListener("pointercancel", lost, true); + }; + }, + [track, drop, cancel], + ); + + // A drag never outlives the header + useEffect( + () => () => { + unlisten.current?.(); + cancel(); + }, + [cancel], + ); + + /** Sets where the drag would drop, telling the list when that changes */ + function target(s: NonNullable) { + const gridLeft = gridRef.current?.getBoundingClientRect().left ?? 0; + const cells = s.cells.map((c) => ({ left: gridLeft + c.left, right: gridLeft + c.right })); + const to = dropBoundary(s.x, cells, s.from); + if (to === s.to) return; + s.to = to; + latest.current.onColumnDrag({ type: "target", to }); + } + + return { + sensors, + gridRef, + onPointerDownCapture, + dndHandlers: { onDragStart, onDragEnd: drop, onDragCancel: cancel }, + }; +} + +/** Which columns show, in order, to tell when that changes */ +function shownKey(columns: Column[]): string { + return columns.map((c) => c.id).join(" "); +} diff --git a/apps/yaak-proxy/components/FlowMessages.tsx b/apps/yaak-proxy/components/FlowMessages.tsx new file mode 100644 index 000000000..d80663389 --- /dev/null +++ b/apps/yaak-proxy/components/FlowMessages.tsx @@ -0,0 +1,131 @@ +import type { Flow } from "@yaakapp-internal/proxy-lib"; +import { + type EventStreamColumns, + EventStreamViewer, + HStack, + type StreamEvent, + type StreamPayloadView, +} from "@yaakapp-internal/ui"; +import { useCallback, useMemo } from "react"; +import { useFlowMessages, useMessageSource } from "../hooks/useFlowMessages"; +import { base64ToBytes } from "../lib/body"; +import { grpcStatusText, messageToStreamEvent, streamIsOpen } from "../lib/messages"; + +const WEBSOCKET_COLUMNS: EventStreamColumns = { + direction: true, + kind: "Type", + preview: "Message", + size: true, + time: true, +}; +const SSE_COLUMNS: EventStreamColumns = { + kind: "Event", + kindWidth: "9.5rem", + preview: "Data", + size: true, + time: true, +}; +const GRPC_COLUMNS: EventStreamColumns = { + direction: true, + kind: "Type", + preview: "Message", + size: true, + time: true, +}; + +/** + * A streaming flow's messages: a WebSocket's frames, an event stream's events, a gRPC call's + * messages and status, following new ones while the stream is open. The selected message's + * payload opens below as text or a hexdump; a gRPC message's also decoded, with its schema or + * without one. + */ +export function FlowMessages({ flow }: { flow: Flow }) { + const source = useMessageSource(); + const { messages, loading, error } = useFlowMessages(flow.id, source, flow.messageCount); + const events = useMemo(() => messages.map(messageToStreamEvent), [messages]); + const kind = flow.streamKind; + const grpc = kind === "grpc" || kind === "grpc_web"; + const columns = kind === "sse" ? SSE_COLUMNS : grpc ? GRPC_COLUMNS : WEBSOCKET_COLUMNS; + const noun = kind === "sse" ? "Event" : "Message"; + const catchUp = useMemo( + () => ({ + label: (count: number) => `${count} new ${noun.toLowerCase()}${count === 1 ? "" : "s"}`, + }), + [noun], + ); + + const loadPayload = useCallback( + async (event: StreamEvent) => { + const res = await source.payload(flow.id, Number(event.key)); + return { bytes: base64ToBytes(res.data) }; + }, + [flow.id, source], + ); + + const payloadViews = useCallback( + (event: StreamEvent): StreamPayloadView[] | null => { + if (!grpc || event.direction === "info") return null; + const decode = (schemaless: boolean) => async () => { + const decoded = await source.decodeGrpc(flow.id, Number(event.key), schemaless); + const note = [ + decoded.messageType == null ? null : `Decoded as ${decoded.messageType}`, + decoded.note, + ] + .filter(Boolean) + .join(". "); + return { text: decoded.json, language: "json" as const, note: note || null }; + }; + return [ + { value: "decoded", label: "Decoded", type: "text", load: decode(false) }, + { value: "schemaless", label: "Schemaless", type: "text", load: decode(true) }, + { value: "raw", label: "Raw bytes", type: "hexdump" }, + ]; + }, + [flow.id, grpc, source], + ); + + const open = streamIsOpen(flow); + const count = Math.max(flow.messageCount, messages.length); + const header = ( + + {kind === "websocket" && ( + <> + {open ? ( + CONNECTED + ) : flow.error != null ? ( + ERROR + ) : ( + CLOSED + )} + • + + )} + + {count} {count === 1 ? noun : `${noun}s`} + + {grpc && flow.grpcStatus != null && ( + <> + • + + {grpcStatusText(flow.grpcStatus, flow.grpcMessage)} + + + )} + + ); + + return ( + + ); +} diff --git a/apps/yaak-proxy/components/FlowRequestBody.test.tsx b/apps/yaak-proxy/components/FlowRequestBody.test.tsx new file mode 100644 index 000000000..cc4b54f44 --- /dev/null +++ b/apps/yaak-proxy/components/FlowRequestBody.test.tsx @@ -0,0 +1,54 @@ +import type { ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, test, vi } from "vite-plus/test"; +import type { FlowBodyData } from "../lib/flowViews"; +import { FlowRequestBody } from "./FlowRequestBody"; + +// The package's index reaches for the window as it loads; these three are all this renders. +vi.mock("@yaakapp-internal/ui", () => ({ + Banner: ({ children, color }: { children: ReactNode; color?: string }) => ( +
{children}
+ ), + EmptyStateText: ({ children }: { children: ReactNode }) =>
{children}
, + LoadingIcon: () => LOADING, + CONTROL_TOOLTIP_DELAY: 0, + Tooltip: ({ children }: { children: ReactNode }) => <>{children}, +})); + +const data = (truncated = false): FlowBodyData => ({ + bytes: new TextEncoder().encode('{"a":1}'), + truncated, + storedSize: 7, +}); + +function render(body: Parameters[0]["body"]) { + return renderToStaticMarkup( + EDITOR
} requestSize={2048} />, + ); +} + +describe("FlowRequestBody", () => { + test("a body that failed to load says why, not that there is none", () => { + const html = render({ data: undefined, isLoading: false, error: new Error("Key unavailable") }); + expect(html).toContain('data-banner="danger"'); + expect(html).toContain("Key unavailable"); + expect(html).not.toContain("EDITOR"); + }); + + test("shows it is loading while the body is read", () => { + const html = render({ data: undefined, isLoading: true, error: null }); + expect(html).not.toContain("EDITOR"); + expect(html).toContain("LOADING"); + }); + + test("the viewer once loaded", () => { + expect(render({ data: data(), isLoading: false, error: null })).toContain("EDITOR"); + }); + + test("a cut body says how much was kept", () => { + const html = render({ data: data(true), isLoading: false, error: null }); + expect(html).toContain("EDITOR"); + expect(html).toContain('data-banner="notice"'); + expect(html).toContain("kept"); + }); +}); diff --git a/apps/yaak-proxy/components/FlowRequestBody.tsx b/apps/yaak-proxy/components/FlowRequestBody.tsx new file mode 100644 index 000000000..11d6cf69d --- /dev/null +++ b/apps/yaak-proxy/components/FlowRequestBody.tsx @@ -0,0 +1,56 @@ +import { formatSize } from "@yaakapp-internal/lib/formatSize"; +import { + Banner, + CONTROL_TOOLTIP_DELAY, + EmptyStateText, + LoadingIcon, + Tooltip, +} from "@yaakapp-internal/ui"; +import type { HttpBodyResult } from "@yaakapp-internal/ui/httpTypes"; +import type { ReactNode } from "react"; +import type { FlowBodyData } from "../lib/flowViews"; + +interface Props { + /** The request body as the engine's body RPC returned it */ + body: HttpBodyResult; + /** The body in the viewer for its type, formatted or raw */ + viewer: ReactNode; + /** Bytes of the request body on the wire */ + requestSize: number; +} + +/** + * The request half's Body tab: the body in its viewer, or why it isn't there yet. A body that + * failed to load says why, as the response's viewer does, rather than reading as no body. + */ +export function FlowRequestBody({ body, viewer, requestSize }: Props) { + if (body.error != null) { + return ( + + {body.error.message} + + ); + } + if (body.isLoading) { + return ( + + + + ); + } + if (body.data?.truncated) { + return ( +
+ + + + First {formatSize(body.data.storedSize)} of {formatSize(requestSize)} kept + + + +
{viewer}
+
+ ); + } + return viewer; +} diff --git a/apps/yaak-proxy/components/FlowTimeline.tsx b/apps/yaak-proxy/components/FlowTimeline.tsx new file mode 100644 index 000000000..51e93bb56 --- /dev/null +++ b/apps/yaak-proxy/components/FlowTimeline.tsx @@ -0,0 +1,71 @@ +import type { Flow } from "@yaakapp-internal/proxy-lib"; +import { + CONTROL_TOOLTIP_DELAY, + EventViewer, + EventViewerRow, + formatMillis, + Icon, + type IconProps, + Tooltip, +} from "@yaakapp-internal/ui"; +import { useMemo } from "react"; +import { type FlowPhase, flowPhases, type PhaseKind } from "../lib/phases"; + +const ICONS: Record = { + start: { icon: "send_horizontal", color: "secondary" }, + step: { icon: "arrow_right", color: "secondary" }, + end: { icon: "check", color: "success" }, + error: { icon: "alert_triangle", color: "danger" }, + cancelled: { icon: "circle_off", color: "secondary" }, +}; + +/** Yaak's event list with the flow's phases as rows, each saying how long it took */ +export function FlowTimeline({ flow }: { flow: Flow }) { + const phases = useMemo(() => flowPhases(flow), [flow]); + return ( + + events={phases} + getEventKey={(p) => p.key} + splitLayoutStorageKey="proxy_flow_timeline" + enableKeyboardNav={false} + emptyMessage="No timings recorded" + renderRow={({ event, isActive, onClick }) => { + const { icon, color } = ICONS[event.kind]; + return ( + } + content={ + event.detail == null ? ( + {event.label} + ) : ( + + + {event.label} + {` ${event.detail}`} + + + ) + } + columns="auto minmax(0,1fr) 6rem 6rem" + cells={{ + trailing: [ + + {event.kind === "start" ? "" : `+${formatMillis(event.tookMs)}`} + , + + {formatMillis(event.atMs)} + , + ], + }} + /> + ); + }} + /> + ); +} diff --git a/apps/yaak-proxy/components/LockedState.tsx b/apps/yaak-proxy/components/LockedState.tsx new file mode 100644 index 000000000..4dd5ba066 --- /dev/null +++ b/apps/yaak-proxy/components/LockedState.tsx @@ -0,0 +1,63 @@ +import type { ProxyLock } from "@yaakapp-internal/proxy-lib"; +import { Button, Icon, LoadingIcon } from "@yaakapp-internal/ui"; +import { useAtomValue } from "jotai"; +import { useRpcMutation } from "../hooks/useRpcMutation"; +import { encryptingPercent } from "../lib/encrypting"; +import { lockedLine } from "../lib/locked"; +import { proxyStateAtom } from "../lib/store"; +import { getOsType } from "../lib/tauri"; + +/** + * Over the list and the detail pane while captured traffic can't be read: its key is + * unavailable, or traffic from before encryption is being encrypted. Retry reads the key again + * and opens it. + */ +export function LockedState({ lock }: { lock: ProxyLock }) { + const proxyState = useAtomValue(proxyStateAtom); + const retry = useRpcMutation("take_over"); + const encrypting = encryptingPercent(proxyState); + + return ( +
+
+ {encrypting != null ? ( + + ) : ( + + )} +
+ {encrypting != null ? ( + <> + Encrypting stored traffic,{" "} + {/* Sized for "100%" and right-aligned, so the centred line never changes width as + the number ticks: a changing width re-rasterizes every glyph at a new + sub-pixel offset, and the line shakes */} + {encrypting} + + ) : ( + "Traffic is locked" + )} +
+
+ {encrypting != null + ? "Earlier traffic shows here once it's encrypted." + : lockedLine(lock, getOsType())} +
+ {encrypting == null && ( + + )} + {encrypting == null && retry.error != null && ( +
{retry.error.message}
+ )} +
+
+ ); +} diff --git a/apps/yaak-proxy/components/NotDecrypted.tsx b/apps/yaak-proxy/components/NotDecrypted.tsx new file mode 100644 index 000000000..b45e4bd8f --- /dev/null +++ b/apps/yaak-proxy/components/NotDecrypted.tsx @@ -0,0 +1,97 @@ +import { formatSize } from "@yaakapp-internal/lib/formatSize"; +import type { Flow } from "@yaakapp-internal/proxy-lib"; +import { Button, CONTROL_TOOLTIP_DELAY, formatMillis, Icon, Tooltip } from "@yaakapp-internal/ui"; +import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList"; +import { type DecryptSubject, detailActions, listEdit, setDecrypted } from "../lib/decrypt"; +import { sidebarPath } from "../lib/search"; +import { EmptyState } from "./FlowBodyViewer"; + +/** + * The detail of HTTPS passed through undecrypted: its sizes and time, and buttons that add its + * host or its app to the decrypt list, from the next connection on. + */ +export function NotDecrypted({ flow }: { flow: Flow }) { + const list = useDecryptList(); + const save = useEditDecryptList(); + const host = sidebarPath(flow.url).split("/")[0] ?? flow.url; + const hostSubject: DecryptSubject = { kind: "host", host }; + const appSubject: DecryptSubject | null = + flow.clientName == null + ? null + : { kind: "app", name: flow.clientName, bundleId: flow.clientBundleId }; + const app = flow.clientName; + const actions = detailActions( + list, + host, + app == null ? null : { name: app, bundleId: flow.clientBundleId }, + ); + const open = flow.elapsedMs == null && flow.error == null; + + const decrypt = (subject: DecryptSubject) => + save.mutate(listEdit(list, setDecrypted(list, [subject], true))); + + const facts = [ + `${formatSize(Number(flow.requestSize))} sent`, + `${formatSize(Number(flow.responseSize))} received`, + open ? "open" : flow.elapsedMs == null ? null : formatMillis(flow.elapsedMs), + ].filter((f) => f != null); + + return ( + +
+
+ + Not decrypted +
+
{facts.join(" · ")}
+ {flow.error != null &&
{flow.error}
} + {actions.listed ? ( + +
Decrypting new connections
+
+ ) : actions.blocked != null ? ( + +
+ Excluded by {actions.blocked} +
+
+ ) : ( +
+ {actions.host && ( + + )} + {actions.app && appSubject != null && ( + + )} +
+ )} +
+
+ ); +} diff --git a/apps/yaak-proxy/components/ProxyLayout.tsx b/apps/yaak-proxy/components/ProxyLayout.tsx index 46e3017e9..00d72a756 100644 --- a/apps/yaak-proxy/components/ProxyLayout.tsx +++ b/apps/yaak-proxy/components/ProxyLayout.tsx @@ -1,5 +1,6 @@ import { HeaderSize, + HeaderTint, IconButton, SidebarLayout, SplitLayout, @@ -11,22 +12,33 @@ 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 { setupIncomplete } from "../lib/firstRun"; +import { useMenuExportHar } from "../lib/flowActions"; +import { useNavigationControls } from "../lib/navigation"; +import { proxyStatusOf, statusTintColor } from "../lib/proxyStatus"; +import { lockedAtom, noFlowsAtom, proxyStateAtom, systemProxyEverOnAtom } from "../lib/store"; import { getOsType } from "../lib/tauri"; +import { AddColumnDialog } from "./AddColumnDialog"; import { ClearFlowsButton } from "./ClearFlowsButton"; import { FirstRun } from "./FirstRun"; import { FlowDetail } from "./FlowDetail"; import { FlowList } from "./FlowList"; -import { ProxyStatus } from "./ProxyStatus"; +import { LockedState } from "./LockedState"; +import { ProxyStatus, useProxySetup } from "./ProxyStatus"; import { HelperDialog } from "./HelperDialog"; import { SaveDialog } from "./SaveDialog"; -import { selectedSidebarLabelAtom, Sidebar } from "./Sidebar"; +import { SavedSearchDialog } from "./SavedSearchDialog"; +import { SearchBar } from "./SearchBar"; +import { SettingsDialogFallback, useOpenSettings } from "./Settings"; +import { Sidebar } from "./Sidebar"; import { TakeOverBanner } from "./TakeOverBanner"; export function ProxyLayout() { const os = getOsType(); - const title = useAtomValue(selectedSidebarLabelAtom); const [flowLayout, setFlowLayout] = useAtom(flowLayoutAtom); + const openSettings = useOpenSettings(); + useMenuExportHar(); + useNavigationControls(); const [sidebarWidth, setSidebarWidth] = useLocalStorage("sidebar_width", 250); const [sidebarHidden, setSidebarHidden] = useLocalStorage("sidebar_hidden", false); const [floatingSidebarHidden, setFloatingSidebarHidden] = useLocalStorage( @@ -35,6 +47,7 @@ export function ProxyLayout() { ); const [floating, setFloating] = useState(false); const isHidden = floating ? (floatingSidebarHidden ?? true) : (sidebarHidden ?? false); + const tint = statusTintColor(proxyStatusOf(useAtomValue(proxyStateAtom))); return (
-
-
+ + {/* Yaak's silhouette: the sidebar toggle and the state pill where Yaak has the toggle and + the environment, the search where it names the request, then its icons. Only the + controls take the pointer: everything around them, the traffic lights' corner + included, falls through to the header, which drags the window. */} +
+
{ @@ -67,27 +90,35 @@ export function ProxyLayout() { } }} /> -
-
- {title} - -
-
+
+
+
+ +
+
+
setFlowLayout((prev) => (prev === "horizontal" ? "vertical" : "horizontal")) } /> + openSettings()} + />
@@ -120,6 +151,7 @@ export function ProxyLayout() { setFloatingSidebarHidden(true)} @@ -140,35 +172,41 @@ export function ProxyLayout() {
+ + +
); } -/** Its own component, so new traffic re-renders the count rather than the whole layout */ -function FlowCount() { - const count = useAtomValue(shownTotalAtom); - const searching = useAtomValue(searchWindowAtom) != null; - const noun = searching ? (count === 1 ? "match" : "matches") : count === 1 ? "flow" : "flows"; - return {`${count} ${noun}`}; -} - /** - * 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. + * The flow list beside or above the detail pane, or, while setup is incomplete and there are no + * flows, the first-run card across the whole area. Once setup is done an empty list says so + * itself, after a Clear too. While captured traffic is locked, the locked state takes the whole + * area, or the first-run card does, saying why, while setup is incomplete too. */ function FlowsOrFirstRun({ flowLayout }: { flowLayout: SplitLayoutLayout }) { - if (useAtomValue(showFirstRunAtom)) return ; + const locked = useAtomValue(lockedAtom); + const noFlows = useAtomValue(noFlowsAtom) || locked != null; + const { caStatus, systemProxy } = useProxySetup(); + const systemProxyEverOn = useAtomValue(systemProxyEverOnAtom); + const incomplete = setupIncomplete({ + trusted: caStatus.data?.trusted ?? null, + systemProxySupported: systemProxy.data?.supported ?? null, + systemProxyEverOn, + }); + if (noFlows && incomplete) return ; + if (locked != null) return ; return ( ( - - )} + firstSlot={({ style }) => } secondSlot={({ style, orientation }) => ( )} diff --git a/apps/yaak-proxy/components/ProxyStatus.tsx b/apps/yaak-proxy/components/ProxyStatus.tsx index 48a9779f5..e4b524544 100644 --- a/apps/yaak-proxy/components/ProxyStatus.tsx +++ b/apps/yaak-proxy/components/ProxyStatus.tsx @@ -7,41 +7,37 @@ import { type DropdownItem, type DropdownRef, Icon, + LoadingIcon, } from "@yaakapp-internal/ui"; import classNames from "classnames"; -import { useAtomValue, useSetAtom, useStore } from "jotai"; +import { useAtom, useAtomValue } from "jotai"; import type { HTMLAttributes, ReactNode, Ref } from "react"; -import { useEffect, useRef } from "react"; +import { useEffect, useRef, useState } from "react"; import { useRpcEvent } from "../hooks/useRpcEvent"; import { useRpcMutation } from "../hooks/useRpcMutation"; import { useRpcQuery } from "../hooks/useRpcQuery"; -import { helperDialogOpenAtom, helperRegisteredAtAtom } from "../lib/atoms"; +import { helperRegisteredAtAtom } from "../lib/atoms"; +import { encryptingPercent } from "../lib/encrypting"; import { environmentExports } from "../lib/env"; -import { proxyStateAtom, refreshProxyState } from "../lib/store"; -import { - helperPollInterval, - helperRow, - recordingLabel, - systemProxySwitch, -} from "../lib/systemProxy"; +import { proxyStatusOf } from "../lib/proxyStatus"; +import { proxyStateAtom, systemProxyEverOnAtom } from "../lib/store"; +import { helperPollInterval, recordingLabel, systemProxySwitch } from "../lib/systemProxy"; import { onWindowFocus } from "../lib/tauri"; import { useShowToast } from "../lib/toast"; /** - * The header's state pill and its menu: recording, the system proxy, the certificate and HTTP/2. 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. + * The header's state pill and its menu: the listening address, which copies itself, the state, + * Pause or Resume Recording, Override 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. Everything set once and left alone lives in Settings. */ export function ProxyStatus() { const dropdownRef = useRef(null); + const [copied, setCopied] = useCopied(); const proxyState = useAtomValue(proxyStateAtom); const setup = useProxySetup(); const execute = useRpcMutation("execute_action"); const retry = useRpcMutation("take_over"); - const setAtLaunch = useSetSystemProxyAtLaunch(); - const setHttpVersion = useSetHttpVersion(); - const copyEnvironment = useCopyEnvironment(); - const setHelperDialogOpen = useSetAtom(helperDialogOpenAtom); const { caStatus, trust, systemProxy, setSystemProxy } = setup; const systemSwitch = useSystemProxySwitch(setup); @@ -50,22 +46,31 @@ export function ProxyStatus() { const other = proxyState?.otherOwner ?? null; const port = proxyState?.port ?? other?.proxyPort ?? null; const untrusted = caStatus.data != null && !caStatus.data.trusted; + // The same status the header's tint takes its colour from + const status = proxyStatusOf(proxyState); + const encrypting = status === "encrypting" ? encryptingPercent(proxyState) : null; const stateRow = - other != null ? ( + status === "encrypting" ? ( + } + title={`Encrypting stored traffic, ${encrypting}`} + description="Traffic captured before this version is being encrypted on disk. Recording starts when it's done." + /> + ) : status === "cli" && other != null ? ( } 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 ? ( + ) : status === "recording" || status === "paused" ? ( } + icon={} 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." + ? "Every flow is stored as it passes." + : "Traffic passes through untouched, and nothing is stored." } /> ) : ( @@ -93,9 +98,40 @@ export function ProxyStatus() { /> ); + // Until the helper is approved, every change asks for the password; said where it is felt. + const helperNotice = + systemProxy.data != null && + systemProxy.data.backend !== "helper" && + systemProxy.data.helper !== "enabled" && + systemProxy.data.helper !== "unavailable"; + + const address = port == null ? null : `127.0.0.1:${port}`; const items: DropdownItem[] = [ + { + label: {address}, + hidden: address == null, + keepOpenOnSelect: true, + rightSlot: copied ? ( + Copied + ) : ( + + ), + onSelect: () => { + if (address == null) return; + navigator.clipboard.writeText(address).then(setCopied, console.error); + }, + }, + { type: "separator", hidden: address == null }, { type: "content", label: stateRow }, - { type: "separator", hidden: systemProxy.data?.supported !== true }, + { + label: recordingLabel(recording), + icon: recording ? "circle_pause" : "circle_play", + hidden: !running, + hotKeyAction: "recording_toggle", + hotKeyLabelOnly: true, + onSelect: () => execute.mutate({ scope: "global", action: "recording_toggle" }), + }, + { type: "separator" }, { type: "content", hidden: systemProxy.data?.supported !== true, @@ -104,9 +140,16 @@ export function ProxyStatus() { icon={} title="Override system proxy" description={ - - {systemSwitch.description} - + <> + + {systemSwitch.description} + + {helperNotice && ( + + macOS asks for your password each time until the helper is approved in Settings. + + )} + } action={ @@ -123,35 +166,6 @@ export function ProxyStatus() { /> ), }, - { - type: "content", - hidden: systemProxy.data?.supported !== true, - label: ( - - Override system proxy at launch - } - checked={proxyState?.systemProxyAtLaunch ?? true} - disabled={setAtLaunch.isPending} - onChange={(enabled) => setAtLaunch.mutate({ enabled })} - /> - - ), - }, - { - type: "content", - hidden: systemProxy.data?.supported !== true, - label: systemProxy.data != null && ( - { - dropdownRef.current?.close?.(); - setHelperDialogOpen(true); - }} - /> - ), - }, { type: "content", label: caStatus.data?.trusted ? ( @@ -190,69 +204,27 @@ export function ProxyStatus() { /> ), }, - { - type: "content", - label: ( - } - title="HTTP/2" - description="Lets browsers send many requests at once. Turn off for apps that misbehave on it. Applies to new connections." - action={ - - - setHttpVersion.mutate({ httpVersion: enabled ? "auto" : "http1Only" }) - } - /> - - } - /> - ), - }, - { type: "separator" }, - { - 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: "recording_toggle" }), - }, ]; return ( <> - {untrusted && ( - dropdownRef.current?.open()}> - - Certificate not trusted - - )} - - {other != null ? ( + + {status === "encrypting" ? ( + <> + + Encrypting + {encrypting} + + ) : status === "cli" && other != null ? ( <> CLI - {other.proxyPort != null && ( - :{other.proxyPort} - )} - ) : running ? ( + ) : status === "recording" || status === "paused" ? ( <> - + {recording ? "Recording" : "Paused"} - {port != null && :{port}} ) : ( <> @@ -263,6 +235,12 @@ export function ProxyStatus() { + {untrusted && ( + dropdownRef.current?.open()}> + + Certificate not trusted + + )} ); } @@ -300,6 +278,12 @@ export function useProxySetup() { // 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()); + // Setup counts as done once the system proxy has been on, whatever it is now. + const [everOn, setEverOn] = useAtom(systemProxyEverOnAtom); + const on = systemProxy.data?.enabled === true; + useEffect(() => { + if (on && !everOn) setEverOn(true); + }, [on, everOn, setEverOn]); return { caStatus, trust, systemProxy, setSystemProxy }; } @@ -317,74 +301,6 @@ export function useSystemProxySwitch(setup: ReturnType) { } /** The privileged helper: whether it is installed and approved, and which way changes go */ -function HelperMenuRow({ - status, - onOpenDialog, -}: { - status: SystemProxyStatus; - onOpenDialog: () => void; -}) { - const queryClient = useQueryClient(); - const unregister = useRpcMutation("helper_unregister", { - onSuccess: (status) => - queryClient.setQueryData(["system_proxy_status", {}], status), - }); - const row = helperRow(status.helper, status.backend); - const error = unregister.error; - return ( - - } - title={row.title} - description={ - error != null ? {error.message} : row.description - } - action={ - row.action != 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), - }); -} - -/** Saves the HTTP versions offered to clients, which the engine applies to new connections */ -function useSetHttpVersion() { - const store = useStore(); - return useRpcMutation("set_http_version", { - onSettled: () => void refreshProxyState(store), - }); -} - export function useCopyEnvironment() { const proxyState = useAtomValue(proxyStateAtom); const caStatus = useRpcQuery("ca_status", {}); @@ -404,6 +320,18 @@ export function useCopyEnvironment() { } }; } + +/** Whether something was just copied, for a moment, and the call that says it was */ +function useCopied(): [boolean, () => void] { + const [copied, setCopied] = useState(false); + useEffect(() => { + if (!copied) return; + const timeout = setTimeout(() => setCopied(false), 1500); + return () => clearTimeout(timeout); + }, [copied]); + return [copied, () => setCopied(true)]; +} + /** 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 ( diff --git a/apps/yaak-proxy/components/SaveDialog.tsx b/apps/yaak-proxy/components/SaveDialog.tsx index 653632474..229a6f5a6 100644 --- a/apps/yaak-proxy/components/SaveDialog.tsx +++ b/apps/yaak-proxy/components/SaveDialog.tsx @@ -6,11 +6,13 @@ import type { } from "@yaakapp-internal/proxy-lib"; import { Banner, + CONTROL_TOOLTIP_DELAY, Dialog, DialogFooter, HttpMethodTagRaw, LoadingIcon, PlainInput, + Tooltip, } from "@yaakapp-internal/ui"; import { unnamedRequestName } from "@yaakapp-internal/ui/resolvedModelName"; import { openUrl } from "@tauri-apps/plugin-opener"; @@ -181,13 +183,16 @@ function SaveForm({
{p.droppedHeaders.map((h) => ( - - {h.name} - + + {h.name} + + ))}
diff --git a/apps/yaak-proxy/components/SavedSearchDialog.tsx b/apps/yaak-proxy/components/SavedSearchDialog.tsx new file mode 100644 index 000000000..6fda7826f --- /dev/null +++ b/apps/yaak-proxy/components/SavedSearchDialog.tsx @@ -0,0 +1,82 @@ +import { Dialog, DialogFooter, PlainInput } from "@yaakapp-internal/ui"; +import { atom, useAtom } from "jotai"; +import { useState } from "react"; +import { useRpcMutation } from "../hooks/useRpcMutation"; +import { useShowToast } from "../lib/toast"; + +/** Saving the search box's text under a name, or renaming a saved search */ +export type SavedSearchDialog = + | { mode: "save"; query: string } + | { mode: "rename"; id: string; name: string }; + +export const savedSearchDialogAtom = atom(null); + +const FORM_ID = "saved-search"; + +/** Names a saved search, as `savedSearchDialogAtom` asks */ +export function SavedSearchDialog() { + const [dialog, setDialog] = useAtom(savedSearchDialogAtom); + if (dialog == null) return null; + // Keyed, so each opening starts from its own name. + return ( + setDialog(null)} + /> + ); +} + +function NameDialog({ dialog, onClose }: { dialog: SavedSearchDialog; onClose: () => void }) { + const [name, setName] = useState(dialog.mode === "rename" ? dialog.name : ""); + const showToast = useShowToast(); + const onError = (err: Error) => + showToast({ id: "saved-search", message: err.message, color: "danger" }); + const create = useRpcMutation("create_saved_query", { onSuccess: onClose, onError }); + const rename = useRpcMutation("rename_saved_query", { onSuccess: onClose, onError }); + const busy = create.isPending || rename.isPending; + + const submit = () => { + if (name.trim() === "" || busy) return; + if (dialog.mode === "save") create.mutate({ name, query: dialog.query }); + else rename.mutate({ id: dialog.id, name }); + }; + + return ( + +
{ + e.preventDefault(); + submit(); + }} + > + + + +
+ ); +} diff --git a/apps/yaak-proxy/components/SearchBar.tsx b/apps/yaak-proxy/components/SearchBar.tsx index ed9d107f3..c092840b8 100644 --- a/apps/yaak-proxy/components/SearchBar.tsx +++ b/apps/yaak-proxy/components/SearchBar.tsx @@ -1,111 +1,529 @@ -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 { + autocompletion, + closeCompletion, + type Completion, + completionStatus, + startCompletion, +} from "@codemirror/autocomplete"; +import type { Extension } from "@codemirror/state"; +import { Compartment, Prec } from "@codemirror/state"; +import { EditorView, keymap, tooltips, ViewPlugin, type ViewUpdate } from "@codemirror/view"; +import { + Dropdown, + type DropdownItem, + Icon, + IconButton, + Input, + type InputHandle, + LazyCodeEditor, +} from "@yaakapp-internal/ui"; +import { queryFilter } from "@yaakapp-internal/ui/editor"; +import classNames from "classnames"; +import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai"; +import { + type CSSProperties, + memo, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react"; +import { useRpcQueryWithEvent } from "../hooks/useRpcQueryWithEvent"; +import { useRpcQuery } from "../hooks/useRpcQuery"; +import { appliedFilterAtom } from "../lib/atoms"; +import { isUnapplied, pressEnter, pressEscape, type Recall, stepHistory } from "../lib/filterBox"; +import { useExportShownHar } from "../lib/flowActions"; +import { applyFilter, searchDraftAtom, searchDraftVersionAtom } from "../lib/navigation"; +import { rpc } from "../lib/rpc"; +import { loadSeenValues, savedCompletions, searchProblems } from "../lib/searchBox"; +import { allTrafficTotalAtom, lockedAtom, savedQueriesAtom, type Store } from "../lib/store"; import { useShowToast } from "../lib/toast"; +import { savedSearchDialogAtom } from "./SavedSearchDialog"; -/** How long typing settles before the search runs */ -const SEARCH_DEBOUNCE_MS = 200; +/** Recent filters listed above the fields when the empty box is focused */ +const RECENT_IN_COMPLETIONS = 5; + +const NO_HISTORY: string[] = []; /** - * 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. + * The header's search over every flow in the database, in the query language: bare words match + * the URL, method, status and content type, and `@field:value` terms the rest, highlighted and + * completed as Yaak's sidebar filter is, with the values the proxy has seen. The box composes a + * filter and Enter applies it, as Yaak's URL bar sends; until then a return key at its right + * says so, and Escape puts the applied filter back. The magnifier lists the filters applied + * before, which Up in the empty box steps through too. Its placeholder counts the flows. ⌘F + * focuses it. Focused, it wraps a long query over as many lines as it needs, as Yaak's URL bar + * does, over what is below; blurred, it is one line again. */ 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 as the ref - const inputRef = useRef(null); - // Bumped to empty the field, which only takes a value from outside when this changes - const [resetKey, setResetKey] = useState(0); + const [draft, setDraft] = useAtom(searchDraftAtom); + const version = useAtomValue(searchDraftVersionAtom); + const applied = useAtomValue(appliedFilterAtom); + const total = useAtomValue(allTrafficTotalAtom); + const store = useStore(); + const setSavedDialog = useSetAtom(savedSearchDialogAtom); + const exportShown = useExportShownHar(); + // Nothing to search while captured traffic is locked. + const locked = useAtomValue(lockedAtom) != null; + const schema = useRpcQuery("query_schema", {}, { staleTime: Infinity }).data?.schema; + const historyQuery = useRpcQueryWithEvent("list_filter_history", {}, "filter_history_changed", { + enabled: !locked, + }); + const history = useMemo( + () => historyQuery.data?.map((e) => e.filter) ?? NO_HISTORY, + [historyQuery.data], + ); + const handleRef = useRef(null); + const boxRef = useRef(null); + const [focused, setFocused] = useState(false); + // Where the box is while focused, so it grows over the list from the header's place for it + const [place, setPlace] = useState(null); - useEffect(() => { - const timer = setTimeout(() => setTerms(searchTerms(text)), SEARCH_DEBOUNCE_MS); - return () => clearTimeout(timer); - }, [text, setTerms]); + // Read by the editor's keys, which are made once + const latest = useRef({ applied, history }); + useLayoutEffect(() => { + latest.current = { applied, history }; + }); + + useLayoutEffect(() => { + if (!focused) { + setPlace(null); + return; + } + const measure = () => { + const rect = boxRef.current?.getBoundingClientRect(); + if (rect != null) setPlace({ top: rect.top, left: rect.left, width: rect.width }); + }; + measure(); + window.addEventListener("resize", measure); + return () => window.removeEventListener("resize", measure); + }, [focused]); 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(); + handleRef.current?.selectAll(); } }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, []); - // The field is replaced to empty it, so focus moves to the new one. + // The language goes in once the schema is read: into the editor there is, through a + // compartment, and into each one made after, as taking text from the sidebar makes one. + const compartment = useRef(new Compartment()); + const filter = useMemo( + () => + schema == null + ? [] + : queryFilter({ + schema, + loadValues: loadSeenValues, + // Read as completion opens, so saved searches are current without remaking it. + moreCompletions: (typed) => savedCompletions(store.get(savedQueriesAtom), typed), + leadCompletions: () => recentCompletions(latest.current.history), + problems: searchProblems, + }), + [schema, store], + ); + const keys = useMemo(() => boxKeys(store, latest), [store]); + const extensions = useMemo( + () => [compartment.current.of(filter), completionAcrossBox, keys], + [filter, keys], + ); + useEffect(() => { + handleRef.current?.dispatch({ effects: compartment.current.reconfigure(filter) }); + }, [filter]); + + // Applies no filter at once, leaving the box focused and empty. const clear = () => { - setText(""); - setTerms(null); - setResetKey((k) => k + 1); - requestAnimationFrame(() => inputRef.current?.focus()); + const handle = handleRef.current; + handle?.dispatch({ changes: { from: 0, to: handle.value().length, insert: "" } }); + applyFilter(store, ""); + requestAnimationFrame(() => handleRef.current?.focus()); }; + const unapplied = isUnapplied({ draft, applied }); + const hasText = draft !== "" || applied !== ""; + return ( -
-
- +
+ ( + + )} + setRef={(h) => { + handleRef.current = h; + }} 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(); - } - }} + size="sm" + className="font-mono text-xs" + containerClassName={classNames(focused && "bg-surface shadow-lg")} + stateKey={null} + language={null} + wrapLines={focused} + onFocus={() => setFocused(true)} + onBlur={() => setFocused(false)} + placeholder={locked ? "Traffic is locked" : placeholderFor(total)} + disabled={locked} + defaultValue={draft} + forceUpdateKey={String(version)} + onChange={setDraft} + extensions={extensions} leftSlot={ - + // oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- keeps focus in the editor +
e.preventDefault()} + className="flex items-center self-center ml-0.5" + > + +
} rightSlot={ - text === "" ? ( - - ⌘F - - ) : ( - - ) + // oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- keeps focus in the editor +
e.preventDefault()} + className="flex items-center self-center ml-1 mr-0.5" + > + {unapplied ? ( + ↵ + ) : hasText ? null : ( + ⌘F + )} + {hasText && ( + <> + , + onSelect: () => + setSavedDialog({ + mode: "save", + query: (draft.trim() === "" ? applied : draft).trim(), + }), + }, + exportShown(), + ]} + > + + + + + )} +
} />
- { - 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" }); - } - }} - />
); }); + +function Key({ children, className }: { children: string; className?: string }) { + return ( + + {children} + + ); +} + +/** + * The magnifier, which lists the filters applied before, newest first: choosing one applies it + * again, and each can be saved as a search or forgotten + */ +function FilterHistory({ + history, + store, + disabled, +}: { + history: string[]; + store: Store; + disabled: boolean; +}) { + const setSavedDialog = useSetAtom(savedSearchDialogAtom); + const showToast = useShowToast(); + const fail = (err: unknown) => + showToast({ id: "filter-history", message: String(err), color: "danger" }); + + const items: DropdownItem[] = + history.length === 0 + ? [{ label: "No recent filters", disabled: true }] + : [ + ...history.map((filter): DropdownItem => ({ + label: ( + + {filter} + + ), + onSelect: () => applyFilter(store, filter, { record: true }), + actions: [ + { + icon: "bookmark", + title: "Save search", + closeMenu: true, + onSelect: () => setSavedDialog({ mode: "save", query: filter }), + }, + { + icon: "x", + title: "Remove", + onSelect: () => void rpc("delete_filter_history", { filter }).catch(fail), + }, + ], + })), + { type: "separator" }, + { + label: "Clear History", + leftSlot: , + onSelect: () => void rpc("clear_filter_history", {}).catch(fail), + }, + ]; + + return ( + + + + ); +} + +/** The recent filters the empty box's completions start with */ +function recentCompletions(history: string[]): Completion[] { + return history.slice(0, RECENT_IN_COMPLETIONS).map((filter) => ({ + label: filter, + detail: "Recent", + type: "text", + apply: filter, + })); +} + +/** The menu of completions is open, so the keys are its own */ +function menuOpen(view: EditorView): boolean { + return completionStatus(view.state) === "active"; +} + +function replaceText(view: EditorView, text: string) { + view.dispatch({ + changes: { from: 0, to: view.state.doc.length, insert: text }, + selection: { anchor: text.length }, + }); +} + +/** + * Enter, Escape, Up and Down in the box, over the editor's own and under its completions': Enter + * applies the draft, Escape puts the applied filter back or clears it, and Up and Down step + * through the filter history from an empty box. Each is the completion menu's while it is open, + * except Up from an empty box, which the history has. + */ +function boxKeys( + store: Store, + latest: { current: { applied: string; history: string[] } }, +): Extension { + let recall: Recall | null = null; + const step = (view: EditorView, key: "up" | "down") => { + const next = stepHistory(latest.current.history, recall, view.state.doc.toString(), key); + if (next == null) return false; + recall = next.recall; + closeCompletion(view); + replaceText(view, next.draft); + return true; + }; + const box = (view: EditorView) => ({ + draft: view.state.doc.toString(), + applied: latest.current.applied, + }); + return [ + Prec.high( + keymap.of([ + { + key: "Enter", + stopPropagation: true, + run: (view) => { + if (menuOpen(view)) return false; + const next = pressEnter(box(view)); + recall = null; + applyFilter(store, next.apply ?? "", { record: next.record }); + return true; + }, + }, + { + key: "Escape", + stopPropagation: true, + run: (view) => { + if (menuOpen(view)) return false; + const next = pressEscape(box(view)); + if (next == null) return false; + recall = null; + replaceText(view, next.draft); + if (next.apply != null) applyFilter(store, next.apply); + return true; + }, + }, + { + key: "ArrowUp", + run: (view) => { + const draft = view.state.doc.toString(); + const stepping = recall != null && recall.text === draft; + if (menuOpen(view) && draft !== "" && !stepping) return false; + return step(view, "up"); + }, + }, + { + key: "ArrowDown", + run: (view) => (menuOpen(view) ? false : step(view, "down")), + }, + ]), + ), + // The empty box lists the recent filters as it is focused. + EditorView.domEventHandlers({ + focus: (_e, view) => { + if (view.state.doc.length > 0 || latest.current.history.length === 0) return; + requestAnimationFrame(() => { + if (view.hasFocus && view.state.doc.length === 0) startCompletion(view); + }); + }, + }), + ]; +} + +/** The search box's width, which its completions take */ +const BOX_WIDTH_VAR = "--proxy-search-width"; + +/** The search box an editor is in */ +function boxOf(view: EditorView): HTMLElement | null { + return view.dom.closest(".x-theme-input"); +} + +/** Pixels between a completion's info and the window's edge */ +const INFO_MARGIN = 8; + +/** + * Where a completion's info goes: beside the list, in the window's room either side of the box, + * or, with none, under the option as CodeMirror puts it in a narrow space + */ +function positionInfo( + view: EditorView, + list: { left: number; right: number; top: number; bottom: number }, + option: { top: number; bottom: number }, + info: { left: number; right: number; top: number; bottom: number }, +): { style: string; class: string } { + const win = view.dom.ownerDocument.defaultView ?? window; + const width = info.right - info.left; + const height = info.bottom - info.top; + const right = win.innerWidth - list.right - INFO_MARGIN; + const left = list.left - INFO_MARGIN; + if (Math.max(left, right) >= width) { + const top = Math.max(0, Math.min(option.top, win.innerHeight - height)) - list.top; + const onRight = right >= width; + return { + style: `top: ${top}px; max-width: ${onRight ? right : left}px`, + class: onRight ? "cm-completionInfo-right" : "cm-completionInfo-left", + }; + } + return { + style: `top: ${option.bottom - list.top}px; max-width: 400px`, + class: "cm-completionInfo-right-narrow", + }; +} + +/** + * The completions under the search box, as wide as it and level with its left edge, rather + * than a narrow list wherever the cursor is + */ +const completionAcrossBox: Extension = [ + autocompletion({ positionInfo }), + tooltips({ + tooltipSpace: (view) => { + const win = view.dom.ownerDocument.defaultView ?? window; + const rect = boxOf(view)?.getBoundingClientRect(); + return { + top: 0, + bottom: win.innerHeight, + left: rect?.left ?? 0, + right: rect?.right ?? win.innerWidth, + }; + }, + }), + ViewPlugin.fromClass( + class { + observer: ResizeObserver | null = null; + + constructor(view: EditorView) { + this.watch(view); + } + + // The editor is put in the page after it is made, so the box may only be found later. + update(update: ViewUpdate) { + if (this.observer == null) this.watch(update.view); + } + + watch(view: EditorView) { + const box = boxOf(view); + if (box == null) return; + const root = view.dom.ownerDocument.documentElement; + this.observer = new ResizeObserver(() => { + root.style.setProperty(BOX_WIDTH_VAR, `${box.getBoundingClientRect().width}px`); + }); + this.observer.observe(box); + } + + destroy() { + this.observer?.disconnect(); + } + }, + ), + EditorView.theme({ + ".cm-tooltip.cm-tooltip-autocomplete": { width: `var(${BOX_WIDTH_VAR})` }, + ".cm-tooltip.cm-tooltip-autocomplete > ul": { minWidth: "0", maxWidth: "none" }, + }), +]; + +/** + * Ctrl+Space lists what can be typed, fields and saved searches on an empty spot, as it does in + * Yaak's editors, whose shared editor leaves the key to each app + */ +function startCompletionOnCtrlSpace(e: KeyboardEvent, view: EditorView): boolean { + if (!(e.ctrlKey && e.key === " " && !e.metaKey && !e.altKey && !e.shiftKey)) return false; + e.preventDefault(); + startCompletion(view); + return true; +} + +/** "Search 4,102 flows", the title and count that sat in the header's middle */ +function placeholderFor(total: number): string { + if (total === 0) return "Search flows"; + return `Search ${total.toLocaleString()} ${total === 1 ? "flow" : "flows"}`; +} diff --git a/apps/yaak-proxy/components/Settings.tsx b/apps/yaak-proxy/components/Settings.tsx new file mode 100644 index 000000000..0904f0ffd --- /dev/null +++ b/apps/yaak-proxy/components/Settings.tsx @@ -0,0 +1,265 @@ +import { useQuery } from "@tanstack/react-query"; +import { getVersion } from "@tauri-apps/api/app"; +import { appDataDir, appLogDir } from "@tauri-apps/api/path"; +import { + Dialog, + EmptyStateText, + SETTINGS_TAB_GENERAL, + SETTINGS_TAB_INTERFACE, + SETTINGS_TAB_LICENSE, + SETTINGS_TAB_THEME, + type SettingsCallbacks, + SettingsDialog, + SettingsGeneral, + SettingsInterface, + SettingsTheme, + type SettingsTitlebar, + Toasts, +} from "@yaakapp-internal/ui"; +import { atom, useAtom, useAtomValue, useSetAtom } from "jotai"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { settingsValuesAtom } from "../lib/interfaceSettings"; +import { openLink, revealPath } from "../lib/opener"; +import { proxySettingsView } from "../lib/settings"; +import { closeWindow, command, currentWindowLabel, getOsType, subscribe } from "../lib/tauri"; +import { useShowToast } from "../lib/toast"; +import { + openSettingsVia, + requestedSettingsTab, + SETTINGS_TAB_EVENT, + windowKind, +} from "../lib/windows"; +import { HelperDialog } from "./HelperDialog"; +import { useProxySetup } from "./ProxyStatus"; +import { SettingsProxy } from "./SettingsProxy"; + +export const SETTINGS_TAB_PROXY = "proxy"; + +/** The settings dialog is open, on a tab, or closed, where Settings has no window of its own */ +const settingsDialogAtom = atom(null); + +/** + * Yaak's settings, shared: its General, Theme, Interface and License tabs, plus the proxy's own + * Proxy tab. The header's gear and `⌘,` open it in a window of its own, or, where the app has + * no second window to give, such as the browser harness, in this dialog. + */ +export function SettingsDialogFallback() { + const [tab, setTab] = useAtom(settingsDialogAtom); + useSettingsHotkey(); + return ( + setTab(null)} + size="lg" + noPadding + noScroll + className="h-[min(44rem,90vh)]" + > + {tab != null && } + + ); +} + +/** + * The Settings window: the settings alone, full-window under their own title bar, on the tab + * asked for, moving to another tab each time Settings is opened on one. Escape closes it. The + * dialogs the settings open, and their toasts, show over it. + */ +export function SettingsWindowContent() { + const [shown, setShown] = useState(() => ({ + tab: requestedSettingsTab() ?? SETTINGS_TAB_GENERAL, + // Keys the tabs, which take their tab only as they mount + version: 0, + })); + useEffect( + () => + subscribe(SETTINGS_TAB_EVENT, (tab) => + setShown((s) => ({ tab, version: s.version + 1 })), + ), + [], + ); + useEffect(() => { + function onKeyDown(e: KeyboardEvent) { + // A dialog over the settings takes its own Escape and stops it here, an editor's popup + // marks it handled, and an open menu closes on it, leaving the window open + if (e.key !== "Escape" || e.defaultPrevented) return; + if (document.querySelector('[role="menu"]') != null) return; + closeWindow().catch(console.error); + } + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, []); + // Reads the system proxy and certificate as the main window's header does, polling while the + // helper awaits approval, so the helper's dialog here sees it given. + useProxySetup(); + const { hideWindowControls } = useAtomValue(settingsValuesAtom); + const titlebar = useMemo( + () => ({ + osType: getOsType(), + hideWindowControls, + // The proxy draws its own title bar always, as its main window does + useNativeTitlebar: false, + interfaceScale: 1, + }), + [hideWindowControls], + ); + + return ( +
+ + + +
+ ); +} + +/** The settings themselves, as the window or the dialog holds them */ +export function SettingsContent({ + defaultTab, + titlebar = null, +}: { + defaultTab: string; + /** The window's title bar; none in the dialog, which has its own frame */ + titlebar?: SettingsTitlebar | null; +}) { + const [values, change] = useAtom(settingsValuesAtom); + const app = useAppInfo(); + const systemAppearance = useSystemAppearance(); + const view = useMemo( + () => proxySettingsView(values, app, systemAppearance), + [values, app, systemAppearance], + ); + const showToast = useShowToast(); + const callbacks = useMemo(() => { + const fail = (message: string) => showToast({ message, color: "danger" }); + return { + onChange: (patch) => change(patch), + // The proxy draws its own title bar always; the row isn't shown + onApplyNativeTitlebar: (useNativeTitlebar) => change({ useNativeTitlebar }), + onCheckForUpdates: () => undefined, + onActivateLicense: async () => undefined, + onDeactivateLicense: () => undefined, + onOpenUrl: (url) => void openLink(url, fail), + onRevealPath: (path) => void revealPath(path, fail), + pricingUrl: (intent) => `https://yaak.app/pricing?intent=${encodeURIComponent(intent)}`, + }; + }, [change, showToast]); + const props = { view, callbacks }; + + return ( + , + }, + { + value: SETTINGS_TAB_THEME, + label: "Theme", + icon: "palette", + content: , + }, + { + value: SETTINGS_TAB_INTERFACE, + label: "Interface", + icon: "columns_2", + content: , + }, + { + value: SETTINGS_TAB_PROXY, + label: "Proxy", + icon: "wifi", + content: , + }, + { + value: SETTINGS_TAB_LICENSE, + label: "License", + icon: "key_round", + content: Coming soon, + }, + ]} + /> + ); +} + +/** `⌘,`, or `Ctrl+,` off macOS, opens settings, as in Yaak, on the tab they were left on */ +function useSettingsHotkey() { + const open = useOpenSettings(); + useEffect(() => { + const mac = getOsType() === "macos"; + function onKeyDown(e: KeyboardEvent) { + if (e.key !== "," || e.shiftKey || e.altKey) return; + if (mac ? !e.metaKey || e.ctrlKey : !e.ctrlKey || e.metaKey) return; + e.preventDefault(); + open(null); + } + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [open]); +} + +function useAppInfo() { + const os = getOsType(); + const { data } = useQuery({ + queryKey: ["settings_app_info"], + queryFn: async () => { + const [version, dataDir, logDir] = await Promise.all([ + getVersion(), + appDataDir(), + appLogDir(), + ]); + return { version, dataDir, logDir }; + }, + retry: false, + }); + return useMemo( + () => ({ + name: "Yaak Proxy", + version: data?.version ?? "", + dataDir: data?.dataDir ?? "", + logDir: data?.logDir ?? "", + revealPathLabel: + os === "macos" + ? "Reveal in Finder" + : os === "windows" + ? "Show in Explorer" + : "Show in Folder", + }), + [data, os], + ); +} + +function useSystemAppearance(): "light" | "dark" { + const query = "(prefers-color-scheme: dark)"; + const [dark, setDark] = useState(() => window.matchMedia(query).matches); + useEffect(() => { + const media = window.matchMedia(query); + const onChange = () => setDark(media.matches); + media.addEventListener("change", onChange); + return () => media.removeEventListener("change", onChange); + }, []); + return dark ? "dark" : "light"; +} + +/** + * Opens settings on a tab, General unless another is given. With `null`, opens it on General, + * or brings it forward on the tab it is on. + */ +export function useOpenSettings() { + const setDialog = useSetAtom(settingsDialogAtom); + const showToast = useShowToast(); + return useCallback( + (tab: string | null = SETTINGS_TAB_GENERAL) => { + openSettingsVia(tab, { + kind: windowKind(currentWindowLabel()), + openWindow: (tab) => command("cmd_open_settings", { tab }), + openDialog: (tab) => setDialog((open) => tab ?? open ?? SETTINGS_TAB_GENERAL), + }).catch((err) => showToast({ id: "open-settings", color: "danger", message: String(err) })); + }, + [setDialog, showToast], + ); +} diff --git a/apps/yaak-proxy/components/SettingsProxy.tsx b/apps/yaak-proxy/components/SettingsProxy.tsx new file mode 100644 index 000000000..94359b1eb --- /dev/null +++ b/apps/yaak-proxy/components/SettingsProxy.tsx @@ -0,0 +1,385 @@ +import { useQueryClient } from "@tanstack/react-query"; +import { formatSize } from "@yaakapp-internal/lib/formatSize"; +import type { HttpVersion, SystemProxyStatus, TrafficRetention } from "@yaakapp-internal/proxy-lib"; +import { + Button, + Dialog, + DialogFooter, + Heading, + Icon, + RadioDropdown, + SettingRow, + SettingRowBoolean, + PlainInput, + SettingRowSelect, + SettingSelectControl, + SettingSnippet, + SettingsList, + SettingsSection, + VStack, +} from "@yaakapp-internal/ui"; +import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai"; +import { useState } from "react"; +import { useRpcMutation } from "../hooks/useRpcMutation"; +import { useRpcQuery } from "../hooks/useRpcQuery"; +import { helperDialogOpenAtom } from "../lib/atoms"; +import { confirmClearFlowsAtom } from "../lib/clearFlows"; +import { + defaultShell, + environmentBlock, + environmentVars, + TERMINAL_SHELLS, + type TerminalShell, +} from "../lib/env"; +import { + KEEP_TRAFFIC_OPTIONS, + sizeFromOptionValue, + sizeOptionsFor, + sizeOptionValue, +} from "../lib/settings"; +import { helperRow } from "../lib/systemProxy"; +import { proxyStateAtom, refreshProxyState } from "../lib/store"; +import { getOsType } from "../lib/tauri"; +import { useShowToast } from "../lib/toast"; +import { DecryptListEditor } from "./DecryptListEditor"; + +/** + * The proxy's own settings tab: how it listens and the system proxy, what it decrypts, what + * happens to captured traffic, and the environment for one terminal. Everything set once and + * left alone, which is what left the state pill's menu. + */ +export function SettingsProxy() { + const proxyState = useAtomValue(proxyStateAtom); + const store = useStore(); + const refresh = { onSettled: () => void refreshProxyState(store) }; + const setHttpVersion = useRpcMutation("set_http_version", refresh); + const setAtLaunch = useRpcMutation("set_system_proxy_at_launch", refresh); + const systemProxy = useRpcQuery("system_proxy_status", {}); + // Another process owning the engine wouldn't see changes until it restarts + const elsewhere = proxyState?.otherOwner != null; + + return ( + +
+ Proxy +

Listening, decryption, traffic and terminals

+
+ + + + + name="httpVersion" + title="HTTP version" + description="For new connections" + value={proxyState?.httpVersion ?? "auto"} + disabled={elsewhere} + onChange={(httpVersion) => setHttpVersion.mutate({ httpVersion })} + options={[ + { label: "Auto", value: "auto" }, + { label: "HTTP/1.1 only", value: "http1Only" }, + ]} + /> + {systemProxy.data?.supported === true && ( + <> + setAtLaunch.mutate({ enabled })} + /> + + + )} + + + + + + + + + {proxyState?.traffic === "keep" && } + + + + + + + + +
+ ); +} + +/** A port from 1 to 65535, or null */ +function parsePort(text: string): number | null { + if (!/^\d+$/.test(text.trim())) return null; + const port = Number(text.trim()); + return port > 0 && port < 65536 ? port : null; +} + +/** + * The port, saved when the field is left or Enter is pressed rather than on each keystroke: + * every save restarts a running proxy, so typing 8080 must not restart it on 8, 80 and 808. + */ +function PortRow({ disabled }: { disabled: boolean }) { + const proxyState = useAtomValue(proxyStateAtom); + const store = useStore(); + const showToast = useShowToast(); + const saved = proxyState?.configuredPort ?? 9090; + const [draft, setDraft] = useState(null); + // Puts the saved port back in the field after a rejected or failed change + const [resets, setResets] = useState(0); + const reset = () => { + setDraft(null); + setResets((n) => n + 1); + }; + const setPort = useRpcMutation("set_port", { + onError: (err) => showToast({ message: err.message, color: "danger" }), + onSettled: () => { + reset(); + void refreshProxyState(store); + }, + }); + const commit = () => { + if (draft == null || setPort.isPending) return; + const port = parsePort(draft); + if (port == null || port === saved) { + reset(); + return; + } + setPort.mutate({ port }); + }; + return ( + + parsePort(v) != null} + onChange={setDraft} + onBlur={commit} + onKeyDownCapture={(e) => { + if (e.key === "Enter") commit(); + }} + /> + + ); +} + +function HelperRow({ status }: { status: SystemProxyStatus }) { + const queryClient = useQueryClient(); + const openDialog = useSetAtom(helperDialogOpenAtom); + const unregister = useRpcMutation("helper_unregister", { + onSuccess: (status) => + queryClient.setQueryData(["system_proxy_status", {}], status), + }); + const row = helperRow(status.helper, status.backend); + return ( + {unregister.error.message} + ) : ( + `${capitalize(row.title.replace(/^Helper: /, ""))}. ${row.description}` + ) + } + > + {row.action != null && ( + + )} + + ); +} + +/** Whether captured traffic is cleared as the app launches or kept between launches */ +function TrafficRow() { + const proxyState = useAtomValue(proxyStateAtom); + const store = useStore(); + const setTraffic = useRpcMutation("set_traffic", { + onSettled: () => void refreshProxyState(store), + }); + return ( + + name="traffic" + title="Captured traffic" + selectClassName="w-56!" + value={proxyState?.traffic ?? "clearOnLaunch"} + disabled={proxyState?.otherOwner != null} + onChange={(traffic) => setTraffic.mutate({ traffic })} + options={[ + { label: "Clear on launch", value: "clearOnLaunch" }, + { label: "Keep between launches", value: "keep" }, + ]} + /> + ); +} + +/** The most traffic kept between launches, beside what is stored now */ +function KeepTrafficRow() { + const proxyState = useAtomValue(proxyStateAtom); + const store = useStore(); + const size = useRpcQuery("get_storage_size", {}, { refetchInterval: 10_000 }); + const setKeep = useRpcMutation("set_keep_traffic", { + onSettled: () => void refreshProxyState(store), + }); + const keep = proxyState?.keepTrafficBytes ?? null; + return ( + +
+ {size.data != null && ( + + {formatSize(size.data.bytes)} used + + )} + setKeep.mutate({ bytes: sizeFromOptionValue(v) })} + options={sizeOptionsFor(KEEP_TRAFFIC_OPTIONS, keep).map(({ label, value }) => ({ + label, + value, + }))} + /> +
+
+ ); +} + +/** Asking before Clear, which its dialog's "Don't ask again" turns off */ +function ConfirmClearRow() { + const [confirm, setConfirm] = useAtom(confirmClearFlowsAtom); + return ( + + ); +} + +function ResetRow() { + const [confirming, setConfirming] = useState(false); + const store = useStore(); + const queryClient = useQueryClient(); + const showToast = useShowToast(); + const reset = useRpcMutation("reset_captured_data", { + onSuccess: () => { + setConfirming(false); + void queryClient.invalidateQueries(); + showToast({ message: "Captured data reset" }); + }, + onSettled: () => void refreshProxyState(store), + }); + return ( + + + setConfirming(false)} + size="sm" + title="Reset captured data?" + description="Every captured flow and the keys that encrypt them are deleted." + > + {reset.error != null &&

{reset.error.message}

} + setConfirming(false) }, + { + label: "Reset", + color: "danger", + isLoading: reset.isPending, + onClick: () => reset.mutate({}), + }, + ]} + /> +
+
+ ); +} + +function TerminalRow() { + const proxyState = useAtomValue(proxyStateAtom); + const caStatus = useRpcQuery("ca_status", {}); + const showToast = useShowToast(); + const os = getOsType(); + const [shell, setShell] = useState(() => defaultShell(os)); + const openTerminal = useRpcMutation("open_terminal", { + onError: (err) => showToast({ message: err.message, color: "danger" }), + }); + const port = + proxyState?.port ?? proxyState?.otherOwner?.proxyPort ?? proxyState?.configuredPort ?? 9090; + const caPath = caStatus.data?.certPath; + const shellLabel = TERMINAL_SHELLS.find((s) => s.value === shell)?.label ?? shell; + + return ( +
+
+ Environment + setShell(v as TerminalShell)} + items={TERMINAL_SHELLS.map((s) => ({ label: s.label, value: s.value }))} + > + + + +
+

Proxies one terminal instead of the system

+ {caPath != null && ( + + )} +
+ ); +} + +function capitalize(s: string): string { + return s.charAt(0).toUpperCase() + s.slice(1); +} diff --git a/apps/yaak-proxy/components/Sidebar.tsx b/apps/yaak-proxy/components/Sidebar.tsx index 91c3ff932..cef3aecfa 100644 --- a/apps/yaak-proxy/components/Sidebar.tsx +++ b/apps/yaak-proxy/components/Sidebar.tsx @@ -1,31 +1,36 @@ -import type { Flow } from "@yaakapp-internal/proxy-lib"; -import type { TreeNode } from "@yaakapp-internal/ui"; -import { selectedIdsFamily, Tree } from "@yaakapp-internal/ui"; -import { atom, useAtomValue } from "jotai"; +import { + ContextMenu, + CONTROL_TOOLTIP_DELAY, + type DropdownItem, + Icon, + Tooltip, + Tree, + type TreeProps, +} from "@yaakapp-internal/ui"; +import { atom, useAtom, useAtomValue, useSetAtom, useStore } 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 { type PointerEvent, type SyntheticEvent, useCallback, useEffect } from "react"; +import { useDecryptList, useEditDecryptList } from "../hooks/useDecryptList"; +import { useRpcMutation } from "../hooks/useRpcMutation"; +import { appliedFilterAtom, SIDEBAR_TREE_ID } from "../lib/atoms"; +import { blockerOf, decryptMenuAction, isDecrypted, listEdit, setDecrypted } from "../lib/decrypt"; +import { revealLabel, revealPath } from "../lib/opener"; import { applyCollapsed, type CollapsedMap, collapsedMap, folderIds } from "../lib/sidebarCollapse"; -import { flowsAtom, flowTotalAtom } from "../lib/store"; +import { + copyRowsText, + filterWithRows, + type SidebarItem, + SYSTEM_ID, + valueRows, +} from "../lib/sidebarTree"; +import { applyFilter, noteSidebarInput, noteSidebarMenu } from "../lib/navigation"; +import { hideSystemAtom, sidebarTreeAtom } from "../lib/store"; +import { getOsType } from "../lib/tauri"; +import { useShowToast } from "../lib/toast"; import { AppIcon } from "./AppIcon"; +import { savedSearchDialogAtom } from "./SavedSearchDialog"; -/** 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; -}; - -const sidebarTreeAtom = atom>((get) => { - const exchanges = get(flowsAtom); - return buildTree(exchanges, get(flowTotalAtom)); -}); - -/** The domains and paths the user expanded, by node id, kept across launches */ +/** The apps, sites, hosts and paths the user expanded, by node id, kept across launches */ const expandedAtom = atomWithStorage>("sidebar_expanded", {}, undefined, { getOnInit: true, }); @@ -33,7 +38,7 @@ const expandedAtom = atomWithStorage>("sidebar_expanded" /** The other nodes' collapsed flags, for this launch, as before */ const otherCollapsedAtom = atom({}); -/** Domains and paths collapsed until the user expands them, for the tree */ +/** Every app's tree, site, host and path, and System, collapsed until the user expands them */ const collapsedAtom = atom( (get) => collapsedMap(folderIds(get(sidebarTreeAtom)), get(expandedAtom), get(otherCollapsedAtom)), @@ -46,196 +51,275 @@ const collapsedAtom = atom( }, ); -/** 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"; -}); - -const nodeIdsByFlow = new WeakMap(); - -/** - * The ids of the nodes a flow sits under, its domain first and then each path segment's, parsed - * once per flow rather than on every change to the list. - */ -function nodeIdsOf(ex: Flow): string[] { - let ids = nodeIdsByFlow.get(ex); - if (ids != null) return ids; - // 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 node = `path:${hostname}`; - for (const seg of segments) { - node += `/${seg}`; - ids.push(node); - } - nodeIdsByFlow.set(ex, ids); - return ids; -} - -const collator = new Intl.Collator(); - -/** - * Build a domain → path-segment trie from a flat list of exchanges. - * - * Example: Given URLs - * GET https://api.example.com/v1/users - * GET https://api.example.com/v1/users/123 - * POST https://api.example.com/v1/orders - * - * Produces: - * api.example.com - * /v1 - * /users - * /123 - * /orders - */ -function buildTree(exchanges: Flow[], total: number): TreeNode { - const root: SidebarItem = { id: "root", label: "All Traffic", count: 0 }; - const rootNode: TreeNode = { - item: root, - parent: null, - depth: 0, - children: [], - draggable: false, - }; - - // Intermediate trie structure for building - type TrieNode = { - id: string; - label: string; - count: number; - children: Map; - }; - - const domainMap = new Map(); - - for (const ex of exchanges) { - const ids = nodeIdsOf(ex); - let current: TrieNode | undefined; - for (const id of ids) { - const siblings = current == null ? domainMap : current.children; - let node = siblings.get(id); - if (node == null) { - // The domain, or the path's last segment - const label = current == null ? id.slice("domain:".length) : id.slice(id.lastIndexOf("/")); - node = { id, label, count: 0, children: new Map() }; - siblings.set(id, node); - } - node.count++; - current = node; - } - } - - // Convert trie to TreeNode structure - function toTreeNode( - trie: TrieNode, - parent: TreeNode, - depth: number, - ): TreeNode { - const node: TreeNode = { - item: { - id: trie.id, - label: trie.label, - count: trie.count, - }, - parent, - depth, - children: [], - draggable: false, - }; - const sortedChildren = [...trie.children.values()].sort((a, b) => - collator.compare(a.label, b.label), - ); - for (const child of sortedChildren) { - node.children?.push(toTreeNode(child, node, depth + 1)); - } - return node; - } - - // Add a "Domains" folder between root and domain nodes - const domainsFolder: TreeNode = { - item: { id: "domains", label: "Domains", count: total }, - parent: rootNode, - depth: 1, - children: [], - draggable: false, - }; - - const sortedDomains = [...domainMap.values()].sort((a, b) => collator.compare(a.label, b.label)); - for (const domain of sortedDomains) { - 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(); - 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 = { - 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; +function Count({ item }: { item: SidebarItem }) { + const text = item.count > 0 ? item.count.toLocaleString() : null; + if (text == null && item.kind !== "all") return null; + return ( + + {text ?? "0"} + + ); } function ItemInner({ item }: { item: SidebarItem }) { - const count = item.count; + if (item.kind === "group") { + return ( +
+ {item.label} + +
+ ); + } return (
- {item.appPath != null && } - {item.label} - {count > 0 && {count}} + {item.kind === "all" && } + {item.kind === "tunnelled" && } + {item.kind === "saved" && } + {item.kind === "folder" && } + {item.appPath != null && } + {item.kind === "folder" && item.path != null ? ( + // Named by its last part; the whole path on hover + + {item.label} + + ) : ( + {item.label} + )} + {item.sublabel != null && ( + {item.sublabel} + )} + {item.decrypt != null && } +
); } -export function Sidebar() { - const tree = useAtomValue(sidebarTreeAtom); +/** Input in the sidebar itself, not in a row's menu, whose events reach it through its portal */ +function inSidebar(e: SyntheticEvent): boolean { + return e.target instanceof Node && e.currentTarget.contains(e.target); +} - const getItemKey = useCallback((item: SidebarItem) => `${item.id}:${item.count}`, []); - const treeId = SIDEBAR_TREE_ID; +/** A press that opens a context menu: the secondary button, or Control and a click on macOS */ +function opensMenu(e: PointerEvent): boolean { + return e.button !== 0 || (e.ctrlKey && getOsType() === "macos"); +} + +/** The menu's sections that have items, a separator between each */ +function withSeparators(sections: DropdownItem[][]): DropdownItem[] { + return sections + .filter((s) => s.some((i) => !i.hidden)) + .flatMap((s, n) => (n === 0 ? s : [{ type: "separator" } as const, ...s])); +} + +/** A row with nothing in its menu: the menu closes as it opens, so the row is not left marked */ +function CloseAtOnce({ onClose }: { onClose: () => void }) { + useEffect(() => onClose(), [onClose]); + return null; +} + +/** A small open lock on a host, site or app the decrypt list decrypts */ +function DecryptedMark({ item }: { item: SidebarItem }) { + const list = useDecryptList(); + if (item.decrypt == null || !isDecrypted(list, item.decrypt)) return null; + return ( + + + + ); +} + +export function Sidebar() { + const store = useStore(); + const tree = useAtomValue(sidebarTreeAtom); + const getItemKey = useCallback( + // The label too, as a saved search's changes when it is renamed + (item: SidebarItem) => `${item.id}:${item.count}:${item.label}`, + [], + ); + const [hideSystem, setHideSystem] = useAtom(hideSystemAtom); + const decryptList = useDecryptList(); + const setDecryptList = useEditDecryptList(); + const { mutate: saveDecryptList } = setDecryptList; + const showToast = useShowToast(); + const setSavedDialog = useSetAtom(savedSearchDialogAtom); + const { mutate: deleteSaved } = useRpcMutation("delete_saved_query", { + onError: (err) => showToast({ id: "saved-search", message: err.message, color: "danger" }), + }); + + // A program's folder, or the program, is shown in Finder, and a folder's path copied. + const fail = useCallback( + (message: string) => showToast({ id: "sidebar-path", message, color: "danger" }), + [showToast], + ); + const pathItems = useCallback( + (item: SidebarItem | undefined): DropdownItem[] => { + const path = item?.path; + if (item == null || path == null) return []; + return [ + { + label: revealLabel(getOsType()), + leftSlot: , + onSelect: () => void revealPath(path, fail), + }, + { + label: "Copy path", + leftSlot: , + hidden: item.kind !== "folder", + onSelect: () => { + navigator.clipboard.writeText(path).catch((err) => fail(String(err))); + }, + }, + ]; + }, + [fail], + ); + + // The selected apps, folders, sites, hosts and paths added to the filter, either way, at once, + // or their values copied, as a cell's menu in the list does. + const filterItems = useCallback( + (items: SidebarItem[]): DropdownItem[] => { + if (valueRows(items).length === 0) return []; + const add = (negated: boolean) => + applyFilter(store, filterWithRows(store.get(appliedFilterAtom), items, negated)); + return [ + { label: "Filter by This Value", icon: "filter", onSelect: () => add(false) }, + { label: "Exclude This Value", icon: "minus_circle", onSelect: () => add(true) }, + { + label: "Copy Value", + icon: "copy", + onSelect: async () => { + try { + await navigator.clipboard.writeText(copyRowsText(items)); + showToast({ message: "Copied value" }); + } catch (err) { + showToast({ message: `Failed to copy value: ${String(err)}`, color: "danger" }); + } + }, + }, + ]; + }, + [store, showToast], + ); + + // Filter by the selected rows, Decrypt or Stop Decrypting the selected hosts, sites and apps, + // from new connections on, then a program's folder. A saved search is renamed or deleted, and + // System is shown in All traffic or left out of it. + const getContextMenu = useCallback( + (items: SidebarItem[]): DropdownItem[] => { + if (items.length === 1 && items[0]?.id === SYSTEM_ID) { + return [ + { + label: "Show in All Traffic", + leftSlot: hideSystem ? ( + + ) : ( + + ), + onSelect: () => setHideSystem(!hideSystem), + }, + ]; + } + const paths = items.length === 1 ? pathItems(items[0]) : []; + const saved = items.flatMap((i) => (i.savedId == null ? [] : [{ ...i, id: i.savedId }])); + if (saved.length > 0) { + const [first] = saved; + return [ + { + label: "Rename", + leftSlot: , + hidden: saved.length > 1 || first == null, + onSelect: () => { + if (first != null) + setSavedDialog({ mode: "rename", id: first.id, name: first.label }); + }, + }, + { + label: "Delete", + color: "danger", + leftSlot: , + onSelect: () => { + for (const s of saved) deleteSaved({ id: s.id }); + }, + }, + ]; + } + const subjects = items.flatMap((i) => (i.decrypt == null ? [] : [i.decrypt])); + const action = decryptMenuAction(decryptList, subjects); + const decrypt: DropdownItem[] = + action == null + ? [] + : [ + { + label: action.label, + icon: action.on ? "lock_open" : "lock", + onSelect: () => { + const blocked = action.on ? blockerOf(decryptList, subjects) : null; + if (blocked != null) { + showToast({ + id: "decrypt-blocked", + color: "notice", + message: `Excluded by ${blocked}`, + }); + return; + } + // Only what this changes, applied to the list as it is then, so a second change + // made before this one lands keeps it. + const next = setDecrypted(decryptList, subjects, action.on); + saveDecryptList(listEdit(decryptList, next)); + }, + }, + ]; + return withSeparators([filterItems(items), decrypt, paths]); + }, + [ + decryptList, + saveDecryptList, + showToast, + setSavedDialog, + deleteSaved, + pathItems, + filterItems, + hideSystem, + setHideSystem, + ], + ); + const renderContextMenu = useCallback["renderContextMenu"]>>( + ({ items, position, onClose }) => + items.length === 0 ? ( + + ) : ( + + ), + [], + ); return ( // The tree scrolls itself, in a row of bounded height, so its virtualizer mounts only the rows - // in view rather than every domain and path. -