mirror of
https://github.com/block/buzz.git
synced 2026-11-26 11:12:22 +00:00
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 <cursoragent@cursor.com>
This commit is contained in:
106
desktop/src-tauri/src/commands/console.rs
Normal file
106
desktop/src-tauri/src/commands/console.rs
Normal file
@@ -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<String, String> {
|
||||
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<String>,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<SproutCliOutput, String> {
|
||||
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(),
|
||||
})
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<BrowseDialogType>(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 });
|
||||
|
||||
@@ -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<void>;
|
||||
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({
|
||||
/>
|
||||
</React.Suspense>
|
||||
) : null}
|
||||
|
||||
<QuakeConsole
|
||||
channels={channels}
|
||||
onOpenChange={onConsoleOpenChange}
|
||||
onOpenChannel={onSelectChannel}
|
||||
open={isConsoleOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
45
desktop/src/app/useQuakeConsoleShortcut.ts
Normal file
45
desktop/src/app/useQuakeConsoleShortcut.ts
Normal file
@@ -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]);
|
||||
}
|
||||
321
desktop/src/features/console/ui/QuakeConsole.tsx
Normal file
321
desktop/src/features/console/ui/QuakeConsole.tsx
Normal file
@@ -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<HTMLInputElement>(null);
|
||||
const scrollRef = React.useRef<HTMLDivElement>(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<ConsoleLine[]>(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<ConsoleLine, "id">[]) => {
|
||||
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<ConsoleLine, "id">[] = [
|
||||
{ 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 (
|
||||
<div
|
||||
aria-label="Sprout console"
|
||||
aria-modal="true"
|
||||
className="fixed inset-0 z-[220] bg-black/20 backdrop-blur-3xl supports-[backdrop-filter]:bg-black/10"
|
||||
data-testid="quake-console"
|
||||
role="dialog"
|
||||
>
|
||||
<div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,rgba(0,0,0,0.16)_48%,rgba(0,0,0,0.44)_100%),linear-gradient(180deg,rgba(0,0,0,0.06),rgba(0,0,0,0.24))]" />
|
||||
<div
|
||||
className="relative flex h-full w-full flex-col overflow-hidden bg-black/18 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.16)] backdrop-blur-3xl supports-[backdrop-filter]:bg-black/12"
|
||||
onMouseDown={() => inputRef.current?.focus()}
|
||||
role="document"
|
||||
>
|
||||
<div
|
||||
className="min-h-0 flex-1 overflow-y-auto px-8 pb-8 pt-14 font-mono text-[13px] leading-[1.45] text-zinc-100"
|
||||
ref={scrollRef}
|
||||
>
|
||||
{lines.map((line) => (
|
||||
<div
|
||||
className={
|
||||
line.kind === "input"
|
||||
? "text-zinc-50"
|
||||
: line.kind === "error"
|
||||
? "text-red-300"
|
||||
: line.kind === "hint"
|
||||
? "text-zinc-300"
|
||||
: "text-zinc-100"
|
||||
}
|
||||
key={line.id}
|
||||
>
|
||||
{line.text}
|
||||
</div>
|
||||
))}
|
||||
|
||||
<form
|
||||
className="mt-1 flex items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void runCommand(draft);
|
||||
setDraft("");
|
||||
}}
|
||||
>
|
||||
<label className="sr-only" htmlFor="quake-console-command">
|
||||
Console command
|
||||
</label>
|
||||
<span className="shrink-0 text-zinc-50">$</span>
|
||||
<input
|
||||
id="quake-console-command"
|
||||
aria-label="Console command"
|
||||
className="min-w-0 flex-1 bg-transparent text-zinc-50 caret-zinc-50 outline-none placeholder:text-zinc-600"
|
||||
disabled={isRunning}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
onOpenChange(false);
|
||||
}
|
||||
}}
|
||||
placeholder=""
|
||||
ref={inputRef}
|
||||
value={draft}
|
||||
/>
|
||||
{isRunning ? (
|
||||
<span className="shrink-0 text-zinc-500">running...</span>
|
||||
) : null}
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -555,6 +555,30 @@ export function getRelayHttpUrl(): Promise<string> {
|
||||
return invokeTauri<string>("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<SproutCliOutput> {
|
||||
const output = await invokeTauri<RawSproutCliOutput>("run_sprout_cli", {
|
||||
args,
|
||||
});
|
||||
|
||||
return {
|
||||
exitCode: output.exit_code,
|
||||
stderr: output.stderr,
|
||||
stdout: output.stdout,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getChannels(): Promise<Channel[]> {
|
||||
const channels = await invokeTauri<RawChannel[]>("get_channels");
|
||||
return channels.map(fromRawChannel);
|
||||
|
||||
Reference in New Issue
Block a user