feat: replace prompt templates with snippets

Replace the prompt-template workflow with snippet support that is compatible with opencode snippet conventions. Snippets are now stored and loaded from global and project snippet directories, including legacy pluralized paths, with frontmatter metadata for aliases and descriptions. Snippet expansion supports recursive references plus prepend and append sections, while inject sections are treated as unsupported no-ops so OpenChamber remains compatible without requiring an external plugin.

Add the snippets settings experience and remove the old prompt-template settings surface. The new settings page and sidebar support creating, editing, deleting, selecting, and describing snippets, with localized copy across every supported locale. The settings navigation now exposes Snippets with a dedicated icon and metadata.

Wire snippets into all prompt-entry surfaces that need them. Chat, multi-run groups, and scheduled task prompts now offer hash-trigger snippet autocomplete and expand snippets before sending work to OpenCode. Chat also uses an adaptive compact placeholder on mobile or narrow composer widths so helper trigger guidance stays readable in constrained layouts.

Keep multi-run aligned with grouped prompts. Multi-run sessions now use a shared title builder that handles both legacy titles and the newer g1, g2 prompt-group title format. Fusion parsing now recognizes grouped multi-run titles, scopes fusion sources to the same prompt group, and creates fusion sessions under the matching group so outputs from different prompts are not mixed accidentally.

Harden the icon sprite pipeline. The sprite generator now discovers icon names used through typed icon maps, JSX icon props, IconName returns, and generated-value flows without scanning unrelated string literals or the generated sprite itself. The generated sprite is strictly typed so invalid icon names are caught by type checking, and existing invalid or unsafe icon references were cleaned up across settings, provider, Git identity, scheduled task, voice, header, and sidebar surfaces.

Update backend configuration routes and documentation for snippets. The OpenCode config route layer now exposes snippet CRUD and expansion endpoints, accepts JSON bodies for snippet writes, and removes the old prompt-template provider. Scheduled task runtime expansion now uses snippets before dispatching messages.

