feat: expand magic prompts coverage and split generation prompts (#835)

- Add configurable visible/instructions prompt families for commit/PR generation, PR checks/comments flows, and git conflict resolution helpers.
- Refactor prompt sending to explicit visible + synthetic parts instead of newline-based splitting, with legacy override migration for old keys.
- Polish Magic Prompts settings UX with grouped sidebar entries, tooltip-based descriptions, AI icon, and validation that visible prompts cannot be empty across web and VS Code runtimes.
This commit is contained in:
Bohdan Triapitsyn
2026-04-07 22:51:14 +03:00
committed by GitHub
parent 2e5b02e753
commit 5f0d1623ae
21 changed files with 1415 additions and 279 deletions
@@ -0,0 +1,322 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { GridLoader } from '@/components/ui/grid-loader';
import { toast } from '@/components/ui';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { RiInformationLine } from '@remixicon/react';
import {
fetchMagicPromptOverrides,
getDefaultMagicPromptTemplate,
getMagicPromptDefinition,
resetAllMagicPromptOverrides,
resetMagicPromptOverride,
saveMagicPromptOverride,
type MagicPromptId,
} from '@/lib/magicPrompts';
import { useMagicPromptsStore } from '@/stores/useMagicPromptsStore';
type PromptBlock = {
id: MagicPromptId;
title: string;
};
type PromptPageConfig = {
title: string;
description: string;
blocks: PromptBlock[];
};
const PROMPT_PAGE_MAP: Record<string, PromptPageConfig> = {
'git.commit.generate': {
title: 'Commit Generation',
description: 'Prompts used for commit message generation: visible user message + hidden instructions.',
blocks: [
{ id: 'git.commit.generate.visible', title: 'Visible Prompt' },
{ id: 'git.commit.generate.instructions', title: 'Instructions' },
],
},
'git.pr.generate': {
title: 'PR Generation',
description: 'Prompts used for PR title/body generation: visible user message + hidden instructions.',
blocks: [
{ id: 'git.pr.generate.visible', title: 'Visible Prompt' },
{ id: 'git.pr.generate.instructions', title: 'Instructions' },
],
},
'github.pr.review': {
title: 'PR Review',
description: 'Prompts used for PR review flow: visible user message + hidden instruction payload.',
blocks: [
{ id: 'github.pr.review.visible', title: 'Visible Prompt' },
{ id: 'github.pr.review.instructions', title: 'Instructions' },
],
},
'github.issue.review': {
title: 'Issue Review',
description: 'Prompts used for issue review flow: visible user message + hidden instruction payload.',
blocks: [
{ id: 'github.issue.review.visible', title: 'Visible Prompt' },
{ id: 'github.issue.review.instructions', title: 'Instructions' },
],
},
'github.pr.checks.review': {
title: 'PR Failed Checks Review',
description: 'Prompts used for PR failed checks analysis.',
blocks: [
{ id: 'github.pr.checks.review.visible', title: 'Visible Prompt' },
{ id: 'github.pr.checks.review.instructions', title: 'Instructions' },
],
},
'github.pr.comments.review': {
title: 'PR Comments Review',
description: 'Prompts used for PR comments analysis.',
blocks: [
{ id: 'github.pr.comments.review.visible', title: 'Visible Prompt' },
{ id: 'github.pr.comments.review.instructions', title: 'Instructions' },
],
},
'github.pr.comment.single': {
title: 'Single PR Comment Review',
description: 'Prompts used for single PR comment analysis.',
blocks: [
{ id: 'github.pr.comment.single.visible', title: 'Visible Prompt' },
{ id: 'github.pr.comment.single.instructions', title: 'Instructions' },
],
},
'git.conflict.resolve': {
title: 'Merge/Rebase Conflict Resolution',
description: 'Prompts used when resolving merge/rebase conflicts with AI.',
blocks: [
{ id: 'git.conflict.resolve.visible', title: 'Visible Prompt' },
{ id: 'git.conflict.resolve.instructions', title: 'Instructions' },
],
},
'git.integrate.cherrypick.resolve': {
title: 'Cherry-pick Conflict Resolution',
description: 'Prompts used when resolving cherry-pick conflicts in integrate flow.',
blocks: [
{ id: 'git.integrate.cherrypick.resolve.visible', title: 'Visible Prompt' },
{ id: 'git.integrate.cherrypick.resolve.instructions', title: 'Instructions' },
],
},
};
const hasOwn = (input: Record<string, string>, key: string) => Object.prototype.hasOwnProperty.call(input, key);
const isVisiblePromptId = (id: MagicPromptId): boolean => id.endsWith('.visible');
export const MagicPromptsPage: React.FC = () => {
const selectedPromptId = useMagicPromptsStore((state) => state.selectedPromptId);
const [loading, setLoading] = React.useState(true);
const [overrides, setOverrides] = React.useState<Record<string, string>>({});
const [drafts, setDrafts] = React.useState<Record<string, string>>({});
const [savingIds, setSavingIds] = React.useState<Record<string, boolean>>({});
const [resettingIds, setResettingIds] = React.useState<Record<string, boolean>>({});
const [resettingAll, setResettingAll] = React.useState(false);
React.useEffect(() => {
let active = true;
const load = async () => {
setLoading(true);
try {
const nextOverrides = await fetchMagicPromptOverrides();
if (!active) return;
setOverrides(nextOverrides);
} catch (error) {
console.warn('Failed to load magic prompts:', error);
toast.error('Failed to load Magic Prompts');
} finally {
if (active) {
setLoading(false);
}
}
};
void load();
return () => {
active = false;
};
}, []);
const pageConfig = PROMPT_PAGE_MAP[selectedPromptId] ?? PROMPT_PAGE_MAP['git.commit.generate'];
const getBaseline = React.useCallback((id: MagicPromptId) => {
return hasOwn(overrides, id) ? overrides[id] : getDefaultMagicPromptTemplate(id);
}, [overrides]);
const getDraft = React.useCallback((id: MagicPromptId) => {
return drafts[id] ?? getBaseline(id);
}, [drafts, getBaseline]);
const setDraft = React.useCallback((id: MagicPromptId, value: string) => {
setDrafts((current) => {
if (current[id] === value) {
return current;
}
return { ...current, [id]: value };
});
}, []);
const savePrompt = React.useCallback(async (id: MagicPromptId) => {
const value = getDraft(id);
if (isVisiblePromptId(id) && value.trim().length === 0) {
toast.error('Visible prompt cannot be empty');
return;
}
setSavingIds((current) => ({ ...current, [id]: true }));
try {
const payload = value === getDefaultMagicPromptTemplate(id)
? await resetMagicPromptOverride(id)
: await saveMagicPromptOverride(id, value);
setOverrides(payload.overrides);
toast.success('Magic prompt saved');
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
toast.error('Failed to save magic prompt', { description: message });
} finally {
setSavingIds((current) => ({ ...current, [id]: false }));
}
}, [getDraft]);
const resetPrompt = React.useCallback(async (id: MagicPromptId) => {
setResettingIds((current) => ({ ...current, [id]: true }));
try {
const payload = await resetMagicPromptOverride(id);
setOverrides(payload.overrides);
setDrafts((current) => ({
...current,
[id]: getDefaultMagicPromptTemplate(id),
}));
toast.success('Prompt reset to default');
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
toast.error('Failed to reset prompt', { description: message });
} finally {
setResettingIds((current) => ({ ...current, [id]: false }));
}
}, []);
const handleResetAll = React.useCallback(async () => {
setResettingAll(true);
try {
const payload = await resetAllMagicPromptOverrides();
setOverrides(payload.overrides);
setDrafts({});
toast.success('All prompt overrides reset');
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
toast.error('Failed to reset all prompts', { description: message });
} finally {
setResettingAll(false);
}
}, []);
if (loading) {
return (
<div className="py-6 px-6 flex items-center gap-2 text-muted-foreground">
<GridLoader size="sm" />
<span className="typography-ui">Loading Magic Prompts...</span>
</div>
);
}
return (
<div className="h-full overflow-auto">
<div className="mx-auto w-full max-w-4xl px-6 py-6 space-y-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="space-y-1">
<div className="flex items-center gap-2">
<h2 className="typography-ui-header font-semibold text-foreground">{pageConfig.title}</h2>
<Tooltip delayDuration={700}>
<TooltipTrigger asChild>
<RiInformationLine className="h-3.5 w-3.5 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{pageConfig.description}
</TooltipContent>
</Tooltip>
</div>
</div>
<Button
variant="outline"
size="sm"
onClick={() => {
void handleResetAll();
}}
disabled={resettingAll || Object.keys(overrides).length === 0}
>
{resettingAll ? 'Resetting...' : 'Reset All Overrides'}
</Button>
</div>
{pageConfig.blocks.map((block, index) => {
const definition = getMagicPromptDefinition(block.id);
const baseline = getBaseline(block.id);
const draft = getDraft(block.id);
const isOverridden = hasOwn(overrides, block.id);
const isDirty = draft !== baseline;
const isInvalidEmptyVisiblePrompt = isVisiblePromptId(block.id) && draft.trim().length === 0;
const saving = savingIds[block.id] === true;
const resetting = resettingIds[block.id] === true;
return (
<section key={block.id} className={index > 0 ? 'space-y-3 pt-5 border-t border-border' : 'space-y-3'}>
<div className="space-y-1">
<div className="flex flex-wrap items-center gap-2">
<h3 className="typography-ui-label text-foreground">{block.title}</h3>
<Tooltip delayDuration={700}>
<TooltipTrigger asChild>
<RiInformationLine className="h-3.5 w-3.5 text-muted-foreground/60 cursor-help" />
</TooltipTrigger>
<TooltipContent sideOffset={8} className="max-w-xs">
{definition.description}
</TooltipContent>
</Tooltip>
</div>
{definition.placeholders && definition.placeholders.length > 0 && (
<div className="typography-micro text-muted-foreground">
Placeholders: {definition.placeholders.map((item) => `{{${item.key}}}`).join(', ')}
</div>
)}
</div>
<Textarea
value={draft}
onChange={(event) => setDraft(block.id, event.target.value)}
className="min-h-[220px] font-mono text-sm"
/>
{isInvalidEmptyVisiblePrompt && (
<div className="typography-micro text-[var(--status-error)]">Visible prompt cannot be empty.</div>
)}
<div className="flex items-center justify-between gap-2">
<span className="typography-micro text-muted-foreground">
{isDirty ? 'Unsaved changes' : isOverridden ? 'Using saved override' : 'Using built-in default'}
</span>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => {
void resetPrompt(block.id);
}}
disabled={!isOverridden || saving || resetting}
>
{resetting ? 'Resetting...' : 'Reset to Default'}
</Button>
<Button
size="sm"
onClick={() => {
void savePrompt(block.id);
}}
disabled={!isDirty || saving || resetting || isInvalidEmptyVisiblePrompt}
>
{saving ? 'Saving...' : 'Save'}
</Button>
</div>
</div>
</section>
);
})}
</div>
</div>
);
};
@@ -0,0 +1,73 @@
import React from 'react';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { useMagicPromptsStore } from '@/stores/useMagicPromptsStore';
import { cn } from '@/lib/utils';
interface MagicPromptsSidebarProps {
onItemSelect?: () => void;
}
export const MagicPromptsSidebar: React.FC<MagicPromptsSidebarProps> = ({ onItemSelect }) => {
const selectedPromptId = useMagicPromptsStore((state) => state.selectedPromptId);
const setSelectedPromptId = useMagicPromptsStore((state) => state.setSelectedPromptId);
const grouped = React.useMemo(() => {
return [
{
group: 'Git',
items: [
{ id: 'git.commit.generate', title: 'Commit Generation' },
{ id: 'git.pr.generate', title: 'PR Generation' },
{ id: 'git.conflict.resolve', title: 'Merge/Rebase Conflict Resolution' },
{ id: 'git.integrate.cherrypick.resolve', title: 'Cherry-pick Conflict Resolution' },
],
},
{
group: 'GitHub',
items: [
{ id: 'github.pr.review', title: 'PR Review' },
{ id: 'github.issue.review', title: 'Issue Review' },
{ id: 'github.pr.checks.review', title: 'PR Failed Checks Review' },
{ id: 'github.pr.comments.review', title: 'PR Comments Review' },
{ id: 'github.pr.comment.single', title: 'Single PR Comment Review' },
],
},
] as const;
}, []);
return (
<div className="flex h-full flex-col bg-background">
<div className="border-b px-3 pt-4 pb-3">
<h2 className="text-base font-semibold text-foreground">Magic Prompts</h2>
<p className="typography-meta mt-1 text-muted-foreground">Select a prompt template to edit.</p>
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-3 px-3 py-2 overflow-x-hidden">
{grouped.map((group) => (
<div key={group.group} className="space-y-1">
<div className="typography-micro px-1 text-muted-foreground">{group.group}</div>
{group.items.map((item) => {
const selected = selectedPromptId === item.id;
return (
<button
key={item.id}
type="button"
onClick={() => {
setSelectedPromptId(item.id);
onItemSelect?.();
}}
className={cn(
'flex w-full items-center rounded-md px-2 py-1.5 text-left transition-colors',
selected ? 'bg-interactive-selection text-foreground' : 'text-foreground hover:bg-interactive-hover'
)}
>
<span className="typography-ui-label truncate font-normal">{item.title}</span>
</button>
);
})}
</div>
))}
</ScrollableOverlay>
</div>
);
};
@@ -29,6 +29,7 @@ import { useContextStore } from '@/stores/contextStore';
import { useUIStore } from '@/stores/useUIStore';
import { useGitHubAuthStore } from '@/stores/useGitHubAuthStore';
import { opencodeClient } from '@/lib/opencode/client';
import { renderMagicPrompt } from '@/lib/magicPrompts';
import { createWorktreeSessionForNewBranch } from '@/lib/worktreeSessionCreator';
import { generateBranchSlug } from '@/lib/git/branchNameGenerator';
import type { GitHubIssue, GitHubIssueComment, GitHubIssuesListResult, GitHubIssueSummary } from '@/lib/api/types';
@@ -450,42 +451,10 @@ export function GitHubIssuePickerDialog({
}
}
const visiblePromptText = 'Review this issue using the provided issue context: title, body, labels, assignees, comments, metadata.';
const instructionsText = `Review this issue using the provided issue context.
Process:
- First classify the issue type (bug / feature request / question/support / refactor / ops) and state it as: Type: <one label>.
- Gather any needed repository context (code, config, docs) to validate assumptions.
- After gathering, if anything is still unclear or cannot be verified, do not speculate—state whats missing and ask targeted questions.
Output rules:
- Compact output; pick ONE template below and omit the others.
- No emojis. No code snippets. No fenced blocks.
- Short inline code identifiers allowed.
- Reference evidence with file paths and line ranges when applicable; if exact lines arent available, cite the file and say “approx” + why.
- Keep the entire response under ~300 words.
Templates (choose one):
Bug:
- Summary (1-2 sentences)
- Likely cause (max 2)
- Repro/diagnostics needed (max 3)
- Fix approach (max 4 steps)
- Verification (max 3)
Feature:
- Summary (1-2 sentences)
- Requirements (max 4)
- Unknowns/questions (max 4)
- Proposed plan (max 5 steps)
- Verification (max 3)
Question/Support:
- Summary (1-2 sentences)
- Answer/guidance (max 6 lines)
- Missing info (max 4)
Do not implement changes until I confirm; end with: “Next actions: <1 sentence>”.`;
const visiblePromptText = await renderMagicPrompt('github.issue.review.visible', {
issue_number: String(issue.number),
});
const instructionsText = await renderMagicPrompt('github.issue.review.instructions');
const contextText = buildIssueContextText({ repo: issueRes.repo, issue, comments });
void opencodeClient.sendMessage({
@@ -22,6 +22,7 @@ import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useUIStore } from '@/stores/useUIStore';
import { useGitHubAuthStore } from '@/stores/useGitHubAuthStore';
import { renderMagicPrompt } from '@/lib/magicPrompts';
import type { GitHubPullRequestContextResult, GitHubPullRequestSummary, GitHubPullRequestsListResult } from '@/lib/api/types';
const parsePrNumber = (value: string): number | null => {
@@ -47,50 +48,6 @@ const buildPullRequestContextText = (payload: GitHubPullRequestContextResult) =>
return `GitHub pull request context (JSON)\n${JSON.stringify(payload, null, 2)}`;
};
const PR_REVIEW_INSTRUCTIONS = `Before reporting issues:
- First identify the PR intent (what it's trying to achieve) from title/body/diff, then evaluate whether the implementation matches that intent; call out missing pieces, incorrect behavior vs intent, and scope creep.
- Gather any needed repository context (code, config, docs) to validate assumptions.
- No speculation: if something is unclear or cannot be verified, say what's missing and ask for it instead of guessing.
Output rules:
- Start with a 1-2 sentence summary.
- Provide a single concise PR review comment.
- No emojis. No code snippets. No fenced blocks.
- Short inline code identifiers allowed, but no snippets or fenced blocks.
- Reference evidence with file paths and line ranges (e.g., path/to/file.ts:120-138). If exact lines aren't available, cite the file and say "approx" + why.
- Keep the entire comment under ~300 words.
Report:
- Must-fix issues (blocking)-brief why and a one-line action each.
- Nice-to-have improvements (optional)-brief why and a one-line action each.
Quality & safety (general):
- Call out correctness risks, edge cases, performance regressions, security/privacy concerns, and backwards-compatibility risks.
- Call out missing tests/verification steps and suggest the minimal validation needed.
- Note readability/maintainability issues when they materially affect future changes.
Applicability (only if relevant):
- If changes affect multiple components/targets/environments (e.g., client/server, OSs, deployments), state what is affected vs not, and why.
Architecture:
- Call out breakages, missing implementations across modules/targets, boundary violations, and cross-cutting concerns (errors, logging/observability, accessibility).
Precedence:
- If local precedent conflicts with best practices, state it and suggest a follow-up task.
Do not implement changes until I confirm; end with a short "Next actions" sentence describing the recommended plan.
Format exactly:
Must-fix:
- <issue> - <brief why> - <file:line-range> - Action: <one-line action>
Nice-to-have:
- <issue> - <brief why> - <file:line-range> - Action: <one-line action>
If no issues, write:
Must-fix:
- None
Nice-to-have:
- None`;
export function GitHubPrPickerDialog({
open,
onOpenChange,
@@ -272,6 +229,7 @@ export function GitHubPrPickerDialog({
}
if (onSelect) {
const instructionsText = await renderMagicPrompt('github.pr.review.instructions');
onSelect({
number: context.pr.number,
title: context.pr.title,
@@ -279,7 +237,7 @@ export function GitHubPrPickerDialog({
head: context.pr.head,
base: context.pr.base,
includeDiff,
instructionsText: PR_REVIEW_INSTRUCTIONS,
instructionsText,
contextText: buildPullRequestContextText(context),
author: context.pr.author
? {
@@ -50,6 +50,7 @@ import { getWorktreeSetupCommands } from '@/lib/openchamberConfig';
import { getRootBranch } from '@/lib/worktrees/worktreeStatus';
import { generateBranchSlug } from '@/lib/git/branchNameGenerator';
import { opencodeClient } from '@/lib/opencode/client';
import { renderMagicPrompt } from '@/lib/magicPrompts';
import { rankBranchesForQuery } from '@/lib/worktrees/branchSearch';
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { useGitBranches, useGitStore, useGitLoadingBranches } from '@/stores/useGitStore';
@@ -547,42 +548,10 @@ export function NewWorktreeDialog({
throw new Error('Failed to load issue comments');
}
const visiblePromptText = `Review this issue #${args.issue.number} using the provided issue context`;
const instructionsText = `Review this issue using the provided issue context: title, body, labels, assignees, comments, metadata.
Process:
- First classify the issue type (bug / feature request / question/support / refactor / ops) and state it as: Type: <one label>.
- Gather any needed repository context (code, config, docs) to validate assumptions.
- After gathering, if anything is still unclear or cannot be verified, do not speculate-state what's missing and ask targeted questions.
Output rules:
- Compact output; pick ONE template below and omit the others.
- No emojis. No code snippets. No fenced blocks.
- Short inline code identifiers allowed.
- Reference evidence with file paths and line ranges when applicable; if exact lines aren't available, cite the file and say "approx" + why.
- Keep the entire response under ~300 words.
Templates (choose one):
Bug:
- Summary (1-2 sentences)
- Likely cause (max 2)
- Repro/diagnostics needed (max 3)
- Fix approach (max 4 steps)
- Verification (max 3)
Feature:
- Summary (1-2 sentences)
- Requirements (max 4)
- Unknowns/questions (max 4)
- Proposed plan (max 5 steps)
- Verification (max 3)
Question/Support:
- Summary (1-2 sentences)
- Answer/guidance (max 6 lines)
- Missing info (max 4)
Do not implement changes until I confirm; end with: "Next actions: <1 sentence>".`;
const visiblePromptText = await renderMagicPrompt('github.issue.review.visible', {
issue_number: String(args.issue.number),
});
const instructionsText = await renderMagicPrompt('github.issue.review.instructions');
const contextText = buildIssueContextText({
repo: issueRes.repo,
issue: issueRes.issue,
@@ -619,50 +588,10 @@ Do not implement changes until I confirm; end with: "Next actions: <1 sentence>"
throw new Error('Failed to load PR context');
}
const visiblePromptText = `Review this pull request #${args.pr.number} using the provided PR context`;
const instructionsText = `Before reporting issues:
- First identify the PR intent (what it's trying to achieve) from title/body/diff, then evaluate whether the implementation matches that intent; call out missing pieces, incorrect behavior vs intent, and scope creep.
- Gather any needed repository context (code, config, docs) to validate assumptions.
- No speculation: if something is unclear or cannot be verified, say what's missing and ask for it instead of guessing.
Output rules:
- Start with a 1-2 sentence summary.
- Provide a single concise PR review comment.
- No emojis. No code snippets. No fenced blocks.
- Short inline code identifiers allowed, but no snippets or fenced blocks.
- Reference evidence with file paths and line ranges (e.g., path/to/file.ts:120-138). If exact lines aren't available, cite the file and say "approx" + why.
- Keep the entire comment under ~300 words.
Report:
- Must-fix issues (blocking)-brief why and a one-line action each.
- Nice-to-have improvements (optional)-brief why and a one-line action each.
Quality & safety (general):
- Call out correctness risks, edge cases, performance regressions, security/privacy concerns, and backwards-compatibility risks.
- Call out missing tests/verification steps and suggest the minimal validation needed.
- Note readability/maintainability issues when they materially affect future changes.
Applicability (only if relevant):
- If changes affect multiple components/targets/environments (e.g., client/server, OSs, deployments), state what is affected vs not, and why.
Architecture:
- Call out breakages, missing implementations across modules/targets, boundary violations, and cross-cutting concerns (errors, logging/observability, accessibility).
Precedence:
- If local precedent conflicts with best practices, state it and suggest a follow-up task.
Do not implement changes until I confirm; end with a short "Next actions" sentence describing the recommended plan.
Format exactly:
Must-fix:
- <issue> - <brief why> - <file:line-range> - Action: <one-line action>
Nice-to-have:
- <issue> - <brief why> - <file:line-range> - Action: <one-line action>
If no issues, write:
Must-fix:
- None
Nice-to-have:
- None`;
const visiblePromptText = await renderMagicPrompt('github.pr.review.visible', {
pr_number: String(args.pr.number),
});
const instructionsText = await renderMagicPrompt('github.pr.review.instructions');
const contextText = buildPullRequestContextText(prContext);
await opencodeClient.sendMessage({
@@ -9,6 +9,7 @@ import { useSkillsStore } from '@/stores/useSkillsStore';
import { useSkillsCatalogStore } from '@/stores/useSkillsCatalogStore';
import {
RiAiAgentLine,
RiAiGenerate2,
RiArrowLeftSLine,
RiBarChart2Line,
RiBookLine,
@@ -22,9 +23,9 @@ import {
RiGitBranchLine,
RiGlobalLine,
RiMicLine,
RiListUnordered,
RiNotification3Line,
RiPaletteLine,
RiListUnordered,
RiRobot2Line,
RiRestartLine,
RiServerLine,
@@ -48,6 +49,8 @@ import { ProvidersSidebar } from '@/components/sections/providers/ProvidersSideb
import { ProvidersPage } from '@/components/sections/providers/ProvidersPage';
import { UsageSidebar } from '@/components/sections/usage/UsageSidebar';
import { UsagePage } from '@/components/sections/usage/UsagePage';
import { MagicPromptsSidebar } from '@/components/sections/magic-prompts/MagicPromptsSidebar';
import { MagicPromptsPage } from '@/components/sections/magic-prompts/MagicPromptsPage';
import { GitPage } from '@/components/sections/git-identities/GitPage';
import type { OpenChamberSection } from '@/components/sections/openchamber/types';
import { OpenChamberPage } from '@/components/sections/openchamber/OpenChamberPage';
@@ -86,6 +89,7 @@ const pageOrder: SettingsPageSlug[] = [
'sessions',
'shortcuts',
'git',
'magic-prompts',
'projects',
'remote-instances',
'agents',
@@ -122,6 +126,8 @@ function getSettingsNavIcon(slug: SettingsPageSlug): React.ComponentType<{ class
return RiPaletteLine;
case 'chat':
return RiChatAi3Line;
case 'magic-prompts':
return RiAiGenerate2;
case 'notifications':
return RiNotification3Line;
case 'shortcuts':
@@ -404,6 +410,8 @@ export const SettingsView: React.FC<SettingsViewProps> = ({ onClose, forceMobile
return <ProvidersSidebar onItemSelect={opts.onItemSelect} />;
case 'usage':
return <UsageSidebar onItemSelect={opts.onItemSelect} />;
case 'magic-prompts':
return <MagicPromptsSidebar onItemSelect={opts.onItemSelect} />;
default:
return null;
}
@@ -436,6 +444,8 @@ export const SettingsView: React.FC<SettingsViewProps> = ({ onClose, forceMobile
return <ProvidersPage />;
case 'usage':
return <UsagePage />;
case 'magic-prompts':
return <MagicPromptsPage />;
case 'git':
return <GitPage />;
case 'appearance':
@@ -14,6 +14,7 @@ import { useInputStore } from '@/sync/input-store';
import { useUIStore } from '@/stores/useUIStore';
import { toast } from '@/components/ui';
import { getConflictDetails, type MergeConflictDetails } from '@/lib/gitApi';
import { renderMagicPrompt } from '@/lib/magicPrompts';
interface ConflictDialogProps {
open: boolean;
@@ -65,36 +66,29 @@ export const ConflictDialog: React.FC<ConflictDialogProps> = ({
});
}, [open, directory]);
const buildConflictContext = React.useCallback((): {
const buildConflictContext = React.useCallback(async (): Promise<{
visibleText: string;
instructionsText: string;
payloadText: string;
} | null => {
} | null> => {
if (!conflictDetails) return null;
const operationLabel = operation === 'merge' ? 'merge' : 'rebase';
const headRef = conflictDetails.headInfo || (operation === 'merge' ? 'MERGE_HEAD' : 'REBASE_HEAD');
const continueCmd = operation === 'merge' ? 'git commit --no-edit' : 'git rebase --continue';
const visibleText = `Resolve ${operationLabel} conflicts, stage the resolved files, and complete the ${operationLabel}. Preserve the intent of changes from ${headRef}.`;
const visibleText = await renderMagicPrompt('git.conflict.resolve.visible', {
operation_label: operationLabel,
head_ref: headRef,
});
const instructionsText = `Git ${operationLabel} operation is in progress with conflicts.
- Directory: ${directory}
- Operation: ${operation}
- Head Info: ${conflictDetails.headInfo || 'N/A'}
Required steps:
1. Read each conflicted file to understand the conflict markers (<<<<<<< HEAD, =======, >>>>>>> ...)
2. Edit each file to resolve conflicts by choosing the correct code or merging both changes appropriately
3. Stage all resolved files with: git add <file>
4. Complete the ${operationLabel} with: ${continueCmd}
Important:
- Remove ALL conflict markers from files (<<<<<<< HEAD, =======, >>>>>>>)
- Make sure the final code is syntactically correct and preserves intent from both sides
- Do not leave any files with unresolved conflict markers
- After completing all steps, confirm the ${operationLabel} was successful
`;
const instructionsText = await renderMagicPrompt('git.conflict.resolve.instructions', {
operation_label: operationLabel,
directory,
operation,
head_info: conflictDetails.headInfo || 'N/A',
continue_cmd: continueCmd,
});
const payloadText = `${operationLabel} conflict context (JSON)\n${JSON.stringify(
{
@@ -122,8 +116,8 @@ Important:
onOpenChange(false);
};
const handleResolveInCurrentSession = () => {
const context = buildConflictContext();
const handleResolveInCurrentSession = async () => {
const context = await buildConflictContext();
if (!context) {
toast.error('No conflict details available');
return;
@@ -146,8 +140,8 @@ Important:
onOpenChange(false);
};
const handleResolveInNewSession = () => {
const context = buildConflictContext();
const handleResolveInNewSession = async () => {
const context = await buildConflictContext();
if (!context) {
toast.error('No conflict details available');
return;
@@ -234,7 +228,9 @@ Important:
<div className="flex flex-col gap-2 pt-2">
<Button
variant="default"
onClick={handleResolveInNewSession}
onClick={() => {
void handleResolveInNewSession();
}}
disabled={isLoading || !conflictDetails}
className="w-full gap-2"
>
@@ -19,6 +19,7 @@ import { useSessionUIStore } from '@/sync/session-ui-store';
import { useInputStore } from '@/sync/input-store';
import { useUIStore } from '@/stores/useUIStore';
import { execCommand } from '@/lib/execCommands';
import { renderMagicPrompt } from '@/lib/magicPrompts';
import {
abortIntegrate,
computeIntegratePlan,
@@ -184,29 +185,18 @@ export const IntegrateCommitsSection: React.FC<{
const openNewSessionDraft = useSessionUIStore((s) => s.openNewSessionDraft);
const buildConflictContext = React.useCallback((payload: { state: IntegrateInProgress; details: IntegrateConflictDetails }) => {
const visibleText = `Resolve cherry-pick conflicts, stage the resolved files, and continue the cherry-pick. Keep intent of commit ${payload.state.currentCommit} onto branch ${payload.state.targetBranch}.`;
const instructionsText = `Worktree commit integration (cherry-pick) is in progress with conflicts.
- Repo root: ${payload.state.repoRoot}
- Temp target worktree: ${payload.state.tempWorktreePath}
- Source branch: ${payload.state.sourceBranch}
- Target branch: ${payload.state.targetBranch}
- Current commit: ${payload.state.currentCommit}
Required steps:
1. Read each conflicted file in the temp worktree to understand the conflict markers (<<<<<<< HEAD, =======, >>>>>>> ...)
2. Edit each file to resolve conflicts by choosing the correct code or merging both changes appropriately
3. Stage all resolved files with: git add <file>
4. Complete the cherry-pick with: git cherry-pick --continue
Important:
- Work inside the temp worktree directory: ${payload.state.tempWorktreePath}
- Remove ALL conflict markers from files (<<<<<<< HEAD, =======, >>>>>>>)
- Preserve the intent of the commit being applied
- Make sure the final code is syntactically correct
- Do not leave any files with unresolved conflict markers
- After completing all steps, confirm the cherry-pick was successful
`;
const buildConflictContext = React.useCallback(async (payload: { state: IntegrateInProgress; details: IntegrateConflictDetails }) => {
const visibleText = await renderMagicPrompt('git.integrate.cherrypick.resolve.visible', {
current_commit: payload.state.currentCommit,
target_branch: payload.state.targetBranch,
});
const instructionsText = await renderMagicPrompt('git.integrate.cherrypick.resolve.instructions', {
repo_root: payload.state.repoRoot,
temp_worktree_path: payload.state.tempWorktreePath,
source_branch: payload.state.sourceBranch,
target_branch: payload.state.targetBranch,
current_commit: payload.state.currentCommit,
});
const payloadText = `Cherry-pick conflict context (JSON)\n${JSON.stringify({
repoRoot: payload.state.repoRoot,
tempWorktreePath: payload.state.tempWorktreePath,
@@ -227,11 +217,11 @@ Important:
const setPendingInputText = useInputStore((s) => s.setPendingInputText);
const setPendingSyntheticParts = useInputStore((s) => s.setPendingSyntheticParts);
const handleResolveWithAi = React.useCallback((
const handleResolveWithAi = React.useCallback(async (
payload: { state: IntegrateInProgress; details: IntegrateConflictDetails },
useNewSession: boolean
) => {
const context = buildConflictContext(payload);
const context = await buildConflictContext(payload);
if (useNewSession) {
// Open new session with the conflict context as initial prompt + synthetic parts
@@ -45,6 +45,7 @@ import {
CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { generatePullRequestDescription } from '@/lib/gitApi';
import { renderMagicPrompt } from '@/lib/magicPrompts';
import { openExternalUrl } from '@/lib/url';
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
import { useDeviceInfo } from '@/lib/device';
@@ -831,13 +832,8 @@ export const PullRequestSection: React.FC<{
return;
}
const visibleText = 'Review these PR failed checks and propose likely fixes. Do not implement until I confirm.';
const instructionsText = `Use the attached checks payload.
- Summarize what is failing.
- Prioritize check annotations/errors over generic status text.
- Identify likely root cause(s).
- Propose a minimal fix plan and verification steps.
- No speculation: ask for missing info if needed.`;
const visibleText = await renderMagicPrompt('github.pr.checks.review.visible');
const instructionsText = await renderMagicPrompt('github.pr.checks.review.instructions');
const failedAnnotations = failed.flatMap((run) => {
const annotations = Array.isArray(run.annotations) ? run.annotations : [];
return annotations.map((annotation) => ({
@@ -888,12 +884,8 @@ export const PullRequestSection: React.FC<{
return;
}
const visibleText = 'Review these PR comments and propose the required changes and next actions. Do not implement until I confirm.';
const instructionsText = `Use the attached comments payload.
- Identify required vs optional changes.
- Call out intent/implementation mismatch if present.
- Propose a minimal plan and verification steps.
- No speculation: ask for missing info if needed.`;
const visibleText = await renderMagicPrompt('github.pr.comments.review.visible');
const instructionsText = await renderMagicPrompt('github.pr.comments.review.instructions');
const payloadText = `GitHub PR comments (JSON)\n${JSON.stringify({
repo: context.repo ?? null,
pr: context.pr ?? null,
@@ -908,7 +900,7 @@ export const PullRequestSection: React.FC<{
}
}, [directory, dispatchSyntheticPrompt, github, pr, resolveChatDispatchTarget, setActiveMainTab]);
const sendSingleCommentToChat = React.useCallback((comment: TimelineCommentItem) => {
const sendSingleCommentToChat = React.useCallback(async (comment: TimelineCommentItem) => {
setCommentsDialogOpen(false);
setActiveMainTab('chat');
@@ -917,12 +909,8 @@ export const PullRequestSection: React.FC<{
return;
}
const visibleText = 'Address this comment from PR and propose required changes. Do not implement until I confirm.';
const instructionsText = `Use the attached single-comment payload.
- Explain what the reviewer is asking for.
- Identify exact code areas likely impacted.
- Propose a minimal implementation plan and verification steps.
- Call out ambiguity and ask focused follow-up questions if needed.`;
const visibleText = await renderMagicPrompt('github.pr.comment.single.visible');
const instructionsText = await renderMagicPrompt('github.pr.comment.single.instructions');
const payloadText = `GitHub PR comment (JSON)\n${JSON.stringify({
repo: commentsDetails?.repo ?? null,
pr: commentsDetails?.pr ?? pr ?? null,
@@ -1947,7 +1935,9 @@ export const PullRequestSection: React.FC<{
variant="ghost"
size="sm"
className="h-6 px-0 has-[>svg]:px-0 sm:px-2 sm:has-[>svg]:px-2.5 text-[var(--status-success)] hover:bg-[var(--status-success-background)] hover:text-[var(--status-success)] justify-start"
onClick={() => sendSingleCommentToChat(comment)}
onClick={() => {
void sendSingleCommentToChat(comment);
}}
aria-label="Send this comment to agent"
>
<RiAiGenerate2 className="size-3.5" />
+28 -45
View File
@@ -3,6 +3,7 @@
import type { RuntimeAPIs } from './api/types';
import * as gitHttp from './gitApiHttp';
import { opencodeClient } from './opencode/client';
import { renderMagicPrompt } from './magicPrompts';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { useContextStore } from '@/stores/contextStore';
import { useConfigStore } from '@/stores/useConfigStore';
@@ -131,25 +132,16 @@ export async function generateCommitMessage(
agent: generationSession.agent,
});
const prompt = `You are generating a Conventional Commits subject line using session context and selected file paths.
Return JSON with exactly this shape:
{"subject": string, "highlights": string[]}
Rules:
- subject format: <type>: <summary>
- allowed types: feat, fix, refactor, perf, docs, test, build, ci, chore, style, revert
- no scope in subject
- keep subject concise and user-facing
- highlights: 0-3 concise user-facing points
Selected files:
${files.map((file) => `- ${file}`).join('\n')}`;
const visiblePrompt = await renderMagicPrompt('git.commit.generate.visible');
const hiddenPrompt = await renderMagicPrompt('git.commit.generate.instructions', {
selected_files: files.map((file) => `- ${file}`).join('\n'),
});
try {
const structured = await runStructuredGenerationInActiveSession({
directory,
prompt,
visiblePrompt,
hiddenPrompt,
generationSession,
schema: {
type: 'object',
@@ -257,30 +249,20 @@ export async function generatePullRequestDescription(
changedFiles: changedFiles.length,
});
const prompt = `You are drafting GitHub Pull Request title and body using session context, commit list, and changed files.
Return JSON with exactly this shape:
{"title": string, "body": string}
Rules:
- title: concise, outcome-first, conventional style
- body: markdown with sections: ## Summary, ## Why, ## Testing
- keep output concrete and user-facing
Base branch: ${payload.base}
Head branch: ${payload.head}
Commits in range (base...head):
${commits.map((commit) => `- ${commit.hash.slice(0, 7)} ${commit.subject || '(no subject)'}`).join('\n')}
Files changed across these commits:
${changedFiles.length > 0 ? changedFiles.map((file) => `- ${file}`).join('\n') : '- none detected'}
${payload.context?.trim() ? `\nAdditional context:\n${payload.context.trim()}` : ''}`;
const visiblePrompt = await renderMagicPrompt('git.pr.generate.visible');
const hiddenPrompt = await renderMagicPrompt('git.pr.generate.instructions', {
base_branch: payload.base,
head_branch: payload.head,
commits: commits.map((commit) => `- ${commit.hash.slice(0, 7)} ${commit.subject || '(no subject)'}`).join('\n'),
changed_files: changedFiles.length > 0 ? changedFiles.map((file) => `- ${file}`).join('\n') : '- none detected',
additional_context_block: payload.context?.trim() ? `\nAdditional context:\n${payload.context.trim()}` : '',
});
try {
const structured = await runStructuredGenerationInActiveSession({
directory,
prompt,
visiblePrompt,
hiddenPrompt,
generationSession,
schema: {
type: 'object',
@@ -355,13 +337,15 @@ const resolveSessionGenerationContext = (): SessionGenerationContext | null => {
const runStructuredGenerationInActiveSession = async ({
directory,
prompt,
visiblePrompt,
hiddenPrompt,
generationSession,
schema,
kind,
}: {
directory: string;
prompt: string;
visiblePrompt: string;
hiddenPrompt?: string;
generationSession: SessionGenerationContext;
schema: Record<string, unknown>;
kind: 'commit' | 'pr';
@@ -376,18 +360,17 @@ const runStructuredGenerationInActiveSession = async ({
agent: generationSession.agent,
});
const trimmedDirectory = typeof directory === 'string' ? directory.trim() : '';
const firstNewlineIndex = prompt.indexOf('\n');
const visiblePrompt = (firstNewlineIndex === -1 ? prompt : prompt.slice(0, firstNewlineIndex)).trim();
const hiddenPrompt = (firstNewlineIndex === -1 ? '' : prompt.slice(firstNewlineIndex + 1)).trim();
const visiblePromptText = typeof visiblePrompt === 'string' ? visiblePrompt.trim() : '';
const hiddenPromptText = typeof hiddenPrompt === 'string' ? hiddenPrompt.trim() : '';
const promptParts: Array<{ type: 'text'; text: string; synthetic?: boolean }> = [];
if (visiblePrompt) {
promptParts.push({ type: 'text', text: visiblePrompt, synthetic: false });
if (visiblePromptText) {
promptParts.push({ type: 'text', text: visiblePromptText, synthetic: false });
}
if (hiddenPrompt) {
promptParts.push({ type: 'text', text: hiddenPrompt, synthetic: true });
if (hiddenPromptText) {
promptParts.push({ type: 'text', text: hiddenPromptText, synthetic: true });
}
if (promptParts.length === 0) {
promptParts.push({ type: 'text', text: prompt, synthetic: false });
throw new Error('Generation prompts are empty');
}
const response = await opencodeClient.withDirectory(directory, async () => {
+526
View File
@@ -0,0 +1,526 @@
export type MagicPromptId =
| 'git.commit.generate.visible'
| 'git.commit.generate.instructions'
| 'git.pr.generate.visible'
| 'git.pr.generate.instructions'
| 'git.conflict.resolve.visible'
| 'git.conflict.resolve.instructions'
| 'git.integrate.cherrypick.resolve.visible'
| 'git.integrate.cherrypick.resolve.instructions'
| 'github.pr.review.visible'
| 'github.pr.review.instructions'
| 'github.issue.review.visible'
| 'github.issue.review.instructions'
| 'github.pr.checks.review.visible'
| 'github.pr.checks.review.instructions'
| 'github.pr.comments.review.visible'
| 'github.pr.comments.review.instructions'
| 'github.pr.comment.single.visible'
| 'github.pr.comment.single.instructions';
export interface MagicPromptDefinition {
id: MagicPromptId;
title: string;
description: string;
group: 'Git' | 'GitHub';
template: string;
placeholders?: Array<{ key: string; description: string }>;
}
export interface MagicPromptOverridesPayload {
version: number;
overrides: Record<string, string>;
}
const API_ENDPOINT = '/api/magic-prompts';
export const MAGIC_PROMPT_DEFINITIONS: readonly MagicPromptDefinition[] = [
{
id: 'git.commit.generate.visible',
title: 'Commit Generation Visible Prompt',
group: 'Git',
description: 'Visible user message for commit message generation.',
template: 'You are generating a Conventional Commits subject line using session context and selected file paths.',
},
{
id: 'git.commit.generate.instructions',
title: 'Commit Generation Instructions',
group: 'Git',
description: 'Hidden instructions for commit message generation.',
placeholders: [
{ key: 'selected_files', description: 'Bullet list of currently selected file paths.' },
],
template: `Return JSON with exactly this shape:
{"subject": string, "highlights": string[]}
Rules:
- subject format: <type>: <summary>
- allowed types: feat, fix, refactor, perf, docs, test, build, ci, chore, style, revert
- no scope in subject
- keep subject concise and user-facing
- highlights: 0-3 concise user-facing points
Selected files:
{{selected_files}}`,
},
{
id: 'git.pr.generate.visible',
title: 'PR Generation Visible Prompt',
group: 'Git',
description: 'Visible user message for PR title/body generation.',
template: 'You are drafting GitHub Pull Request title and body using session context, commit list, and changed files.',
},
{
id: 'git.pr.generate.instructions',
title: 'PR Generation Instructions',
group: 'Git',
description: 'Hidden instructions for PR title/body generation.',
placeholders: [
{ key: 'base_branch', description: 'Base branch name.' },
{ key: 'head_branch', description: 'Head branch name.' },
{ key: 'commits', description: 'Bullet list of commits in base...head.' },
{ key: 'changed_files', description: 'Bullet list of changed files in base...head.' },
{ key: 'additional_context_block', description: 'Optional Additional context block (already formatted).' },
],
template: `Return JSON with exactly this shape:
{"title": string, "body": string}
Rules:
- title: concise, outcome-first, conventional style
- body: markdown with sections: ## Summary, ## Why, ## Testing
- keep output concrete and user-facing
Base branch: {{base_branch}}
Head branch: {{head_branch}}
Commits in range (base...head):
{{commits}}
Files changed across these commits:
{{changed_files}}{{additional_context_block}}`,
},
{
id: 'github.pr.review.visible',
title: 'PR Review Visible Prompt',
group: 'GitHub',
description: 'Visible user message when creating PR review requests from GitHub context.',
placeholders: [
{ key: 'pr_number', description: 'Pull request number.' },
],
template: 'Review this pull request #{{pr_number}} using the provided PR context',
},
{
id: 'github.pr.review.instructions',
title: 'PR Review Instructions',
group: 'GitHub',
description: 'Hidden instructions attached when generating a PR review response.',
template: `Before reporting issues:
- First identify the PR intent (what it's trying to achieve) from title/body/diff, then evaluate whether the implementation matches that intent; call out missing pieces, incorrect behavior vs intent, and scope creep.
- Gather any needed repository context (code, config, docs) to validate assumptions.
- No speculation: if something is unclear or cannot be verified, say what's missing and ask for it instead of guessing.
Output rules:
- Start with a 1-2 sentence summary.
- Provide a single concise PR review comment.
- No emojis. No code snippets. No fenced blocks.
- Short inline code identifiers allowed, but no snippets or fenced blocks.
- Reference evidence with file paths and line ranges (e.g., path/to/file.ts:120-138). If exact lines aren't available, cite the file and say "approx" + why.
- Keep the entire comment under ~300 words.
Report:
- Must-fix issues (blocking)-brief why and a one-line action each.
- Nice-to-have improvements (optional)-brief why and a one-line action each.
Quality & safety (general):
- Call out correctness risks, edge cases, performance regressions, security/privacy concerns, and backwards-compatibility risks.
- Call out missing tests/verification steps and suggest the minimal validation needed.
- Note readability/maintainability issues when they materially affect future changes.
Applicability (only if relevant):
- If changes affect multiple components/targets/environments (e.g., client/server, OSs, deployments), state what is affected vs not, and why.
Architecture:
- Call out breakages, missing implementations across modules/targets, boundary violations, and cross-cutting concerns (errors, logging/observability, accessibility).
Precedence:
- If local precedent conflicts with best practices, state it and suggest a follow-up task.
Do not implement changes until I confirm; end with a short "Next actions" sentence describing the recommended plan.
Format exactly:
Must-fix:
- <issue> - <brief why> - <file:line-range> - Action: <one-line action>
Nice-to-have:
- <issue> - <brief why> - <file:line-range> - Action: <one-line action>
If no issues, write:
Must-fix:
- None
Nice-to-have:
- None`,
},
{
id: 'github.issue.review.visible',
title: 'Issue Review Visible Prompt',
group: 'GitHub',
description: 'Visible user message when creating issue review requests from GitHub context.',
placeholders: [
{ key: 'issue_number', description: 'Issue number.' },
],
template: 'Review this issue #{{issue_number}} using the provided issue context',
},
{
id: 'github.issue.review.instructions',
title: 'Issue Review Instructions',
group: 'GitHub',
description: 'Hidden instructions attached when generating an issue review response.',
template: `Review this issue using the provided issue context.
Process:
- First classify the issue type (bug / feature request / question/support / refactor / ops) and state it as: Type: <one label>.
- Gather any needed repository context (code, config, docs) to validate assumptions.
- After gathering, if anything is still unclear or cannot be verified, do not speculate-state what's missing and ask targeted questions.
Output rules:
- Compact output; pick ONE template below and omit the others.
- No emojis. No code snippets. No fenced blocks.
- Short inline code identifiers allowed.
- Reference evidence with file paths and line ranges when applicable; if exact lines are not available, cite the file and say "approx" + why.
- Keep the entire response under ~300 words.
Templates (choose one):
Bug:
- Summary (1-2 sentences)
- Likely cause (max 2)
- Repro/diagnostics needed (max 3)
- Fix approach (max 4 steps)
- Verification (max 3)
Feature:
- Summary (1-2 sentences)
- Requirements (max 4)
- Unknowns/questions (max 4)
- Proposed plan (max 5 steps)
- Verification (max 3)
Question/Support:
- Summary (1-2 sentences)
- Answer/guidance (max 6 lines)
- Missing info (max 4)
Do not implement changes until I confirm; end with: "Next actions: <1 sentence>".`,
},
{
id: 'github.pr.checks.review.visible',
title: 'PR Failed Checks Visible Prompt',
group: 'GitHub',
description: 'Visible user message for PR failed checks analysis.',
template: 'Review these PR failed checks and propose likely fixes. Do not implement until I confirm.',
},
{
id: 'github.pr.checks.review.instructions',
title: 'PR Failed Checks Instructions',
group: 'GitHub',
description: 'Hidden instructions for PR failed checks analysis.',
template: `Use the attached checks payload.
- Summarize what is failing.
- Prioritize check annotations/errors over generic status text.
- Identify likely root cause(s).
- Propose a minimal fix plan and verification steps.
- No speculation: ask for missing info if needed.`,
},
{
id: 'github.pr.comments.review.visible',
title: 'PR Comments Review Visible Prompt',
group: 'GitHub',
description: 'Visible user message for PR comments analysis.',
template: 'Review these PR comments and propose the required changes and next actions. Do not implement until I confirm.',
},
{
id: 'github.pr.comments.review.instructions',
title: 'PR Comments Review Instructions',
group: 'GitHub',
description: 'Hidden instructions for PR comments analysis.',
template: `Use the attached comments payload.
- Identify required vs optional changes.
- Call out intent/implementation mismatch if present.
- Propose a minimal plan and verification steps.
- No speculation: ask for missing info if needed.`,
},
{
id: 'github.pr.comment.single.visible',
title: 'Single PR Comment Visible Prompt',
group: 'GitHub',
description: 'Visible user message for single PR comment analysis.',
template: 'Address this comment from PR and propose required changes. Do not implement until I confirm.',
},
{
id: 'github.pr.comment.single.instructions',
title: 'Single PR Comment Instructions',
group: 'GitHub',
description: 'Hidden instructions for single PR comment analysis.',
template: `Use the attached single-comment payload.
- Explain what the reviewer is asking for.
- Identify exact code areas likely impacted.
- Propose a minimal implementation plan and verification steps.
- Call out ambiguity and ask focused follow-up questions if needed.`,
},
{
id: 'git.conflict.resolve.visible',
title: 'Merge/Rebase Conflict Visible Prompt',
group: 'Git',
description: 'Visible user message for merge/rebase conflict resolution help.',
placeholders: [
{ key: 'operation_label', description: 'Operation label in lower-case (merge/rebase).' },
{ key: 'head_ref', description: 'Head reference for preserving intent.' },
],
template: 'Resolve {{operation_label}} conflicts, stage the resolved files, and complete the {{operation_label}}. Preserve the intent of changes from {{head_ref}}.',
},
{
id: 'git.conflict.resolve.instructions',
title: 'Merge/Rebase Conflict Instructions',
group: 'Git',
description: 'Hidden instructions for merge/rebase conflict resolution help.',
placeholders: [
{ key: 'operation_label', description: 'Operation label in lower-case (merge/rebase).' },
{ key: 'directory', description: 'Repository directory path.' },
{ key: 'operation', description: 'Operation name.' },
{ key: 'head_info', description: 'Head metadata if available.' },
{ key: 'continue_cmd', description: 'Command to continue operation.' },
],
template: `Git {{operation_label}} operation is in progress with conflicts.
- Directory: {{directory}}
- Operation: {{operation}}
- Head Info: {{head_info}}
Required steps:
1. Read each conflicted file to understand the conflict markers (<<<<<<< HEAD, =======, >>>>>>> ...)
2. Edit each file to resolve conflicts by choosing the correct code or merging both changes appropriately
3. Stage all resolved files with: git add <file>
4. Complete the {{operation_label}} with: {{continue_cmd}}
Important:
- Remove ALL conflict markers from files (<<<<<<< HEAD, =======, >>>>>>>)
- Make sure the final code is syntactically correct and preserves intent from both sides
- Do not leave any files with unresolved conflict markers
- After completing all steps, confirm the {{operation_label}} was successful`,
},
{
id: 'git.integrate.cherrypick.resolve.visible',
title: 'Cherry-pick Conflict Visible Prompt',
group: 'Git',
description: 'Visible user message for cherry-pick conflict resolution help.',
placeholders: [
{ key: 'current_commit', description: 'Current commit hash being applied.' },
{ key: 'target_branch', description: 'Target branch name.' },
],
template: 'Resolve cherry-pick conflicts, stage the resolved files, and continue the cherry-pick. Keep intent of commit {{current_commit}} onto branch {{target_branch}}.',
},
{
id: 'git.integrate.cherrypick.resolve.instructions',
title: 'Cherry-pick Conflict Instructions',
group: 'Git',
description: 'Hidden instructions for cherry-pick conflict resolution help.',
placeholders: [
{ key: 'repo_root', description: 'Repository root path.' },
{ key: 'temp_worktree_path', description: 'Temporary worktree path.' },
{ key: 'source_branch', description: 'Source branch name.' },
{ key: 'target_branch', description: 'Target branch name.' },
{ key: 'current_commit', description: 'Current commit hash being applied.' },
],
template: `Worktree commit integration (cherry-pick) is in progress with conflicts.
- Repo root: {{repo_root}}
- Temp target worktree: {{temp_worktree_path}}
- Source branch: {{source_branch}}
- Target branch: {{target_branch}}
- Current commit: {{current_commit}}
Required steps:
1. Read each conflicted file in the temp worktree to understand the conflict markers (<<<<<<< HEAD, =======, >>>>>>> ...)
2. Edit each file to resolve conflicts by choosing the correct code or merging both changes appropriately
3. Stage all resolved files with: git add <file>
4. Complete the cherry-pick with: git cherry-pick --continue
Important:
- Work inside the temp worktree directory: {{temp_worktree_path}}
- Remove ALL conflict markers from files (<<<<<<< HEAD, =======, >>>>>>>)
- Preserve the intent of the commit being applied
- Make sure the final code is syntactically correct
- Do not leave any files with unresolved conflict markers
- After completing all steps, confirm the cherry-pick was successful`,
},
] as const;
const MAGIC_PROMPT_DEFINITION_BY_ID = new Map<MagicPromptId, MagicPromptDefinition>(
MAGIC_PROMPT_DEFINITIONS.map((definition) => [definition.id, definition])
);
const LEGACY_PROMPT_KEY_MAP: Record<string, { visible: MagicPromptId; instructions: MagicPromptId }> = {
'git.commit.generate': {
visible: 'git.commit.generate.visible',
instructions: 'git.commit.generate.instructions',
},
'git.pr.generate': {
visible: 'git.pr.generate.visible',
instructions: 'git.pr.generate.instructions',
},
};
let cachedOverrides: Record<string, string> | null = null;
let inFlightOverridesRequest: Promise<Record<string, string>> | null = null;
const replaceTemplateVariables = (template: string, variables: Record<string, string>) => {
return template.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_match, key: string) => {
if (!Object.prototype.hasOwnProperty.call(variables, key)) {
return '';
}
return variables[key] ?? '';
});
};
const normalizeOverridesPayload = (payload: unknown): Record<string, string> => {
const overridesRaw = (payload as { overrides?: unknown } | null)?.overrides;
if (!overridesRaw || typeof overridesRaw !== 'object' || Array.isArray(overridesRaw)) {
return {};
}
const result: Record<string, string> = {};
for (const [key, value] of Object.entries(overridesRaw as Record<string, unknown>)) {
if (typeof value !== 'string') {
continue;
}
result[key] = value;
}
for (const [legacyKey, splitKeys] of Object.entries(LEGACY_PROMPT_KEY_MAP)) {
const legacyValue = result[legacyKey];
if (typeof legacyValue !== 'string') {
continue;
}
const firstNewlineIndex = legacyValue.indexOf('\n');
const visible = (firstNewlineIndex === -1 ? legacyValue : legacyValue.slice(0, firstNewlineIndex)).trim();
const instructions = (firstNewlineIndex === -1 ? '' : legacyValue.slice(firstNewlineIndex + 1)).trim();
if (!(splitKeys.visible in result) && visible.length > 0) {
result[splitKeys.visible] = visible;
}
if (!(splitKeys.instructions in result) && instructions.length > 0) {
result[splitKeys.instructions] = instructions;
}
}
return result;
};
export const fetchMagicPromptOverrides = async (): Promise<Record<string, string>> => {
if (cachedOverrides) {
return cachedOverrides;
}
if (!inFlightOverridesRequest) {
inFlightOverridesRequest = fetch(API_ENDPOINT, {
method: 'GET',
headers: { Accept: 'application/json' },
})
.then(async (response) => {
if (!response.ok) {
throw new Error('Failed to load magic prompts');
}
const payload = await response.json().catch(() => ({}));
const normalized = normalizeOverridesPayload(payload);
cachedOverrides = normalized;
return normalized;
})
.finally(() => {
inFlightOverridesRequest = null;
});
}
return inFlightOverridesRequest;
};
export const invalidateMagicPromptOverridesCache = () => {
cachedOverrides = null;
inFlightOverridesRequest = null;
};
export const getMagicPromptDefinition = (id: MagicPromptId): MagicPromptDefinition => {
const definition = MAGIC_PROMPT_DEFINITION_BY_ID.get(id);
if (!definition) {
throw new Error(`Unknown magic prompt id: ${id}`);
}
return definition;
};
export const getDefaultMagicPromptTemplate = (id: MagicPromptId): string => {
return getMagicPromptDefinition(id).template;
};
export const getEffectiveMagicPromptTemplate = async (id: MagicPromptId): Promise<string> => {
const overrides = await fetchMagicPromptOverrides().catch((): Record<string, string> => ({}));
const override = overrides[id];
if (typeof override === 'string') {
return override;
}
return getDefaultMagicPromptTemplate(id);
};
export const renderMagicPrompt = async (id: MagicPromptId, variables: Record<string, string> = {}): Promise<string> => {
const template = await getEffectiveMagicPromptTemplate(id);
return replaceTemplateVariables(template, variables);
};
export const saveMagicPromptOverride = async (id: MagicPromptId, text: string): Promise<MagicPromptOverridesPayload> => {
const response = await fetch(`${API_ENDPOINT}/${encodeURIComponent(id)}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({ text }),
});
if (!response.ok) {
const errorPayload = await response.json().catch(() => ({}));
throw new Error((errorPayload as { error?: string })?.error || 'Failed to save magic prompt');
}
const payload = await response.json();
cachedOverrides = normalizeOverridesPayload(payload);
return {
version: typeof payload?.version === 'number' ? payload.version : 1,
overrides: cachedOverrides,
};
};
export const resetMagicPromptOverride = async (id: MagicPromptId): Promise<MagicPromptOverridesPayload> => {
const response = await fetch(`${API_ENDPOINT}/${encodeURIComponent(id)}`, {
method: 'DELETE',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
const errorPayload = await response.json().catch(() => ({}));
throw new Error((errorPayload as { error?: string })?.error || 'Failed to reset magic prompt');
}
const payload = await response.json();
cachedOverrides = normalizeOverridesPayload(payload);
return {
version: typeof payload?.version === 'number' ? payload.version : 1,
overrides: cachedOverrides,
};
};
export const resetAllMagicPromptOverrides = async (): Promise<MagicPromptOverridesPayload> => {
const response = await fetch(API_ENDPOINT, {
method: 'DELETE',
headers: { Accept: 'application/json' },
});
if (!response.ok) {
const errorPayload = await response.json().catch(() => ({}));
throw new Error((errorPayload as { error?: string })?.error || 'Failed to reset all magic prompts');
}
const payload = await response.json();
cachedOverrides = normalizeOverridesPayload(payload);
return {
version: typeof payload?.version === 'number' ? payload.version : 1,
overrides: cachedOverrides,
};
};
+8
View File
@@ -16,6 +16,7 @@ export type SettingsPageSlug =
| 'chat'
| 'shortcuts'
| 'sessions'
| 'magic-prompts'
| 'notifications'
| 'voice'
| 'tunnel';
@@ -167,6 +168,13 @@ export const SETTINGS_PAGE_METADATA: readonly SettingsPageMeta[] = [
kind: 'single',
keywords: ['defaults', 'default agent', 'default model', 'retention', 'memory', 'limits', 'zen'],
},
{
slug: 'magic-prompts',
title: 'Magic Prompts',
group: 'general',
kind: 'split',
keywords: ['prompts', 'templates', 'git', 'github', 'review', 'commit', 'pull request'],
},
{ slug: 'notifications', title: 'Notifications', group: 'general', kind: 'single', keywords: ['alerts', 'native', 'summary', 'summarization'], },
{ slug: 'voice', title: 'Voice', group: 'advanced', kind: 'single', keywords: ['tts', 'speech', 'voice'], isAvailable: (ctx) => !ctx.isVSCode },
@@ -0,0 +1,20 @@
import { create } from 'zustand';
type MagicPromptsState = {
selectedPromptId: string;
setSelectedPromptId: (id: string) => void;
};
const DEFAULT_PROMPT_ID = 'git.commit.generate';
export const useMagicPromptsStore = create<MagicPromptsState>((set) => ({
selectedPromptId: DEFAULT_PROMPT_ID,
setSelectedPromptId: (id) => {
set((state) => {
if (state.selectedPromptId === id) {
return state;
}
return { selectedPromptId: id };
});
},
}));
@@ -47,6 +47,10 @@ type BridgeMessageInput = {
type ConfigRuntimeDeps = {
readSettings: (ctx?: BridgeContext) => Record<string, unknown>;
persistSettings: (changes: Record<string, unknown>, ctx?: BridgeContext) => Promise<Record<string, unknown>>;
readMagicPromptOverrides: () => { version: number; overrides: Record<string, string> };
saveMagicPromptOverride: (id: string, text: string) => Promise<{ version: number; overrides: Record<string, string> }>;
resetMagicPromptOverride: (id: string) => Promise<{ version: number; overrides: Record<string, string> }>;
resetAllMagicPromptOverrides: () => Promise<{ version: number; overrides: Record<string, string> }>;
fetchOpenCodeSkillsFromApi: (ctx: BridgeContext | undefined, workingDirectory?: string) => Promise<DiscoveredSkill[] | null>;
clientReloadDelayMs: number;
};
@@ -140,6 +144,38 @@ export async function handleConfigBridgeMessage(
return { id, type, success: true, data: updated };
}
case 'api:magic-prompts:get': {
return { id, type, success: true, data: deps.readMagicPromptOverrides() };
}
case 'api:magic-prompts:save': {
const request = (payload || {}) as { id?: string; text?: string };
const promptId = typeof request.id === 'string' ? request.id : '';
if (!promptId) {
return { id, type, success: false, error: 'Prompt id is required' };
}
if (typeof request.text !== 'string') {
return { id, type, success: false, error: 'Prompt text is required' };
}
const data = await deps.saveMagicPromptOverride(promptId, request.text);
return { id, type, success: true, data };
}
case 'api:magic-prompts:reset': {
const request = (payload || {}) as { id?: string };
const promptId = typeof request.id === 'string' ? request.id : '';
if (!promptId) {
return { id, type, success: false, error: 'Prompt id is required' };
}
const data = await deps.resetMagicPromptOverride(promptId);
return { id, type, success: true, data };
}
case 'api:magic-prompts:reset-all': {
const data = await deps.resetAllMagicPromptOverrides();
return { id, type, success: true, data };
}
case 'api:config/reload': {
await ctx?.manager?.restart();
return { id, type, success: true, data: { restarted: true } };
@@ -7,6 +7,11 @@ import type { BridgeContext } from './bridge';
const SETTINGS_KEY = 'openchamber.settings';
const OPENCHAMBER_SHARED_SETTINGS_PATH = path.join(os.homedir(), '.config', 'openchamber', 'settings.json');
const OPENCHAMBER_MAGIC_PROMPTS_PATH = path.join(os.homedir(), '.config', 'openchamber', 'magic-prompts.json');
const MAGIC_PROMPTS_FILE_VERSION = 1;
const MAGIC_PROMPT_ID_PATTERN = /^[a-z0-9._-]{1,160}$/;
const MAGIC_PROMPT_TEXT_MAX_LENGTH = 200_000;
const isVisiblePromptId = (id: string): boolean => id.endsWith('.visible');
const isPathInside = (candidatePath: string, parentPath: string): boolean => {
const relative = path.relative(parentPath, candidatePath);
@@ -166,6 +171,42 @@ const writeSharedSettingsToDisk = async (changes: Record<string, unknown>): Prom
}
};
const sanitizeMagicPromptOverrides = (input: unknown): Record<string, string> => {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
return {};
}
const next: Record<string, string> = {};
for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
if (!MAGIC_PROMPT_ID_PATTERN.test(key) || typeof value !== 'string') {
continue;
}
next[key] = value;
}
return next;
};
const readMagicPromptFile = (): { version: number; overrides: Record<string, string> } => {
try {
const raw = fs.readFileSync(OPENCHAMBER_MAGIC_PROMPTS_PATH, 'utf8');
const parsed = JSON.parse(raw) as { overrides?: unknown };
return {
version: MAGIC_PROMPTS_FILE_VERSION,
overrides: sanitizeMagicPromptOverrides(parsed?.overrides),
};
} catch {
return {
version: MAGIC_PROMPTS_FILE_VERSION,
overrides: {},
};
}
};
const writeMagicPromptFile = async (state: { version: number; overrides: Record<string, string> }): Promise<void> => {
await fs.promises.mkdir(path.dirname(OPENCHAMBER_MAGIC_PROMPTS_PATH), { recursive: true });
await fs.promises.writeFile(OPENCHAMBER_MAGIC_PROMPTS_PATH, JSON.stringify(state, null, 2), 'utf8');
};
export const readSettings = (ctx?: BridgeContext): Record<string, unknown> => {
const stored = ctx?.context?.globalState.get<Record<string, unknown>>(SETTINGS_KEY) || {};
const restStored = { ...stored };
@@ -229,3 +270,63 @@ export const persistSettings = async (changes: Record<string, unknown>, ctx?: Br
return merged;
};
export const readMagicPromptOverrides = (): { version: number; overrides: Record<string, string> } => {
return readMagicPromptFile();
};
export const saveMagicPromptOverride = async (id: string, text: string): Promise<{ version: number; overrides: Record<string, string> }> => {
const normalizedId = typeof id === 'string' ? id.trim() : '';
if (!MAGIC_PROMPT_ID_PATTERN.test(normalizedId)) {
throw new Error('Invalid prompt id');
}
if (typeof text !== 'string') {
throw new Error('Prompt text must be a string');
}
if (isVisiblePromptId(normalizedId) && text.trim().length === 0) {
throw new Error('Visible prompt text cannot be empty');
}
if (text.length > MAGIC_PROMPT_TEXT_MAX_LENGTH) {
throw new Error('Prompt text is too long');
}
const current = readMagicPromptFile();
const next = {
version: MAGIC_PROMPTS_FILE_VERSION,
overrides: {
...current.overrides,
[normalizedId]: text,
},
};
await writeMagicPromptFile(next);
return next;
};
export const resetMagicPromptOverride = async (id: string): Promise<{ version: number; overrides: Record<string, string> }> => {
const normalizedId = typeof id === 'string' ? id.trim() : '';
if (!MAGIC_PROMPT_ID_PATTERN.test(normalizedId)) {
throw new Error('Invalid prompt id');
}
const current = readMagicPromptFile();
if (!Object.prototype.hasOwnProperty.call(current.overrides, normalizedId)) {
return current;
}
const nextOverrides = { ...current.overrides };
delete nextOverrides[normalizedId];
const next = {
version: MAGIC_PROMPTS_FILE_VERSION,
overrides: nextOverrides,
};
await writeMagicPromptFile(next);
return next;
};
export const resetAllMagicPromptOverrides = async (): Promise<{ version: number; overrides: Record<string, string> }> => {
const next = {
version: MAGIC_PROMPTS_FILE_VERSION,
overrides: {},
};
await writeMagicPromptFile(next);
return next;
};
+13 -1
View File
@@ -6,7 +6,15 @@ import { handleFsBridgeMessage } from './bridge-fs-runtime';
import { handleConfigBridgeMessage } from './bridge-config-runtime';
import { handleSystemBridgeMessage } from './bridge-system-runtime';
import { handleProxyBridgeMessage } from './bridge-proxy-runtime';
import { fetchOpenCodeSkillsFromApi, persistSettings, readSettings } from './bridge-settings-runtime';
import {
fetchOpenCodeSkillsFromApi,
persistSettings,
readSettings,
readMagicPromptOverrides,
saveMagicPromptOverride,
resetMagicPromptOverride,
resetAllMagicPromptOverrides,
} from './bridge-settings-runtime';
import { execGit } from './bridge-git-process-runtime';
import {
parseDroppedFileReference,
@@ -89,6 +97,10 @@ export async function handleBridgeMessage(message: BridgeRequest, ctx?: BridgeCo
{
readSettings,
persistSettings,
readMagicPromptOverrides,
saveMagicPromptOverride,
resetMagicPromptOverride,
resetAllMagicPromptOverrides,
fetchOpenCodeSkillsFromApi,
clientReloadDelayMs: CLIENT_RELOAD_DELAY_MS,
},
+24
View File
@@ -831,6 +831,30 @@ const handleLocalApiRequest = async (url: URL, init?: RequestInit) => {
return new Response(JSON.stringify(updated), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
if (pathname === '/api/magic-prompts') {
if (method === 'GET') {
const data = await sendBridgeMessage('api:magic-prompts:get');
return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
if (method === 'DELETE') {
const data = await sendBridgeMessage('api:magic-prompts:reset-all');
return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
}
if (pathname.startsWith('/api/magic-prompts/')) {
const id = decodeURIComponent(pathname.slice('/api/magic-prompts/'.length));
if (method === 'PUT') {
const body = init?.body ? JSON.parse(init.body as string) : {};
const data = await sendBridgeMessage('api:magic-prompts:save', { id, text: body?.text });
return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
if (method === 'DELETE') {
const data = await sendBridgeMessage('api:magic-prompts:reset', { id });
return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json' } });
}
}
if (pathname === '/api/config/opencode-resolution' && method === 'GET') {
try {
const data = await sendBridgeMessage('api:config/opencode-resolution:get');
@@ -0,0 +1,63 @@
import { createMagicPromptRuntime } from './runtime.js';
export const registerMagicPromptRoutes = (app, dependencies) => {
const {
fsPromises,
path,
openchamberDataDir,
} = dependencies;
const runtime = createMagicPromptRuntime({
fsPromises,
path,
filePath: path.join(openchamberDataDir, 'magic-prompts.json'),
});
app.get('/api/magic-prompts', async (_req, res) => {
try {
const state = await runtime.readPromptState();
res.json(state);
} catch (error) {
res.status(500).json({ error: error instanceof Error ? error.message : 'Failed to read magic prompts' });
}
});
app.put('/api/magic-prompts/:id', async (req, res) => {
const id = typeof req.params?.id === 'string' ? req.params.id : '';
const text = typeof req.body?.text === 'string' ? req.body.text : null;
if (text === null) {
return res.status(400).json({ error: 'text is required' });
}
try {
const state = await runtime.setOverride(id, text);
return res.json(state);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const status = message.includes('Invalid prompt id') || message.includes('too long') || message.includes('cannot be empty') ? 400 : 500;
return res.status(status).json({ error: message });
}
});
app.delete('/api/magic-prompts/:id', async (req, res) => {
const id = typeof req.params?.id === 'string' ? req.params.id : '';
try {
const state = await runtime.resetOverride(id);
return res.json(state);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
const status = message.includes('Invalid prompt id') ? 400 : 500;
return res.status(status).json({ error: message });
}
});
app.delete('/api/magic-prompts', async (_req, res) => {
try {
const state = await runtime.resetAllOverrides();
return res.json(state);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return res.status(500).json({ error: message || 'Failed to reset magic prompts' });
}
});
};
@@ -0,0 +1,119 @@
const FILE_VERSION = 1;
const MAX_PROMPT_TEXT_LENGTH = 200_000;
const PROMPT_ID_PATTERN = /^[a-z0-9._-]{1,160}$/;
const isVisiblePromptID = (id) => typeof id === 'string' && id.endsWith('.visible');
const hasOwn = (input, key) => Object.prototype.hasOwnProperty.call(input, key);
const sanitizeOverrides = (value) => {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return {};
}
const next = {};
for (const [key, entry] of Object.entries(value)) {
if (!PROMPT_ID_PATTERN.test(key) || typeof entry !== 'string') {
continue;
}
next[key] = entry;
}
return next;
};
export const createMagicPromptRuntime = (dependencies) => {
const {
fsPromises,
path,
filePath,
} = dependencies;
let writeLock = Promise.resolve();
const readPromptState = async () => {
try {
const raw = await fsPromises.readFile(filePath, 'utf8');
const parsed = JSON.parse(raw);
const overrides = sanitizeOverrides(parsed?.overrides);
return {
version: FILE_VERSION,
overrides,
};
} catch (error) {
if (error && typeof error === 'object' && error.code === 'ENOENT') {
return { version: FILE_VERSION, overrides: {} };
}
console.warn('Failed to read magic prompts file:', error);
return { version: FILE_VERSION, overrides: {} };
}
};
const writePromptState = async (state) => {
await fsPromises.mkdir(path.dirname(filePath), { recursive: true });
await fsPromises.writeFile(filePath, JSON.stringify(state, null, 2), 'utf8');
};
const persist = async (mutator) => {
const run = async () => {
const current = await readPromptState();
const next = await mutator(current);
await writePromptState(next);
return next;
};
writeLock = writeLock.then(run, run);
return writeLock;
};
const setOverride = async (id, text) => {
const normalizedId = typeof id === 'string' ? id.trim() : '';
if (!PROMPT_ID_PATTERN.test(normalizedId)) {
throw new Error('Invalid prompt id');
}
if (typeof text !== 'string') {
throw new Error('Prompt text must be a string');
}
if (isVisiblePromptID(normalizedId) && text.trim().length === 0) {
throw new Error('Visible prompt text cannot be empty');
}
if (text.length > MAX_PROMPT_TEXT_LENGTH) {
throw new Error('Prompt text is too long');
}
return persist(async (state) => {
const nextOverrides = { ...state.overrides, [normalizedId]: text };
return {
version: FILE_VERSION,
overrides: nextOverrides,
};
});
};
const resetOverride = async (id) => {
const normalizedId = typeof id === 'string' ? id.trim() : '';
if (!PROMPT_ID_PATTERN.test(normalizedId)) {
throw new Error('Invalid prompt id');
}
return persist(async (state) => {
if (!hasOwn(state.overrides, normalizedId)) {
return state;
}
const nextOverrides = { ...state.overrides };
delete nextOverrides[normalizedId];
return {
version: FILE_VERSION,
overrides: nextOverrides,
};
});
};
const resetAllOverrides = async () => {
return persist(async () => ({ version: FILE_VERSION, overrides: {} }));
};
return {
readPromptState,
setOverride,
resetOverride,
resetAllOverrides,
};
};
@@ -161,6 +161,7 @@ export const registerCommonRequestMiddleware = (app, dependencies) => {
req.path.startsWith('/api/projects') ||
req.path.startsWith('/api/fs') ||
req.path.startsWith('/api/git') ||
req.path.startsWith('/api/magic-prompts') ||
req.path.startsWith('/api/prompts') ||
req.path.startsWith('/api/terminal') ||
req.path.startsWith('/api/opencode') ||
@@ -2,6 +2,7 @@ import { registerFsRoutes } from '../fs/routes.js';
import { registerQuotaRoutes } from '../quota/routes.js';
import { registerGitHubRoutes } from '../github/routes.js';
import { registerGitRoutes } from '../git/routes.js';
import { registerMagicPromptRoutes } from '../magic-prompts/routes.js';
import { registerConfigEntityRoutes } from './config-entity-routes.js';
import { registerSettingsUtilityRoutes } from './core-routes.js';
import { registerProjectIconRoutes } from './project-icon-routes.js';
@@ -196,6 +197,11 @@ export const createFeatureRoutesRuntime = (dependencies) => {
registerQuotaRoutes(app, { getQuotaProviders });
registerGitHubRoutes(app);
registerGitRoutes(app);
registerMagicPromptRoutes(app, {
fsPromises,
path,
openchamberDataDir,
});
registerFsRoutes(app, {
os,
path,