The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Assist: SKILL.md escapes round-trip, memory import drops assistant boilerplate, project skills survive rename/delete
Clauded6b711b875af
diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex ab93dc19..a8db42f0 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -197,7 +197,15 @@ export function parseFrontmatter(src: string): Record<string, Yamlish> {const unquote = (v: string) => {const t = v.trim();if ((t.startsWith('"') && t.endsWith('"') && t.length > 1) || (t.startsWith("'") && t.endsWith("'") && t.length > 1)) {- return t.startsWith('"') ? t.slice(1, -1).replace(/\\"/g, '"').replace(/\\n/g, "\n") : t.slice(1, -1).replace(/''/g, "'");+ if (t.startsWith("'")) return t.slice(1, -1).replace(/''/g, "'");+ // Double-quoted scalars use JSON's escapes (toSkillMd writes them with JSON.stringify).+ try {+ const v = JSON.parse(t) as unknown;+ if (typeof v === "string") return v;+ } catch {+ // Not valid JSON (a lone backslash…): unescape the common cases only.+ }+ return t.slice(1, -1).replace(/\\(["\\])/g, "$1").replace(/\\n/g, "\n");}return t.replace(/\s+#.*$/, "");};@@ -400,8 +408,31 @@ const CATEGORY_ALIASES: Record<string, MemoryCategory> = {notes: "Notes",note: "Notes",other: "Notes",+ misc: "Notes",+ general: "Notes",};+/** Lines an assistant writes around its list, not memories ("Here's what I remember:", "Let me know…"). */+const BOILERPLATE = [+ /^(?:here(?:'|’)?s|here (?:is|are)|below (?:is|are)|these are|this is|that's|that is)\b.*\b(?:memor\w*|remember\w*|know|saved|stored|things)\b.*$/i,+ /^(?:let me know|feel free|is there anything|if you(?:'|’)?d like|if you want|want me to|would you like|i can (?:also )?(?:update|forget|add))\b/i,+ /^(?:memories|memory|saved memories|my memories|your memories|what i (?:know|remember)(?: about you)?)$/i,+];++/** Leading dates some exports put on each memory ("2025-03-12:", "[12/03/2025]", "March 12, 2025 —"). */+const LEADING_DATE =+ /^\[?(?:\d{4}-\d{2}-\d{2}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?Z?)?|\d{1,2}[/.]\d{1,2}[/.]\d{2,4}|(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.? \d{1,2},? \d{4})\]?\s*(?:[:—–-]\s*)?/i;++/** Markdown emphasis and code marks around words (**Name**, __x__, `y`). */+const stripMarks = (s: string) => s.replace(/(\*\*|__)(.+?)\1/g, "$2").replace(/(^|\s)[*_](\S(?:.*?\S)?)[*_](?=\s|[:.,;!?]|$)/g, "$1$2").replace(/`([^`]+)`/g, "$1");++/** "Sure! Here's…" → "Here's…"; "I remember that you prefer…" → "You prefer…". */+const stripLeadIn = (s: string) =>+ s+ .replace(/^(?:sure|of course|certainly|okay|ok|absolutely|great)\b[,!.]*\s*/i, "")+ .replace(/^i (?:remember|know|recall|noted|have saved)(?: that)?\s+(?=you\b)/i, "")+ .replace(/^you\b/, "You");+export const toCategory = (s: string | undefined): MemoryCategory | undefined => (s ? CATEGORY_ALIASES[s.trim().toLowerCase()] : undefined);/**@@ -422,12 +453,13 @@ export function parseMemoryImport(text: string): { category: MemoryCategory; tex// Plain text.}const add = (raw: string, cat?: MemoryCategory) => {- let t = raw.replace(/\s+/g, " ").trim();+ let t = stripLeadIn(stripMarks(raw.replace(/\s+/g, " ").trim()).replace(LEADING_DATE, "").trim());const prefix = /^\[?([A-Za-z ]{3,20})\]?\s*[:—–-]\s+(.+)$/.exec(t);const pc = prefix ? toCategory(prefix[1]) : undefined;if (pc) t = prefix![2].trim();t = t.replace(/^["“](.*)["”]$/, "$1").trim();- if (t.length < 4 || /^(here (is|are)|below (is|are)|these are|i remember|memories|memory|saved memories)\b.*:?$/i.test(t)) return;+ // A lead-in or a heading ends with a colon and has nothing after it.+ if (t.length < 4 || /:\s*$/.test(t) || BOILERPLATE.some((re) => re.test(t))) return;const key = t.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();if (!key || seen.has(key)) return;seen.add(key);@@ -447,9 +479,11 @@ export function parseMemoryImport(text: string): { category: MemoryCategory; texfor (const line of text.split(/\r?\n/)) {const l = line.trim();if (!l) continue;- const h = /^(?:#{1,6}\s+|\*\*)?([A-Za-z ]{3,24}?)(?:\*\*)?\s*:?\s*$/.exec(l);- if (h && toCategory(h[1]) && !/^[-*•]\s/.test(l)) {- heading = toCategory(h[1]);+ // "## Preferences", "**Your preferences:**", "Style:" set the category for the lines below.+ const h = /^(?:#{1,6}\s+)?([A-Za-z ]{3,30}?)\s*:?\s*$/.exec(stripMarks(l).replace(/:\s*$/, ""));+ const hc = h ? toCategory(h[1].replace(/^(?:your|my|the)\s+/i, "")) : undefined;+ if (hc && !/^[-*•]\s/.test(l)) {+ heading = hc;continue;}if (/^#{1,6}\s/.test(l)) continue;diff --git a/src/server/assist/context.ts b/src/server/assist/context.tsindex a1066049..6af1731a 100644--- a/src/server/assist/context.ts+++ b/src/server/assist/context.ts@@ -44,11 +44,15 @@ export const approvalLine = (autoApprove: boolean) =>? "Auto-run is on: generations start without an approval card, so keep plans within what the user asked for. Memories you save are kept straight away.": "Ask-first is on: each generate call (and each memory you save) shows an approval card.";-/** The skills a chat can use: a project's own list when it has one, else every enabled skill. */+/** A project's own skills that still exist (a deleted or renamed one drops out). */+function projectSkills(project: { skills: string[] } | null): Skill[] {+ return project?.skills.map((n) => getSkill(n)).filter((s): s is Skill => !!s) ?? [];+}++/** The skills a chat can use: a project's own list when it has one that resolves, else every enabled skill. */export function skillsFor(projectId: string | null): Skill[] {- const project = projectId ? getProject(projectId) : null;- if (project?.skills.length) return project.skills.map((n) => getSkill(n)).filter((s): s is Skill => !!s);- return enabledSkills();+ const own = projectSkills(projectId ? getProject(projectId) : null);+ return own.length ? own : enabledSkills();}export function canUseSkill(name: string, projectId: string | null): boolean {@@ -73,7 +77,7 @@ export function chatFacts(c: ChatInfo, now = new Date()): ContextFact[] {text: [`This chat is in the project “${project.name}”.`,project.instructions ? `The project's instructions — follow them:\n${project.instructions}` : "It has no extra instructions.",- project.skills.length ? `Only the project's skills are available here.` : "",+ projectSkills(project).length ? `Only the project's skills are available here.` : "",].filter(Boolean).join("\n"),diff --git a/src/server/skills.ts b/src/server/skills.tsindex 4f6b2d88..691245e9 100644--- a/src/server/skills.ts+++ b/src/server/skills.ts@@ -226,12 +226,35 @@ export function updateSkill(name: string, patch: Partial<SkillInput>): Skill {if (conflict) throw new SkillError(conflict, 409);}const meta = { ...(s.icon && { icon: s.icon }), ...(s.studio && { studio: s.studio }), ...(s.tags?.length && { tags: s.tags }), ...(cur.offline && { offline: cur.offline }) };- db()- .prepare("UPDATE skills SET name = ?, title = ?, description = ?, when_to_use = ?, body = ?, meta_json = ?, updated_at = ? WHERE name = ?")- .run(s.name, s.title, s.description, s.whenToUse, s.body, JSON.stringify(meta), Date.now(), name);+ db().transaction(() => {+ db()+ .prepare("UPDATE skills SET name = ?, title = ?, description = ?, when_to_use = ?, body = ?, meta_json = ?, updated_at = ? WHERE name = ?")+ .run(s.name, s.title, s.description, s.whenToUse, s.body, JSON.stringify(meta), Date.now(), name);+ if (s.name !== name) renameSkillRefs(name, s.name);+ })();return getSkill(s.name)!;}+/**+ * Keep the skill lists of projects and chats in step with a rename (`to`) or a delete (`to` null):+ * a project whose only skill went away would otherwise have no skills at all.+ */+function renameSkillRefs(from: string, to: string | null): void {+ const like = `%${JSON.stringify(from)}%`;+ for (const [table, key] of [+ ["assist_projects", "id"],+ ["assist_thread_state", "thread_id"],+ ] as const) {+ const rows = db().prepare(`SELECT ${key} AS id, skills_json FROM ${table} WHERE skills_json LIKE ?`).all(like) as { id: string; skills_json: string }[];+ for (const r of rows) {+ const list = JSON.parse(r.skills_json) as string[];+ if (!list.includes(from)) continue;+ const next = [...new Set(list.flatMap((n) => (n === from ? (to ? [to] : []) : [n])))];+ db().prepare(`UPDATE ${table} SET skills_json = ? WHERE ${key} = ?`).run(JSON.stringify(next), r.id);+ }+ }+}+/** A user copy of any skill (the way to change a built-in). */export function duplicateSkill(name: string): Skill {const cur = getSkill(name);@@ -249,7 +272,10 @@ export function deleteSkill(name: string): void {const cur = getSkill(name);if (!cur) throw new SkillError("No such skill", 404);if (cur.source === "builtin") throw new SkillError("Built-in skills can't be deleted — switch it off instead", 403);- db().prepare("DELETE FROM skills WHERE name = ?").run(name);+ db().transaction(() => {+ db().prepare("DELETE FROM skills WHERE name = ?").run(name);+ renameSkillRefs(name, null);+ })();}export function setSkillEnabled(name: string, enabled: boolean): Skill {diff --git a/tests/assist-skills.test.ts b/tests/assist-skills.test.tsindex f0b06f79..4c0bd161 100644--- a/tests/assist-skills.test.ts+++ b/tests/assist-skills.test.ts@@ -30,6 +30,7 @@ const { zipStored, unzip } = await import("@/server/assist/unzip");const { createElement } = await import("@/server/elements");const { saveFile } = await import("@/server/storage");const agent = await import("@/server/assist/agent");+const { db } = await import("@/server/db");afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));@@ -83,6 +84,20 @@ offline:expect(r.ok && r.skill).toMatchObject({ name: "a-b", title: "A: b", description: "Does a thing well", whenToUse: "When asked", icon: "film", studio: "/video", tags: ["x", "y z"], body: "# Hi\n\nText" });});+ it("round-trips backslashes, quotes, '#' and colons through SKILL.md, unchanged on every save", () => {+ const s = { name: "esc", title: 'Back\\slash "quoted" #1: yes', description: "Save to C:\\new\\tables — 50% #brand 'ok'", whenToUse: "When it's \\n literally", tags: ["a#b", 'c"d'], body: "Body" };+ let md1 = toSkillMd(s);+ for (let k = 0; k < 3; k++) {+ const r = parseSkillMd(md1);+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.skill).toMatchObject({ title: s.title, description: s.description, whenToUse: s.whenToUse });+ md1 = toSkillMd({ ...r.skill, tags: s.tags });+ }+ // Hand-written YAML: a lone backslash in double quotes is kept, single quotes double up.+ expect(parseFrontmatter(`a: "C:\\d"\nb: 'it''s'\nc: plain # comment`)).toEqual({ a: "C:\\d", b: "it's", c: "plain" });+ });+it("makes names from titles", () => {expect(skillSlug("Café Reels — 2026!")).toBe("cafe-reels-2026");expect(skillSlug("!!!")).toBe("my-skill");@@ -126,6 +141,32 @@ Tooling: Uses an RTX 4090 with ComfyUI{ category: "Tooling", text: "Uses an RTX 4090 with ComfyUI" },]);});+ it("reads a real ChatGPT memory answer: lead-in, bold labels, dates and the sign-off", () => {+ const items = parseMemoryImport(`Sure! Here's what I remember about you:++1. **Name**: Sam+2. **Preferences**: Prefers vertical 9:16 videos for social.+3. **Work:** Runs a small video studio in Lisbon.+4. Uses ComfyUI on an RTX 4090.+5. [2025-03-12] Likes warm, *filmic* colour grading.+6. March 3, 2025 — Wants replies short and direct.++**Your communication preferences:**+- I remember that you hate emoji in captions.++Here’s everything I know.+Let me know if you'd like me to update or forget any of these!`);+ expect(items).toEqual([+ { category: "Notes", text: "Name: Sam" },+ { category: "Preference", text: "Prefers vertical 9:16 videos for social." },+ { category: "Tooling", text: "Work: Runs a small video studio in Lisbon." },+ { category: "Environment", text: "Uses ComfyUI on an RTX 4090." },+ { category: "Style", text: "Likes warm, filmic colour grading." },+ { category: "Communication", text: "Wants replies short and direct." },+ { category: "Communication", text: "You hate emoji in captions." },+ ]);+ });+it("reads JSON exports too", () => {expect(parseMemoryImport(JSON.stringify({ memories: [{ content: "Brand colour is teal #1E9E8F", category: "convention" }, "Call me Sam"] }))).toEqual([{ category: "Convention", text: "Brand colour is teal #1E9E8F" },@@ -311,6 +352,26 @@ describe("projects", () => {expect(projects.getProject(p.id)!.sources).toHaveLength(19);});+ it("renaming or deleting a project's only skill keeps the project usable", async () => {+ const { skillsFor, canUseSkill } = await import("@/server/assist/context");+ skills.createSkill({ name: "only-one", title: "Only one", description: "The project's skill.", body: "# Do" });+ const p = projects.createProject({ name: "One skill", skills: ["only-one"] });+ const t = agent.createThread({ engine: "cloud", agent: "offline", projectId: p.id });+ agent.addMessage(t.id, "/only-one hello");+ expect(skillsFor(p.id).map((s) => s.name)).toEqual(["only-one"]);+ skills.updateSkill("only-one", { name: "only-two" });+ expect(projects.getProject(p.id)!.skills).toEqual(["only-two"]);+ expect(canUseSkill("only-two", p.id)).toBe(true);+ skills.deleteSkill("only-two");+ expect(projects.getProject(p.id)!.skills).toEqual([]);+ // With none of its own left, the project falls back to every enabled skill.+ expect(skillsFor(p.id).length).toBeGreaterThan(10);+ expect(canUseSkill("narration", p.id)).toBe(true);+ // A project that still lists a skill that has vanished (an old row) falls back too.+ db().prepare("UPDATE assist_projects SET skills_json = ? WHERE id = ?").run(JSON.stringify(["gone-skill"]), p.id);+ expect(canUseSkill("narration", p.id)).toBe(true);+ });+it("deleting a project keeps its chats as personal chats and drops its memory", () => {const p = projects.createProject({ name: "Doomed" });const t = agent.createThread({ engine: "cloud", agent: "offline", projectId: p.id });