Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(skills): measure draft dirtiness against a seeded baseline (MUL-5645) (#6294)
Naiyuan Qing76fbd48849de
diff --git a/packages/views/skills/components/skill-detail-page.test.tsx b/packages/views/skills/components/skill-detail-page.test.tsxindex 0e3e9814f4..dd3661950a 100644--- a/packages/views/skills/components/skill-detail-page.test.tsx+++ b/packages/views/skills/components/skill-detail-page.test.tsx@@ -133,7 +133,18 @@ function renderPage(searchParams = new URLSearchParams()) {</NavigationProvider></I18nProvider>,);- return { replace };+ return { replace, queryClient };+}++/** Publishes a new server version of the skill, as a `skill:updated` event would. */+async function remoteUpdate(queryClient: QueryClient, next: Partial<Skill>) {+ skillRef.current = {+ ...(skillRef.current as Skill),+ updated_at: "2026-07-29T10:00:00Z",+ ...next,+ };+ await queryClient.invalidateQueries({ queryKey: ["skill", "ws-1", "skill-1"] });+ await new Promise((resolve) => setTimeout(resolve, 0));}beforeEach(() => {@@ -255,3 +266,98 @@ describe("SkillDetailPage properties", () => {).toBeTruthy();});});++/**+ * MUL-5645. Dirty state is measured against the seeded baseline, not against+ * the latest server skill. The two failures that rule prevents:+ *+ * 1. A description carrying trailing whitespace — what `description: |`+ * frontmatter yields, so every imported skill — used to compare unequal to+ * itself because only one side of the check was trimmed. The page opened+ * permanently dirty and Discard reseeded the same value, so it never cleared.+ * 2. A remote update read as a local edit, because the check compared the draft+ * against the NEW server skill. Any agent edit froze the editor on stale+ * text behind a conflict banner, whatever the description looked like.+ */+describe("SkillDetailPage draft baseline (MUL-5645)", () => {+ const CONFLICT_BANNER = "Someone else updated this skill";++ it("opens clean when the description carries a trailing newline", async () => {+ skillRef.current = { ...baseSkill, description: `${LONG_DESCRIPTION}\n` };+ renderPage();+ await screen.findAllByRole("tab", { name: /Overview|Files/ });+ expect(screen.queryByText(/^Changed:/)).toBeNull();+ });++ it("stays clean after Discard on a trailing-newline description", async () => {+ skillRef.current = { ...baseSkill, description: `${LONG_DESCRIPTION}\n` };+ renderPage();+ const field = (await screen.findByLabelText(+ "Description",+ )) as HTMLTextAreaElement;+ fireEvent.change(field, { target: { value: "edited" } });+ fireEvent.click(await screen.findByRole("button", { name: "Discard" }));+ expect(screen.queryByText(/^Changed:/)).toBeNull();+ });++ it("pulls a remote edit in silently while the draft is untouched", async () => {+ const { queryClient } = renderPage();+ await screen.findAllByRole("tab", { name: /Overview|Files/ });++ await remoteUpdate(queryClient, { description: "Rewritten by the agent" });++ // The new text reaching the field IS the fix: the old code left the editor+ // frozen on the pre-update value behind a conflict banner.+ expect(await screen.findByDisplayValue("Rewritten by the agent")).toBeTruthy();+ expect(screen.queryByText(CONFLICT_BANNER)).toBeNull();+ expect(screen.queryByText(/^Changed:/)).toBeNull();+ });++ it("pulls a remote SKILL.md edit in silently too", async () => {+ const { queryClient } = renderPage(new URLSearchParams("view=files"));+ await screen.findAllByRole("tab", { name: /Overview|Files/ });++ await remoteUpdate(queryClient, {+ content: `${baseSkill.content}\n## Added remotely\n`,+ });++ const preview = await screen.findByTestId("preview");+ expect(preview.textContent).toContain("Added remotely");+ expect(screen.queryByText(CONFLICT_BANNER)).toBeNull();+ expect(screen.queryByText(/^Changed:/)).toBeNull();+ });++ it("releases the conflict once the user reverts their own edits", async () => {+ const { queryClient } = renderPage();+ const field = (await screen.findByLabelText(+ "Description",+ )) as HTMLTextAreaElement;+ fireEvent.change(field, { target: { value: "my unsaved edit" } });++ await remoteUpdate(queryClient, { description: "Rewritten by the agent" });+ expect(await screen.findByText(CONFLICT_BANNER)).toBeTruthy();++ // Reverting by hand leaves nothing to protect. The save bar is dirty-gated,+ // so if the page held the conflict here the banner would sit above stale+ // text with no Discard left to press — a dead end short of a reload.+ fireEvent.change(field, { target: { value: LONG_DESCRIPTION } });++ expect(await screen.findByDisplayValue("Rewritten by the agent")).toBeTruthy();+ expect(screen.queryByText(CONFLICT_BANNER)).toBeNull();+ });++ it("keeps the draft and warns when a remote edit lands on real local edits", async () => {+ const { queryClient } = renderPage();+ const field = (await screen.findByLabelText(+ "Description",+ )) as HTMLTextAreaElement;+ fireEvent.change(field, { target: { value: "my unsaved edit" } });++ await remoteUpdate(queryClient, { description: "Rewritten by the agent" });++ expect(await screen.findByText(CONFLICT_BANNER)).toBeTruthy();+ expect(+ (screen.getByLabelText("Description") as HTMLTextAreaElement).value,+ ).toBe("my unsaved edit");+ });+});diff --git a/packages/views/skills/components/skill-detail-page.tsx b/packages/views/skills/components/skill-detail-page.tsxindex e8f7b6d2a0..ecc4452427 100644--- a/packages/views/skills/components/skill-detail-page.tsx+++ b/packages/views/skills/components/skill-detail-page.tsx@@ -83,6 +83,72 @@ const SKILL_MD = "SKILL.md";type DraftFile = { id?: string; path: string; content: string };+/** The four editable fields, as one snapshot. */+type SkillDraft = {+ name: string;+ description: string;+ content: string;+ files: DraftFile[];+};++/**+ * Server skill -> editable draft.+ *+ * `name` and `description` are trimmed here because Save trims them too:+ * normalizing once, at the single seam where server data becomes a draft, is+ * what lets every later comparison be plain equality. Trimming at comparison+ * time instead is how the two sides drifted apart in the first place — the+ * dirty check trimmed one operand and not the other, so a description ending+ * in a newline (what `description: |` frontmatter yields) never compared equal+ * to itself and the page opened permanently dirty.+ *+ * `content` and file bodies are deliberately NOT normalized: leading and+ * trailing whitespace in a SKILL.md body is content, not formatting.+ */+function toDraft(s: Skill): SkillDraft {+ return {+ name: s.name.trim(),+ description: s.description.trim(),+ content: s.content,+ files: (s.files ?? []).map((f: SkillFile) => ({+ id: f.id,+ path: f.path,+ content: f.content,+ })),+ };+}++/**+ * Order-insensitive snapshot of a file set. The two endpoints that return+ * files disagree on order — GET sorts by path, PUT echoes request order — and+ * an order difference is not a content difference.+ */+function fileSignature(files: DraftFile[]): string {+ return JSON.stringify(+ files+ .map((f) => ({ path: f.path, content: f.content }))+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)),+ );+}++/**+ * Did the USER change anything, measured against the draft we handed them?+ *+ * Deliberately not "does the draft differ from the latest server skill": that+ * question conflates two independent causes — the user typed something, or the+ * server moved underneath us — and answering it as if only the first existed+ * is what made every remote update look like a local edit.+ */+function hasLocalEdits(draft: SkillDraft, baseline: SkillDraft | null): boolean {+ if (!baseline) return false;+ return (+ draft.name.trim() !== baseline.name ||+ draft.description.trim() !== baseline.description ||+ draft.content !== baseline.content ||+ fileSignature(draft.files) !== fileSignature(baseline.files)+ );+}+/*** Two tabs, not three. A skill has no settings axis to speak of:* `UpdateSkillRequest` carries only name / description / content / config /@@ -720,48 +786,69 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {const seededKeyRef = useRef<string | null>(null);+ /**+ * The draft this page last handed the user, normalized by `toDraft`. Dirty+ * state is measured against THIS, never against the latest server skill.+ *+ * INVARIANT: `seedFromSkill` is the only writer, and it always writes the+ * same snapshot it pushes into state. `dirtySummary` is a `useMemo` keyed on+ * those state values, so every baseline write is paired with the state+ * change that recomputes it. Assigning this ref anywhere else breaks that+ * pairing and silently re-opens MUL-5645.+ */+ const baselineRef = useRef<SkillDraft | null>(null);++ const seedFromSkill = useCallback((s: Skill) => {+ const seeded = toDraft(s);+ setName(seeded.name);+ setDescription(seeded.description);+ setContent(seeded.content);+ setFiles(seeded.files);+ baselineRef.current = seeded;+ }, []);++ /**+ * Adopt a server version wholesale: draft, baseline, seeded key and conflict+ * flag all move together. Every path that accepts a server version goes+ * through here — first load, silent refresh, Save, Discard — so the four+ * pieces can never drift apart.+ */+ const adoptServerVersion = useCallback(+ (s: Skill, resetSelection = false) => {+ seededKeyRef.current = `${wsId}:${s.id}@${s.updated_at}`;+ setConflictPending(false);+ seedFromSkill(s);+ if (resetSelection) setSelectedPath(SKILL_MD);+ },+ [wsId, seedFromSkill],+ );+useEffect(() => {if (!skill) return;- const key = `${wsId}:${skill.id}@${skill.updated_at}`;- if (seededKeyRef.current === key) return;+ if (seededKeyRef.current === `${wsId}:${skill.id}@${skill.updated_at}`) {+ return;+ }const sameSkill =seededKeyRef.current !== null &&seededKeyRef.current.startsWith(`${wsId}:${skill.id}@`);- if (sameSkill) {- const d = draftRef.current;- const serverFilesJson = JSON.stringify(- (skill.files ?? []).map((f) => ({ path: f.path, content: f.content })),- );- const draftFilesJson = JSON.stringify(- d.files.map((f) => ({ path: f.path, content: f.content })),- );- const hasEdits =- d.name.trim() !== skill.name ||- d.description.trim() !== skill.description ||- d.content !== skill.content ||- draftFilesJson !== serverFilesJson;- if (hasEdits) {- setConflictPending(true);- return;- }+ // Same skill, newer server version. Whether that is a conflict depends on+ // the local draft alone: with no local edits the user is simply reading+ // the page, so pull the new version in silently instead of accusing them+ // of an edit they never made and freezing the editor on stale text.+ //+ // Re-run on draft changes, not just on new server versions: a conflict the+ // user resolves by reverting their own edits has to release the page. The+ // save bar is dirty-gated, so holding the conflict past that point would+ // leave the banner above stale text with no Discard left to press.+ if (sameSkill && hasLocalEdits(draftRef.current, baselineRef.current)) {+ setConflictPending(true);+ return;}- seededKeyRef.current = key;- setConflictPending(false);- setName(skill.name);- setDescription(skill.description);- setContent(skill.content);- setFiles(- (skill.files ?? []).map((f: SkillFile) => ({- id: f.id,- path: f.path,- content: f.content,- })),- );- if (!sameSkill) setSelectedPath(SKILL_MD);- }, [skill, wsId]);+ adoptServerVersion(skill, !sameSkill);+ }, [skill, wsId, adoptServerVersion, name, description, content, files]);const creator = useMemo<MemberWithUser | null>(() =>@@ -798,49 +885,42 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {}}, [fileMap, selectedPath]);- // Files are matched by id so a rename counts as one changed file, not a- // delete plus an add; SKILL.md is its own entry since it lives in `content`.+ // Compared against the seeded baseline, not against the latest server skill,+ // so a remote update can never read as a local edit. Files are matched by id+ // so a rename counts as one changed file, not a delete plus an add; SKILL.md+ // is its own entry since it lives in `content`.const dirtySummary = useMemo(() => {- if (!skill) return { nameChanged: false, descChanged: false, changedFileCount: 0 };- const serverFiles: SkillFile[] = skill.files ?? [];- const serverById = new Map(serverFiles.map((f) => [f.id, f]));- let changedFileCount = content !== skill.content ? 1 : 0;+ const baseline = baselineRef.current;+ if (!baseline) {+ return { nameChanged: false, descChanged: false, changedFileCount: 0 };+ }+ const baselineById = new Map(+ baseline.files.flatMap((f) => (f.id ? [[f.id, f] as const] : [])),+ );+ let changedFileCount = content !== baseline.content ? 1 : 0;const draftIds = new Set<string>();for (const f of files) {if (f.id) draftIds.add(f.id);- const server = f.id ? serverById.get(f.id) : undefined;- if (!server || server.path !== f.path || server.content !== f.content) {+ const base = f.id ? baselineById.get(f.id) : undefined;+ if (!base || base.path !== f.path || base.content !== f.content) {changedFileCount += 1;}}- for (const f of serverFiles) {- if (!draftIds.has(f.id)) changedFileCount += 1;+ for (const f of baseline.files) {+ if (f.id && !draftIds.has(f.id)) changedFileCount += 1;}return {- nameChanged: name.trim() !== skill.name,- descChanged: description.trim() !== skill.description,+ nameChanged: name.trim() !== baseline.name,+ descChanged: description.trim() !== baseline.description,changedFileCount,};- }, [skill, name, description, content, files]);+ }, [name, description, content, files]);const isDirty =dirtySummary.nameChanged ||dirtySummary.descChanged ||dirtySummary.changedFileCount > 0;- const seedFromSkill = (s: Skill) => {- setName(s.name);- setDescription(s.description);- setContent(s.content);- setFiles(- (s.files ?? []).map((f: SkillFile) => ({- id: f.id,- path: f.path,- content: f.content,- })),- );- };-const handleSave = async () => {if (!skill || !canEdit) return;const trimmedName = name.trim();@@ -855,9 +935,7 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {};const updated = await api.updateSkill(skill.id, payload);qc.setQueryData(skillDetailOptions(wsId, skill.id).queryKey, updated);- seedFromSkill(updated);- seededKeyRef.current = `${wsId}:${updated.id}@${updated.updated_at}`;- setConflictPending(false);+ adoptServerVersion(updated);qc.invalidateQueries({queryKey: workspaceKeys.skills(wsId),exact: true,@@ -873,9 +951,7 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {const handleDiscard = () => {if (!skill) return;- seedFromSkill(skill);- seededKeyRef.current = `${wsId}:${skill.id}@${skill.updated_at}`;- setConflictPending(false);+ adoptServerVersion(skill);};const handleDelete = async () => {diff --git a/server/internal/skill/frontmatter.go b/server/internal/skill/frontmatter.goindex 7b7156968a..4e23de52c5 100644--- a/server/internal/skill/frontmatter.go+++ b/server/internal/skill/frontmatter.go@@ -37,7 +37,14 @@ func ParseSkillFrontmatter(content string) (name, description string) {if err := yaml.Unmarshal([]byte(match[1]), &fm); err != nil {return "", ""}- return coerceFrontmatterValue(fm["name"]), coerceFrontmatterValue(fm["description"])+ // Trimmed because both fields are single-line labels wherever they are+ // consumed, while YAML block scalars (`description: |`, `description: >`)+ // carry a trailing newline by clip chomping. Storing that newline made the+ // imported skill differ from its own trimmed form, which the skill detail+ // page read as an unsaved edit (MUL-5645). Normalize at the parse seam so+ // no import path has to remember to.+ return strings.TrimSpace(coerceFrontmatterValue(fm["name"])),+ strings.TrimSpace(coerceFrontmatterValue(fm["description"]))}// coerceFrontmatterValue renders a decoded YAML value as a string, mirroring thediff --git a/server/internal/skill/frontmatter_test.go b/server/internal/skill/frontmatter_test.goindex a318e7cf45..0b70ac57b3 100644--- a/server/internal/skill/frontmatter_test.go+++ b/server/internal/skill/frontmatter_test.go@@ -28,10 +28,11 @@ func TestParseSkillFrontmatter(t *testing.T) {wantDesc: "hello world",},{- name: "literal block scalar keeps newlines",+ // Interior newlines survive; only the chomped trailing one is dropped.+ name: "literal block scalar keeps interior newlines",content: "---\nname: foo\ndescription: |\n line1\n line2\n---\nbody",wantName: "foo",- wantDesc: "line1\nline2\n",+ wantDesc: "line1\nline2",},{name: "literal strip chomping drops trailing newline",@@ -43,7 +44,7 @@ func TestParseSkillFrontmatter(t *testing.T) {name: "folded block scalar joins with spaces",content: "---\nname: foo\ndescription: >\n line1\n line2\n---\nbody",wantName: "foo",- wantDesc: "line1 line2\n",+ wantDesc: "line1 line2",},{name: "CRLF line endings",@@ -118,6 +119,14 @@ func TestParseSkillFrontmatter(t *testing.T) {wantName: "my-skill",wantDesc: `{"a":1,"b":2}`,},+ {+ // MUL-5645: padding never reaches storage, so an imported skill can+ // never differ from its own trimmed form in the editor.+ name: "surrounding whitespace is trimmed off both fields",+ content: "---\nname: \" foo \"\ndescription: \" hello world\\n\"\n---\nbody",+ wantName: "foo",+ wantDesc: "hello world",+ },{// Reproduction for issue #3495: Chinese block scalar.name: "issue 3495 chinese literal block scalar",@@ -131,7 +140,7 @@ func TestParseSkillFrontmatter(t *testing.T) {wantName: "requirements-workshop",wantDesc: "当用户想要开发新功能、讨论需求、梳理业务逻辑时触发。通过多轮对话将模糊的想法转化为结构化的需求文档,为后续技术方案设计提供输入。\n" +"适用场景:用户说\"我想实现XX功能\"、\"讨论一下这个需求\"、\"帮我分析一下怎么做\"、\"这个需求该怎么设计\"、\"写个需求文档\"等。\n" +- "本skill只负责产出需求文档,不进入技术设计或代码实现阶段。\n",+ "本skill只负责产出需求文档,不进入技术设计或代码实现阶段。",},}