Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

GUI thinking controls + polish (on top of the GUI port) (#11)

Rach78d9264c7aad
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index afa74ee2..ab8ee719 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -45,6 +45,9 @@ jobs:
- name: zig build test
run: zig build test --summary all
+ - name: JSON live-control protocol test
+ run: python3 scripts/test-json-controls.py zig-out/bin/graff
+
- name: SDK generation drift
run: |
python3 sdk/generate.py --harness ./zig-out/bin/graff
diff --git a/gui/src-tauri/src/commands.rs b/gui/src-tauri/src/commands.rs
index 2e834e74..4ebc1f58 100644
--- a/gui/src-tauri/src/commands.rs
+++ b/gui/src-tauri/src/commands.rs
@@ -223,6 +223,32 @@ pub(crate) fn export_workflow_draft(
state.manager.export_workflow_draft(draft)
}
+#[tauri::command]
+pub(crate) async fn set_effort(
+ level: String,
+ workspace_path: Option<String>,
+ state: tauri::State<'_, DesktopState>,
+) -> Result<(), String> {
+ state
+ .manager
+ .set_effort(level, workspace_path)
+ .await
+ .map_err(map_command_error)
+}
+
+#[tauri::command]
+pub(crate) async fn set_fast(
+ on: bool,
+ workspace_path: Option<String>,
+ state: tauri::State<'_, DesktopState>,
+) -> Result<(), String> {
+ state
+ .manager
+ .set_fast(on, workspace_path)
+ .await
+ .map_err(map_command_error)
+}
+
#[tauri::command]
pub(crate) async fn set_active_agent(
agent_id: String,
diff --git a/gui/src-tauri/src/dto/runtime.rs b/gui/src-tauri/src/dto/runtime.rs
index 4bba1553..c5dc7a90 100644
--- a/gui/src-tauri/src/dto/runtime.rs
+++ b/gui/src-tauri/src/dto/runtime.rs
@@ -276,6 +276,7 @@ pub struct PromptSettingsDto {
pub selected_provider_id: Option<String>,
pub selected_model_id: Option<String>,
pub selected_reasoning_effort: Option<String>,
+ pub fast_enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
diff --git a/gui/src-tauri/src/lib.rs b/gui/src-tauri/src/lib.rs
index d1bb1e3d..138fd3ae 100644
--- a/gui/src-tauri/src/lib.rs
+++ b/gui/src-tauri/src/lib.rs
@@ -35,7 +35,7 @@ use commands::{
pick_directory, pick_workspace, push_git_branch, quick_start_project, reload_mcp_servers,
remove_mcp_server, remove_provider, rename_saved_workspace, rename_workspace, respond_followup,
run_slash_command, save_conversation_layout, select_conversation, send_prompt,
- set_active_agent, start_new_chat, start_provider_auth, stop_prompt, terminal_close,
+ set_active_agent, set_effort, set_fast, start_new_chat, start_provider_auth, stop_prompt, terminal_close,
terminal_open, terminal_resize, terminal_write, update_prompt_settings,
update_saved_workspace_layout, workspace_query, workspace_sync,
};
@@ -101,6 +101,8 @@ pub fn run() {
build_workflow_draft,
export_workflow_draft,
set_active_agent,
+ set_effort,
+ set_fast,
list_mcp_servers,
import_mcp_config,
remove_mcp_server,
diff --git a/gui/src-tauri/src/runtime/simple.rs b/gui/src-tauri/src/runtime/simple.rs
index de5fceeb..acd2a6ee 100644
--- a/gui/src-tauri/src/runtime/simple.rs
+++ b/gui/src-tauri/src/runtime/simple.rs
@@ -40,6 +40,10 @@ struct RuntimeState {
/// UI model selection, applied as `--model` when a session is spawned.
selected_provider: Option<String>,
selected_model: Option<String>,
+ /// Thinking controls (set via the GUI), applied on session spawn and
+ /// forwarded live to running sessions. None effort = the binary default.
+ selected_effort: Option<String>,
+ fast_enabled: bool,
/// Cached `graff --schema` model list (populated lazily).
model_catalog: Option<Vec<ModelOption>>,
/// Live `ask_user` prompts awaiting a GUI answer, keyed by conversation.
@@ -75,6 +79,7 @@ struct GraffSessionIo {
}
/// Coordinates the copied desktop GUI with the Zig-native codegraff binary.
+#[derive(Clone)]
pub struct RuntimeManager {
emitter: Arc<dyn UiEventEmitter>,
projects: Arc<ProjectStore>,
@@ -85,12 +90,17 @@ pub struct RuntimeManager {
impl RuntimeManager {
/// Creates a runtime manager backed by the copied GUI project registry.
pub fn new(emitter: Arc<dyn UiEventEmitter>, projects: Arc<ProjectStore>) -> Self {
+ let persisted_prompt = load_persisted_prompt_settings();
Self {
emitter,
projects,
state: Arc::new(Mutex::new(RuntimeState {
active_agent_id: Some("forge".into()),
conversations: load_persisted_conversations(),
+ selected_provider: persisted_prompt.selected_provider,
+ selected_model: persisted_prompt.selected_model,
+ selected_effort: persisted_prompt.selected_effort,
+ fast_enabled: persisted_prompt.fast_enabled,
..RuntimeState::default()
})),
sessions: Arc::new(Mutex::new(HashMap::new())),
@@ -133,11 +143,34 @@ impl RuntimeManager {
/// Returns the model picker, populated from `graff --schema`.
pub async fn get_prompt_settings(&self, _: Option<String>) -> Result<PromptSettingsDto> {
let catalog = self.ensure_model_catalog().await;
- let (selected_provider, selected_model) = {
+ // Only surface models for providers the user has credentials for,
+ // ordered codex first, then codegraff, then the rest (stable within
+ // each group).
+ let catalog = {
+ let key_list = codegraff_key_list().await.unwrap_or_default();
+ let configured: std::collections::HashSet<&str> = CODEGRAFF_PROVIDERS
+ .iter()
+ .filter(|provider| provider_configured(provider, &key_list))
+ .map(|provider| provider.id)
+ .collect();
+ let mut models: Vec<ModelOption> = catalog
+ .into_iter()
+ .filter(|model| configured.contains(model.provider.as_str()))
+ .collect();
+ models.sort_by_key(|model| match model.provider.as_str() {
+ "codex" => 0u8,
+ "codegraff" => 1,
+ _ => 2,
+ });
+ models
+ };
+ let (selected_provider, selected_model, selected_effort, fast_enabled) = {
let state = self.state.lock().await;
(
state.selected_provider.clone(),
state.selected_model.clone(),
+ state.selected_effort.clone(),
+ state.fast_enabled,
)
};
@@ -157,19 +190,38 @@ impl RuntimeManager {
selected_provider_id: Some("codegraff".into()),
selected_model_id: Some("default".into()),
selected_reasoning_effort: None,
+ fast_enabled: false,
});
}
let available_models = catalog
.iter()
- .map(|model| PromptModelOptionDto {
- provider_id: model.provider.clone(),
- provider_name: provider_display_name(&model.provider),
- model_id: model.name.clone(),
- model_name: Some(model.name.clone()),
- context_length: model.context,
- supports_reasoning: false,
- reasoning_efforts: vec![],
+ .map(|model| {
+ // Effort-capable providers (mirrors the binary's effortApplies):
+ // codex takes reasoning.effort via the Responses API; codegraff
+ // and deepseek take a top-level reasoning_effort. But the
+ // gateway's gpt-* models go through /v1/chat/completions, which
+ // rejects reasoning_effort (they need the codex/Responses path),
+ // so don't advertise effort for them.
+ let effort_capable = match model.provider.as_str() {
+ "codex" => true,
+ "codegraff" | "deepseek" => !model.name.starts_with("gpt-"),
+ _ => false,
+ };
+ let reasoning_efforts: Vec<String> = if effort_capable {
+ vec!["low".into(), "medium".into(), "high".into()]
+ } else {
+ vec![]
+ };
+ PromptModelOptionDto {
+ provider_id: model.provider.clone(),
+ provider_name: provider_display_name(&model.provider),
+ model_id: model.name.clone(),
+ model_name: Some(model.name.clone()),
+ context_length: model.context,
+ supports_reasoning: !reasoning_efforts.is_empty(),
+ reasoning_efforts,
+ }
})
.collect();
@@ -193,10 +245,67 @@ impl RuntimeManager {
available_models,
selected_provider_id,
selected_model_id,
- selected_reasoning_effort: None,
+ selected_reasoning_effort: selected_effort,
+ fast_enabled,
})
}
+ /// Generates a short chat title with the active model (a one-shot graff run)
+ /// and updates the conversation. Best-effort and fire-and-forget: failures
+ /// just leave the prompt-derived title in place.
+ async fn generate_and_set_title(
+ &self,
+ conversation_id: String,
+ prompt: String,
+ model: Option<String>,
+ ) {
+ let title_prompt = format!(
+ "Output a concise 2 to 4 word topic label in Title Case for the user's \
+ first chat message. Describe the topic literally — do NOT interpret, \
+ correct, rephrase, or expand the message. Examples: \"hey there\" -> \
+ Greeting; \"go through the repo\" -> Repo Walkthrough; \"fix the login \
+ bug\" -> Login Bug Fix. Reply with ONLY the label, nothing else.\n\nMessage: {prompt}"
+ );
+ let mut command = tokio::process::Command::new(codegraff_binary());
+ command.arg("-p").arg(&title_prompt).arg("--yolo");
+ if let Some(model) = &model {
+ command.arg("--model").arg(model);
+ }
+ let Ok(output) = command.output().await else {
+ return;
+ };
+ if !output.status.success() {
+ return;
+ }
+ let title = clean_title(&String::from_utf8_lossy(&output.stdout));
+ if title.is_empty() {
+ return;
+ }
+ {
+ let mut state = self.state.lock().await;
+ if let Some(conversation) = state.conversations.get_mut(&conversation_id) {
+ conversation.title = title;
+ }
+ }
+ self.persist_conversations().await;
+ let _ = self.emit().await;
+ }
+
+ /// Writes the current model/effort/fast selection to disk so it persists
+ /// across app restarts and seeds new chats.
+ async fn persist_prompt_settings(&self) {
+ let settings = {
+ let state = self.state.lock().await;
+ PersistedPromptSettings {
+ selected_provider: state.selected_provider.clone(),
+ selected_model: state.selected_model.clone(),
+ selected_effort: state.selected_effort.clone(),
+ fast_enabled: state.fast_enabled,
+ }
+ };
+ save_prompt_settings(&settings);
+ }
+
/// Persists the model selection and applies it to the live session when possible.
pub async fn update_prompt_settings(
&self,
@@ -206,6 +315,9 @@ impl RuntimeManager {
let mut state = self.state.lock().await;
state.selected_provider = Some(input.provider_id.clone());
state.selected_model = Some(input.model_id.clone());
+ if let Some(effort) = &input.reasoning_effort {
+ state.selected_effort = Some(effort.clone());
+ }
state.active_conversation_id.clone()
};
if let Some(conversation_id) = live_conversation_id {
@@ -218,8 +330,16 @@ impl RuntimeManager {
}),
)
.await?;
+ if let Some(effort) = &input.reasoning_effort {
+ self.send_control(
+ &conversation_id,
+ serde_json::json!({ "type": "set_effort", "level": effort }),
+ )
+ .await?;
+ }
}
}
+ self.persist_prompt_settings().await;
self.get_prompt_settings(input.workspace_path).await
}
@@ -347,8 +467,11 @@ impl RuntimeManager {
.unwrap_or_else(|| format!("chat-{}", Uuid::new_v4().simple()));
let request_id = format!("request-{}", Uuid::new_v4().simple());
let plan_mode = input.agent_id.as_deref() == Some("muse");
+ let is_first_turn;
+ let title_model;
{
let mut state = self.state.lock().await;
+ title_model = state.selected_model.clone();
set_active_workspace(&mut state, &input.workspace_path);
state.active_conversation_id = Some(conversation_id.clone());
state
@@ -368,6 +491,7 @@ impl RuntimeManager {
plan_mode,
});
conversation.plan_mode = plan_mode;
+ is_first_turn = conversation.messages.is_empty();
conversation.messages.push(SessionMessageDto::User {
id: format!("{request_id}-user"),
request_id: request_id.clone(),
@@ -395,6 +519,17 @@ impl RuntimeManager {
self.emit().await?;
+ if is_first_turn {
+ let manager = self.clone();
+ let conversation_id = conversation_id.clone();
+ let prompt = input.prompt.clone();
+ tokio::spawn(async move {
+ manager
+ .generate_and_set_title(conversation_id, prompt, title_model)
+ .await;
+ });
+ }
+
if self.session_exists(&conversation_id).await {
self.send_control(
&conversation_id,
@@ -735,7 +870,7 @@ impl RuntimeManager {
continue;
};
match event.get("type").and_then(serde_json::Value::as_str) {
- Some("model" | "compact" | "mode" | "agent") => break event,
+ Some("model" | "compact" | "mode" | "agent" | "effort" | "fast") => break event,
Some("error") => {
let message = event
.get("message")
@@ -810,7 +945,7 @@ impl RuntimeManager {
) -> Result<GraffSessionIo> {
let mut sessions = self.sessions.lock().await;
if !sessions.contains_key(conversation_id) {
- let (model, active_agent_id, plan_mode) = {
+ let (model, active_agent_id, plan_mode, effort, fast) = {
let state = self.state.lock().await;
let conversation = state.conversations.get(conversation_id);
(
@@ -821,6 +956,8 @@ impl RuntimeManager {
conversation
.map(|conversation| conversation.plan_mode)
.unwrap_or(false),
+ state.selected_effort.clone(),
+ state.fast_enabled,
)
};
let session = spawn_graff_session(workspace_path, model.as_deref())?;
@@ -840,6 +977,20 @@ impl RuntimeManager {
)
.await?;
}
+ if let Some(level) = effort {
+ self.send_control(
+ conversation_id,
+ serde_json::json!({ "type": "set_effort", "level": level }),
+ )
+ .await?;
+ }
+ if fast {
+ self.send_control(
+ conversation_id,
+ serde_json::json!({ "type": "set_fast", "on": true }),
+ )
+ .await?;
+ }
sessions = self.sessions.lock().await;
}
let session = sessions
@@ -1001,6 +1152,47 @@ impl RuntimeManager {
}
/// Sets the active agent and applies it to the live conversation when present.
+ /// Sets the reasoning-effort level (low|medium|high). Stored for future
+ /// sessions and forwarded to the active session if one is live.
+ pub async fn set_effort(&self, level: String, _: Option<String>) -> Result<()> {
+ let conversation_id = {
+ let mut state = self.state.lock().await;
+ state.selected_effort = Some(level.clone());
+ state.active_conversation_id.clone()
+ };
+ if let Some(conversation_id) = conversation_id {
+ if self.session_exists(&conversation_id).await {
+ self.send_control(
+ &conversation_id,
+ serde_json::json!({ "type": "set_effort", "level": level }),
+ )
+ .await?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Toggles Codex "fast" mode (priority service tier). Stored for future
+ /// sessions and forwarded to the active session if one is live.
+ pub async fn set_fast(&self, on: bool, _: Option<String>) -> Result<()> {
+ let conversation_id = {
+ let mut state = self.state.lock().await;
+ state.fast_enabled = on;
+ state.active_conversation_id.clone()
+ };
+ if let Some(conversation_id) = conversation_id {
+ if self.session_exists(&conversation_id).await {
+ self.send_control(
+ &conversation_id,
+ serde_json::json!({ "type": "set_fast", "on": on }),
+ )
+ .await?;
+ }
+ }
+ self.persist_prompt_settings().await;
+ Ok(())
+ }
+
pub async fn set_active_agent(
&self,
agent_id: String,
@@ -1748,6 +1940,47 @@ struct PersistedConversation {
}
/// Path to the transcript store (`~/.codegraff-gui/conversations.json`).
+#[derive(serde::Serialize, serde::Deserialize, Default)]
+struct PersistedPromptSettings {
+ #[serde(default)]
+ selected_provider: Option<String>,
+ #[serde(default)]
+ selected_model: Option<String>,
+ #[serde(default)]
+ selected_effort: Option<String>,
+ #[serde(default)]
+ fast_enabled: bool,
+}
+
+/// Path to the persisted prompt selection (`~/.codegraff-gui/prompt-settings.json`).
+fn prompt_settings_store_path() -> Option<PathBuf> {
+ std::env::var_os("HOME")
+ .map(|home| PathBuf::from(home).join(".codegraff-gui").join("prompt-settings.json"))
+}
+
+/// Loads the last model/effort/fast selection so it survives app restarts.
+fn load_persisted_prompt_settings() -> PersistedPromptSettings {
+ let Some(path) = prompt_settings_store_path() else {
+ return PersistedPromptSettings::default();
+ };
+ let Ok(data) = std::fs::read_to_string(&path) else {
+ return PersistedPromptSettings::default();
+ };
+ serde_json::from_str(&data).unwrap_or_default()
+}
+
+fn save_prompt_settings(settings: &PersistedPromptSettings) {
+ let Some(path) = prompt_settings_store_path() else {
+ return;
+ };
+ if let Some(dir) = path.parent() {
+ let _ = std::fs::create_dir_all(dir);
+ }
+ if let Ok(data) = serde_json::to_string_pretty(settings) {
+ let _ = std::fs::write(&path, data);
+ }
+}
+
fn conversations_store_path() -> Option<PathBuf> {
std::env::var_os("HOME").map(|home| {
PathBuf::from(home)
@@ -2333,9 +2566,15 @@ fn provider_configured(provider: &CodegraffProvider, key_list: &str) -> bool {
}
fn key_list_mentions_provider(key_list: &str, provider_id: &str) -> bool {
- key_list
- .lines()
- .any(|line| line.split_whitespace().any(|part| part == provider_id))
+ // `graff key list` lists every provider; a provider only counts as keyed
+ // when its row's trailing "stored" column isn't the "—" placeholder.
+ key_list.lines().any(|line| {
+ let mut parts = line.split_whitespace();
+ parts.next() == Some(provider_id)
+ && parts
+ .last()
+ .map_or(false, |stored| stored != "—" && stored != "-")
+ })
}
fn home_file_exists(relative_path: &str) -> bool {
@@ -2507,6 +2746,23 @@ fn shell_single_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
+/// Normalizes a model-generated title: first line, stripped of quotes/punctuation,
+/// capped to a handful of words.
+fn clean_title(raw: &str) -> String {
+ let first = raw.trim().lines().next().unwrap_or("").trim();
+ let trimmed = first.trim_matches(|c: char| {
+ c == '"' || c == '\'' || c == '.' || c == ':' || c.is_whitespace()
+ });
+ trimmed
+ .split_whitespace()
+ .take(8)
+ .collect::<Vec<_>>()
+ .join(" ")
+ .chars()
+ .take(60)
+ .collect()
+}
+
fn title_from_prompt(prompt: &str) -> String {
let title = prompt
.split_whitespace()
diff --git a/gui/src/app/SessionProvider.test.tsx b/gui/src/app/SessionProvider.test.tsx
index 04b0d605..55cb0e84 100644
--- a/gui/src/app/SessionProvider.test.tsx
+++ b/gui/src/app/SessionProvider.test.tsx
@@ -121,6 +121,7 @@ const promptSettingsFixture: PromptSettings = {
selectedModelId: "gpt-5.4",
selectedProviderId: "openai",
selectedReasoningEffort: "medium",
+ fastEnabled: false,
};
mock.module("../hooks/useSessionBootstrap", () => ({
@@ -128,6 +129,7 @@ mock.module("../hooks/useSessionBootstrap", () => ({
}));
mock.module("../services/desktop/client", () => ({
+ setFast: async () => {},
openExternalUrl: async () => {},
openPathInTarget: async () => {},
ensureConversationView: async () => {
diff --git a/gui/src/app/sessionStore.test.ts b/gui/src/app/sessionStore.test.ts
index dfa3b733..d58689af 100644
--- a/gui/src/app/sessionStore.test.ts
+++ b/gui/src/app/sessionStore.test.ts
@@ -46,6 +46,7 @@ const promptSettingsFixture: PromptSettings = {
selectedModelId: "gpt-5.4",
selectedProviderId: "openai",
selectedReasoningEffort: "medium",
+ fastEnabled: false,
};
function createSnapshot(
@@ -97,6 +98,7 @@ function createSnapshot(
}
mock.module("../services/desktop/client", () => ({
+ setFast: async () => {},
openExternalUrl: async () => {},
openPathInTarget: async () => {},
ensureConversationView: async (workspacePath: string, conversationId: string) => {
diff --git a/gui/src/components/PromptInputCard.test.tsx b/gui/src/components/PromptInputCard.test.tsx
index dd01c4c6..7f0a33a4 100644
--- a/gui/src/components/PromptInputCard.test.tsx
+++ b/gui/src/components/PromptInputCard.test.tsx
@@ -25,6 +25,7 @@ const promptSettings: PromptSettings = {
selectedModelId: "claude-sonnet-long",
selectedProviderId: "anthropic",
selectedReasoningEffort: "medium",
+ fastEnabled: false,
};
function renderPromptInputCard() {
diff --git a/gui/src/components/PromptInputCard.tsx b/gui/src/components/PromptInputCard.tsx
index 13e21df2..f82c73f6 100644
--- a/gui/src/components/PromptInputCard.tsx
+++ b/gui/src/components/PromptInputCard.tsx
@@ -1,9 +1,10 @@
-import { useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import {
ArrowUpIcon,
ChevronDownIcon,
MapIcon,
SquareIcon,
+ ZapIcon,
} from "lucide-react";
import { Button } from "@/components/ui/Button";
@@ -36,6 +37,7 @@ import { useAttachments } from "@/hooks/useSession";
import { useCommandAutocomplete } from "@/hooks/useCommandAutocomplete";
import { useDropZone } from "@/hooks/useFileDrop";
import { usePromptModelPicker } from "@/hooks/usePromptModelPicker";
+import { setFast } from "@/services/desktop/client";
import { cn } from "@/utils/cn";
import {
formatPlanningThinkingLabel,
@@ -97,6 +99,20 @@ export function PromptInputCard({
updatePromptSettings,
});
+ const [fastEnabled, setFastEnabled] = useState(
+ promptSettings?.fastEnabled ?? false,
+ );
+ useEffect(() => {
+ setFastEnabled(promptSettings?.fastEnabled ?? false);
+ }, [promptSettings?.fastEnabled]);
+ const isCodexModel = selectedModel?.providerId === "codex";
+
+ function handleFastToggle() {
+ const next = !fastEnabled;
+ setFastEnabled(next);
+ void setFast(next);
+ }
+
function handleAutocompleteSelect(command: Parameters<typeof onCommandSelect>[0]) {
// The model picker lives in this component, so handle `/model` here rather
// than routing it up.
@@ -349,6 +365,26 @@ export function PromptInputCard({
<MapIcon data-icon="inline-start" />
<span className="text-xs">Plan</span>
</Button>
+ {isCodexModel ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ aria-label="Toggle fast mode"
+ aria-pressed={fastEnabled}
+ className={cn(
+ "text-muted-foreground hover:bg-transparent hover:text-foreground",
+ fastEnabled &&
+ "border-[color:var(--accent)] bg-[color:color-mix(in_oklab,var(--accent)_10%,transparent)] text-foreground hover:bg-[color:color-mix(in_oklab,var(--accent)_14%,transparent)]",
+ )}
+ disabled={isControlDisabled}
+ onClick={handleFastToggle}
+ title="Codex priority service tier — lower latency"
+ >
+ <ZapIcon data-icon="inline-start" />
+ <span className="text-xs">Fast</span>
+ </Button>
+ ) : null}
{isPlanningMode ? (
<span
className="inline-flex h-8 items-center gap-2 px-1.5 text-xs font-medium text-muted-foreground"
diff --git a/gui/src/components/chat/ChatActivityRow.tsx b/gui/src/components/chat/ChatActivityRow.tsx
index af59b526..861622b6 100644
--- a/gui/src/components/chat/ChatActivityRow.tsx
+++ b/gui/src/components/chat/ChatActivityRow.tsx
@@ -1,5 +1,19 @@
-import { useEffect, useRef, useState } from "react";
-import { ChevronDown, ChevronRight } from "lucide-react";
+import { useEffect, useRef, useState, type ComponentType } from "react";
+import {
+ Activity,
+ Bot,
+ ChevronDown,
+ ChevronRight,
+ FileText,
+ Globe,
+ ListTodo,
+ Map,
+ MessageCircle,
+ Pencil,
+ Search,
+ Sparkles,
+ Terminal,
+} from "lucide-react";
import {
Collapsible,
@@ -35,6 +49,35 @@ const activityTextClassName = cn(
CHAT_MUTED_TEXT_CLASS,
);
+function operationIcon(kind: string): ComponentType<{ className?: string }> {
+ switch (kind) {
+ case "file_read":
+ return FileText;
+ case "file_update":
+ return Pencil;
+ case "shell":
+ return Terminal;
+ case "search":
+ case "codebase_search":
+ return Search;
+ case "fetch":
+ return Globe;
+ case "followup":
+ return MessageCircle;
+ case "plan":
+ return Map;
+ case "skill":
+ return Sparkles;
+ case "task":
+ return Bot;
+ case "todo_read":
+ case "todo_write":
+ return ListTodo;
+ default:
+ return Activity;
+ }
+}
+
function ActivityChevron({
open,
className,
@@ -64,9 +107,11 @@ function ActivityOperationRow({
const isExpandable = result != null;
const label = formatOperationLabel(operation, workspacePath);
const isCommand = operation.detail.kind === "shell";
+ const Icon = operationIcon(operation.detail.kind);
const content = (
<>
+ <Icon className="size-3.5 shrink-0 text-muted-foreground/60" />
<span className="min-w-0">
{isCommand ? (
<code className="rounded-md bg-muted px-1.5 py-0.5 font-mono text-xs text-foreground">
@@ -161,7 +206,7 @@ export function ChatActivityRow({ item, workspacePath }: ChatActivityRowProps) {
<article className="grid min-w-0 max-w-3xl gap-1">
<CollapsibleTrigger className={activityTriggerClassName}>
{item.isRunning ? (
- <Throbber variant="tool" className="text-muted-foreground" />
+ <Throbber variant="spinner" className="text-muted-foreground" />
) : null}
<ChatStatusLabel text={item.summary} />
<ActivityChevron
@@ -170,7 +215,7 @@ export function ChatActivityRow({ item, workspacePath }: ChatActivityRowProps) {
/>
</CollapsibleTrigger>
<CollapsibleContent className="min-w-0 max-w-full">
- <div className="grid min-w-0 gap-1">
+ <div className="ml-[7px] grid min-w-0 gap-1.5 border-l border-border/50 pl-3 pt-0.5">
{item.operations.map((operation) => (
<ActivityOperationRow
key={operation.id}
diff --git a/gui/src/services/desktop/client.ts b/gui/src/services/desktop/client.ts
index 43282290..d30750ac 100644
--- a/gui/src/services/desktop/client.ts
+++ b/gui/src/services/desktop/client.ts
@@ -185,6 +185,7 @@ function qaPromptSettings(): PromptSettings {
selectedModelId: "claude-sonnet-4",
selectedProviderId: "anthropic",
selectedReasoningEffort: qaReasoningEffort,
+ fastEnabled: false,
};
}
@@ -462,6 +463,26 @@ export function setActiveAgent(
});
}
+export function setEffort(
+ level: "low" | "medium" | "high",
+ workspacePath?: string | null,
+): Promise<void> {
+ return invokeCommand("set_effort", {
+ level,
+ workspacePath: workspacePath ?? null,
+ });
+}
+
+export function setFast(
+ on: boolean,
+ workspacePath?: string | null,
+): Promise<void> {
+ return invokeCommand("set_fast", {
+ on,
+ workspacePath: workspacePath ?? null,
+ });
+}
+
export function listMcpServers(
workspacePath?: string | null,
): Promise<McpSettingsPayload> {
diff --git a/gui/src/services/desktop/types/contracts.generated.ts b/gui/src/services/desktop/types/contracts.generated.ts
index b44a77cc..a1b332cb 100644
--- a/gui/src/services/desktop/types/contracts.generated.ts
+++ b/gui/src/services/desktop/types/contracts.generated.ts
@@ -43,7 +43,7 @@ export type SessionSnapshot = { activeWorkspacePath: string | null, activeConver
export type PromptModelOption = { providerId: string, providerName: string, modelId: string, modelName: string | null, contextLength: bigint | null, supportsReasoning: boolean, reasoningEfforts: Array<string>, };
-export type PromptSettings = { availableModels: Array<PromptModelOption>, selectedProviderId: string | null, selectedModelId: string | null, selectedReasoningEffort: string | null, };
+export type PromptSettings = { availableModels: Array<PromptModelOption>, selectedProviderId: string | null, selectedModelId: string | null, selectedReasoningEffort: string | null, fastEnabled: boolean, };
export type UpdatePromptSettingsInput = { workspacePath: string | null, providerId: string, modelId: string, reasoningEffort: string | null, };
diff --git a/scripts/test-json-controls.py b/scripts/test-json-controls.py
new file mode 100755
index 00000000..6e140e48
--- /dev/null
+++ b/scripts/test-json-controls.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Automated integration test for the graff --json live control protocol.
+
+Spawns `graff --json`, sends each control request (set_model / compact /
+set_mode / set_agent) plus error paths, and asserts the structured ack/error
+events. Deterministic and offline: a dummy CODEGRAFF_API_KEY lets the session
+start and switch within codegraff, while switching to a keyless provider
+exercises the error path -- no real API calls.
+
+Usage: python3 scripts/test-json-controls.py [path-to-graff]
+Exit 0 if all assertions pass, 1 otherwise.
+"""
+import json, os, subprocess, sys, tempfile
+
+BIN = sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff"
+
+# (request, predicate(event)->bool, human description)
+CASES = [
+ ({"type": "set_mode", "mode": "plan"},
+ lambda e: e.get("type") == "mode" and e.get("ok") and e.get("mode") == "plan",
+ "set_mode plan -> mode ack"),
+ ({"type": "set_mode", "mode": "normal"},
+ lambda e: e.get("type") == "mode" and e.get("mode") == "normal",
+ "set_mode normal -> mode ack"),
+ ({"type": "set_mode", "mode": "sideways"},
+ lambda e: e.get("type") == "error" and "plan" in e.get("message", ""),
+ "set_mode invalid -> error"),
+ ({"type": "set_agent", "id": "reviewer"},
+ lambda e: e.get("type") == "agent" and e.get("ok") and e.get("id") == "reviewer" and e.get("chars", 0) > 0,
+ "set_agent reviewer -> agent ack"),
+ ({"type": "set_agent", "id": ""},
+ lambda e: e.get("type") == "agent" and e.get("ok") and e.get("id") == "",
+ "set_agent reset -> agent ack"),
+ ({"type": "set_agent", "id": "definitely-not-an-agent"},
+ lambda e: e.get("type") == "error" and "unknown agent" in e.get("message", ""),
+ "set_agent unknown -> error"),
+ ({"type": "set_model", "name": "codegraff deepseek-v4-pro"},
+ lambda e: e.get("type") == "model" and e.get("ok") and e.get("id") == "codegraff",
+ "set_model (keyed provider) -> model ack"),
+ ({"type": "set_model", "name": "anthropic"},
+ lambda e: e.get("type") == "error" and "key" in e.get("message", "").lower(),
+ "set_model (keyless provider) -> error"),
+ ({"type": "set_model", "name": ""},
+ lambda e: e.get("type") == "error" and "non-empty" in e.get("message", ""),
+ "set_model empty -> error"),
+ ({"type": "compact"},
+ lambda e: e.get("type") == "compact" and e.get("ok") and e.get("chars") == 0,
+ "compact (empty history) -> compact ack"),
+ ({"type": "set_effort", "level": "high"},
+ lambda e: e.get("type") == "effort" and e.get("ok") and e.get("level") == "high",
+ "set_effort high -> effort ack"),
+ ({"type": "set_effort", "level": "medium"},
+ lambda e: e.get("type") == "effort" and e.get("level") == "medium",
+ "set_effort medium -> effort ack"),
+ ({"type": "set_effort", "level": "sideways"},
+ lambda e: e.get("type") == "error" and "low" in e.get("message", ""),
+ "set_effort invalid -> error"),
+ ({"type": "set_fast", "on": True},
+ lambda e: e.get("type") == "fast" and e.get("ok") and e.get("on") is True,
+ "set_fast on -> fast ack"),
+ ({"type": "set_fast", "on": False},
+ lambda e: e.get("type") == "fast" and e.get("on") is False,
+ "set_fast off -> fast ack"),
+]
+CONTROL_TYPES = {"model", "compact", "mode", "agent", "effort", "fast", "error"}
+
+def run():
+ env = dict(os.environ)
+ env["CODEGRAFF_API_KEY"] = "dummy-key-for-test" # lets the session start + switch within codegraff
+ env["GRAFF_NO_TELEMETRY"] = "1"
+ env["HOME"] = tempfile.mkdtemp() # isolate: no codex auth, no real keys
+ for k in list(env):
+ if k.endswith("_API_KEY") and k != "CODEGRAFF_API_KEY":
+ del env[k]
+ stdin = "".join(json.dumps(c[0]) + "\n" for c in CASES)
+ try:
+ p = subprocess.run([BIN, "--json"], input=stdin, text=True,
+ capture_output=True, timeout=60, env=env)
+ out = p.stdout
+ except subprocess.TimeoutExpired as e:
+ out = (e.stdout or b"").decode("utf-8", "ignore") if isinstance(e.stdout, bytes) else (e.stdout or "")
+
+ acks = []
+ for line in out.splitlines():
+ line = line.strip()
+ if not line.startswith("{"):
+ continue
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ if ev.get("type") in CONTROL_TYPES:
+ acks.append(ev)
+
+ passed = failed = 0
+ for i, (req, pred, desc) in enumerate(CASES):
+ ev = acks[i] if i < len(acks) else None
+ ok = ev is not None and pred(ev)
+ print(f" {'PASS' if ok else 'FAIL'} {desc}")
+ if not ok:
+ print(f" got: {json.dumps(ev) if ev else '(no event)'}")
+ failed += 1
+ else:
+ passed += 1
+ print(f"\n {passed}/{len(CASES)} passed")
+ return failed == 0
+
+if __name__ == "__main__":
+ print(f"graff --json live-control protocol test ({BIN})\n")
+ sys.exit(0 if run() else 1)
diff --git a/src/main.zig b/src/main.zig
index 6562fc9b..76a4b2e5 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -79,7 +79,7 @@ var unattended = false; // -p one-shot: no human to prompt; unapproved tool call
const schema_protocol_json =
\\{
\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",
- \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"name\":\"provider|provider/model|model\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"} are live control requests acked by model/compact/mode/agent events. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",
+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"name\":\"provider|provider/model|model\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast events. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",
\\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to harness.trajectory.jsonl (the append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",
\\ "events": [
\\ {"type": "text", "text": "assistant text delta"},
@@ -92,6 +92,8 @@ const schema_protocol_json =
\\ {"type": "compact", "ok": true, "chars": 0},
\\ {"type": "mode", "ok": true, "mode": "plan"},
\\ {"type": "agent", "ok": true, "id": "reviewer", "chars": 0},
+ \\ {"type": "effort", "ok": true, "level": "medium", "applies": true},
+ \\ {"type": "fast", "ok": true, "on": true, "applies": true},
\\ {"type": "score", "ok": true, "prompt_sha": "..."},
\\ {"type": "error", "message": "..."}
\\ ]
@@ -4048,6 +4050,29 @@ pub fn main(init: std.process.Init) !void {
root.emit(.{ .type = "agent", .ok = true, .id = id, .chars = root.sys_normal.len });
continue;
}
+ if (std.mem.eql(u8, rtype, "set_effort")) {
+ const level = if (parsed.object.get("level")) |v| (if (v == .string) v.string else "") else "";
+ if (std.mem.eql(u8, level, "low")) {
+ root.reasoning = .low;
+ } else if (std.mem.eql(u8, level, "medium")) {
+ root.reasoning = .medium;
+ } else if (std.mem.eql(u8, level, "high")) {
+ root.reasoning = .high;
+ } else {
+ root.emit(.{ .type = "error", .message = "set_effort needs level 'low', 'medium', or 'high'" });
+ continue;
+ }
+ _ = saveThinkingSettings(root.io, root.gpa, root.reasoning, root.fast);
+ root.emit(.{ .type = "effort", .ok = true, .level = level, .applies = root.effortApplies() });
+ continue;
+ }
+ if (std.mem.eql(u8, rtype, "set_fast")) {
+ const on = if (parsed.object.get("on")) |v| (if (v == .bool) v.bool else false) else false;
+ root.fast = on;
+ _ = saveThinkingSettings(root.io, root.gpa, root.reasoning, root.fast);
+ root.emit(.{ .type = "fast", .ok = true, .on = on, .applies = root.provider.kind == .responses });
+ continue;
+ }
if (std.mem.eql(u8, rtype, "score")) {
const sha = if (parsed.object.get("prompt_sha")) |v| (if (v == .string) v.string else "") else "";
const sc: f64 = if (parsed.object.get("score")) |v| switch (v) {
@@ -4374,6 +4399,7 @@ fn applyProvider(root: *Agent, arena: Allocator, p: Provider) []const u8 {
}
}
root.cap_new = false; // per-provider token-cap quirk; relearn on rejection
+ root.effort_rejected = false; // new model may accept reasoning_effort; relearn
root.provider = p;
saveModel(root.io, root.home, p.id, p.model); // remember for next launch
return note;
@@ -6198,7 +6224,8 @@ fn serveTerminalEvent(line: []const u8) bool {
return std.mem.eql(u8, t, "turn") or std.mem.eql(u8, t, "error") or
std.mem.eql(u8, t, "system_prompt") or std.mem.eql(u8, t, "score") or
std.mem.eql(u8, t, "model") or std.mem.eql(u8, t, "compact") or
- std.mem.eql(u8, t, "mode") or std.mem.eql(u8, t, "agent");
+ std.mem.eql(u8, t, "mode") or std.mem.eql(u8, t, "agent") or
+ std.mem.eql(u8, t, "effort") or std.mem.eql(u8, t, "fast");
}
/// Remove a dead session and free it (child already gone or being killed).
@@ -6534,6 +6561,7 @@ fn loadSession(root: *Agent, keys: Keys, arena: Allocator, name: []const u8) !vo
root.strict = strict;
root.last_context_tokens = 0;
root.cap_new = false; // per-provider; relearn on rejection
+ root.effort_rejected = false;
}
/// A normalized tool invocation — same shape for both providers.
@@ -6639,6 +6667,7 @@ const Agent = struct {
streamed_args: ArgTool = .none, // which meta tool's prose streamed live this request
streamed_args_len: usize = 0, // raw bytes emitted for it (gates re-print suppression)
cap_new: bool = false, // provider rejected max_tokens → use max_completion_tokens
+ effort_rejected: bool = false, // model rejected reasoning_effort → drop it (e.g. gpt-5.5 on chat/completions wants /v1/responses)
next_ask_id: u64 = 1,
fn prompt(self: *Agent) !void {
@@ -6883,6 +6912,10 @@ const Agent = struct {
self.cap_new = true; // provider wants the post-deprecation name
continue;
}
+ if (!self.effort_rejected and std.mem.indexOf(u8, msg, "reasoning_effort") != null) {
+ self.effort_rejected = true; // model rejects reasoning_effort here (wants /v1/responses); drop + retry
+ continue;
+ }
if (self.tracer) |tr| tr.api(self.label, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("api error: {s}", .{msg});
return error.ApiError;
@@ -7704,7 +7737,7 @@ const Agent = struct {
// Reasoning-effort hint for OpenAI-compatible providers that
// honor it (codegraff gateway, deepseek). Mirrors the
// Responses `reasoning.effort` set in the branch below.
- if (self.effortApplies()) {
+ if (self.effortApplies() and !self.effort_rejected) {
try s.objectField("reasoning_effort");
try s.write(@tagName(self.reasoning));
}