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
@@ -18,6 +18,7 @@ This module provides OpenCode server integration utilities for the web server ru
- `packages/web/server/lib/opencode/network-runtime.js`: OpenCode URL construction, health-probe readiness checks, and API prefix runtime.
- `packages/web/server/lib/opencode/project-directory-runtime.js`: request-scoped and settings-backed project directory resolution/validation runtime.
- `packages/web/server/lib/opencode/config-entity-routes.js`: route registration for agent/command/MCP config orchestration and reload semantics.
- `packages/web/server/lib/opencode/snippets.js`: opencode-snippets-compatible snippet file CRUD, discovery, and hashtag expansion.
- `packages/web/server/lib/opencode/cli-options.js`: CLI/environment option parsing for server startup arguments.
- `packages/web/server/lib/opencode/core-routes.js`: server status/system routes, auth/access guard routes, and settings utility route registration.
- `packages/web/server/lib/opencode/shutdown-runtime.js`: graceful shutdown orchestration runtime for watcher/session/terminal/process/server teardown.
@@ -211,6 +212,7 @@ This module provides OpenCode server integration utilities for the web server ru
- Agents: `/api/config/agents/:name` and `/api/config/agents/:name/config`
- Commands: `/api/config/commands/:name`
- MCP servers: `/api/config/mcp` and `/api/config/mcp/:name`
- Snippets: `/api/config/snippets`, `/api/config/snippets/:name`, and `/api/config/snippets/expand`
## Public exports (auth-state-runtime.js)
- `createOpenCodeAuthStateRuntime(dependencies)`: creates runtime for managed OpenCode auth password state and request headers.
@@ -18,11 +18,12 @@ export const registerConfigEntityRoutes = (app, dependencies) => {
createMcpConfig,
updateMcpConfig,
deleteMcpConfig,
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
listSnippets,
getSnippet,
createSnippet,
updateSnippet,
deleteSnippet,
expandSnippets,
} = dependencies;
const completeMcpMutation = async (res, action, name, applyChange) => {
@@ -373,94 +374,112 @@ export const registerConfigEntityRoutes = (app, dependencies) => {
}
});
app.get('/api/config/prompt-templates', async (req, res) => {
app.get('/api/config/snippets', async (req, res) => {
try {
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
const templates = listPromptTemplates(directory);
res.json(templates);
res.json(listSnippets(directory));
} catch (error) {
console.error('[API:GET /api/config/prompt-templates] Failed:', error);
res.status(500).json({ error: error.message || 'Failed to list prompt templates' });
console.error('[API:GET /api/config/snippets] Failed:', error);
res.status(500).json({ error: error.message || 'Failed to list snippets' });
}
});
app.get('/api/config/prompt-templates/:id', async (req, res) => {
app.post('/api/config/snippets/expand', async (req, res) => {
try {
const id = req.params.id;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
const template = getPromptTemplate(id, directory);
if (!template) {
return res.status(404).json({ error: `Prompt template "${id}" not found` });
}
res.json(template);
res.json({ text: expandSnippets(req.body?.text ?? '', directory) });
} catch (error) {
console.error('[API:GET /api/config/prompt-templates/:id] Failed:', error);
res.status(500).json({ error: error.message || 'Failed to get prompt template' });
console.error('[API:POST /api/config/snippets/expand] Failed:', error);
res.status(500).json({ error: error.message || 'Failed to expand snippets' });
}
});
app.post('/api/config/prompt-templates/:id', async (req, res) => {
app.get('/api/config/snippets/:name', async (req, res) => {
try {
const id = req.params.id;
const config = req.body || {};
const name = req.params.name;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
console.log(`[API:POST /api/config/prompt-templates] Creating prompt template: ${id}`);
const template = createPromptTemplate(id, config, directory);
res.json({ success: true, template });
const snippet = getSnippet(name, directory);
if (!snippet) {
return res.status(404).json({ error: `Snippet "${name}" not found` });
}
res.json(snippet);
} catch (error) {
console.error('[API:POST /api/config/prompt-templates/:id] Failed:', error);
console.error('[API:GET /api/config/snippets/:name] Failed:', error);
if (error.message?.includes('Snippet name')) {
return res.status(400).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to get snippet' });
}
});
app.post('/api/config/snippets/:name', async (req, res) => {
try {
const name = req.params.name;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
const snippet = createSnippet(name, req.body || {}, directory, req.body?.scope || 'global');
res.json({ success: true, snippet });
} catch (error) {
console.error('[API:POST /api/config/snippets/:name] Failed:', error);
if (error.message?.includes('already exists')) {
return res.status(409).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to create prompt template' });
if (error.message?.includes('Snippet name') || error.message?.includes('Project directory')) {
return res.status(400).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to create snippet' });
}
});
app.patch('/api/config/prompt-templates/:id', async (req, res) => {
app.patch('/api/config/snippets/:name', async (req, res) => {
try {
const id = req.params.id;
const updates = req.body;
const name = req.params.name;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
console.log(`[API:PATCH /api/config/prompt-templates] Updating prompt template: ${id}`);
const template = updatePromptTemplate(id, updates, directory);
res.json({ success: true, template });
res.json({ success: true, snippet: updateSnippet(name, req.body || {}, directory) });
} catch (error) {
console.error('[API:PATCH /api/config/prompt-templates/:id] Failed:', error);
console.error('[API:PATCH /api/config/snippets/:name] Failed:', error);
if (error.message?.includes('not found')) {
return res.status(404).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to update prompt template' });
if (error.message?.includes('Snippet name')) {
return res.status(400).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to update snippet' });
}
});
app.delete('/api/config/prompt-templates/:id', async (req, res) => {
app.delete('/api/config/snippets/:name', async (req, res) => {
try {
const id = req.params.id;
const name = req.params.name;
const { directory, error } = await resolveOptionalProjectDirectory(req);
if (error) {
return res.status(400).json({ error });
}
console.log(`[API:DELETE /api/config/prompt-templates] Deleting prompt template: ${id}`);
deletePromptTemplate(id, directory);
deleteSnippet(name, directory);
res.json({ success: true });
} catch (error) {
console.error('[API:DELETE /api/config/prompt-templates/:id] Failed:', error);
console.error('[API:DELETE /api/config/snippets/:name] Failed:', error);
if (error.message?.includes('not found')) {
return res.status(404).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to delete prompt template' });
if (error.message?.includes('Snippet name')) {
return res.status(400).json({ error: error.message });
}
res.status(500).json({ error: error.message || 'Failed to delete snippet' });
}
});
};
@@ -464,6 +464,7 @@ export const registerCommonRequestMiddleware = (app, dependencies) => {
req.path.startsWith('/api/config/agents') ||
req.path.startsWith('/api/config/commands') ||
req.path.startsWith('/api/config/mcp') ||
req.path.startsWith('/api/config/snippets') ||
req.path.startsWith('/api/config/settings') ||
req.path.startsWith('/api/config/skills') ||
req.path.startsWith('/api/projects') ||
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
import express from 'express';
import request from 'supertest';
import { registerServerStatusRoutes } from './core-routes.js';
import { registerCommonRequestMiddleware, registerServerStatusRoutes } from './core-routes.js';
describe('core-routes', () => {
it('should call gracefulShutdown with exitProcess: true on /api/system/shutdown', async () => {
@@ -14,6 +14,7 @@ describe('core-routes', () => {
getHealthSnapshot: () => ({ status: 'ok' }),
openchamberVersion: '1.0.0',
runtimeName: 'test',
express,
};
registerServerStatusRoutes(app, dependencies);
@@ -23,4 +24,19 @@ describe('core-routes', () => {
expect(dependencies.gracefulShutdown).toHaveBeenCalled();
expect(shutdownOpts).toEqual({ exitProcess: true });
});
it('should parse JSON bodies for snippet config routes', async () => {
const app = express();
registerCommonRequestMiddleware(app, { express });
app.post('/api/config/snippets/example', (req, res) => {
res.json({ body: req.body });
});
const response = await request(app)
.post('/api/config/snippets/example')
.send({ content: 'Snippet body' })
.expect(200);
expect(response.body).toEqual({ body: { content: 'Snippet body' } });
});
});
@@ -123,11 +123,12 @@ export const createFeatureRoutesRuntime = (dependencies) => {
createMcpConfig,
updateMcpConfig,
deleteMcpConfig,
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
listSnippets,
getSnippet,
createSnippet,
updateSnippet,
deleteSnippet,
expandSnippets,
} = await import('./index.js');
registerConfigEntityRoutes(app, {
@@ -149,11 +150,12 @@ export const createFeatureRoutesRuntime = (dependencies) => {
createMcpConfig,
updateMcpConfig,
deleteMcpConfig,
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
listSnippets,
getSnippet,
createSnippet,
updateSnippet,
deleteSnippet,
expandSnippets,
});
const {
+7 -7
View File
@@ -66,10 +66,10 @@ export {
} from './mcp.js';
export {
listPromptTemplates,
getPromptTemplate,
createPromptTemplate,
updatePromptTemplate,
deletePromptTemplate,
slugify as slugifyPromptTemplate,
} from './prompt-templates.js';
listSnippets,
getSnippet,
createSnippet,
updateSnippet,
deleteSnippet,
expandSnippets,
} from './snippets.js';
@@ -1,159 +0,0 @@
import {
readConfigLayers,
writeConfig,
getJsonWriteTarget,
CONFIG_FILE,
} from './shared.js';
const SECTION_KEY = 'promptTemplates';
const DEFAULT_TEMPLATES = {
simple: {
name: 'Simple',
body: 'Implement this task using the simplest possible approach. Prefer readability and straightforward solutions over clever abstractions. Keep the code easy to understand and maintain.',
isDefault: true,
},
fast: {
name: 'Fast',
body: 'Implement this task as quickly as possible. Optimize for speed of development. Use the most direct path to a working solution. Favor existing libraries and proven patterns.',
isDefault: true,
},
'memory-efficient': {
name: 'Memory Efficient',
body: 'Implement this task with memory efficiency in mind. Minimize memory allocations, use streaming where possible, avoid holding large data structures in memory, and prefer lazy evaluation.',
isDefault: true,
},
'cpu-efficient': {
name: 'CPU Efficient',
body: 'Implement this task with CPU efficiency in mind. Optimize algorithms, minimize unnecessary computations, use efficient data structures, and avoid redundant work.',
isDefault: true,
},
'tests-first': {
name: 'Tests First',
body: 'Implement this task using a test-driven approach. Write tests first, then implement the minimum code to pass them. Ensure comprehensive test coverage including edge cases.',
isDefault: true,
},
'spec-first': {
name: 'Spec First',
body: 'Implement this task by first creating a detailed specification, then implementing according to the spec. Start by documenting the requirements, interfaces, and expected behavior before writing any implementation code.',
isDefault: true,
},
};
function slugify(name) {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.substring(0, 60);
}
function ensureDefaults(templates) {
if (!templates || typeof templates !== 'object') {
return { ...DEFAULT_TEMPLATES };
}
let changed = false;
const result = { ...templates };
for (const [id, template] of Object.entries(DEFAULT_TEMPLATES)) {
if (!(id in result)) {
result[id] = { ...template };
changed = true;
}
}
return changed ? result : templates;
}
function readTemplatesFromConfig(workingDirectory) {
const layers = readConfigLayers(workingDirectory);
const merged = layers.mergedConfig || {};
const raw = merged[SECTION_KEY];
if (!raw || typeof raw !== 'object') {
return ensureDefaults(null);
}
return ensureDefaults(raw);
}
function writeTemplatesToConfig(templates, workingDirectory) {
const layers = readConfigLayers(workingDirectory);
const target = getJsonWriteTarget(layers, 'user');
const config = { ...target.config };
config[SECTION_KEY] = templates;
writeConfig(config, target.path || CONFIG_FILE);
}
export function listPromptTemplates(workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
return Object.entries(templates).map(([id, value]) => ({
id,
name: value.name || id,
body: value.body || '',
isDefault: value.isDefault === true,
}));
}
export function getPromptTemplate(id, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
const entry = templates[id];
if (!entry) {
return null;
}
return {
id,
name: entry.name || id,
body: entry.body || '',
isDefault: entry.isDefault === true,
};
}
export function createPromptTemplate(id, config, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
if (templates[id]) {
throw new Error(`Prompt template "${id}" already exists`);
}
templates[id] = {
name: config.name || id,
body: config.body || '',
isDefault: false,
};
writeTemplatesToConfig(templates, workingDirectory);
return getPromptTemplate(id, workingDirectory);
}
export function updatePromptTemplate(id, updates, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
const existing = templates[id];
if (!existing) {
throw new Error(`Prompt template "${id}" not found`);
}
templates[id] = {
...existing,
...(updates.name !== undefined ? { name: updates.name } : {}),
...(updates.body !== undefined ? { body: updates.body } : {}),
};
writeTemplatesToConfig(templates, workingDirectory);
return getPromptTemplate(id, workingDirectory);
}
export function deletePromptTemplate(id, workingDirectory) {
const templates = readTemplatesFromConfig(workingDirectory);
if (!templates[id]) {
throw new Error(`Prompt template "${id}" not found`);
}
delete templates[id];
writeTemplatesToConfig(templates, workingDirectory);
}
export { slugify };
@@ -0,0 +1,233 @@
import fs from 'fs';
import path from 'path';
import os from 'os';
import yaml from 'yaml';
const OPENCODE_CONFIG_DIR = path.join(os.homedir(), '.config', 'opencode');
const GLOBAL_SNIPPET_DIR = path.join(OPENCODE_CONFIG_DIR, 'snippet');
const GLOBAL_SNIPPET_DIR_ALT = path.join(OPENCODE_CONFIG_DIR, 'snippets');
const SNIPPET_EXTENSION = '.md';
const SNIPPET_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,79}$/i;
const HASHTAG_PATTERN = /#([a-z0-9_-]+)/gi;
const MAX_EXPANSION_COUNT = 15;
function getProjectSnippetDirs(workingDirectory) {
if (!workingDirectory) return [];
return [
path.join(workingDirectory, '.opencode', 'snippets'),
path.join(workingDirectory, '.opencode', 'snippet'),
];
}
function getGlobalSnippetDirs() {
return [GLOBAL_SNIPPET_DIR_ALT, GLOBAL_SNIPPET_DIR];
}
function getLoadDirs(workingDirectory) {
return [
...getGlobalSnippetDirs().map((dir) => ({ dir, source: 'global' })),
...getProjectSnippetDirs(workingDirectory).map((dir) => ({ dir, source: 'project' })),
];
}
function assertValidSnippetName(name) {
if (typeof name !== 'string' || !SNIPPET_NAME_PATTERN.test(name)) {
throw new Error('Snippet name must use letters, numbers, dashes, or underscores');
}
}
function parseMarkdownFile(filePath) {
const content = fs.readFileSync(filePath, 'utf8');
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) {
return { frontmatter: {}, body: content.trim() };
}
return {
frontmatter: yaml.parse(match[1]) || {},
body: match[2].trim(),
};
}
function normalizeAliases(frontmatter) {
const raw = frontmatter.aliases ?? frontmatter.alias;
if (!raw) return [];
const aliases = Array.isArray(raw) ? raw : [raw];
return aliases.map((alias) => String(alias).trim()).filter(Boolean);
}
function writeMarkdownFile(filePath, { content, aliases = [], description }) {
const frontmatter = {};
const normalizedAliases = aliases.map((alias) => String(alias).trim()).filter(Boolean);
if (normalizedAliases.length > 0) frontmatter.aliases = normalizedAliases;
if (description?.trim()) frontmatter.description = description.trim();
const body = content ?? '';
const output = Object.keys(frontmatter).length > 0
? `---\n${yaml.stringify(frontmatter)}---\n${body ? `\n${body}` : ''}`
: body;
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, output, 'utf8');
}
function loadSnippetFile(dir, filename, source) {
const name = path.basename(filename, SNIPPET_EXTENSION);
if (!SNIPPET_NAME_PATTERN.test(name)) return null;
const filePath = path.join(dir, filename);
const { frontmatter, body } = parseMarkdownFile(filePath);
return {
name,
content: body,
aliases: normalizeAliases(frontmatter),
description: typeof frontmatter.description === 'string' ? frontmatter.description : undefined,
filePath,
source,
};
}
function registerSnippet(registry, snippet) {
const key = snippet.name.toLowerCase();
const existing = registry.get(key);
if (existing) {
for (const alias of existing.aliases) registry.delete(alias.toLowerCase());
}
registry.set(key, snippet);
for (const alias of snippet.aliases) {
if (SNIPPET_NAME_PATTERN.test(alias)) registry.set(alias.toLowerCase(), snippet);
}
}
function loadSnippetRegistry(workingDirectory) {
const registry = new Map();
for (const { dir, source } of getLoadDirs(workingDirectory)) {
if (!fs.existsSync(dir)) continue;
for (const filename of fs.readdirSync(dir)) {
if (!filename.endsWith(SNIPPET_EXTENSION)) continue;
try {
const snippet = loadSnippetFile(dir, filename, source);
if (snippet) registerSnippet(registry, snippet);
} catch (error) {
console.warn(`[Snippets] Failed to load ${path.join(dir, filename)}:`, error);
}
}
}
return registry;
}
function listUniqueSnippets(registry) {
const seen = new Set();
const snippets = [];
for (const snippet of registry.values()) {
const key = `${snippet.source}:${snippet.filePath}`;
if (seen.has(key)) continue;
seen.add(key);
snippets.push(snippet);
}
return snippets.sort((a, b) => a.name.localeCompare(b.name));
}
function getWritableSnippetDir(scope, workingDirectory) {
if (scope === 'project') {
if (!workingDirectory) throw new Error('Project directory is required for project snippets');
const preferred = path.join(workingDirectory, '.opencode', 'snippet');
const alternate = path.join(workingDirectory, '.opencode', 'snippets');
return fs.existsSync(alternate) && !fs.existsSync(preferred) ? alternate : preferred;
}
return fs.existsSync(GLOBAL_SNIPPET_DIR_ALT) && !fs.existsSync(GLOBAL_SNIPPET_DIR)
? GLOBAL_SNIPPET_DIR_ALT
: GLOBAL_SNIPPET_DIR;
}
function findSnippetByName(name, workingDirectory) {
assertValidSnippetName(name);
const registry = loadSnippetRegistry(workingDirectory);
return registry.get(name.toLowerCase()) ?? null;
}
function parseSnippetBlocks(content) {
const blocks = { prepend: [], append: [] };
let inline = content;
for (const type of ['prepend', 'append']) {
const regex = new RegExp(`<${type}>([\\s\\S]*?)(?:<\\/${type}>|$)`, 'gi');
inline = inline.replace(regex, (_match, value) => {
const normalized = String(value).trim();
if (normalized) blocks[type].push(normalized);
return '';
});
}
inline = inline.replace(/<inject>[\s\S]*?(?:<\/inject>|$)/gi, '').trim();
return { inline, prepend: blocks.prepend, append: blocks.append };
}
function expandText(text, registry, expansionCounts, collector) {
let expanded = text;
let changed = true;
while (changed) {
const previous = expanded;
let loopDetected = false;
HASHTAG_PATTERN.lastIndex = 0;
expanded = expanded.replace(HASHTAG_PATTERN, (match, name, offset, input) => {
if (name.toLowerCase() === 'skill' && input[offset + match.length] === '(') return match;
const snippet = registry.get(name.toLowerCase());
if (!snippet) return match;
const key = snippet.name.toLowerCase();
const count = (expansionCounts.get(key) || 0) + 1;
if (count > MAX_EXPANSION_COUNT) {
loopDetected = true;
return match;
}
expansionCounts.set(key, count);
const parsed = parseSnippetBlocks(snippet.content);
for (const block of parsed.prepend) collector.prepend.push(expandText(block, registry, expansionCounts, collector));
for (const block of parsed.append) collector.append.push(expandText(block, registry, expansionCounts, collector));
return expandText(parsed.inline, registry, expansionCounts, collector);
});
changed = expanded !== previous && !loopDetected;
}
return expanded;
}
export function listSnippets(workingDirectory) {
return listUniqueSnippets(loadSnippetRegistry(workingDirectory));
}
export function getSnippet(name, workingDirectory) {
return findSnippetByName(name, workingDirectory);
}
export function createSnippet(name, config, workingDirectory, scope = 'global') {
assertValidSnippetName(name);
const dir = getWritableSnippetDir(scope, workingDirectory);
const filePath = path.join(dir, `${name}${SNIPPET_EXTENSION}`);
if (fs.existsSync(filePath)) throw new Error(`Snippet "${name}" already exists`);
writeMarkdownFile(filePath, config || {});
return getSnippet(name, workingDirectory);
}
export function updateSnippet(name, updates, workingDirectory) {
const existing = findSnippetByName(name, workingDirectory);
if (!existing) throw new Error(`Snippet "${name}" not found`);
writeMarkdownFile(existing.filePath, { ...existing, ...(updates || {}) });
return getSnippet(name, workingDirectory);
}
export function deleteSnippet(name, workingDirectory) {
const existing = findSnippetByName(name, workingDirectory);
if (!existing) throw new Error(`Snippet "${name}" not found`);
fs.unlinkSync(existing.filePath);
}
export function expandSnippets(text, workingDirectory) {
const registry = loadSnippetRegistry(workingDirectory);
const collector = { prepend: [], append: [] };
const expanded = expandText(text || '', registry, new Map(), collector).trim();
return [...collector.prepend, expanded, ...collector.append].filter(Boolean).join('\n\n');
}
export { assertValidSnippetName };
@@ -0,0 +1,68 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import fs from 'fs';
import os from 'os';
import path from 'path';
import {
createSnippet,
deleteSnippet,
expandSnippets,
getSnippet,
listSnippets,
updateSnippet,
} from './snippets.js';
let projectDir;
function writeSnippet(relativePath, content) {
const filePath = path.join(projectDir, relativePath);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content, 'utf8');
}
describe('snippets', () => {
beforeEach(() => {
projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-snippets-'));
});
afterEach(() => {
fs.rmSync(projectDir, { recursive: true, force: true });
});
test('loads project snippets with aliases and description', () => {
writeSnippet('.opencode/snippet/review.md', '---\naliases: [rev]\ndescription: Review helper\n---\nReview carefully.');
expect(listSnippets(projectDir)).toContainEqual(
expect.objectContaining({ name: 'review', aliases: ['rev'], description: 'Review helper', source: 'project' }),
);
expect(getSnippet('rev', projectDir)).toEqual(expect.objectContaining({ name: 'review' }));
});
test('snippet directory wins over snippets directory', () => {
writeSnippet('.opencode/snippets/same.md', 'Old');
writeSnippet('.opencode/snippet/same.md', 'New');
expect(getSnippet('same', projectDir)?.content).toBe('New');
});
test('creates updates and deletes snippets', () => {
expect(createSnippet('custom-one', { content: 'Body', aliases: ['co'] }, projectDir, 'project')).toEqual(
expect.objectContaining({ name: 'custom-one', content: 'Body', aliases: ['co'] }),
);
expect(updateSnippet('custom-one', { content: 'Updated' }, projectDir)).toEqual(
expect.objectContaining({ name: 'custom-one', content: 'Updated', aliases: ['co'] }),
);
deleteSnippet('custom-one', projectDir);
expect(getSnippet('custom-one', projectDir)).toBeNull();
});
test('expands snippets recursively with prepend and append blocks', () => {
writeSnippet('.opencode/snippet/base.md', 'Base text');
writeSnippet('.opencode/snippet/review.md', '<prepend>Before</prepend>Review #base<append>After</append>');
expect(expandSnippets('Please #review', projectDir)).toBe('Before\n\nPlease Review Base text\n\nAfter');
});
test('rejects invalid snippet names', () => {
expect(() => createSnippet('../bad', { content: '' }, projectDir, 'project')).toThrow('Snippet name');
});
});