Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agents): global prompts editor on /agents (#409)
Call White8b986a2271bc
diff --git a/tests/test_global_agents_md.py b/tests/test_global_agents_md.pynew file mode 100644index 000000000..f083d3717--- /dev/null+++ b/tests/test_global_agents_md.py@@ -0,0 +1,153 @@+"""Unit tests for vibe.global_agents_md — per-backend global instruction file+resolution + the read/write/sync helpers that back the Web UI "Global prompts"+dialog. All tests pass an isolated ``home`` so they never touch the real+``~/.claude`` / ``~/.codex`` / ``~/.config/opencode`` files."""++import os++import pytest++from pathlib import Path++from vibe.global_agents_md import (+ global_instruction_path,+ read_all_global_agents_md,+ read_global_agents_md,+ write_global_agents_md,+ write_many_global_agents_md,+)+++# --- path resolution ------------------------------------------------------+++def test_path_resolution_per_backend(tmp_path: Path):+ assert global_instruction_path("claude", tmp_path) == tmp_path / ".claude" / "CLAUDE.md"+ assert global_instruction_path("codex", tmp_path) == tmp_path / ".codex" / "AGENTS.md"+ assert (+ global_instruction_path("opencode", tmp_path)+ == tmp_path / ".config" / "opencode" / "AGENTS.md"+ )+++def test_path_resolution_unknown_backend_raises(tmp_path: Path):+ with pytest.raises(ValueError):+ global_instruction_path("cursor", tmp_path)+++def test_opencode_ignores_legacy_config_dir(tmp_path: Path):+ # OpenCode reads global rules from ~/.config/opencode/AGENTS.md regardless of+ # a legacy ~/.opencode config dir — editing the latter would have no effect.+ alt = tmp_path / ".opencode"+ alt.mkdir()+ (alt / "opencode.json").write_text("{}", encoding="utf-8")+ (alt / "AGENTS.md").write_text("legacy", encoding="utf-8")+ assert (+ global_instruction_path("opencode", tmp_path)+ == tmp_path / ".config" / "opencode" / "AGENTS.md"+ )+++# --- read -----------------------------------------------------------------+++def test_read_missing_file_is_empty(tmp_path: Path):+ result = read_global_agents_md("claude", tmp_path)+ assert result == {+ "backend": "claude",+ "path": str(tmp_path / ".claude" / "CLAUDE.md"),+ "filename": "CLAUDE.md",+ "content": "",+ "exists": False,+ "read_error": False,+ }+++def test_read_invalid_utf8_sets_read_error(tmp_path: Path):+ # A non-UTF-8 file must degrade gracefully (read_error flag) rather than+ # raising — otherwise one bad file would 500 the whole editor.+ path = tmp_path / ".codex" / "AGENTS.md"+ path.parent.mkdir(parents=True)+ path.write_bytes(b"\xff\xfe garbage")+ result = read_global_agents_md("codex", tmp_path)+ assert result["read_error"] is True+ assert result["exists"] is True+ assert result["content"] == ""+++def test_read_existing_file(tmp_path: Path):+ path = tmp_path / ".codex" / "AGENTS.md"+ path.parent.mkdir(parents=True)+ path.write_text("be concise", encoding="utf-8")+ result = read_global_agents_md("codex", tmp_path)+ assert result["content"] == "be concise"+ assert result["exists"] is True+ assert result["filename"] == "AGENTS.md"+++def test_read_all_covers_every_backend(tmp_path: Path):+ results = read_all_global_agents_md(tmp_path)+ assert {r["backend"] for r in results} == {"claude", "codex", "opencode"}+++# --- write ----------------------------------------------------------------+++def test_write_creates_file_and_parents(tmp_path: Path):+ result = write_global_agents_md("claude", "hello world", tmp_path)+ path = tmp_path / ".claude" / "CLAUDE.md"+ assert path.read_text(encoding="utf-8") == "hello world"+ assert result["exists"] is True+ assert result["content"] == "hello world"+++def test_write_overwrites_existing(tmp_path: Path):+ write_global_agents_md("opencode", "v1", tmp_path)+ write_global_agents_md("opencode", "v2", tmp_path)+ assert (tmp_path / ".config" / "opencode" / "AGENTS.md").read_text(encoding="utf-8") == "v2"+++def test_write_preserves_symlink(tmp_path: Path):+ # A symlinked global prompt file (e.g. dotfiles repo) must stay a symlink;+ # the write updates the link target rather than replacing the link.+ real = tmp_path / "dotfiles" / "CLAUDE.md"+ real.parent.mkdir(parents=True)+ real.write_text("old", encoding="utf-8")+ link = tmp_path / ".claude" / "CLAUDE.md"+ link.parent.mkdir(parents=True)+ os.symlink(real, link)+ write_global_agents_md("claude", "new", tmp_path)+ assert link.is_symlink() # link preserved, not clobbered into a regular file+ assert real.read_text(encoding="utf-8") == "new" # target updated through the link+ assert link.read_text(encoding="utf-8") == "new"+++# --- write_many (per-backend Save + one-click Sync) -----------------------+++def test_write_many_single_backend_only_writes_that_one(tmp_path: Path):+ write_many_global_agents_md(["claude"], "only claude", tmp_path)+ assert (tmp_path / ".claude" / "CLAUDE.md").read_text(encoding="utf-8") == "only claude"+ assert not (tmp_path / ".codex" / "AGENTS.md").exists()+ assert not (tmp_path / ".config" / "opencode" / "AGENTS.md").exists()+++def test_write_many_all_backends_syncs_identical_content(tmp_path: Path):+ result = write_many_global_agents_md(["claude", "codex", "opencode"], "shared", tmp_path)+ assert (tmp_path / ".claude" / "CLAUDE.md").read_text(encoding="utf-8") == "shared"+ assert (tmp_path / ".codex" / "AGENTS.md").read_text(encoding="utf-8") == "shared"+ assert (tmp_path / ".config" / "opencode" / "AGENTS.md").read_text(encoding="utf-8") == "shared"+ # The refreshed seed reflects all three as existing with the synced content.+ assert all(entry["exists"] and entry["content"] == "shared" for entry in result)+++def test_write_many_unknown_backend_raises_before_writing(tmp_path: Path):+ # Validation happens up front, so a bad id cannot half-apply the sync.+ with pytest.raises(ValueError):+ write_many_global_agents_md(["claude", "bogus"], "should not persist", tmp_path)+ assert not (tmp_path / ".claude" / "CLAUDE.md").exists()+++def test_write_many_empty_list_raises(tmp_path: Path):+ with pytest.raises(ValueError):+ write_many_global_agents_md([], "x", tmp_path)diff --git a/ui/src/components/ui/editor-dialog.tsx b/ui/src/components/ui/editor-dialog.tsxindex 27e00af79..0cbffb675 100644--- a/ui/src/components/ui/editor-dialog.tsx+++ b/ui/src/components/ui/editor-dialog.tsx@@ -4,12 +4,8 @@ import { useTranslation } from 'react-i18next';import { Loader2 } from 'lucide-react';import { Dialog, DialogContent, DialogDescription, DialogTitle } from './dialog';-import { SegmentedRadio } from './segmented';import { Button } from './button';-import { Textarea } from './textarea';-import { Markdown } from './markdown';--type EditorMode = 'edit' | 'preview';+import { MarkdownEditor } from './markdown-editor';export interface EditorDialogProps {open: boolean;@@ -63,16 +59,15 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({}) => {const { t } = useTranslation();const [draft, setDraft] = useState(value);- const [mode, setMode] = useState<EditorMode>('edit');const [saving, setSaving] = useState(false);- // Reseed the draft (and reset to edit mode) each time the modal opens, so a- // cancelled edit never leaks into the next open and an external change to- // ``value`` between opens is picked up.+ // Reseed the draft each time the modal opens, so a cancelled edit never leaks+ // into the next open and an external change to ``value`` between opens is+ // picked up. The Edit/Preview mode resets on its own — MarkdownEditor remounts+ // with the dialog content on each open.useEffect(() => {if (open) {setDraft(value);- setMode('edit');setSaving(false);}// eslint-disable-next-line react-hooks/exhaustive-deps@@ -96,8 +91,6 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({}};- const showPreview = markdownPreview && mode === 'preview';-return (<Dialogopen={open}@@ -129,51 +122,14 @@ export const EditorDialog: React.FC<EditorDialogProps> = ({</div>)}- {/* Toolbar — Edit/Preview toggle + Markdown hint (preview-capable only). */}- {markdownPreview && (- <div className="flex items-center justify-between gap-3 border-b border-border px-5 py-2.5">- <div className="w-[200px]">- <SegmentedRadio<EditorMode>- value={mode}- onChange={setMode}- ariaLabel={t('editor.modeLabel')}- options={[- { id: 'edit', label: t('editor.edit') },- { id: 'preview', label: t('editor.preview') },- ]}- />- </div>- <span className="font-mono text-[10px] text-muted">{t('editor.markdownHint')}</span>- </div>- )}-- {/* Body — editor or preview, fills the remaining height. */}- <div className="min-h-0 flex-1 overflow-hidden p-5">- {showPreview ? (- <div className="h-full overflow-auto rounded-lg border border-border bg-surface-2 px-4 py-3">- {draft.trim() ? (- <Markdown content={draft} />- ) : (- <span className="text-[12px] text-muted">{t('editor.previewEmpty')}</span>- )}- </div>- ) : (- <Textarea- autoFocus- value={draft}- onChange={(e) => setDraft(e.target.value)}- onKeyDown={(e) => {- // Cmd/Ctrl+Enter saves from anywhere in the textarea.- if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {- e.preventDefault();- handleSave();- }- }}- placeholder={placeholder}- className="h-full resize-none font-mono text-[13px] leading-relaxed"- />- )}- </div>+ {/* Body — the shared Markdown editing surface fills the remaining height. */}+ <MarkdownEditor+ value={draft}+ onChange={setDraft}+ placeholder={placeholder}+ markdownPreview={markdownPreview}+ onSubmit={handleSave}+ />{/* Footer — optional slot (e.g. a toggle) above the draft hint + actions. */}<div className="flex flex-col gap-3 border-t border-border px-5 py-3">diff --git a/ui/src/components/ui/markdown-editor.tsx b/ui/src/components/ui/markdown-editor.tsxnew file mode 100644index 000000000..764cb38d9--- /dev/null+++ b/ui/src/components/ui/markdown-editor.tsx@@ -0,0 +1,90 @@+import * as React from 'react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { SegmentedRadio } from './segmented';+import { Textarea } from './textarea';+import { Markdown } from './markdown';++type EditorMode = 'edit' | 'preview';++export interface MarkdownEditorProps {+ value: string;+ onChange: (value: string) => void;+ placeholder?: string;+ /** Show the Edit/Preview toggle + Markdown preview (default true). */+ markdownPreview?: boolean;+ /** Called on Cmd/Ctrl+Enter from inside the textarea. */+ onSubmit?: () => void;+ /** Focus the textarea on mount (default true). */+ autoFocus?: boolean;+}++// The Markdown editing surface shared by EditorDialog and the Global Prompts+// dialog: a large monospace textarea with an optional Edit/Preview toggle that+// renders through the shared <Markdown> component and the .vr-markdown styling.+// Controlled (value / onChange); it owns only the local edit/preview mode, so+// any container — a full modal or a tabbed panel — can host the same surface.+// It fills its parent's remaining height (min-h-0 flex-1 flex-col).+export const MarkdownEditor: React.FC<MarkdownEditorProps> = ({+ value,+ onChange,+ placeholder,+ markdownPreview = true,+ onSubmit,+ autoFocus = true,+}) => {+ const { t } = useTranslation();+ const [mode, setMode] = useState<EditorMode>('edit');+ const showPreview = markdownPreview && mode === 'preview';++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ {/* Toolbar — Edit/Preview toggle + Markdown hint (preview-capable only). */}+ {markdownPreview && (+ <div className="flex items-center justify-between gap-3 border-b border-border px-5 py-2.5">+ <div className="w-[200px]">+ <SegmentedRadio<EditorMode>+ value={mode}+ onChange={setMode}+ ariaLabel={t('editor.modeLabel')}+ options={[+ { id: 'edit', label: t('editor.edit') },+ { id: 'preview', label: t('editor.preview') },+ ]}+ />+ </div>+ <span className="font-mono text-[10px] text-muted">{t('editor.markdownHint')}</span>+ </div>+ )}++ {/* Body — editor or preview, fills the remaining height. */}+ <div className="min-h-0 flex-1 overflow-hidden p-5">+ {showPreview ? (+ <div className="h-full overflow-auto rounded-lg border border-border bg-surface-2 px-4 py-3">+ {value.trim() ? (+ <Markdown content={value} />+ ) : (+ <span className="text-[12px] text-muted">{t('editor.previewEmpty')}</span>+ )}+ </div>+ ) : (+ <Textarea+ autoFocus={autoFocus}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={(e) => {+ // Cmd/Ctrl+Enter submits from anywhere in the textarea.+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {+ e.preventDefault();+ onSubmit?.();+ }+ }}+ placeholder={placeholder}+ className="h-full resize-none font-mono text-[13px] leading-relaxed"+ />+ )}+ </div>+ </div>+ );+};diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex 572c43047..999bf2c7a 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -4,6 +4,7 @@ import {Bot,ChevronDown,ChevronRight,+ FileText,Funnel,Loader2,Maximize2,@@ -23,6 +24,7 @@ import type { VibeAgentBrief, VibeAgentFull } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import { NewAgentDialog } from './NewAgentDialog';import { RunAgentDialog } from './RunAgentDialog';+import { GlobalPromptsDialog } from './GlobalPromptsDialog';import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { Switch } from '../ui/switch';@@ -62,6 +64,7 @@ export const AgentsPage: React.FC = () => {const [selected, setSelected] = useState<VibeAgentFull | null>(null);const [loading, setLoading] = useState(false);const [showNew, setShowNew] = useState(false);+ const [showGlobalPrompts, setShowGlobalPrompts] = useState(false);const [error, setError] = useState<string | null>(null);const [search, setSearch] = useState('');const [backendFilter, setBackendFilter] = useState<Backend | 'all'>('all');@@ -252,6 +255,10 @@ export const AgentsPage: React.FC = () => {</div><BackendFilter value={backendFilter} onChange={setBackendFilter} /><div className="flex-1" />+ <Button type="button" variant="outline" size="xs" onClick={() => setShowGlobalPrompts(true)}>+ <FileText className="size-3.5" />+ {t('globalPrompts.button')}+ </Button><ImportMenu onImport={onImport} importing={importing} /><Button type="button" variant="brand" size="xs" onClick={() => setShowNew(true)}><Plus />@@ -342,6 +349,7 @@ export const AgentsPage: React.FC = () => {</div><NewAgentDialog open={showNew} onClose={() => setShowNew(false)} onCreated={onCreated} />+ <GlobalPromptsDialog open={showGlobalPrompts} onClose={() => setShowGlobalPrompts(false)} /></div>);};diff --git a/ui/src/components/workbench/GlobalPromptsDialog.tsx b/ui/src/components/workbench/GlobalPromptsDialog.tsxnew file mode 100644index 000000000..926f4c352--- /dev/null+++ b/ui/src/components/workbench/GlobalPromptsDialog.tsx@@ -0,0 +1,253 @@+import * as React from 'react';+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Bot, Copy, Loader2 } from 'lucide-react';+import clsx from 'clsx';++import { useApi } from '../../context/ApiContext';+import type { GlobalPromptFile } from '../../context/ApiContext';+import { useToast } from '../../context/ToastContext';+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../ui/dialog';+import { Button } from '../ui/button';+import { MarkdownEditor } from '../ui/markdown-editor';+import { BACKEND_ORDER, BACKEND_LABEL, BACKEND_TEXT, BACKEND_DOT, type Backend } from '../../lib/backendAccent';++type FileMeta = { path: string; filename: string; exists: boolean; readError: boolean };++const emptyStringMap = (): Record<Backend, string> => ({ claude: '', opencode: '', codex: '' });+const emptyMetaMap = (): Record<Backend, FileMeta | null> => ({ claude: null, opencode: null, codex: null });++// Index an API response (one entry per backend) into a per-backend map over the+// canonical BACKEND_ORDER, so missing/extra ids never desync the editor state.+const mapContent = (files: GlobalPromptFile[]): Record<Backend, string> => {+ const out = emptyStringMap();+ for (const backend of BACKEND_ORDER) out[backend] = files.find((f) => f.backend === backend)?.content ?? '';+ return out;+};+const mapMeta = (files: GlobalPromptFile[]): Record<Backend, FileMeta | null> => {+ const out = emptyMetaMap();+ for (const backend of BACKEND_ORDER) {+ const file = files.find((f) => f.backend === backend);+ out[backend] = file+ ? { path: file.path, filename: file.filename, exists: file.exists, readError: file.read_error }+ : null;+ }+ return out;+};++// Edit each backend's *global* instructions file from one place — the global+// twin of the per-project AGENTS.md editor. Backends are tabs; each carries its+// own in-memory draft seeded from the loaded file, so edits across tabs survive+// switching until the user Saves (one backend) or Syncs (overwrites all three+// with the active draft). Reuses the shared MarkdownEditor surface.+export const GlobalPromptsDialog: React.FC<{ open: boolean; onClose: () => void }> = ({ open, onClose }) => {+ const { t } = useTranslation();+ const api = useApi();+ const { showToast } = useToast();++ const [loading, setLoading] = useState(true);+ const [saved, setSaved] = useState<Record<Backend, string>>(emptyStringMap);+ const [drafts, setDrafts] = useState<Record<Backend, string>>(emptyStringMap);+ const [meta, setMeta] = useState<Record<Backend, FileMeta | null>>(emptyMetaMap);+ const [active, setActive] = useState<Backend>('claude');+ const [busy, setBusy] = useState(false);++ // Load every backend's file once per open and seed both the saved baseline+ // and the editable drafts from it.+ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ setLoading(true);+ setActive('claude');+ api.getGlobalPrompts().then(+ (res) => {+ if (cancelled) return;+ setSaved(mapContent(res.backends));+ setDrafts(mapContent(res.backends));+ setMeta(mapMeta(res.backends));+ setLoading(false);+ },+ () => {+ // The shared apiFetch layer already surfaced the error toast.+ if (!cancelled) onClose();+ },+ );+ return () => {+ cancelled = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open]);++ if (!open) return null;++ const isDirty = (backend: Backend) => drafts[backend] !== saved[backend];+ const anyDirty = BACKEND_ORDER.some(isDirty);+ // Sync overwrites every backend, so any unreadable target (not just the+ // active one) must block it — otherwise sync would clobber a file whose+ // contents were never shown, defeating the read-error safeguard.+ const anyReadError = BACKEND_ORDER.some((backend) => meta[backend]?.readError);+ const activeMeta = meta[active];++ // Fold the refreshed file list back into the saved baseline + metadata+ // (clearing the active tab's dirty state) without disturbing drafts the user+ // is still editing on other tabs.+ const applyResult = (files: GlobalPromptFile[]) => {+ setSaved(mapContent(files));+ setMeta(mapMeta(files));+ };++ const handleClose = () => {+ if (busy) return;+ if (anyDirty && !window.confirm(t('globalPrompts.discardConfirm'))) return;+ onClose();+ };++ const handleSave = async () => {+ if (busy || !isDirty(active) || meta[active]?.readError) return;+ setBusy(true);+ try {+ const res = await api.saveGlobalPrompts({ content: drafts[active], backends: [active] });+ applyResult(res.backends);+ showToast(t('globalPrompts.saved', { backend: BACKEND_LABEL[active] }), 'success');+ } catch {+ // apiFetch already toasted; keep the dialog + draft so nothing is lost.+ } finally {+ setBusy(false);+ }+ };++ const handleSync = async () => {+ if (busy || anyReadError) return;+ if (!window.confirm(t('globalPrompts.syncConfirm', { backend: BACKEND_LABEL[active] }))) return;+ setBusy(true);+ try {+ const res = await api.saveGlobalPrompts({ content: drafts[active], backends: [...BACKEND_ORDER] });+ applyResult(res.backends);+ // Every backend now holds the active content — reflect it across all tabs+ // so they read clean and show the synced text.+ setDrafts(mapContent(res.backends));+ showToast(t('globalPrompts.synced'), 'success');+ } catch {+ // apiFetch already toasted.+ } finally {+ setBusy(false);+ }+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!next) handleClose();+ }}+ >+ <DialogContent+ className="flex h-[82vh] w-[92vw] max-w-[920px] flex-col gap-0 overflow-hidden p-0"+ // Non-dismissable: an outside click / Esc would discard multi-tab edits,+ // so closing goes through the X / Cancel (which confirm when dirty).+ onInteractOutside={(e) => e.preventDefault()}+ onEscapeKeyDown={(e) => e.preventDefault()}+ >+ {/* Header — pr-12 leaves room for the Dialog's built-in close X. */}+ <div className="flex flex-col gap-1 border-b border-border px-5 py-4 pr-12">+ <DialogTitle className="text-[15px] font-bold text-foreground">{t('globalPrompts.title')}</DialogTitle>+ <DialogDescription className="text-[12px] leading-relaxed text-muted">+ {t('globalPrompts.description')}+ </DialogDescription>+ </div>++ {!loading && (+ <>+ {/* Backend tabs — accent-colored, with a dot marking unsaved edits. */}+ <div role="tablist" className="flex items-center gap-1 border-b border-border px-3">+ {BACKEND_ORDER.map((backend) => {+ const activeTab = backend === active;+ return (+ <Button+ key={backend}+ type="button"+ role="tab"+ aria-selected={activeTab}+ variant="ghost"+ size="sm"+ onClick={() => setActive(backend)}+ className={clsx(+ 'h-auto gap-2 rounded-none border-b-2 px-3 py-2.5 hover:bg-transparent',+ activeTab+ ? clsx('border-current', BACKEND_TEXT[backend])+ : 'border-transparent text-muted hover:text-foreground',+ )}+ >+ <Bot className={clsx('size-3.5', activeTab ? BACKEND_TEXT[backend] : 'text-muted')} />+ {BACKEND_LABEL[backend]}+ {isDirty(backend) && (+ <span className={clsx('size-1.5 rounded-full', BACKEND_DOT[backend])} aria-hidden />+ )}+ </Button>+ );+ })}+ </div>++ {/* Tip — the exact file being edited + what it does, in plain terms. */}+ {activeMeta && (+ <div className="flex flex-col gap-0.5 border-b border-border bg-surface-2 px-5 py-2">+ <span className="font-mono text-[11px] text-foreground">{activeMeta.path}</span>+ {activeMeta.readError ? (+ <span className="text-[11px] leading-relaxed text-gold">{t('globalPrompts.readError')}</span>+ ) : (+ <span className="text-[11px] leading-relaxed text-muted">+ {t('globalPrompts.tipEffect', { backend: BACKEND_LABEL[active] })}+ {!activeMeta.exists && <> · {t('globalPrompts.missingHint')}</>}+ </span>+ )}+ </div>+ )}+ </>+ )}++ {/* Body — loading spinner, then the shared Markdown editing surface. */}+ {loading ? (+ <div className="flex min-h-0 flex-1 items-center justify-center">+ <Loader2 className="size-5 animate-spin text-muted" />+ </div>+ ) : (+ <MarkdownEditor+ value={drafts[active]}+ onChange={(next) => setDrafts((prev) => ({ ...prev, [active]: next }))}+ placeholder={t('globalPrompts.placeholder')}+ onSubmit={handleSave}+ />+ )}++ {/* Footer — Sync (left) + Cancel / Save (right). */}+ <div className="flex items-center justify-between gap-3 border-t border-border px-5 py-3">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={handleSync}+ disabled={busy || loading || anyReadError}+ >+ <Copy className="size-3.5" />+ {t('globalPrompts.sync')}+ </Button>+ <div className="flex items-center gap-2">+ <Button type="button" variant="outline" size="sm" onClick={handleClose} disabled={busy}>+ {t('common.cancel')}+ </Button>+ <Button+ type="button"+ variant="brand"+ size="sm"+ onClick={handleSave}+ disabled={busy || loading || !!activeMeta?.readError || !isDirty(active)}+ >+ {busy && <Loader2 className="size-3.5 animate-spin" />}+ {t('globalPrompts.save')}+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+};diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 73c5428f1..96e98e416 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -3,6 +3,19 @@ import { useTranslation } from 'react-i18next';import { useToast } from './ToastContext';import { apiFetch } from '../lib/apiFetch';+// One backend's *global* instructions file, surfaced by the Global Prompts+// editor. ``backend`` is an agent backend id (claude / opencode / codex).+export type GlobalPromptFile = {+ backend: string;+ path: string;+ filename: string;+ content: string;+ exists: boolean;+ /** True when the file exists but couldn't be decoded as UTF-8; the editor+ * then warns and refuses to overwrite it with an empty draft. */+ read_error: boolean;+};+export type ApiContextType = {getConfig: () => Promise<any>;getPlatformCatalog: () => Promise<any>;@@ -112,6 +125,10 @@ export type ApiContextType = {projectId: string,payload: { content: string; symlink: boolean },) => Promise<{ ok: boolean; symlinked: boolean; claude_is_regular_file: boolean; migrated: boolean; symlink_error: string | null }>;+ getGlobalPrompts: () => Promise<{ backends: GlobalPromptFile[] }>;+ saveGlobalPrompts: (+ payload: { content: string; backends: string[] },+ ) => Promise<{ ok: boolean; backends: GlobalPromptFile[] }>;listSessions: (params?: { projectId?: string; status?: 'active' | 'archived' | 'all'; limit?: number; beforeId?: string }) => Promise<{ sessions: WorkbenchSession[]; next_before_id: string | null }>;createSession: (payload: WorkbenchSessionCreate) => Promise<WorkbenchSession>;getSession: (sessionId: string) => Promise<WorkbenchSession>;@@ -1180,6 +1197,18 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children}return res.json();},+ getGlobalPrompts: () => getJson('/api/global-prompts'),+ saveGlobalPrompts: async (payload) => {+ const res = await apiFetch('/api/global-prompts', {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ });+ if (!res.ok) {+ await handleApiError(res, 'PUT /api/global-prompts');+ }+ return res.json();+ },listSessions: (params) => {const search = new URLSearchParams();if (params?.projectId) search.set('project_id', params.projectId);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 0bcd1b458..d99db486d 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1426,6 +1426,21 @@"saved": "AGENTS.md saved","savedSymlinkFailed": "AGENTS.md saved, but the symlink could not be created."},+ "globalPrompts": {+ "button": "Global prompts",+ "title": "Global prompts",+ "description": "Edit each backend's global instructions file — applied ahead of every agent's system prompt on this machine.",+ "placeholder": "Write global instructions for this backend in Markdown…",+ "tipEffect": "Prepended to the system prompt of every {{backend}} agent. New sessions pick it up.",+ "missingHint": "this file doesn't exist yet — saving creates it",+ "readError": "Couldn't read this file (not valid UTF-8). Fix it on disk before editing it here.",+ "save": "Save",+ "sync": "Sync to all backends",+ "syncConfirm": "Overwrite all three backends' global prompt files with {{backend}}'s current content?",+ "saved": "Saved {{backend}}'s global prompt.",+ "synced": "Synced to all backends.",+ "discardConfirm": "You have unsaved changes. Close and discard them?"+ },"skills": {"title": "Skills","subtitle": "Manage global and project skills across your agent backends · powered by askill.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c09c896a7..b1961ef7e 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1425,6 +1425,21 @@"saved": "AGENTS.md 已保存","savedSymlinkFailed": "AGENTS.md 已保存,但软链接创建失败。"},+ "globalPrompts": {+ "button": "全局提示词",+ "title": "全局提示词",+ "description": "分别编辑各 backend 的全局指令文件,会加在本机所有 agent 系统提示词的最前面。",+ "placeholder": "用 Markdown 写下该 backend 的全局指令…",+ "tipEffect": "会加在 {{backend}} 所有 agent 系统提示词的最前面,新会话自动生效。",+ "missingHint": "该文件尚不存在,保存后会自动创建",+ "readError": "无法读取该文件(不是有效的 UTF-8),请先在磁盘上修复后再编辑。",+ "save": "保存",+ "sync": "一键同步到全部 backend",+ "syncConfirm": "用 {{backend}} 的当前内容覆盖全部三个 backend 的全局提示词文件?",+ "saved": "已保存 {{backend}} 的全局提示词。",+ "synced": "已同步到全部 backend。",+ "discardConfirm": "有未保存的修改,确定关闭并丢弃吗?"+ },"skills": {"title": "技能","subtitle": "跨各 Agent 后端管理全局与项目级技能 · 基于 askill。",diff --git a/vibe/global_agents_md.py b/vibe/global_agents_md.pynew file mode 100644index 000000000..7817f36a8--- /dev/null+++ b/vibe/global_agents_md.py@@ -0,0 +1,156 @@+"""Read/write each agent backend's *global* instructions file.++These are the user-level "global system prompt" files the agent CLIs read at+the start of every session, ahead of any project- or agent-specific prompt:++- ``claude`` -> ``~/.claude/CLAUDE.md`` (Claude Code "user memory")+- ``codex`` -> ``$CODEX_HOME/AGENTS.md`` (default ``~/.codex/AGENTS.md``)+- ``opencode`` -> ``~/.config/opencode/AGENTS.md`` (OpenCode global rules)++This is the *global* twin of :mod:`vibe.project_agents_md`, which edits a single+project's ``AGENTS.md``. The Web UI "Global prompts" dialog edits all three from+one place and can sync one backend's content over the others.++Path resolution reuses the existing per-backend home resolvers+(:func:`get_claude_home` / :func:`get_codex_home` / :func:`get_opencode_config_paths`)+so we always point at the directory the live CLI actually consults — including+``CLAUDE_CONFIG_DIR`` / ``CODEX_HOME`` overrides.++The functions are deliberately pure filesystem helpers keyed by backend id,+accepting an optional ``home`` override so they stay unit-testable in isolation+(the HTTP layer passes none and they resolve the real user home).+"""++from __future__ import annotations++import os+import tempfile+from collections.abc import Iterable+from pathlib import Path++from modules.agents.catalog import AGENT_BACKENDS, is_agent_backend+from vibe.claude_config import get_claude_home+from vibe.codex_config import get_codex_home+from vibe.opencode_config import get_opencode_config_paths++# Per-backend global instruction filename. Claude reads its legacy ``CLAUDE.md``+# "user memory"; Codex and OpenCode both read ``AGENTS.md``.+GLOBAL_INSTRUCTION_FILENAME: dict[str, str] = {+ "claude": "CLAUDE.md",+ "codex": "AGENTS.md",+ "opencode": "AGENTS.md",+}+++def _opencode_global_dir(home: Path | None = None) -> Path:+ """Return the directory OpenCode reads its global ``AGENTS.md`` from.++ OpenCode's rules docs pin global rules to ``~/.config/opencode/AGENTS.md``+ (with a ``~/.claude/CLAUDE.md`` fallback) — *not* next to a legacy+ ``~/.opencode/opencode.json``. Editing ``~/.opencode/AGENTS.md`` would report+ a successful save while new sessions keep reading the unchanged+ ``~/.config/opencode/AGENTS.md``, so we always target the documented path+ (the first ``get_opencode_config_paths`` candidate's directory).+ """+ return get_opencode_config_paths(home)[0].parent+++def global_instruction_path(backend: str, home: Path | None = None) -> Path:+ """Resolve the absolute path to *backend*'s global instructions file."""+ if backend == "claude":+ return get_claude_home(home) / GLOBAL_INSTRUCTION_FILENAME["claude"]+ if backend == "codex":+ return get_codex_home(home) / GLOBAL_INSTRUCTION_FILENAME["codex"]+ if backend == "opencode":+ return _opencode_global_dir(home) / GLOBAL_INSTRUCTION_FILENAME["opencode"]+ raise ValueError(f"Unsupported agent backend: {backend!r}")+++def read_global_agents_md(backend: str, home: Path | None = None) -> dict:+ """Return the editor seed for *backend*'s global instructions file.++ ``exists`` is ``False`` (and ``content`` empty) when the file is absent, so+ the UI shows an empty editor and still surfaces the path the save will+ create.+ """+ path = global_instruction_path(backend, home)+ exists = path.is_file()+ content = ""+ read_error = False+ if exists:+ try:+ content = path.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ # A non-UTF-8 or otherwise unreadable file must not 500 the whole+ # editor — one bad file would block every backend's tab. Surface it+ # so the UI can warn and refuse to overwrite it with an empty draft.+ read_error = True+ return {+ "backend": backend,+ "path": str(path),+ "filename": GLOBAL_INSTRUCTION_FILENAME[backend],+ "content": content,+ "exists": exists,+ "read_error": read_error,+ }+++def read_all_global_agents_md(home: Path | None = None) -> list[dict]:+ """Return the editor seed for every known backend, in catalog order."""+ return [read_global_agents_md(backend, home) for backend in AGENT_BACKENDS]+++def _atomic_write(path: Path, content: str) -> None:+ """Write *content* to *path* atomically, creating parent dirs as needed.++ A temp file in the target directory is swapped in with ``os.replace`` so a+ failed write never truncates an existing global instructions file.++ Writes *through* a symlink to its real target: a user who symlinks their+ global prompt file into a shared dotfiles repo (e.g. ``~/.claude/CLAUDE.md``+ -> ``~/dotfiles/CLAUDE.md``) keeps the link intact, since replacing it with a+ regular file would silently break that sharing setup.+ """+ target = Path(os.path.realpath(path))+ target.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=str(target.parent), text=True)+ tmp = Path(tmp_name)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(content)+ os.replace(tmp, target)+ finally:+ if tmp.exists():+ try:+ tmp.unlink()+ except OSError: # pragma: no cover - best effort cleanup+ pass+++def write_global_agents_md(backend: str, content: str, home: Path | None = None) -> dict:+ """Write *content* to *backend*'s global instructions file and re-read it."""+ path = global_instruction_path(backend, home)+ _atomic_write(path, content)+ return read_global_agents_md(backend, home)+++def write_many_global_agents_md(+ backends: Iterable[str], content: str, home: Path | None = None+) -> list[dict]:+ """Write the same *content* to each backend in *backends*.++ Backs both per-backend Save (a single id) and one-click Sync (every id).+ All ids are validated before any write so a bad request cannot half-apply.+ Returns the refreshed seed for every backend so the UI can re-sync paths and+ ``exists`` flags after the write.+ """+ targets: list[str] = []+ for backend in backends:+ if not is_agent_backend(backend) or backend not in GLOBAL_INSTRUCTION_FILENAME:+ raise ValueError(f"Unsupported agent backend: {backend!r}")+ targets.append(backend)+ if not targets:+ raise ValueError("backends must not be empty")+ for backend in targets:+ write_global_agents_md(backend, content, home)+ return read_all_global_agents_md(home)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 22347a608..032279732 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2855,6 +2855,44 @@ def project_agents_md_save(project_id: str):return jsonify({"ok": True, **save_agents_md(folder, str(content), symlink)})[email protected]("/api/global-prompts", methods=["GET"])+def global_prompts_get():+ """Read every backend's *global* instructions file for the editor.++ The global twin of the per-project AGENTS.md editor: each backend's+ user-level prompt file (claude→~/.claude/CLAUDE.md, codex→~/.codex/AGENTS.md,+ opencode→~/.config/opencode/AGENTS.md) that the CLI prepends to every+ session's system prompt.+ """+ from vibe.global_agents_md import read_all_global_agents_md++ return jsonify({"backends": read_all_global_agents_md()})++[email protected]("/api/global-prompts", methods=["PUT"])+def global_prompts_save():+ """Write content to one or more backends' global instructions files.++ Body ``{"content": str, "backends": ["claude", ...]}``: a single id backs+ per-backend Save, the full set backs one-click Sync. Unknown ids are+ rejected before any write so a bad request can't half-apply.+ """+ from vibe.global_agents_md import write_many_global_agents_md++ payload = request.json or {}+ content = payload.get("content")+ if content is None:+ return jsonify({"error": "content is required"}), 400+ backends = payload.get("backends")+ if not isinstance(backends, list) or not backends:+ return jsonify({"error": "backends must be a non-empty list"}), 400+ try:+ result = write_many_global_agents_md(backends, str(content))+ except ValueError as err:+ return jsonify({"error": str(err)}), 400+ return jsonify({"ok": True, "backends": result})++# Agent Skills — thin shells over api.* (which wraps the askill CLI). Pure# data CRUD, so it stays in the UI-server process via core/services (no# dispatch-socket round-trip). See docs/plans/workbench-skills-page.md.