Merge main into feat/request-versioning

Clean merge with no conflicts or compile fixes. Regenerated bindings
differ from the merged files only in formatting, so none are included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and Stetta task tk_mw563e1dcqtc4sqh committed 2026-11-10 14:27:51 -07:00
commit 07956fe68e
326 files changed
+48389 -5165

No files matched your search

+3
View File
@@ -59,3 +59,6 @@ flatpak/node-sources.json
# Claude Code local settings
.claude/settings.local.json
.claude/worktrees/
# Headless screenshots taken while working
.shots/
Generated
+96
View File
@@ -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"
+2
View File
@@ -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" }
@@ -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";
@@ -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 {
@@ -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";
+64 -106
View File
@@ -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<SettingsTab, Omit<SettingsTabDef, "value" | "label">> = {
[TAB_GENERAL]: { icon: "settings", content: <SettingsGeneral /> },
[TAB_THEME]: { icon: "palette", content: <SettingsTheme /> },
[TAB_INTERFACE]: { icon: "columns_2", content: <SettingsInterface /> },
[TAB_SHORTCUTS]: { icon: "keyboard", content: <SettingsHotkeys /> },
[TAB_PLUGINS]: {
icon: "puzzle",
rightSlot: <CountBadge count={plugins.filter((p) => p.source !== "bundled").length} />,
content: <SettingsPlugins defaultSubtab={mainTab === TAB_PLUGINS ? subtab : undefined} />,
contentClassName: "h-full grid grid-rows-1",
},
[TAB_AGENTS]: {
icon: "sparkles",
hidden: !platform.capabilities.agents,
content: <SettingsAgents />,
},
[TAB_CERTIFICATES]: {
icon: "shield_check",
rightSlot: <CountBadge count={settings.clientCertificates.length} />,
content: <SettingsCertificates />,
},
[TAB_PROXY]: {
icon: "wifi",
rightSlot: settings.proxy?.type === "enabled" ? <CountBadge count /> : null,
content: <SettingsProxy />,
},
[TAB_LICENSE]: {
icon: "key_round",
hidden: !appInfo.featureLicense,
rightSlot:
licenseCheck.check.data?.status === "personal_use" ? (
<CountBadge count color="notice" />
) : null,
content: <SettingsLicense />,
},
};
return (
<div className={classNames("grid grid-rows-[auto_minmax(0,1fr)] h-full")}>
{hide ? (
<span />
) : (
<HeaderSize
data-tauri-drag-region
ignoreControlsSpacing
onlyXWindowControl
size="md"
className="x-theme-appHeader bg-surface text-text-subtle flex items-center justify-center border-b border-border-subtle text-sm font-semibold"
osType={platform.osType()}
hideWindowControls={settings.hideWindowControls}
useNativeTitlebar={settings.useNativeTitlebar}
interfaceScale={settings.interfaceScale}
>
<HStack
space={2}
justifyContent="center"
className="w-full h-full grid grid-cols-[1fr_auto] pointer-events-none"
>
<div className={classNames(platform.osType() === "macos" ? "text-center" : "pl-2")}>Settings</div>
</HStack>
</HeaderSize>
)}
<Tabs
layout="horizontal"
defaultValue={mainTab}
addBorders
tabListClassName="min-w-40 bg-surface x-theme-sidebar border-r border-border pl-3"
label="Settings"
tabs={tabs.map(
(value): TabItem => ({
value,
label: capitalize(value),
hidden:
(!appInfo.featureLicense && value === TAB_LICENSE) ||
(!platform.capabilities.agents && value === TAB_AGENTS),
leftSlot:
value === TAB_GENERAL ? (
<Icon icon="settings" className="text-secondary" />
) : value === TAB_THEME ? (
<Icon icon="palette" className="text-secondary" />
) : value === TAB_INTERFACE ? (
<Icon icon="columns_2" className="text-secondary" />
) : value === TAB_SHORTCUTS ? (
<Icon icon="keyboard" className="text-secondary" />
) : value === TAB_CERTIFICATES ? (
<Icon icon="shield_check" className="text-secondary" />
) : value === TAB_PROXY ? (
<Icon icon="wifi" className="text-secondary" />
) : value === TAB_PLUGINS ? (
<Icon icon="puzzle" className="text-secondary" />
) : value === TAB_AGENTS ? (
<Icon icon="sparkles" className="text-secondary" />
) : value === TAB_LICENSE ? (
<Icon icon="key_round" className="text-secondary" />
) : null,
rightSlot:
value === TAB_CERTIFICATES ? (
<CountBadge count={settings.clientCertificates.length} />
) : value === TAB_PLUGINS ? (
<CountBadge count={plugins.filter((p) => p.source !== "bundled").length} />
) : value === TAB_PROXY && settings.proxy?.type === "enabled" ? (
<CountBadge count />
) : value === TAB_LICENSE && licenseCheck.check.data?.status === "personal_use" ? (
<CountBadge count color="notice" />
) : null,
}),
)}
>
<TabContent value={TAB_GENERAL} className="overflow-y-auto h-full px-6 py-4!">
<SettingsGeneral />
</TabContent>
<TabContent value={TAB_INTERFACE} className="overflow-y-auto h-full px-6 py-4!">
<SettingsInterface />
</TabContent>
<TabContent value={TAB_THEME} className="overflow-y-auto h-full px-6 py-4!">
<SettingsTheme />
</TabContent>
<TabContent value={TAB_SHORTCUTS} className="overflow-y-auto h-full px-6 py-4!">
<SettingsHotkeys />
</TabContent>
<TabContent value={TAB_PLUGINS} className="h-full grid grid-rows-1">
<SettingsPlugins defaultSubtab={mainTab === TAB_PLUGINS ? subtab : undefined} />
</TabContent>
<TabContent value={TAB_AGENTS} className="overflow-y-auto h-full px-6 py-4!">
<SettingsAgents />
</TabContent>
<TabContent value={TAB_PROXY} className="overflow-y-auto h-full px-6 py-4!">
<SettingsProxy />
</TabContent>
<TabContent value={TAB_CERTIFICATES} className="overflow-y-auto h-full px-6 py-4!">
<SettingsCertificates />
</TabContent>
<TabContent value={TAB_LICENSE} className="overflow-y-auto h-full px-6 py-4!">
<SettingsLicense />
</TabContent>
</Tabs>
</div>
<SettingsDialog
defaultTab={mainTab}
titlebar={
hide
? null
: {
osType: platform.osType(),
hideWindowControls: settings.hideWindowControls,
useNativeTitlebar: settings.useNativeTitlebar,
interfaceScale: settings.interfaceScale,
}
}
tabs={tabs.map((value) => ({ value, label: capitalize(value), ...tabDefs[value] }))}
/>
);
}
@@ -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,
@@ -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 (
<VStack space={1.5} className="mb-4">
<div>
<Heading>General</Heading>
<p className="text-text-subtle">
Configure general settings for update behavior and more.
</p>
</div>
<div className="mt-3 mb-5">
<CommercialUseBanner source="settings-general" title="Using Yaak for work?" />
</div>
<SettingsList className="space-y-8">
<CargoFeature feature="updater">
<SettingsSection title="Updates">
<SettingRow
title="Update Channel"
description="Choose whether Yaak should use stable releases or beta releases."
>
<div className="grid grid-cols-[12rem_auto] gap-1">
<ModelSettingSelectControl
model={settings}
modelKey="updateChannel"
label="Update Channel"
selectClassName="w-full!"
options={[
{ label: "Stable", value: "stable" },
{ label: "Beta", value: "beta" },
]}
/>
<IconButton
variant="border"
size="sm"
title="Check for updates"
icon="refresh"
spin={checkForUpdates.isPending}
onClick={() => checkForUpdates.mutateAsync()}
/>
</div>
</SettingRow>
<SettingRowSelect
title="Update Behavior"
description="Choose whether updates are installed automatically or manually."
name="autoupdate"
value={settings.autoupdate ? "auto" : "manual"}
onChange={(v) =>
patchModel(settings, { autoupdate: v === "auto" })
}
options={[
{ label: "Automatic", value: "auto" },
{ label: "Manual", value: "manual" },
]}
/>
<ModelSettingRowBoolean
model={settings}
modelKey="autoDownloadUpdates"
title="Automatically download updates"
description="Download Yaak updates in the background so they are ready to install."
disabled={!settings.autoupdate}
/>
<ModelSettingRowBoolean
model={settings}
modelKey="checkNotifications"
title="Check for notifications"
description="Periodically ping Yaak servers to check for relevant notifications."
/>
<SettingRowBoolean
title="Send anonymous usage statistics"
description="Yaak is local-first and does not collect analytics or usage data."
disabled
checked={false}
onChange={() => {}}
/>
</SettingsSection>
</CargoFeature>
<CargoFeature feature="license">
<SettingsSection title="Feedback">
<SettingRowBoolean
title="Prompt for feedback"
description="Show rare one-time prompts asking how new features are working."
checked={settings.promptFeedback}
onChange={(promptFeedback) => patchModel(settings, { promptFeedback })}
/>
</SettingsSection>
</CargoFeature>
{showWorkspaceSettingsMovedBanner && (
<SharedSettingsGeneral
view={bound.view}
callbacks={bound.callbacks}
banner={<CommercialUseBanner source="settings-general" title="Using Yaak for work?" />}
extraSections={
showWorkspaceSettingsMovedBanner && (
<DismissibleBanner
id="workspace-settings-moved-2026-06-30"
color="info"
className="w-full p-4 max-w-xl mr-auto"
>
<p>
Workspace specific settings have moved to{" "}
<b>Workspace Settings</b>, accessible from the workspace switcher
menu.
Workspace specific settings have moved to <b>Workspace Settings</b>, accessible from
the workspace switcher menu.
</p>
</DismissibleBanner>
)}
<SettingsSection title="App Info">
<SettingRow title="Version" description="Current Yaak version.">
<SettingValue value={appInfo.version} />
</SettingRow>
<SettingRow
title="Data Directory"
description="Where Yaak stores application data."
controlClassName="min-w-0 max-w-[min(42rem,55vw)] gap-2"
>
<SettingValue
value={appInfo.appDataDir}
actions={[
{
title: revealInFinderText,
icon: "folder_open",
onClick: () => platform.revealItemInDir(appInfo.appDataDir),
},
]}
/>
</SettingRow>
<SettingRow
title="Logs Directory"
description="Where Yaak writes application logs."
controlClassName="min-w-0 max-w-[min(42rem,55vw)] gap-2"
>
<SettingValue
value={appInfo.appLogDir}
actions={[
{
title: revealInFinderText,
icon: "folder_open",
onClick: () => platform.revealItemInDir(appInfo.appLogDir),
},
]}
/>
</SettingRow>
</SettingsSection>
</SettingsList>
</VStack>
)
}
/>
);
}
@@ -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 (
<VStack space={1.5} className="mb-4">
<div className="mb-3">
<Heading>Interface</Heading>
<p className="text-text-subtle">Tweak settings related to the user interface.</p>
</div>
<SettingsList className="space-y-8">
<SharedSettingsInterface
view={bound.view}
callbacks={bound.callbacks}
leadingSections={
<SettingsSection title="Workspaces">
<SettingRowSelect
title="Open workspace behavior"
@@ -78,151 +49,13 @@ export function SettingsInterface() {
]}
/>
</SettingsSection>
<SettingsSection title="Fonts">
<SettingRow
title="Interface font"
description="Font used for Yaak interface controls."
controlClassName="gap-1"
>
{fonts.data && (
<SettingSelectControl
name="uiFont"
label="Interface font"
selectClassName="w-72!"
value={settings.interfaceFont ?? NULL_FONT_VALUE}
defaultValue={NULL_FONT_VALUE}
options={[
{ label: "System default", value: NULL_FONT_VALUE },
...fonts.data.uiFonts.map((f) => ({ 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 });
}}
/>
)}
<SettingSelectControl
name="interfaceFontSize"
label="Interface Font Size"
selectClassName="w-20!"
value={`${settings.interfaceFontSize}`}
defaultValue="14"
options={fontSizeOptions}
onChange={(v) => patchModel(settings, { interfaceFontSize: Number.parseInt(v, 10) })}
/>
</SettingRow>
<SettingRow
title="Editor font"
description="Font used in request and response editors."
controlClassName="gap-1"
>
{fonts.data && (
<SettingSelectControl
name="editorFont"
label="Editor font"
selectClassName="w-72!"
value={settings.editorFont ?? NULL_FONT_VALUE}
defaultValue={NULL_FONT_VALUE}
options={[
{ label: "System default", value: NULL_FONT_VALUE },
...fonts.data.editorFonts.map((f) => ({ label: f, value: f })),
]}
onChange={async (v) => {
const editorFont = v === NULL_FONT_VALUE ? null : v;
await patchModel(settings, { editorFont });
}}
/>
)}
<SettingSelectControl
name="editorFontSize"
label="Editor Font Size"
selectClassName="w-20!"
value={`${settings.editorFontSize}`}
defaultValue="12"
options={fontSizeOptions}
onChange={(v) =>
patchModel(settings, {
editorFontSize: clamp(Number.parseInt(v, 10) || 14, 8, 30),
})
}
/>
</SettingRow>
</SettingsSection>
<SettingsSection title="Editor">
<ModelSettingRowSelect
model={settings}
modelKey="editorKeymap"
title="Editor keymap"
description="Keyboard shortcut preset used by text editors."
options={keymaps}
/>
<ModelSettingRowBoolean
model={settings}
modelKey="editorSoftWrap"
title="Wrap editor lines"
description="Wrap long lines in request and response editors."
/>
<ModelSettingRowBoolean
model={settings}
modelKey="coloredMethods"
title="Colorize request methods"
description="Use method-specific colors for HTTP request methods."
/>
</SettingsSection>
<SettingsSection title="Window">
<NativeTitlebarSetting settings={settings} />
{platform.osType() !== "macos" && (
<ModelSettingRowBoolean
model={settings}
modelKey="hideWindowControls"
title="Hide window controls"
description="Hide the close, maximize, and minimize controls on Windows or Linux."
/>
)}
</SettingsSection>
}
trailingSections={
<CargoFeature feature="license">
<LicenseSettings settings={settings} />
</CargoFeature>
</SettingsList>
</VStack>
);
}
function NativeTitlebarSetting({ settings }: { settings: Settings }) {
const [nativeTitlebar, setNativeTitlebar] = useState(settings.useNativeTitlebar);
return (
<SettingRow
title="Native title bar"
description="Use the operating system's standard title bar and window controls."
controlClassName="gap-2"
>
<Checkbox
hideLabel
size="md"
checked={nativeTitlebar}
title="Native title bar"
onChange={setNativeTitlebar}
/>
{settings.useNativeTitlebar !== nativeTitlebar && (
<Button
color="primary"
size="xs"
onClick={async () => {
await patchModel(settings, { useNativeTitlebar: nativeTitlebar });
await rpc("cmd_restart");
}}
>
Apply and Restart
</Button>
)}
</SettingRow>
}
/>
);
}
@@ -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<string>("");
const [activateFormVisible, toggleActivateFormVisible] = useToggle(false);
if (check.isPending) {
return null;
}
const renderBanner = () => {
if (!check.data) return null;
switch (check.data.status) {
case "active":
return <Banner color="success">Your license is active 🥳</Banner>;
case "trialing":
return (
<Banner color="info" className="max-w-lg">
<p className="w-full">
<strong>
{pluralizeCount("day", differenceInDays(check.data.data.end, new Date()))}
</strong>{" "}
left to evaluate Yaak for commercial use.
<br />
<span className="opacity-50">Personal use is always free, forever.</span>
<Separator className="my-2" />
<div className="flex flex-wrap items-center gap-x-2 text-sm text-notice">
<Link noUnderline href={pricingUrl(`app.license.learn.${check.data.status}`)}>
Learn More
</Link>
</div>
</p>
</Banner>
);
case "personal_use":
return (
<Banner color="notice" className="max-w-lg">
<p className="w-full">
Your commercial-use trial has ended.
<br />
<span className="opacity-50">
You may continue using Yaak for personal use only.
<br />A license is required for commercial use.
</span>
<Separator className="my-2" />
<div className="flex flex-wrap items-center gap-x-2 text-sm text-notice">
<Link noUnderline href={pricingUrl(`app.license.learn.${check.data.status}`)}>
Learn More
</Link>
</div>
</p>
</Banner>
);
case "inactive":
return (
<Banner color="danger">
Your license is invalid. Please <Link href="https://yaak.app/dashboard">Sign In</Link>{" "}
for more details
</Banner>
);
case "expired":
return (
<Banner color="notice">
Your license expired{" "}
<strong>{formatDate(check.data.data.periodEnd, "MMMM dd, yyyy")}</strong>. Please{" "}
<Link href="https://yaak.app/dashboard">Resubscribe</Link> to continue receiving
updates.
{check.data.data.changesUrl && (
<>
<br />
<Link href={check.data.data.changesUrl}>What's new in latest builds</Link>
</>
)}
</Banner>
);
case "past_due":
return (
<Banner color="danger">
<strong>Your payment method needs attention.</strong>
<br />
To re-activate your license, please{" "}
<Link href={check.data.data.billingUrl}>update your billing info</Link>.
</Banner>
);
case "error":
return (
<Banner color="danger">
License check failed: {check.data.data.message} (Code: {check.data.data.code})
</Banner>
);
}
};
return (
<div className="flex flex-col gap-6 max-w-xl">
{renderBanner()}
{check.error && <Banner color="danger">{check.error}</Banner>}
{activate.error && <Banner color="danger">{activate.error}</Banner>}
{check.data?.status === "active" ? (
<HStack space={2}>
<Button variant="border" color="secondary" size="sm" onClick={() => deactivate.mutate()}>
Deactivate License
</Button>
<Button
color="secondary"
size="sm"
onClick={() => platform.openUrl("https://yaak.app/dashboard?intent=app.license.support")}
rightSlot={<Icon icon="external_link" />}
>
Direct Support
</Button>
</HStack>
) : (
<HStack space={2}>
<Button variant="border" color="secondary" size="sm" onClick={toggleActivateFormVisible}>
Activate License
</Button>
<Button
size="sm"
color="primary"
rightSlot={<Icon icon="external_link" />}
onClick={() =>
platform.openUrl(pricingUrl(`app.license.purchase.${check.data?.status ?? "unknown"}`))
}
>
Purchase License
</Button>
</HStack>
)}
{activateFormVisible && (
<VStack
as="form"
space={3}
className="max-w-sm"
onSubmit={async (e) => {
e.preventDefault();
await activate.mutateAsync({ licenseKey: key });
toggleActivateFormVisible();
}}
>
<PlainInput
autoFocus
label="License Key"
name="key"
onChange={setKey}
placeholder="YK1-XXXXX-XXXXX-XXXXX-XXXXX"
/>
<Button type="submit" color="primary" size="sm" isLoading={activate.isPending}>
Submit
</Button>
</VStack>
)}
</div>
);
const bound = useSettingsView();
if (bound == null) return null;
return <SharedSettingsLicense view={bound.view} callbacks={bound.callbacks} />;
}
@@ -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<string>["options"] = activeTheme.data.themes
.filter((theme) => !theme.dark)
.map((theme) => ({
label: theme.label,
value: theme.id,
}));
const darkThemes: SelectProps<string>["options"] = activeTheme.data.themes
.filter((theme) => theme.dark)
.map((theme) => ({
label: theme.label,
value: theme.id,
}));
return (
<VStack space={1.5} className="mb-4">
<div className="mb-3">
<Heading>Theme</Heading>
<p className="text-text-subtle">
Make Yaak your own by selecting a theme, or{" "}
<Link href="https://yaak.app/docs/plugin-development/plugins-quick-start">
Create Your Own
</Link>
</p>
</div>
<SettingsList className="space-y-8">
<SettingsSection title="Theme">
<ModelSettingRowSelect
model={settings}
modelKey="appearance"
title="Appearance"
description="Choose whether Yaak follows your system appearance or uses a fixed mode."
options={[
{ label: "Automatic", value: "system" },
{ label: "Light", value: "light" },
{ label: "Dark", value: "dark" },
]}
/>
{(settings.appearance === "system" || settings.appearance === "light") && (
<SettingRowSelect
name="lightTheme"
title="Light theme"
description="Theme used when Yaak is in light mode."
value={activeTheme.data.light.id}
options={lightThemes}
onChange={(themeLight) => patchModel(settings, { themeLight })}
/>
)}
{(settings.appearance === "system" || settings.appearance === "dark") && (
<SettingRowSelect
name="darkTheme"
title="Dark theme"
description="Theme used when Yaak is in dark mode."
value={activeTheme.data.dark.id}
options={darkThemes}
onChange={(themeDark) => patchModel(settings, { themeDark })}
/>
)}
</SettingsSection>
<SettingsSection title="Preview">
<VStack
space={3}
className="mt-4 w-full bg-surface p-3 border border-dashed border-border-subtle rounded-sm overflow-x-auto"
>
<HStack className="text" space={1.5}>
<Icon icon={appearance === "dark" ? "moon" : "sun"} />
<strong>{activeTheme.data.active.label}</strong>
<em>(preview)</em>
</HStack>
<HStack space={1.5} className="w-full">
{buttonColors.map((c, i) => (
<IconButton
key={c}
color={c}
size="2xs"
iconSize="xs"
icon={icons[i % icons.length] ?? "info"}
iconClassName="text"
title={`${c}`}
/>
))}
{buttonColors.map((c, i) => (
<IconButton
key={c}
color={c}
variant="border"
size="2xs"
iconSize="xs"
icon={icons[i % icons.length] ?? "info"}
iconClassName="text"
title={`${c}`}
/>
))}
</HStack>
<Suspense>
<Editor
defaultValue={[
"let foo = { // Demo code editor",
' foo: ("bar" || "baz" ?? \'qux\'),',
" baz: [1, 10.2, null, false, true],",
"};",
].join("\n")}
heightMode="auto"
language="javascript"
stateKey={null}
/>
</Suspense>
</VStack>
</SettingsSection>
</SettingsList>
</VStack>
);
return <SharedSettingsTheme view={bound.view} callbacks={bound.callbacks} />;
}
+75 -39
View File
@@ -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<HTMLElement>(null);
const treeRef = useRef<TreeHandle>(null);
@@ -553,18 +551,18 @@ function Sidebar({ className }: { className?: string }) {
const filterCompartmentMountExtRef = useRef<Extension | null>(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<SidebarModel>, FieldDef[], SidebarFilterSuggestion[]] | null
[TreeNode<SidebarModel>, Record<string, string[]>, 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<SidebarModel>[] = [];
const cells: (string | null)[] = [];
// returns true if this node OR any child matches the filter
const allFields: Record<string, Set<string>> = {};
const suggestionFields = new Set<string>();
const build = (node: TreeNode<SidebarModel>, depth: number): boolean => {
const build = (node: TreeNode<SidebarModel>, 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<TreeNode<SidebarModel>> | null = null;
const markHidden = (node: TreeNode<SidebarModel>): 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<SidebarModel> = {
@@ -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<string, string[]> = {};
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<Record<string, GitStatus>>((get) => {
+3 -15
View File
@@ -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 <RedirectToLatestWorkspace />;
}
@@ -81,13 +75,7 @@ export function Workspace() {
useNativeTitlebar={settings.useNativeTitlebar}
interfaceScale={settings.interfaceScale}
>
<div className="absolute inset-0 pointer-events-none">
<div style={environmentBgStyle} className="absolute inset-0 opacity-[0.07]" />
<div
style={environmentBgStyle}
className="absolute left-0 right-0 -bottom-px h-px opacity-20"
/>
</div>
<HeaderTint color={activeEnvironment?.color ?? null} />
<WorkspaceHeader className="pointer-events-none" floatingSidebar={floating} />
</HeaderSize>
);
@@ -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<unknown>>(),
mergeModelsInStore: vi.fn(),
deleteModelWithConfirm: vi.fn<(model: unknown) => Promise<boolean>>(),
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<WorkspaceMeta[]>([]),
mergeModelsInStore: mocks.mergeModelsInStore,
patchModel: vi.fn(),
};
});
vi.mock("@yaakapp-internal/ui", () => ({
Banner: ({ children }: { children: ReactNode }) => <div role="alert">{children}</div>,
CountBadge: () => null,
HStack: ({ children }: { children: ReactNode }) => <div>{children}</div>,
InlineCode: ({ children }: { children: ReactNode }) => <code>{children}</code>,
}));
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 }) => (
<button type="button" onClick={onClick}>
{children}
</button>
),
}));
vi.mock("./core/PlainInput", () => ({
PlainInput: ({ label, defaultValue }: { label: string; defaultValue: string }) => (
<input aria-label={label} defaultValue={defaultValue} />
),
}));
vi.mock("./core/SettingRow", () => ({
SettingsList: ({ children }: { children: ReactNode }) => <div>{children}</div>,
SettingsSection: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));
// Render every tab at once so the test can see all of them
vi.mock("./core/Tabs/Tabs", () => ({
Tabs: ({ children }: { children: ReactNode }) => <div>{children}</div>,
TabContent: ({ children, value }: { children: ReactNode; value: string }) => (
<div data-tab={value}>{children}</div>
),
}));
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 } }) => (
<div data-testid="sync-setting">{value.filePath}</div>
),
}));
vi.mock("./WorkspaceEncryptionSetting", () => ({
WorkspaceEncryptionSetting: () => <div data-testid="encryption-setting" />,
}));
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<WorkspaceMeta[]>;
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(<WorkspaceSettingsDialog workspaceId="wk_test" hide={() => {}} />),
);
}
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<HTMLInputElement>('input[aria-label="Name"]')?.value).toBe("Broken");
expect(general.contains(deleteButton() ?? null)).toBe(true);
});
@@ -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 (
<Banner color="danger">
<InlineCode>WorkspaceMeta</InlineCode> not found for workspace
</Banner>
);
return (
<Tabs
defaultValue={tab ?? DEFAULT_TAB}
@@ -105,15 +110,26 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) {
<TabContent value={TAB_SETTINGS} className="overflow-y-auto h-full px-4">
<SettingsList className="space-y-8 pb-3">
<SettingsSection title={null}>
<SyncToFilesystemSetting
layout="settings"
value={{ filePath: workspaceMeta.settingSyncDir }}
onCreateNewWorkspace={hide}
onChange={({ filePath }) => patchModel(workspaceMeta, { settingSyncDir: filePath })}
/>
<div className="mt-4">
<WorkspaceEncryptionSetting layout="settings" size="xs" />
</div>
{workspaceMeta != null ? (
<>
<SyncToFilesystemSetting
layout="settings"
value={{ filePath: workspaceMeta.settingSyncDir }}
onCreateNewWorkspace={hide}
onChange={({ filePath }) =>
patchModel(workspaceMeta, { settingSyncDir: filePath })
}
/>
<div className="mt-4">
<WorkspaceEncryptionSetting layout="settings" size="xs" />
</div>
</>
) : workspaceMetaError != null ? (
<Banner color="danger">
Sync and encryption settings are unavailable because{" "}
<InlineCode>WorkspaceMeta</InlineCode> could not be loaded: {workspaceMetaError}
</Banner>
) : null}
</SettingsSection>
<ModelSettingsEditor model={workspace} showSectionTitles />
</SettingsList>
@@ -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<string | null>(null);
useEffect(() => {
if (!missing) return;
let cancelled = false;
setError(null);
rpc<WorkspaceMeta>("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",
@@ -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"
@@ -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");
});
});
@@ -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
})
@@ -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);
});
});
@@ -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}`;
}
@@ -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,
});
@@ -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<Tok, { kind: "PHRASE" }>;
return { type: "Phrase", value: t.text };
}
// Field or bare word
if (this.at("WORD")) {
const wordTok = this.advance() as Extract<Tok, { kind: "WORD" }>;
if (this.at("COLON")) {
// field:value or field:"phrase"
this.advance(); // :
let value: string;
if (this.at("PHRASE")) {
const p = this.advance() as Extract<Tok, { kind: "PHRASE" }>;
value = p.text;
} else if (this.at("WORD")) {
const w = this.advance() as Extract<Tok, { kind: "WORD" }>;
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<Tok, { kind: "WORD" }>;
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<string, unknown>;
};
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<string, string[]> = {};
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);
}
@@ -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<T> {
/** 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<T>({
events,
getEventKey,
renderRow,
renderDetail,
header,
error,
splitLayoutStorageKey,
defaultRatio = 0.4,
enableKeyboardNav = true,
isLoading = false,
loadingMessage = "Loading events...",
emptyMessage = "No events recorded",
onActiveIndexChange,
}: EventViewerProps<T>) {
const [activeIndex, setActiveIndexInternal] = useState<number | null>(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<HTMLDivElement>(null);
const virtualizerRef = useRef<Virtualizer<HTMLDivElement, Element> | 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<HTMLDivElement, Element>) => {
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 <div className="p-3 text-text-subtlest italic">{loadingMessage}</div>;
}
if (events.length === 0 && !error) {
return <div className="p-3 text-text-subtlest italic">{emptyMessage}</div>;
}
return (
<div ref={containerRef} className="h-full">
<SplitLayout
layout="vertical"
storageKey={splitLayoutStorageKey}
defaultRatio={defaultRatio}
minHeightPx={72}
firstSlot={({ style }) => (
<div style={style} className="w-full h-full grid grid-rows-[auto_minmax(0,1fr)]">
{header ?? <span aria-hidden />}
<AutoScroller
data={events}
focusable={enableKeyboardNav}
onVirtualizerReady={handleVirtualizerReady}
header={
error && (
<Banner color="danger" className="m-3">
{error}
</Banner>
)
}
render={(event, index) => (
<div key={getEventKey(event, index)}>
{renderRow({
event,
index,
isActive: index === activeIndex,
onClick: () => handleRowClick(index),
})}
</div>
)}
/>
</div>
)}
secondSlot={
activeEvent != null && renderDetail && isPanelOpen
? ({ style }) => (
<div style={style} className="grid grid-rows-[auto_minmax(0,1fr)] bg-surface">
<div className="pb-3 px-2">
<Separator />
</div>
<div className="mx-2 overflow-y-auto">
{renderDetail({
event: activeEvent,
index: activeIndex ?? 0,
onClose: handleClose,
})}
</div>
</div>
)
: null
}
/>
</div>
);
}
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<string>["options"];
/** Change handler */
onChange: (value: string) => void;
};
interface EventDetailHeaderProps {
title: string;
prefix?: ReactNode;
timestamp?: string;
actions?: EventDetailAction[];
copyText?: string | (() => Promise<string | null>);
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 (
<div className="flex items-center justify-between gap-2 mb-2 h-xs">
<HStack space={2} className="items-center min-w-0">
{prefix}
<h3 className="font-semibold select-auto cursor-auto truncate">{title}</h3>
</HStack>
<HStack space={2} className="items-center">
{actions?.map((action) =>
action.type === "select" ? (
<div key={action.key} className="w-32">
<Select
name={action.key}
label={action.label}
hideLabel
size="xs"
value={action.value}
options={action.options}
onChange={action.onChange}
/>
</div>
) : (
<Button
key={action.key}
type="button"
variant="border"
size="xs"
onClick={action.onClick}
>
{action.icon}
{action.label}
</Button>
),
)}
{copyText != null && (
<CopyIconButton text={copyText} size="xs" title="Copy" variant="border" iconSize="sm" />
)}
{formattedTime && (
<span className="text-text-subtlest font-mono text-editor ml-2">{formattedTime}</span>
)}
{onClose != null && (
<div
className={classNames(
copyText != null ||
formattedTime ||
((actions ?? []).length > 0 && "border-l border-l-surface-highlight ml-2 pl-3"),
)}
>
<IconButton
color="custom"
className="text-text-subtle -mr-3"
size="xs"
icon="x"
title="Close event panel"
onClick={onClose}
/>
</div>
)}
</HStack>
</div>
);
}
export type { EventDetailAction } from "@yaakapp-internal/ui";
export { EventDetailHeader, EventViewer } from "@yaakapp-internal/ui";
@@ -1,38 +1 @@
import classNames from "classnames";
import { format } from "date-fns";
import type { ReactNode } from "react";
interface EventViewerRowProps {
isActive: boolean;
onClick: () => void;
icon: ReactNode;
content: ReactNode;
timestamp?: string;
}
export function EventViewerRow({
isActive,
onClick,
icon,
content,
timestamp,
}: EventViewerRowProps) {
return (
<div className="px-1">
<button
type="button"
onClick={onClick}
className={classNames(
"w-full grid grid-cols-[auto_minmax(0,1fr)_auto] gap-2 items-center text-left",
"px-1.5 h-xs font-mono text-editor cursor-default group focus:outline-hidden focus:text-text rounded-sm",
isActive && "bg-surface-active text-text!",
"text-text-subtle hover:text",
)}
>
{icon}
<div className="w-full truncate">{content}</div>
{timestamp && <div className="opacity-50">{format(`${timestamp}Z`, "HH:mm:ss.SSS")}</div>}
</button>
</div>
);
}
export { EventViewerRow } from "@yaakapp-internal/ui";
+28 -32
View File
@@ -3,16 +3,43 @@ import { platform } from "@yaakapp-internal/platform";
import classNames from "classnames";
import type { HTMLAttributes } from "react";
import { appInfo } from "../../lib/appInfo";
import { Icon } from "@yaakapp-internal/ui";
import { ExternalLink, isYaakUrl } from "@yaakapp-internal/ui";
interface Props extends HTMLAttributes<HTMLAnchorElement> {
href: string;
noUnderline?: boolean;
}
/** Tags a link to yaak.app with which app it came from */
export function withYaakRef(href: string): string {
if (!isYaakUrl(href)) return href;
const url = new URL(href);
url.searchParams.set("ref", appInfo.identifier);
return url.toString();
}
/** Opens a link outside the app, tagged as `Link` tags it */
export function openExternalUrl(href: string) {
void platform.openUrl(withYaakRef(href));
}
export function Link({ href, children, noUnderline, className, ...other }: Props) {
const isExternal = href.match(/^https?:\/\//);
if (isExternal) {
return (
<ExternalLink
href={withYaakRef(href)}
noUnderline={noUnderline}
onOpen={openExternalUrl}
className={className}
{...other}
>
{children}
</ExternalLink>
);
}
className = classNames(
className,
"relative",
@@ -20,37 +47,6 @@ export function Link({ href, children, noUnderline, className, ...other }: Props
!noUnderline && "underline",
);
if (isExternal) {
const isYaakLink = href.startsWith("https://yaak.app");
let finalHref = href;
if (isYaakLink) {
const url = new URL(href);
url.searchParams.set("ref", appInfo.identifier);
finalHref = url.toString();
}
return (
// eslint-disable-next-line react/jsx-no-target-blank
<a
href={finalHref}
target="_blank"
rel={isYaakLink ? undefined : "noopener noreferrer"}
onClick={(e) => {
e.preventDefault();
void platform.openUrl(finalHref);
}}
className={className}
{...other}
>
<span className="pr-5">{children}</span>
<Icon
className="inline absolute right-0.5 top-[0.3em] opacity-70 group-hover:opacity-100"
size="xs"
icon="external_link"
/>
</a>
);
}
return (
<RouterLink to={href} className={className} {...other}>
{children}
+2 -148
View File
@@ -1,148 +1,2 @@
import { platform } from "@yaakapp-internal/platform";
import { HStack, Label } from "@yaakapp-internal/ui";
import classNames from "classnames";
import type { CSSProperties, ReactNode } from "react";
import { useState } from "react";
import type { ButtonProps } from "./Button";
import { Button } from "./Button";
import type { RadioDropdownItem } from "./RadioDropdown";
import { RadioDropdown } from "./RadioDropdown";
export interface SelectProps<T extends string> {
name: string;
label: string;
labelPosition?: "top" | "left";
labelClassName?: string;
hideLabel?: boolean;
value: T;
help?: ReactNode;
leftSlot?: ReactNode;
options: RadioDropdownItem<T>[];
onChange: (value: T) => void;
defaultValue?: T;
size?: ButtonProps["size"];
className?: string;
disabled?: boolean;
filterable?: boolean;
}
export function Select<T extends string>({
labelPosition = "top",
name,
help,
labelClassName,
disabled,
hideLabel,
label,
value,
options,
leftSlot,
onChange,
className,
defaultValue,
filterable,
size = "md",
}: SelectProps<T>) {
const [focused, setFocused] = useState<boolean>(false);
const id = `input-${name}`;
const isInvalidSelection = options.find((o) => "value" in o && o.value === value) == null;
const handleChange = (value: T) => {
onChange?.(value);
};
return (
<div
className={classNames(
className,
"x-theme-input",
"w-full",
"pointer-events-auto", // Just in case we're placing in disabled parent
labelPosition === "left" && "grid grid-cols-[auto_1fr] items-center gap-2",
labelPosition === "top" && "flex-row gap-0.5",
)}
>
<Label htmlFor={id} visuallyHidden={hideLabel} className={labelClassName} help={help}>
{label}
</Label>
{platform.osType() === "macos" && !filterable ? (
<HStack
space={2}
className={classNames(
"w-full rounded-md text text-sm font-mono",
"pl-2",
"border",
focused && !disabled ? "border-border-focus" : "border-border",
disabled && "border-dotted",
isInvalidSelection && "border-danger",
size === "xs" && "h-xs",
size === "sm" && "h-sm",
size === "md" && "h-md",
)}
>
{leftSlot && <div>{leftSlot}</div>}
<select
value={value}
style={selectBackgroundStyles}
onChange={(e) => 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 && <option value={"__NONE__"}>-- Select an Option --</option>}
{options.map((o) => {
if (o.type === "separator") return null;
return (
<option key={o.value} value={o.value}>
{o.label}
{o.value === defaultValue && " (default)"}
</option>
);
})}
</select>
</HStack>
) : (
// Use custom "select" component until Tauri can be configured to have select menus not always appear in
// light mode
<RadioDropdown
value={value}
onChange={handleChange}
items={options.map((o) =>
o.type === "separator" || o.value !== defaultValue
? o
: { ...o, label: <>{o.label} (default)</> },
)}
>
<Button
className={classNames(
"w-full text-sm font-mono",
disabled && "border-dotted",
isInvalidSelection && "border-danger",
)}
justify="start"
variant="input"
size={size}
leftSlot={leftSlot}
disabled={disabled}
forDropdown
>
{options.find((o) => o.type !== "separator" && o.value === value)?.label ?? "--"}
</Button>
</RadioDropdown>
)}
</div>
);
}
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";
+25 -450
View File
@@ -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<T, V> = {
[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 <div className={classNames("w-full", className)}>{children}</div>;
}
export function SettingsSection({
children,
className,
description,
title,
}: {
children: ReactNode;
className?: string;
description?: ReactNode;
title: ReactNode | null;
}) {
const showHeader = title != null || description != null;
return (
<section className={classNames(className, "w-full")}>
{showHeader && (
<div className="border-b border-border-subtle pb-2">
{title != null && <div className="text-text-subtle">{title}</div>}
{description != null && <p className="mt-1 text-sm text-text-subtlest">{description}</p>}
</div>
)}
<div className="[&>*:last-child]:border-b-0">{children}</div>
</section>
);
}
export function SettingRow({
children,
className,
controlClassName,
description,
disabled,
title,
}: {
children: ReactNode;
} & SettingRowBaseProps) {
return (
<div
aria-disabled={disabled || undefined}
className={classNames(
className,
"@container border-b border-border-subtle py-4",
disabled && "opacity-disabled",
)}
>
<div
className={classNames(
"grid grid-cols-1 gap-2",
"@[30rem]:grid-cols-[minmax(0,1fr)_auto] items-center",
)}
>
<div className="min-w-0">
<div className="text text-text">{title}</div>
{description != null && (
<div className="mt-1 max-w-2xl text-sm text-text-subtle">{description}</div>
)}
</div>
<div
className={classNames(
"flex min-w-0 items-center justify-start @[40rem]:justify-end",
controlClassName,
)}
>
{children}
</div>
</div>
</div>
);
}
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 (
<>
<span
className={classNames(
className,
"cursor-text select-text truncate font-mono text-editor text-text-subtle pr-1.5",
)}
>
{value}
</span>
{actions?.map((action) => (
<IconButton
key={action.title}
icon={action.icon}
title={action.title}
size="2xs"
iconSize="sm"
onClick={action.onClick}
/>
))}
{enableCopy && textToCopy != null && (
<CopyIconButton size="2xs" text={textToCopy} title="Copy value" />
)}
</>
);
}
/**
* 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<SettingRowBaseProps, "className">) {
return (
<div
aria-disabled={disabled || undefined}
className={classNames(
className,
"border-b border-border-subtle py-4",
disabled && "opacity-disabled",
)}
>
<div className="flex min-w-0 items-center gap-2 text text-text">
<span>{title}</span>
{done != null && done !== false && (
<span className="inline-flex items-center gap-1 text-sm text-success">
<Icon icon="check" size="sm" />
{done}
</span>
)}
</div>
{description != null && (
<div className="mt-1 max-w-2xl text-sm text-text-subtle">{description}</div>
)}
<SettingSnippet className="mt-3" language={language} snippet={snippet} />
</div>
);
}
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 (
<div
className={classNames(
className,
"flex items-start gap-2 rounded-md border border-border-subtle bg-surface-highlight/40 py-1.5 pr-1.5 pl-3",
)}
>
<div className="flex min-h-sm min-w-0 flex-1 items-center font-mono text-editor text-text">
<span className="cursor-text select-text whitespace-pre-wrap [overflow-wrap:anywhere]">
{prompt && (
<span aria-hidden className="mr-2 select-none text-text-subtlest">
$
</span>
)}
{snippet}
</span>
</div>
<CopyIconButton size="sm" variant="border" title="Copy" text={snippet} className="shrink-0" />
</div>
);
}
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 (
<SettingRow title={title} {...props}>
<Checkbox
hideLabel
size={checkboxSize}
checked={checked}
disabled={props.disabled}
title={title}
onChange={onChange}
/>
</SettingRow>
);
}
export function ModelSettingRowBoolean<M extends AnyModel, K extends ModelKeyOfValue<M, boolean>>({
model,
modelKey,
@@ -272,50 +48,6 @@ export function ModelSettingRowBoolean<M extends AnyModel, K extends ModelKeyOfV
);
}
export function SettingRowNumber({
inputClassName,
inputWidthClassName = "w-48!",
name,
onChange,
placeholder,
required,
title,
type = "number",
validate,
value,
...props
}: {
inputClassName?: string;
inputWidthClassName?: string;
name: string;
onChange: (value: number) => void;
placeholder?: string;
required?: boolean;
type?: "number";
validate?: (value: string) => boolean;
value: number;
} & SettingRowBaseProps) {
return (
<SettingRow title={title} {...props}>
<PlainInput
required={required}
hideLabel
size="sm"
name={name}
label={typeof title === "string" ? title : name}
placeholder={placeholder}
defaultValue={`${value}`}
validate={validate}
onChange={(value) => onChange(Number.parseInt(value, 10) || 0)}
type={type}
className={inputClassName}
containerClassName={inputWidthClassName}
disabled={props.disabled}
/>
</SettingRow>
);
}
export function ModelSettingRowNumber<M extends AnyModel, K extends ModelKeyOfValue<M, number>>({
model,
modelKey,
@@ -334,47 +66,6 @@ export function ModelSettingRowNumber<M extends AnyModel, K extends ModelKeyOfVa
);
}
export function SettingRowText({
inputClassName,
inputWidthClassName = "w-80!",
name,
onChange,
placeholder,
required,
title,
type = "text",
value,
...props
}: {
inputClassName?: string;
inputWidthClassName?: string;
name: string;
onChange: (value: string) => void;
placeholder?: string;
required?: boolean;
type?: "text" | "password";
value: string;
} & SettingRowBaseProps) {
return (
<SettingRow title={title} {...props}>
<PlainInput
required={required}
hideLabel
size="sm"
name={name}
label={typeof title === "string" ? title : name}
placeholder={placeholder}
defaultValue={value}
onChange={onChange}
type={type}
className={inputClassName}
containerClassName={inputWidthClassName}
disabled={props.disabled}
/>
</SettingRow>
);
}
export function ModelSettingRowText<M extends AnyModel, K extends ModelKeyOfValue<M, string>>({
model,
modelKey,
@@ -438,74 +129,6 @@ export function SettingRowDirectory({
return <SettingRowFile directory noun={noun} {...props} />;
}
export function SettingRowSelect<T extends string>({
defaultValue,
name,
onChange,
options,
selectClassName = "w-48!",
title,
value,
...props
}: {
defaultValue?: T;
name: string;
onChange: (value: T) => void;
options: RadioDropdownItem<T>[];
selectClassName?: string;
value: T;
} & SettingRowBaseProps) {
return (
<SettingRow title={title} {...props}>
<SettingSelectControl
name={name}
label={typeof title === "string" ? title : name}
value={value}
defaultValue={defaultValue}
selectClassName={selectClassName}
disabled={props.disabled}
onChange={onChange}
options={options}
/>
</SettingRow>
);
}
export function SettingSelectControl<T extends string>({
defaultValue,
disabled,
label,
name,
onChange,
options,
selectClassName = "w-48!",
value,
}: {
defaultValue?: T;
disabled?: boolean;
label: string;
name: string;
onChange: (value: T) => void;
options: RadioDropdownItem<T>[];
selectClassName?: string;
value: T;
}) {
return (
<Select
hideLabel
name={name}
value={value}
defaultValue={defaultValue}
label={label}
size="sm"
className={selectClassName}
disabled={disabled}
onChange={onChange}
options={options}
/>
);
}
export function ModelSettingSelectControl<
M extends AnyModel,
K extends ModelKeyOfValue<M, string>,
@@ -549,51 +172,3 @@ export function ModelSettingRowSelect<
/>
);
}
export function SettingOverrideRow({
children,
className,
controlClassName,
description,
disabled,
onResetOverride,
overridden,
resetTitle = "Reset override",
title,
}: {
children: ReactNode;
className?: string;
controlClassName?: string;
description?: ReactNode;
disabled?: boolean;
onResetOverride: () => void;
overridden: boolean;
resetTitle?: string;
title: ReactNode;
}) {
return (
<SettingRow
className={className}
controlClassName={controlClassName}
description={description}
disabled={disabled}
title={
<span className="inline-flex items-center gap-1.5">
{title}
{overridden && (
<IconButton
icon="undo_2"
size="2xs"
iconSize="sm"
title={resetTitle}
className="text-text-subtle"
onClick={onResetOverride}
/>
)}
</span>
}
>
{children}
</SettingRow>
);
}
@@ -1,6 +1,15 @@
import type { HttpResponse } from "@yaakapp-internal/models";
import { extractSseValueAtPath, type ServerSentEvent } from "@yaakapp-internal/sse";
import { HStack, Icon, InlineCode, SplitLayout, VStack, IconTooltip } from "@yaakapp-internal/ui";
import {
EventStreamViewer as SharedEventStreamViewer,
HStack,
Icon,
InlineCode,
SplitLayout,
type StreamEvent,
VStack,
IconTooltip,
} from "@yaakapp-internal/ui";
import classNames from "classnames";
import type { CSSProperties, ReactNode } from "react";
import { Fragment, useMemo, useState } from "react";
@@ -20,8 +29,7 @@ import type { DropdownItem } from "../core/Dropdown";
import { Dropdown } from "../core/Dropdown";
import type { EditorProps } from "../core/Editor/Editor";
import { Editor } from "../core/Editor/LazyEditor";
import { EventDetailHeader, EventViewer } from "../core/EventViewer";
import { EventViewerRow } from "../core/EventViewerRow";
import { EventDetailHeader } from "../core/EventViewer";
import { IconButton } from "../core/IconButton";
import { Input } from "../core/Input";
import { Select } from "../core/Select";
@@ -62,6 +70,7 @@ function ActualEventStreamViewer({ response }: Props) {
});
const summarySettings = useSseSummaryResultKeyPath({ response });
const events = useResponseBodyEventSource(response);
const streamEvents = useMemo(() => (events.data ?? []).map(toStreamEvent), [events.data]);
const summary = useResponseBodySseSummary(response, summarySettings.resultKeyPath);
const showExtractedText = summarySettings.resultKeyPath != null;
const showResultKeyPathWarning =
@@ -105,10 +114,7 @@ function ActualEventStreamViewer({ response }: Props) {
),
},
],
[
applyToDetailsSetting,
filterEventPreviewsSetting,
],
[applyToDetailsSetting, filterEventPreviewsSetting],
);
return (
@@ -175,30 +181,21 @@ function ActualEventStreamViewer({ response }: Props) {
resizeHandleClassName="hover:bg-surface-highlight active:bg-surface-highlight"
firstSlot={({ style }) => (
<div style={style} className="min-h-0">
<EventViewer
events={events.data ?? []}
getEventKey={(_, index) => String(index)}
<SharedEventStreamViewer
events={streamEvents}
error={events.error ? String(events.error) : null}
splitLayoutStorageKey="sse_events"
defaultRatio={0.4}
renderRow={({ event, index, isActive, onClick }) => (
<EventViewerRow
isActive={isActive}
onClick={onClick}
icon={<Icon color="info" title="Server Message" icon="arrow_big_down_dash" />}
content={
<HStack space={2} className="items-center">
<EventLabels event={event} index={index} isActive={isActive} />
<span className="truncate text-xs">
{getEventPreview(event, summarySettings.resultKeyPath, filterEventPreviews)}
</span>
</HStack>
}
/>
)}
getPreview={(event) =>
getEventPreview(
sseEventOf(events.data, event),
summarySettings.resultKeyPath,
filterEventPreviews,
)
}
renderDetail={({ event, index, onClose }) => (
<EventDetail
event={event}
event={sseEventOf(events.data, event)}
index={index}
applyJsonPath={applyToDetails}
resultKeyPath={summarySettings.resultKeyPath}
@@ -312,6 +309,23 @@ function SseSummaryFooter({
);
}
/** An SSE event as the shared viewer lists it: received, with its id (or place) and type */
function toStreamEvent(event: ServerSentEvent, index: number): StreamEvent {
return {
key: String(index),
direction: "received",
kind: event.eventType || null,
labels: [String(event.id ?? index), ...(event.eventType ? [event.eventType] : [])],
timestamp: null,
size: null,
preview: event.data,
};
}
function sseEventOf(events: ServerSentEvent[] | undefined, event: StreamEvent): ServerSentEvent {
return events?.[Number(event.key)] ?? { data: "", eventType: "", id: null, retry: null };
}
function getEventPreview(
event: ServerSentEvent,
resultKeyPath: string | null,
@@ -1,4 +1,9 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vite-plus/test";
// Loaded once as the file is collected (the mocks below are hoisted above it), so the first
// transform of its module graph, the shared UI package among it, is not timed against whichever
// test imports it first. Each test still gets the module fresh after `vi.resetModules()`, which
// reuses that transform.
import "./useSendAnyHttpRequest";
const mocks = vi.hoisted(() => ({
platform: { httpProxyUrl: "https://web.yaak.test" as string | null },
+76
View File
@@ -0,0 +1,76 @@
import { useFonts } from "@yaakapp-internal/fonts";
import { useLicense } from "@yaakapp-internal/license";
import { patchModel, settingsAtom } from "@yaakapp-internal/models";
import { platform } from "@yaakapp-internal/platform";
import type { SettingsCallbacks, SettingsView } from "@yaakapp-internal/ui";
import { useAtomValue } from "jotai";
import { openExternalUrl } from "../components/core/Link";
import { appInfo } from "../lib/appInfo";
import { pricingUrl } from "../lib/pricingUrl";
import { revealInFinderText } from "../lib/reveal";
import { rpc } from "../lib/rpc";
import {
licenseStatusFromCheck,
settingsValuesFromModel,
themesViewFromResolved,
} from "../lib/settingsView";
import { useCheckForUpdates } from "./useCheckForUpdates";
import { useResolvedAppearance } from "./useResolvedAppearance";
import { useResolvedTheme } from "./useResolvedTheme";
/** Binds the shared settings tabs to the client's settings model, themes, fonts and license */
export function useSettingsView(): { view: SettingsView; callbacks: SettingsCallbacks } | null {
const settings = useAtomValue(settingsAtom);
const appearance = useResolvedAppearance();
const activeTheme = useResolvedTheme();
const fonts = useFonts();
const { check, activate, deactivate } = useLicense();
const checkForUpdates = useCheckForUpdates();
if (settings == null) {
return null;
}
const view: SettingsView = {
app: {
name: "Yaak",
version: appInfo.version,
dataDir: appInfo.appDataDir,
logDir: appInfo.appLogDir,
revealPathLabel: revealInFinderText,
},
values: settingsValuesFromModel(settings),
themes: themesViewFromResolved(activeTheme.data, appearance),
fonts: fonts.data ?? null,
windowControlsSetting: platform.osType() !== "macos",
updates: appInfo.featureUpdater ? { checking: checkForUpdates.isPending } : null,
feedbackPrompts: appInfo.featureLicense,
license: appInfo.featureLicense
? {
pending: check.isPending,
status: licenseStatusFromCheck(check.data),
checkError: check.error ?? null,
activateError: activate.error ?? null,
activating: activate.isPending,
}
: null,
};
const callbacks: SettingsCallbacks = {
onChange: async (patch) => {
await patchModel(settings, patch);
},
onApplyNativeTitlebar: async (useNativeTitlebar) => {
await patchModel(settings, { useNativeTitlebar });
await rpc("cmd_restart");
},
onCheckForUpdates: () => checkForUpdates.mutate(),
onActivateLicense: (licenseKey) => activate.mutateAsync({ licenseKey }),
onDeactivateLicense: () => deactivate.mutate(),
onOpenUrl: openExternalUrl,
onRevealPath: (path) => platform.revealItemInDir(path),
pricingUrl,
};
return { view, callbacks };
}
@@ -1,6 +1,11 @@
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, beforeEach, describe, expect, test, vi } from "vite-plus/test";
import type { DialogInstance } from "../components/Dialogs";
// Loaded once as the file is collected (the mocks below are hoisted above it), so the first
// transform of its module graph, the shared UI package among it, is not timed against whichever
// test imports it first. Each test still gets the module fresh after `vi.resetModules()`, which
// reuses that transform.
import "./confirmWebProxy";
const mocks = vi.hoisted(() => ({
platform: { httpProxyUrl: "https://web.yaak.app" },
+126
View File
@@ -0,0 +1,126 @@
import type { LicenseCheckStatus } from "@yaakapp-internal/license";
import type { Settings } from "@yaakapp-internal/models";
import { describe, expect, test } from "vite-plus/test";
import {
licenseStatusFromCheck,
settingsValuesFromModel,
themesViewFromResolved,
} from "./settingsView";
describe("settingsValuesFromModel", () => {
test("picks the shared tabs' values and nothing client-only", () => {
const settings = {
model: "settings",
id: "st_1",
appearance: "dark",
themeLight: "yaak-light",
themeDark: "hotdog",
interfaceFont: "Inter",
interfaceFontSize: 15,
editorFont: null,
editorFontSize: 13,
editorKeymap: "emacs",
editorSoftWrap: false,
coloredMethods: true,
useNativeTitlebar: true,
hideWindowControls: true,
updateChannel: "beta",
autoupdate: false,
autoDownloadUpdates: false,
checkNotifications: false,
promptFeedback: false,
openWorkspaceNewWindow: true,
hideLicenseBadge: true,
clientCertificates: [],
} as unknown as Settings;
expect(settingsValuesFromModel(settings)).toEqual({
appearance: "dark",
themeLight: "yaak-light",
themeDark: "hotdog",
interfaceFont: "Inter",
interfaceFontSize: 15,
editorFont: null,
editorFontSize: 13,
editorKeymap: "emacs",
editorSoftWrap: false,
coloredMethods: true,
useNativeTitlebar: true,
hideWindowControls: true,
updateChannel: "beta",
autoupdate: false,
autoDownloadUpdates: false,
checkNotifications: false,
promptFeedback: false,
});
});
});
describe("licenseStatusFromCheck", () => {
test("is null without a check", () => {
expect(licenseStatusFromCheck(null)).toBeNull();
expect(licenseStatusFromCheck(undefined)).toBeNull();
});
test("keeps what each state's copy needs", () => {
const cases: [LicenseCheckStatus, unknown][] = [
[
{ status: "active", data: { periodEnd: "2027-01-01", cancelAt: null } },
{ status: "active" },
],
[
{ status: "trialing", data: { end: "2026-11-20" } },
{ status: "trialing", trialEnd: "2026-11-20" },
],
[{ status: "personal_use", data: { trial_ended: "2026-01-01" } }, { status: "personal_use" }],
[{ status: "inactive", data: { status: "canceled" } }, { status: "inactive" }],
[
{
status: "expired",
data: {
changes: 3,
changesUrl: "https://yaak.app/changes",
billingUrl: "https://yaak.app/billing",
periodEnd: "2026-03-04",
},
},
{ status: "expired", periodEnd: "2026-03-04", changesUrl: "https://yaak.app/changes" },
],
[
{ status: "past_due", data: { billingUrl: "https://yaak.app/billing", periodEnd: "x" } },
{ status: "past_due", billingUrl: "https://yaak.app/billing" },
],
[
{ status: "error", data: { message: "Boom", code: "E1" } },
{ status: "error", message: "Boom", code: "E1" },
],
];
for (const [check, expected] of cases) {
expect(licenseStatusFromCheck(check)).toEqual(expected);
}
});
});
describe("themesViewFromResolved", () => {
const light = { id: "yaak-light", label: "Yaak", dark: false, base: {} };
const dark = { id: "yaak-dark", label: "Yaak", dark: true, base: {} };
test("is null while the themes load", () => {
expect(themesViewFromResolved(undefined, "dark")).toBeNull();
});
test("keeps each theme's id, label and darkness, and the resolved appearance", () => {
expect(
themesViewFromResolved({ themes: [dark, light], light, dark, active: dark }, "dark"),
).toEqual({
themes: [
{ id: "yaak-dark", label: "Yaak", dark: true },
{ id: "yaak-light", label: "Yaak", dark: false },
],
light: { id: "yaak-light", label: "Yaak", dark: false },
dark: { id: "yaak-dark", label: "Yaak", dark: true },
active: { id: "yaak-dark", label: "Yaak", dark: true },
resolvedAppearance: "dark",
});
});
});
+84
View File
@@ -0,0 +1,84 @@
import type { LicenseCheckStatus } from "@yaakapp-internal/license";
import type { Settings } from "@yaakapp-internal/models";
import type {
SettingsLicenseStatus,
SettingsThemeOption,
SettingsThemesView,
SettingsValues,
} from "@yaakapp-internal/ui";
/** The values the shared settings tabs read, picked off the client's `Settings` model */
export function settingsValuesFromModel(settings: Settings): SettingsValues {
return {
appearance: settings.appearance,
themeLight: settings.themeLight,
themeDark: settings.themeDark,
interfaceFont: settings.interfaceFont,
interfaceFontSize: settings.interfaceFontSize,
editorFont: settings.editorFont,
editorFontSize: settings.editorFontSize,
editorKeymap: settings.editorKeymap,
editorSoftWrap: settings.editorSoftWrap,
coloredMethods: settings.coloredMethods,
useNativeTitlebar: settings.useNativeTitlebar,
hideWindowControls: settings.hideWindowControls,
updateChannel: settings.updateChannel,
autoupdate: settings.autoupdate,
autoDownloadUpdates: settings.autoDownloadUpdates,
checkNotifications: settings.checkNotifications,
promptFeedback: settings.promptFeedback,
};
}
/** A license check, as the shared License tab's copy needs it */
export function licenseStatusFromCheck(
check: LicenseCheckStatus | null | undefined,
): SettingsLicenseStatus | null {
if (check == null) return null;
switch (check.status) {
case "active":
return { status: "active" };
case "trialing":
return { status: "trialing", trialEnd: check.data.end };
case "personal_use":
return { status: "personal_use" };
case "inactive":
return { status: "inactive" };
case "expired":
return {
status: "expired",
periodEnd: check.data.periodEnd,
changesUrl: check.data.changesUrl,
};
case "past_due":
return { status: "past_due", billingUrl: check.data.billingUrl };
case "error":
return { status: "error", message: check.data.message, code: check.data.code };
}
}
/** The fields of a theme the settings show */
interface ThemeLike {
id: string;
label: string;
dark: boolean;
}
function themeOption({ id, label, dark }: ThemeLike): SettingsThemeOption {
return { id, label, dark };
}
/** The resolved themes, as the shared Theme tab shows them; null while they load */
export function themesViewFromResolved(
data: { themes: ThemeLike[]; light: ThemeLike; dark: ThemeLike; active: ThemeLike } | undefined,
resolvedAppearance: "light" | "dark",
): SettingsThemesView | null {
if (data == null) return null;
return {
themes: data.themes.map(themeOption),
light: themeOption(data.light),
dark: themeOption(data.dark),
active: themeOption(data.active),
resolvedAppearance,
};
}
@@ -0,0 +1,132 @@
import { startCompletion } from "@codemirror/autocomplete";
import { Compartment, EditorState, type Extension } from "@codemirror/state";
import { EditorView, ViewPlugin } from "@codemirror/view";
import type { Schema } from "@yaakapp-internal/query";
import {
Dialog,
DialogFooter,
Input,
type InputHandle,
LazyCodeEditor,
} from "@yaakapp-internal/ui";
import { queryFilter } from "@yaakapp-internal/ui/editor";
import { atom, useAtom, useSetAtom } from "jotai";
import { useEffect, useMemo, useRef, useState } from "react";
import { useRpcQuery } from "../hooks/useRpcQuery";
import {
addCustomColumn,
customPath,
customPathProblem,
fieldReferenceChanges,
} from "../lib/columns";
import { loadSeenValues } from "../lib/searchBox";
import { columnPrefsAtom } from "../lib/store";
/** The Add Column dialog is open */
export const addColumnDialogAtom = atom(false);
const FORM_ID = "add-column";
/** Keeps the field a reference to a field, `@header.x-cache`, whatever was typed or pasted */
const asFieldReference = EditorState.transactionFilter.of((tr) => {
if (!tr.docChanged) return tr;
const changes = fieldReferenceChanges(tr.newDoc.toString());
return changes.length === 0 ? tr : [tr, { changes, sequential: true }];
});
/** Opens completion on the fields while the field is focused and empty */
const completeWhenEmpty = [
ViewPlugin.define((view) => {
if (view.hasFocus && view.state.doc.length === 0) {
queueMicrotask(() => startCompletion(view));
}
return {};
}),
EditorView.updateListener.of((update) => {
if (update.focusChanged && update.view.hasFocus && update.state.doc.length === 0) {
startCompletion(update.view);
}
}),
];
/**
* Adds a column for a header or query parameter, named by a reference to its field as the search
* names it, `@header.x-request-id` or `@query.page`, completed from the fields and the names seen
*/
export function AddColumnDialog() {
const [open, setOpen] = useAtom(addColumnDialogAtom);
if (!open) return null;
return <AddColumnForm onClose={() => setOpen(false)} />;
}
function AddColumnForm({ onClose }: { onClose: () => void }) {
const [text, setText] = useState("");
const setPrefs = useSetAtom(columnPrefsAtom);
const handleRef = useRef<InputHandle | null>(null);
const schema = useRpcQuery("query_schema", {}, { staleTime: Infinity }).data?.schema;
// Only the fields a column can show: the maps of headers and query parameters. It goes in
// once the schema is read, through a compartment, as the search box's does.
const compartment = useRef(new Compartment());
const filter = useMemo<Extension>(() => {
if (schema == null) return [];
const maps: Schema = { ...schema, fields: schema.fields.filter((f) => f.map) };
return [
queryFilter({ schema: maps, loadValues: loadSeenValues, fieldsOnly: true }),
completeWhenEmpty,
];
}, [schema]);
const extensions = useMemo(() => [asFieldReference, compartment.current.of(filter)], [filter]);
useEffect(() => {
handleRef.current?.dispatch({ effects: compartment.current.reconfigure(filter) });
}, [filter]);
const path = customPath(text);
const problem = customPathProblem(text);
const submit = () => {
if (path == null) return;
setPrefs((p) => addCustomColumn(p, path));
onClose();
};
return (
<Dialog open onClose={onClose} size="dynamic" title="Add Column" className="w-[26rem]">
<form
id={FORM_ID}
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<Input
renderEditor={(props) => <LazyCodeEditor {...props} />}
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();
}
}}
/>
<div className="h-5 pt-1 text-xs text-danger">{problem}</div>
</form>
<DialogFooter
actions={[
{ label: "Cancel", variant: "border", onClick: onClose },
{ label: "Add", color: "primary", form: FORM_ID, disabled: path == null },
]}
/>
</Dialog>
);
}
+4 -4
View File
@@ -24,8 +24,8 @@ function loadIcon(path: string): Promise<string | null> {
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 ? (
<span aria-hidden className={classNames(className, "inline-block w-4 h-4 shrink-0")} />
<span aria-hidden className={classNames(className, "inline-block shrink-0")} />
) : (
<img alt="" src={url} className={classNames(className, "w-4 h-4 shrink-0")} />
<img alt="" src={url} className={classNames(className, "shrink-0")} />
);
}
+105 -35
View File
@@ -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: (
<div className="px-1.5 py-1 max-w-[17rem]">
<div className="text-sm text-text">
{total === 1 ? "Clear 1 flow?" : `Clear all ${total} flows?`}
</div>
<div className="text-xs text-text-subtle mt-0.5">
{clear.error != null ? (
<span className="text-danger">{clear.error.message}</span>
) : (
"They are deleted from disk with their bodies, for good."
)}
</div>
</div>
),
},
{ 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 (
<Dropdown items={items} hotKeyAction="flows_clear">
<>
<IconButton
className="pointer-events-auto"
icon="trash"
title="Clear flows"
title={
locked != null
? "Clear flows (traffic is locked)"
: total === 0
? "Clear flows (none yet)"
: hotkey == null
? "Clear flows"
: `Clear flows ${hotkey}`
}
tooltip
size="sm"
iconColor="secondary"
disabled={action === "disabled"}
onClick={start}
/>
</Dropdown>
<Dialog
open={confirming}
onClose={() => setConfirming(false)}
size="sm"
title="Clear traffic?"
>
{confirming && (
<ConfirmClear
total={total}
onCancel={() => setConfirming(false)}
onClear={(dontAskAgain) => {
setConfirming(false);
if (dontAskAgain) setConfirm(false);
clear();
}}
/>
)}
</Dialog>
</>
);
}
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<HTMLFormElement>) => {
e.preventDefault();
onClear(dontAskAgain);
};
return (
<form id={formId} className="flex flex-col gap-3" onSubmit={handleSubmit}>
<p>
{total === 1
? "1 flow will be removed."
: `${total.toLocaleString()} flows will be removed.`}
</p>
<Checkbox checked={dontAskAgain} title="Don't ask again" onChange={setDontAskAgain} />
<DialogFooter
inline
actions={[
{ label: "Cancel", onClick: onCancel },
{ label: "Clear", color: "danger", form: formId, autoFocus: true },
]}
/>
</form>
);
}
@@ -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<SeenTargets | undefined>(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 (
<div className={classNames(className, "grid gap-2")}>
<EntryInput
seenRef={seenRef}
list={list}
disabled={save.isPending}
onAdd={(entry) => save.mutate({ add: [entry], remove: [] })}
/>
<div className="rounded-md border border-border-subtle divide-y divide-border-subtle">
{list.length === 0 && (
<div className="px-3 py-2 text-sm text-text-subtle">Nothing decrypted</div>
)}
{list.map((e) => (
<EntryRow
key={e.entry}
entry={e}
disabled={save.isPending}
onRemove={() => remove(e.entry)}
/>
))}
</div>
</div>
);
}
function EntryRow({
entry,
disabled,
onRemove,
}: {
entry: DecryptListEntry;
disabled: boolean;
onRemove: () => void;
}) {
const negated = entry.entry.startsWith("!");
return (
<div
className={classNames(
"group/entry flex items-center gap-2 h-xs pl-3 pr-1 text-sm",
entry.builtIn && "text-text-subtlest",
)}
>
<Tooltip wrap content={negated ? "Excluded" : "Decrypted"} delay={CONTROL_TOOLTIP_DELAY}>
<Icon
icon={negated ? "lock" : "lock_open"}
size="sm"
className={classNames("shrink-0", entry.builtIn ? "opacity-60" : "text-text-subtle")}
/>
</Tooltip>
<span className={classNames("truncate", entry.entry !== "*" && "font-mono text-xs")}>
{entryLabel(entry.entry)}
</span>
{entry.builtIn && (
<Tooltip wrap content="Ships with Yaak Proxy" delay={CONTROL_TOOLTIP_DELAY}>
<span className="shrink-0 text-2xs rounded px-1 border border-border-subtle">
built-in
</span>
</Tooltip>
)}
<IconButton
size="xs"
icon="x"
iconColor="secondary"
title={`Remove ${entryLabel(entry.entry)}`}
tooltip
disabled={disabled}
className="ml-auto opacity-0 group-hover/entry:opacity-100 focus-visible:opacity-100"
onClick={onRemove}
/>
</div>
);
}
/** 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<SeenTargets | undefined>;
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<string | null>(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 (
<Tooltip wrap content="Applies to new connections" delay={CONTROL_TOOLTIP_DELAY}>
<div className="grid gap-1">
<Input
label="Add entry"
hideLabel
size="sm"
stateKey={null}
language={null}
placeholder="Add host, app or *"
extensions={extensions}
onChange={() => setError(null)}
/>
{error != null && <div className="text-xs text-danger">{error}</div>}
</div>
</Tooltip>
);
}
+88 -12
View File
@@ -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 (
<div className="grid place-items-center h-full px-10 pb-16 pt-6">
<div className="w-full max-w-[40rem]">
<div className="text-xl font-semibold mb-1.5">Set up Yaak Proxy</div>
<div className="text-text-subtle text-sm leading-relaxed mb-4">
Three steps, once. Afterwards every app on this Mac sends its traffic here, and HTTPS
reads as plain text.
{systemSupported ? "Four" : "Three"} steps, once. Then every app on this Mac sends its
traffic here.
</div>
<div className="rounded-lg border border-border-subtle bg-surface divide-y divide-border-subtle">
<Step
@@ -79,7 +97,7 @@ export function FirstRun() {
color={trustState === "fail" ? "default" : "primary"}
onClick={() => trust.mutate({})}
>
{trustState === "fail" ? "Try again" : "Trust certificate"}
{trustState === "fail" ? "Try Again" : "Trust Certificate"}
</Button>
) : 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"}
</Button>
) : null
}
@@ -112,10 +130,60 @@ export function FirstRun() {
)}
<Step
n={systemSupported ? 3 : 2}
state={trafficState}
title={trafficState === "wait" ? "Waiting for traffic" : "See traffic"}
state={decrypt.state}
title="What to decrypt"
description={
trafficState === "fail"
everything ? (
<Tooltip
wrap
content="Except the built-in exclusions"
delay={CONTROL_TOOLTIP_DELAY}
>
<span>Everything</span>
</Tooltip>
) : (
<Tooltip wrap content="From a flow or the sidebar" delay={CONTROL_TOOLTIP_DELAY}>
<span>Pick as they appear</span>
</Tooltip>
)
}
action={
everything ? (
<Button
size="2xs"
variant="border"
isLoading={saveDecryptList.isPending}
onClick={() => setEverything(false)}
>
Pick As They Appear
</Button>
) : (
<Button
size="2xs"
variant="border"
color={decrypt.state === "next" ? "primary" : "default"}
isLoading={saveDecryptList.isPending}
onClick={() => setEverything(true)}
>
Everything
</Button>
)
}
/>
<Step
n={systemSupported ? 4 : 3}
state={trafficState}
title={
encrypting != null
? `Encrypting stored traffic, ${encrypting}`
: trafficState === "wait"
? "Waiting for traffic"
: "See traffic"
}
description={
encrypting != null
? "Traffic captured before this version is being encrypted on disk. Recording starts when it's done."
: trafficState === "fail"
? (retry.error?.message ?? proxyState?.startError ?? "The proxy has not started.")
: !recording
? "Recording is paused, so traffic passes through without being stored."
@@ -139,7 +207,7 @@ export function FirstRun() {
color="primary"
onClick={() => execute.mutate({ scope: "global", action: "recording_toggle" })}
>
Resume recording
Resume Recording
</Button>
) : null
}
@@ -154,9 +222,17 @@ export function FirstRun() {
leftSlot={<Icon icon="square_terminal" size="sm" />}
onClick={() => void copyEnvironment()}
>
Copy environment
Copy Environment
</Button>
</div>
<div className="mt-2 text-sm text-text-subtle">
Working with an agent? <InlineCode>yaak mcp</InlineCode> gives it the proxy's flows and
actions.
</div>
<div className="mt-2 text-sm text-text-subtle">
Captured traffic is encrypted on disk with a key kept in your keychain, so macOS may ask
to let Yaak Proxy use it.
</div>
</div>
</div>
);
@@ -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");
});
});
+160 -19
View File
@@ -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<ChosenViewMode | null>(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 <Banner color="danger">{body.error.message}</Banner>;
}
const { bytes, truncated, storedSize, decodeError } = body.data;
const { bytes, truncated, storedSize, decodeError, note } = body.data;
if (bytes.length === 0 && decodeError == null) {
return <EmptyState>{which === "request" ? "No request body" : "Empty"}</EmptyState>;
return <EmptyState>{emptyBodyText(which, note)}</EmptyState>;
}
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 : (
<BodyViewModeSwitch pretty={prettyView} value={mode} onChange={setMode} />
);
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 = <BinaryBody flow={flow} which={which} bytes={bytes} />;
} else if (mime.startsWith("multipart/") && pretty) {
} else if (prettyView === "parts" && pretty) {
const boundary = contentType?.match(/;\s*boundary="?([^";]+)"?/i)?.[1] ?? "unknown";
viewer = (
<MultipartViewer
@@ -87,22 +196,43 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) {
viewer = <ImageBody bytes={bytes} mime={imageType} />;
} else if (text == null) {
viewer = <BinaryBody flow={flow} which={which} bytes={bytes} />;
} else if (mime.startsWith("image/svg")) {
viewer = <SvgViewer text={text} />;
} 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 = <CsvViewer text={text} className="pb-2" />;
} else if (prettyView === "preview" && pretty) {
viewer = mime.startsWith("image/svg") ? (
<SvgViewer text={text} />
) : (
<WebPageViewer html={text} baseUrl={flow.url} />
);
} else {
const language = languageFromContentType(contentType, text);
if (language === "html" && pretty && which === "response") {
viewer = <WebPageViewer html={text} baseUrl={flow.url} />;
} else {
viewer = (
<FlowTextViewer flow={flow} which={which} text={text} language={language} pretty={pretty} />
);
}
ownsBar = true;
viewer = (
<FlowTextViewer
flow={flow}
which={which}
text={text}
language={language}
pretty={pretty}
modeSwitch={modeSwitch}
/>
);
}
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 = (
<div className={classNames(ACTIONS_BAR_CONTAINER, "h-full w-full")}>
{viewer}
<ActionsBar>{modeSwitch}</ActionsBar>
</div>
);
}
if ((!truncated || hideCutNote) && decodeError == null) return viewer;
return (
<div className="h-full grid grid-rows-[auto_auto_minmax(0,1fr)]">
@@ -111,7 +241,7 @@ export function FlowBodyViewer({ flow, which, pretty }: Props) {
{decodeError}. Showing the body as it was on the wire.
</Banner>
)}
{truncated && (
{truncated && !hideCutNote && (
<Banner color="notice" className="text-sm mb-2">
{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}
/>
);
}
+333
View File
@@ -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 (
<ProxyEditorHost>
<SplitLayout
storageKey={listBeside ? "proxy_card_stacked" : "proxy_card_side"}
layout={listBeside ? "vertical" : "horizontal"}
minHeightPx={120}
minWidthPx={240}
firstSlot={({ style }) => (
<div style={style}>
<FlowRequestHalf flow={flow} />
</div>
)}
secondSlot={({ style, orientation }) => (
<div style={style}>
<FlowResponseHalf
flow={flow}
className={orientation === "vertical" ? "border-t" : "border-l"}
/>
</div>
)}
/>
</ProxyEditorHost>
);
}
/**
* 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<FlowBodyData | null> {
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<ExtraPaneTab[]>(
() => [
{
tab: {
value: REQUEST_TAB_COOKIES,
label: "Cookies",
rightSlot: <CountBadge count={sentCount} />,
},
content: <ResponseCookies response={cookies} side="sent" />,
},
],
[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 (
<HttpRequestPaneView
// Padded below as the response half's tabs are, so their content, and the actions bar
// over it, sit the same distance from the card's edges
className="px-3 pb-3"
request={request}
fullHeight
forceUpdateKey={forceUpdateKey}
tabsStorageKey="proxy_request_tabs"
bodyLoader={loader}
extraTabs={extraTabs}
defaultTab={defaultTab}
activeTab={activeTab}
onTabChange={onTabChange}
urlLine={<UrlLine flow={flow} />}
renderBody={() => (
<FlowRequestBody
body={body}
// The response's viewer choice, with the form's fields as a URL-encoded body's
// formatted view, the switch in one bar with their bulk-view toggle
viewer={
<FlowBodyViewer
flow={flow}
which="request"
form={
request.bodyType === BODY_TYPE_FORM_URLENCODED
? (actions) => (
<FormUrlencodedEditor
readOnly
requestId={request.id}
form={request.body.form}
forceUpdateKey={forceUpdateKey}
actions={actions}
/>
)
: 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
<Tooltip wrap onlyWhenTruncated content={flow.url} delay={CONTROL_TOOLTIP_DELAY}>
<div
className={classNames(
"flex items-center gap-2 min-h-[calc(var(--height-sm)+0.25rem)] -mb-1.5",
"font-mono text-sm whitespace-nowrap overflow-x-auto hide-scrollbars",
)}
>
<span className="text-text-subtle shrink-0">{flow.method}</span>
<span className="text-text select-text cursor-text">{flow.url}</span>
</div>
</Tooltip>
);
}
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<ExtraPaneTab[]>(
() => [
{
tab: { value: RESPONSE_TAB_TIMELINE, label: "Timeline" },
content: <FlowTimeline flow={flow} />,
},
{ tab: { value: RESPONSE_TAB_INFO, label: "Info" }, content: <FlowInfo flow={flow} /> },
...(messagesLabel == null
? []
: [
{
tab: {
value: RESPONSE_TAB_MESSAGES,
label: messagesLabel,
rightSlot: (
<CountBadge
count={flow.messageCount}
color="info"
showZero
className="tabular-nums"
/>
),
},
content: <FlowMessages flow={flow} />,
},
]),
],
[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 (
<HttpResponsePaneView
bare
requestShownApart
className={classNames(className, "border-border-subtle")}
response={response}
body={loader}
requestBody={null}
emptyState={<EmptyStateText>Waiting for a response</EmptyStateText>}
tabsStorageKey="proxy_response_tabs"
activeTabKey={flow.id}
defaultTab={defaultTab}
activeTab={activeTab}
onTabChange={onTabChange}
extraTabs={extraTabs}
renderBodyViewer={() => <FlowBodyViewer flow={flow} which="response" />}
statusLineCenter={
flow.responseTruncated ? (
<span
className={classNames(
"justify-self-end flex items-center gap-1.5 h-5 px-2.5 ml-3 rounded-full",
"border border-notice/50 text-notice font-sans text-xs",
)}
>
<Icon icon="scissors" size="xs" />
{body.data == null ? "Body cut" : `First ${formatSize(body.data.storedSize)} kept`}
</span>
) : undefined
}
statusLineRight={
<div className="flex items-center gap-0.5 m-0.5">
<IconButton
size="sm"
icon="bookmark"
iconColor={saved ? "primary" : "secondary"}
title={saved ? "Saved to Yaak" : "Save to Yaak"}
tooltip
onClick={() => openSave(flow)}
/>
<Dropdown items={flowActions(flow).slice(2)}>
<IconButton size="sm" icon="ellipsis" iconColor="secondary" title="Actions" tooltip />
</Dropdown>
</div>
}
/>
);
}
+13 -274
View File
@@ -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 (
<div
style={style}
className={classNames("min-h-0 min-w-0 pb-2", sideBySide ? "pr-2 pt-2" : "px-2")}
className={classNames("min-h-0 min-w-0 pb-2", sideBySide ? "pr-2 pt-3" : "px-2")}
>
<div
className={classNames(
@@ -55,257 +32,19 @@ export function FlowDetail({ style, sideBySide }: { style?: CSSProperties; sideB
<span>Pause or resume recording</span>
<Keys keys={["⌘", "R"]} />
<span>Clear flows</span>
<Keys keys={["⌘", "K"]} />
<Keys keys={["⌘", "⇧", "K"]} />
</div>
</EmptyState>
) : flow.tunnelled ? (
<NotDecrypted flow={flow} />
) : (
<FlowPane flow={flow} />
<FlowCard flow={flow} listBeside={sideBySide} />
)}
</div>
</div>
);
}
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<TabItem[]>(
() => [
{
value: TAB_RESPONSE,
renderButton: ({ buttonProps, isActive }) => (
<ViewModeButton
buttonProps={buttonProps}
isActive={isActive}
pretty={pretty}
onChangePretty={setPretty}
prettyLabel={mime === "text/html" ? "Preview" : "Response"}
allowRaw={!mime?.startsWith("image/")}
/>
),
},
{
value: TAB_REQUEST,
label: "Request",
rightSlot: flow.requestSize > 0 ? <CountBadge count={true} /> : null,
},
{
value: TAB_HEADERS,
label: "Headers",
rightSlot: (
<CountBadge
count={flow.requestHeaders.length}
count2={flow.responseHeaders.length}
showZero
/>
),
},
{
value: TAB_QUERY,
label: "Query",
rightSlot: <CountBadge count={queryCount} showZero />,
},
],
[
pretty,
mime,
flow.requestSize,
flow.requestHeaders.length,
flow.responseHeaders.length,
queryCount,
],
);
return (
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] grid-cols-1">
<div
className={classNames(
"grid grid-cols-[auto_minmax(4rem,1fr)_auto] items-center h-sm -mb-1.5",
"cursor-default select-none whitespace-nowrap w-full px-3",
"overflow-x-auto font-mono text-sm text-text-subtle hide-scrollbars",
)}
>
<HStack space={2} className="w-full shrink-0">
{flow.cancelled && flow.status == null ? (
<span>Cancelled</span>
) : (
<HttpStatusTagRaw
showReason
status={flow.status ?? 0}
statusReason={flow.status == null ? null : statusReason(flow.status)}
/>
)}
{flow.elapsedMs != null && (
<>
<span>&bull;</span>
<span
title={
flow.elapsedHeadersMs == null
? undefined
: `HEADERS: ${formatMillis(flow.elapsedHeadersMs)}\nTOTAL: ${formatMillis(flow.elapsedMs)}`
}
>
{formatMillis(flow.elapsedMs)}
</span>
</>
)}
{!noResponse && (
<>
<span>&bull;</span>
<SizeTag contentLength={flow.responseSize} />
</>
)}
</HStack>
{flow.responseTruncated ? (
<span
className={classNames(
"justify-self-end flex items-center gap-1.5 h-5 px-2.5 ml-3 rounded-full",
"border border-notice/50 text-notice font-sans text-xs",
)}
>
<Icon icon="scissors" size="xs" />
{responseBody.data == null
? "Body cut"
: `First ${formatSize(responseBody.data.storedSize)} kept`}
</span>
) : (
<span />
)}
<HStack space={1} className="font-sans ml-3">
<Button
size="2xs"
variant="border"
color={flow.savedRequestId == null ? "default" : "primary"}
title={flow.savedRequestId == null ? undefined : "Saved to Yaak. Click to save again."}
leftSlot={<Icon icon="bookmark" size="xs" />}
onClick={() => openSave(flow)}
>
{flow.savedRequestId == null ? "Save to Yaak" : "Saved"}
</Button>
<Dropdown items={flowActions(flow).slice(2)}>
<IconButton size="xs" icon="ellipsis" iconColor="secondary" title="Copy and export" />
</Dropdown>
</HStack>
</div>
<div className="overflow-hidden flex flex-col min-h-0">
{flow.error != null && (
<Banner color="danger" className="mx-3 mt-1 shrink-0 font-mono text-sm">
{flow.error}
</Banner>
)}
{flow.cancelled && (
<Banner color="secondary" className="mx-3 mt-1 shrink-0 text-sm">
{flow.status == null
? "The app cancelled the request before a response came back."
: "The app cancelled the request before the response finished."}
</Banner>
)}
<Tabs
tabs={tabs}
label="Flow"
className="ml-3 mr-3 mb-3 min-h-0 flex-1"
tabListClassName="mt-0.5 -mb-1.5"
>
<TabContent value={TAB_RESPONSE}>
{noResponse ? (
<EmptyState>
<div className="text-text-subtle mb-1">
{flow.cancelled ? "Cancelled" : "No response"}
</div>
<div className="text-xs">
{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.
</div>
</EmptyState>
) : (
<FlowBodyViewer flow={flow} which="response" pretty={pretty} />
)}
</TabContent>
<TabContent value={TAB_REQUEST}>
<FlowBodyViewer flow={flow} which="request" pretty />
</TabContent>
<TabContent value={TAB_HEADERS}>
<FlowHeaders flow={flow} />
</TabContent>
<TabContent value={TAB_QUERY}>
<FlowQuery flow={flow} />
</TabContent>
</Tabs>
</div>
</div>
);
}
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: <CheckMark visible={showPretty} />,
onSelect: () => onChangePretty(true),
},
{
label: `${prettyLabel} (Raw)`,
hidden: !allowRaw,
leftSlot: <CheckMark visible={!showPretty} />,
onSelect: () => onChangePretty(false),
},
];
return (
<Dropdown items={items}>
<Button
{...buttonProps}
onClick={(e) => {
if (isActive) return;
e.preventDefault();
buttonProps.onClick?.(e);
}}
rightSlot={
<Icon
size="sm"
icon="chevron_down"
className={classNames("ml-1", isActive ? "text-text-subtle" : "text-text-subtlest")}
/>
}
>
{showPretty ? prettyLabel : "Raw"}
</Button>
</Dropdown>
);
}
function CheckMark({ visible }: { visible: boolean }) {
return <Icon icon={visible ? "check" : "empty"} size="sm" />;
}
function Keys({ keys }: { keys: string[] }) {
return (
<span className="flex gap-1 justify-end">
-109
View File
@@ -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 (
<div className="overflow-auto h-full pb-4 gap-y-3 flex flex-col pr-0.5">
<DetailsBanner defaultOpen storageKey="flow.info" summary={<h2>Info</h2>}>
<KeyValueRows>
<KeyValueRow label="Started">
{startedFormat.format(new Date(`${flow.startedAt}Z`))}
</KeyValueRow>
<KeyValueRow label="URL">{flow.url}</KeyValueRow>
<KeyValueRow label="Remote Address">{flow.remoteAddr ?? <Missing />}</KeyValueRow>
<KeyValueRow label="Version">{versions}</KeyValueRow>
<KeyValueRow label="Timing">
{flow.elapsedMs == null ? (
<Missing />
) : flow.elapsedHeadersMs == null ? (
`${formatMillis(flow.elapsedMs)} in all`
) : (
`${formatMillis(flow.elapsedMs)} in all, headers after ${formatMillis(flow.elapsedHeadersMs)}`
)}
</KeyValueRow>
<KeyValueRow label="Size">
<span>
{formatSize(flow.requestSize)} sent, {formatSize(flow.responseSize)} received{" "}
<span className="text-text-subtlest">
({bytesFormat.format(flow.responseSize)} B)
</span>
</span>
</KeyValueRow>
</KeyValueRows>
</DetailsBanner>
<HeadersTable
title="Request Headers"
headers={flow.requestHeaders}
labelColor="primary"
storageKey="flow.request_headers"
/>
<HeadersTable
defaultOpen
title="Response Headers"
headers={flow.responseHeaders}
labelColor="info"
storageKey="flow.response_headers"
/>
</div>
);
}
export function FlowQuery({ flow }: { flow: Flow }) {
const params = useMemo(() => queryParams(flow.url), [flow.url]);
if (params.length === 0) {
return <EmptyState>No query parameters</EmptyState>;
}
return (
<div className="overflow-auto h-full pb-4">
<KeyValueRows>
{params.map(([name, value], i) => (
// oxlint-disable-next-line react/no-array-index-key -- a name can repeat
<KeyValueRow key={i} label={name} labelColor="primary">
{value}
</KeyValueRow>
))}
</KeyValueRows>
</div>
);
}
export function queryParams(url: string): [string, string][] {
try {
return [...new URL(url).searchParams.entries()];
} catch {
return [];
}
}
function Missing() {
return <span className="text-text-subtlest">--</span>;
}
+125
View File
@@ -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 (
<div className="overflow-auto h-full pb-4 gap-y-3 flex flex-col pr-0.5">
<Section title="Connection">
{[
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),
]}
</Section>
<Section title="App">
{[
row(
"app",
"Name",
flow.clientName == null ? null : (
<span className="flex items-center gap-1.5">
{flow.clientPath != null && <AppIcon path={flow.clientPath} className="size-5" />}
{flow.clientName}
{folder != null && <span className="text-text-subtlest">{folder}</span>}
</span>
),
),
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 }),
]}
</Section>
<Section title="Timing">
{[
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)),
]}
</Section>
<Section title="Size">
{[
row("request_size", "Request", formatSize(flow.requestSize)),
row("response_size", "Response", formatSize(flow.responseSize)),
]}
</Section>
<Section title="Record">
{[
row("number", "Number", `#${flow.number}`, { copy: true }),
row("id", "ID", flow.id, { copy: true }),
row("saved", "Saved As", flow.savedRequestId, { copy: true }),
]}
</Section>
</div>
);
}
/** A row as `KeyValueRows` takes it */
type Row = ReactElement<HTMLAttributes<HTMLTableColElement>>;
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 (
<DetailsBanner defaultOpen summary={<h2>{title}</h2>}>
<KeyValueRows>{rows}</KeyValueRows>
</DetailsBanner>
);
}
/** 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 (
<KeyValueRow
key={key}
labelColor="secondary"
label={label}
enableCopy={opts.copy}
copy={copyText}
>
{value}
</KeyValueRow>
);
}
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);
}
File diff suppressed because it is too large. Load diff
@@ -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 <NoResults text={text} />;
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 (
<EmptyStateText wrapperClassName="p-1.5" className="not-italic flex-col gap-1 text-center px-6">
<div className="text-text text-sm">{recording ? "No flows yet" : "Recording is paused"}</div>
<div className="text-sm text-text-subtle max-w-[26rem]">
{!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.`}
</div>
</EmptyStateText>
);
}
/**
* 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 (
<div
style={style}
className={classNames(
"absolute left-1.5 right-1.5 flex items-center gap-2 h-xs px-3 mt-1",
"rounded-md border border-dashed border-border-subtle text-text-subtle text-sm",
)}
>
<Icon icon="circle_pause" size="sm" className="text-text-subtlest" />
<span className="truncate">
{pausedAt == null ? "Paused." : `Paused at ${timeOf(pausedAt)}.`} Traffic passes through
without being stored.
</span>
<Hotkey action="recording_toggle" variant="text" className="ml-auto" />
</div>
);
}
/**
* 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 (
<EmptyStateText
wrapperClassName="p-1.5 !h-auto"
className="not-italic !h-auto py-3 px-4 text-sm text-text-subtle"
>
<div className="text-center leading-relaxed">
No flows match.
{wider.length > 0 && " Found matches for "}
{wider.map((w, i) => (
<span key={w.text}>
{i > 0 && (i === wider.length - 1 ? ", or " : ", ")}
<button type="button" className="hover:underline" onClick={() => setText(w.text)}>
<InlineCode>{w.text === "" ? "all traffic" : w.text}</InlineCode>
</button>{" "}
({w.count.toLocaleString()})
</span>
))}
</div>
</EmptyStateText>
);
}
function timeOf(ms: number): string {
return new Date(ms).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}
@@ -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: <div className="px-1.5 pt-1 text-xs text-text-subtlest">Columns</div>,
},
...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 ? (
<Icon icon="check" size="sm" />
) : (
<span aria-hidden className="inline-block w-4 h-4" />
),
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<HTMLElement>("[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.
<div style={{ width, minWidth: "100%" }} className="px-1.5">
{/* oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- a right-click opens the column's menu */}
<div
ref={gridRef}
data-flow-header
onPointerDownCapture={onPointerDownCapture}
onContextMenu={openMenu}
style={{ gridTemplateColumns: template }}
className={classNames(
"group/header grid items-center h-xs px-1.5 select-none",
"text-xs text-text-subtlest border-b border-border-subtle",
)}
>
<span className="flex items-center justify-center">
<Dropdown items={pickerItems}>
<IconButton
size="xs"
icon="settings_2"
title="Columns"
tooltip
iconColor="secondary"
className="opacity-0 group-hover/header:opacity-100 focus-visible:opacity-100 !h-5 !w-5"
/>
</Dropdown>
</span>
<DndContext sensors={sensors} autoScroll={false} {...dndHandlers}>
{columns.map((c) => (
<HeaderCell
key={c.id}
column={c}
sort={sort}
onSort={onSort}
onResizeStart={() => {
startWidth.current = c.current;
}}
onResizeMove={(dx) => setPrefs((p) => resizeColumn(p, c.id, startWidth.current + dx))}
onResetWidth={() => setPrefs((p) => resetWidth(p, c.id))}
/>
))}
</DndContext>
<ContextMenu
triggerPosition={menu}
items={menu == null ? [] : menu.column == null ? pickerItems : columnItems(menu.column)}
onClose={() => setMenu(null)}
/>
</div>
</div>
);
});
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 (
<span data-column={c.id} className="relative h-full flex items-center min-w-0 px-1.5">
<button
ref={setNodeRef}
type="button"
{...listeners}
// A press that moves drags instead; dnd-kit swallows the click that ends a drag.
onClick={(e) => onSort(c.id, e.altKey)}
// No tooltip: the header sits under the search field, and a tooltip here covered it
aria-label={`Sort by ${c.label}`}
className={classNames(
"flex items-center gap-0.5 min-w-0 w-full h-full whitespace-nowrap",
"hover:text-text-subtle",
c.align === "right" && "justify-end",
sorted && "text-text-subtle",
)}
>
<ColumnLabel column={c} sort={sort} />
</button>
{/* On the column's right edge, the boundary with the next, resizing this one */}
<ResizeHandle
side="right"
justify="center"
className="absolute top-0 translate-x-1/2"
onResizeStart={onResizeStart}
onResizeMove={(e) => onResizeMove(e.x - e.xStart)}
onReset={onResetWidth}
/>
</span>
);
}
/** 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 && (
<Icon
icon="chevron_down"
size="xs"
className={classNames("shrink-0", !key.descending && "rotate-180")}
/>
)}
{key != null && sort.length > 1 && (
<span className="shrink-0 -ml-0.5 text-2xs tabular-nums">{at + 1}</span>
)}
<span className="truncate">{c.id === "app" ? "" : c.label}</span>
</>
);
}
/**
* 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<HTMLDivElement>(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<HTMLElement>(":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<typeof state.current>) {
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(" ");
}
+131
View File
@@ -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 = (
<HStack space={2} className="pl-2 mb-1 h-xs font-mono text-xs text-text-subtle">
{kind === "websocket" && (
<>
{open ? (
<span className="text-success">CONNECTED</span>
) : flow.error != null ? (
<span className="text-danger">ERROR</span>
) : (
<span className="text-text-subtle">CLOSED</span>
)}
<span>&bull;</span>
</>
)}
<span>
{count} {count === 1 ? noun : `${noun}s`}
</span>
{grpc && flow.grpcStatus != null && (
<>
<span>&bull;</span>
<span className={flow.grpcStatus === 0 ? "text-success" : "text-danger"}>
{grpcStatusText(flow.grpcStatus, flow.grpcMessage)}
</span>
</>
)}
</HStack>
);
return (
<EventStreamViewer
events={events}
header={header}
error={error ?? (open ? null : flow.error)}
isLoading={loading && events.length === 0}
emptyMessage={open ? `Waiting for the first ${noun.toLowerCase()}` : `No ${noun}s`}
splitLayoutStorageKey="proxy_flow_messages"
columns={columns}
loadPayload={loadPayload}
payloadViews={payloadViews}
catchUp={catchUp}
/>
);
}
@@ -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 }) => (
<div data-banner={color}>{children}</div>
),
EmptyStateText: ({ children }: { children: ReactNode }) => <div>{children}</div>,
LoadingIcon: () => <span>LOADING</span>,
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<typeof FlowRequestBody>[0]["body"]) {
return renderToStaticMarkup(
<FlowRequestBody body={body} viewer={<div>EDITOR</div>} 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");
});
});
@@ -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<FlowBodyData | null>;
/** 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 (
<Banner color="danger" className="text-sm">
{body.error.message}
</Banner>
);
}
if (body.isLoading) {
return (
<EmptyStateText>
<LoadingIcon />
</EmptyStateText>
);
}
if (body.data?.truncated) {
return (
<div className="h-full grid grid-rows-[auto_minmax(0,1fr)]">
<Banner color="notice" className="text-sm mb-2">
<Tooltip wrap content="The app sent all of it" delay={CONTROL_TOOLTIP_DELAY}>
<span>
First {formatSize(body.data.storedSize)} of {formatSize(requestSize)} kept
</span>
</Tooltip>
</Banner>
<div className="min-h-0">{viewer}</div>
</div>
);
}
return viewer;
}
@@ -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<PhaseKind, { icon: IconProps["icon"]; color: IconProps["color"] }> = {
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 (
<EventViewer<FlowPhase>
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 (
<EventViewerRow
isActive={isActive}
onClick={onClick}
icon={<Icon icon={icon} color={color} size="sm" />}
content={
event.detail == null ? (
<span>{event.label}</span>
) : (
<Tooltip
wrap
content={event.detail}
delay={CONTROL_TOOLTIP_DELAY}
>
<span>
{event.label}
<span className="text-text-subtlest">{` ${event.detail}`}</span>
</span>
</Tooltip>
)
}
columns="auto minmax(0,1fr) 6rem 6rem"
cells={{
trailing: [
<span key="took" className="tabular-nums">
{event.kind === "start" ? "" : `+${formatMillis(event.tookMs)}`}
</span>,
<span key="at" className="tabular-nums opacity-50">
{formatMillis(event.atMs)}
</span>,
],
}}
/>
);
}}
/>
);
}
@@ -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 (
<div className="grid place-items-center h-full px-10 pb-16">
<div className="flex flex-col items-center text-center gap-2 max-w-[28rem]">
{encrypting != null ? (
<LoadingIcon size="lg" className="text-text-subtle mb-1" />
) : (
<Icon icon="lock" size="lg" className="text-text-subtle mb-1" />
)}
<div className="text-lg font-semibold whitespace-nowrap">
{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 */}
<span className="inline-block w-[4.5ch] text-right tabular-nums">{encrypting}</span>
</>
) : (
"Traffic is locked"
)}
</div>
<div className="text-sm text-text-subtle">
{encrypting != null
? "Earlier traffic shows here once it's encrypted."
: lockedLine(lock, getOsType())}
</div>
{encrypting == null && (
<Button
size="xs"
variant="border"
className="mt-2"
isLoading={retry.isPending}
onClick={() => retry.mutate({})}
>
Retry
</Button>
)}
{encrypting == null && retry.error != null && (
<div className="text-xs text-danger">{retry.error.message}</div>
)}
</div>
</div>
);
}
@@ -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 (
<EmptyState>
<div className="grid justify-items-center gap-2">
<div className="flex items-center gap-1.5 text-text-subtle">
<Icon icon="lock" size="sm" />
Not decrypted
</div>
<div className="font-mono text-xs">{facts.join(" · ")}</div>
{flow.error != null && <div className="text-danger">{flow.error}</div>}
{actions.listed ? (
<Tooltip
wrap
content="Still tunnelled? The app may pin its certificate"
delay={CONTROL_TOOLTIP_DELAY}
>
<div>Decrypting new connections</div>
</Tooltip>
) : actions.blocked != null ? (
<Tooltip
wrap
content="Remove it from the decrypt list to decrypt"
delay={CONTROL_TOOLTIP_DELAY}
>
<div>
Excluded by <span className="font-mono text-xs">{actions.blocked}</span>
</div>
</Tooltip>
) : (
<div className="flex gap-2 mt-1">
{actions.host && (
<Button
size="xs"
variant="border"
title={`Decrypt new connections to ${host}`}
tooltip
disabled={save.isPending}
onClick={() => decrypt(hostSubject)}
>
Decrypt Host
</Button>
)}
{actions.app && appSubject != null && (
<Button
size="xs"
variant="border"
title={`Decrypt new connections from ${app}`}
tooltip
disabled={save.isPending}
onClick={() => decrypt(appSubject)}
>
Decrypt App
</Button>
)}
</div>
)}
</div>
</EmptyState>
);
}
+68 -30
View File
@@ -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 (
<div
@@ -52,11 +65,21 @@ export function ProxyLayout() {
interfaceScale={1}
className="x-theme-appHeader bg-surface"
>
<div className="grid grid-cols-[auto_minmax(0,1fr)_auto] items-center w-full h-full pointer-events-none">
<div className="flex items-center pl-1 pointer-events-auto">
<HeaderTint color={tint} animate />
{/* 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. */}
<div
data-tauri-drag-region
className="grid grid-cols-[minmax(auto,1fr)_minmax(0,44rem)_minmax(auto,1fr)] gap-2 items-center w-full h-full pointer-events-none"
>
<div data-tauri-drag-region className="flex items-center gap-1 pl-1 whitespace-nowrap">
<IconButton
className="pointer-events-auto"
size="sm"
title="Toggle sidebar"
tooltip
icon={isHidden ? "left_panel_hidden" : "left_panel_visible"}
iconColor="secondary"
onClick={() => {
@@ -67,27 +90,35 @@ export function ProxyLayout() {
}
}}
/>
</div>
<div
data-tauri-drag-region
className="pointer-events-none flex items-center justify-center gap-2 text-sm px-2 min-w-0"
>
<span className="truncate">{title}</span>
<FlowCount />
</div>
<div className="flex items-center gap-1 pr-1">
<ProxyStatus />
</div>
<div data-tauri-drag-region className="min-w-0">
<div className="pointer-events-auto">
<SearchBar />
</div>
</div>
<div data-tauri-drag-region className="flex items-center justify-end gap-1 pr-1">
<ClearFlowsButton />
<IconButton
className="pointer-events-auto"
icon={flowLayout === "horizontal" ? "columns_2" : "rows_2"}
title={`Change to ${flowLayout === "horizontal" ? "vertical" : "horizontal"} layout`}
tooltip
size="sm"
iconColor="secondary"
onClick={() =>
setFlowLayout((prev) => (prev === "horizontal" ? "vertical" : "horizontal"))
}
/>
<IconButton
className="pointer-events-auto"
icon="settings"
title="Settings"
tooltip
size="sm"
iconColor="secondary"
onClick={() => openSettings()}
/>
</div>
</div>
</HeaderSize>
@@ -120,6 +151,7 @@ export function ProxyLayout() {
<IconButton
size="sm"
title="Toggle sidebar"
tooltip
icon="left_panel_visible"
iconColor="secondary"
onClick={() => setFloatingSidebarHidden(true)}
@@ -140,35 +172,41 @@ export function ProxyLayout() {
</div>
</SidebarLayout>
<SaveDialog />
<SavedSearchDialog />
<AddColumnDialog />
<HelperDialog />
<SettingsDialogFallback />
<Toasts />
</div>
);
}
/** 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 <span className="text-text-subtlest shrink-0">{`${count} ${noun}`}</span>;
}
/**
* The flow list above the detail pane, or, while the database has no flows at all, the first-run
* card across the whole area: it is the empty state until traffic replaces it.
* 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 <FirstRun />;
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 <FirstRun />;
if (locked != null) return <LockedState lock={locked} />;
return (
<SplitLayout
storageKey="proxy_detail"
className="gap-1"
// The card sits a wider gutter from the list side by side; the handle fills the gutter.
gutter={flowLayout === "vertical" ? 8 : 20}
layout={flowLayout}
defaultRatio={0.55}
firstSlot={({ style, orientation }) => (
<FlowList sideBySide={orientation === "horizontal"} style={style} className="pt-1" />
)}
firstSlot={({ style }) => <FlowList style={style} className="pt-1" />}
secondSlot={({ style, orientation }) => (
<FlowDetail style={style} sideBySide={orientation === "horizontal"} />
)}
+103 -175
View File
@@ -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<DropdownRef>(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" ? (
<MenuRow
icon={<LoadingIcon size="sm" className="text-text-subtle" />}
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 ? (
<MenuRow
icon={<StateDot state="cli" />}
title="Running from the CLI"
description={`Started by yaak proxy start, pid ${other.pid}, since ${timeOf(other.startedAt)}.${other.proxyPort == null ? "" : ` Port ${other.proxyPort}.`}`}
/>
) : running ? (
) : status === "recording" || status === "paused" ? (
<MenuRow
icon={<StateDot state={recording ? "recording" : "paused"} />}
icon={<StateDot state={status} />}
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: <span className="font-mono">{address}</span>,
hidden: address == null,
keepOpenOnSelect: true,
rightSlot: copied ? (
<span className="text-xs text-text-subtle">Copied</span>
) : (
<Icon icon="copy" size="sm" className="text-text-subtlest" />
),
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={<Icon icon="wifi" size="sm" color="secondary" />}
title="Override system proxy"
description={
<span className={classNames(systemSwitch.failed && "text-danger")}>
{systemSwitch.description}
</span>
<>
<span className={classNames(systemSwitch.failed && "text-danger")}>
{systemSwitch.description}
</span>
{helperNotice && (
<span className="block text-notice">
macOS asks for your password each time until the helper is approved in Settings.
</span>
)}
</>
}
action={
<KeepMenuOpen>
@@ -123,35 +166,6 @@ export function ProxyStatus() {
/>
),
},
{
type: "content",
hidden: systemProxy.data?.supported !== true,
label: (
<KeepMenuOpen className="block pl-[2.125rem] pr-1.5 pb-1.5">
<Checkbox
title={
<span className="text-xs text-text-subtle">Override system proxy at launch</span>
}
checked={proxyState?.systemProxyAtLaunch ?? true}
disabled={setAtLaunch.isPending}
onChange={(enabled) => setAtLaunch.mutate({ enabled })}
/>
</KeepMenuOpen>
),
},
{
type: "content",
hidden: systemProxy.data?.supported !== true,
label: systemProxy.data != null && (
<HelperMenuRow
status={systemProxy.data}
onOpenDialog={() => {
dropdownRef.current?.close?.();
setHelperDialogOpen(true);
}}
/>
),
},
{
type: "content",
label: caStatus.data?.trusted ? (
@@ -190,69 +204,27 @@ export function ProxyStatus() {
/>
),
},
{
type: "content",
label: (
<MenuRow
icon={<Icon icon="zap" size="sm" color="secondary" />}
title="HTTP/2"
description="Lets browsers send many requests at once. Turn off for apps that misbehave on it. Applies to new connections."
action={
<KeepMenuOpen>
<Checkbox
title="HTTP/2"
hideLabel
checked={proxyState?.httpVersion !== "http1Only"}
// The owner's engine would not see the change until it restarts.
disabled={other != null || setHttpVersion.isPending}
onChange={(enabled) =>
setHttpVersion.mutate({ httpVersion: enabled ? "auto" : "http1Only" })
}
/>
</KeepMenuOpen>
}
/>
),
},
{ 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 && (
<Pill color="warning" onClick={() => dropdownRef.current?.open()}>
<Icon icon="shield_off" size="xs" />
Certificate not trusted
</Pill>
)}
<Dropdown ref={dropdownRef} items={items}>
<Pill color={!running && other == null && proxyState != null ? "warning" : undefined}>
{other != null ? (
<Pill color={status === "stopped" ? "warning" : undefined}>
{status === "encrypting" ? (
<>
<LoadingIcon size="xs" />
<span className="text-text">Encrypting</span>
<span className="font-mono text-text-subtle">{encrypting}</span>
</>
) : status === "cli" && other != null ? (
<>
<StateDot state="cli" />
<span className="text-text">CLI</span>
{other.proxyPort != null && (
<span className="font-mono text-text-subtle">:{other.proxyPort}</span>
)}
</>
) : running ? (
) : status === "recording" || status === "paused" ? (
<>
<StateDot state={recording ? "recording" : "paused"} />
<StateDot state={status} />
<span className="text-text">{recording ? "Recording" : "Paused"}</span>
{port != null && <span className="font-mono text-text-subtle">:{port}</span>}
</>
) : (
<>
@@ -263,6 +235,12 @@ export function ProxyStatus() {
<Icon icon="chevron_down" size="xs" className="text-text-subtlest" />
</Pill>
</Dropdown>
{untrusted && (
<Pill color="warning" onClick={() => dropdownRef.current?.open()}>
<Icon icon="shield_off" size="xs" />
Certificate not trusted
</Pill>
)}
</>
);
}
@@ -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<typeof useProxySetup>) {
}
/** 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<SystemProxyStatus>(["system_proxy_status", {}], status),
});
const row = helperRow(status.helper, status.backend);
const error = unregister.error;
return (
<MenuRow
icon={
<Icon
icon={status.helper === "enabled" ? "badge_check" : "lock"}
size="sm"
color={status.helper === "enabled" ? "success" : "secondary"}
/>
}
title={row.title}
description={
error != null ? <span className="text-danger">{error.message}</span> : row.description
}
action={
row.action != null && (
<Button
size="2xs"
variant="border"
color={row.action === "unregister" ? "default" : "primary"}
isLoading={unregister.isPending}
onClick={(e) => {
e.stopPropagation();
if (row.action === "unregister") unregister.mutate({});
else onOpenDialog();
}}
>
{row.action === "install"
? "Install"
: row.action === "approve"
? "Approve"
: "Unregister"}
</Button>
)
}
/>
);
}
/** 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 (
+10 -5
View File
@@ -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({
</div>
<div className="flex flex-wrap gap-1.5 mt-2">
{p.droppedHeaders.map((h) => (
<span
<Tooltip
key={h.name}
title={`${h.name}: ${h.value}\n${reasonLabel(h.reason)}`}
className="font-mono text-xs leading-[22px] px-1.5 rounded-sm border border-border-subtle text-text-subtle line-through decoration-text-subtlest"
wrap
content={`${h.name}: ${h.value}\n${reasonLabel(h.reason)}`}
delay={CONTROL_TOOLTIP_DELAY}
>
{h.name}
</span>
<span className="font-mono text-xs leading-[22px] px-1.5 rounded-sm border border-border-subtle text-text-subtle line-through decoration-text-subtlest">
{h.name}
</span>
</Tooltip>
))}
</div>
</div>
@@ -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<SavedSearchDialog | null>(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 (
<NameDialog
key={dialog.mode === "save" ? `save:${dialog.query}` : `rename:${dialog.id}`}
dialog={dialog}
onClose={() => 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 (
<Dialog
open
onClose={onClose}
size="dynamic"
title={dialog.mode === "save" ? "Save search" : "Rename search"}
className="w-[26rem]"
>
<form
id={FORM_ID}
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<PlainInput
label="Name"
autoFocus
defaultValue={name}
onChange={setName}
placeholder={dialog.mode === "save" ? dialog.query : undefined}
/>
</form>
<DialogFooter
actions={[
{ label: "Cancel", variant: "border", onClick: onClose },
{
label: dialog.mode === "save" ? "Save" : "Rename",
color: "primary",
form: FORM_ID,
disabled: name.trim() === "",
isLoading: busy,
},
]}
/>
</Dialog>
);
}
+496 -78
View File
@@ -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 <input> as the ref
const inputRef = useRef<HTMLInputElement>(null);
// Bumped to empty the field, which only takes a value from outside when this changes
const [resetKey, setResetKey] = useState(0);
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<InputHandle | null>(null);
const boxRef = useRef<HTMLDivElement>(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<CSSProperties | null>(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<Extension>(
() =>
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 (
<div className="flex items-center gap-1.5 px-3 pb-1.5">
<div className="flex-1 min-w-0">
<PlainInput
ref={inputRef}
// Holds the header's place for the box, which floats over the list while focused
<div ref={boxRef} className="relative h-sm">
<div
style={place ?? undefined}
className={classNames(place == null ? "absolute inset-x-0 top-0" : "fixed z-30")}
>
<Input
renderEditor={(props) => (
<LazyCodeEditor {...props} keyDownHandler={startCompletionOnCtrlSpace} />
)}
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={
<Icon icon="search" size="sm" className="ml-2 mr-2.5 self-center text-text-subtlest" />
// oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- keeps focus in the editor
<div
onMouseDown={(e) => e.preventDefault()}
className="flex items-center self-center ml-0.5"
>
<FilterHistory history={history} store={store} disabled={locked} />
</div>
}
rightSlot={
text === "" ? (
<kbd className="self-center mr-2 px-1 rounded-sm border border-border-subtle font-sans text-2xs text-text-subtlest">
⌘F
</kbd>
) : (
<IconButton
size="xs"
icon="x"
title="Clear search"
iconColor="secondary"
className="self-center"
onClick={clear}
/>
)
// oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- keeps focus in the editor
<div
// Pressing these leaves the editor focused, so a wrapped box does not collapse and
// move them before the click lands.
onMouseDown={(e) => e.preventDefault()}
className="flex items-center self-center ml-1 mr-0.5"
>
{unapplied ? (
<Key className="mr-1">↵</Key>
) : hasText ? null : (
<Key className="ml-1 mr-1.5">⌘F</Key>
)}
{hasText && (
<>
<Dropdown
items={[
{
label: "Save search",
leftSlot: <Icon icon="bookmark" />,
onSelect: () =>
setSavedDialog({
mode: "save",
query: (draft.trim() === "" ? applied : draft).trim(),
}),
},
exportShown(),
]}
>
<IconButton
size="xs"
icon="ellipsis"
title="Search actions"
tooltip
iconColor="secondary"
/>
</Dropdown>
<IconButton
size="xs"
icon="x"
title="Clear search"
tooltip
iconColor="secondary"
onClick={clear}
/>
</>
)}
</div>
}
/>
</div>
<IconButton
size="xs"
icon="download"
iconColor="secondary"
title={query == null ? "Export every flow as HAR" : "Export the flows shown as HAR"}
onClick={async () => {
try {
const written = await exportHar(query == null ? {} : { filter: query }, "flows.har");
if (written != null) {
showToast({
message:
written === 1 ? "Exported 1 flow as HAR" : `Exported ${written} flows as HAR`,
});
}
} catch (err) {
showToast({ message: `Failed to export HAR: ${String(err)}`, color: "danger" });
}
}}
/>
</div>
);
});
function Key({ children, className }: { children: string; className?: string }) {
return (
<kbd
className={classNames(
className,
"px-1 rounded-sm border border-border-subtle font-sans text-2xs text-text-subtlest",
)}
>
{children}
</kbd>
);
}
/**
* 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: (
<span className="block font-mono text-xs truncate max-w-md" title={filter}>
{filter}
</span>
),
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: <Icon icon="trash" />,
onSelect: () => void rpc("clear_filter_history", {}).catch(fail),
},
];
return (
<Dropdown items={items}>
<IconButton
size="xs"
icon="search"
title="Recent filters"
tooltip
iconColor="secondary"
disabled={disabled}
/>
</Dropdown>
);
}
/** 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<HTMLElement>(".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"}`;
}
+265
View File
@@ -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<string | null>(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 (
<Dialog
open={tab != null}
onClose={() => setTab(null)}
size="lg"
noPadding
noScroll
className="h-[min(44rem,90vh)]"
>
{tab != null && <SettingsContent defaultTab={tab} />}
</Dialog>
);
}
/**
* 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<string>(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<SettingsTitlebar>(
() => ({
osType: getOsType(),
hideWindowControls,
// The proxy draws its own title bar always, as its main window does
useNativeTitlebar: false,
interfaceScale: 1,
}),
[hideWindowControls],
);
return (
<div className="h-full w-full bg-surface">
<SettingsContent key={shown.version} defaultTab={shown.tab} titlebar={titlebar} />
<HelperDialog />
<Toasts />
</div>
);
}
/** 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<SettingsCallbacks>(() => {
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 (
<SettingsDialog
titlebar={titlebar}
defaultTab={defaultTab}
tabs={[
{
value: SETTINGS_TAB_GENERAL,
label: "General",
icon: "settings",
content: <SettingsGeneral {...props} />,
},
{
value: SETTINGS_TAB_THEME,
label: "Theme",
icon: "palette",
content: <SettingsTheme {...props} />,
},
{
value: SETTINGS_TAB_INTERFACE,
label: "Interface",
icon: "columns_2",
content: <SettingsInterface {...props} />,
},
{
value: SETTINGS_TAB_PROXY,
label: "Proxy",
icon: "wifi",
content: <SettingsProxy />,
},
{
value: SETTINGS_TAB_LICENSE,
label: "License",
icon: "key_round",
content: <EmptyStateText>Coming soon</EmptyStateText>,
},
]}
/>
);
}
/** `⌘,`, 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<void>("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],
);
}
@@ -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 (
<VStack space={1.5} className="mb-4">
<div className="mb-3">
<Heading>Proxy</Heading>
<p className="text-text-subtle">Listening, decryption, traffic and terminals</p>
</div>
<SettingsList className="space-y-8">
<SettingsSection title="Proxy">
<PortRow disabled={elsewhere} />
<SettingRowSelect<HttpVersion>
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 && (
<>
<SettingRowBoolean
title="Override system proxy"
description="At launch"
checked={proxyState?.systemProxyAtLaunch ?? true}
disabled={setAtLaunch.isPending}
onChange={(enabled) => setAtLaunch.mutate({ enabled })}
/>
<HelperRow status={systemProxy.data} />
</>
)}
</SettingsSection>
<SettingsSection title="Decryption">
<DecryptListEditor className="py-4" />
</SettingsSection>
<SettingsSection title="Traffic">
<TrafficRow />
{proxyState?.traffic === "keep" && <KeepTrafficRow />}
<ConfirmClearRow />
<ResetRow />
</SettingsSection>
<SettingsSection title="Terminal">
<TerminalRow />
</SettingsSection>
</SettingsList>
</VStack>
);
}
/** 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<string | null>(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 (
<SettingRow title="Port" description="Restarts the proxy">
<PlainInput
hideLabel
size="sm"
name="port"
label="Port"
type="number"
containerClassName="w-48!"
defaultValue={`${saved}`}
forceUpdateKey={`${saved}.${resets}`}
disabled={disabled || setPort.isPending}
validate={(v) => parsePort(v) != null}
onChange={setDraft}
onBlur={commit}
onKeyDownCapture={(e) => {
if (e.key === "Enter") commit();
}}
/>
</SettingRow>
);
}
function HelperRow({ status }: { status: SystemProxyStatus }) {
const queryClient = useQueryClient();
const openDialog = useSetAtom(helperDialogOpenAtom);
const unregister = useRpcMutation("helper_unregister", {
onSuccess: (status) =>
queryClient.setQueryData<SystemProxyStatus>(["system_proxy_status", {}], status),
});
const row = helperRow(status.helper, status.backend);
return (
<SettingRow
title="Helper"
description={
unregister.error != null ? (
<span className="text-danger">{unregister.error.message}</span>
) : (
`${capitalize(row.title.replace(/^Helper: /, ""))}. ${row.description}`
)
}
>
{row.action != null && (
<Button
size="xs"
variant="border"
color={row.action === "unregister" ? "default" : "primary"}
isLoading={unregister.isPending}
onClick={() => (row.action === "unregister" ? unregister.mutate({}) : openDialog(true))}
>
{row.action === "install"
? "Install"
: row.action === "approve"
? "Approve"
: "Unregister"}
</Button>
)}
</SettingRow>
);
}
/** 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 (
<SettingRowSelect<TrafficRetention>
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 (
<SettingRow title="Size limit" description="Oldest flows dropped past it">
<div className="flex items-center gap-3">
{size.data != null && (
<span className="text-sm text-text-subtle tabular-nums whitespace-nowrap">
{formatSize(size.data.bytes)} used
</span>
)}
<SettingSelectControl
name="keepTraffic"
label="Size limit"
value={sizeOptionValue(keep)}
disabled={proxyState?.otherOwner != null}
onChange={(v) => setKeep.mutate({ bytes: sizeFromOptionValue(v) })}
options={sizeOptionsFor(KEEP_TRAFFIC_OPTIONS, keep).map(({ label, value }) => ({
label,
value,
}))}
/>
</div>
</SettingRow>
);
}
/** Asking before Clear, which its dialog's "Don't ask again" turns off */
function ConfirmClearRow() {
const [confirm, setConfirm] = useAtom(confirmClearFlowsAtom);
return (
<SettingRowBoolean title="Confirm before clearing" checked={confirm} onChange={setConfirm} />
);
}
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 (
<SettingRow title="Reset captured data" description="Deletes all flows and their keys">
<Button size="xs" variant="border" color="danger" onClick={() => setConfirming(true)}>
Reset…
</Button>
<Dialog
open={confirming}
onClose={() => setConfirming(false)}
size="sm"
title="Reset captured data?"
description="Every captured flow and the keys that encrypt them are deleted."
>
{reset.error != null && <p className="text-danger text-sm">{reset.error.message}</p>}
<DialogFooter
actions={[
{ label: "Cancel", variant: "border", onClick: () => setConfirming(false) },
{
label: "Reset",
color: "danger",
isLoading: reset.isPending,
onClick: () => reset.mutate({}),
},
]}
/>
</Dialog>
</SettingRow>
);
}
function TerminalRow() {
const proxyState = useAtomValue(proxyStateAtom);
const caStatus = useRpcQuery("ca_status", {});
const showToast = useShowToast();
const os = getOsType();
const [shell, setShell] = useState<TerminalShell>(() => 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 (
<div className="py-4">
<div className="flex items-center gap-2">
<span className="text-text">Environment</span>
<RadioDropdown
value={shell}
onChange={(v) => setShell(v as TerminalShell)}
items={TERMINAL_SHELLS.map((s) => ({ label: s.label, value: s.value }))}
>
<Button
size="2xs"
variant="border"
title="Shell"
rightSlot={<Icon icon="chevron_down" size="xs" className="ml-1" />}
>
{shellLabel}
</Button>
</RadioDropdown>
<Button
size="2xs"
variant="border"
className="ml-auto"
title={
os === "macos"
? "A new Terminal window with these set"
: "Not available on this platform yet"
}
disabled={caPath == null || os !== "macos"}
isLoading={openTerminal.isPending}
onClick={() =>
caPath != null && openTerminal.mutate({ vars: environmentVars(port, caPath) })
}
>
Open Terminal
</Button>
</div>
<p className="mt-1 text-sm text-text-subtle">Proxies one terminal instead of the system</p>
{caPath != null && (
<SettingSnippet
className="mt-3"
language="text"
snippet={environmentBlock(shell, port, caPath)}
/>
)}
</div>
);
}
function capitalize(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+280 -196
View File
@@ -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<TreeNode<SidebarItem>>((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<Record<string, boolean>>("sidebar_expanded", {}, undefined, {
getOnInit: true,
});
@@ -33,7 +38,7 @@ const expandedAtom = atomWithStorage<Record<string, boolean>>("sidebar_expanded"
/** The other nodes' collapsed flags, for this launch, as before */
const otherCollapsedAtom = atom<CollapsedMap>({});
/** 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<Flow, string[]>();
/**
* 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<SidebarItem> {
const root: SidebarItem = { id: "root", label: "All Traffic", count: 0 };
const rootNode: TreeNode<SidebarItem> = {
item: root,
parent: null,
depth: 0,
children: [],
draggable: false,
};
// Intermediate trie structure for building
type TrieNode = {
id: string;
label: string;
count: number;
children: Map<string, TrieNode>;
};
const domainMap = new Map<string, TrieNode>();
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<SidebarItem>,
depth: number,
): TreeNode<SidebarItem> {
const node: TreeNode<SidebarItem> = {
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<SidebarItem> = {
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<string, SidebarItem>();
for (const ex of exchanges) {
const key = appKeyOf(ex);
if (key == null) continue;
const id = appNodeId(key);
const app = apps.get(id);
if (app == null) {
apps.set(id, { id, label: ex.clientName ?? key, count: 1, appPath: ex.clientPath ?? key });
} else {
app.count++;
}
}
if (apps.size > 0) {
const appsFolder: TreeNode<SidebarItem> = {
item: { id: "apps", label: "Apps", count: 0 },
parent: rootNode,
depth: 1,
children: [],
draggable: false,
};
const sortedApps = [...apps.values()].sort((a, b) => collator.compare(a.label, b.label));
for (const item of sortedApps) {
appsFolder.children?.push({ item, parent: appsFolder, depth: 2, draggable: false });
}
rootNode.children?.push(appsFolder);
}
rootNode.children?.push(domainsFolder);
return rootNode;
function Count({ item }: { item: SidebarItem }) {
const text = item.count > 0 ? item.count.toLocaleString() : null;
if (text == null && item.kind !== "all") return null;
return (
<span className="ml-auto pl-2 text-text-subtlest text-2xs tabular-nums shrink-0">
{text ?? "0"}
</span>
);
}
function ItemInner({ item }: { item: SidebarItem }) {
const count = item.count;
if (item.kind === "group") {
return (
<div className="flex items-center gap-2 w-full min-w-0 text-xs text-text-subtlest">
<span className="truncate">{item.label}</span>
<Count item={item} />
</div>
);
}
return (
<div className="flex items-center gap-2 w-full min-w-0">
{item.appPath != null && <AppIcon path={item.appPath} />}
<span className="truncate">{item.label}</span>
{count > 0 && <span className="ml-auto text-text-subtlest text-2xs shrink-0">{count}</span>}
{item.kind === "all" && <Icon icon="layers" size="sm" className="text-text-subtle" />}
{item.kind === "tunnelled" && <Icon icon="lock" size="sm" className="text-text-subtle" />}
{item.kind === "saved" && <Icon icon="bookmark" size="sm" className="text-text-subtle" />}
{item.kind === "folder" && <Icon icon="folder" size="sm" className="text-text-subtle" />}
{item.appPath != null && <AppIcon path={item.appPath} className="size-[1.125rem]" />}
{item.kind === "folder" && item.path != null ? (
// Named by its last part; the whole path on hover
<Tooltip wrap content={item.path} delay={CONTROL_TOOLTIP_DELAY}>
<span className="truncate">{item.label}</span>
</Tooltip>
) : (
<span className="truncate">{item.label}</span>
)}
{item.sublabel != null && (
<span className="truncate text-xs text-text-subtlest">{item.sublabel}</span>
)}
{item.decrypt != null && <DecryptedMark item={item} />}
<Count item={item} />
</div>
);
}
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<HTMLElement>): 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<HTMLElement>): 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 (
<Tooltip wrap content="Decrypted" delay={CONTROL_TOOLTIP_DELAY}>
<Icon icon="lock_open" size="xs" className="shrink-0 text-text-subtlest" />
</Tooltip>
);
}
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: <Icon icon="folder_open" />,
onSelect: () => void revealPath(path, fail),
},
{
label: "Copy path",
leftSlot: <Icon icon="copy" />,
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 ? (
<span aria-hidden className="inline-block w-4 h-4" />
) : (
<Icon icon="check" size="sm" />
),
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: <Icon icon="pencil" />,
hidden: saved.length > 1 || first == null,
onSelect: () => {
if (first != null)
setSavedDialog({ mode: "rename", id: first.id, name: first.label });
},
},
{
label: "Delete",
color: "danger",
leftSlot: <Icon icon="trash" />,
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<NonNullable<TreeProps<SidebarItem>["renderContextMenu"]>>(
({ items, position, onClose }) =>
items.length === 0 ? (
<CloseAtOnce onClose={onClose} />
) : (
<ContextMenu items={items as DropdownItem[]} triggerPosition={position} onClose={onClose} />
),
[],
);
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.
<aside className="x-theme-sidebar bg-surface h-full w-full min-w-0 grid grid-rows-[minmax(0,1fr)] border-r border-border-subtle">
// in view rather than every site, host and path.
// A click or key here marks the selection change it makes as the person's, so it writes the
// search; the tree's own upkeep does not. Opening a row's menu selects it too, but leaves the
// search as it is, for the menu's Filter by This Value to add to, and the rows as it says.
// oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- only notes input the tree handles
<aside
onPointerDownCapture={(e) => {
if (!inSidebar(e)) return;
if (opensMenu(e)) noteSidebarMenu();
else noteSidebarInput();
}}
onKeyDownCapture={(e) => {
if (inSidebar(e)) noteSidebarInput();
}}
className="x-theme-sidebar bg-surface h-full w-full min-w-0 grid grid-rows-[minmax(0,1fr)] border-r border-border-subtle"
>
<Tree
treeId={treeId}
treeId={SIDEBAR_TREE_ID}
collapsedAtom={collapsedAtom}
className="px-2 pt-2 pb-10"
root={tree}
getItemKey={getItemKey}
ItemInner={ItemInner}
getContextMenu={getContextMenu}
renderContextMenu={renderContextMenu}
/>
</aside>
);
+6 -2
View File
@@ -1,2 +1,6 @@
// Hardcode font size for now. In the future, this could be configurable.
document.documentElement.style.fontSize = "14px";
import { applyFontSizes } from "./lib/interfaceSettings";
import { readSettingsValues, SETTINGS_VALUES_KEY } from "./lib/settings";
// Yaak's default sizes unless changed in Settings' Interface tab, so the two apps read as one
// family.
applyFontSizes(readSettingsValues(localStorage.getItem(SETTINGS_VALUES_KEY)));
@@ -0,0 +1,57 @@
import { useEffect, useState } from "react";
interface Probe {
x: number;
y: number;
kind: "drag" | "control" | "dead";
}
/**
* Dev only, with `?window&dragcheck`: probes the header across its width and marks what a press
* at each point lands on. Green drags the window (the element hit carries
* `data-tauri-drag-region`, which Tauri reads off the target alone), blue is a control, and red
* is dead space that neither drags nor does anything.
*/
export function DragRegionCheck() {
const [probes, setProbes] = useState<Probe[]>([]);
useEffect(() => {
const timer = setTimeout(() => {
const header = document.querySelector<HTMLElement>(".x-theme-appHeader");
if (header == null) return;
const rect = header.getBoundingClientRect();
const out: Probe[] = [];
for (const y of [rect.top + 6, rect.top + rect.height / 2]) {
for (let x = rect.left + 4; x < rect.right; x += 10) {
const el = document.elementFromPoint(x, y);
const kind =
el == null
? "dead"
: el.hasAttribute("data-tauri-drag-region")
? "drag"
: el.closest("button, input, [role=button], .cm-editor, [role=combobox]") != null
? "control"
: "dead";
out.push({ x, y, kind });
}
}
setProbes(out);
}, 800);
return () => clearTimeout(timer);
}, []);
return (
<div className="pointer-events-none fixed inset-0 z-50">
{probes.map((p) => (
<span
key={`${p.x}:${p.y}`}
className="absolute size-1.5 -ml-[3px] -mt-[3px] rounded-full"
style={{
left: p.x,
top: p.y,
background:
p.kind === "drag" ? "#22c55e" : p.kind === "control" ? "#3b82f6" : "#ef4444",
}}
/>
))}
</div>
);
}
+82 -94
View File
@@ -1,24 +1,18 @@
import {
HttpRequestPaneView,
HttpResponsePaneView,
type HttpBodyResult,
type ResponseViewMode,
} from "@yaakapp-internal/ui";
import { useMemo, useState } from "react";
import { ProxyEditorHost } from "../components/ProxyEditorHost";
import { findHeader } from "../lib/body";
import {
type FlowBodyData,
flowBodyFromRpc,
flowBodyLoader,
flowRequestToView,
flowResponseToView,
} from "../lib/flowViews";
import { useSetAtom, useStore } from "jotai";
import { useEffect, useLayoutEffect, useState } from "react";
import { AddColumnDialog } from "../components/AddColumnDialog";
import { FlowDetail } from "../components/FlowDetail";
import { FlowList } from "../components/FlowList";
import { browserTabMemory, learnedTabKey, flowShape } from "../lib/defaultTab";
import { goToPlace } from "../lib/navigation";
import { flowWindowAtom } from "../lib/store";
import { type FlowFixture, fixtures } from "./fixtures";
/**
* Dev only: renders captured flows through the shared request and response panes, read-only,
* side by side, the way the proxy's detail view will. Open `/harness.html?flow=0&theme=dark`.
* Dev only: captured flows in the detail card, over fixtures. Open
* `/harness.html?flow=0&theme=dark`; `&list` puts the flow list beside the card (its halves
* stacked), `&below` puts it above (side by side), and `&tab=info` opens the response half on a
* tab, as though it were chosen by hand for flows of that shape.
*/
export function FlowPanesHarness() {
const params = new URLSearchParams(location.search);
@@ -27,87 +21,81 @@ export function FlowPanesHarness() {
if (fixture == null) return null;
return (
<ProxyEditorHost formatText={formatLocally}>
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] gap-2 p-2 bg-surface">
<div className="flex gap-2 text-sm">
{fixtures.map((f, i) => (
<button
key={f.flow.id}
type="button"
className={i === index ? "text-text" : "text-text-subtle"}
onClick={() => setIndex(i)}
>
{f.label}
</button>
))}
</div>
<FlowPanes key={fixture.flow.id} fixture={fixture} />
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] gap-2 p-2 bg-surface">
<div className="flex gap-2 text-sm">
{fixtures.map((f, i) => (
<button
key={f.flow.id}
type="button"
className={i === index ? "text-text" : "text-text-subtle"}
onClick={() => setIndex(i)}
>
{f.label}
</button>
))}
</div>
</ProxyEditorHost>
);
}
function FlowPanes({ fixture }: { fixture: FlowFixture }) {
const { flow } = fixture;
const [viewMode, setViewMode] = useState<ResponseViewMode>("pretty");
const requestBody = useMemo(() => flowBodyFromRpc(fixture.requestBody), [fixture]);
const responseBody = useMemo(() => flowBodyFromRpc(fixture.responseBody), [fixture]);
const request = useMemo(() => flowRequestToView(flow, requestBody), [flow, requestBody]);
const response = useMemo(() => flowResponseToView(flow, responseBody), [flow, responseBody]);
const requestLoader = useMemo(
() =>
flowBodyLoader({
useBody: () => loaded(requestBody),
contentType: findHeader(flow.requestHeaders, "content-type"),
}),
[requestBody, flow],
);
const responseLoader = useMemo(
() =>
flowBodyLoader({
useBody: () => loaded(responseBody),
contentType: findHeader(flow.responseHeaders, "content-type"),
}),
[responseBody, flow],
);
return (
<div className="grid grid-cols-2 gap-2 min-h-0">
<div className="min-h-0 px-2">
<HttpRequestPaneView
request={request}
fullHeight
forceUpdateKey={flow.updatedAt}
tabsStorageKey="flow_request_tabs"
bodyLoader={requestLoader}
/>
</div>
<HttpResponsePaneView
response={response}
body={responseLoader}
requestBody={requestLoader}
emptyState={<div className="p-3 text-text-subtle">Waiting for a response</div>}
viewMode={viewMode}
onViewModeChange={setViewMode}
tabsStorageKey="flow_response_tabs"
activeTabKey={flow.id}
onCopyAsCurl={() => undefined}
/>
<FixtureCard key={fixture.flow.id} fixture={fixture} />
<AddColumnDialog />
</div>
);
}
function loaded(data: FlowBodyData): HttpBodyResult<FlowBodyData | null> {
return { data, isLoading: false, error: null };
}
function FixtureCard({ fixture }: { fixture: FlowFixture }) {
const params = new URLSearchParams(location.search);
const store = useStore();
const setWindow = useSetAtom(flowWindowAtom);
const [ready, setReady] = useState(false);
useLayoutEffect(() => {
const flows = fixtures.map((f, i) => ({ ...f.flow, number: 1401 + i }));
const tab = params.get("tab");
if (tab != null) {
browserTabMemory()?.setItem(learnedTabKey("response", flowShape(fixture.flow)), tab);
}
setWindow({ flows, hasOlder: false, total: flows.length });
const shown = flows.find((f) => f.id === fixture.flow.id) ?? fixture.flow;
goToPlace(store, "update", { selection: [shown.id], flow: shown });
setReady(true);
// oxlint-disable-next-line react-hooks/exhaustive-deps -- once per fixture
}, [fixture]);
/** The engine formats JSON over RPC, which a page outside the app can't reach */
async function formatLocally(text: string, language: unknown): Promise<string> {
if (language !== "json") return text;
try {
return JSON.stringify(JSON.parse(text), null, 2);
} catch {
return text;
// `&arrive=3`: that many new flows, one a second, as traffic would bring them
useEffect(() => {
const count = Number(params.get("arrive") ?? 0);
let added = 0;
const timer = setInterval(() => {
if (added >= count) return clearInterval(timer);
added++;
const source = fixtures[added % fixtures.length]?.flow;
if (source == null) return;
const flow = {
...source,
// The fixture's id first, so the backend finds its bodies, as `manyFlows` does
id: `${source.id}~arrived_${added}`,
number: 1500 + added,
startedAt: new Date().toISOString().slice(0, 23),
};
setWindow((w) => ({ ...w, flows: [...w.flows, flow], total: w.total + 1 }));
}, 1000);
return () => clearInterval(timer);
// oxlint-disable-next-line react-hooks/exhaustive-deps -- once per fixture
}, [fixture]);
if (!ready) return null;
if (params.has("list")) {
return (
<div className="h-full min-h-0 grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">
<FlowList className="min-h-0" />
<FlowDetail sideBySide />
</div>
);
}
if (params.has("below")) {
return (
<div className="h-full min-h-0 grid grid-rows-[minmax(0,0.45fr)_minmax(0,0.55fr)]">
<FlowList className="min-h-0" />
<FlowDetail sideBySide={false} />
</div>
);
}
return <FlowDetail sideBySide={false} />;
}
+102
View File
@@ -0,0 +1,102 @@
import { HotkeyProvider } from "@yaakapp-internal/ui";
import type { GetProxyStateResponse } from "@yaakapp-internal/proxy-lib";
import { useStore } from "jotai";
import { type ReactNode, useEffect, useState } from "react";
import { ProxyLayout } from "../components/ProxyLayout";
import { DragRegionCheck } from "./DragRegionCheck";
import { useHotkeyContextValue } from "../lib/hotkeys";
import { syncNavigation, syncSidebarSelection } from "../lib/navigation";
import { syncFlows, syncProxyState } from "../lib/store";
const LOCKED =
"Traffic is locked: Yaak Proxy stores traffic encrypted and couldn't read its key from the " +
"keychain: Encryption error: User canceled the operation. Allow it access, then retry.";
const STATE: GetProxyStateResponse = {
state: "stopped",
port: null,
configuredPort: 9090,
recording: true,
systemProxyAtLaunch: true,
httpVersion: "auto",
startError: LOCKED.slice("Traffic is locked: ".length),
encrypting: null,
locked: { message: LOCKED, keychain: true },
otherOwner: null,
captureBodyLimit: 10 * 1024 * 1024,
traffic: "clearOnLaunch",
keepTrafficBytes: null,
};
/** What the backend answers while the keychain refuses: the state, and every read refused */
function answer(cmd: string): unknown {
switch (cmd) {
case "get_proxy_state":
return STATE;
case "ca_status":
return { trusted: true, installed: true, certPath: "/tmp/yaak-proxy-ca.pem" };
case "system_proxy_status":
return {
enabled: false,
port: 9090,
services: [],
backend: "helper",
helper: "enabled",
supported: true,
};
case "list_actions":
return { actions: [] };
default:
throw new Error(LOCKED);
}
}
/** Stands in for Tauri's IPC, answering as a locked proxy does */
export function installLockedBackend() {
const internals = (window as unknown as { __TAURI_INTERNALS__: Record<string, unknown> })
.__TAURI_INTERNALS__;
internals.invoke = async (cmd: string, args?: { cmd?: string }) => {
if (cmd === "rpc") return answer(args?.cmd ?? "");
if (cmd.startsWith("plugin:event|")) return 0;
throw new Error(`Not in the harness: ${cmd}`);
};
(
window as unknown as { __TAURI_OS_PLUGIN_INTERNALS__: Record<string, string> }
).__TAURI_OS_PLUGIN_INTERNALS__ = {
os_type: "macos",
platform: "macos",
family: "unix",
version: "15.0",
eol: "\n",
};
// Setup was done before, as for anyone whose traffic is locked after an upgrade.
localStorage.setItem("system_proxy_ever_on", "true");
}
/**
* The whole window, as the app renders it: while captured traffic is locked, or over the
* fixture backend with `?window`
*/
export function LockedHarness() {
const store = useStore();
const [synced, setSynced] = useState(false);
useEffect(() => {
syncProxyState(store);
void syncNavigation(store).then(() => {
syncFlows(store);
syncSidebarSelection(store);
setSynced(true);
});
}, [store]);
if (!synced) return null;
return (
<Hotkeys>
<ProxyLayout />
{new URLSearchParams(location.search).has("dragcheck") && <DragRegionCheck />}
</Hotkeys>
);
}
function Hotkeys({ children }: { children: ReactNode }) {
return <HotkeyProvider value={useHotkeyContextValue()}>{children}</HotkeyProvider>;
}
@@ -0,0 +1,81 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import { useSetAtom, useStore } from "jotai";
import { useLayoutEffect, useMemo, useState } from "react";
import { FlowDetail } from "../components/FlowDetail";
import { FlowList } from "../components/FlowList";
import { ProxyEditorHost } from "../components/ProxyEditorHost";
import { MessageSourceContext } from "../hooks/useFlowMessages";
import { goToPlace } from "../lib/navigation";
import { flowWindowAtom } from "../lib/store";
import { fixtureSource, type StreamFixture, streamFixtures } from "./streamFixtures";
/**
* Dev only: a streaming flow's detail, opened on its Messages tab, over fixtures served the way
* the engine serves them. Open `/harness.html?stream=0&theme=dark`; add `&list` for the flow list
* beside it, holding every fixture's flow.
*/
export function MessagesHarness() {
const params = new URLSearchParams(location.search);
const [index, setIndex] = useState(Number(params.get("stream") ?? 0));
const fixture = streamFixtures[index] ?? streamFixtures[0];
if (fixture == null) return null;
return (
<ProxyEditorHost>
<div className="h-full w-full grid grid-rows-[auto_minmax(0,1fr)] gap-2 p-2 bg-surface">
<div className="flex gap-2 text-sm">
{streamFixtures.map((f, i) => (
<button
key={f.flow.id}
type="button"
className={i === index ? "text-text" : "text-text-subtle"}
onClick={() => setIndex(i)}
>
{f.label}
</button>
))}
</div>
<StreamDetail key={fixture.flow.id} fixture={fixture} />
</div>
</ProxyEditorHost>
);
}
/** Each fixture's flow as the list holds it, one after another, the shown one as it is now */
function listedFlows(shown: Flow): Flow[] {
return streamFixtures.map((f, i) => {
const flow = f.flow.id === shown.id ? shown : f.flow;
return { ...flow, number: 1410 + i, startedAt: `2026-11-05T21:41:1${i}.000` };
});
}
function StreamDetail({ fixture }: { fixture: StreamFixture }) {
const source = useMemo(() => fixtureSource(fixture), [fixture]);
const store = useStore();
const setWindow = useSetAtom(flowWindowAtom);
const [flow, setFlow] = useState(fixture.flow);
const withList = new URLSearchParams(location.search).has("list");
useLayoutEffect(() => {
const flows = listedFlows(flow);
setWindow({ flows, hasOlder: false, total: flows.length });
const shown = flows.find((f) => f.id === flow.id) ?? flow;
goToPlace(store, "update", { selection: [shown.id], flow: shown });
}, [flow, store, setWindow]);
// The count on the flow follows its messages, as the engine writes it
useLayoutEffect(
() => source.subscribe(() => setFlow((f) => ({ ...f, messageCount: f.messageCount + 1 }))),
[source],
);
return (
<MessageSourceContext.Provider value={source}>
{withList ? (
<div className="h-full min-h-0 grid grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">
<FlowList className="min-h-0" />
<FlowDetail sideBySide />
</div>
) : (
<FlowDetail sideBySide={false} />
)}
</MessageSourceContext.Provider>
);
}
@@ -0,0 +1,26 @@
import { useStore } from "jotai";
import { useEffect, useState } from "react";
import { SETTINGS_TAB_PROXY, SettingsContent } from "../components/Settings";
import { syncProxyState } from "../lib/store";
/**
* Dev only: the settings window over the fixture backend, at the dialog's size. Open
* `/harness.html?settings&theme=dark`; `&tab=general` opens another tab than Proxy.
*/
export function SettingsHarness() {
const store = useStore();
const [synced, setSynced] = useState(false);
useEffect(() => {
syncProxyState(store);
setSynced(true);
}, [store]);
const tab = new URLSearchParams(location.search).get("tab") ?? SETTINGS_TAB_PROXY;
if (!synced) return null;
return (
<div className="h-full w-full grid place-items-center bg-surface-highlight p-6">
<div className="h-full w-[min(56rem,100%)] bg-surface rounded-lg border border-border-subtle overflow-hidden">
<SettingsContent defaultTab={tab} />
</div>
</div>
);
}
+378
View File
@@ -0,0 +1,378 @@
import type {
Flow,
FlowSortKey,
GetProxyStateResponse,
SavedQuery,
} from "@yaakapp-internal/proxy-lib";
import { sortFlows } from "../lib/columns";
import { appIconPng, fixtures } from "./fixtures";
/**
* Dev only: answers the engine's RPCs the harness pages need, from fixtures, so the card and
* settings render outside the app as they do inside it.
*/
export function installFixtureBackend() {
const internals = (window as unknown as { __TAURI_INTERNALS__: Record<string, unknown> })
.__TAURI_INTERNALS__;
// For checking the window as traffic arrives: `__harnessEmit("model_write", payload)`
(window as unknown as { __harnessEmit: typeof emit }).__harnessEmit = emit;
internals.transformCallback = (callback: (event: unknown) => void) => {
const id = callbacks.size + 1;
callbacks.set(id, callback);
return id;
};
internals.invoke = async (
cmd: string,
args?: { cmd?: string; payload?: unknown; event?: string; handler?: number },
) => {
if (cmd === "rpc") return answer(args?.cmd ?? "", args?.payload);
if (cmd === "plugin:event|listen" && args?.event != null && args.handler != null) {
listeners.set(args.event, [...(listeners.get(args.event) ?? []), args.handler]);
return args.handler;
}
if (cmd.startsWith("plugin:event|")) return 0;
// The app menu's Go items, which the harness has none of
if (cmd === "set_go_menu") return null;
throw new Error(`Not in the harness: ${cmd}`);
};
(
window as unknown as { __TAURI_OS_PLUGIN_INTERNALS__: Record<string, string> }
).__TAURI_OS_PLUGIN_INTERNALS__ = {
os_type: "macos",
platform: "macos",
family: "unix",
version: "15.0",
eol: "\n",
};
}
export const HARNESS_STATE: GetProxyStateResponse = {
state: "running",
port: 9090,
configuredPort: 9090,
recording: true,
systemProxyAtLaunch: true,
httpVersion: "auto",
captureBodyLimit: 10 * 1024 * 1024,
traffic: "keep",
keepTrafficBytes: 2 * 1024 * 1024 * 1024,
startError: null,
encrypting: null,
locked: null,
otherOwner: null,
};
/** The engine's state as `?status=paused`, `stopped`, `failed` or `cli` asks; recording otherwise */
function harnessState(status: string | null): GetProxyStateResponse {
const stopped = { ...HARNESS_STATE, state: "stopped" as const, port: null };
switch (status) {
case "paused":
return { ...HARNESS_STATE, recording: false };
case "stopped":
return stopped;
case "failed":
return { ...stopped, startError: "Port 9090 is in use by another process." };
case "cli":
return {
...stopped,
otherOwner: {
owner: "cli",
pid: 4242,
startedAt: new Date().toISOString(),
proxyPort: 9090,
},
};
default:
return HARNESS_STATE;
}
}
/** Callbacks the window registered, by id, and the ids listening to each event */
const callbacks = new Map<number, (event: unknown) => void>();
const listeners = new Map<string, number[]>();
/** Sends an event to the window, as the engine does */
function emit(event: string, payload: unknown = {}) {
for (const id of listeners.get(event) ?? []) callbacks.get(id)?.({ event, id, payload });
}
/** Filters applied, newest first, and saved searches, kept across reloads as the database is */
const HISTORY_KEY = "harness_filter_history";
const SAVED_KEY = "harness_saved_queries";
const LAST_FILTER_KEY = "harness_last_filter";
function stored<T>(key: string): T[] {
try {
return JSON.parse(localStorage.getItem(key) ?? "[]") as T[];
} catch {
return [];
}
}
function store(key: string, value: unknown[]) {
localStorage.setItem(key, JSON.stringify(value));
}
/**
* A rough stand-in for the engine's search: `@host:`, `@method:` and `@status:` terms, and bare
* words in the method, URL and status
*/
function matches(flow: Flow, query: string): boolean {
const host = (() => {
try {
return new URL(flow.url).host;
} catch {
return flow.url;
}
})();
const text = `${flow.method} ${flow.url} ${flow.status ?? ""}`.toLowerCase();
// `OR` between groups, as the sidebar writes several rows
const groups = query.replace(/[()]/g, " ").split(/\s+OR\s+/);
if (groups.length > 1) return groups.some((g) => matches(flow, g));
return query
.toLowerCase()
.split(/\s+/)
.filter((t) => t !== "")
.every((term) => {
const [, field, value = ""] = /^@([a-z.]+):(.*)$/.exec(term) ?? [];
if (field === "host") return host.toLowerCase().includes(value.replaceAll("*", ""));
if (field === "method") return flow.method.toLowerCase() === value;
if (field === "status") return String(flow.status ?? "").startsWith(value.replace(/x+$/, ""));
return field == null ? text.includes(term) : true;
});
}
function allFlows(): Flow[] {
const many = Number(new URLSearchParams(location.search).get("many") ?? 0);
return (many > 0 ? manyFlows(many) : fixtures.map((f) => f.flow)).map((f, i) => ({
...f,
number: 1401 + i,
}));
}
function answer(cmd: string, payload: unknown): unknown {
const req = (payload ?? {}) as Record<string, unknown>;
switch (cmd) {
case "get_flows": {
const ids = new Set(req.ids as string[]);
return allFlows().filter((f) => ids.has(f.id));
}
case "list_filter_history":
return stored<string>(HISTORY_KEY).map((filter) => ({ filter, appliedAt: "" }));
case "record_filter": {
const filter = String(req.filter).trim();
if (filter === "") return false;
store(HISTORY_KEY, [filter, ...stored<string>(HISTORY_KEY).filter((f) => f !== filter)]);
emit("filter_history_changed");
return true;
}
case "delete_filter_history":
store(
HISTORY_KEY,
stored<string>(HISTORY_KEY).filter((f) => f !== req.filter),
);
emit("filter_history_changed");
return true;
case "clear_filter_history":
store(HISTORY_KEY, []);
emit("filter_history_changed");
return 0;
// Held by the engine for as long as the app runs; the tab's session here
case "get_window_places":
return sessionStorage.getItem("harness_window_places");
case "set_window_places":
sessionStorage.setItem("harness_window_places", String(req.places));
return true;
case "get_last_filter":
return localStorage.getItem(LAST_FILTER_KEY) ?? "";
case "set_last_filter":
localStorage.setItem(LAST_FILTER_KEY, String(req.filter));
return true;
case "list_saved_queries":
return stored<SavedQuery>(SAVED_KEY);
case "create_saved_query": {
const saved = stored<SavedQuery>(SAVED_KEY);
const query = {
id: `sq_${saved.length + 1}`,
name: String(req.name),
query: String(req.query),
sortOrder: saved.length,
};
store(SAVED_KEY, [...saved, query]);
emit("saved_queries_changed");
return query;
}
case "count_saved_queries":
return stored<SavedQuery>(SAVED_KEY).map((s) => ({
id: s.id,
count: allFlows().filter((f) => matches(f, s.query)).length,
}));
case "watch_query":
return true;
case "get_flow_body": {
// A copy from `?many` reads its original's body
const id = String(req.flowId).split("~")[0];
const fixture = fixtures.find((f) => f.flow.id === id);
if (fixture == null) throw new Error(`No fixture for ${String(req.flowId)}`);
return req.which === "request" ? fixture.requestBody : fixture.responseBody;
}
case "format_body": {
const text = typeof req.text === "string" ? req.text : "";
try {
return JSON.stringify(JSON.parse(text), null, 2);
} catch {
return text;
}
}
case "app_icon":
return appIconPng;
case "get_proxy_state":
return harnessState(new URLSearchParams(location.search).get("status"));
case "get_storage_size":
return { bytes: 412 * 1024 * 1024 };
case "ca_status":
return {
trusted: true,
installed: true,
certPath: "/Users/you/Library/Application Support/app.yaak.proxy/ca.pem",
};
case "system_proxy_status":
return {
enabled: true,
port: 9090,
services: [],
backend: "helper",
helper: "enabled",
supported: true,
};
case "get_decrypt_list":
return {
entries: [
{ entry: "host:api.stripe.com", builtIn: false },
{ entry: "app:Google Chrome", builtIn: false },
{ entry: "!host:*.apple.com", builtIn: true },
],
};
case "list_actions":
// As the engine lists them on macOS
return {
actions: [
[
{ scope: "global", action: "recording_toggle" },
{ label: "Pause or Resume Recording", defaultHotkey: "Meta+R" },
],
[
{ scope: "global", action: "flows_clear" },
{ label: "Clear Flows", defaultHotkey: "Meta+Shift+K" },
],
],
};
case "list_flows": {
const all = allFlows();
const query = typeof req.query === "string" ? req.query : "";
const matching = all.filter((f) => matches(f, query));
// In a sort's order, as the database lists it, all in one page
const sort = (req.sort ?? []) as FlowSortKey[];
const flows = sort.length > 0 ? sortFlows(matching, sort) : matching.reverse();
const page = req.limit === 0 ? [] : flows;
return {
flows: page,
total: all.length,
matching: query === "" ? null : matching.length,
cursor: null,
};
}
case "list_seen":
return { hosts: [], apps: [] };
// A few of the engine's fields, so the search box highlights and completes
case "query_schema":
return {
schema: {
fields: [
{
name: "host",
kind: { type: "text" },
info: "The request's host",
example: "@host:api.example.com",
},
{
name: "method",
kind: { type: "text" },
info: "GET, POST, …",
example: "@method:post",
},
{
name: "status",
kind: { type: "number", units: [] },
info: "The response's status",
example: "@status:>=400",
},
{
name: "header",
kind: { type: "text" },
map: true,
info: "A request or response header",
example: "@header.accept:*json*",
},
{
name: "res.header",
kind: { type: "text" },
map: true,
info: "A response header",
example: "@res.header.x-cache:hit",
},
{
name: "query",
kind: { type: "text" },
map: true,
info: "A query parameter",
example: "@query.page:2",
},
],
},
};
// Header and query parameter names, for completing a map's keys
case "query_values": {
const path = (payload as { path?: string } | undefined)?.path ?? "";
if (path.endsWith("header")) return ["x-cache", "x-request-id", "content-type"];
return path === "query" ? ["expand", "limit"] : [];
}
case "validate_query":
return [];
default:
throw new Error(`Not in the harness: ${cmd}`);
}
}
/**
* `?many=3000`: the fixtures over and over, a second apart, for checking the list with a lot of
* traffic. Every fourth has no response yet, and a program runs in a few working folders.
*/
function manyFlows(count: number): Flow[] {
const start = Date.parse("2026-11-09T09:00:00Z");
const folders = ["/Users/you/src/yaak", "/Users/you/.codex/worktrees/1a79/yaak", null];
return Array.from({ length: count }, (_, i) => {
const base = fixtures[i % fixtures.length]?.flow as Flow;
const pending = i % 4 === 3;
return {
...base,
id: `${base.id}~${i}`,
startedAt: new Date(start + i * 1000).toISOString().replace("Z", ""),
url:
i % 7 === 0 ? `${base.url}/a/rather/long/path/segment/${i}?page=${i}&q=search` : base.url,
status: pending ? null : base.status,
contentType: pending ? null : base.contentType,
responseSize: pending ? 0 : base.responseSize,
elapsedMs: pending ? null : base.elapsedMs,
clientCwd: base.clientBundleId == null ? (folders[i % folders.length] ?? null) : null,
// A cache header with a few values and some without, for a column of it to sort
responseHeaders:
i % 5 === 4
? base.responseHeaders
: [
...base.responseHeaders,
{ name: "X-Cache", value: ["HIT", "miss", "Hit", "EXPIRED"][i % 4] ?? "" },
],
};
});
}
+163
View File
@@ -17,6 +17,7 @@ function body(data: string | Uint8Array): GetFlowBodyResponse {
const base: Flow = {
id: "fl_harness",
number: 1429,
createdAt: "2026-11-04T22:10:00",
updatedAt: "2026-11-04T22:10:01",
startedAt: "2026-11-04T22:10:00.000",
@@ -42,6 +43,22 @@ const base: Flow = {
clientName: "curl",
clientBundleId: null,
clientPath: "/usr/bin/curl",
clientCwd: null,
streamKind: null,
messageCount: 0,
grpcService: null,
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
graphqlOperation: null,
tunnelled: false,
agentRead: false,
clientAddr: "127.0.0.1:54321",
elapsedConnectMs: 18,
elapsedTlsMs: 41,
elapsedRequestMs: 43,
upstreamTlsVersion: "TLSv1.3",
upstreamTlsCipher: "TLS13_AES_128_GCM_SHA256",
};
const jsonRequest = JSON.stringify({ amount: 4200, currency: "usd", capture: true });
@@ -53,7 +70,43 @@ const jsonResponse = JSON.stringify({
status: "succeeded",
charges: { data: [{ id: "ch_1", paid: true }] },
});
const graphqlRequest = JSON.stringify({
query: "query GetViewer { viewer { login } }",
operationName: "GetViewer",
});
const formRequest = "grant_type=client_credentials&client_id=yaak-proxy&scope=read+write";
const csvResponse = [
"id,email,plan,created_at",
"1,ada@example.com,pro,2026-10-01",
"2,grace@example.com,team,2026-10-14",
"3,linus@example.com,free,2026-11-02",
].join("\n");
const tsvResponse = [
"sku\tname\tstock\tnote",
"A-100\tDesk lamp\t42\tWarm white, dimmable, ships with a long braided fabric cable",
"A-101\tMonitor arm\t7\t",
"A-102\tKeyboard tray\t0\tBack in stock next week",
].join("\n");
const multipartBoundary = "yaakBoundary7MA4YWxk";
const multipartRequest = [
`--${multipartBoundary}`,
'Content-Disposition: form-data; name="title"',
"",
"Quarterly report",
`--${multipartBoundary}`,
'Content-Disposition: form-data; name="meta"; filename="meta.json"',
"Content-Type: application/json",
"",
'{"pages":12,"draft":false}',
`--${multipartBoundary}`,
'Content-Disposition: form-data; name="rows"; filename="rows.csv"',
"Content-Type: text/csv",
"",
"region,revenue\nnorth,1200\nsouth,980",
`--${multipartBoundary}--`,
"",
].join("\r\n");
const textResponse = "Uploaded 3 parts";
const htmlResponse =
"<!doctype html><html><body style='font-family:sans-serif'><h1>Signed in</h1><p>You can close this window.</p></body></html>";
// A 24x24 PNG gradient
@@ -138,4 +191,114 @@ export const fixtures: FlowFixture[] = [
requestBody: body(""),
responseBody: body(""),
},
{
label: "Tunnelled",
flow: {
...base,
id: "fl_tunnel",
method: "CONNECT",
url: "bank.example.com:443",
status: null,
elapsedHeadersMs: null,
elapsedMs: 4_210,
clientHttpVersion: "HTTP/1.1",
upstreamHttpVersion: null,
clientName: "Safari",
clientBundleId: "com.apple.Safari",
clientPath: "/Applications/Safari.app",
requestSize: 3_412,
responseSize: 48_210,
tunnelled: true,
},
requestBody: body(""),
responseBody: body(""),
},
{
label: "GraphQL POST",
flow: {
...base,
id: "fl_graphql",
method: "POST",
url: "https://api.github.com/graphql",
contentType: "application/json",
requestHeaders: [{ name: "Content-Type", value: "application/json" }],
responseHeaders: [{ name: "X-Cache", value: "MISS" }],
requestSize: graphqlRequest.length,
responseSize: 64,
graphqlOperation: "GetViewer",
},
requestBody: body(graphqlRequest),
responseBody: body('{"data":{"viewer":{"login":"yaak"}}}'),
},
{
label: "CSV GET",
flow: {
...base,
id: "fl_csv",
url: "https://api.example.com/users/export.csv",
contentType: "text/csv",
requestHeaders: [{ name: "Accept", value: "text/csv" }],
responseHeaders: [{ name: "Content-Type", value: "text/csv; charset=utf-8" }],
responseSize: csvResponse.length,
},
requestBody: body(""),
responseBody: body(csvResponse),
},
{
label: "TSV GET",
flow: {
...base,
id: "fl_tsv",
url: "https://api.example.com/inventory.tsv",
contentType: "text/tab-separated-values",
requestHeaders: [{ name: "Accept", value: "text/tab-separated-values" }],
responseHeaders: [{ name: "Content-Type", value: "text/tab-separated-values" }],
responseSize: tsvResponse.length,
},
requestBody: body(""),
responseBody: body(tsvResponse),
},
{
label: "Multipart POST",
flow: {
...base,
id: "fl_multipart",
method: "POST",
url: "https://api.example.com/reports",
contentType: "text/plain",
requestHeaders: [
{
name: "Content-Type",
value: `multipart/form-data; boundary=${multipartBoundary}`,
},
],
responseHeaders: [{ name: "Content-Type", value: "text/plain; charset=utf-8" }],
requestSize: multipartRequest.length,
responseSize: textResponse.length,
},
requestBody: body(multipartRequest),
responseBody: body(textResponse),
},
{
label: "gRPC call",
flow: {
...base,
id: "fl_grpc",
method: "POST",
url: "https://grpc.example.com/pkg.Greeter/SayHello",
contentType: "application/grpc",
clientHttpVersion: "HTTP/2",
upstreamHttpVersion: "HTTP/2",
requestHeaders: [{ name: "Content-Type", value: "application/grpc" }],
responseHeaders: [{ name: "Content-Type", value: "application/grpc" }],
grpcService: "pkg.Greeter",
grpcMethod: "SayHello",
grpcStatus: 0,
},
requestBody: body(""),
responseBody: body(""),
},
];
/** An app icon for every flow in the harness, as base64 PNG */
export const appIconPng = btoa(String.fromCharCode(...png));
+24 -2
View File
@@ -1,19 +1,41 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { applyThemeToDocument, defaultDarkTheme, defaultLightTheme } from "@yaakapp-internal/theme";
import { createStore, Provider } from "jotai";
import { LazyMotion, MotionConfig } from "motion/react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { installFixtureBackend } from "./backend";
import { FlowPanesHarness } from "./FlowPanesHarness";
import { installLockedBackend, LockedHarness } from "./LockedHarness";
import { MessagesHarness } from "./MessagesHarness";
import { SettingsHarness } from "./SettingsHarness";
import "../main.css";
const dark = new URLSearchParams(location.search).get("theme") !== "light";
const params = new URLSearchParams(location.search);
// As the app loads them, so dialogs fade in
const motionFeatures = () => import("framer-motion").then((mod) => mod.domAnimation);
const dark = params.get("theme") !== "light";
applyThemeToDocument(dark ? defaultDarkTheme : defaultLightTheme);
if (params.has("locked")) installLockedBackend();
else installFixtureBackend();
createRoot(document.getElementById("root") as HTMLElement).render(
<StrictMode>
<QueryClientProvider client={new QueryClient()}>
<Provider store={createStore()}>
<FlowPanesHarness />
<LazyMotion strict features={motionFeatures}>
<MotionConfig transition={{ duration: 0.1 }}>
{params.has("locked") || params.has("window") ? (
<LockedHarness />
) : params.has("settings") ? (
<SettingsHarness />
) : params.has("stream") ? (
<MessagesHarness />
) : (
<FlowPanesHarness />
)}
</MotionConfig>
</LazyMotion>
</Provider>
</QueryClientProvider>
</StrictMode>,
+381
View File
@@ -0,0 +1,381 @@
import type { DecodedGrpcMessage, Flow, FlowMessage } from "@yaakapp-internal/proxy-lib";
import type { MessageSource } from "../hooks/useFlowMessages";
/** A streaming flow with its messages and their payloads, for the Messages tab */
export interface StreamFixture {
label: string;
flow: Flow;
messages: FlowMessage[];
payloads: Uint8Array[];
/** Messages still to come while the harness runs, one at a time */
later?: { message: FlowMessage; payload: Uint8Array }[];
decoded?: Record<number, { decoded: DecodedGrpcMessage; schemaless: DecodedGrpcMessage }>;
}
const encode = (s: string) => new TextEncoder().encode(s);
const flowBase: Flow = {
id: "fl_stream",
number: 1410,
createdAt: "2026-11-05T21:41:12",
updatedAt: "2026-11-05T21:41:20",
startedAt: "2026-11-05T21:41:12.100",
method: "GET",
url: "https://gateway.discord.gg/?v=10&encoding=json",
clientHttpVersion: "HTTP/1.1",
upstreamHttpVersion: "HTTP/1.1",
remoteAddr: "162.159.135.234:443",
status: 101,
contentType: null,
requestHeaders: [{ name: "Upgrade", value: "websocket" }],
responseHeaders: [{ name: "Upgrade", value: "websocket" }],
requestSize: 0,
responseSize: 0,
requestTruncated: false,
responseTruncated: false,
elapsedHeadersMs: 88,
elapsedMs: 128_400,
error: null,
cancelled: false,
savedRequestId: null,
clientPid: 812,
clientName: "Discord",
clientBundleId: "com.hnc.Discord",
clientPath: "/Applications/Discord.app",
clientCwd: null,
streamKind: "websocket",
messageCount: 0,
grpcService: null,
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
graphqlOperation: null,
tunnelled: false,
agentRead: false,
clientAddr: null,
elapsedConnectMs: null,
elapsedTlsMs: null,
elapsedRequestMs: null,
upstreamTlsVersion: null,
upstreamTlsCipher: null,
};
/** Seconds past 21:41:12 as a stored timestamp */
function at(seconds: number): string {
const ms = Math.round(seconds * 1000);
const s = 12 + Math.floor(ms / 1000);
const m = 41 + Math.floor(s / 60);
const pad = (n: number, w = 2) => String(n).padStart(w, "0");
return `2026-11-05T21:${pad(m)}:${pad(s % 60)}.${pad(ms % 1000, 3)}`;
}
function build(
flowId: string,
rows: [number, FlowMessage["direction"], FlowMessage["kind"], Uint8Array, FlowMessage["meta"]?][],
): { messages: FlowMessage[]; payloads: Uint8Array[] } {
const messages = rows.map(([seconds, direction, kind, payload, meta], seq) => {
const text = new TextDecoder().decode(payload);
const binary = kind === "websocket_binary" || kind === "grpc_message";
return {
id: `fm_${flowId}_${seq}`,
flowId,
seq,
direction,
kind,
timestamp: at(seconds),
size: kind === "sse_event" ? (meta?.raw?.length ?? payload.length) : payload.length,
storedSize: payload.length,
truncated: false,
compressed: false,
error: null,
meta: meta ?? {},
preview:
binary || kind === "grpc_trailers"
? null
: kind === "websocket_close"
? (meta?.closeReason ?? null)
: text.slice(0, 200) || null,
} satisfies FlowMessage;
});
return { messages, payloads: rows.map((r) => r[3]) };
}
const json = (v: unknown) => encode(JSON.stringify(v));
const ws = build("fl_ws", [
[0.09, "server", "websocket_text", json({ op: 10, d: { heartbeat_interval: 41250 } })],
[0.11, "client", "websocket_text", json({ op: 2, d: { token: "mfa.••••", intents: 3276799 } })],
[
0.41,
"server",
"websocket_text",
json({ t: "READY", s: 1, op: 0, d: { v: 10, session_id: "5f1c…" } }),
],
[
1.02,
"server",
"websocket_binary",
Uint8Array.from([0x78, 0x9c, 0xab, 0x56, 0xca, 0x2f, 0x50, 0xb2, 0x32, 0xd4, 0x51, 0x02, 0x00]),
],
[41.25, "client", "websocket_text", json({ op: 1, d: 1 })],
[41.31, "server", "websocket_text", json({ op: 11 })],
[
43.3,
"server",
"websocket_text",
json({
t: "MESSAGE_CREATE",
s: 5,
op: 0,
d: { content: "shipping the proxy beta tonight?", author: { username: "mara" } },
}),
],
[60.0, "server", "websocket_ping", new Uint8Array()],
[60.0, "client", "websocket_pong", new Uint8Array()],
[82.5, "client", "websocket_text", json({ op: 1, d: 5 })],
[82.56, "server", "websocket_text", json({ op: 11 })],
[
128.3,
"client",
"websocket_close",
Uint8Array.from([0x03, 0xe8, 0x62, 0x79, 0x65]),
{ closeCode: 1000, closeReason: "bye" },
],
[128.4, "server", "websocket_close", Uint8Array.from([0x03, 0xe8]), { closeCode: 1000 }],
]);
const sseEvents: [string, unknown][] = [
[
"message_start",
{
type: "message_start",
message: { id: "msg_01HqX", model: "claude-opus-5-5", usage: { input_tokens: 18204 } },
},
],
[
"content_block_start",
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
],
["ping", { type: "ping" }],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: "The 402 comes from" },
},
],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: " Stripe: the card on" },
},
],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: " file was declined with" },
},
],
[
"content_block_delta",
{
type: "content_block_delta",
index: 0,
delta: { type: "text_delta", text: " insufficient_funds." },
},
],
["content_block_stop", { type: "content_block_stop", index: 0 }],
[
"message_delta",
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 312 } },
],
["message_stop", { type: "message_stop" }],
];
function sse(flowId: string, count: number) {
return build(
flowId,
sseEvents.slice(0, count).map(([event, data], i) => {
const payload = json(data);
const raw = `event: ${event}\ndata: ${new TextDecoder().decode(payload)}\n\n`;
return [0.8 + i * (i < 3 ? 0.05 : 0.18), "server", "sse_event", payload, { event, raw }];
}),
);
}
const sseFlow: Flow = {
...flowBase,
method: "POST",
url: "https://api.anthropic.com/v1/messages",
clientHttpVersion: "HTTP/2",
upstreamHttpVersion: "HTTP/2",
status: 200,
contentType: "text/event-stream; charset=utf-8",
responseHeaders: [{ name: "content-type", value: "text/event-stream; charset=utf-8" }],
clientName: "claude",
clientBundleId: null,
clientPath: "/opt/homebrew/bin/claude",
streamKind: "sse",
elapsedMs: 2_610,
};
const sseDone = sse("fl_sse_done", sseEvents.length);
const sseOpen = sse("fl_sse_open", sseEvents.length);
// A string in field 1, as a server-streaming call's replies
function proto(text: string, n?: number): Uint8Array {
const bytes = encode(text);
const out = [0x0a, bytes.length, ...bytes];
if (n != null) out.push(0x10, n);
return Uint8Array.from(out);
}
const grpcReplies = ["us-east-1a ok", "us-east-1b ok", "us-east-1c degraded", "eu-west-1a ok"];
const grpc = build("fl_grpc", [
[0.02, "client", "grpc_message", proto("prod")],
...grpcReplies.map(
(r, i) =>
[0.31 + i * 0.42, "server", "grpc_message", proto(r, i + 1)] as [
number,
"server",
"grpc_message",
Uint8Array,
],
),
[2.1, "server", "grpc_trailers", encode("grpc-status: 0\r\n"), { grpcStatus: 0 }],
]);
const schema = {
id: "gs_1",
createdAt: "2026-11-05T20:00:00",
updatedAt: "2026-11-05T20:00:00",
hostPattern: "health.internal",
source: "reflection" as const,
protoPaths: [],
services: ["ops.Health"],
};
const grpcDecoded: StreamFixture["decoded"] = Object.fromEntries(
[["prod"], ...grpcReplies.map((r, i) => [r, i + 1])].map(([text, n], seq) => [
seq,
{
decoded: {
json: JSON.stringify(
seq === 0
? { environment: text }
: { zone: String(text).split(" ")[0], state: String(text).split(" ")[1], sequence: n },
null,
2,
),
messageType: seq === 0 ? "ops.WatchRequest" : "ops.ZoneHealth",
schema,
note: null,
},
schemaless: {
json: JSON.stringify(
[
{ field: 1, wireType: "len", string: text },
...(n == null ? [] : [{ field: 2, wireType: "varint", value: n }]),
],
null,
2,
),
messageType: null,
schema: null,
note: "Decoded without a schema: field names and types are guesses",
},
},
]),
);
export const streamFixtures: StreamFixture[] = [
{
label: "WebSocket",
flow: { ...flowBase, id: "fl_ws", messageCount: ws.messages.length },
...ws,
},
{
label: "SSE, open",
flow: { ...sseFlow, id: "fl_sse_open", elapsedMs: null, messageCount: 6 },
messages: sseOpen.messages.slice(0, 6),
payloads: sseOpen.payloads,
later: sseOpen.messages.slice(6).map((message) => ({
message,
payload: sseOpen.payloads[message.seq] ?? new Uint8Array(),
})),
},
{
label: "SSE, done",
flow: { ...sseFlow, id: "fl_sse_done", messageCount: sseDone.messages.length },
...sseDone,
},
{
label: "gRPC stream",
flow: {
...flowBase,
id: "fl_grpc",
method: "POST",
url: "https://health.internal/ops.Health/Watch",
clientHttpVersion: "HTTP/2",
upstreamHttpVersion: "HTTP/2",
status: 200,
contentType: "application/grpc",
responseHeaders: [{ name: "content-type", value: "application/grpc" }],
clientName: "grpcurl",
clientPath: "/opt/homebrew/bin/grpcurl",
streamKind: "grpc",
grpcService: "ops.Health",
grpcMethod: "Watch",
grpcStatus: 0,
elapsedMs: 2_100,
messageCount: grpc.messages.length,
},
...grpc,
decoded: grpcDecoded,
},
];
function base64(bytes: Uint8Array): string {
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary);
}
/** The fixture's messages as the engine would serve them, the later ones arriving every 900 ms */
export function fixtureSource(fixture: StreamFixture): MessageSource {
const messages = [...fixture.messages];
const listeners = new Set<(m: FlowMessage) => void>();
const later = [...(fixture.later ?? [])];
if (later.length > 0) {
const timer = setInterval(() => {
const next = later.shift();
if (next == null) return clearInterval(timer);
messages.push(next.message);
for (const l of listeners) l(next.message);
}, 900);
}
return {
list: async (_flowId, afterSeq, limit) => {
const after = messages.filter((m) => afterSeq == null || m.seq > afterSeq);
return { messages: after.slice(0, limit), total: messages.length };
},
subscribe: (callback) => {
listeners.add(callback);
return () => listeners.delete(callback);
},
payload: async (_flowId, seq) => ({
data: base64(fixture.payloads[seq] ?? new Uint8Array()),
truncated: false,
}),
decodeGrpc: async (_flowId, seq, schemaless) => {
const entry = fixture.decoded?.[seq];
if (entry == null) throw new Error(`Message ${seq} is not a gRPC message`);
return schemaless ? entry.schemaless : entry.decoded;
},
};
}
+45
View File
@@ -0,0 +1,45 @@
import { useQueryClient } from "@tanstack/react-query";
import type {
DecryptList,
DecryptListChangedPayload,
DecryptListEntry,
} from "@yaakapp-internal/proxy-lib";
import { useCallback } from "react";
import { useShowToast } from "../lib/toast";
import { useRpcEvent } from "./useRpcEvent";
import { useRpcMutation } from "./useRpcMutation";
import { useRpcQuery } from "./useRpcQuery";
const KEY = ["get_decrypt_list", {}];
const EMPTY: DecryptListEntry[] = [];
/**
* The decrypt list's entries, empty until read. Kept current as this process changes it, from
* the app or through its control API.
*/
export function useDecryptList(): DecryptListEntry[] {
const queryClient = useQueryClient();
const onChanged = useCallback(
(payload: DecryptListChangedPayload) =>
queryClient.setQueryData<DecryptList>(KEY, payload.list),
[queryClient],
);
useRpcEvent("decrypt_list_changed", onChanged);
return useRpcQuery("get_decrypt_list", {}).data?.entries ?? EMPTY;
}
/**
* Adds and removes entries, `edit_decrypt_list` applying them to the list as it is when they
* land, so two changes made in quick succession both stick. Everything that reads the list
* then reads it again. A failure, such as an entry that does not parse, is a toast.
*/
export function useEditDecryptList() {
const queryClient = useQueryClient();
const showToast = useShowToast();
return useRpcMutation("edit_decrypt_list", {
// Read again rather than taken from the answer, which can land after a newer change's
// event and would put the older list back.
onSuccess: () => queryClient.invalidateQueries({ queryKey: KEY }),
onError: (e) => showToast({ id: "decrypt-list", color: "danger", message: e.message }),
});
}
+140
View File
@@ -0,0 +1,140 @@
import type {
DecodedGrpcMessage,
FlowMessage,
GetMessagePayloadResponse,
ListMessagesResponse,
} from "@yaakapp-internal/proxy-lib";
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { mergeMessages } from "../lib/messages";
import { listen, rpc } from "../lib/rpc";
/** Where a flow's messages come from: the engine, or fixtures in the harness */
export interface MessageSource {
list: (
flowId: string,
afterSeq: number | undefined,
limit: number,
) => Promise<ListMessagesResponse>;
/** Calls back with each message as it is written. Returns an unsubscribe function */
subscribe: (callback: (message: FlowMessage) => void) => () => void;
payload: (flowId: string, seq: number) => Promise<GetMessagePayloadResponse>;
decodeGrpc: (flowId: string, seq: number, schemaless: boolean) => Promise<DecodedGrpcMessage>;
}
export const engineMessageSource: MessageSource = {
list: (flowId, afterSeq, limit) => rpc("list_messages", { flowId, afterSeq, limit }),
subscribe: (callback) => listen("message_write", ({ message }) => callback(message)),
payload: (flowId, seq) => rpc("get_message_payload", { flowId, seq }),
decodeGrpc: (flowId, seq, schemaless) => rpc("decode_grpc_message", { flowId, seq, schemaless }),
};
/** Where the Messages tab reads from: the engine, unless the harness provides fixtures */
export const MessageSourceContext = createContext<MessageSource>(engineMessageSource);
export function useMessageSource(): MessageSource {
return useContext(MessageSourceContext);
}
/** Messages read in one call at most, while catching up */
const PAGE = 500;
interface State {
flowId: string;
messages: FlowMessage[];
loading: boolean;
error: string | null;
}
/**
* A flow's messages, kept up to date while it streams: read in pages after the last one held,
* and added as each is written. A message that does not follow on from the last one held (one
* written while a page loaded) reads the pages after it instead.
*/
export function useFlowMessages(flowId: string, source: MessageSource, messageCount: number) {
// Reads what's after the last message held, for a count that says there's more
const readMore = useRef<(() => void) | null>(null);
const [state, setState] = useState<State>({
flowId,
messages: [],
loading: true,
error: null,
});
useEffect(() => {
let cancelled = false;
let messages: FlowMessage[] = [];
let reading = false;
let readAgain = false;
let frame: number | null = null;
const publish = (loading: boolean, error: string | null = null) => {
if (cancelled) return;
if (frame != null) cancelAnimationFrame(frame);
frame = null;
setState({ flowId, messages, loading, error });
};
// A chatty stream is drawn at most once a frame
const publishSoon = () => {
if (frame != null || cancelled) return;
frame = requestAnimationFrame(() => {
frame = null;
if (!cancelled) setState({ flowId, messages, loading: false, error: null });
});
};
const readAfter = async () => {
if (reading) {
readAgain = true;
return;
}
reading = true;
try {
for (;;) {
readAgain = false;
const last = messages[messages.length - 1];
const page = await source.list(flowId, last?.seq, PAGE);
if (cancelled) return;
messages = mergeMessages(messages, page.messages);
// Shown as each page lands, so a stream that never pauses still shows what's read
if (page.messages.length < PAGE && !readAgain) break;
publishSoon();
}
publish(false);
} catch (e) {
publish(false, String(e));
} finally {
reading = false;
}
};
setState({ flowId, messages: [], loading: true, error: null });
readMore.current = () => void readAfter();
void readAfter();
const unsubscribe = source.subscribe((message) => {
if (message.flowId !== flowId) return;
const last = messages[messages.length - 1];
const next = last == null ? 0 : last.seq + 1;
if (!reading && message.seq === next) {
messages = [...messages, message];
publishSoon();
} else if (last == null || message.seq > last.seq) {
void readAfter();
}
});
return () => {
cancelled = true;
if (frame != null) cancelAnimationFrame(frame);
unsubscribe();
};
}, [flowId, source]);
// A message written before the subscription took hold is in neither the first page nor its
// events; the flow's count, written after its messages, says it's there to read.
const held = state.flowId === flowId ? state.messages.length : 0;
useEffect(() => {
if (messageCount > held) readMore.current?.();
}, [held, messageCount]);
// Another flow's, until the effect has started over for this one
return state.flowId === flowId ? state : { flowId, messages: [], loading: true, error: null };
}
+4 -2
View File
@@ -3,16 +3,18 @@ import type { RpcSchema } from "@yaakapp-internal/proxy-lib";
import { minPromiseMillis } from "@yaakapp-internal/ui";
import type { Req, Res } from "../lib/rpc";
import { rpc } from "../lib/rpc";
import { announceEngineChange } from "../lib/windowSync";
/**
* React Query mutation wrapper for RPC commands.
* React Query mutation wrapper for RPC commands. The app's other windows hear of each one once
* it settles, and read again what it may have changed.
*/
export function useRpcMutation<K extends keyof RpcSchema>(
cmd: K,
opts?: Omit<UseMutationOptions<Res<K>, Error, Req<K>>, "mutationFn">,
) {
return useMutation<Res<K>, Error, Req<K>>({
mutationFn: (payload) => minPromiseMillis(rpc(cmd, payload)),
mutationFn: (payload) => minPromiseMillis(rpc(cmd, payload)).finally(announceEngineChange),
...opts,
});
}
+3
View File
@@ -24,5 +24,8 @@
<script type="module" src="/font-size.ts"></script>
<script type="module" src="/lib/theme.ts"></script>
<script type="module" src="/main.tsx"></script>
<div id="cm-portal" class="cm-portal"></div>
<div id="react-portal"></div>
<div id="radix-portal" class="cm-portal"></div>
</body>
</html>
+50 -1
View File
@@ -1,7 +1,8 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
import type { SplitLayoutLayout } from "@yaakapp-internal/ui";
import type { ResponseViewMode, SplitLayoutLayout } from "@yaakapp-internal/ui";
import { atom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { currentPlace, EMPTY_PLACE, type PlaceStack, stackOf, updatePlace } from "./places";
/** The sidebar's tree, whose selection narrows the list */
export const SIDEBAR_TREE_ID = "proxy-sidebar";
@@ -11,6 +12,46 @@ export const selectedFlowAtom = atom<Flow | null>(null);
export const selectedFlowIdAtom = atom((get) => get(selectedFlowAtom)?.id ?? null);
/** The places Back and Forward walk, the current one what the window shows */
export const placeStackAtom = atom<PlaceStack>(stackOf(EMPTY_PLACE));
export const placeAtom = atom((get) => currentPlace(get(placeStackAtom)));
/** The filter the list, its counts and the sidebar follow, changed only by applying one */
export const appliedFilterAtom = atom((get) => get(placeAtom).filter);
/** The flows selected at the current place */
export const placeSelectionAtom = atom((get) => get(placeAtom).selection);
/** The tab each half of the card has open at the current place */
export const placeTabsAtom = atom((get) => get(placeAtom).tabs);
export const canGoBackAtom = atom((get) => get(placeStackAtom).index > 0);
export const canGoForwardAtom = atom((get) => {
const stack = get(placeStackAtom);
return stack.index < stack.places.length - 1;
});
/**
* Lets go of flows that are gone, deleted or cleared: the detail empties and the current place
* no longer selects them, without a place of its own. All of them without `ids`.
*/
export const dropSelectedAtom = atom(null, (get, set, ids?: ReadonlySet<string>) => {
const selected = get(selectedFlowAtom);
if (selected != null && (ids == null || ids.has(selected.id))) set(selectedFlowAtom, null);
set(placeStackAtom, (stack) => {
const place = currentPlace(stack);
const kept = [...place.selection].filter((id) => ids != null && !ids.has(id));
if (kept.length === place.selection.size) return stack;
const tabs = kept.length === 0 ? {} : place.tabs;
return updatePlace(stack, { ...place, selection: new Set(kept), tabs });
});
});
/** A flow to scroll into view once the list has it, as going back to a place asks */
export const revealFlowAtom = atom<{ id: string } | null>(null);
/** The list follows new traffic, rather than being held where it was scrolled or selected */
export const followingAtom = atom(true);
@@ -22,3 +63,11 @@ export const helperDialogOpenAtom = atom(false);
/** Stacked by default; the header's toggle switches to side by side */
export const flowLayoutAtom = atomWithStorage<SplitLayoutLayout>("flow_layout", "vertical");
/** Bodies show formatted or raw, one choice for both halves of every flow */
export const bodyViewModeAtom = atomWithStorage<ResponseViewMode>(
"body_view_mode",
"pretty",
undefined,
{ getOnInit: true },
);
+18
View File
@@ -6,7 +6,9 @@ import {
bodyFileName,
bodyImageType,
bytesToText,
emptyBodyText,
flowBodyQueryOptions,
viewerBody,
viewerText,
} from "./body";
import { rpc } from "./rpc";
@@ -225,3 +227,19 @@ describe("flowBodyQueryOptions", () => {
client.clear();
});
});
describe("a body that isn't there", () => {
test("a WebSocket's note reaches the viewer, which points at its messages", () => {
const note = "A WebSocket has no body after its 101 response. Its frames are its messages.";
const body = viewerBody({ data: "", truncated: false, storedSize: 0, note });
expect(body.note).toBe(note);
expect(emptyBodyText("response", body.note)).toBe("No body. See Messages.");
});
test("any other empty body says so as before", () => {
const body = viewerBody({ data: "", truncated: false, storedSize: 0 });
expect(body.note).toBeNull();
expect(emptyBodyText("response", body.note)).toBe("Empty");
expect(emptyBodyText("request", body.note)).toBe("No request body");
});
});
+28 -10
View File
@@ -4,7 +4,12 @@ import {
decodeBodyText,
strictUtf8Text,
} from "@yaakapp-internal/lib/decodeBodyText";
import type { FilterLanguage, Flow, FlowBody } from "@yaakapp-internal/proxy-lib";
import type {
FilterLanguage,
Flow,
FlowBody,
GetFlowBodyResponse,
} from "@yaakapp-internal/proxy-lib";
import type { CodeEditorProps } from "@yaakapp-internal/ui/editor";
import vkBeautify from "vkbeautify";
import { rpc } from "./rpc";
@@ -13,20 +18,33 @@ import { rpc } from "./rpc";
export function flowBodyQueryOptions(flow: Flow, which: FlowBody) {
return queryOptions({
queryKey: ["get_flow_body", flow.id, which, flow.updatedAt],
queryFn: async () => {
const res = await rpc("get_flow_body", { flowId: flow.id, which });
return {
bytes: base64ToBytes(res.data),
truncated: res.truncated,
storedSize: res.storedSize,
decodeError: res.decodeError ?? null,
};
},
queryFn: async () => viewerBody(await rpc("get_flow_body", { flowId: flow.id, which })),
// Reading a stored body fails the same way every time, so the error shows at once.
retry: false,
// A stream's body changes with each message, each a new key: dropped once unwatched, so a
// long stream left selected doesn't hold a copy per message
...(flow.streamKind == null ? {} : { gcTime: 0 }),
});
}
/** The body RPC's answer as the viewer reads it, with what to know of it beyond its bytes */
export function viewerBody(res: GetFlowBodyResponse) {
return {
bytes: base64ToBytes(res.data),
truncated: res.truncated,
storedSize: res.storedSize,
decodeError: res.decodeError ?? null,
/** Why there is no body, as a WebSocket has none after its 101 */
note: res.note ?? null,
};
}
/** What an empty body's pane says: a WebSocket's points at its messages */
export function emptyBodyText(which: FlowBody, note: string | null): string {
if (note != null) return "No body. See Messages.";
return which === "request" ? "No request body" : "Empty";
}
export function base64ToBytes(data: string): Uint8Array<ArrayBuffer> {
const binary = atob(data);
const bytes = new Uint8Array(binary.length);
+56
View File
@@ -0,0 +1,56 @@
import { createStore } from "jotai";
import { beforeEach, describe, expect, test, vi } from "vite-plus/test";
import { clearFlowsAction, confirmClearFlowsAtom } from "./clearFlows";
describe("clearFlowsAction", () => {
test("asks first while the preference is on", () => {
expect(clearFlowsAction({ total: 3, locked: false, confirm: true })).toBe("confirm");
});
test("clears at once once asking is turned off", () => {
expect(clearFlowsAction({ total: 3, locked: false, confirm: false })).toBe("clear");
});
test("does nothing with none to clear or traffic locked, whatever the preference", () => {
for (const confirm of [true, false]) {
expect(clearFlowsAction({ total: 0, locked: false, confirm })).toBe("disabled");
expect(clearFlowsAction({ total: 3, locked: true, confirm })).toBe("disabled");
}
});
});
/** The preference as a new window reads it, once something shows it */
function mounted() {
const store = createStore();
const unsub = store.sub(confirmClearFlowsAtom, () => {});
const value = store.get(confirmClearFlowsAtom);
unsub();
return value;
}
describe("confirmClearFlowsAtom", () => {
let saved: Map<string, string>;
beforeEach(() => {
saved = new Map();
vi.stubGlobal("localStorage", {
getItem: (k: string) => saved.get(k) ?? null,
setItem: (k: string, v: string) => void saved.set(k, v),
removeItem: (k: string) => void saved.delete(k),
});
});
test("is on by default", () => {
expect(createStore().get(confirmClearFlowsAtom)).toBe(true);
});
test("keeps Don't ask again for later launches, until Settings turns it back on", () => {
createStore().set(confirmClearFlowsAtom, false);
expect(saved.get("confirm_clear_flows")).toBe("false");
expect(mounted()).toBe(false);
createStore().set(confirmClearFlowsAtom, true);
expect(saved.get("confirm_clear_flows")).toBe("true");
expect(mounted()).toBe(true);
});
});
+32
View File
@@ -0,0 +1,32 @@
import { atomWithStorage, createJSONStorage } from "jotai/utils";
/**
* Clearing traffic asks first, until "Don't ask again" is checked in its dialog. The switch in
* Settings turns the asking back on.
*/
export const confirmClearFlowsAtom = atomWithStorage<boolean>(
"confirm_clear_flows",
true,
// Read through globalThis so tests, which have no localStorage, can import this
createJSONStorage<boolean>(() => globalThis.localStorage),
{ getOnInit: true },
);
/** What Clear does now: nothing, ask first, or clear at once */
export type ClearFlowsAction = "disabled" | "confirm" | "clear";
export function clearFlowsAction({
total,
locked,
confirm,
}: {
/** Flows there are to clear */
total: number;
/** Captured traffic is locked, so none of it can be read */
locked: boolean;
/** The saved preference to ask before clearing */
confirm: boolean;
}): ClearFlowsAction {
if (locked || total === 0) return "disabled";
return confirm ? "confirm" : "clear";
}
+575
View File
@@ -0,0 +1,575 @@
import type { Flow, FlowSortKey } from "@yaakapp-internal/proxy-lib";
import { describe, expect, test } from "vite-plus/test";
import customSortFixture from "../../../crates-proxy/yaak-proxy-lib/tests/fixtures/custom_column_sort.json";
import {
addCustomColumn,
addSortKey,
allColumns,
cellFilterTerm,
columnShifts,
type ColumnPrefs,
customPath,
customPathProblem,
customValue,
defaultColumnPrefs,
dropBoundary,
fieldReference,
fieldReferenceChanges,
gridTemplate,
gridWidth,
hideOtherColumns,
moveColumn,
moveColumnBy,
nextSort,
operationOf,
parseColumnPrefs,
removeCustomColumn,
resetOrder,
resetWidth,
resetWidths,
resizeColumn,
showOperationFor,
shownColumns,
sortFlows,
toggleColumn,
toggleSortKey,
urlParts,
} from "./columns";
function flow(number: number, extra: Partial<Flow> = {}): Flow {
return {
id: `fl_${String(number).padStart(3, "0")}`,
number,
startedAt: `2026-11-09T12:00:${String(number).padStart(2, "0")}`,
url: "https://example.com/",
method: "GET",
status: 200,
error: null,
requestSize: 0,
responseSize: 0,
elapsedMs: null,
elapsedHeadersMs: null,
contentType: null,
clientName: null,
clientBundleId: null,
clientPath: null,
clientCwd: null,
clientHttpVersion: "HTTP/1.1",
upstreamHttpVersion: null,
upstreamTlsVersion: null,
remoteAddr: null,
requestHeaders: [],
responseHeaders: [],
grpcService: null,
grpcMethod: null,
graphqlOperation: null,
tunnelled: false,
...extra,
} as Flow;
}
const ids = (prefs: ColumnPrefs) => shownColumns(prefs).map((c) => c.id);
describe("shownColumns", () => {
test("shows every visible column, Query after Path", () => {
expect(ids(defaultColumnPrefs)).toEqual([
"number",
"app",
"method",
"host",
"path",
"query",
"status",
"type",
"size",
"time",
]);
});
test("follows the picker, Path included, but keeps the last column", () => {
let prefs = toggleColumn(defaultColumnPrefs, "remote");
prefs = toggleColumn(prefs, "type");
prefs = toggleColumn(prefs, "path");
expect(ids(prefs)).toContain("remote");
expect(ids(prefs)).not.toContain("type");
expect(ids(prefs)).not.toContain("path");
const alone = hideOtherColumns(defaultColumnPrefs, "host");
expect(ids(alone)).toEqual(["host"]);
expect(toggleColumn(alone, "host")).toBe(alone);
// Where App has nothing to show, the last other column is the last one.
const withApp = hideOtherColumns(defaultColumnPrefs, "app");
const both = toggleColumn(withApp, "host");
expect(toggleColumn(both, "host", ["app"])).toBe(both);
expect(ids(both)).toEqual(["app", "host"]);
expect(shownColumns(both, ["app"]).map((c) => c.id)).toEqual(["host"]);
});
test("lays out every column at a fixed width", () => {
let prefs = resizeColumn(defaultColumnPrefs, "host", 240.4);
prefs = resizeColumn(prefs, "path", 500);
const columns = shownColumns(prefs);
const pad = (w: number) => `calc(${w}px + 0.75rem)`;
expect(gridTemplate(columns)).toBe(
["24px", ...[46, 20, 50, 240, 500, 120, 46, 50, 72, 64].map(pad)].join(" "),
);
expect(gridWidth(columns)).toBe("calc(1232px + 10 * 0.75rem)");
});
});
describe("column preferences", () => {
test("persist through storage and drop what no longer applies", () => {
let prefs = resizeColumn(defaultColumnPrefs, "host", 10);
prefs = toggleColumn(prefs, "number");
prefs = addCustomColumn(prefs, "header.x-cache");
prefs = { ...prefs, sort: [{ column: "status", descending: true }] };
const stored = JSON.parse(JSON.stringify(prefs));
expect(parseColumnPrefs(stored)).toEqual({
visible: { number: false, "field:header.x-cache": true },
widths: { host: 60 },
custom: ["field:header.x-cache"],
order: [],
sort: [{ column: "status", descending: true }],
});
expect(
parseColumnPrefs({
visible: { gone: true, size: "yes" },
widths: { time: -1, size: 90 },
custom: ["field:nope.x", 3, "field:query.page"],
sort: [
{ column: "gone", descending: true },
{ column: "host" },
{ column: "time", descending: false },
],
}),
).toEqual({
visible: {},
widths: { size: 90 },
custom: ["field:query.page"],
order: [],
sort: [{ column: "time", descending: false }],
});
expect(parseColumnPrefs(null)).toEqual(defaultColumnPrefs);
expect(resetWidths(prefs).widths).toEqual({});
});
test("a double-click resets one column's width", () => {
let prefs = resizeColumn(defaultColumnPrefs, "host", 300);
prefs = resizeColumn(prefs, "path", 400);
expect(resetWidth(prefs, "path").widths).toEqual({ host: 300 });
});
test("custom columns are added at the end and removed with their settings", () => {
let prefs = addCustomColumn(defaultColumnPrefs, "res.header.x-cache");
prefs = resizeColumn(prefs, "field:res.header.x-cache", 200);
expect(ids(prefs).at(-1)).toBe("field:res.header.x-cache");
prefs = removeCustomColumn(prefs, "field:res.header.x-cache");
expect(prefs).toEqual(defaultColumnPrefs);
});
test("a custom column's sort persists with it and goes when it does", () => {
let prefs = addCustomColumn(defaultColumnPrefs, "header.x-cache");
const sort: FlowSortKey[] = [
{ column: "field:header.x-cache", descending: true },
{ column: "status", descending: false },
];
prefs = { ...prefs, sort };
expect(parseColumnPrefs(JSON.parse(JSON.stringify(prefs))).sort).toEqual(sort);
// A key for a column that is no longer there is dropped
expect(parseColumnPrefs({ ...prefs, custom: [] }).sort).toEqual([sort[1]]);
expect(removeCustomColumn(prefs, "field:header.x-cache").sort).toEqual([sort[1]]);
});
test("Operation shows itself once, unless the person set it", () => {
const grpc = flow(1, { grpcService: "pkg.Greeter", grpcMethod: "SayHello" });
const anonymous = flow(2, { graphqlOperation: "" });
expect(showOperationFor(defaultColumnPrefs, [flow(3), anonymous])).toBe(defaultColumnPrefs);
expect(showOperationFor(defaultColumnPrefs, [grpc]).visible.operation).toBe(true);
const hidden = { ...defaultColumnPrefs, visible: { operation: false } };
expect(showOperationFor(hidden, [grpc])).toBe(hidden);
});
});
describe("column order", () => {
const defaults = ids(defaultColumnPrefs);
test("a column moves to the boundary it was dropped at", () => {
expect(ids(moveColumn(defaultColumnPrefs, "status", 2))).toEqual([
"number",
"app",
"status",
"method",
"host",
"path",
"query",
"type",
"size",
"time",
]);
// Rightwards, before the column at the boundary
expect(ids(moveColumn(defaultColumnPrefs, "method", 5)).slice(2, 6)).toEqual([
"host",
"path",
"method",
"query",
]);
// To either end
expect(ids(moveColumn(defaultColumnPrefs, "time", 0))[0]).toBe("time");
expect(ids(moveColumn(defaultColumnPrefs, "number", defaults.length)).at(-1)).toBe("number");
// The picker lists them in the same order
const moved = moveColumn(defaultColumnPrefs, "time", 0);
expect(allColumns(moved)[0]?.id).toBe("time");
});
test("a drop where the column already is changes nothing", () => {
expect(moveColumn(defaultColumnPrefs, "host", 3)).toBe(defaultColumnPrefs);
expect(moveColumn(defaultColumnPrefs, "host", 4)).toBe(defaultColumnPrefs);
expect(moveColumn(defaultColumnPrefs, "host", -1)).toBe(defaultColumnPrefs);
expect(moveColumn(defaultColumnPrefs, "host", defaults.length + 1)).toBe(defaultColumnPrefs);
// A hidden column has no place among those shown
expect(moveColumn(defaultColumnPrefs, "latency", 0)).toBe(defaultColumnPrefs);
});
test("Move Left and Move Right go one place, and not past the ends", () => {
expect(ids(moveColumnBy(defaultColumnPrefs, "host", -1)).slice(2, 5)).toEqual([
"host",
"method",
"path",
]);
expect(ids(moveColumnBy(defaultColumnPrefs, "host", 1)).slice(3, 6)).toEqual([
"path",
"host",
"query",
]);
expect(moveColumnBy(defaultColumnPrefs, "number", -1)).toBe(defaultColumnPrefs);
expect(moveColumnBy(defaultColumnPrefs, "time", 1)).toBe(defaultColumnPrefs);
// Where App has nothing to show, Number is next to Method
expect(
shownColumns(moveColumnBy(defaultColumnPrefs, "method", -1, ["app"]), ["app"]).map(
(c) => c.id,
)[0],
).toBe("method");
});
test("a hidden column keeps its place and comes back to it", () => {
let prefs = moveColumn(defaultColumnPrefs, "time", 0);
prefs = toggleColumn(prefs, "status");
prefs = moveColumn(prefs, "host", 0);
expect(ids(prefs)).not.toContain("status");
prefs = toggleColumn(prefs, "status");
expect(ids(prefs)).toEqual([
"host",
"time",
"number",
"app",
"method",
"path",
"query",
"status",
"type",
"size",
]);
});
test("never reordered, a built-in column turned on takes its default place", () => {
// Request Size's default place is before Size
const prefs = toggleColumn(defaultColumnPrefs, "requestSize");
expect(prefs.order).toEqual([]);
expect(ids(prefs).slice(-4)).toEqual(["type", "requestSize", "size", "time"]);
// Among the built-in ones, so a custom column stays at the end
const custom = addCustomColumn(defaultColumnPrefs, "header.x-cache");
expect(ids(custom).at(-1)).toBe("field:header.x-cache");
const both = toggleColumn(custom, "requestSize");
expect(both.order).toEqual([]);
expect(ids(both).slice(-4)).toEqual(["requestSize", "size", "time", "field:header.x-cache"]);
});
test("once reordered, a column turned on goes at the end, unless it had a place", () => {
let prefs = moveColumn(defaultColumnPrefs, "time", 0);
prefs = toggleColumn(prefs, "requestSize");
expect(ids(prefs).at(-1)).toBe("requestSize");
// Moved, hidden and shown again, it goes back where it was moved to
const before = ids(prefs).indexOf("size");
prefs = moveColumn(prefs, "requestSize", before);
prefs = toggleColumn(toggleColumn(prefs, "requestSize"), "requestSize");
expect(ids(prefs).slice(-3)).toEqual(["type", "requestSize", "size"]);
// A custom column added goes at the end too
expect(ids(addCustomColumn(prefs, "query.page")).at(-1)).toBe("field:query.page");
});
test("a custom column is added at the end and leaves the order when removed", () => {
const moved = moveColumn(defaultColumnPrefs, "size", 0);
let prefs = addCustomColumn(moved, "header.x-cache");
expect(ids(prefs).at(-1)).toBe("field:header.x-cache");
prefs = moveColumn(prefs, "field:header.x-cache", 1);
expect(ids(prefs).slice(0, 2)).toEqual(["size", "field:header.x-cache"]);
// Hidden and added again, it keeps its place
prefs = addCustomColumn(toggleColumn(prefs, "field:header.x-cache"), "header.x-cache");
expect(ids(prefs)[1]).toBe("field:header.x-cache");
prefs = removeCustomColumn(prefs, "field:header.x-cache");
expect(prefs.order).not.toContain("field:header.x-cache");
expect(ids(prefs)).toEqual(ids(moved));
// Added again, it starts over at the end
expect(ids(addCustomColumn(prefs, "header.x-cache")).at(-1)).toBe("field:header.x-cache");
});
test("the order persists, and columns it doesn't list follow it in their default order", () => {
let prefs = addCustomColumn(defaultColumnPrefs, "query.page");
prefs = moveColumn(prefs, "field:query.page", 0);
expect(parseColumnPrefs(JSON.parse(JSON.stringify(prefs))).order).toEqual(prefs.order);
const parsed = parseColumnPrefs({
custom: ["field:query.page"],
order: ["time", "gone", 3, "time", "field:header.x-gone", "field:query.page", "host"],
});
expect(parsed.order).toEqual(["time", "field:query.page", "host"]);
expect(ids(parsed)).toEqual([
"time",
"field:query.page",
"host",
"number",
"app",
"method",
"path",
"query",
"status",
"type",
"size",
]);
expect(parseColumnPrefs({ order: "time" }).order).toEqual([]);
});
test("a drag's target is the boundary nearest the pointer, null in its own slot", () => {
// Four columns 100px wide from x 24, after the mark column; the third is dragged
const cells = [24, 124, 224, 324].map((left) => ({ left, right: left + 100 }));
const at = (x: number) => dropBoundary(x, cells, 2);
// Over the mark column or the first's left half: the first boundary
expect(at(5)).toBe(0);
expect(at(60)).toBe(0);
expect(at(80)).toBe(1);
// The left neighbour's near half, its own column, the right neighbour's near half: staying
expect(at(190)).toBeNull();
expect(at(250)).toBeNull();
expect(at(290)).toBeNull();
expect(at(350)).toBeNull();
// Past the right neighbour's middle, and past the end
expect(at(380)).toBe(4);
expect(at(900)).toBe(4);
// The last column dragged to the end stays
expect(dropBoundary(900, cells, 3)).toBeNull();
});
test("the columns a drag passes slide by its width to make room", () => {
// Five columns; the second, 80px wide, is dragged
expect(columnShifts(5, 1, 80, null)).toEqual([0, 0, 0, 0, 0]);
// Right, to before the fifth: the third and fourth slide left
expect(columnShifts(5, 1, 80, 4)).toEqual([0, 0, -80, -80, 0]);
// Right, to the end: all after it slide left
expect(columnShifts(5, 1, 80, 5)).toEqual([0, 0, -80, -80, -80]);
// Left, to the start: the first slides right
expect(columnShifts(5, 1, 80, 0)).toEqual([80, 0, 0, 0, 0]);
// The fourth, dragged left to before the second: the second and third slide right
expect(columnShifts(5, 3, 60, 1)).toEqual([0, 60, 60, 0, 0]);
});
test("Reset Column Order puts every column back", () => {
let prefs = moveColumn(defaultColumnPrefs, "time", 0);
prefs = toggleColumn(prefs, "latency");
prefs = resetOrder(prefs);
expect(prefs.order).toEqual([]);
expect(ids(prefs)).toEqual([...defaults.slice(0, -1), "time", "latency"]);
});
});
describe("sorting", () => {
const one = (column: FlowSortKey["column"], descending: boolean) => [{ column, descending }];
test("a click sorts by a column alone, reverses it, then goes back to arrival order", () => {
expect(nextSort([], "size")).toEqual(one("size", true));
expect(nextSort([], "host")).toEqual(one("host", false));
expect(nextSort(one("host", false), "host")).toEqual(one("host", true));
expect(nextSort(one("host", true), "host")).toEqual([]);
expect(nextSort(one("size", true), "size")).toEqual(one("size", false));
expect(nextSort(one("size", false), "size")).toEqual([]);
// Another column, or a sort on several, starts over.
expect(nextSort(one("host", true), "size")).toEqual(one("size", true));
const two = [...one("host", false), ...one("size", true)];
expect(nextSort(two, "host")).toEqual(one("host", false));
});
test("Option-click adds a key ascending, reverses it, then takes it out", () => {
let sort = toggleSortKey(one("status", true), "host");
expect(sort).toEqual([...one("status", true), ...one("host", false)]);
sort = toggleSortKey(sort, "host");
expect(sort).toEqual([...one("status", true), ...one("host", true)]);
expect(toggleSortKey(sort, "host")).toEqual(one("status", true));
expect(addSortKey(sort, "status", false)).toEqual([
...one("status", false),
...one("host", true),
]);
expect(addSortKey([], "time", true)).toEqual(one("time", true));
});
test("a custom column sorts on click and Option-click as the others do", () => {
const cache = "field:header.x-cache";
expect(nextSort([], cache)).toEqual(one(cache, false));
expect(nextSort(one(cache, false), cache)).toEqual(one(cache, true));
expect(toggleSortKey(one("status", true), cache)).toEqual([
...one("status", true),
...one(cache, false),
]);
});
// Flows and the order each sort lists them in, shared with
// `a_custom_column_sorts_by_its_value_and_pages` in the lib's `flows.rs`, which checks the
// database lists them in the same order.
test("a custom column sorts as the database does", () => {
const fixture = customSortFixture as {
flows: Partial<Flow>[];
sorts: { sort: FlowSortKey[]; order: number[] }[];
};
const flows = fixture.flows.map((f, i) => flow(i, f));
for (const { sort, order } of fixture.sorts) {
expect(
sortFlows(flows, sort).map((f) => f.number),
JSON.stringify(sort),
).toEqual(order);
}
});
// The same flows and orders as `a_sort_on_several_columns_pages_in_its_order` in the lib's
// `flows.rs`, so the app places a flow where the database would.
const flows = [
flow(0, { url: "https://B.com/x", status: 200 }),
flow(1, { url: "https://a.com/y", status: 404 }),
flow(2, { url: "https://a.com/z", status: null }),
flow(3, { url: "https://c.com/", status: 200 }),
flow(4, { url: "https://a.com/", status: null, error: "boom" }),
flow(5, { url: "https://b.com/q", status: 200 }),
flow(6, { url: "https://A.com/", status: 404 }),
flow(7, { url: "https://c.com/", status: 200 }),
];
const numbers = (sort: FlowSortKey[]) => sortFlows(flows, sort).map((f) => f.number);
test("sorts on several columns as the database does", () => {
const status = [...one("status", true), ...one("host", false)];
expect(numbers(status)).toEqual([1, 6, 0, 5, 3, 7, 4, 2]);
const ascending = [...one("status", false), ...one("host", false)];
expect(numbers(ascending)).toEqual([2, 4, 0, 5, 3, 7, 1, 6]);
expect(numbers(one("query", true))).toEqual([0, 1, 2, 3, 4, 5, 6, 7]);
expect(sortFlows(flows, [])).toBe(flows);
});
test("sizes, times and the rest put flows without a value lowest", () => {
const a = flow(1, { responseSize: 10, elapsedMs: 5, requestSize: 3, elapsedHeadersMs: 2 });
const b = flow(2, { responseSize: 300, elapsedMs: null, requestSize: 0 });
const c = flow(3, { responseSize: 10, elapsedMs: 50, elapsedHeadersMs: 40 });
const d = flow(4, { error: "DNS lookup failed", status: null, responseSize: 99 });
const four = [a, b, c, d];
const by = (column: FlowSortKey["column"], descending: boolean) =>
sortFlows(four, one(column, descending)).map((f) => f.number);
expect(by("size", true)).toEqual([2, 1, 3, 4]);
expect(by("size", false)).toEqual([4, 1, 3, 2]);
expect(by("time", true)).toEqual([3, 1, 2, 4]);
expect(by("latency", true)).toEqual([3, 1, 2, 4]);
expect(by("requestSize", true)).toEqual([1, 2, 3, 4]);
expect(by("number", true)).toEqual([4, 3, 2, 1]);
// Failures sort below every status.
expect(by("status", true)).toEqual([1, 2, 3, 4]);
expect(by("status", false)).toEqual([4, 1, 2, 3]);
});
});
describe("values", () => {
test("splits URLs as the lib does", () => {
expect(urlParts("https://a.com:8080/v1/x?page=2&q=1#top")).toEqual({
authority: "a.com:8080",
path: "/v1/x",
query: "page=2&q=1",
});
expect(urlParts("https://a.com?x")).toEqual({ authority: "a.com", path: "", query: "x" });
expect(urlParts("bank.example.com:443")).toEqual({
authority: "bank.example.com:443",
path: "",
query: null,
});
});
test("reads a custom column's path from what was typed", () => {
expect(customPath("@header.X-Request-Id:")).toBe("header.x-request-id");
expect(customPath("query.page")).toBe("query.page");
expect(customPath(" res.header.x-cache ")).toBe("res.header.x-cache");
expect(customPath("@host")).toBeNull();
expect(customPath("header.")).toBeNull();
expect(customPath("header.a b")).toBeNull();
expect(customPath("query.filter[status]")).toBeNull();
});
test("says tersely why what was typed names no column", () => {
expect(customPathProblem("")).toBeNull();
expect(customPathProblem("@")).toBeNull();
expect(customPathProblem("@req.header.user-agent")).toBeNull();
expect(customPathProblem("@hea")).toBe("Incomplete");
expect(customPathProblem("@res.header")).toBe("Incomplete");
expect(customPathProblem("@header.")).toBe("Missing name");
expect(customPathProblem("@query.a b")).toBe("Invalid name");
expect(customPathProblem("@host")).toBe("Unknown field");
});
test("keeps the Add Column field a reference to a field", () => {
expect(fieldReference("")).toBe("");
expect(fieldReference("@")).toBe("@");
expect(fieldReference("h")).toBe("@h");
expect(fieldReference("header.x-cache")).toBe("@header.x-cache");
expect(fieldReference("@req.header.user-agent:")).toBe("@req.header.user-agent");
expect(fieldReference(" @@Header.X-Cache: ")).toBe("@Header.X-Cache");
expect(fieldReference(":")).toBe("");
expect(fieldReference("@:")).toBe("@");
expect(fieldReferenceChanges("@header.x")).toEqual([]);
expect(fieldReferenceChanges("query.page:")).toEqual([
{ from: 0, to: 0, insert: "@" },
{ from: 10, to: 11, insert: "" },
]);
});
test("a custom column shows the first value, the response's header before the request's", () => {
const f = flow(1, {
url: "https://a.com/?Page=2&page=3",
requestHeaders: [
{ name: "X-Cache", value: "req" },
{ name: "Accept", value: "a" },
{ name: "accept", value: "b" },
],
responseHeaders: [{ name: "x-cache", value: "HIT" }],
});
expect(customValue(f, "header.x-cache")).toBe("HIT");
expect(customValue(f, "req.header.x-cache")).toBe("req");
expect(customValue(f, "header.accept")).toBe("a");
expect(customValue(f, "query.page")).toBe("2");
expect(customValue(f, "query.nope")).toBeNull();
});
test("a cell's filter terms, where its column has a field to match", () => {
const f = flow(1, {
url: "https://api.stripe.com:443/v1/charges?x=1",
status: 404,
clientName: "Google Chrome",
contentType: "application/json; charset=utf-8",
responseHeaders: [{ name: "X-Cache", value: "HIT" }],
});
expect(cellFilterTerm(f, "host", false)).toBe("@host:api.stripe.com");
expect(cellFilterTerm(f, "status", true)).toBe("-@status:404");
expect(cellFilterTerm(f, "app", false)).toBe('@app:"Google Chrome"');
expect(cellFilterTerm(f, "path", false)).toBe("@path:/v1/charges");
expect(cellFilterTerm(f, "type", false)).toBe("@type:application/json");
expect(cellFilterTerm(f, "field:header.x-cache", false)).toBe("@header.x-cache:HIT");
for (const column of ["number", "size", "time", "query", "started"] as const) {
expect(cellFilterTerm(f, column, false)).toBeNull();
}
const grpc = flow(2, { grpcService: "pkg.Greeter", grpcMethod: "SayHello" });
expect(operationOf(grpc)).toBe("pkg.Greeter/SayHello");
expect(cellFilterTerm(grpc, "operation", true)).toBe(
"-(@grpc.service:pkg.Greeter @grpc.method:SayHello)",
);
const graphql = flow(3, { graphqlOperation: "GetUser" });
expect(cellFilterTerm(graphql, "operation", false)).toBe("@graphql.operation:GetUser");
});
});
+675
View File
@@ -0,0 +1,675 @@
import type { Flow, FlowSortKey, SortColumn } from "@yaakapp-internal/proxy-lib";
import { compareFlows } from "./flowWindow";
import { fieldTerm } from "./query";
import { sidebarPath } from "./search";
/** The columns the list has built in; each sorts by the `SortColumn` of the same name */
export type BuiltinColumnId = SortColumn;
/** A column of a header or query parameter the person added, by its field's path */
export type CustomColumnId = `field:${string}`;
export type ColumnId = BuiltinColumnId | CustomColumnId;
export interface ColumnDef {
id: ColumnId;
/** In the header and the picker */
label: string;
/** Pixels of content, at the default interface size; each cell adds `CELL_PADDING` */
width: number;
minWidth: number;
align: "left" | "right";
/** Shown until the person hides it */
defaultVisible: boolean;
/** The header or query parameter a custom column shows: `header.x-request-id` */
path?: string;
}
const builtin = (
id: BuiltinColumnId,
label: string,
width: number,
minWidth: number,
align: "left" | "right",
defaultVisible: boolean,
): ColumnDef => ({ id, label, width, minWidth, align, defaultVisible });
export const COLUMNS: ColumnDef[] = [
builtin("number", "#", 46, 30, "left", true),
builtin("app", "App", 20, 20, "left", true),
builtin("method", "Method", 50, 40, "left", true),
builtin("host", "Host", 190, 60, "left", true),
builtin("path", "Path", 300, 60, "left", true),
builtin("query", "Query", 120, 40, "left", true),
builtin("status", "Status", 46, 34, "left", true),
builtin("type", "Type", 50, 34, "left", true),
builtin("requestSize", "Request Size", 80, 44, "right", false),
builtin("size", "Size", 72, 44, "right", true),
builtin("time", "Time", 64, 44, "right", true),
builtin("latency", "Latency", 64, 44, "right", false),
builtin("started", "Started", 92, 60, "left", false),
builtin("remote", "Remote Address", 150, 60, "left", false),
builtin("version", "HTTP Version", 70, 44, "left", false),
builtin("tls", "TLS Version", 70, 34, "left", false),
builtin("operation", "Operation", 160, 60, "left", false),
];
const DEFS = new Map<ColumnId, ColumnDef>(COLUMNS.map((c) => [c.id, c]));
/** Map fields a custom column can show, as the query language names them */
const CUSTOM_MAPS = ["req.header.", "res.header.", "header.", "query."];
/** `header.x-request-id` from what was typed, `@header.X-Request-Id:` included, or null */
export function customPath(typed: string): string | null {
const path = typed.trim().replace(/^@/, "").replace(/:$/, "").trim();
const map = CUSTOM_MAPS.find((m) => path.toLowerCase().startsWith(m));
if (map == null) return null;
const key = path.slice(map.length);
// As a field path takes it, so the column's filter items make a term the search can run
if (!/^[A-Za-z0-9_-]+$/.test(key)) return null;
return map + key.toLowerCase();
}
/** Why what was typed names no custom column, in a few words; null when it does or is empty */
export function customPathProblem(typed: string): string | null {
if (customPath(typed) != null) return null;
const path = typed.trim().replace(/^@/, "").replace(/:$/, "").trim().toLowerCase();
if (path === "") return null;
const map = CUSTOM_MAPS.find((m) => path.startsWith(m));
if (map != null) return path === map ? "Missing name" : "Invalid name";
// On the way to a map: `@hea`, `@req.header`
if (CUSTOM_MAPS.some((m) => m.startsWith(path))) return "Incomplete";
return "Unknown field";
}
/**
* The edits that turn what the Add Column field holds into a reference to a field, `@` and its
* path: an `@` in front when it lacks one, and no colon or space after, as a pasted
* `@header.x-cache:` or a typed `header.x-cache` has. A lone `@` stays, to complete from.
*/
export function fieldReferenceChanges(
text: string,
): { from: number; to: number; insert: string }[] {
const lead = /^[\s@]*/.exec(text)?.[0].length ?? 0;
const trail = /[\s:]*$/.exec(text.slice(lead))?.[0].length ?? 0;
const end = text.length - trail;
const at = end > lead || text.includes("@") ? "@" : "";
const changes = [];
if (text.slice(0, lead) !== at) changes.push({ from: 0, to: lead, insert: at });
if (trail > 0) changes.push({ from: end, to: text.length, insert: "" });
return changes;
}
/** What the Add Column field shows for `text`, `fieldReferenceChanges` made */
export function fieldReference(text: string): string {
let result = text;
for (const { from, to, insert } of [...fieldReferenceChanges(text)].reverse()) {
result = result.slice(0, from) + insert + result.slice(to);
}
return result;
}
export function customColumnId(path: string): CustomColumnId {
return `field:${path}`;
}
export function isCustomColumn(id: ColumnId): id is CustomColumnId {
return id.startsWith("field:");
}
function customDef(id: CustomColumnId): ColumnDef {
const path = id.slice("field:".length);
return {
id,
label: path,
width: 140,
minWidth: 40,
align: "left",
defaultVisible: true,
path,
};
}
export function columnDef(id: ColumnId): ColumnDef {
if (isCustomColumn(id)) return customDef(id);
const def = DEFS.get(id);
if (def == null) throw new Error(`No column ${id}`);
return def;
}
/** The mark column, first and fixed */
export const MARK_WIDTH = 24;
/** Each cell's padding, both sides together, added to its column's width; `px-1.5` per side */
export const CELL_PADDING = "0.75rem";
/**
* What the person chose: which columns show, the widths they dragged, by id, the header and
* query parameter columns they added, in order, the order they dragged the columns into, and the
* list's sort
*/
export interface ColumnPrefs {
visible: Partial<Record<ColumnId, boolean>>;
widths: Partial<Record<ColumnId, number>>;
custom: CustomColumnId[];
/**
* The columns' order, by id. Columns not listed follow the listed ones, in their default order;
* empty for the default order.
*/
order: ColumnId[];
/** The keys in order; empty for the order flows arrive in */
sort: FlowSortKey[];
}
export const defaultColumnPrefs: ColumnPrefs = {
visible: {},
widths: {},
custom: [],
order: [],
sort: [],
};
export interface Column extends ColumnDef {
/** Its width now, in pixels of content */
current: number;
}
/**
* Every column, in the order the person left them: those they placed, then the rest in their
* default order, the built-in ones before those added. The picker lists them so.
*/
export function allColumns(prefs: ColumnPrefs): ColumnDef[] {
const defaults = [...COLUMNS, ...prefs.custom.map(customDef)];
if (prefs.order.length === 0) return defaults;
const byId = new Map(defaults.map((c) => [c.id, c]));
const placed = prefs.order.flatMap((id) => byId.get(id) ?? []);
return [...placed, ...defaults.filter((c) => !prefs.order.includes(c.id))];
}
function isVisible(prefs: ColumnPrefs, def: ColumnDef): boolean {
return prefs.visible[def.id] ?? def.defaultVisible;
}
/**
* The columns shown, in order. Each keeps its width however narrow the list is; the list scrolls
* sideways instead. At least one always shows.
*/
export function shownColumns(prefs: ColumnPrefs, unavailable: ColumnId[] = []): Column[] {
const all = allColumns(prefs).filter((c) => !unavailable.includes(c.id));
const shown = all.filter((c) => isVisible(prefs, c));
const columns = shown.length > 0 ? shown : all.filter((c) => c.id === "path");
return columns.map((c) => ({ ...c, current: columnWidth(prefs, c.id) }));
}
/** Columns the platform has nothing for: App, where it cannot tell which app sent a flow */
export function unavailableColumns(hasApps: boolean): ColumnId[] {
return hasApps ? [] : ["app"];
}
export function columnWidth(prefs: ColumnPrefs, id: ColumnId): number {
const def = columnDef(id);
return Math.max(def.minWidth, Math.round(prefs.widths[id] ?? def.width));
}
/** The grid template for the header and every row: the mark, then each column and its padding */
export function gridTemplate(columns: Column[]): string {
const cells = columns.map((c) => `calc(${c.current}px + ${CELL_PADDING})`);
return [`${MARK_WIDTH}px`, ...cells].join(" ");
}
/** The width of a row's grid, as CSS: the list scrolls sideways when it is wider than the list */
export function gridWidth(columns: Column[]): string {
const px = columns.reduce((sum, c) => sum + c.current, MARK_WIDTH);
return `calc(${px}px + ${columns.length} * ${CELL_PADDING})`;
}
/** Whether the picker may uncheck `id`: any column but the last one shown */
export function canHide(prefs: ColumnPrefs, id: ColumnId, unavailable: ColumnId[] = []): boolean {
const shown = allColumns(prefs).filter((c) => !unavailable.includes(c.id) && isVisible(prefs, c));
return !shown.every((c) => c.id === id);
}
export function toggleColumn(
prefs: ColumnPrefs,
id: ColumnId,
unavailable: ColumnId[] = [],
): ColumnPrefs {
const shown = isVisible(prefs, columnDef(id));
if (shown && !canHide(prefs, id, unavailable)) return prefs;
const next = { ...prefs, visible: { ...prefs.visible, [id]: !shown } };
return shown ? next : placeAtEnd(next, id);
}
/**
* Puts a column just shown after the others shown, unless the person placed it before, so it
* goes back to that place. The columns shown before it are placed too, where they are, so the
* ones not listed don't jump ahead of it. Until the person has ordered the columns, each keeps
* its default place: a built-in one among the others, an added one at the end.
*/
function placeAtEnd(prefs: ColumnPrefs, id: ColumnId): ColumnPrefs {
if (prefs.order.length === 0 || prefs.order.includes(id)) return prefs;
const all = allColumns(prefs);
if (all.filter((c) => isVisible(prefs, c)).at(-1)?.id === id) return prefs;
const placed = all.filter(
(c) => c.id !== id && (prefs.order.includes(c.id) || isVisible(prefs, c)),
);
return { ...prefs, order: [...placed.map((c) => c.id), id] };
}
/**
* Moves a shown column to the boundary `to` between the columns shown: 0 before the first, their
* count after the last. Hidden columns keep their places among the others.
*/
export function moveColumn(
prefs: ColumnPrefs,
id: ColumnId,
to: number,
unavailable: ColumnId[] = [],
): ColumnPrefs {
const shown = shownColumns(prefs, unavailable).map((c) => c.id);
const from = shown.indexOf(id);
if (from === -1 || to < 0 || to > shown.length || to === from || to === from + 1) return prefs;
// Every column shown, and those hidden that were placed, so they keep their places
const order = allColumns(prefs)
.filter((c) => c.id !== id && (prefs.order.includes(c.id) || shown.includes(c.id)))
.map((c) => c.id);
// Before the column at the boundary, or after the last one shown
const before = shown[to];
const last = shown.at(-1);
const at = before != null ? order.indexOf(before) : last == null ? -1 : order.indexOf(last) + 1;
if (at === -1) return prefs;
order.splice(at, 0, id);
return { ...prefs, order };
}
/** One place left, or with `1`, right, among the columns shown */
export function moveColumnBy(
prefs: ColumnPrefs,
id: ColumnId,
by: -1 | 1,
unavailable: ColumnId[] = [],
): ColumnPrefs {
const from = shownColumns(prefs, unavailable).findIndex((c) => c.id === id);
if (from === -1) return prefs;
return moveColumn(prefs, id, by === -1 ? from - 1 : from + 2, unavailable);
}
/** Every column back to its default place */
export function resetOrder(prefs: ColumnPrefs): ColumnPrefs {
return { ...prefs, order: [] };
}
/**
* Where a dragged column would drop, from the pointer and the shown columns' edges, left to
* right, as they are laid out before the drag: the boundary before the first column whose middle
* is right of the pointer. Over its own column or the near half of a neighbour, that is an edge
* of its own slot, where it would stay, so null. Left of the first column, over the fixed mark
* column, it is the first boundary.
*/
export function dropBoundary(
x: number,
cells: { left: number; right: number }[],
from: number,
): number | null {
let at = cells.findIndex((r) => x < (r.left + r.right) / 2);
if (at === -1) at = cells.length;
const stays = from === -1 || at === from || at === from + 1;
return stays ? null : at;
}
/**
* How far, in pixels, each of `count` shown columns slides while the one at `from`, `width`
* wide, is dragged to the boundary `to`: those it would pass make room for it, leftwards when it
* goes right and rightwards when it goes left. The dragged column itself, and the rest, stay.
*/
export function columnShifts(
count: number,
from: number,
width: number,
to: number | null,
): number[] {
return Array.from({ length: count }, (_, i) => {
if (to == null || i === from) return 0;
if (to > from && i > from && i < to) return -width;
if (to < from && i >= to && i < from) return width;
return 0;
});
}
/** Shows `id` alone */
export function hideOtherColumns(prefs: ColumnPrefs, id: ColumnId): ColumnPrefs {
const visible: ColumnPrefs["visible"] = {};
for (const c of allColumns(prefs)) visible[c.id] = c.id === id;
return { ...prefs, visible };
}
/**
* Adds a column for a header or query parameter's path, shown at the end; already there, shown,
* in its place
*/
export function addCustomColumn(prefs: ColumnPrefs, path: string): ColumnPrefs {
const id = customColumnId(path);
const custom = prefs.custom.includes(id) ? prefs.custom : [...prefs.custom, id];
return placeAtEnd({ ...prefs, custom, visible: { ...prefs.visible, [id]: true } }, id);
}
/** Takes the column out, and out of the order and the sort */
export function removeCustomColumn(prefs: ColumnPrefs, id: CustomColumnId): ColumnPrefs {
const { [id]: _v, ...visible } = prefs.visible;
const { [id]: _w, ...widths } = prefs.widths;
const custom = prefs.custom.filter((c) => c !== id);
const order = prefs.order.filter((c) => c !== id);
const sort = prefs.sort.filter((k) => k.column !== id);
return { ...prefs, custom, visible, widths, order, sort };
}
export function resizeColumn(prefs: ColumnPrefs, id: ColumnId, width: number): ColumnPrefs {
const w = Math.max(columnDef(id).minWidth, Math.round(width));
return { ...prefs, widths: { ...prefs.widths, [id]: w } };
}
export function resetWidths(prefs: ColumnPrefs): ColumnPrefs {
return { ...prefs, widths: {} };
}
/** One column back to its default width */
export function resetWidth(prefs: ColumnPrefs, id: ColumnId): ColumnPrefs {
const { [id]: _, ...widths } = prefs.widths;
return { ...prefs, widths };
}
/** Shows Operation the first time a flow has one, unless the person ever set it themselves */
export function showOperationFor(prefs: ColumnPrefs, flows: Flow[]): ColumnPrefs {
if (prefs.visible.operation !== undefined) return prefs;
if (!flows.some((f) => (operationOf(f) ?? "") !== "")) return prefs;
return { ...prefs, visible: { ...prefs.visible, operation: true } };
}
/**
* Reads stored preferences, dropping what no longer applies: unknown ids, and values of the
* wrong type, so a change to the columns never breaks the list.
*/
export function parseColumnPrefs(value: unknown): ColumnPrefs {
const prefs: ColumnPrefs = { visible: {}, widths: {}, custom: [], order: [], sort: [] };
if (value == null || typeof value !== "object") return prefs;
const { visible, widths, custom, order, sort } = value as Record<string, unknown>;
if (Array.isArray(custom)) {
for (const id of custom) {
if (typeof id !== "string" || !id.startsWith("field:")) continue;
const path = customPath(id.slice("field:".length));
if (path != null && !prefs.custom.includes(customColumnId(path))) {
prefs.custom.push(customColumnId(path));
}
}
}
for (const def of allColumns(prefs)) {
const v = (visible as Record<string, unknown> | undefined)?.[def.id];
if (typeof v === "boolean") prefs.visible[def.id] = v;
const w = (widths as Record<string, unknown> | undefined)?.[def.id];
if (typeof w === "number" && Number.isFinite(w) && w > 0) prefs.widths[def.id] = w;
}
// Columns no longer there are dropped; those not listed follow the rest in their default order
if (Array.isArray(order)) {
for (const column of order) {
if (typeof column !== "string") continue;
const id = column as ColumnId;
const known = isCustomColumn(id) ? prefs.custom.includes(id) : DEFS.has(id);
if (known && !prefs.order.includes(id)) prefs.order.push(id);
}
}
if (Array.isArray(sort)) {
for (const key of sort) {
if (key == null || typeof key !== "object") continue;
const { column, descending } = key as Record<string, unknown>;
if (typeof column !== "string" || typeof descending !== "boolean") continue;
// A built-in column, or one the person added that is still there
const id = column as ColumnId;
const known = isCustomColumn(id) ? prefs.custom.includes(id) : DEFS.has(id);
if (!known || prefs.sort.some((k) => k.column === id)) continue;
prefs.sort.push({ column: id, descending });
}
}
return prefs;
}
// -- Sorting --
/** Numbers sort largest first on the first click, names from A */
export function firstDirection(column: ColumnId): boolean {
switch (column) {
case "number":
case "status":
case "size":
case "requestSize":
case "time":
case "latency":
return true;
default:
return false;
}
}
/**
* A click on a column's label: sort by it alone, reverse the sort it has alone, then, from the
* reversed sort, go back to the order flows arrive in
*/
export function nextSort(sort: FlowSortKey[], column: ColumnId): FlowSortKey[] {
const first = firstDirection(column);
const only = sort.length === 1 ? sort[0] : null;
if (only?.column !== column) return [{ column, descending: first }];
if (only.descending === first) return [{ column, descending: !first }];
return [];
}
/**
* An Option-click on a column's label: adds it as the last key, ascending; again reverses it, and
* a third time takes it out
*/
export function toggleSortKey(sort: FlowSortKey[], column: ColumnId): FlowSortKey[] {
const key = sort.find((k) => k.column === column);
if (key == null) return [...sort, { column, descending: false }];
if (!key.descending)
return sort.map((k) => (k.column === column ? { column, descending: true } : k));
return sort.filter((k) => k.column !== column);
}
/** Adds `column` as a key in `descending` order: the last key, or in its place if it is one */
export function addSortKey(
sort: FlowSortKey[],
column: ColumnId,
descending: boolean,
): FlowSortKey[] {
if (sort.some((k) => k.column === column)) {
return sort.map((k) => (k.column === column ? { column, descending } : k));
}
return [...sort, { column, descending }];
}
/** What an empty number sorts as, below every value; `EMPTY_NUMBER` in the lib's `flows.rs` */
const EMPTY_NUMBER = -1e18;
/** Text as SQLite's `NOCASE` compares it: ASCII letters lowercased, nothing else changed */
function noCase(text: string | null | undefined): string {
return (text ?? "").replace(/[A-Z]/g, (c) => c.toLowerCase());
}
function emptyNumber(n: number | null | undefined): number {
return n == null || n === 0 ? EMPTY_NUMBER : n;
}
/**
* The value `column` sorts `flow` by, as `SortBy::sql` in the lib's `flows.rs` makes it in the
* database, so a flow placed here lands where a page read from there would have it. A custom
* column's is the value it shows, as text.
*/
export function columnSortKey(flow: Flow, column: ColumnId): string | number {
if (isCustomColumn(column)) return noCase(customValue(flow, column.slice("field:".length)));
switch (column) {
case "number":
return flow.number;
case "app":
return noCase(flow.clientName ?? flow.clientBundleId ?? flow.clientPath);
case "method":
return noCase(flow.method);
case "host":
return noCase(urlParts(flow.url).authority);
case "path":
return noCase(urlParts(flow.url).path);
case "query":
return noCase(urlParts(flow.url).query);
case "status":
return flow.error != null ? -1 : emptyNumber(flow.status);
case "type":
return noCase(flow.contentType);
case "size":
return flow.error != null && flow.status == null
? EMPTY_NUMBER
: emptyNumber(flow.responseSize);
case "requestSize":
return emptyNumber(flow.requestSize);
case "time":
return emptyNumber(flow.elapsedMs);
case "latency":
return emptyNumber(flow.elapsedHeadersMs);
case "started":
return flow.startedAt;
case "remote":
return noCase(flow.remoteAddr);
case "version":
return noCase(flow.upstreamHttpVersion ?? flow.clientHttpVersion);
case "tls":
return noCase(flow.upstreamTlsVersion);
case "operation":
return noCase(
flow.grpcService != null && flow.grpcMethod != null
? `${flow.grpcService}/${flow.grpcMethod}`
: flow.graphqlOperation,
);
}
}
function compareKeys(a: string | number, b: string | number): number {
if (a === b) return 0;
return a < b ? -1 : 1;
}
/**
* Orders flows as `list_flows` orders them for `sort`: each key in turn, then by start and id,
* oldest first
*/
export function sortComparator(sort: FlowSortKey[]): (a: Flow, b: Flow) => number {
return (a, b) => {
for (const { column, descending } of sort) {
const c = compareKeys(columnSortKey(a, column), columnSortKey(b, column));
if (c !== 0) return descending ? -c : c;
}
return compareFlows(a, b);
};
}
/** The flows in `sort`'s order, as the database orders them */
export function sortFlows(flows: Flow[], sort: FlowSortKey[]): Flow[] {
if (sort.length === 0) return flows;
return [...flows].sort(sortComparator(sort));
}
// -- Values --
/**
* A URL's parts as the lib's `url_parts` reads them: no scheme, all host; otherwise the
* authority up to the first `/`, `?` or `#`, then the path and the query without its `?`
*/
export function urlParts(url: string): { authority: string; path: string; query: string | null } {
const start = url.indexOf("://");
if (start === -1) return { authority: url, path: "", query: null };
const rest = url.slice(start + 3);
const end = rest.search(/[/?#]/);
const authority = end === -1 ? rest : rest.slice(0, end);
const tail = (end === -1 ? "" : rest.slice(end)).split("#")[0] ?? "";
const q = tail.indexOf("?");
return q === -1
? { authority, path: tail, query: null }
: { authority, path: tail.slice(0, q), query: tail.slice(q + 1) };
}
/** The URL's host, with its port */
export function hostOf(url: string): string {
return url.includes("://") ? urlParts(url).authority : "";
}
/** `Service/Method` for a gRPC call, the operation's name for GraphQL, or null */
export function operationOf(flow: Flow): string | null {
if (flow.grpcService != null && flow.grpcMethod != null) {
return `${flow.grpcService}/${flow.grpcMethod}`;
}
return flow.graphqlOperation ?? null;
}
/** `1.3` from `TLSv1.3` */
export function tlsVersionOf(flow: Flow): string {
return (flow.upstreamTlsVersion ?? "").replace(/^TLSv?/i, "");
}
/**
* The value of a custom column's path for `flow`: a header's first value, the response's before
* the request's for `header.`, or a query parameter's first value
*/
export function customValue(flow: Flow, path: string): string | null {
const header = (headers: Flow["requestHeaders"], name: string) =>
headers.find((h) => h.name.toLowerCase() === name)?.value ?? null;
if (path.startsWith("req.header.")) {
return header(flow.requestHeaders, path.slice("req.header.".length));
}
if (path.startsWith("res.header.")) {
return header(flow.responseHeaders, path.slice("res.header.".length));
}
if (path.startsWith("header.")) {
const name = path.slice("header.".length);
return header(flow.responseHeaders, name) ?? header(flow.requestHeaders, name);
}
if (path.startsWith("query.")) {
const query = urlParts(flow.url).query;
if (query == null) return null;
const name = path.slice("query.".length);
for (const [key, value] of new URLSearchParams(query)) {
if (key.toLowerCase() === name) return value;
}
}
return null;
}
/**
* The search term that finds flows with `flow`'s value in `column`, or excludes them, for the
* cell's menu; null for columns with no field to match their value exactly
*/
export function cellFilterTerm(flow: Flow, column: ColumnId, negated: boolean): string | null {
const term = (field: string, value: string | null | undefined) =>
value == null || value === "" ? null : fieldTerm(field, value, negated);
if (isCustomColumn(column)) {
const path = column.slice("field:".length);
return term(path, customValue(flow, path));
}
switch (column) {
case "app":
return term("app", flow.clientName ?? flow.clientBundleId ?? flow.clientPath);
case "method":
return term("method", flow.method);
case "host":
return term("host", sidebarPath(flow.url).split("/")[0]);
case "path":
return flow.tunnelled ? null : term("path", urlParts(flow.url).path);
case "status":
return flow.status == null ? null : term("status", String(flow.status));
case "type":
return term("type", flow.contentType?.split(";")[0]?.trim());
case "operation": {
if (flow.grpcService != null && flow.grpcMethod != null) {
const both = `${fieldTerm("grpc.service", flow.grpcService)} ${fieldTerm("grpc.method", flow.grpcMethod)}`;
return negated ? `-(${both})` : both;
}
return term("graphql.operation", flow.graphqlOperation);
}
default:
return null;
}
}
+305
View File
@@ -0,0 +1,305 @@
import { CompletionContext } from "@codemirror/autocomplete";
import { EditorState } from "@codemirror/state";
import type { DecryptListEntry } from "@yaakapp-internal/proxy-lib";
import { filterCompletionSource } from "@yaakapp-internal/ui/editor";
import { describe, expect, test } from "vite-plus/test";
import {
blockerOf,
blockingExclusion,
decryptFilterOptions,
detailActions,
decryptMenuAction,
decrypts,
decryptsEverything,
entryLabel,
everythingEdit,
isDecrypted,
listEdit,
normalizeEntry,
setDecrypted,
subjectQuery,
toggleDecrypt,
} from "./decrypt";
const user = (...entries: string[]): DecryptListEntry[] =>
entries.map((entry) => ({ entry, builtIn: false }));
const builtIn = (...entries: string[]): DecryptListEntry[] =>
entries.map((entry) => ({ entry, builtIn: true }));
const BUILT_INS = builtIn("!host:*.apple.com", "!host:*.icloud.com");
describe("normalizeEntry", () => {
test("a bare hostname is a host entry", () => {
expect(normalizeEntry("api.example.com")).toBe("host:api.example.com");
expect(normalizeEntry(" API.Example.com. ")).toBe("host:api.example.com");
expect(normalizeEntry("https://api.example.com:8443/v1")).toBe("host:api.example.com:8443");
});
test("prefixes and exclusions", () => {
expect(normalizeEntry("HOST:*.Example.com")).toBe("host:*.example.com");
expect(normalizeEntry("!x.com")).toBe("!host:x.com");
expect(normalizeEntry("! host:x.com")).toBe("!host:x.com");
expect(normalizeEntry('app:"Google Chrome"')).toBe("app:Google Chrome");
expect(normalizeEntry("App: com.google.Chrome")).toBe("app:com.google.Chrome");
expect(normalizeEntry("host:[::1]:8443")).toBe("host:[::1]:8443");
expect(normalizeEntry(" * ")).toBe("*");
});
test("what is not an entry", () => {
for (const bad of ["", "!", "app:", "host:a b", "host:a.com:http", "host:a.com:99999"]) {
expect(normalizeEntry(bad)).toBeNull();
}
});
test("labels", () => {
expect(entryLabel("*")).toBe("Everything");
expect(entryLabel("host:a.com")).toBe("host:a.com");
});
});
describe("decrypts", () => {
test("an empty list decrypts nothing, with or without the built-ins", () => {
expect(decrypts([], { host: "a.com" })).toBe(false);
expect(decrypts(BUILT_INS, { host: "a.com" })).toBe(false);
});
test("hosts, sites and ports", () => {
const list = user("host:*.example.com", "host:other.com:8443");
expect(decrypts(list, { host: "api.example.com" })).toBe(true);
expect(decrypts(list, { host: "example.com" })).toBe(true);
expect(decrypts(list, { host: "notexample.com" })).toBe(false);
expect(decrypts(list, { host: "other.com", port: 8443 })).toBe(true);
expect(decrypts(list, { host: "other.com" })).toBe(false);
});
test("apps by name or bundle id", () => {
const chrome = { name: "Google Chrome", bundleId: "com.google.Chrome" };
expect(decrypts(user("app:google chrome"), { host: "a.com", app: chrome })).toBe(true);
expect(decrypts(user("app:com.google.*"), { host: "a.com", app: chrome })).toBe(true);
expect(decrypts(user("app:Safari"), { host: "a.com", app: chrome })).toBe(false);
});
test("everything keeps the built-in exclusions, which a specific entry beats", () => {
const list = [...user("*"), ...BUILT_INS];
expect(decrypts(list, { host: "api.example.com" })).toBe(true);
expect(decrypts(list, { host: "gateway.icloud.com" })).toBe(false);
const specific = [...user("*", "host:developer.apple.com"), ...BUILT_INS];
expect(decrypts(specific, { host: "developer.apple.com" })).toBe(true);
expect(decrypts(specific, { host: "www.apple.com" })).toBe(false);
});
test("the user's exclusions win wherever they sit", () => {
for (const list of [user("!host:a.example.com", "*"), user("*", "!host:a.example.com")]) {
expect(decrypts(list, { host: "a.example.com" })).toBe(false);
expect(decrypts(list, { host: "b.example.com" })).toBe(true);
}
});
});
describe("the sidebar's Decrypt and Stop Decrypting", () => {
test("Decrypt adds the host's entry before the built-ins", () => {
const list = BUILT_INS;
const subject = { kind: "host", host: "api.example.com" } as const;
expect(isDecrypted(list, subject)).toBe(false);
expect(toggleDecrypt(list, subject)).toEqual([
"host:api.example.com",
"!host:*.apple.com",
"!host:*.icloud.com",
]);
});
test("Stop Decrypting removes the entry that decrypts it", () => {
const list = [...user("host:api.example.com", "host:b.com"), ...BUILT_INS];
const subject = { kind: "host", host: "api.example.com" } as const;
expect(isDecrypted(list, subject)).toBe(true);
expect(toggleDecrypt(list, subject)).toEqual([
"host:b.com",
"!host:*.apple.com",
"!host:*.icloud.com",
]);
});
test("Stop Decrypting under everything excludes the host", () => {
const list = user("*");
const subject = { kind: "site", site: "example.com" } as const;
expect(isDecrypted(list, subject)).toBe(true);
expect(toggleDecrypt(list, subject)).toEqual(["*", "!host:*.example.com"]);
});
test("Decrypt adds nothing while a broader exclusion of the user's would still win", () => {
const list = user("*", "!host:*.example.com");
const subject = { kind: "host", host: "api.example.com" } as const;
expect(blockingExclusion(list, subjectQuery(subject))).toBe("!host:*.example.com");
expect(toggleDecrypt(list, subject)).toEqual(["*", "!host:*.example.com"]);
// The built-ins are not the user's to block with: a specific entry beats them.
expect(blockingExclusion(BUILT_INS, { host: "www.apple.com" })).toBeNull();
});
test("Decrypt undoes the sidebar's own Stop Decrypting", () => {
const subject = { kind: "site", site: "example.com" } as const;
const stopped = toggleDecrypt(user("*"), subject);
expect(stopped).toEqual(["*", "!host:*.example.com"]);
const list = user(...stopped);
expect(blockerOf(list, [subject])).toBeNull();
expect(toggleDecrypt(list, subject)).toEqual(["*"]);
const host = { kind: "host", host: "api.example.com" } as const;
expect(blockerOf(list, [host])).toBe("!host:*.example.com");
});
test("an exact site entry beats the built-in exclusion of the same site", () => {
expect(decrypts([...user("host:apple.com"), ...BUILT_INS], { host: "apple.com" })).toBe(true);
});
test("Decrypt drops the user's own exclusion first", () => {
const list = user("*", "!host:*.example.com");
const subject = { kind: "site", site: "example.com" } as const;
expect(toggleDecrypt(list, subject)).toEqual(["*"]);
});
test("apps by name, and a host with a port", () => {
const slack = { kind: "app", name: "Slack", bundleId: "com.tinyspeck.slackmacgap" } as const;
expect(toggleDecrypt([], slack)).toEqual(["app:Slack"]);
expect(isDecrypted(user("app:com.tinyspeck.slackmacgap"), slack)).toBe(true);
expect(isDecrypted(user("*"), slack)).toBe(true);
const port = { kind: "host", host: "localhost:8443" } as const;
expect(toggleDecrypt([], port)).toEqual(["host:localhost:8443"]);
expect(isDecrypted(user("host:localhost:8443"), port)).toBe(true);
});
});
describe("the sidebar menu", () => {
const a = { kind: "host", host: "a.com" } as const;
const b = { kind: "host", host: "b.com" } as const;
test("offers Decrypt unless every selected row is decrypted", () => {
expect(decryptMenuAction(user("host:a.com"), [a])).toEqual({
label: "Stop Decrypting",
on: false,
});
expect(decryptMenuAction(user("host:a.com"), [a, b])).toEqual({ label: "Decrypt", on: true });
expect(decryptMenuAction([], [])).toBeNull();
});
test("applies to every selected row, leaving those already so", () => {
const next = setDecrypted(user("host:a.com"), [a, b], true).map((e) => e.entry);
expect(next).toEqual(["host:a.com", "host:b.com"]);
expect(setDecrypted(user("host:a.com", "host:b.com"), [a, b], false)).toEqual([]);
});
});
describe("the Not decrypted detail's buttons", () => {
const slack = { name: "Slack", bundleId: "com.tinyspeck.slackmacgap" };
test("each button is offered only when its own change would decrypt the connection", () => {
// `!app:Slack` still excludes Slack's connections whatever host is added.
const list = user("*", "!app:Slack");
expect(detailActions(list, "edgeapi.slack.com", slack)).toEqual({
listed: false,
host: false,
app: true,
blocked: null,
});
// And `!host:` the other way round.
expect(detailActions(user("*", "!host:edgeapi.slack.com"), "edgeapi.slack.com", slack)).toEqual(
{ listed: false, host: true, app: false, blocked: null },
);
});
test("names the exclusion when neither would", () => {
const list = user("*", "!host:*.slack.com", "!app:Slack");
expect(detailActions(list, "edgeapi.slack.com", slack)).toEqual({
listed: false,
host: false,
app: false,
blocked: "!host:*.slack.com",
});
});
test("both on an empty list, and none once it is listed", () => {
expect(detailActions(BUILT_INS, "a.com", slack)).toEqual({
listed: false,
host: true,
app: true,
blocked: null,
});
expect(detailActions(user("host:a.com"), "a.com", null).listed).toBe(true);
});
});
describe("the first-run step", () => {
test("Everything adds *, and Pick as they appear takes it out", () => {
expect(decryptsEverything(BUILT_INS)).toBe(false);
expect(decryptsEverything([...user("*"), ...BUILT_INS])).toBe(true);
expect(everythingEdit(true)).toEqual({ add: ["*"], remove: [] });
expect(everythingEdit(false)).toEqual({ add: [], remove: ["*"] });
});
});
describe("edits sent as additions and removals", () => {
test("a toggle becomes what it adds and removes, not the whole list", () => {
const list = [...user("*", "!host:*.example.com"), ...BUILT_INS];
const site = { kind: "site", site: "example.com" } as const;
expect(listEdit(list, setDecrypted(list, [site], true))).toEqual({
add: [],
remove: ["!host:*.example.com"],
});
const host = { kind: "host", host: "a.com" } as const;
expect(listEdit(BUILT_INS, setDecrypted(BUILT_INS, [host], true))).toEqual({
add: ["host:a.com"],
remove: [],
});
});
test("two edits from the same stale list both survive, applied in turn", () => {
// What the lib does with each edit: remove, then add after the user's own entries.
const apply = (entries: string[], e: { add: string[]; remove: string[] }) => [
...entries.filter((x) => !e.remove.includes(x)),
...e.add,
];
const stale = BUILT_INS;
const first = listEdit(stale, setDecrypted(stale, [{ kind: "host", host: "a.com" }], true));
const second = listEdit(stale, setDecrypted(stale, [{ kind: "host", host: "b.com" }], true));
const saved = apply(apply([], first), second);
expect(saved).toEqual(["host:a.com", "host:b.com"]);
});
});
describe("the list's autocomplete", () => {
const source = filterCompletionSource(
decryptFilterOptions({
hosts: ["api.example.com", "www.example.org"],
apps: [
{ name: "Google Chrome", bundleId: "com.google.Chrome" },
{ name: "curl", bundleId: null },
],
}),
);
function complete(doc: string) {
const state = EditorState.create({ doc });
const result = source(new CompletionContext(state, doc.length, true));
if (result == null || result instanceof Promise) return null;
return { from: result.from, labels: result.options.map((o) => o.label) };
}
test("an empty input offers host:, app: and !", () => {
expect(complete("")).toEqual({ from: 0, labels: ["host", "app", "!"] });
expect(complete("ho")).toEqual({ from: 0, labels: ["host", "app", "!"] });
});
test("after ! it offers the fields negated", () => {
expect(complete("!")).toEqual({ from: 0, labels: ["!host", "!app"] });
expect(complete("!ap")).toEqual({ from: 0, labels: ["!host", "!app"] });
});
test("after host: the hosts seen, replacing only the value", () => {
expect(complete("host:")).toEqual({ from: 5, labels: ["api.example.com", "www.example.org"] });
expect(complete("!host:api")?.from).toBe(6);
});
test("after app: the apps seen, by name and bundle id", () => {
expect(complete("app:")).toEqual({
from: 4,
labels: ['"Google Chrome"', "com.google.Chrome", "curl"],
});
});
});
+394
View File
@@ -0,0 +1,394 @@
import type { DecryptListEntry, SeenTargets } from "@yaakapp-internal/proxy-lib";
import type { FilterOptions } from "@yaakapp-internal/ui/editor";
/**
* The decrypt list as the engine reads it: `host:` and `app:` entries, `*` for everything, any
* of them after `!` to exclude. `DecryptEntry` and `DecryptPolicy` in `crates/yaak-proxy`, which
* decide each connection, follow the same rules; this copy marks the sidebar and the detail.
*/
export const EVERYTHING = "*";
export interface ParsedEntry {
negated: boolean;
kind: "everything" | "host" | "app";
/** A host pattern, lowercased, or an app's name or bundle id as written */
pattern: string;
/** The port a host entry is limited to */
port: number | null;
}
/**
* An entry as typed: with its prefix, or a bare hostname, which is a `host:` entry. A URL is
* taken as its host. Null when it is not one.
*/
export function parseEntry(input: string): ParsedEntry | null {
let rest = input.trim();
const negated = rest.startsWith("!");
if (negated) rest = rest.slice(1).trimStart();
if (rest === "") return null;
if (rest === EVERYTHING) return { negated, kind: "everything", pattern: "", port: null };
if (/^app:/i.test(rest)) {
const app = unquote(rest.slice(4).trim());
return app === "" ? null : { negated, kind: "app", pattern: app, port: null };
}
const host = unquote((/^host:/i.test(rest) ? rest.slice(5) : rest).trim());
const parsed = parseHost(host);
return parsed == null ? null : { negated, kind: "host", ...parsed };
}
function unquote(s: string): string {
return s.length >= 2 && s.startsWith('"') && s.endsWith('"') ? s.slice(1, -1).trim() : s;
}
function parseHost(input: string): { pattern: string; port: number | null } | null {
let host = input;
const scheme = host.indexOf("://");
if (scheme !== -1) {
host = host.slice(scheme + 3).split(/[/?#]/)[0] ?? "";
host = host.slice(host.lastIndexOf("@") + 1);
}
let pattern: string;
let port: number | null = null;
if (host.startsWith("[")) {
const end = host.indexOf("]");
if (end === -1) return null;
pattern = host.slice(1, end);
const after = host.slice(end + 1);
if (after !== "") {
if (!after.startsWith(":")) return null;
port = parsePort(after.slice(1));
if (port == null) return null;
}
} else {
const colon = host.lastIndexOf(":");
const name = colon === -1 ? host : host.slice(0, colon);
// One colon is a port; more, a bare IPv6 address.
if (colon !== -1 && !name.includes(":")) {
port = parsePort(host.slice(colon + 1));
if (port == null) return null;
pattern = name;
} else {
pattern = host;
}
}
pattern = pattern.replace(/\.+$/, "").toLowerCase();
if (pattern === "" || !/^[a-z0-9\-._*:]+$/.test(pattern)) return null;
return { pattern, port };
}
function parsePort(s: string): number | null {
if (!/^\d+$/.test(s)) return null;
const n = Number(s);
return n <= 65535 ? n : null;
}
/** The entry as stored: `host:api.example.com`, `!app:Slack`, `*` */
export function formatEntry(e: ParsedEntry): string {
const not = e.negated ? "!" : "";
if (e.kind === "everything") return `${not}${EVERYTHING}`;
if (e.kind === "app") return `${not}app:${e.pattern}`;
if (e.port == null) return `${not}host:${e.pattern}`;
const host = e.pattern.includes(":") ? `[${e.pattern}]` : e.pattern;
return `${not}host:${host}:${e.port}`;
}
/** An entry as typed, normalized as the engine stores it, or null when it is not one */
export function normalizeEntry(input: string): string | null {
const parsed = parseEntry(input);
return parsed == null ? null : formatEntry(parsed);
}
/** How the list names an entry: `*` is Everything, anything else as written */
export function entryLabel(entry: string): string {
if (entry === EVERYTHING) return "Everything";
if (entry === `!${EVERYTHING}`) return "Nothing";
return entry;
}
/** What a connection is: where it goes and, when known, the app that sent it */
export interface DecryptQuery {
host: string;
port?: number | null;
app?: { name: string; bundleId: string | null } | null;
}
function glob(pattern: string, text: string): boolean {
let pi = 0;
let ti = 0;
let star: [number, number] | null = null;
while (ti < text.length) {
if (pi < pattern.length && pattern[pi] === "*") {
star = [pi, ti];
pi++;
} else if (pi < pattern.length && pattern[pi] === text[ti]) {
pi++;
ti++;
} else if (star != null) {
pi = star[0] + 1;
ti = star[1] + 1;
star = [star[0], star[1] + 1];
} else {
return false;
}
}
return pattern
.slice(pi)
.split("")
.every((c) => c === "*");
}
/** `*.example.com` matches `example.com` too, as the search's `@host` does */
function hostMatches(pattern: string, host: string): boolean {
const h = host
.replace(/^\[|\]$/g, "")
.replace(/\.+$/, "")
.toLowerCase();
return glob(pattern, h) || (pattern.startsWith("*.") && glob(pattern.slice(2), h));
}
function matches(e: ParsedEntry, q: DecryptQuery): boolean {
switch (e.kind) {
case "everything":
return true;
case "host":
return (e.port == null || e.port === (q.port ?? 443)) && hostMatches(e.pattern, q.host);
case "app": {
if (q.app == null) return false;
const p = e.pattern.toLowerCase();
return (
glob(p, q.app.name.toLowerCase()) ||
(q.app.bundleId != null && glob(p, q.app.bundleId.toLowerCase()))
);
}
}
}
function specificity(e: ParsedEntry): number {
if (e.kind === "everything") return 0;
if (e.kind === "app") return Number.POSITIVE_INFINITY;
// A site's `*.` counts for nothing, as `*.apple.com` matches `apple.com` itself.
const pattern = e.pattern.startsWith("*.") ? e.pattern.slice(2) : e.pattern;
return pattern.replaceAll("*", "").length + (e.port == null ? 0 : 1);
}
/**
* Whether the list decrypts `q`: a positive entry matches and no negative one does, wherever
* each sits. A built-in exclusion yields to a positive entry at least as specific as itself.
*/
export function decrypts(list: DecryptListEntry[], q: DecryptQuery): boolean {
const parsed = list.flatMap((e) => {
const p = parseEntry(e.entry);
return p == null ? [] : [{ ...p, builtIn: e.builtIn }];
});
let best = -1;
for (const e of parsed) {
if (!e.negated && matches(e, q)) best = Math.max(best, specificity(e));
}
if (best < 0) return false;
return !parsed.some((e) => e.negated && matches(e, q) && (!e.builtIn || specificity(e) > best));
}
/** Some entry decrypts something: the list is not only exclusions */
export function decryptsAnything(list: DecryptListEntry[]): boolean {
return list.some((e) => !e.entry.trim().startsWith("!"));
}
/** What a sidebar row or the detail's buttons decrypt: a host, a site, or an app */
export type DecryptSubject =
| { kind: "host"; host: string }
| { kind: "site"; site: string }
| { kind: "app"; name: string; bundleId: string | null };
/** The entry that names `subject` alone: `host:api.example.com`, `host:*.example.com`, `app:Slack` */
export function subjectEntry(subject: DecryptSubject): string {
switch (subject.kind) {
case "host":
return normalizeEntry(`host:${subject.host}`) ?? `host:${subject.host}`;
case "site":
return `host:*.${subject.site.toLowerCase()}`;
case "app":
return `app:${subject.name}`;
}
}
/** The connection a subject stands for, as the list judges it */
export function subjectQuery(subject: DecryptSubject): DecryptQuery {
switch (subject.kind) {
case "host": {
const parsed = parseHost(subject.host);
return { host: parsed?.pattern ?? subject.host, port: parsed?.port ?? 443 };
}
case "site":
return { host: subject.site };
case "app":
// No host matches an empty one, so only `*` and app entries decide.
return { host: "", app: { name: subject.name, bundleId: subject.bundleId } };
}
}
/**
* An exclusion of the user's that matches `q`, which no entry added beats: Decrypt cannot help
* until it is edited. Null when there is none.
*/
export function blockingExclusion(
list: DecryptListEntry[],
q: DecryptQuery,
builtIns = false,
): string | null {
for (const e of list) {
if (e.builtIn && !builtIns) continue;
const parsed = parseEntry(e.entry);
if (parsed?.negated && matches(parsed, q)) return e.entry;
}
return null;
}
/**
* What keeps Decrypt on `subject` from working: an exclusion of the user's that matches it,
* other than its own exact one, which Decrypt removes. Null when Decrypt works.
*/
export function blockerOf(list: DecryptListEntry[], subjects: DecryptSubject[]): string | null {
const own = new Set(subjects.map((s) => `!${subjectEntry(s)}`));
const rest = list.filter((e) => !own.has(e.entry));
for (const subject of subjects) {
const blocker = blockingExclusion(rest, subjectQuery(subject));
if (blocker != null) return blocker;
}
return null;
}
/** What the Not decrypted detail offers for one tunnelled connection */
export interface DetailActions {
/** The connection is decrypted from the next one on already */
listed: boolean;
/** Decrypt Host would decrypt it */
host: boolean;
/** Decrypt App would decrypt it */
app: boolean;
/** Neither would: the exclusion that keeps it out */
blocked: string | null;
}
/**
* Each button judged on its own: whether decrypting the host, or the app, would decrypt this
* connection, with its host, port and app together. A button whose change something else
* still excludes is not offered; with neither, the exclusion is named.
*/
export function detailActions(
list: DecryptListEntry[],
host: string,
app: { name: string; bundleId: string | null } | null,
): DetailActions {
const hostSubject: DecryptSubject = { kind: "host", host };
const q = { ...subjectQuery(hostSubject), app };
if (decrypts(list, q)) return { listed: true, host: false, app: false, blocked: null };
const works = (subject: DecryptSubject) => decrypts(setDecrypted(list, [subject], true), q);
const hostWorks = works(hostSubject);
const appWorks = app != null && works({ kind: "app", ...app });
const blocked =
hostWorks || appWorks ? null : (blockingExclusion(list, q) ?? blockingExclusion(list, q, true));
return { listed: false, host: hostWorks, app: appWorks, blocked };
}
/** The list decrypts `subject`'s connections, as its sidebar row marks it */
export function isDecrypted(list: DecryptListEntry[], subject: DecryptSubject): boolean {
return decrypts(list, subjectQuery(subject));
}
/**
* The entries after Decrypt or Stop Decrypting on `subject`, to save whole. Decrypt drops an
* exclusion of the subject the user added, then adds its entry if it is still not decrypted.
* Stop drops its entry, then excludes it if something broader, `*` say, still decrypts it.
*/
export function toggleDecrypt(list: DecryptListEntry[], subject: DecryptSubject): string[] {
return setDecrypted(list, [subject], !isDecrypted(list, subject)).map((e) => e.entry);
}
/**
* The list with every one of `subjects` decrypted (`on`) or not, each as [`toggleDecrypt`]
* changes it, those already so left alone: several sidebar rows at once.
*/
export function setDecrypted(
list: DecryptListEntry[],
subjects: DecryptSubject[],
on: boolean,
): DecryptListEntry[] {
let next = list;
for (const subject of subjects) {
if (isDecrypted(next, subject) === on) continue;
const entry = subjectEntry(subject);
const drop = on ? `!${entry}` : entry;
next = next.filter((e) => e.builtIn || e.entry !== drop);
if (isDecrypted(next, subject) === on) continue;
// Something the user excluded more broadly still keeps it out; adding would change nothing.
if (on && blockingExclusion(next, subjectQuery(subject)) != null) continue;
const add = on ? entry : `!${entry}`;
next = [...next.filter((e) => !e.builtIn), { entry: add, builtIn: false }, ...builtIns(next)];
}
return next;
}
/**
* The sidebar menu's row for the selected rows that can be decrypted: Stop Decrypting when every
* one of them is, else Decrypt. Null when none can.
*/
export function decryptMenuAction(
list: DecryptListEntry[],
subjects: DecryptSubject[],
): { label: "Decrypt" | "Stop Decrypting"; on: boolean } | null {
if (subjects.length === 0) return null;
const on = !subjects.every((s) => isDecrypted(list, s));
return { label: on ? "Decrypt" : "Stop Decrypting", on };
}
function builtIns(list: DecryptListEntry[]): DecryptListEntry[] {
return list.filter((e) => e.builtIn);
}
/**
* What turns `before` into `after`, as `edit_decrypt_list` takes it: the entries to add and to
* remove, applied to the list as it is when they land, so edits made together each keep the
* other's.
*/
export function listEdit(
before: DecryptListEntry[],
after: DecryptListEntry[],
): { add: string[]; remove: string[] } {
const was = new Set(before.map((e) => e.entry));
const now = new Set(after.map((e) => e.entry));
return {
add: after.filter((e) => !was.has(e.entry)).map((e) => e.entry),
remove: before.filter((e) => !now.has(e.entry)).map((e) => e.entry),
};
}
/** The edit that adds `*`, or takes it out, as the first-run card's choice makes it */
export function everythingEdit(on: boolean): { add: string[]; remove: string[] } {
return on ? { add: [EVERYTHING], remove: [] } : { add: [], remove: [EVERYTHING] };
}
/** Whether the list decrypts everything, as the first-run card's choice reads it */
export function decryptsEverything(list: DecryptListEntry[]): boolean {
return list.some((e) => e.entry === EVERYTHING);
}
/**
* What the list's input suggests: `host:`, `app:` and `!` to start an entry; after `host:` the
* hosts seen in the capture, after `app:` the apps seen, by name and bundle id.
*/
export function decryptFilterOptions(seen: SeenTargets | null | undefined): FilterOptions {
const apps = new Set<string>();
for (const app of seen?.apps ?? []) {
apps.add(app.name);
if (app.bundleId != null) apps.add(app.bundleId);
}
return {
fieldPrefix: "",
replaceValueOnly: true,
negation: { prefix: "!", info: "Exclude" },
fields: [
{ name: "host", values: seen?.hosts ?? [], info: "Host or *.site" },
{ name: "app", values: [...apps], info: "App name or bundle id" },
],
};
}
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, test } from "vite-plus/test";
import {
defaultTabFor,
flowShape,
learnTab,
REQUEST_TAB_BODY,
REQUEST_TAB_HEADERS,
RESPONSE_TAB_BODY,
RESPONSE_TAB_HEADERS,
RESPONSE_TAB_INFO,
RESPONSE_TAB_MESSAGES,
RESPONSE_TAB_TIMELINE,
type TabMemory,
} from "./defaultTab";
type ShapeFlow = Parameters<typeof flowShape>[0];
const ok: ShapeFlow = {
streamKind: null,
status: 200,
error: null,
cancelled: false,
requestSize: 0,
responseSize: 120,
};
function memory(): TabMemory & { items: Map<string, string> } {
const items = new Map<string, string>();
return {
items,
getItem: (k) => items.get(k) ?? null,
setItem: (k, v) => void items.set(k, v),
};
}
const RESPONSE_TABS = [
RESPONSE_TAB_BODY,
RESPONSE_TAB_HEADERS,
"cookies",
RESPONSE_TAB_TIMELINE,
RESPONSE_TAB_INFO,
];
describe("flowShape", () => {
test("names what the flow has", () => {
expect(flowShape(ok)).toBe("response_body");
expect(flowShape({ ...ok, responseSize: 0, requestSize: 20 })).toBe("request_body");
expect(flowShape({ ...ok, responseSize: 0 })).toBe("neither");
expect(flowShape({ ...ok, streamKind: "websocket" })).toBe("stream");
expect(flowShape({ ...ok, status: null, error: "refused" })).toBe("no_response");
expect(flowShape({ ...ok, status: null, cancelled: true })).toBe("no_response");
});
test("a body cut after the headers still has its response", () => {
expect(flowShape({ ...ok, error: "reset mid-body" })).toBe("response_body");
});
});
describe("defaultTabFor", () => {
test("follows the table", () => {
const m = memory();
// A response body
expect(defaultTabFor("request", ok, [], m)).toBe(REQUEST_TAB_HEADERS);
expect(defaultTabFor("request", { ...ok, requestSize: 9 }, [], m)).toBe(REQUEST_TAB_BODY);
expect(defaultTabFor("response", ok, RESPONSE_TABS, m)).toBe(RESPONSE_TAB_BODY);
// A request body, no response body
const post = { ...ok, requestSize: 30, responseSize: 0 };
expect(defaultTabFor("request", post, [], m)).toBe(REQUEST_TAB_BODY);
expect(defaultTabFor("response", post, RESPONSE_TABS, m)).toBe(RESPONSE_TAB_HEADERS);
// Neither
const empty = { ...ok, responseSize: 0 };
expect(defaultTabFor("request", empty, [], m)).toBe(REQUEST_TAB_HEADERS);
expect(defaultTabFor("response", empty, RESPONSE_TABS, m)).toBe(RESPONSE_TAB_HEADERS);
// A stream
const ws = { ...ok, streamKind: "websocket" as const };
expect(defaultTabFor("response", ws, [...RESPONSE_TABS, RESPONSE_TAB_MESSAGES], m)).toBe(
RESPONSE_TAB_MESSAGES,
);
// No response at all
const failed = { ...ok, status: null, error: "refused", responseSize: 0 };
expect(defaultTabFor("response", failed, RESPONSE_TABS, m)).toBe(RESPONSE_TAB_TIMELINE);
expect(defaultTabFor("request", { ...failed, requestSize: 4 }, [], m)).toBe(REQUEST_TAB_BODY);
});
test("a tab chosen by hand becomes the default for the same shape and pane", () => {
const m = memory();
learnTab("response", ok, RESPONSE_TAB_INFO, m);
expect(defaultTabFor("response", ok, RESPONSE_TABS, m)).toBe(RESPONSE_TAB_INFO);
// Not for other shapes, nor the other pane
const post = { ...ok, requestSize: 30, responseSize: 0 };
expect(defaultTabFor("response", post, RESPONSE_TABS, m)).toBe(RESPONSE_TAB_HEADERS);
expect(defaultTabFor("request", ok, ["body", "headers", "info"], m)).toBe(REQUEST_TAB_HEADERS);
});
test("a learned tab the flow doesn't have falls back to the table", () => {
const m = memory();
const ws = { ...ok, streamKind: "websocket" as const };
learnTab("response", ws, RESPONSE_TAB_MESSAGES, m);
learnTab("response", ok, RESPONSE_TAB_MESSAGES, m);
expect(defaultTabFor("response", ok, RESPONSE_TABS, m)).toBe(RESPONSE_TAB_BODY);
});
test("works without storage", () => {
expect(defaultTabFor("response", ok, RESPONSE_TABS, null)).toBe(RESPONSE_TAB_BODY);
});
});
+97
View File
@@ -0,0 +1,97 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
/** The request half's tabs, named as the shared request pane names them */
export const REQUEST_TAB_BODY = "body";
export const REQUEST_TAB_PARAMS = "params";
export const REQUEST_TAB_HEADERS = "headers";
export const REQUEST_TAB_AUTH = "auth";
export const REQUEST_TAB_COOKIES = "cookies";
/** The response half's tabs, named as the shared response pane names them */
export const RESPONSE_TAB_BODY = "body";
export const RESPONSE_TAB_HEADERS = "headers";
export const RESPONSE_TAB_COOKIES = "cookies";
export const RESPONSE_TAB_TIMELINE = "timeline";
export const RESPONSE_TAB_INFO = "info";
export const RESPONSE_TAB_MESSAGES = "messages";
export type FlowPane = "request" | "response";
/** What a flow has, which picks the tab each half opens on */
export type FlowShape = "response_body" | "request_body" | "neither" | "stream" | "no_response";
export function flowShape(
flow: Pick<
Flow,
"streamKind" | "status" | "error" | "cancelled" | "requestSize" | "responseSize"
>,
): FlowShape {
if (flow.streamKind != null) return "stream";
if (flow.status == null && (flow.error != null || flow.cancelled)) return "no_response";
if (flow.responseSize > 0) return "response_body";
if (flow.requestSize > 0) return "request_body";
return "neither";
}
/** The tab a half opens on for a shape, before anything was learned */
export function shapeDefaultTab(pane: FlowPane, shape: FlowShape, hasRequestBody: boolean): string {
if (pane === "request") {
return hasRequestBody ? REQUEST_TAB_BODY : REQUEST_TAB_HEADERS;
}
switch (shape) {
case "response_body":
return RESPONSE_TAB_BODY;
case "stream":
return RESPONSE_TAB_MESSAGES;
case "no_response":
return RESPONSE_TAB_TIMELINE;
case "request_body":
case "neither":
return RESPONSE_TAB_HEADERS;
}
}
/** Where the tab last chosen by hand for a shape is kept */
export function learnedTabKey(pane: FlowPane, shape: FlowShape): string {
return `proxy_learned_tab.${pane}.${shape}`;
}
/** Where learned tabs are read from and written to: local storage in the app */
export interface TabMemory {
getItem: (key: string) => string | null;
setItem: (key: string, value: string) => void;
}
/**
* The tab a half opens on for a flow with no tab of its own: the one last chosen by hand for
* flows of its shape, when this flow has that tab, else the shape's default.
*/
export function defaultTabFor(
pane: FlowPane,
flow: Parameters<typeof flowShape>[0],
available: string[],
memory: TabMemory | null,
): string {
const shape = flowShape(flow);
const learned = memory?.getItem(learnedTabKey(pane, shape)) ?? null;
if (learned != null && available.includes(learned)) return learned;
return shapeDefaultTab(pane, shape, flow.requestSize > 0);
}
/** A tab chosen by hand becomes the default for flows of the same shape */
export function learnTab(
pane: FlowPane,
flow: Parameters<typeof flowShape>[0],
tab: string,
memory: TabMemory | null,
) {
memory?.setItem(learnedTabKey(pane, flowShape(flow)), tab);
}
export function browserTabMemory(): TabMemory | null {
try {
return window.localStorage;
} catch {
return null;
}
}
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, test } from "vite-plus/test";
import { encryptingPercent } from "./encrypting";
describe("encryptingPercent", () => {
const state = (encrypting: number | null) =>
({ encrypting }) as Parameters<typeof encryptingPercent>[0];
test("is null when nothing is being encrypted", () => {
expect(encryptingPercent(null)).toBeNull();
expect(encryptingPercent(state(null))).toBeNull();
});
test("rounds down and stays within 0 and 100", () => {
expect(encryptingPercent(state(0))).toBe("0%");
expect(encryptingPercent(state(0.426))).toBe("42%");
expect(encryptingPercent(state(0.999))).toBe("99%");
expect(encryptingPercent(state(1))).toBe("100%");
expect(encryptingPercent(state(1.2))).toBe("100%");
});
});
+11
View File
@@ -0,0 +1,11 @@
import type { GetProxyStateResponse } from "@yaakapp-internal/proxy-lib";
/**
* How far encrypting traffic stored before encryption has got, as "42%", while it runs; null
* otherwise. Rounded down, so it reads 100% only once it is done.
*/
export function encryptingPercent(state: GetProxyStateResponse | null | undefined): string | null {
const fraction = state?.encrypting;
if (fraction == null) return null;
return `${Math.floor(Math.min(Math.max(fraction, 0), 1) * 100)}%`;
}
+62 -6
View File
@@ -1,19 +1,75 @@
import { describe, expect, test } from "vite-plus/test";
import { environmentExports } from "./env";
import { defaultShell, environmentBlock, environmentExports } from "./env";
const MAC_PATH = "/Users/me/Library/Application Support/app.yaak.proxy/ca/ca.pem";
describe("environmentExports", () => {
test("points the proxy variables at the port and the CA variables at the certificate", () => {
const path = "/Users/me/Library/Application Support/app.yaak.proxy/ca/ca.pem";
expect(environmentExports(9090, path)).toBe(
expect(environmentExports(9090, MAC_PATH)).toBe(
[
"export HTTP_PROXY=http://127.0.0.1:9090",
"export HTTPS_PROXY=http://127.0.0.1:9090",
"export http_proxy=http://127.0.0.1:9090",
"export https_proxy=http://127.0.0.1:9090",
`export SSL_CERT_FILE='${path}'`,
`export NODE_EXTRA_CA_CERTS='${path}'`,
`export REQUESTS_CA_BUNDLE='${path}'`,
`export SSL_CERT_FILE='${MAC_PATH}'`,
`export NODE_EXTRA_CA_CERTS='${MAC_PATH}'`,
`export REQUESTS_CA_BUNDLE='${MAC_PATH}'`,
].join("\n"),
);
});
});
describe("environmentBlock", () => {
test("bash and zsh quote only what needs it", () => {
const lines = environmentBlock("posix", 9090, "/tmp/it's.pem").split("\n");
expect(lines[0]).toBe("export HTTP_PROXY=http://127.0.0.1:9090");
expect(lines[4]).toBe(`export SSL_CERT_FILE='/tmp/it'\\''s.pem'`);
});
test("fish", () => {
const lines = environmentBlock("fish", 8080, MAC_PATH).split("\n");
expect(lines[0]).toBe("set -gx HTTP_PROXY http://127.0.0.1:8080");
expect(lines[6]).toBe(`set -gx REQUESTS_CA_BUNDLE '${MAC_PATH}'`);
expect(environmentBlock("fish", 1, "/a b/it's\\x").split("\n")[4]).toBe(
`set -gx SSL_CERT_FILE '/a b/it\\'s\\\\x'`,
);
});
test("PowerShell", () => {
const path = "C:\\Users\\O'Neil\\AppData\\Roaming\\app.yaak.proxy\\ca.pem";
const lines = environmentBlock("powershell", 9090, path).split("\n");
expect(lines[1]).toBe("$env:HTTPS_PROXY = 'http://127.0.0.1:9090'");
expect(lines[5]).toBe(
"$env:NODE_EXTRA_CA_CERTS = 'C:\\Users\\O''Neil\\AppData\\Roaming\\app.yaak.proxy\\ca.pem'",
);
});
test("cmd", () => {
const path = "C:\\Program Files\\Yaak\\ca.pem";
const lines = environmentBlock("cmd", 9090, path).split("\n");
expect(lines[0]).toBe(`set "HTTP_PROXY=http://127.0.0.1:9090"`);
expect(lines[4]).toBe(`set "SSL_CERT_FILE=${path}"`);
});
test("names every variable a tool reads", () => {
const block = environmentBlock("posix", 9090, "/ca.pem");
for (const name of [
"HTTP_PROXY",
"HTTPS_PROXY",
"SSL_CERT_FILE",
"NODE_EXTRA_CA_CERTS",
"REQUESTS_CA_BUNDLE",
]) {
expect(block).toContain(`export ${name}=`);
}
});
});
describe("defaultShell", () => {
test("by the platform", () => {
expect(defaultShell("macos")).toBe("posix");
expect(defaultShell("linux")).toBe("posix");
expect(defaultShell("windows")).toBe("powershell");
expect(defaultShell(null)).toBe("posix");
});
});
+67 -18
View File
@@ -1,21 +1,70 @@
import { shellQuote } from "./curl";
/**
* Shell exports that send one terminal's traffic through the proxy on `port` and trust its CA at
* `caPath`, for tools that read neither the system proxy nor the login keychain: Node, Python,
* and anything built on OpenSSL.
*/
export function environmentExports(port: number, caPath: string): string {
const proxy = `http://127.0.0.1:${port}`;
const ca = shellQuote(caPath);
return [
`export HTTP_PROXY=${proxy}`,
`export HTTPS_PROXY=${proxy}`,
// curl reads only the lowercase name for plain HTTP.
`export http_proxy=${proxy}`,
`export https_proxy=${proxy}`,
`export SSL_CERT_FILE=${ca}`,
`export NODE_EXTRA_CA_CERTS=${ca}`,
`export REQUESTS_CA_BUNDLE=${ca}`,
].join("\n");
/** The shells the terminal environment is written for */
export type TerminalShell = "posix" | "fish" | "powershell" | "cmd";
export const TERMINAL_SHELLS: { value: TerminalShell; label: string }[] = [
{ value: "posix", label: "bash / zsh" },
{ value: "fish", label: "fish" },
{ value: "powershell", label: "PowerShell" },
{ value: "cmd", label: "cmd" },
];
/** The shell a platform's terminal opens by default */
export function defaultShell(osType: string | null | undefined): TerminalShell {
return osType === "windows" ? "powershell" : "posix";
}
/**
* The variables that send one terminal's traffic through the proxy on `port` and trust its CA
* at `caPath`, for tools that read neither the system proxy nor the login keychain: Node,
* Python, and anything built on OpenSSL.
*/
export function environmentVars(port: number, caPath: string): [string, string][] {
const proxy = `http://127.0.0.1:${port}`;
return [
["HTTP_PROXY", proxy],
["HTTPS_PROXY", proxy],
// curl reads only the lowercase name for plain HTTP.
["http_proxy", proxy],
["https_proxy", proxy],
["SSL_CERT_FILE", caPath],
["NODE_EXTRA_CA_CERTS", caPath],
["REQUESTS_CA_BUNDLE", caPath],
];
}
/** The variables as `shell` sets them, one a line */
export function environmentBlock(shell: TerminalShell, port: number, caPath: string): string {
return environmentVars(port, caPath)
.map(([name, value]) => setLine(shell, name, value))
.join("\n");
}
function setLine(shell: TerminalShell, name: string, value: string): string {
switch (shell) {
case "posix":
return `export ${name}=${SAFE.test(value) ? value : shellQuote(value)}`;
case "fish":
return `set -gx ${name} ${fishQuote(value)}`;
case "powershell":
return `$env:${name} = '${value.replaceAll("'", "''")}'`;
case "cmd":
// The quotes around the pair keep spaces and stop at the closing one, unlike `set A="b"`
return `set "${name}=${value}"`;
}
}
/** Needs no quotes in any POSIX shell or fish */
const SAFE = /^[\w@%+=:,./-]+$/;
/** Fish quotes like the POSIX shells, except a backslash and a quote escape inside single quotes */
function fishQuote(value: string): string {
if (SAFE.test(value)) return value;
return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
}
/** Shell exports for bash and zsh, as the palette and Settings copy them */
export function environmentExports(port: number, caPath: string): string {
return environmentBlock("posix", port, caPath);
}
+107
View File
@@ -0,0 +1,107 @@
import { describe, expect, test } from "vite-plus/test";
import {
applyFromOutside,
isUnapplied,
pressEnter,
pressEscape,
type Recall,
stepHistory,
} from "./filterBox";
describe("the draft and the applied filter", () => {
test("Enter applies the draft, and keeps it unless it is blank", () => {
expect(pressEnter({ draft: "@status:>=400 ", applied: "" })).toEqual({
draft: "@status:>=400 ",
apply: "@status:>=400",
record: true,
});
expect(pressEnter({ draft: " ", applied: "stripe" })).toEqual({
draft: " ",
apply: "",
record: false,
});
});
test("a draft is unapplied while it differs from the filter, spaces aside", () => {
expect(isUnapplied({ draft: "stripe", applied: "" })).toBe(true);
expect(isUnapplied({ draft: "", applied: "stripe" })).toBe(true);
expect(isUnapplied({ draft: "stripe ", applied: "stripe" })).toBe(false);
expect(isUnapplied({ draft: "", applied: "" })).toBe(false);
});
test("Escape over an unapplied draft puts the applied filter back", () => {
expect(pressEscape({ draft: "@host:x", applied: "stripe" })).toEqual({
draft: "stripe",
apply: null,
record: false,
});
expect(pressEscape({ draft: "@host:x", applied: "" })).toEqual({
draft: "",
apply: null,
record: false,
});
});
test("Escape with nothing unapplied clears the filter and applies", () => {
expect(pressEscape({ draft: "stripe", applied: "stripe" })).toEqual({
draft: "",
apply: "",
record: false,
});
});
test("Escape in an empty box is left to anything else", () => {
expect(pressEscape({ draft: "", applied: "" })).toBeNull();
});
test("a filter set from outside the box applies at once, unrecorded", () => {
expect(applyFromOutside("@host:api.stripe.com")).toEqual({
draft: "@host:api.stripe.com",
apply: "@host:api.stripe.com",
record: false,
});
});
});
describe("stepping through the filter history", () => {
const history = ["newest", "middle", "oldest"];
function steps(keys: ("up" | "down")[], draft = ""): (string | null)[] {
let recall: Recall | null = null;
let text = draft;
return keys.map((key) => {
const next = stepHistory(history, recall, text, key);
if (next == null) return null;
recall = next.recall;
text = next.draft;
return text;
});
}
test("Up from an empty box goes back through it, and stays at the oldest", () => {
expect(steps(["up", "up", "up", "up"])).toEqual(["newest", "middle", "oldest", "oldest"]);
});
test("Down steps forward, then empties the box", () => {
expect(steps(["up", "up", "down", "down", "down"])).toEqual([
"newest",
"middle",
"newest",
"",
null,
]);
});
test("is not for a box with text of its own, or Down first", () => {
expect(steps(["up"], "stripe")).toEqual([null]);
expect(steps(["down"])).toEqual([null]);
expect(stepHistory([], null, "", "up")).toBeNull();
});
test("typing over a recalled filter ends the stepping", () => {
const first = stepHistory(history, null, "", "up");
expect(first?.draft).toBe("newest");
expect(stepHistory(history, first?.recall ?? null, "newest @x", "up")).toBeNull();
expect(stepHistory(history, first?.recall ?? null, "newest @x", "down")).toBeNull();
});
});
+76
View File
@@ -0,0 +1,76 @@
/**
* The search box composes a filter, then applies it, as Yaak's URL bar composes a request: the
* draft is what the box holds, the applied filter what the list shows.
*/
export interface FilterBox {
draft: string;
applied: string;
}
/** What a key does to the box: its text from now, and a filter to apply, or null for none */
export interface BoxStep {
draft: string;
apply: string | null;
/** Applied with Enter, so kept in the filter history */
record: boolean;
}
/** The draft differs from what is applied, so Enter has something to do */
export function isUnapplied(box: FilterBox): boolean {
return box.draft.trim() !== box.applied.trim();
}
/** Enter applies the draft, kept in the history unless it is blank */
export function pressEnter(box: FilterBox): BoxStep {
const apply = box.draft.trim();
return { draft: box.draft, apply, record: apply !== "" };
}
/**
* Escape puts the applied filter back over an unapplied draft; with nothing unapplied, it clears
* the filter. Null when it has nothing to do, so the key goes on to whatever else wants it.
*/
export function pressEscape(box: FilterBox): BoxStep | null {
if (isUnapplied(box)) return { draft: box.applied, apply: null, record: false };
if (box.applied.trim() !== "") return { draft: "", apply: "", record: false };
return null;
}
/** Something outside the box sets the filter, applying it at once */
export function applyFromOutside(text: string): BoxStep {
return { draft: text, apply: text, record: false };
}
/**
* Where Up and Down are in the filter history: `index` into it, newest first, and the text it
* put in the box, so typing over it ends the stepping
*/
export interface Recall {
index: number;
text: string;
}
/**
* Up in an empty box puts the latest filter applied in it, and each Up after an older one; Down
* steps back toward the newest, then empties the box. Null when the key is not for stepping:
* the box holds text of its own, or there is nowhere to go.
*/
export function stepHistory(
history: string[],
recall: Recall | null,
draft: string,
key: "up" | "down",
): { recall: Recall | null; draft: string } | null {
const stepping = recall != null && recall.text === draft;
if (!stepping) {
if (key === "down" || draft !== "") return null;
const first = history[0];
return first == null ? null : { recall: { index: 0, text: first }, draft: first };
}
const index = recall.index + (key === "up" ? 1 : -1);
if (index < 0) return { recall: null, draft: "" };
const text = history[index];
// At the oldest, Up stays put.
if (text == null) return { recall, draft };
return { recall: { index, text }, draft: text };
}
+45
View File
@@ -0,0 +1,45 @@
import { describe, expect, test } from "vite-plus/test";
import { decryptStep, setupIncomplete } from "./firstRun";
describe("setupIncomplete", () => {
const done = { trusted: true, systemProxySupported: true, systemProxyEverOn: true };
test("is incomplete while the certificate is untrusted", () => {
expect(setupIncomplete({ ...done, trusted: false })).toBe(true);
});
test("is incomplete until the system proxy has been on once", () => {
expect(setupIncomplete({ ...done, systemProxyEverOn: false })).toBe(true);
expect(setupIncomplete(done)).toBe(false);
});
test("needs no system proxy where there is none", () => {
expect(
setupIncomplete({ ...done, systemProxySupported: false, systemProxyEverOn: false }),
).toBe(false);
expect(setupIncomplete({ ...done, systemProxySupported: false, trusted: false })).toBe(true);
});
test("waits for both to be read, so the card does not flash", () => {
expect(setupIncomplete({ ...done, trusted: null })).toBe(false);
expect(setupIncomplete({ ...done, systemProxySupported: null, trusted: false })).toBe(false);
});
});
describe("decryptStep", () => {
const builtIns = [{ entry: "!host:*.apple.com", builtIn: true }];
test("picks hosts as they appear by default, after the certificate", () => {
expect(decryptStep(builtIns, false)).toEqual({ choice: "pick", state: "todo" });
expect(decryptStep(builtIns, true)).toEqual({ choice: "pick", state: "next" });
});
test("is done once everything, or a host, is on the list", () => {
const everything = [{ entry: "*", builtIn: false }, ...builtIns];
expect(decryptStep(everything, true)).toEqual({ choice: "everything", state: "done" });
const host = [{ entry: "host:api.example.com", builtIn: false }];
expect(decryptStep(host, true)).toEqual({ choice: "pick", state: "done" });
// An exclusion alone decrypts nothing.
expect(decryptStep([{ entry: "!host:a.com", builtIn: false }], true).state).toBe("next");
});
});
+42
View File
@@ -0,0 +1,42 @@
import type { DecryptListEntry } from "@yaakapp-internal/proxy-lib";
import { decryptsEverything } from "./decrypt";
/** What decides whether setup is done, as the app last read it */
export interface SetupState {
/** The certificate is trusted, or null until read */
trusted: boolean | null;
/** The system proxy can be set on this platform, or null until read */
systemProxySupported: boolean | null;
/** The system proxy has been on at some point since this install */
systemProxyEverOn: boolean;
}
/**
* The first-run card shows while setup is incomplete: the certificate untrusted, or the system
* proxy never on since this install, where there is one. Not while either is still being read,
* so the card does not flash. Once setup is done an empty list is the "no flows yet" state,
* after a Clear too.
*/
export function setupIncomplete(s: SetupState): boolean {
if (s.trusted == null || s.systemProxySupported == null) return false;
if (!s.trusted) return true;
return s.systemProxySupported && !s.systemProxyEverOn;
}
/** The first-run card's "Choose what to decrypt" step, as the decrypt list has it */
export interface DecryptStep {
/** Everything is decrypted, `*` on the list; else hosts are picked as they appear */
choice: "everything" | "pick";
state: "todo" | "next" | "done";
}
/**
* Picking hosts as they appear is the default and needs nothing done, so the step waits on the
* certificate like the others and is done once a choice is on the list: everything, or any host
* or app picked already.
*/
export function decryptStep(list: DecryptListEntry[], trusted: boolean): DecryptStep {
const choice = decryptsEverything(list) ? "everything" : "pick";
const picked = list.some((e) => !e.builtIn && !e.entry.startsWith("!"));
return { choice, state: picked ? "done" : trusted ? "next" : "todo" };
}
+61 -2
View File
@@ -2,11 +2,14 @@ import type { ExportHarRequest, Flow, FlowBody } from "@yaakapp-internal/proxy-l
import type { DropdownItem } from "@yaakapp-internal/ui";
import { save } from "@tauri-apps/plugin-dialog";
import { formatSize } from "@yaakapp-internal/lib/formatSize";
import { atom, useSetAtom } from "jotai";
import { useCallback } from "react";
import { atom, useAtomValue, useSetAtom } from "jotai";
import { useCallback, useEffect } from "react";
import { base64ToBytes, bodyFileName } from "./body";
import { curlBodyText, toCurl } from "./curl";
import type { FlowQuery } from "./query";
import { rpc } from "./rpc";
import { activeQueryAtom, lockedAtom } from "./store";
import { subscribe } from "./tauri";
import { useShowToast } from "./toast";
/** The flow the save dialog is open for */
@@ -60,6 +63,62 @@ export async function exportHar(
return rpc("export_har", { ...req, path });
}
/** Exports every flow `query` covers, or all of them, as HAR, saying how many it wrote */
function useExportHarOf(): (query: FlowQuery | null) => Promise<void> {
const showToast = useShowToast();
return useCallback(
async (query: FlowQuery | null) => {
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" });
}
},
[showToast],
);
}
/**
* Exporting every flow the list covers as HAR, all of them or the search's, for the list's and
* the search box's menus: it acts on flows, so it lives where they are chosen.
*/
export function useExportShownHar(): () => DropdownItem {
const exportOf = useExportHarOf();
const query = useAtomValue(activeQueryAtom);
// Nothing can be read to export while captured traffic is locked.
const locked = useAtomValue(lockedAtom) != null;
return useCallback(
() => ({
label: query == null ? "Export All Flows as HAR" : "Export Matching Flows as HAR",
icon: "download",
disabled: locked,
onSelect: () => exportOf(query),
}),
[query, locked, exportOf],
);
}
/** File's Export All Flows as HAR, which the app menu sends as an event */
export function useMenuExportHar() {
const exportOf = useExportHarOf();
const locked = useAtomValue(lockedAtom) != null;
useEffect(
() =>
subscribe<null>(MENU_EXPORT_HAR_EVENT, () => {
if (!locked) void exportOf(null);
}),
[exportOf, locked],
);
}
/** `EXPORT_HAR_EVENT` in the app's `window_menu.rs` */
const MENU_EXPORT_HAR_EVENT = "menu_export_har";
/** What a flow's context menu and the detail pane's menu offer */
export function useFlowActions(): (flow: Flow) => DropdownItem[] {
const showToast = useShowToast();
+17
View File
@@ -19,6 +19,7 @@ import {
const flow: Flow = {
id: "fl_1",
number: 1,
createdAt: "2026-11-04T22:10:00Z",
updatedAt: "2026-11-04T22:10:01Z",
startedAt: "2026-11-04T22:10:00Z",
@@ -50,6 +51,22 @@ const flow: Flow = {
clientName: null,
clientBundleId: null,
clientPath: null,
clientCwd: null,
streamKind: null,
messageCount: 0,
grpcService: null,
grpcMethod: null,
grpcStatus: null,
grpcMessage: null,
graphqlOperation: null,
tunnelled: false,
agentRead: false,
clientAddr: null,
elapsedConnectMs: null,
elapsedTlsMs: null,
elapsedRequestMs: null,
upstreamTlsVersion: null,
upstreamTlsCipher: null,
};
function bytes(text: string): FlowBodyData {
+18 -3
View File
@@ -15,7 +15,7 @@ import {
type HttpResponseView,
} from "@yaakapp-internal/ui/httpTypes";
import { useEffect, useState } from "react";
import { base64ToBytes, bytesToText, findHeader, mimeEssence } from "./body";
import { base64ToBytes, bodyAsText, findHeader, mimeEssence } from "./body";
import { statusReason } from "./statusReason";
/** A captured body as the engine's body RPC returns it, decoded */
@@ -32,7 +32,8 @@ export function flowBodyFromRpc(res: GetFlowBodyResponse): FlowBodyData {
/** A captured request as the shared request pane shows it, read-only */
export function flowRequestToView(flow: Flow, body: FlowBodyData | null): HttpRequestView {
const contentType = findHeader(flow.requestHeaders, "content-type");
const text = body == null ? null : bytesToText(body.bytes, body.truncated);
// In its declared charset, as the response viewers read text
const text = body == null ? null : bodyAsText(body.bytes, body.truncated, contentType);
const { bodyType, body: bodyView } = requestBodyView(contentType, body, text);
return {
@@ -84,7 +85,18 @@ export function flowResponseToView(
): HttpResponseView | null {
const ended = flow.elapsedMs != null || flow.error != null || flow.cancelled;
if (flow.status == null && !ended) return null;
return responseView(flow, body, ended);
}
/**
* A flow as the shared cookie lists read it, whether or not a response came: the request
* half's Cookies tab shows what was sent before anything was received.
*/
export function flowCookiesView(flow: Flow): HttpResponseView {
return responseView(flow, null, flow.elapsedMs != null || flow.error != null || flow.cancelled);
}
function responseView(flow: Flow, body: FlowBodyData | null, ended: boolean): HttpResponseView {
const encoding = findHeader(flow.responseHeaders, "content-encoding")?.trim().toLowerCase();
const encoded = encoding != null && encoding !== "" && encoding !== "identity";
@@ -133,7 +145,10 @@ export function flowBodyLoader({
return {
useText: () => {
const body = useBody();
return { ...body, data: mapData(body, (b) => bytesToText(b.bytes, b.truncated)) };
return {
...body,
data: mapData(body, (b) => bodyAsText(b.bytes, b.truncated, contentType)),
};
},
useBytes: () => {
const body = useBody();
+26 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vite-plus/test";
import { countNewFlows } from "./follow";
import { countNewFlows, isAtEnd, resumesFollowing } from "./follow";
const at = (...times: string[]) => times.map((t) => ({ startedAt: `2026-10-26T10:00:${t}` }));
@@ -26,3 +26,28 @@ describe("countNewFlows", () => {
expect(countNewFlows(at("03", "03.25"), "2026-10-26T10:00:03.2")).toBe(1);
});
});
describe("resumesFollowing", () => {
const fits = { scrollHeight: 300, scrollTop: 0, clientHeight: 300 };
const scrolledUp = { scrollHeight: 3000, scrollTop: 1200, clientHeight: 300 };
const atBottom = { scrollHeight: 3000, scrollTop: 2700, clientHeight: 300 };
test("follows again when the list fits its viewport, so it never shows new flows as unseen", () => {
expect(isAtEnd(fits)).toBe(true);
expect(resumesFollowing({ following: false, sorted: false, el: fits })).toBe(true);
});
test("follows again at the end of a list that overflows", () => {
expect(resumesFollowing({ following: false, sorted: false, el: atBottom })).toBe(true);
});
test("stays held while scrolled up in a list that overflows", () => {
expect(isAtEnd(scrolledUp)).toBe(false);
expect(resumesFollowing({ following: false, sorted: false, el: scrolledUp })).toBe(false);
});
test("never follows while sorted, and has nothing to do while following", () => {
expect(resumesFollowing({ following: false, sorted: true, el: fits })).toBe(false);
expect(resumesFollowing({ following: true, sorted: false, el: fits })).toBe(false);
});
});
+25
View File
@@ -1,5 +1,30 @@
import type { Flow } from "@yaakapp-internal/proxy-lib";
/** Where a list's scroll is, as its element reports it */
export interface ScrollPosition {
scrollHeight: number;
scrollTop: number;
clientHeight: number;
}
/** The list is scrolled to its end, or fits its viewport and has no scroll at all */
export function isAtEnd(el: ScrollPosition): boolean {
return el.scrollHeight - el.scrollTop - el.clientHeight < 2;
}
/**
* A held list follows new traffic again once it is at its end, unless it is sorted: after a
* scroll there, or after its flows, filter or size change leave it there, as a list that fits its
* viewport always is. One scrolled up in a list that overflows stays held.
*/
export function resumesFollowing(state: {
following: boolean;
sorted: boolean;
el: ScrollPosition;
}): boolean {
return !state.following && !state.sorted && isAtEnd(state.el);
}
/**
* Flows in the list that started after the list was held. `heldAt` is the start of the newest
* flow across all traffic at that moment, or null when there was none, so it still holds when
Loaded 100 of 326 files, more files were not shown because too many files have changed in this diff. Show more