Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(visualize): reject fatal GeoGebra Text patterns and surface evalCommand failures (#1346)

evan188199-tech9286ede57f59
diff --git a/deeptutor/tools/vision/ggb_validator.py b/deeptutor/tools/vision/ggb_validator.py
index c156305e2..f65672aba 100644
--- a/deeptutor/tools/vision/ggb_validator.py
+++ b/deeptutor/tools/vision/ggb_validator.py
@@ -171,6 +171,76 @@ def validate_equation_format(command: str) -> tuple[str, list[str]]:
return command, warnings
+def _split_command_args(arg_string: str) -> list[str]:
+ """Split a comma-separated argument string, respecting nested brackets.
+
+ String literals (``"..."``) and parenthesised expressions may contain
+ commas that are not argument separators.
+ """
+ args: list[str] = []
+ depth = 0
+ in_string = False
+ current: list[str] = []
+ for char in arg_string:
+ if char == '"' and (not current or current[-1] != "\\"):
+ in_string = not in_string
+ if in_string:
+ current.append(char)
+ continue
+ if char in "([":
+ depth += 1
+ elif char in ")]":
+ depth -= 1
+ elif char == "," and depth == 0:
+ args.append("".join(current).strip())
+ current = []
+ continue
+ current.append(char)
+ tail = "".join(current).strip()
+ if tail:
+ args.append(tail)
+ return args
+
+
+def validate_text_command(command: str) -> tuple[str, list[str]]:
+ """Validate a ``Text`` command for arity and LaTeX balance.
+
+ GeoGebra accepts ``Text[<object>, <point>]`` (2 args) or
+ ``Text[<object>, <point>, <bool>, <bool>]`` (4 args) but **not**
+ ``Text[<string>, <x>, <y>]`` (3 args) — that last form is the one
+ reasoning models most often invent, and GeoGebra answers with
+ "illegal argument" rather than a structured error.
+
+ Also checks that ``$`` LaTeX delimiters are balanced inside string
+ arguments; an unbalanced ``$`` silently renders raw markup.
+
+ Returns:
+ Tuple of (command, list of error descriptions).
+ """
+ errors: list[str] = []
+ match = re.search(r"\bText\s*\[(.*)\]\s*$", command, re.DOTALL)
+ if match is None:
+ return command, errors
+
+ args = _split_command_args(match.group(1))
+ if len(args) == 3:
+ errors.append(
+ "Text[] has no 3-argument signature. Use Text[<object>, <point>] "
+ "(2 args) or Text[<object>, <point>, <bool>, <bool>] (4 args); "
+ "never Text[<string>, <x>, <y>]."
+ )
+
+ for arg in args:
+ if arg.startswith('"'):
+ if not arg.endswith('"'):
+ errors.append(f"Text[] argument {arg} has an unterminated string.")
+ continue
+ if arg.count("$") % 2 != 0:
+ errors.append(f"Text[] argument {arg} has unbalanced $ LaTeX delimiters.")
+
+ return command, errors
+
+
def validate_command(command: str) -> ValidationResult:
"""Validate and fix a single GeoGebra command.
@@ -206,6 +276,13 @@ def validate_command(command: str) -> ValidationResult:
_, warnings = validate_equation_format(result.fixed)
result.warnings.extend(warnings)
+ # Check Text command arity and LaTeX balance
+ _, errors = validate_text_command(result.fixed)
+ result.errors.extend(errors)
+
+ if result.errors:
+ result.is_valid = False
+
# Check if anything was fixed
if result.original != result.fixed:
result.is_valid = False
diff --git a/tests/visualizers/test_ggb_validator.py b/tests/visualizers/test_ggb_validator.py
new file mode 100644
index 000000000..cf6eede6e
--- /dev/null
+++ b/tests/visualizers/test_ggb_validator.py
@@ -0,0 +1,72 @@
+"""Tests for GeoGebra command validator fatal-pattern checks."""
+
+from deeptutor.tools.vision.ggb_validator import (
+ validate_command,
+ validate_ggbscript,
+)
+
+
+class TestTextArity:
+ def test_text_with_3_args_is_rejected(self):
+ # The fatal pattern from #1324: Text["str", expr, expr]
+ command = 'T9=Text["$(a+b)^2=a^2+2ab+b^2$",(a+b)/2,a+b+0.8]'
+ result = validate_command(command)
+ assert not result.is_valid
+ assert any("no 3-argument signature" in e for e in result.errors)
+
+ def test_text_with_2_args_passes(self):
+ command = 'T1=Text["$a^2$",(a/2,a/2)]'
+ result = validate_command(command)
+ assert result.is_valid
+ assert result.errors == []
+
+ def test_text_with_4_args_passes(self):
+ command = 'T2=Text["$ab$",(a+b/2,a/2),true,true]'
+ result = validate_command(command)
+ assert result.is_valid
+ assert result.errors == []
+
+ def test_non_text_commands_unaffected(self):
+ command = "S1=Segment[E,F]"
+ result = validate_command(command)
+ assert result.is_valid
+ assert result.errors == []
+
+
+class TestLaTeXBalance:
+ def test_unbalanced_dollar_is_rejected(self):
+ command = 'T1=Text["$a^2,(a/2,a/2)]'
+ result = validate_command(command)
+ assert not result.is_valid
+ assert len(result.errors) > 0
+
+ def test_balanced_dollar_passes(self):
+ command = 'T1=Text["$a^2+b^2$",(a/2,a/2)]'
+ result = validate_command(command)
+ assert result.is_valid
+ assert result.errors == []
+
+
+class TestScriptLevel:
+ def test_mixed_script_reports_line_number(self):
+ script = "\n".join(
+ [
+ "a=Slider(1,5,0.1)",
+ "b=Slider(1,5,0.1)",
+ 'T9=Text["$(a+b)^2$",(a+b)/2,a+b+0.8]',
+ ]
+ )
+ _, _, errors = validate_ggbscript(script)
+ assert len(errors) == 1
+ assert errors[0].startswith("Line 3:")
+
+ def test_clean_script_has_no_errors(self):
+ script = "\n".join(
+ [
+ "A=(0,0)",
+ "B=(1,1)",
+ 'T1=Text["$x$",(0.5,0.5)]',
+ ]
+ )
+ _, warnings, errors = validate_ggbscript(script)
+ assert errors == []
diff --git a/web/components/Geogebra.tsx b/web/components/Geogebra.tsx
index 560147212..98a1ec279 100644
--- a/web/components/Geogebra.tsx
+++ b/web/components/Geogebra.tsx
@@ -105,6 +105,7 @@ const Geogebra: React.FC<GeogebraProps> = ({
);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
+ const [commandErrors, setCommandErrors] = useState<string[]>([]);
useEffect(() => {
let cancelled = false;
@@ -164,14 +165,22 @@ const Geogebra: React.FC<GeogebraProps> = ({
view.y_max,
);
}
+ const failures: string[] = [];
for (const cmd of commands) {
try {
- api.evalCommand(cmd);
+ if (!api.evalCommand(cmd)) {
+ failures.push(cmd);
+ console.warn("[ggb] evalCommand returned false", { cmd });
+ }
} catch (err) {
+ failures.push(cmd);
console.warn("[ggb] evalCommand failed", { cmd, err });
}
}
setLoading(false);
+ if (!cancelled && failures.length > 0) {
+ setCommandErrors(failures);
+ }
},
},
true,
@@ -210,14 +219,36 @@ const Geogebra: React.FC<GeogebraProps> = ({
{t("Failed to load GeoGebra")}: {error}
</div>
) : (
- <div className="relative" style={{ minHeight: height }}>
- {loading ? (
- <div className="absolute inset-0 flex items-center justify-center text-sm text-[var(--muted-foreground)]">
- {t("Loading GeoGebra...")}
+ <>
+ {commandErrors.length > 0 ? (
+ <div
+ role="alert"
+ className="border-b border-[var(--border)] bg-[var(--destructive,#dc2626)]/5 px-3 py-2 text-[12px] leading-relaxed text-[var(--destructive,#dc2626)]"
+ >
+ <span className="font-medium">
+ {t("GeoGebra rejected {{count}} command(s)", {
+ count: commandErrors.length,
+ })}
+ :
+ </span>
+ <ul className="mt-1 list-inside list-disc">
+ {commandErrors.map((cmd) => (
+ <li key={cmd} className="truncate font-mono text-[11px]">
+ {cmd}
+ </li>
+ ))}
+ </ul>
</div>
) : null}
- <div ref={containerRef} className="ggb-applet-container" />
- </div>
+ <div className="relative" style={{ minHeight: height }}>
+ {loading ? (
+ <div className="absolute inset-0 flex items-center justify-center text-sm text-[var(--muted-foreground)]">
+ {t("Loading GeoGebra...")}
+ </div>
+ ) : null}
+ <div ref={containerRef} className="ggb-applet-container" />
+ </div>
+ </>
)}
</div>
);
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 8a91940f4..d889f4458 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1820,6 +1820,7 @@
"Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.": "Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.",
"Delete this turn?": "Delete this turn?",
"Failed to load GeoGebra": "Failed to load GeoGebra",
+ "GeoGebra rejected {{count}} command(s)": "GeoGebra rejected {{count}} command(s)",
"Loading GeoGebra...": "Loading GeoGebra...",
"HTML visualization": "HTML visualization",
"SVG visualization": "SVG visualization",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index d44038055..9afc4322d 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1820,6 +1820,7 @@
"Verify the backend is running and NEXT_PUBLIC_API_BASE points to a reachable host. For Docker, see data/user/settings/system.json.": "请确认后端正在运行,且 NEXT_PUBLIC_API_BASE 指向可访问的主机。Docker 部署请参考 data/user/settings/system.json。",
"Delete this turn?": "删除此轮对话?",
"Failed to load GeoGebra": "加载 GeoGebra 失败",
+ "GeoGebra rejected {{count}} command(s)": "GeoGebra 拒绝了 {{count}} 条命令",
"Loading GeoGebra...": "正在加载 GeoGebra...",
"HTML visualization": "HTML 可视化",
"SVG visualization": "SVG 可视化",