Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(settings): keep values changed elsewhere when a settings form saves (#11495)
pseudoyu90935e2e958b
diff --git a/packages/views/agents/components/agent-detail-inspector.profile.test.tsx b/packages/views/agents/components/agent-detail-inspector.profile.test.tsxnew file mode 100644index 0000000000..e672caa6e2--- /dev/null+++ b/packages/views/agents/components/agent-detail-inspector.profile.test.tsx@@ -0,0 +1,98 @@+// @vitest-environment jsdom++import { useState } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, fireEvent, screen } from "@testing-library/react";+import type { Agent } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { AgentDetailInspector } from "./agent-detail-inspector";++vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQuery: () => ({ data: undefined, isSuccess: false }),+}));+vi.mock("../../common/avatar-upload-control", () => ({+ AvatarUploadControl: () => <div data-testid="avatar-upload" />,+}));+vi.mock("./inspector/model-picker", () => ({+ ModelPicker: () => <div data-testid="model-picker" />,+}));+vi.mock("./inspector/runtime-picker", () => ({+ RuntimePicker: () => <div data-testid="runtime-picker" />,+}));+vi.mock("./inspector/thinking-prop-row", () => ({+ ThinkingSettingField: () => <div data-testid="thinking-field" />,+}));+vi.mock("./inspector/service-tier-setting-field", () => ({+ ServiceTierSettingField: () => <div data-testid="service-tier-field" />,+}));++const initial = {+ id: "agent-1",+ workspace_id: "workspace-1",+ name: "Lambda",+ description: "Old description",+ runtime_id: "runtime-1",+ avatar_url: null,+ conversation_starters: [],+ max_concurrent_tasks: 1,+} as unknown as Agent;++let setAgent: (patch: Partial<Agent>) => void;++function renderInspector(onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>) {+ function Harness() {+ const [agent, set] = useState(initial);+ setAgent = (patch) => act(() => set((current) => ({ ...current, ...patch })));+ return (+ <AgentDetailInspector+ agent={agent}+ runtime={null}+ runtimes={[]}+ members={[]}+ currentUserId="user-1"+ canEdit+ onUpdate={onUpdate}+ />+ );+ }+ renderWithI18n(<Harness />);+}++const advance = (ms: number) => act(() => vi.advanceTimersByTimeAsync(ms));++describe("AgentDetailInspector profile", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ });++ it("saves a rename without writing back a description changed elsewhere", async () => {+ const onUpdate = vi.fn(async () => {});+ renderInspector(onUpdate);++ setAgent({ description: "New description" });+ expect(screen.getByLabelText("Description")).toHaveValue("New description");+ fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Mu" } });+ await advance(1000);++ expect(onUpdate).toHaveBeenCalledExactlyOnceWith("agent-1", { name: "Mu" });+ });++ it("keeps the typed name when an optimistic save is rolled back", async () => {+ renderInspector(async (_id, data) => {+ setAgent(data);+ await new Promise((resolve) => setTimeout(resolve, 100));+ setAgent({ name: "Lambda" });+ });++ fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Mu" } });+ await advance(1000);++ expect(screen.getByLabelText("Name")).toHaveValue("Mu");+ });+});diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsxindex ab0bfd8243..831b78de31 100644--- a/packages/views/agents/components/agent-detail-inspector.tsx+++ b/packages/views/agents/components/agent-detail-inspector.tsx@@ -26,6 +26,7 @@ import {type SettingsSaveStatus,} from "../../settings/components/settings-layout";import { useAutoSave } from "../../settings/components/use-auto-save";+import { useEditedValue } from "../../settings/components/use-edited-value";import { useT } from "../../i18n";import { CharCounter } from "./char-counter";import { ConversationStartersEditor } from "./conversation-starters-editor";@@ -93,15 +94,15 @@ export function AgentDetailInspector({[agent.id, onUpdate],);- const [name, setName] = useState(agent.name);- const [description, setDescription] = useState(agent.description ?? "");+ const nameField = useEditedValue(agent.name, agent.id);+ const descriptionField = useEditedValue(agent.description ?? "", agent.id);+ const name = nameField.value;+ const description = descriptionField.value;const [starters, setStarters] = useState<AgentConversationStarter[]>(agent.conversation_starters ?? [],);useEffect(() => {- setName(agent.name);- setDescription(agent.description ?? "");setStarters(agent.conversation_starters ?? []);// Reset only when moving to another agent. Cache updates from this form// must not erase a newer local draft while an autosave is in flight.@@ -121,9 +122,16 @@ export function AgentDetailInspector({);const saveProfile = useCallback(async (next: ProfileDraft) => {- await update({ name: next.name, description: next.description });+ // Send only what was edited here, so the rest keeps changes made elsewhere.+ const changes: Partial<ProfileDraft> = {};+ if (nameField.edited) changes.name = next.name;+ if (descriptionField.edited) changes.description = next.description;+ if (Object.keys(changes).length === 0) return;+ await update(changes);+ nameField.markSaved(next.name);+ descriptionField.markSaved(next.description);},- [update],+ [descriptionField, nameField, update],);const profileAutoSave = useAutoSave({value: profileDraft,@@ -217,7 +225,7 @@ export function AgentDetailInspector({autoComplete="off"aria-label={t(($) => $.inspector.name_label)}value={name}- onChange={(event) => setName(event.target.value)}+ onChange={(event) => nameField.edit(event.target.value)}onBlur={profileAutoSave.flush}disabled={!canEdit}aria-invalid={nameInvalid || undefined}@@ -241,7 +249,7 @@ export function AgentDetailInspector({autoComplete="off"aria-label={t(($) => $.inspector.description_label)}value={description}- onChange={(event) => setDescription(event.target.value)}+ onChange={(event) => descriptionField.edit(event.target.value)}onBlur={profileAutoSave.flush}disabled={!canEdit}rows={5}diff --git a/packages/views/settings/components/use-edited-value.ts b/packages/views/settings/components/use-edited-value.tsnew file mode 100644index 0000000000..a7f942f1e1--- /dev/null+++ b/packages/views/settings/components/use-edited-value.ts@@ -0,0 +1,37 @@+"use client";++import { useCallback, useEffect, useState } from "react";++interface EditedValue {+ value: string;+ edited: boolean;+ edit: (value: string) => void;+ markSaved: (value: string) => void;+}++/**+ * A form field that follows the saved value until the user edits it, so a form+ * left open neither shows nor writes back a value changed elsewhere. An edit+ * ends when its own save has succeeded and the saved value has caught up:+ * an optimistic value that is rolled back must not take the typed text with it.+ */+export function useEditedValue(savedValue: string, resetKey: string | undefined): EditedValue {+ const [draft, setDraft] = useState<{ value: string; saved: boolean } | null>(null);++ useEffect(() => {+ setDraft(null);+ }, [resetKey]);++ useEffect(() => {+ if (draft?.saved && draft.value === savedValue) setDraft(null);+ }, [draft, savedValue]);++ const edit = useCallback((value: string) => setDraft({ value, saved: false }), []);+ const markSaved = useCallback((value: string) => {+ setDraft((current) =>+ current?.value === value ? { value, saved: true } : current,+ );+ }, []);++ return { value: draft ? draft.value : savedValue, edited: draft !== null, edit, markSaved };+}diff --git a/packages/views/settings/components/workspace-tab.test.tsx b/packages/views/settings/components/workspace-tab.test.tsxindex 908565ca2d..8d7bb2b8b5 100644--- a/packages/views/settings/components/workspace-tab.test.tsx+++ b/packages/views/settings/components/workspace-tab.test.tsx@@ -161,8 +161,6 @@ describe("WorkspaceTab — automatic updates", () => {await waitFor(() => {expect(mockUpdateWorkspace).toHaveBeenCalledWith("workspace-1", {name: "Renamed Workspace",- description: "",- context: "",});});// The inline save state reports success; a toast would repeat it.@@ -170,6 +168,57 @@ describe("WorkspaceTab — automatic updates", () => {expect(mockInvalidateQueries).not.toHaveBeenCalled();});+ it("shows a context changed elsewhere and does not write the old one back", async () => {+ const user = setupUser();+ workspaceRef.current = { ...workspaceRef.current, context: "old context" };+ const { rerender } = render(<WorkspaceTab />, { wrapper: I18nWrapper });+ expect(screen.getByDisplayValue("old context")).toBeInTheDocument();++ workspaceRef.current = { ...workspaceRef.current, context: "new context" };+ rerender(<WorkspaceTab />);+ const contextInput = screen.getByDisplayValue("new context");+ await user.click(contextInput);+ await user.tab();+ await vi.advanceTimersByTimeAsync(1000);++ expect(mockUpdateWorkspace).not.toHaveBeenCalled();+ });++ it("keeps an unsaved edit when the same field changes elsewhere", async () => {+ const user = setupUser();+ const { rerender } = render(<WorkspaceTab />, { wrapper: I18nWrapper });+ const nameInput = screen.getByDisplayValue("Test Workspace");+ await user.type(nameInput, " mine");++ workspaceRef.current = { ...workspaceRef.current, name: "Theirs", context: "new context" };+ rerender(<WorkspaceTab />);+ expect(nameInput).toHaveValue("Test Workspace mine");+ await user.tab();++ await waitFor(() => {+ expect(mockUpdateWorkspace).toHaveBeenCalledExactlyOnceWith("workspace-1", {+ name: "Test Workspace mine",+ });+ });+ });++ it("follows later changes to a field again once its own edit is saved", async () => {+ const user = setupUser();+ const { rerender } = render(<WorkspaceTab />, { wrapper: I18nWrapper });+ const nameInput = screen.getByDisplayValue("Test Workspace");+ await user.type(nameInput, " mine");+ await user.tab();+ await waitFor(() => expect(mockUpdateWorkspace).toHaveBeenCalledOnce());+ workspaceRef.current = { ...workspaceRef.current, name: "Test Workspace mine" };+ rerender(<WorkspaceTab />);+ await vi.advanceTimersByTimeAsync(0);++ workspaceRef.current = { ...workspaceRef.current, name: "Theirs" };+ rerender(<WorkspaceTab />);++ expect(nameInput).toHaveValue("Theirs");+ });+it("changes the prefix only from its own dialog, after previewing the result", async () => {const user = setupUser();render(<WorkspaceTab />, { wrapper: I18nWrapper });diff --git a/packages/views/settings/components/workspace-tab.tsx b/packages/views/settings/components/workspace-tab.tsxindex b6efa8a8a5..1d8c308d88 100644--- a/packages/views/settings/components/workspace-tab.tsx+++ b/packages/views/settings/components/workspace-tab.tsx@@ -59,6 +59,7 @@ import {type SettingsSaveStatus,} from "./settings-layout";import { useAutoSave } from "./use-auto-save";+import { useEditedValue } from "./use-edited-value";interface WorkspaceDetailsDraft {name: string;@@ -140,9 +141,12 @@ export function WorkspaceTab() {navigation.push(resolvePostAuthDestination(remaining, hasOnboarded));};- const [name, setName] = useState(workspace?.name ?? "");- const [description, setDescription] = useState(workspace?.description ?? "");- const [context, setContext] = useState(workspace?.context ?? "");+ const nameField = useEditedValue(workspace?.name ?? "", workspace?.id);+ const descriptionField = useEditedValue(workspace?.description ?? "", workspace?.id);+ const contextField = useEditedValue(workspace?.context ?? "", workspace?.id);+ const name = nameField.value;+ const description = descriptionField.value;+ const context = contextField.value;const [prefixDraft, setPrefixDraft] = useState<string | null>(null);const [prefixSaveStatus, setPrefixSaveStatus] =useState<SettingsSaveStatus>("idle");@@ -166,16 +170,8 @@ export function WorkspaceTab() {const isSoleOwner = isOwner && ownerCount <= 1;const isSoleMember = members.length <= 1;- // Reset form state only when the user switches to a different workspace.- // Keying on workspace?.id (not the object ref) avoids wiping unsaved edits- // when an unrelated mutation — e.g. avatar/logo upload — replaces the- // cached Workspace object via setQueryData.useEffect(() => {- setName(workspace?.name ?? "");- setDescription(workspace?.description ?? "");- setContext(workspace?.context ?? "");setPrefixDraft(null);- // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on id only; see comment above}, [workspace?.id]);// Letters + digits only, uppercase, capped at 10 chars. The backend@@ -204,12 +200,21 @@ export function WorkspaceTab() {const saveDetails = useCallback(async (next: WorkspaceDetailsDraft) => {if (!workspace) return;- const updated = await api.updateWorkspace(workspace.id, next);+ // Send only what was edited here, so the rest keeps changes made elsewhere.+ const changes: Partial<WorkspaceDetailsDraft> = {};+ if (nameField.edited) changes.name = next.name;+ if (descriptionField.edited) changes.description = next.description;+ if (contextField.edited) changes.context = next.context;+ if (Object.keys(changes).length === 0) return;+ const updated = await api.updateWorkspace(workspace.id, changes);qc.setQueryData(workspaceKeys.list(), (old: Workspace[] | undefined) =>old?.map((ws) => (ws.id === updated.id ? updated : ws)),);+ nameField.markSaved(next.name);+ descriptionField.markSaved(next.description);+ contextField.markSaved(next.context);},- [qc, workspace],+ [contextField, descriptionField, nameField, qc, workspace],);const detailsAutoSave = useAutoSave({value: detailsDraft,@@ -374,7 +379,7 @@ export function WorkspaceTab() {autoComplete="organization"aria-label={t(($) => $.workspace.name_label)}value={name}- onChange={(event) => setName(event.target.value)}+ onChange={(event) => nameField.edit(event.target.value)}onBlur={detailsAutoSave.flush}disabled={!canManageWorkspace}/>@@ -395,7 +400,7 @@ export function WorkspaceTab() {autoComplete="off"aria-label={t(($) => $.workspace.description_label)}value={description}- onChange={(event) => setDescription(event.target.value)}+ onChange={(event) => descriptionField.edit(event.target.value)}onBlur={detailsAutoSave.flush}rows={3}disabled={!canManageWorkspace}@@ -420,7 +425,7 @@ export function WorkspaceTab() {autoComplete="off"aria-label={t(($) => $.workspace.context_label)}value={context}- onChange={(event) => setContext(event.target.value)}+ onChange={(event) => contextField.edit(event.target.value)}onBlur={detailsAutoSave.flush}rows={4}disabled={!canManageWorkspace}