graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(gui): /goal starts work immediately (#181) + warn on a stray command on a later line (#182)
Rach Pradhanacd1cfa17578
diff --git a/gui/src/components/CommandResultDialog.tsx b/gui/src/components/CommandResultDialog.tsxindex 6adc57ff..f16ec16b 100644--- a/gui/src/components/CommandResultDialog.tsx+++ b/gui/src/components/CommandResultDialog.tsx@@ -23,12 +23,15 @@ interface CommandResultDialogProps {result: CommandRunResult | null;onClose: () => void;onApproveWorkflow?: (prompt: string) => Promise<void> | void;+ /** When set, renders the stray-command warning actions and sends the draft as-is. */+ onSendAsText?: () => void;}export function CommandResultDialog({result,onClose,onApproveWorkflow,+ onSendAsText,}: CommandResultDialogProps) {const workflowPrompt =result?.payload?.kind === "workflowDraft"@@ -72,6 +75,21 @@ export function CommandResultDialog({Approve</Button>) : null}+ {onSendAsText != null ? (+ <>+ <Button type="button" variant="outline" onClick={onClose}>+ Return to editing+ </Button>+ <Button+ type="button"+ onClick={() => {+ onSendAsText();+ }}+ >+ Send as text+ </Button>+ </>+ ) : null}</DialogFooter></DialogContent></Dialog>diff --git a/gui/src/components/PromptComposer.tsx b/gui/src/components/PromptComposer.tsxindex 0028a0f0..3a6f64aa 100644--- a/gui/src/components/PromptComposer.tsx+++ b/gui/src/components/PromptComposer.tsx@@ -70,6 +70,7 @@ export function PromptComposer({ binding, onCommandResult }: PromptComposerPropstrySubmitAsCommand,commandResult,dismissCommandResult,+ sendDraftAsText,} = useCommandRouter(binding, { onCommandResult });const requiresProviderSetup =promptSettings != null && promptSettings.availableModels.length === 0;@@ -244,6 +245,7 @@ export function PromptComposer({ binding, onCommandResult }: PromptComposerPropsresult={commandResult}onClose={dismissCommandResult}onApproveWorkflow={handleApproveWorkflow}+ onSendAsText={sendDraftAsText ?? undefined}/></div>);diff --git a/gui/src/components/new-chat-screen/NewChatPromptSection.tsx b/gui/src/components/new-chat-screen/NewChatPromptSection.tsxindex 164f1b6c..96f1e373 100644--- a/gui/src/components/new-chat-screen/NewChatPromptSection.tsx+++ b/gui/src/components/new-chat-screen/NewChatPromptSection.tsx@@ -58,6 +58,7 @@ export function NewChatPromptSection({trySubmitAsCommand,commandResult,dismissCommandResult,+ sendDraftAsText,} = useCommandRouter(binding, { onCommandResult });const interrupt = getActiveInterrupt(messages);const lastAssistant = getPlanDecisionAssistant({@@ -153,6 +154,7 @@ export function NewChatPromptSection({<CommandResultDialogresult={commandResult}onClose={dismissCommandResult}+ onSendAsText={sendDraftAsText ?? undefined}/></>);diff --git a/gui/src/hooks/useCommandRouter.test.ts b/gui/src/hooks/useCommandRouter.test.tsindex d9206a03..7fd49101 100644--- a/gui/src/hooks/useCommandRouter.test.ts+++ b/gui/src/hooks/useCommandRouter.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from "bun:test";-import { parseSlashCommand } from "./useCommandRouter";+import { findLineLeadingCommand, parseSlashCommand } from "./useCommandRouter";describe("parseSlashCommand", () => {test("returns null for a plain prompt with no slash", () => {@@ -47,3 +47,42 @@ describe("parseSlashCommand", () => {expect(parsed?.args).toEqual(["echo line1\necho line2"]);});});++describe("findLineLeadingCommand", () => {+ test("detects a known command that begins a non-first line", () => {+ expect(findLineLeadingCommand("context\n/goal investigate")).toBe("goal");+ });++ test("matches a command after leading spaces on a later line", () => {+ expect(findLineLeadingCommand("do the thing\n /loop keep going")).toBe(+ "loop",+ );+ });++ test("ignores the first line (already handled by parseSlashCommand)", () => {+ expect(findLineLeadingCommand("/goal do it\nmore prose")).toBeNull();+ });++ test("returns null for a plain multi-line prompt", () => {+ expect(findLineLeadingCommand("line one\nline two")).toBeNull();+ expect(findLineLeadingCommand("just one line /goal here")).toBeNull();+ });++ test("does not match a command embedded mid-line", () => {+ expect(findLineLeadingCommand("first\nbar /goal baz")).toBeNull();+ });++ test("does not match an unknown command on a later line", () => {+ expect(findLineLeadingCommand("first\n/unknowncmd please")).toBeNull();+ });++ test("does not false-positive on paths, URLs, or quoted commands", () => {+ expect(findLineLeadingCommand("see\n/usr/local/bin/tool")).toBeNull();+ expect(findLineLeadingCommand("docs\nhttps://example.com/goal")).toBeNull();+ expect(findLineLeadingCommand('note\n"/goal x" was run earlier')).toBeNull();+ });++ test("does not match a longer token that only starts with a command name", () => {+ expect(findLineLeadingCommand("first\n/goals of the project")).toBeNull();+ });+});diff --git a/gui/src/hooks/useCommandRouter.ts b/gui/src/hooks/useCommandRouter.tsindex 9a30b4d4..2638bc93 100644--- a/gui/src/hooks/useCommandRouter.ts+++ b/gui/src/hooks/useCommandRouter.ts@@ -1,4 +1,4 @@-import { useCallback, useState } from "react";+import { useCallback, useRef, useState } from "react";import { useSettingsNavigation } from "@/app/settingsNavigationContext";import { sessionStore } from "@/app/sessionStore";@@ -46,6 +46,26 @@ export function parseSlashCommand(draft: string): ParsedCommand | null {};}+/**+ * Detects a known slash command that begins a *continuation* line of the draft+ * (after optional leading spaces/tabs) and returns its name, or null. The whole+ * draft is only routed as a command when its entire trimmed body is one command+ * (see `parseSlashCommand`), so a command starting a later line is otherwise sent+ * silently as prose. The match is anchored to the start of each line, so mid-line+ * `/tokens` in paths, URLs, or quoted commands never false-positive. The first+ * line is skipped because it is already handled by `parseSlashCommand`.+ */+export function findLineLeadingCommand(draft: string): string | null {+ const lines = draft.split("\n");+ for (let index = 1; index < lines.length; index += 1) {+ const match = /^[ \t]*\/([\w-]+)(?:\s|$)/.exec(lines[index]);+ if (match != null && ARG_COMMANDS.has(match[1])) {+ return match[1];+ }+ }+ return null;+}+/*** Routes accepted slash-commands to GUI actions, backend execution, or, when a* command needs arguments, completes it into the draft so the user can finish@@ -61,8 +81,14 @@ export function useCommandRouter(trySubmitAsCommand: (draft: string) => boolean;commandResult: CommandRunResult | null;dismissCommandResult: () => void;+ /**+ * Set when the current dialog is the "stray command on a later line" warning;+ * calling it sends the draft unchanged as an ordinary prompt. Null otherwise.+ */+ sendDraftAsText: (() => void) | null;} {- const { setPlanningMode, setPromptDraft } = usePrompt(binding);+ const { isPlanningMode, setPlanningMode, setPromptDraft, submitPrompt } =+ usePrompt(binding);const { startNewChat, archiveConversation } = useSessionActions();const { openProviderSettings, openMcpSettings } = useSettingsNavigation();const workspacePath = binding?.workspacePath ?? null;@@ -71,6 +97,12 @@ export function useCommandRouter(const [commandResult, setCommandResult] = useState<CommandRunResult | null>(null,);+ // True while `commandResult` is the stray-command warning, so the composer+ // can offer a "send as text" action alongside the default "return to editing".+ const [strayCommandWarning, setStrayCommandWarning] = useState(false);+ // Guards the atomic `/goal` start against duplicate execution from repeated+ // submit events / retries: holds the in-flight `conversation:objective` key.+ const inFlightGoalRef = useRef<string | null>(null);const publishCommandResult = useCallback((result: CommandRunResult) => {if (result.payload?.kind === "workflowDraft") {@@ -121,6 +153,54 @@ export function useCommandRouter(const dispatch = useCallback((name: string, args: string[]): boolean => {switch (name) {+ case "goal": {+ const objective = args.join(" ").trim();+ // `/goal` (show current) and `/goal clear` are display/reset only;+ // they never start a turn, so leave them on the save-only path.+ if (objective.length === 0 || objective.toLowerCase() === "clear") {+ runBackend(name, args);+ return true;+ }+ // Without a persisted conversation we cannot start a turn, so fall+ // back to saving the goal only (the backend confirmation for that+ // path does not imply work has begun).+ if (workspacePath == null || conversationId == null) {+ runBackend(name, args);+ return true;+ }+ // Atomic: persist the goal, then start exactly one turn for it.+ // The in-flight guard drops duplicate submit events for the same goal.+ const guardKey = `${conversationId}:${objective}`;+ if (inFlightGoalRef.current === guardKey) {+ return true;+ }+ inFlightGoalRef.current = guardKey;+ void (async () => {+ try {+ const persisted = await desktopClient.runSlashCommand({+ name: "goal",+ args,+ workspacePath,+ conversationId,+ });+ if (persisted.snapshot != null) {+ sessionStore.getState().applySessionSnapshot(persisted.snapshot);+ }+ const snapshot = await desktopClient.sendPrompt({+ agentId: isPlanningMode ? "muse" : "forge",+ conversationId,+ prompt: objective,+ workspacePath,+ });+ sessionStore.getState().applySessionSnapshot(snapshot);+ } catch {+ // Leave no stale guard so the user can retry after a failure.+ } finally {+ inFlightGoalRef.current = null;+ }+ })();+ return true;+ }case "plan":case "muse":setPlanningMode(true);@@ -172,6 +252,7 @@ export function useCommandRouter(archiveConversation,binding,conversationId,+ isPlanningMode,openProviderSettings,openMcpSettings,runBackend,@@ -218,10 +299,36 @@ export function useCommandRouter([dispatch, publishCommandResult, setPromptDraft],);+ const dismissCommandResult = useCallback(() => {+ setCommandResult(null);+ setStrayCommandWarning(false);+ }, []);++ const confirmSendDraftAsText = useCallback(() => {+ setCommandResult(null);+ setStrayCommandWarning(false);+ void submitPrompt();+ }, [submitPrompt]);+const trySubmitAsCommand = useCallback((draft: string): boolean => {const parsed = parseSlashCommand(draft);if (parsed == null) {+ // A known command that starts a *later* line would otherwise be sent+ // silently as prose. Warn and let the user decide before that happens.+ const strayCommand = findLineLeadingCommand(draft);+ if (strayCommand != null) {+ setStrayCommandWarning(true);+ setCommandResult({+ title: "Did you mean to run a command?",+ body: `"/${strayCommand}" looks like a command, but it is not on the first line, so the whole message will be sent as ordinary text and the command will not run.\n\nReturn to editing to move it to its own message, or send this text unchanged.`,+ snapshot: null,+ savedPath: null,+ resultKind: "text",+ payload: null,+ });+ return true;+ }return false;}const handled = dispatch(parsed.name, parsed.args);@@ -238,6 +345,7 @@ export function useCommandRouter(handleCommandSelect,trySubmitAsCommand,commandResult,- dismissCommandResult: () => setCommandResult(null),+ dismissCommandResult,+ sendDraftAsText: strayCommandWarning ? confirmSendDraftAsText : null,};}