Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
feat(editor): cycle through variable uses in the tiptap variable panel
Sergey Kozyrenkoe29582958d09
diff --git a/frontend/src/components/shared/editor-variable-highlight.ts b/frontend/src/components/shared/editor-variable-highlight.tsindex 98b4f334..c5fc8863 100644--- a/frontend/src/components/shared/editor-variable-highlight.ts+++ b/frontend/src/components/shared/editor-variable-highlight.ts@@ -34,6 +34,26 @@ const buildDecorations = (doc: PMNode): DecorationSet => {return DecorationSet.create(doc, decorations);};+// Regex mirrors settings-prompt.tsx countVariableUses so the panel's "used" badge and this cycle agree.+export const findVariableOccurrences = (doc: PMNode, variable: string): { from: number; to: number }[] => {+ const pattern = new RegExp(`\\{\\{[^{}]*?\\.${variable}\\b[^{}]*?\\}\\}`, 'g');+ const occurrences: { from: number; to: number }[] = [];++ doc.descendants((node, pos) => {+ if (!node.isText || !node.text) {+ return;+ }++ for (const match of node.text.matchAll(pattern)) {+ const from = pos + (match.index ?? 0);++ occurrences.push({ from, to: from + match[0].length });+ }+ });++ return occurrences;+};+export const VariableHighlight = Extension.create({addProseMirrorPlugins() {return [diff --git a/frontend/src/components/shared/markdown-editor-extensions.test.ts b/frontend/src/components/shared/markdown-editor-extensions.test.tsindex 07d719f1..ddacdd6e 100644--- a/frontend/src/components/shared/markdown-editor-extensions.test.ts+++ b/frontend/src/components/shared/markdown-editor-extensions.test.ts@@ -1,6 +1,7 @@import { Editor } from '@tiptap/core';import { beforeAll, describe, expect, it } from 'vitest';+import { findVariableOccurrences } from './editor-variable-highlight';import { createMarkdownExtensions } from './markdown-editor-extensions';beforeAll(() => {@@ -125,3 +126,36 @@ describe('KNOWN UPSTREAM BUG — ordered > bullet > code drops the code block',expect(out).not.toContain('deepcode');});});++describe('findVariableOccurrences — doc spans for the Available-variables cycle', () => {+ const docOf = (md: string) => {+ const editor = new Editor({ content: md, contentType: 'markdown', extensions: createMarkdownExtensions() });+ const { doc } = editor.state;+ editor.destroy();++ return doc;+ };++ it('locates every {{.Var}} and each span maps to the literal token', () => {+ const doc = docOf('Use {{.Foo}} then {{.Foo}} and {{.Bar}}.');+ const foo = findVariableOccurrences(doc, 'Foo');++ expect(foo).toHaveLength(2);++ for (const hit of foo) {+ expect(doc.textBetween(hit.from, hit.to)).toBe('{{.Foo}}');+ }++ expect(findVariableOccurrences(doc, 'Bar')).toHaveLength(1);+ });++ it('returns none for an unused variable (caller then inserts instead of cycling)', () => {+ expect(findVariableOccurrences(docOf('Use {{.Foo}} only.'), 'Missing')).toHaveLength(0);+ });++ it('matches inside control-flow actions but honors word boundaries', () => {+ const doc = docOf('{{if .Enabled}}on{{end}} but not {{.EnabledExtra}}');++ expect(findVariableOccurrences(doc, 'Enabled')).toHaveLength(1);+ });+});diff --git a/frontend/src/components/shared/markdown-editor.tsx b/frontend/src/components/shared/markdown-editor.tsxindex 5425e639..590d5b60 100644--- a/frontend/src/components/shared/markdown-editor.tsx+++ b/frontend/src/components/shared/markdown-editor.tsx@@ -1,7 +1,7 @@import type { Editor } from '@tiptap/react';import { history } from '@tiptap/pm/history';-import { EditorState } from '@tiptap/pm/state';+import { EditorState, TextSelection } from '@tiptap/pm/state';import { EditorContent, useEditor } from '@tiptap/react';import {Bold,@@ -29,9 +29,11 @@ import { Separator } from '@/components/ui/separator';import { Toggle } from '@/components/ui/toggle';import { cn } from '@/lib/utils';+import { findVariableOccurrences } from './editor-variable-highlight';import { createMarkdownExtensions } from './markdown-editor-extensions';export interface MarkdownEditorHandle {+ cycleToVariable: (variable: string) => boolean;focus: () => void;getEditor: () => Editor | null;insertAtCursor: (text: string) => void;@@ -162,6 +164,37 @@ function MarkdownEditor({useImperativeHandle(ref,() => ({+ cycleToVariable: (variable: string) => {+ if (!editor) {+ return false;+ }++ const { state, view } = editor;+ const hits = findVariableOccurrences(state.doc, variable);++ if (hits.length === 0) {+ return false;+ }++ const { from, to } = state.selection;+ const currentIndex = hits.findIndex((hit) => hit.from === from && hit.to === to);+ const target =+ currentIndex >= 0+ ? hits[(currentIndex + 1) % hits.length]+ : (hits.find((hit) => hit.from >= from) ?? hits[0]);++ if (!target) {+ return false;+ }++ // Focus first: ProseMirror won't scrollIntoView an unfocused editor (first post-load click would no-op).+ view.focus();+ view.dispatch(+ state.tr.setSelection(TextSelection.create(state.doc, target.from, target.to)).scrollIntoView(),+ );++ return true;+ },focus: () => editor?.commands.focus(),getEditor: () => editor,insertAtCursor: (text: string) => {@@ -185,6 +218,13 @@ function MarkdownEditor({return;}+ // Skip when `value` is just our own echoed onUpdate output — the editor already reflects it, so the+ // getMarkdown re-serialization below would no-op. Mount (hasResetInitialHistoryRef) and real external+ // changes (form.reset, where value ≠ lastEmittedRef) still fall through and sync.+ if (hasResetInitialHistoryRef.current && value === lastEmittedRef.current) {+ return;+ }+const current = editor.getMarkdown();const shouldExternalSync = current !== value;diff --git a/frontend/src/pages/settings/settings-prompt.tsx b/frontend/src/pages/settings/settings-prompt.tsxindex 5ad4413a..8c6d205f 100644--- a/frontend/src/pages/settings/settings-prompt.tsx+++ b/frontend/src/pages/settings/settings-prompt.tsx@@ -261,14 +261,12 @@ interface VariablesPanelContainerProps {control: Control<HumanFormData> | Control<SystemFormData>;onVariableClick: (variable: string) => void;variables: string[];- viewMode: 'code' | 'plain';}interface VariablesProps {currentTemplate: string;onVariableClick: (variable: string) => void;variables: string[];- viewMode: 'code' | 'plain';}// Don't hoist this useWatch to the parent — it would re-subscribe the whole page per keystroke.@@ -310,7 +308,9 @@ function SettingsPrompt() {const handleVariableClick = useCallback((variable: string, field: { onChange: (value: string) => void; value: string }, formId: string) => {if (viewMode === 'code') {- editorRef.current?.insertAtCursor(`{{.${variable}}}`);+ if (!editorRef.current?.cycleToVariable(variable)) {+ editorRef.current?.insertAtCursor(`{{.${variable}}}`);+ }return;}@@ -981,7 +981,6 @@ function SettingsPrompt() {control={activeControl}onVariableClick={handleVariableClickCallback}variables={variablesData.variables}- viewMode={viewMode}/>) : null;@@ -1202,7 +1201,7 @@ function SettingsPrompt() {);}-function Variables({ currentTemplate, onVariableClick, variables, viewMode }: VariablesProps) {+function Variables({ currentTemplate, onVariableClick, variables }: VariablesProps) {const counts = useMemo(() => countVariableUses(currentTemplate, variables), [currentTemplate, variables]);if (variables.length === 0) {@@ -1214,22 +1213,16 @@ function Variables({ currentTemplate, onVariableClick, variables, viewMode }: Va<div className="border-b px-4 py-3"><h4 className="text-sm font-medium">Available variables</h4><p className="text-muted-foreground mt-1 text-xs">- {viewMode === 'code'- ? 'Click a variable to insert it into the editor.'- : 'Click to insert at the cursor, or cycle through existing uses.'}+ Click to insert at the cursor, or cycle through existing uses.</p></div><div className="bg-background flex flex-wrap gap-1.5 px-4 py-3">{variables.map((variable) => {const count = counts[variable] ?? 0;- // Plain-view only: a code-view click just inserts, so don't imply go-to-occurrence.- const isUsed = viewMode === 'plain' && count > 0;- const action =- viewMode === 'code'- ? `Insert {{.${variable}}} into the editor`- : isUsed- ? `Go to next {{.${variable}}} in the template${count > 1 ? ` (${count} uses)` : ''}`- : `Insert {{.${variable}}} at the cursor`;+ const isUsed = count > 0;+ const action = isUsed+ ? `Go to next {{.${variable}}} in the template${count > 1 ? ` (${count} uses)` : ''}`+ : `Insert {{.${variable}}} at the cursor`;return (<Badge@@ -1262,7 +1255,7 @@ function Variables({ currentTemplate, onVariableClick, variables, viewMode }: Va}// Don't hoist this useWatch to the parent — it would re-subscribe the whole page per keystroke.-function VariablesPanelContainer({ control, onVariableClick, variables, viewMode }: VariablesPanelContainerProps) {+function VariablesPanelContainer({ control, onVariableClick, variables }: VariablesPanelContainerProps) {const currentTemplate = useWatch({ control, name: 'template' });return (@@ -1270,7 +1263,6 @@ function VariablesPanelContainer({ control, onVariableClick, variables, viewModecurrentTemplate={currentTemplate}onVariableClick={onVariableClick}variables={variables}- viewMode={viewMode}/>);}