Add regression coverage for snippet storage and expansion, config-route JSON handling, and multi-run title parsing. Validated with full type checking, full linting, targeted multi-run title tests, and targeted OpenCode snippet/config route tests.
This commit is contained in:
Bohdan Triapitsyn
2026-05-21 20:00:35 +03:00
parent 7d98f388c0
commit 6fd3afd25a
53 changed files with 2037 additions and 1054 deletions
+199 -78
View File
@@ -8,13 +8,14 @@
* packages/ui/src/components/icon/sprite.ts.
*/
import { readFileSync, writeFileSync } from "node:fs"
import { readFileSync, writeFileSync, readdirSync, statSync } from "node:fs"
import { resolve, dirname } from "node:path"
import { fileURLToPath } from "node:url"
const __dirname = dirname(fileURLToPath(import.meta.url))
const repoRoot = resolve(__dirname, "..")
const remixPath = resolve(repoRoot, "node_modules/@remixicon/react/index.mjs")
const outPath = resolve(repoRoot, "packages/ui/src/components/icon/sprite.ts")
const source = readFileSync(remixPath, "utf-8")
@@ -73,6 +74,35 @@ for (const entry of entries) {
}
}
const remixToSpriteName = (name) => {
// RiArrowDownSLine → arrow-down-s
// RiGithubFill → github-fill (keep Fill for fill variants)
return name
.replace(/^Ri/, "")
.replace(/Line$/, "")
.replace(/([a-z])([A-Z0-9])/g, "$1-$2")
.replace(/([0-9])([A-Z])/g, "$1-$2")
.toLowerCase()
}
const spriteNameToRi = new Map()
const hasRemixVariantSuffix = (name) => name.endsWith("Line") || name.endsWith("Fill")
const shouldPreferSpriteCandidate = (current, candidate) => {
if (!current) return true
if (!hasRemixVariantSuffix(candidate) && hasRemixVariantSuffix(current)) return true
if (!hasRemixVariantSuffix(current)) return false
if (candidate.endsWith("Line") && !current.endsWith("Line")) return true
return false
}
for (const iconName of nameToVar.keys()) {
const spriteName = remixToSpriteName(iconName)
const current = spriteNameToRi.get(spriteName)
if (shouldPreferSpriteCandidate(current, iconName)) {
spriteNameToRi.set(spriteName, iconName)
}
}
// --- Step 3: find which icons we actually use ---
const srcDir = resolve(repoRoot, "packages/ui/src")
@@ -92,40 +122,7 @@ function nameToRi(kebab) {
return result
}
const srcFiles = []
function walk(dir) {
const { readdirSync, statSync } = require("node:fs")
for (const entry of readdirSync(dir)) {
const full = resolve(dir, entry)
if (statSync(full).isDirectory()) {
if (entry === "node_modules") continue
walk(full)
} else if (/\.(tsx?|jsx?)$/.test(entry)) {
srcFiles.push(full)
}
}
}
import("node:fs").then(({ readdirSync, statSync: st }) => {
// Already imported above, use recursive function
function localWalk(dir) {
const { readdirSync: rd, statSync: s } = require("node:fs")
for (const entry of rd(dir)) {
const full = resolve(dir, entry)
try {
if (s(full).isDirectory()) {
if (entry === "node_modules") continue
localWalk(full)
} else if (/\.(tsx?)$/.test(entry)) {
srcFiles.push(full)
}
} catch {}
}
}
localWalk(srcDir)
})
// Finish step 3 synchronously with simpler approach
import { readdirSync, statSync } from "node:fs"
function findAllSourceFiles(dir) {
const results = []
for (const entry of readdirSync(dir)) {
@@ -135,7 +132,7 @@ function findAllSourceFiles(dir) {
if (st.isDirectory()) {
if (entry === "node_modules") continue
results.push(...findAllSourceFiles(full))
} else if (/\.(tsx?)$/.test(entry)) {
} else if (/\.(tsx?)$/.test(entry) && full !== outPath) {
results.push(full)
}
} catch { /* skip */ }
@@ -143,18 +140,157 @@ function findAllSourceFiles(dir) {
return results
}
// Helper: convert kebab-case name back to RiX name
function nameToRi(kebab) {
const parts = kebab.split("-")
let result = "Ri"
for (let i = 0; i < parts.length; i++) {
result += parts[i].charAt(0).toUpperCase() + parts[i].slice(1)
}
return result
}
const allSrcFiles = findAllSourceFiles(srcDir)
const usedIcons = new Set()
const addKebabIcon = (kebab) => {
const exactRiName = spriteNameToRi.get(kebab)
if (exactRiName && !hasRemixVariantSuffix(exactRiName)) {
usedIcons.add(exactRiName)
return true
}
for (const suffix of ["Line", "Fill", ""]) {
const riName = nameToRi(kebab) + suffix
if (nameToVar.has(riName)) {
usedIcons.add(riName)
return true
}
}
if (exactRiName) {
usedIcons.add(exactRiName)
return true
}
return false
}
const addIconLiterals = (content) => {
const iconLiteralRegex = /["']([a-z][a-z0-9-]*)["']/g
let literal
while ((literal = iconLiteralRegex.exec(content)) !== null) {
addKebabIcon(literal[1])
}
}
function findMatchingBrace(content, openBraceIndex) {
let depth = 0
let quote = null
let escaped = false
let lineComment = false
let blockComment = false
for (let i = openBraceIndex; i < content.length; i++) {
const char = content[i]
const next = content[i + 1]
if (lineComment) {
if (char === "\n") lineComment = false
continue
}
if (blockComment) {
if (char === "*" && next === "/") {
blockComment = false
i++
}
continue
}
if (quote) {
if (escaped) {
escaped = false
} else if (char === "\\") {
escaped = true
} else if (char === quote) {
quote = null
}
continue
}
if (char === "/" && next === "/") {
lineComment = true
i++
continue
}
if (char === "/" && next === "*") {
blockComment = true
i++
continue
}
if (char === "\"" || char === "'" || char === "`") {
quote = char
continue
}
if (char === "{") {
depth++
} else if (char === "}") {
depth--
if (depth === 0) return i
}
}
return -1
}
const addIconNameFunctionReturns = (content) => {
const functionRegex = /function\s+\w+\s*\([^)]*\)\s*:\s*IconName(?:\s*\|\s*null)?\s*{/g
let match
while ((match = functionRegex.exec(content)) !== null) {
const openBraceIndex = content.indexOf("{", match.index)
if (openBraceIndex === -1) continue
const closeBraceIndex = findMatchingBrace(content, openBraceIndex)
if (closeBraceIndex === -1) continue
const body = content.slice(openBraceIndex + 1, closeBraceIndex)
const returnRegex = /\breturn\s+["']([a-z][a-z0-9-]*)["']/g
let returnMatch
while ((returnMatch = returnRegex.exec(body)) !== null) {
addKebabIcon(returnMatch[1])
}
functionRegex.lastIndex = closeBraceIndex + 1
}
}
const addTypedIconNameRecords = (content) => {
const recordRegex = /:\s*Record<[^>]*IconName[^>]*>\s*=\s*{/g
let match
while ((match = recordRegex.exec(content)) !== null) {
const openBraceIndex = content.indexOf("{", match.index)
if (openBraceIndex === -1) continue
const closeBraceIndex = findMatchingBrace(content, openBraceIndex)
if (closeBraceIndex === -1) continue
addIconLiterals(content.slice(openBraceIndex + 1, closeBraceIndex))
recordRegex.lastIndex = closeBraceIndex + 1
}
}
const addIconNameVariableAssignments = (content) => {
if (!/<Icon\b/.test(content)) return
const variableRegex = /\b(?:const|let|var)\s+\w*IconName\b[^=]*=\s*([\s\S]*?);/g
let match
while ((match = variableRegex.exec(content)) !== null) {
const initializer = match[1]
const directLiteral = /^\s*["']([a-z][a-z0-9-]*)["']/.exec(initializer)
if (directLiteral) {
addKebabIcon(directLiteral[1])
}
const branchLiteralRegex = /(?:\?\?|[?:])\s*["']([a-z][a-z0-9-]*)["']/g
let branchLiteral
while ((branchLiteral = branchLiteralRegex.exec(initializer)) !== null) {
addKebabIcon(branchLiteral[1])
}
}
}
for (const file of allSrcFiles) {
const content = readFileSync(file, "utf-8")
// Match RiIcons from @remixicon/react imports
@@ -167,32 +303,29 @@ for (const file of allSrcFiles) {
}
// Also scan for <Icon name="..." /> patterns (already-migrated icons)
const iconNameRegex = /Icon\s+name="([^"]+)"/g
const iconNameRegex = /<Icon\b[^>]*\bname=(?:["']([^"']+)["']|{\s*["']([^"']+)["']\s*})/g
let nm
while ((nm = iconNameRegex.exec(content)) !== null) {
const kebab = nm[1]
for (const suffix of ["Line", "Fill", ""]) {
const riName = nameToRi(kebab) + suffix
if (nameToVar.has(riName)) {
usedIcons.add(riName)
break
}
}
addKebabIcon(nm[1] || nm[2])
}
// Also scan for icon: 'kebab-name' in object literals (e.g. MODALITY_ICON_MAP)
const iconPropRegex = /icon:\s*'([a-z][a-z0-9-]*)'/g
// Also scan for icon: 'kebab-name' / Icon: 'kebab-name' in object literals.
const iconPropRegex = /\b[Ii]con:\s*["']([a-z][a-z0-9-]*)["']/g
let ip
while ((ip = iconPropRegex.exec(content)) !== null) {
const kebab = ip[1]
for (const suffix of ["Line", "Fill", ""]) {
const riName = nameToRi(kebab) + suffix
if (nameToVar.has(riName)) {
usedIcons.add(riName)
break
}
}
addKebabIcon(ip[1])
}
// Also scan JSX props named icon/Icon with a string literal value.
const iconJsxPropRegex = /\b[Ii]con=(?:["']([^"']+)["']|{\s*["']([^"']+)["']\s*})/g
let jp
while ((jp = iconJsxPropRegex.exec(content)) !== null) {
addKebabIcon(jp[1] || jp[2])
}
addIconNameFunctionReturns(content)
addTypedIconNameRecords(content)
addIconNameVariableAssignments(content)
}
console.log(`Found ${usedIcons.size} unique remixicon names used in source`)
@@ -220,17 +353,6 @@ for (const iconName of [...usedIcons].sort()) {
}
// --- Step 5: write sprite.ts ---
const remixToSpriteName = (name) => {
// RiArrowDownSLine → arrow-down-s
// RiGithubFill → github-fill (keep Fill for fill variants)
return name
.replace(/^Ri/, "")
.replace(/Line$/, "")
.replace(/([a-z])([A-Z0-9])/g, "$1-$2")
.replace(/([0-9])([A-Z])/g, "$1-$2")
.toLowerCase()
}
const spriteLines = iconEntries.map(({ name, content }) => {
const spriteName = remixToSpriteName(name)
return ` "${spriteName}": \`${content}\`,`
@@ -239,12 +361,11 @@ const spriteLines = iconEntries.map(({ name, content }) => {
const spriteContent = `// This file is auto-generated by scripts/generate-icon-sprite.mjs
// Do not edit manually. Run the script to update.
export const iconSpriteData: Record<string, string> = {
export const iconSpriteData = {
${spriteLines.join("\n")}
};
} as const satisfies Record<string, string>;
`
const outPath = resolve(repoRoot, "packages/ui/src/components/icon/sprite.ts")
writeFileSync(outPath, spriteContent, "utf-8")
console.log(`\n✅ Generated sprite data for ${iconEntries.length} icons → ${outPath}`)
console.log(` Total sprite size: ${Buffer.byteLength(spriteContent).toLocaleString()} bytes`)