From 1b9d0b03f0121c4926be542dea7fb038c0ecb23e Mon Sep 17 00:00:00 2001 From: Thomas Petersen Date: Fri, 29 May 2026 13:59:44 -0400 Subject: [PATCH] Prototype Quake-style Sprout console Add a backtick-toggled desktop console that runs allowlisted read-only Sprout CLI commands through Tauri while keeping app-native navigation commands local. Co-authored-by: Cursor --- desktop/src-tauri/src/commands/console.rs | 106 ++++++ desktop/src-tauri/src/commands/mod.rs | 2 + desktop/src-tauri/src/lib.rs | 1 + desktop/src/app/AppShell.tsx | 9 + desktop/src/app/AppShellOverlays.tsx | 12 + desktop/src/app/useQuakeConsoleShortcut.ts | 45 +++ .../src/features/console/ui/QuakeConsole.tsx | 321 ++++++++++++++++++ desktop/src/shared/api/tauri.ts | 24 ++ 8 files changed, 520 insertions(+) create mode 100644 desktop/src-tauri/src/commands/console.rs create mode 100644 desktop/src/app/useQuakeConsoleShortcut.ts create mode 100644 desktop/src/features/console/ui/QuakeConsole.tsx diff --git a/desktop/src-tauri/src/commands/console.rs b/desktop/src-tauri/src/commands/console.rs new file mode 100644 index 0000000000..07c8881d16 --- /dev/null +++ b/desktop/src-tauri/src/commands/console.rs @@ -0,0 +1,106 @@ +use std::process::Command; + +use nostr::ToBech32; +use serde::Serialize; +use tauri::State; + +use crate::{app_state::AppState, relay::relay_ws_url_with_override}; + +#[derive(Serialize)] +pub struct SproutCliOutput { + exit_code: i32, + stdout: String, + stderr: String, +} + +fn resolve_sprout_binary() -> Result { + if let Ok(exe) = std::env::current_exe() { + if let Some(parent) = exe.parent() { + let bundled = parent.join("sprout"); + if bundled.exists() { + return Ok(bundled.display().to_string()); + } + } + } + + Ok("sprout".to_string()) +} + +fn strip_global_args(args: &[String]) -> &[String] { + if args.len() >= 2 && args[0] == "--format" { + return &args[2..]; + } + + args +} + +fn is_allowed_cli_command(args: &[String]) -> bool { + let args = strip_global_args(args); + if args.len() < 2 { + return false; + } + + matches!( + (args[0].as_str(), args[1].as_str()), + ("channels", "list") + | ("channels", "get") + | ("channels", "members") + | ("messages", "get") + | ("messages", "thread") + | ("messages", "search") + | ("reactions", "get") + | ("users", "get") + | ("users", "presence") + | ("dms", "list") + | ("feed", "get") + | ("workflows", "list") + | ("workflows", "get") + | ("workflows", "runs") + | ("canvas", "get") + | ("social", "event") + | ("social", "notes") + | ("social", "contacts") + | ("repos", "get") + | ("repos", "list") + ) +} + +#[tauri::command] +pub async fn run_sprout_cli( + args: Vec, + state: State<'_, AppState>, +) -> Result { + if args.first().is_some_and(|arg| arg == "sprout") { + return Err("omit the leading `sprout`; the desktop app runs it for you".to_string()); + } + + if !is_allowed_cli_command(&args) { + return Err("only read-only sprout commands are enabled in this prototype".to_string()); + } + + let relay_url = relay_ws_url_with_override(&state); + let private_key = { + let keys = state.keys.lock().map_err(|error| error.to_string())?; + keys.secret_key() + .to_bech32() + .map_err(|error| format!("encode nsec: {error}"))? + }; + let sprout_binary = resolve_sprout_binary()?; + + let output = tauri::async_runtime::spawn_blocking(move || { + Command::new(sprout_binary) + .args(args) + .env("SPROUT_RELAY_URL", relay_url) + .env("SPROUT_PRIVATE_KEY", private_key) + .output() + }) + .await + .map_err(|error| format!("join sprout CLI task: {error}"))? + .map_err(|error| format!("run sprout CLI: {error}"))?; + + Ok(SproutCliOutput { + exit_code: output.status.code().unwrap_or(1), + stdout: String::from_utf8_lossy(&output.stdout).into_owned(), + stderr: String::from_utf8_lossy(&output.stderr).into_owned(), + }) +} diff --git a/desktop/src-tauri/src/commands/mod.rs b/desktop/src-tauri/src/commands/mod.rs index 6cec86f5d7..a159f65d58 100644 --- a/desktop/src-tauri/src/commands/mod.rs +++ b/desktop/src-tauri/src/commands/mod.rs @@ -5,6 +5,7 @@ mod agents; mod canvas; mod channel_templates; mod channels; +mod console; mod dms; mod export_util; mod identity; @@ -29,6 +30,7 @@ pub use agents::*; pub use canvas::*; pub use channel_templates::*; pub use channels::*; +pub use console::*; pub use dms::*; pub use identity::*; pub use identity_archive::*; diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index dd443e3623..dc47763207 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -638,6 +638,7 @@ pub fn run() { start_pairing, confirm_pairing_sas, cancel_pairing, + run_sprout_cli, apply_workspace, get_active_workspace, set_prevent_sleep_active, diff --git a/desktop/src/app/AppShell.tsx b/desktop/src/app/AppShell.tsx index c791acdfe5..f5f8a33cc0 100644 --- a/desktop/src/app/AppShell.tsx +++ b/desktop/src/app/AppShell.tsx @@ -12,6 +12,7 @@ import { AppTopChrome } from "@/app/AppTopChrome"; import { useAppNavigation } from "@/app/navigation/useAppNavigation"; import { useBackForwardControls } from "@/app/navigation/useBackForwardControls"; import { useMarkAsReadShortcuts } from "@/app/useMarkAsReadShortcuts"; +import { useQuakeConsoleShortcut } from "@/app/useQuakeConsoleShortcut"; import { useWebviewZoomShortcuts } from "@/app/useWebviewZoomShortcuts"; import { channelsQueryKey, @@ -169,6 +170,7 @@ export function AppShell() { const [isChannelManagementOpen, setIsChannelManagementOpen] = React.useState(false); + const [isConsoleOpen, setIsConsoleOpen] = React.useState(false); const [searchFocusRequest, setSearchFocusRequest] = React.useState(0); const [browseDialogType, setBrowseDialogType] = React.useState(null); @@ -517,6 +519,11 @@ export function AppShell() { setIsNewDmOpen(true); }, []); + const toggleConsole = React.useCallback(() => { + setIsConsoleOpen((open) => !open); + }, []); + useQuakeConsoleShortcut({ isOpen: isConsoleOpen, onToggle: toggleConsole }); + React.useLayoutEffect(() => { if (settingsOpen) { return; @@ -797,9 +804,11 @@ export function AppShell() { channels={channels} currentPubkey={identityQuery.data?.pubkey} isChannelManagementOpen={isChannelManagementOpen} + isConsoleOpen={isConsoleOpen} onBrowseChannelJoin={handleBrowseChannelJoin} onBrowseDialogOpenChange={handleBrowseDialogOpenChange} onChannelManagementOpenChange={setIsChannelManagementOpen} + onConsoleOpenChange={setIsConsoleOpen} onDeleteActiveChannel={() => { setIsChannelManagementOpen(false); void goHome({ replace: true }); diff --git a/desktop/src/app/AppShellOverlays.tsx b/desktop/src/app/AppShellOverlays.tsx index 44b99a0417..7d52b6d842 100644 --- a/desktop/src/app/AppShellOverlays.tsx +++ b/desktop/src/app/AppShellOverlays.tsx @@ -1,5 +1,6 @@ import * as React from "react"; +import { QuakeConsole } from "@/features/console/ui/QuakeConsole"; import type { Channel } from "@/shared/api/types"; const ChannelBrowserDialog = React.lazy(async () => { @@ -20,9 +21,11 @@ type AppShellOverlaysProps = { channels: Channel[]; currentPubkey?: string; isChannelManagementOpen: boolean; + isConsoleOpen: boolean; onBrowseChannelJoin: (channelId: string) => Promise; onBrowseDialogOpenChange: (open: boolean) => void; onChannelManagementOpenChange: (open: boolean) => void; + onConsoleOpenChange: (open: boolean) => void; onDeleteActiveChannel: () => void; onSelectChannel: (channelId: string) => void; }; @@ -33,9 +36,11 @@ export function AppShellOverlays({ channels, currentPubkey, isChannelManagementOpen, + isConsoleOpen, onBrowseChannelJoin, onBrowseDialogOpenChange, onChannelManagementOpenChange, + onConsoleOpenChange, onDeleteActiveChannel, onSelectChannel, }: AppShellOverlaysProps) { @@ -65,6 +70,13 @@ export function AppShellOverlays({ /> ) : null} + + ); } diff --git a/desktop/src/app/useQuakeConsoleShortcut.ts b/desktop/src/app/useQuakeConsoleShortcut.ts new file mode 100644 index 0000000000..1195363e81 --- /dev/null +++ b/desktop/src/app/useQuakeConsoleShortcut.ts @@ -0,0 +1,45 @@ +import * as React from "react"; + +const TEXT_ENTRY_SELECTOR = 'input, textarea, select, [contenteditable="true"]'; + +function isTextEntryEvent(event: KeyboardEvent) { + return ( + event.target instanceof Element && + event.target.closest(TEXT_ENTRY_SELECTOR) !== null + ); +} + +function isBackquoteKey(event: KeyboardEvent) { + return event.key === "`" || event.code === "Backquote"; +} + +export function useQuakeConsoleShortcut({ + isOpen, + onToggle, +}: { + isOpen: boolean; + onToggle: () => void; +}) { + React.useLayoutEffect(() => { + function handleKeyDown(event: KeyboardEvent) { + if ( + !isBackquoteKey(event) || + event.altKey || + event.ctrlKey || + event.metaKey || + event.shiftKey || + (isTextEntryEvent(event) && !isOpen) + ) { + return; + } + + event.preventDefault(); + onToggle(); + } + + window.addEventListener("keydown", handleKeyDown); + return () => { + window.removeEventListener("keydown", handleKeyDown); + }; + }, [isOpen, onToggle]); +} diff --git a/desktop/src/features/console/ui/QuakeConsole.tsx b/desktop/src/features/console/ui/QuakeConsole.tsx new file mode 100644 index 0000000000..9d2b549bdd --- /dev/null +++ b/desktop/src/features/console/ui/QuakeConsole.tsx @@ -0,0 +1,321 @@ +import * as React from "react"; + +import { runSproutCli } from "@/shared/api/tauri"; +import type { Channel } from "@/shared/api/types"; + +type ConsoleLine = { + id: number; + kind: "input" | "output" | "error" | "hint"; + text: string; +}; + +type QuakeConsoleProps = { + channels: Channel[]; + onOpenChange: (open: boolean) => void; + onOpenChannel: (channelId: string) => void; + open: boolean; +}; + +const INTRO_LINES: ConsoleLine[] = [ + { + id: 1, + kind: "hint", + text: "sprout console", + }, + { + id: 2, + kind: "hint", + text: "Type `help` to see available commands.", + }, + { + id: 3, + kind: "hint", + text: "This is a Sprout-native command surface, not a full shell.", + }, +]; + +function normalizeCommand(command: string) { + return command.trim().replace(/\s+/g, " "); +} + +function findChannel(channels: Channel[], rawName: string) { + const normalizedName = rawName.replace(/^#/, "").trim().toLowerCase(); + return ( + channels.find((channel) => channel.name.toLowerCase() === normalizedName) ?? + channels.find((channel) => + channel.name.toLowerCase().includes(normalizedName), + ) ?? + null + ); +} + +function parseCommandArgs(command: string) { + const matches = command.match(/"([^"]*)"|'([^']*)'|\S+/g) ?? []; + return matches.map((match) => { + if ( + (match.startsWith('"') && match.endsWith('"')) || + (match.startsWith("'") && match.endsWith("'")) + ) { + return match.slice(1, -1); + } + + return match; + }); +} + +function formatCliOutput(text: string) { + return text + .trimEnd() + .split("\n") + .filter((line) => line.length > 0); +} + +function isSproutCliCommand(command: string) { + const args = parseCommandArgs(command); + const first = args[0]?.toLowerCase(); + return ( + first === "sprout" || + first === "--format" || + [ + "canvas", + "channels", + "dms", + "feed", + "messages", + "reactions", + "repos", + "social", + "users", + "workflows", + ].includes(first) + ); +} + +function toSproutCliArgs(command: string) { + const args = parseCommandArgs(command); + return args[0] === "sprout" ? args.slice(1) : args; +} + +export function QuakeConsole({ + channels, + onOpenChange, + onOpenChannel, + open, +}: QuakeConsoleProps) { + const inputRef = React.useRef(null); + const scrollRef = React.useRef(null); + const nextLineIdRef = React.useRef(INTRO_LINES.length + 1); + const [draft, setDraft] = React.useState(""); + const [isRunning, setIsRunning] = React.useState(false); + const [lines, setLines] = React.useState(INTRO_LINES); + + React.useEffect(() => { + if (!open) { + return; + } + + const frame = window.requestAnimationFrame(() => { + inputRef.current?.focus(); + }); + return () => window.cancelAnimationFrame(frame); + }, [open]); + + React.useEffect(() => { + if (!open) { + return; + } + + scrollRef.current?.scrollTo({ + top: scrollRef.current.scrollHeight, + behavior: "smooth", + }); + }); + + const appendLines = React.useCallback( + (nextLines: Omit[]) => { + setLines((current) => [ + ...current, + ...nextLines.map((line) => ({ + ...line, + id: nextLineIdRef.current++, + })), + ]); + }, + [], + ); + + const runCommand = React.useCallback( + async (rawCommand: string) => { + const command = normalizeCommand(rawCommand); + if (command.length === 0) { + return; + } + + if (command === "clear") { + setLines(INTRO_LINES); + return; + } + + const output: Omit[] = [ + { kind: "input", text: `$ ${command}` }, + ]; + const lowerCommand = command.toLowerCase(); + + if (lowerCommand === "help") { + output.push( + { + kind: "output", + text: "help Show commands", + }, + { + kind: "output", + text: "clear Reset console", + }, + { + kind: "output", + text: "sprout channels list Run the real Sprout CLI", + }, + { + kind: "output", + text: 'sprout messages search --query "release"', + }, + { + kind: "output", + text: "open #channel App-native channel navigation", + }, + ); + } else if (lowerCommand.startsWith("open ")) { + const channel = findChannel(channels, command.slice(5)); + if (!channel) { + output.push({ + kind: "error", + text: `No channel matched "${command.slice(5)}".`, + }); + } else { + output.push({ kind: "output", text: `Opening #${channel.name}...` }); + onOpenChannel(channel.id); + onOpenChange(false); + } + } else if (isSproutCliCommand(command)) { + appendLines(output); + setIsRunning(true); + try { + const result = await runSproutCli(toSproutCliArgs(command)); + const stdoutLines = formatCliOutput(result.stdout); + const stderrLines = formatCliOutput(result.stderr); + + appendLines([ + ...stdoutLines.map((text) => ({ kind: "output" as const, text })), + ...stderrLines.map((text) => ({ + kind: + result.exitCode === 0 ? ("hint" as const) : ("error" as const), + text, + })), + ...(result.exitCode === 0 + ? [] + : [ + { + kind: "error" as const, + text: `sprout exited with code ${result.exitCode}`, + }, + ]), + ]); + } catch (error) { + appendLines([ + { + kind: "error", + text: error instanceof Error ? error.message : String(error), + }, + ]); + } finally { + setIsRunning(false); + } + return; + } else { + output.push({ + kind: "error", + text: `Unknown command: ${command}. Type \`help\` for options.`, + }); + } + + appendLines(output); + }, + [appendLines, channels, onOpenChange, onOpenChannel], + ); + + if (!open) { + return null; + } + + return ( +
+
+
inputRef.current?.focus()} + role="document" + > +
+ {lines.map((line) => ( +
+ {line.text} +
+ ))} + +
{ + event.preventDefault(); + void runCommand(draft); + setDraft(""); + }} + > + + $ + setDraft(event.target.value)} + onKeyDown={(event) => { + if (event.key === "Escape") { + event.preventDefault(); + onOpenChange(false); + } + }} + placeholder="" + ref={inputRef} + value={draft} + /> + {isRunning ? ( + running... + ) : null} +
+
+
+
+ ); +} diff --git a/desktop/src/shared/api/tauri.ts b/desktop/src/shared/api/tauri.ts index f67c4dfbf7..d89ae90f68 100644 --- a/desktop/src/shared/api/tauri.ts +++ b/desktop/src/shared/api/tauri.ts @@ -555,6 +555,30 @@ export function getRelayHttpUrl(): Promise { return invokeTauri("get_relay_http_url"); } +export type SproutCliOutput = { + exitCode: number; + stderr: string; + stdout: string; +}; + +type RawSproutCliOutput = { + exit_code: number; + stderr: string; + stdout: string; +}; + +export async function runSproutCli(args: string[]): Promise { + const output = await invokeTauri("run_sprout_cli", { + args, + }); + + return { + exitCode: output.exit_code, + stderr: output.stderr, + stdout: output.stdout, + }; +} + export async function getChannels(): Promise { const channels = await invokeTauri("get_channels"); return channels.map(fromRawChannel);