huskies: merge 582_story_bot_configuration_page

This commit is contained in:
dave
2026-04-15 17:33:56 +00:00
parent d80fc143c2
commit 2246278845
6 changed files with 495 additions and 2 deletions
+43
View File
@@ -0,0 +1,43 @@
export interface BotConfig {
transport: string | null;
enabled: boolean | null;
homeserver: string | null;
username: string | null;
password: string | null;
room_ids: string[] | null;
slack_bot_token: string | null;
slack_signing_secret: string | null;
slack_channel_ids: string[] | null;
}
const DEFAULT_API_BASE = "/api";
async function requestJson<T>(
path: string,
options: RequestInit = {},
baseUrl = DEFAULT_API_BASE,
): Promise<T> {
const res = await fetch(`${baseUrl}${path}`, {
headers: { "Content-Type": "application/json", ...(options.headers ?? {}) },
...options,
});
if (!res.ok) {
const text = await res.text();
throw new Error(text || `Request failed (${res.status})`);
}
return res.json() as Promise<T>;
}
export const botConfigApi = {
getConfig(baseUrl?: string): Promise<BotConfig> {
return requestJson<BotConfig>("/bot/config", {}, baseUrl);
},
saveConfig(config: BotConfig, baseUrl?: string): Promise<BotConfig> {
return requestJson<BotConfig>(
"/bot/config",
{ method: "PUT", body: JSON.stringify(config) },
baseUrl,
);
},
};
+344
View File
@@ -0,0 +1,344 @@
import * as React from "react";
import type { BotConfig } from "../api/bot_config";
import { botConfigApi } from "../api/bot_config";
const { useState, useEffect } = React;
interface BotConfigPageProps {
onBack: () => void;
}
const fieldStyle: React.CSSProperties = {
display: "flex",
flexDirection: "column",
gap: "4px",
};
const labelStyle: React.CSSProperties = {
fontSize: "0.8em",
color: "#aaa",
fontWeight: 500,
};
const inputStyle: React.CSSProperties = {
padding: "8px 10px",
borderRadius: "6px",
border: "1px solid #333",
background: "#1e1e1e",
color: "#ececec",
fontSize: "0.9em",
fontFamily: "monospace",
outline: "none",
};
const sectionStyle: React.CSSProperties = {
background: "#1e1e1e",
border: "1px solid #333",
borderRadius: "8px",
padding: "20px",
display: "flex",
flexDirection: "column",
gap: "14px",
};
const sectionTitleStyle: React.CSSProperties = {
fontSize: "0.85em",
fontWeight: 600,
color: "#aaa",
textTransform: "uppercase",
letterSpacing: "0.06em",
marginBottom: "2px",
};
function Field({
label,
value,
onChange,
placeholder,
type = "text",
}: {
label: string;
value: string;
onChange: (v: string) => void;
placeholder?: string;
type?: string;
}) {
return (
<div style={fieldStyle}>
<label style={labelStyle}>{label}</label>
<input
type={type}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
style={inputStyle}
autoComplete="off"
/>
</div>
);
}
function ListField({
label,
value,
onChange,
placeholder,
}: {
label: string;
value: string[];
onChange: (v: string[]) => void;
placeholder?: string;
}) {
return (
<div style={fieldStyle}>
<label style={labelStyle}>{label} (one per line)</label>
<textarea
value={value.join("\n")}
onChange={(e) =>
onChange(e.target.value.split("\n").filter((s) => s.trim()))
}
placeholder={placeholder}
rows={3}
style={{ ...inputStyle, resize: "vertical" }}
/>
</div>
);
}
/// Bot configuration page — form for Matrix and Slack credentials.
export function BotConfigPage({ onBack }: BotConfigPageProps) {
const [transport, setTransport] = useState<"matrix" | "slack">("matrix");
const [enabled, setEnabled] = useState(false);
const [homeserver, setHomeserver] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [roomIds, setRoomIds] = useState<string[]>([]);
const [slackBotToken, setSlackBotToken] = useState("");
const [slackSigningSecret, setSlackSigningSecret] = useState("");
const [slackChannelIds, setSlackChannelIds] = useState<string[]>([]);
const [status, setStatus] = useState<"idle" | "saving" | "saved" | "error">(
"idle",
);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
useEffect(() => {
botConfigApi
.getConfig()
.then((cfg) => {
if (cfg.transport === "slack") setTransport("slack");
setEnabled(cfg.enabled ?? false);
setHomeserver(cfg.homeserver ?? "");
setUsername(cfg.username ?? "");
setPassword(cfg.password ?? "");
setRoomIds(cfg.room_ids ?? []);
setSlackBotToken(cfg.slack_bot_token ?? "");
setSlackSigningSecret(cfg.slack_signing_secret ?? "");
setSlackChannelIds(cfg.slack_channel_ids ?? []);
})
.catch(() => {});
}, []);
function buildConfig(): BotConfig {
return {
transport,
enabled,
homeserver: homeserver || null,
username: username || null,
password: password || null,
room_ids: roomIds.length > 0 ? roomIds : null,
slack_bot_token: slackBotToken || null,
slack_signing_secret: slackSigningSecret || null,
slack_channel_ids: slackChannelIds.length > 0 ? slackChannelIds : null,
};
}
async function handleSave() {
setStatus("saving");
setErrorMsg(null);
try {
await botConfigApi.saveConfig(buildConfig());
setStatus("saved");
setTimeout(() => setStatus("idle"), 2000);
} catch (e) {
setStatus("error");
setErrorMsg(e instanceof Error ? e.message : "Save failed");
}
}
return (
<div
style={{
display: "flex",
flexDirection: "column",
height: "100%",
backgroundColor: "#171717",
color: "#ececec",
overflow: "auto",
}}
>
<div
style={{
padding: "12px 24px",
borderBottom: "1px solid #333",
display: "flex",
alignItems: "center",
gap: "16px",
background: "#171717",
flexShrink: 0,
}}
>
<button
type="button"
onClick={onBack}
style={{
background: "transparent",
border: "none",
cursor: "pointer",
color: "#888",
fontSize: "0.9em",
padding: "4px 8px",
borderRadius: "4px",
}}
>
Back
</button>
<span style={{ fontWeight: 700, fontSize: "1em" }}>
Bot Configuration
</span>
</div>
<div
style={{
flex: 1,
padding: "24px",
display: "flex",
flexDirection: "column",
gap: "20px",
maxWidth: "600px",
}}
>
<div style={sectionStyle}>
<div style={sectionTitleStyle}>General</div>
<div style={fieldStyle}>
<label style={labelStyle}>Transport</label>
<select
value={transport}
onChange={(e) =>
setTransport(e.target.value as "matrix" | "slack")
}
style={{ ...inputStyle, cursor: "pointer" }}
>
<option value="matrix">Matrix</option>
<option value="slack">Slack</option>
</select>
</div>
<label
style={{
display: "flex",
alignItems: "center",
gap: "8px",
cursor: "pointer",
fontSize: "0.9em",
color: "#ccc",
}}
>
<input
type="checkbox"
checked={enabled}
onChange={(e) => setEnabled(e.target.checked)}
/>
Enabled
</label>
</div>
{transport === "matrix" && (
<div style={sectionStyle}>
<div style={sectionTitleStyle}>Matrix Credentials</div>
<Field
label="Homeserver"
value={homeserver}
onChange={setHomeserver}
placeholder="https://matrix.example.com"
/>
<Field
label="Username"
value={username}
onChange={setUsername}
placeholder="@botname:example.com"
/>
<Field
label="Password"
value={password}
onChange={setPassword}
placeholder="bot password"
type="password"
/>
<ListField
label="Room IDs"
value={roomIds}
onChange={setRoomIds}
placeholder="!roomid:example.com"
/>
</div>
)}
{transport === "slack" && (
<div style={sectionStyle}>
<div style={sectionTitleStyle}>Slack Credentials</div>
<Field
label="Bot Token"
value={slackBotToken}
onChange={setSlackBotToken}
placeholder="xoxb-..."
/>
<Field
label="Signing Secret"
value={slackSigningSecret}
onChange={setSlackSigningSecret}
placeholder="signing secret"
type="password"
/>
<ListField
label="Channel IDs"
value={slackChannelIds}
onChange={setSlackChannelIds}
placeholder="C01ABCDEF"
/>
</div>
)}
<div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
<button
type="button"
onClick={handleSave}
disabled={status === "saving"}
style={{
padding: "8px 24px",
borderRadius: "6px",
border: "none",
background: status === "saved" ? "#1a5c2a" : "#2563eb",
color: "#fff",
cursor: status === "saving" ? "not-allowed" : "pointer",
fontSize: "0.9em",
fontWeight: 600,
opacity: status === "saving" ? 0.7 : 1,
}}
>
{status === "saving"
? "Saving..."
: status === "saved"
? "Saved!"
: "Save"}
</button>
{status === "error" && errorMsg && (
<span style={{ color: "#f08080", fontSize: "0.85em" }}>
{errorMsg}
</span>
)}
</div>
</div>
</div>
);
}
+8 -1
View File
@@ -8,6 +8,7 @@ import { useChatSend } from "../hooks/useChatSend";
import { useChatWebSocket } from "../hooks/useChatWebSocket"; import { useChatWebSocket } from "../hooks/useChatWebSocket";
import { estimateTokens, getContextWindowSize } from "../utils/chatUtils"; import { estimateTokens, getContextWindowSize } from "../utils/chatUtils";
import { ApiKeyDialog } from "./ApiKeyDialog"; import { ApiKeyDialog } from "./ApiKeyDialog";
import { BotConfigPage } from "./BotConfigPage";
import { ChatHeader } from "./ChatHeader"; import { ChatHeader } from "./ChatHeader";
import type { ChatInputHandle } from "./ChatInput"; import type { ChatInputHandle } from "./ChatInput";
import { ChatInput } from "./ChatInput"; import { ChatInput } from "./ChatInput";
@@ -61,6 +62,7 @@ export function Chat({
null, null,
); );
const [showHelp, setShowHelp] = useState(false); const [showHelp, setShowHelp] = useState(false);
const [view, setView] = useState<"chat" | "bot-config">("chat");
const [queuedMessages, setQueuedMessages] = useState< const [queuedMessages, setQueuedMessages] = useState<
{ id: string; text: string }[] { id: string; text: string }[]
>([]); >([]);
@@ -373,12 +375,17 @@ export function Chat({
onToggleTools={setEnableTools} onToggleTools={setEnableTools}
wsConnected={wsConnected} wsConnected={wsConnected}
oauthStatus={oauthStatus} oauthStatus={oauthStatus}
onShowBotConfig={() => setView("bot-config")}
/> />
{view === "bot-config" && (
<BotConfigPage onBack={() => setView("chat")} />
)}
<div <div
data-testid="chat-content-area" data-testid="chat-content-area"
style={{ style={{
display: "flex", display: view === "bot-config" ? "none" : "flex",
flex: 1, flex: 1,
minHeight: 0, minHeight: 0,
flexDirection: isNarrowScreen ? "column" : "row", flexDirection: isNarrowScreen ? "column" : "row",
+39
View File
@@ -34,6 +34,7 @@ interface ChatHeaderProps {
onToggleTools: (enabled: boolean) => void; onToggleTools: (enabled: boolean) => void;
wsConnected: boolean; wsConnected: boolean;
oauthStatus?: OAuthStatus | null; oauthStatus?: OAuthStatus | null;
onShowBotConfig?: () => void;
} }
const getContextEmoji = (percentage: number): string => { const getContextEmoji = (percentage: number): string => {
@@ -58,6 +59,7 @@ export function ChatHeader({
onToggleTools, onToggleTools,
wsConnected, wsConnected,
oauthStatus = null, oauthStatus = null,
onShowBotConfig,
}: ChatHeaderProps) { }: ChatHeaderProps) {
const hasModelOptions = availableModels.length > 0 || claudeModels.length > 0; const hasModelOptions = availableModels.length > 0 || claudeModels.length > 0;
const [showConfirm, setShowConfirm] = useState(false); const [showConfirm, setShowConfirm] = useState(false);
@@ -513,6 +515,43 @@ export function ChatHeader({
🔄 New Session 🔄 New Session
</button> </button>
{onShowBotConfig && (
<button
type="button"
onClick={onShowBotConfig}
title="Configure bot credentials"
style={{
padding: "6px 12px",
borderRadius: "99px",
border: "none",
fontSize: "0.85em",
backgroundColor: "#2f2f2f",
color: "#888",
cursor: "pointer",
outline: "none",
transition: "all 0.2s",
}}
onMouseOver={(e) => {
e.currentTarget.style.backgroundColor = "#3f3f3f";
e.currentTarget.style.color = "#ccc";
}}
onMouseOut={(e) => {
e.currentTarget.style.backgroundColor = "#2f2f2f";
e.currentTarget.style.color = "#888";
}}
onFocus={(e) => {
e.currentTarget.style.backgroundColor = "#3f3f3f";
e.currentTarget.style.color = "#ccc";
}}
onBlur={(e) => {
e.currentTarget.style.backgroundColor = "#2f2f2f";
e.currentTarget.style.color = "#888";
}}
>
Bot
</button>
)}
{hasModelOptions ? ( {hasModelOptions ? (
<select <select
value={model} value={model}
+55
View File
@@ -0,0 +1,55 @@
//! Bot configuration endpoints — GET/PUT for .huskies/bot.toml credentials.
use crate::http::context::{AppContext, OpenApiResult, bad_request};
use poem_openapi::{Object, OpenApi, Tags, payload::Json};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Tags)]
enum BotConfigTags {
BotConfig,
}
#[derive(Object, Serialize, Deserialize, Default)]
struct BotConfigPayload {
pub transport: Option<String>,
pub enabled: Option<bool>,
pub homeserver: Option<String>,
pub username: Option<String>,
pub password: Option<String>,
pub room_ids: Option<Vec<String>>,
pub slack_bot_token: Option<String>,
pub slack_signing_secret: Option<String>,
pub slack_channel_ids: Option<Vec<String>>,
}
pub struct BotConfigApi {
pub ctx: Arc<AppContext>,
}
#[OpenApi(tag = "BotConfigTags::BotConfig")]
impl BotConfigApi {
/// Read current bot credentials from .huskies/bot.toml.
#[oai(path = "/bot/config", method = "get")]
async fn get_config(&self) -> OpenApiResult<Json<BotConfigPayload>> {
let root = self.ctx.state.get_project_root().map_err(bad_request)?;
let path = root.join(".huskies").join("bot.toml");
let config: BotConfigPayload = std::fs::read_to_string(&path)
.ok()
.and_then(|s| toml::from_str(&s).ok())
.unwrap_or_default();
Ok(Json(config))
}
/// Persist bot credentials to .huskies/bot.toml.
#[oai(path = "/bot/config", method = "put")]
async fn put_config(
&self,
payload: Json<BotConfigPayload>,
) -> OpenApiResult<Json<BotConfigPayload>> {
let root = self.ctx.state.get_project_root().map_err(bad_request)?;
let path = root.join(".huskies").join("bot.toml");
let content = toml::to_string(&payload.0).map_err(|e| bad_request(e.to_string()))?;
std::fs::write(&path, content).map_err(|e| bad_request(e.to_string()))?;
Ok(payload)
}
}
+6 -1
View File
@@ -4,6 +4,7 @@ pub mod agents_sse;
pub mod anthropic; pub mod anthropic;
pub mod assets; pub mod assets;
pub mod bot_command; pub mod bot_command;
pub mod bot_config;
pub mod chat; pub mod chat;
pub mod context; pub mod context;
pub mod health; pub mod health;
@@ -23,6 +24,7 @@ pub mod ws;
use agents::AgentsApi; use agents::AgentsApi;
use anthropic::AnthropicApi; use anthropic::AnthropicApi;
use bot_command::BotCommandApi; use bot_command::BotCommandApi;
use bot_config::BotConfigApi;
use chat::ChatApi; use chat::ChatApi;
use context::AppContext; use context::AppContext;
use health::HealthApi; use health::HealthApi;
@@ -196,6 +198,7 @@ type ApiTuple = (
HealthApi, HealthApi,
BotCommandApi, BotCommandApi,
wizard::WizardApi, wizard::WizardApi,
BotConfigApi,
); );
type ApiService = OpenApiService<ApiTuple, ()>; type ApiService = OpenApiService<ApiTuple, ()>;
@@ -213,6 +216,7 @@ pub fn build_openapi_service(ctx: Arc<AppContext>) -> (ApiService, ApiService) {
HealthApi, HealthApi,
BotCommandApi { ctx: ctx.clone() }, BotCommandApi { ctx: ctx.clone() },
wizard::WizardApi { ctx: ctx.clone() }, wizard::WizardApi { ctx: ctx.clone() },
BotConfigApi { ctx: ctx.clone() },
); );
let api_service = let api_service =
@@ -228,7 +232,8 @@ pub fn build_openapi_service(ctx: Arc<AppContext>) -> (ApiService, ApiService) {
SettingsApi { ctx: ctx.clone() }, SettingsApi { ctx: ctx.clone() },
HealthApi, HealthApi,
BotCommandApi { ctx: ctx.clone() }, BotCommandApi { ctx: ctx.clone() },
wizard::WizardApi { ctx }, wizard::WizardApi { ctx: ctx.clone() },
BotConfigApi { ctx },
); );
let docs_service = let docs_service =