From 69b7c9921cf09b5a2bae3db255b5a3340c38c713 Mon Sep 17 00:00:00 2001 From: Gregory Schier Date: Tue, 10 Nov 2026 14:15:52 -0700 Subject: [PATCH] Keep Workspace Settings and Delete usable when a workspace's meta is missing (#834) Co-authored-by: Claude Opus 5.5 --- Cargo.lock | 1 + .../WorkspaceSettingsDialog.test.tsx | 177 ++++++++++++++++++ .../components/WorkspaceSettingsDialog.tsx | 78 ++++++-- crates/yaak-commands/Cargo.toml | 1 + crates/yaak-commands/tests/test_host.rs | 107 ++++++++++- 5 files changed, 346 insertions(+), 18 deletions(-) create mode 100644 apps/yaak-client/components/WorkspaceSettingsDialog.test.tsx diff --git a/Cargo.lock b/Cargo.lock index 979e3c573..2ba6a2725 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11577,6 +11577,7 @@ dependencies = [ name = "yaak-commands" version = "0.0.0" dependencies = [ + "rusqlite", "serde_json", "tempfile", "thiserror 2.0.21", diff --git a/apps/yaak-client/components/WorkspaceSettingsDialog.test.tsx b/apps/yaak-client/components/WorkspaceSettingsDialog.test.tsx new file mode 100644 index 000000000..17a437d6c --- /dev/null +++ b/apps/yaak-client/components/WorkspaceSettingsDialog.test.tsx @@ -0,0 +1,177 @@ +// @vitest-environment happy-dom +import type { Workspace, WorkspaceMeta } from "@yaakapp-internal/models"; +import { workspaceMetasAtom } from "@yaakapp-internal/models"; +import { getDefaultStore, type PrimitiveAtom } from "jotai"; +import { act, type ReactNode } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, test, vi } from "vite-plus/test"; +import { WorkspaceSettingsDialog } from "./WorkspaceSettingsDialog"; + +const mocks = vi.hoisted(() => ({ + rpc: vi.fn<(cmd: string, payload: unknown) => Promise>(), + mergeModelsInStore: vi.fn(), + deleteModelWithConfirm: vi.fn<(model: unknown) => Promise>(), + workspace: { + id: "wk_test", + model: "workspace", + name: "Broken", + settingDnsOverrides: [], + } as unknown as Workspace, + workspaceMeta: { + id: "wm_test", + model: "workspace_meta", + workspaceId: "wk_test", + settingSyncDir: "/sync/broken", + encryptionKey: null, + } as WorkspaceMeta, +})); +const { workspace, workspaceMeta } = mocks; + +vi.mock("@yaakapp-internal/models", async () => { + const { atom } = await import("jotai"); + return { + workspacesAtom: atom([mocks.workspace]), + // Starts empty in each test: the workspace failed to load, so the store has no meta for it + workspaceMetasAtom: atom([]), + mergeModelsInStore: mocks.mergeModelsInStore, + patchModel: vi.fn(), + }; +}); +vi.mock("@yaakapp-internal/ui", () => ({ + Banner: ({ children }: { children: ReactNode }) =>
{children}
, + CountBadge: () => null, + HStack: ({ children }: { children: ReactNode }) =>
{children}
, + InlineCode: ({ children }: { children: ReactNode }) => {children}, +})); +vi.mock("../hooks/useAuthTab", () => ({ useAuthTab: () => [] })); +vi.mock("../hooks/useHeadersTab", () => ({ useHeadersTab: () => [] })); +vi.mock("../hooks/useInheritedHeaders", () => ({ useInheritedHeaders: () => [] })); +vi.mock("../lib/deleteModelWithConfirm", () => ({ + deleteModelWithConfirm: mocks.deleteModelWithConfirm, +})); +vi.mock("../lib/dialog", () => ({ showDialog: vi.fn() })); +vi.mock("../lib/router", () => ({ router: { navigate: vi.fn() } })); +vi.mock("../lib/rpc", () => ({ rpc: mocks.rpc })); +vi.mock("./CopyIconButton", () => ({ CopyIconButton: () => null })); +vi.mock("./core/Button", () => ({ + Button: ({ children, onClick }: { children: ReactNode; onClick: () => void }) => ( + + ), +})); +vi.mock("./core/PlainInput", () => ({ + PlainInput: ({ label, defaultValue }: { label: string; defaultValue: string }) => ( + + ), +})); +vi.mock("./core/SettingRow", () => ({ + SettingsList: ({ children }: { children: ReactNode }) =>
{children}
, + SettingsSection: ({ children }: { children: ReactNode }) =>
{children}
, +})); +// Render every tab at once so the test can see all of them +vi.mock("./core/Tabs/Tabs", () => ({ + Tabs: ({ children }: { children: ReactNode }) =>
{children}
, + TabContent: ({ children, value }: { children: ReactNode; value: string }) => ( +
{children}
+ ), +})); +vi.mock("./DnsOverridesEditor", () => ({ DnsOverridesEditor: () => null })); +vi.mock("./HeadersEditor", () => ({ HeadersEditor: () => null })); +vi.mock("./HttpAuthenticationEditor", () => ({ HttpAuthenticationEditor: () => null })); +vi.mock("./MarkdownEditor", () => ({ MarkdownEditor: () => null })); +vi.mock("./ModelSettingsEditor", () => ({ ModelSettingsEditor: () => null })); +vi.mock("./SyncToFilesystemSetting", () => ({ + SyncToFilesystemSetting: ({ value }: { value: { filePath: string | null } }) => ( +
{value.filePath}
+ ), +})); +vi.mock("./WorkspaceEncryptionSetting", () => ({ + WorkspaceEncryptionSetting: () =>
, +})); + +let root: Root; +let host: HTMLDivElement; +beforeEach(() => { + vi.clearAllMocks(); + // Behave like the real store: merged models land in the atom the dialog reads + const store = getDefaultStore(); + const metasAtom = workspaceMetasAtom as unknown as PrimitiveAtom; + store.set(metasAtom, []); + mocks.mergeModelsInStore.mockImplementation((_model: string, models: WorkspaceMeta[]) => + store.set(metasAtom, (prev) => [...prev, ...models]), + ); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +async function render() { + await act(async () => + root.render( {}} />), + ); +} + +function tab(value: string) { + const el = host.querySelector(`[data-tab="${value}"]`); + if (el == null) throw new Error(`No ${value} tab`); + return el; +} + +function deleteButton() { + return Array.from(host.querySelectorAll("button")).find( + (b) => b.textContent === "Delete Workspace", + ); +} + +test("a workspace with no meta in the store still offers Delete", async () => { + mocks.rpc.mockReturnValue(new Promise(() => {})); + mocks.deleteModelWithConfirm.mockResolvedValue(false); + await render(); + + expect(host.textContent).not.toContain("not found"); + const button = deleteButton(); + expect(button).toBeDefined(); + + await act(async () => button?.click()); + expect(mocks.deleteModelWithConfirm).toHaveBeenCalledWith(workspace, { confirmName: "Broken" }); +}); + +test("a missing meta is fetched, put in the store, and its settings rendered", async () => { + mocks.rpc.mockResolvedValue(workspaceMeta); + await render(); + + expect(mocks.rpc).toHaveBeenCalledWith("cmd_get_workspace_meta", { workspaceId: "wk_test" }); + expect(mocks.mergeModelsInStore).toHaveBeenCalledWith("workspace_meta", [workspaceMeta]); + + const settings = tab("settings"); + expect(settings.querySelector('[data-testid="sync-setting"]')?.textContent).toBe("/sync/broken"); + expect(settings.querySelector('[data-testid="encryption-setting"]')).not.toBeNull(); + expect(host.querySelector('[role="alert"]')).toBeNull(); +}); + +test("a meta that cannot be loaded shows the error only where sync and encryption go", async () => { + mocks.rpc.mockRejectedValue("database is locked"); + await render(); + + // The error is the one banner, inside the Settings tab, in place of sync and encryption + const banners = host.querySelectorAll('[role="alert"]'); + expect(banners).toHaveLength(1); + expect(tab("settings").contains(banners[0] ?? null)).toBe(true); + expect(banners[0]?.textContent).toContain("database is locked"); + expect(host.querySelector('[data-testid="sync-setting"]')).toBeNull(); + expect(host.querySelector('[data-testid="encryption-setting"]')).toBeNull(); + expect(mocks.mergeModelsInStore).not.toHaveBeenCalled(); + + // The workspace's own settings and Delete still render + const general = tab("general"); + expect(general.querySelector('input[aria-label="Name"]')?.value).toBe("Broken"); + expect(general.contains(deleteButton() ?? null)).toBe(true); +}); diff --git a/apps/yaak-client/components/WorkspaceSettingsDialog.tsx b/apps/yaak-client/components/WorkspaceSettingsDialog.tsx index a0cddc2af..b40763524 100644 --- a/apps/yaak-client/components/WorkspaceSettingsDialog.tsx +++ b/apps/yaak-client/components/WorkspaceSettingsDialog.tsx @@ -1,12 +1,20 @@ -import { patchModel, workspaceMetasAtom, workspacesAtom } from "@yaakapp-internal/models"; +import type { WorkspaceMeta } from "@yaakapp-internal/models"; +import { + mergeModelsInStore, + patchModel, + workspaceMetasAtom, + workspacesAtom, +} from "@yaakapp-internal/models"; import { Banner, HStack, InlineCode, CountBadge } from "@yaakapp-internal/ui"; import { useAtomValue } from "jotai"; +import { useEffect, useState } from "react"; import { useAuthTab } from "../hooks/useAuthTab"; import { useHeadersTab } from "../hooks/useHeadersTab"; import { useInheritedHeaders } from "../hooks/useInheritedHeaders"; import { deleteModelWithConfirm } from "../lib/deleteModelWithConfirm"; import { showDialog } from "../lib/dialog"; import { router } from "../lib/router"; +import { rpc } from "../lib/rpc"; import { CopyIconButton } from "./CopyIconButton"; import { Button } from "./core/Button"; import { PlainInput } from "./core/PlainInput"; @@ -47,6 +55,10 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) { const authTab = useAuthTab(TAB_AUTH, workspace ?? null); const headersTab = useHeadersTab(TAB_HEADERS, workspace ?? null); const inheritedHeaders = useInheritedHeaders(workspace ?? null); + const workspaceMetaError = useEnsureWorkspaceMeta( + workspaceId, + workspace != null && workspaceMeta == null, + ); if (workspace == null) { return ( @@ -56,13 +68,6 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) { ); } - if (workspaceMeta == null) - return ( - - WorkspaceMeta not found for workspace - - ); - return ( - patchModel(workspaceMeta, { settingSyncDir: filePath })} - /> -
- -
+ {workspaceMeta != null ? ( + <> + + patchModel(workspaceMeta, { settingSyncDir: filePath }) + } + /> +
+ +
+ + ) : workspaceMetaError != null ? ( + + Sync and encryption settings are unavailable because{" "} + WorkspaceMeta could not be loaded: {workspaceMetaError} + + ) : null}
@@ -177,6 +193,34 @@ export function WorkspaceSettingsDialog({ workspaceId, hide, tab }: Props) { ); } +/** + * The meta row normally reaches the store when the workspace loads, which also creates it if it + * is missing. If that load failed (for example on a corrupt row elsewhere in the workspace), the + * store never gets it, so ask for it directly. Returns the error if that fails too. + */ +function useEnsureWorkspaceMeta(workspaceId: string, missing: boolean): string | null { + const [error, setError] = useState(null); + + useEffect(() => { + if (!missing) return; + let cancelled = false; + setError(null); + rpc("cmd_get_workspace_meta", { workspaceId }).then( + (meta) => { + if (!cancelled) mergeModelsInStore("workspace_meta", [meta]); + }, + (err) => { + if (!cancelled) setError(String(err)); + }, + ); + return () => { + cancelled = true; + }; + }, [workspaceId, missing]); + + return error; +} + WorkspaceSettingsDialog.show = (workspaceId: string, tab?: WorkspaceSettingsTab) => { showDialog({ id: "workspace-settings", diff --git a/crates/yaak-commands/Cargo.toml b/crates/yaak-commands/Cargo.toml index 59d011a66..c5bee4c90 100644 --- a/crates/yaak-commands/Cargo.toml +++ b/crates/yaak-commands/Cargo.toml @@ -17,5 +17,6 @@ yaak-rpc-schema = { workspace = true } yaak-templates = { workspace = true } [dev-dependencies] +rusqlite = "0.38" tempfile = "3" tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } diff --git a/crates/yaak-commands/tests/test_host.rs b/crates/yaak-commands/tests/test_host.rs index de31d9f27..09f7595de 100644 --- a/crates/yaak-commands/tests/test_host.rs +++ b/crates/yaak-commands/tests/test_host.rs @@ -23,7 +23,9 @@ use yaak_commands::{Host, PluginHost}; use yaak_core::WorkspaceContext; use yaak_crypto::manager::EncryptionManager; use yaak_models::blob_manager::BlobManager; -use yaak_models::models::{AnyModel, Environment, EnvironmentVariable, Plugin, Workspace}; +use yaak_models::models::{ + AnyModel, Environment, EnvironmentVariable, HttpRequest, Plugin, Workspace, +}; use yaak_models::query_manager::QueryManager; use yaak_models::util::{ModelPayload, UpdateSource}; use yaak_plugins::events::{ @@ -578,3 +580,106 @@ async fn template_function_values_are_rendered_before_the_host_sees_them() { seen.get("token"), ); } + +impl SingleThreadedHost { + fn new() -> Self { + let TestHost { inner } = TestHost::new(); + Self { + inner: Rc::new(Arc::into_inner(inner).expect("sole owner")), + auth_values: Rc::new(RefCell::new(None)), + fn_values: Rc::new(RefCell::new(None)), + } + } + + /// Change rows behind the app's back, the way a damaged or hand-edited + /// database would. + fn raw_sql(&self, sql: &str, id: &str) { + let conn = + rusqlite::Connection::open(self.inner._dir.path().join("db.sqlite")).expect("open db"); + conn.execute(sql, [id]).expect("raw sql"); + } + + async fn create_workspace(&self) -> String { + let workspace = Workspace { name: "No meta".to_string(), ..Default::default() }; + models_upsert(self.clone(), ModelsUpsertReq { model: AnyModel::Workspace(workspace) }) + .await + .expect("upsert workspace") + } + + async fn delete_workspace(&self, id: &str) { + let workspace = self.db().get_workspace(id).expect("get workspace"); + let deleted = + models_delete(self.clone(), ModelsDeleteReq { model: AnyModel::Workspace(workspace) }) + .await + .expect("delete workspace"); + assert_eq!(deleted, id); + assert!(self.db().get_workspace(id).is_err(), "workspace should be gone"); + } +} + +/// A workspace can exist without its meta row: one written by the CLI, an +/// import or an older version, or one whose row was removed. Opening it is the +/// one place that creates the row, and deleting it never needs the row. +#[tokio::test] +async fn opening_a_workspace_without_a_meta_row_creates_one() { + let host = SingleThreadedHost::new(); + let id = host.create_workspace().await; + assert!(host.db().get_workspace_meta(&id).is_none(), "a new workspace has no meta yet"); + + let open = || { + models_workspace_models( + host.clone(), + ModelsWorkspaceModelsReq { workspace_id: Some(id.clone()) }, + ) + }; + let has_meta = |json: &str| { + let models: Vec = serde_json::from_str(json).expect("parse payload"); + models.iter().any(|m| matches!(m, AnyModel::WorkspaceMeta(m) if m.workspace_id == id)) + }; + + assert!(has_meta(&open().await.expect("open")), "opening should load a created meta"); + + host.raw_sql("DELETE FROM workspace_metas WHERE workspace_id = ?1", &id); + assert!(host.db().get_workspace_meta(&id).is_none()); + assert!(has_meta(&open().await.expect("reopen")), "a removed meta should be recreated"); + + host.raw_sql("DELETE FROM workspace_metas WHERE workspace_id = ?1", &id); + host.delete_workspace(&id).await; +} + +/// When something else in the workspace is damaged, opening it fails and the +/// app never receives the meta. Workspace Settings then asks for the meta on +/// its own, which has to work, and the workspace has to stay deletable. +#[tokio::test] +async fn a_workspace_that_fails_to_open_still_gets_its_meta_and_can_be_deleted() { + let host = SingleThreadedHost::new(); + let id = host.create_workspace().await; + let request = HttpRequest { workspace_id: id.clone(), ..Default::default() }; + let request_id = + models_upsert(host.clone(), ModelsUpsertReq { model: AnyModel::HttpRequest(request) }) + .await + .expect("upsert request"); + host.raw_sql("UPDATE http_requests SET created_at = 'garbage' WHERE id = ?1", &request_id); + + // Reading the damaged row panics rather than returning an error, so run the + // load as its own task and count either as a failed open + let open = models_workspace_models( + host.clone(), + ModelsWorkspaceModelsReq { workspace_id: Some(id.clone()) }, + ); + let opened = tokio::task::LocalSet::new() + .run_until(async { tokio::task::spawn_local(open).await }) + .await; + assert!(!matches!(opened, Ok(Ok(_))), "the damaged request should fail the load"); + + host.raw_sql("DELETE FROM workspace_metas WHERE workspace_id = ?1", &id); + let meta = + cmd_get_workspace_meta(host.clone(), CmdGetWorkspaceMetaReq { workspace_id: id.clone() }) + .await + .expect("workspace meta"); + assert_eq!(meta.workspace_id, id); + assert!(host.db().get_workspace_meta(&id).is_some(), "the meta should have been created"); + + host.raw_sql("DELETE FROM workspace_metas WHERE workspace_id = ?1", &id); + host.delete_workspace(&id).await; +}