Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: confirm before discarding unsaved job skill edits in the Prompt Manager (#3939)
[._.]/ Adam Eivyedac9958f82e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 59625c79e8..410a33a20e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -80,3 +80,4 @@- Unsaved Quota Burn edits are no longer lost silently when you navigate away. The page has no Save button — edits persist on a 500ms trailing edge — and the dismount flush that catches everything typed inside that window swallowed its own failure with `.catch(() => {})`, so leaving the page while the header still read "Saving changes…" dropped a pasted work prompt or a changed interval for good, with no toast and nothing on screen having said so. A failed flush now raises an error toast naming what happened and keeps the patch in tab-scoped `sessionStorage`; the next visit that successfully reads a plan replays it through the normal save path, so the edits come back on screen AND get re-sent to the server instead of waiting for the user to retype the field. A visit whose own read failed leaves the stash alone for the visit after it, and a stash that is not a patch object is ignored rather than replayed into a 400.- Clearing a Quota Burn number box no longer discards the edit without saying so. `NumberField` held an uncommitted draft so an empty box could not commit `Number('') === 0` into a 400, but on blur it simply dropped the draft and snapped the input back to the stored value — a user who cleared "Check every (minutes)" or "Reserve (%)" and clicked away saw the old number reappear with nothing on screen explaining why. An empty, non-numeric or out-of-range draft now stays on screen next to an inline error naming what the field accepts ("Must be between 5 and 720"), wired up with `aria-invalid`/`aria-describedby`; the error clears the moment the draft is committable again, and only a committable draft is released back to the stored value. Out-of-range numbers are also no longer committed mid-typing, so a 721-minute interval is caught in the field rather than by the server.- Applying an inbound catalog sync envelope no longer writes each legacy-tagged ingredient twice. The friendlify-on-sync repair — which rewrites an older peer's raw `from-universe` / `universe:<id>` tags to the friendly universe name — ran as a follow-up `updateIngredient` after `upsertIngredientFromPeer` had already written the row, so an envelope carrying N such ingredients cost 2N queries and left a redundant `catalog_ingredient_revisions` entry for every one of them. The rewrite now happens on the row before it is upserted, so it lands cleaned in a single write with no extra revision history. Behavior is otherwise unchanged: the universe name map is still built lazily and only once per apply, a row whose universe is not resolvable locally still lands with its machine tags intact for a later pass, an LWW skip still touches nothing, and a failure to build the map is isolated per row (reported as `ingredient-prepare`) with the raw row still applied. The friendly universe name — minted locally rather than carried by the peer — is still registered in the canonical tag taxonomy so autocomplete can suggest it, but now only for the label the rewrite adds, once per apply, instead of re-normalizing every row's whole tag array.+- Unsaved job-skill edits in the Prompt Manager are no longer thrown away when you click another skill. Selecting a skill replaced the Markdown editor's contents outright, so a half-written template vanished with no warning and no undo the moment the user reached for a neighbouring skill in the sidebar list. The editor now tracks the last server-confirmed text (a full copy, not a flag, so typing an edit and undoing it back to the original stops counting as dirty) and marks itself with an "Unsaved changes" note in the header and an "Unsaved" badge on the list row. Clicking a different skill while dirty parks that click and takes over its list slot with an inline confirm row — "Discard unsaved changes to …?" with Discard / Keep editing — so cancelling leaves the selection, the URL, and the typed text untouched, and the next skill is only fetched once the discard is confirmed. Saving snapshots exactly what was sent as the new clean baseline, so a successful save clears the guard while an edit made mid-flight stays dirty.\ No newline at end of filediff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsxindex a365e9db10..7d24cb5aa7 100644--- a/client/src/pages/PromptManager.jsx+++ b/client/src/pages/PromptManager.jsx@@ -101,8 +101,15 @@ export default function PromptManager() {// Job skills (selection is URL-driven — see selectedJobSkill above)const [jobSkills, setJobSkills] = useState([]);const [jobSkillContent, setJobSkillContent] = useState('');+ // The last content the server confirmed (loaded or saved). Kept as a full copy+ // rather than a boolean flag so typing an edit and undoing it back to the+ // original stops counting as dirty — a stale flag would nag on a no-op edit.+ const [savedJobSkillContent, setSavedJobSkillContent] = useState('');+ // The skill the user clicked while holding unsaved edits, awaiting confirmation.+ const [pendingJobSkill, setPendingJobSkill] = useState(null);const [jobSkillMeta, setJobSkillMeta] = useState({});const [jobSkillPreview, setJobSkillPreview] = useState('');+ const isJobSkillDirty = Boolean(selectedJobSkill) && jobSkillContent !== savedJobSkillContent;const [providers, setProviders] = useState([]);const [activeProviderId, setActiveProviderId] = useState(null);@@ -300,6 +307,8 @@ export default function PromptManager() {useEffect(() => {setJobSkillPreview('');setJobSkillContent('');+ setSavedJobSkillContent('');+ setPendingJobSkill(null);setJobSkillMeta({});if (!selectedJobSkill) return;let cancelled = false;@@ -307,6 +316,7 @@ export default function PromptManager() {.then((res) => {if (cancelled || !res) return;setJobSkillContent(res.content || '');+ setSavedJobSkillContent(res.content || '');setJobSkillMeta({ jobName: res.jobName, jobId: res.jobId, category: res.category, interval: res.interval });}).catch(() => {});@@ -318,11 +328,28 @@ export default function PromptManager() {// keeps the notification to one layer (see client/src/CLAUDE.md).const saveJobSkill = async () => {setSaving(true);- const ok = await apiSaveJobSkill(selectedJobSkill, jobSkillContent, { silent: true })+ // Snapshot what we actually sent — the textarea may change while the PATCH+ // is in flight, and only the persisted text may become the clean baseline.+ const sent = jobSkillContent;+ const ok = await apiSaveJobSkill(selectedJobSkill, sent, { silent: true }).then(() => true).catch((err) => { toast.error(`Failed to save job skill: ${err.message || 'Unknown error'}`); return false; });setSaving(false);- if (ok) toast.success('Job skill saved');+ if (!ok) return;+ setSavedJobSkillContent(sent);+ toast.success('Job skill saved');+ };++ // Switching skills replaces the editor's content, so unsaved edits must be+ // confirmed away first (#3939). The clicked skill parks in `pendingJobSkill`+ // and an inline confirm row takes over its list slot — no window.confirm.+ const requestJobSkill = (name) => {+ if (name === selectedJobSkill) return;+ if (isJobSkillDirty) {+ setPendingJobSkill(name);+ return;+ }+ setSelectedJobSkill(name);};const previewJobSkill = async () => {@@ -839,25 +866,44 @@ export default function PromptManager() {</div><div className="space-y-1">{jobSkills.map((skill) => (- <button- key={skill.name}- onClick={() => setSelectedJobSkill(skill.name)}- className={`w-full text-left px-3 py-2 rounded-lg text-sm ${- selectedJobSkill === skill.name- ? 'bg-port-accent/20 text-port-accent'- : 'text-gray-300 hover:bg-port-border'- }`}- >- <div className="flex items-center gap-1">- <span className="font-medium">{skill.name}</span>- {skill.hasTemplate && (- <span className="shrink-0 text-[10px] px-1.5 py-0.5 bg-port-success/20 text-port-success rounded uppercase font-semibold">- Active- </span>- )}- </div>- <div className="text-xs text-gray-500">{skill.jobId}</div>- </button>+ pendingJobSkill === skill.name ? (+ <InlineConfirmRow+ key={skill.name}+ className="rounded-lg"+ question={`Discard unsaved changes to "${jobSkillMeta.jobName || selectedJobSkill}"?`}+ confirmText="Discard"+ cancelText="Keep editing"+ aria-label={`Confirm discarding unsaved changes to ${jobSkillMeta.jobName || selectedJobSkill}`}+ autoFocus+ onConfirm={() => { setPendingJobSkill(null); setSelectedJobSkill(skill.name); }}+ onCancel={() => setPendingJobSkill(null)}+ />+ ) : (+ <button+ key={skill.name}+ onClick={() => requestJobSkill(skill.name)}+ className={`w-full text-left px-3 py-2 rounded-lg text-sm ${+ selectedJobSkill === skill.name+ ? 'bg-port-accent/20 text-port-accent'+ : 'text-gray-300 hover:bg-port-border'+ }`}+ >+ <div className="flex items-center gap-1">+ <span className="font-medium">{skill.name}</span>+ {skill.hasTemplate && (+ <span className="shrink-0 text-[10px] px-1.5 py-0.5 bg-port-success/20 text-port-success rounded uppercase font-semibold">+ Active+ </span>+ )}+ {selectedJobSkill === skill.name && isJobSkillDirty && (+ <span className="shrink-0 text-[10px] px-1.5 py-0.5 bg-port-warning/20 text-port-warning rounded uppercase font-semibold">+ Unsaved+ </span>+ )}+ </div>+ <div className="text-xs text-gray-500">{skill.jobId}</div>+ </button>+ )))}{jobSkills.length === 0 && (<div className="text-sm text-gray-500 px-3 py-2">No job skill templates found</div>@@ -877,6 +923,7 @@ export default function PromptManager() {{jobSkillMeta.category && <span>Category: {jobSkillMeta.category}</span>}{jobSkillMeta.interval && <span>Interval: {jobSkillMeta.interval}</span>}{jobSkillMeta.jobId && <span>ID: {jobSkillMeta.jobId}</span>}+ {isJobSkillDirty && <span className="text-port-warning">Unsaved changes</span>}</div></div><div className="flex gap-2">diff --git a/client/src/pages/PromptManager.test.jsx b/client/src/pages/PromptManager.test.jsxindex d370d9a1da..615d18cff7 100644--- a/client/src/pages/PromptManager.test.jsx+++ b/client/src/pages/PromptManager.test.jsx@@ -575,3 +575,112 @@ describe('PromptManager job skill save feedback', () => {await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Failed to preview: nope'));});});++// Clicking another skill used to overwrite the editor outright, silently+// discarding whatever the user had typed (#3939).+describe('PromptManager job skill unsaved-edit guard', () => {+ const SKILLS = [+ { name: 'code-fixer', jobId: 'job-code-fixer', hasTemplate: true },+ { name: 'doc-writer', jobId: 'job-doc-writer', hasTemplate: false },+ ];++ beforeEach(() => {+ getPrompts.mockReset().mockResolvedValue({ stages: STAGES, systemStages: SYSTEM_STAGES });+ getJobSkills.mockReset().mockResolvedValue({ skills: SKILLS });+ getJobSkill.mockReset().mockImplementation((name) => Promise.resolve({+ content: `# ${name} template`,+ jobName: `Job ${name}`,+ jobId: `job-${name}`,+ }));+ saveJobSkill.mockReset().mockResolvedValue({ success: true });+ toast.error.mockReset();+ toast.success.mockReset();+ });++ const editor = () => screen.getByLabelText('Skill Template (Markdown)');++ const openDirtyEditor = async () => {+ renderPage('/prompts?tab=job-skills&skill=code-fixer');+ await screen.findByText('Job code-fixer');+ fireEvent.change(editor(), { target: { value: '# edited by hand' } });+ await screen.findByText('Unsaved changes');+ };++ it('marks the editor dirty once the template is modified', async () => {+ renderPage('/prompts?tab=job-skills&skill=code-fixer');+ await screen.findByText('Job code-fixer');+ expect(screen.queryByText('Unsaved changes')).toBeNull();++ fireEvent.change(editor(), { target: { value: '# edited by hand' } });++ expect(screen.getByText('Unsaved changes')).toBeTruthy();+ });++ it('treats an edit reverted to the loaded text as clean again', async () => {+ await openDirtyEditor();++ fireEvent.change(editor(), { target: { value: '# code-fixer template' } });++ expect(screen.queryByText('Unsaved changes')).toBeNull();+ });++ it('asks before discarding unsaved edits when another skill is clicked', async () => {+ await openDirtyEditor();++ fireEvent.click(screen.getByText('doc-writer'));++ expect(screen.getByText('Discard unsaved changes to "Job code-fixer"?')).toBeTruthy();+ // Nothing switched yet: the URL, the fetch, and the typed text all hold.+ expect(currentSearch()).toContain('skill=code-fixer');+ expect(getJobSkill).not.toHaveBeenCalledWith('doc-writer', { silent: true });+ expect(screen.getByDisplayValue('# edited by hand')).toBeTruthy();+ });++ it('keeps the edits when the discard prompt is cancelled', async () => {+ await openDirtyEditor();+ fireEvent.click(screen.getByText('doc-writer'));++ fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));++ expect(screen.queryByText(/Discard unsaved changes/)).toBeNull();+ expect(screen.getByDisplayValue('# edited by hand')).toBeTruthy();+ expect(currentSearch()).toContain('skill=code-fixer');+ });++ it('switches skills after the discard is confirmed', async () => {+ await openDirtyEditor();+ fireEvent.click(screen.getByText('doc-writer'));++ fireEvent.click(screen.getByRole('button', { name: 'Discard' }));++ await waitFor(() => expect(currentSearch()).toContain('skill=doc-writer'));+ await screen.findByText('Job doc-writer');+ expect(screen.getByDisplayValue('# doc-writer template')).toBeTruthy();+ expect(screen.queryByText('Unsaved changes')).toBeNull();+ });++ it('switches without prompting once the edits are saved', async () => {+ await openDirtyEditor();++ // Exact match: the dirty list row is labelled "… Unsaved", which /save/i+ // would also match.+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));+ await waitFor(() => expect(toast.success).toHaveBeenCalled());+ expect(screen.queryByText('Unsaved changes')).toBeNull();++ fireEvent.click(screen.getByText('doc-writer'));++ expect(screen.queryByText(/Discard unsaved changes/)).toBeNull();+ await waitFor(() => expect(currentSearch()).toContain('skill=doc-writer'));+ });++ it('does not prompt when a clean editor switches skills', async () => {+ renderPage('/prompts?tab=job-skills&skill=code-fixer');+ await screen.findByText('Job code-fixer');++ fireEvent.click(screen.getByText('doc-writer'));++ expect(screen.queryByText(/Discard unsaved changes/)).toBeNull();+ await waitFor(() => expect(currentSearch()).toContain('skill=doc-writer'));+ });+});