extracted chat component to widgets

This commit is contained in:
2026-02-17 19:52:41 +00:00
parent 21213c281d
commit 74e98e95e1
37 changed files with 44 additions and 327 deletions
@@ -1,254 +0,0 @@
import type { KeyboardEvent } from 'react';
import { useRef, useEffect, useState } from 'react';
import { toast } from 'sonner';
import { useClient } from 'hooks/useClient';
import type { ModelOption } from '@/state/useModels';
import type { useClaude } from './useClaude';
import { MessageList } from './MessageList';
import { InputArea } from './InputArea';
export type Attachment =
| { type: 'webpage'; url: string; title: string; content: string; attachmentId: string; loading?: boolean }
| { type: 'image'; filename: string; dataUrl: string; attachmentId: string; loading?: boolean };
type EmbeddableChatProps = {
chat: ReturnType<typeof useClaude>;
provider?: 'claude' | 'opencode';
availableModels?: ModelOption[];
onProviderChange?: (provider: 'claude' | 'opencode') => void;
onBeforeSend?: (text: string) => boolean | Promise<boolean>;
commandFeedback?: string | null;
defaultInput?: string;
className?: string;
cwd?: { root?: string; path: string };
autoSend?: boolean;
};
export const EmbeddableChat = ({
chat,
provider = 'claude',
availableModels = [],
onProviderChange,
onBeforeSend,
commandFeedback = null,
defaultInput = '',
className,
cwd,
autoSend = false,
}: EmbeddableChatProps) => {
const {
messages,
streamingText,
isConnected,
isGenerating,
sessionId,
model,
selectedModel,
setSelectedModel,
sendPrompt,
stopGeneration,
} = chat;
const client = useClient();
const [input, setInput] = useState(defaultInput);
const [attachments, setAttachments] = useState<Attachment[]>([]);
const [showJumpToBottom, setShowJumpToBottom] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const scrollViewportRef = useRef<HTMLDivElement | null>(null);
const bottomRef = useRef<HTMLDivElement | null>(null);
const userScrolledRef = useRef(false);
const handleAttachWebpage = async (url: string) => {
const idx = attachments.length;
setAttachments((prev) => [
...prev,
{ type: 'webpage', url, title: '', content: '', attachmentId: '', loading: true },
]);
try {
const res = await client.post<{ url: string; title: string; content: string; attachmentId: string }>('/scrape', {
url,
sessionId: sessionId ?? undefined,
provider,
});
setAttachments((prev) =>
prev.map((a, i) =>
i === idx
? { ...a, title: res.title, content: res.content, attachmentId: res.attachmentId, loading: false }
: a,
),
);
} catch {
setAttachments((prev) => prev.filter((_, i) => i !== idx));
toast.error('Failed to scrape webpage');
}
};
const handleAttachImage = async (file: File) => {
const idx = attachments.length;
setAttachments((prev) => [
...prev,
{ type: 'image', filename: file.name, dataUrl: '', attachmentId: '', loading: true },
]);
try {
const formData = new FormData();
formData.append('file', file);
if (sessionId) formData.append('sessionId', sessionId);
formData.append('provider', provider);
const res = await client.post<{ filename: string; dataUrl: string; attachmentId: string }>('/upload', formData);
setAttachments((prev) =>
prev.map((a, i) =>
i === idx ? { ...a, dataUrl: res.dataUrl, attachmentId: res.attachmentId, loading: false } : a,
),
);
} catch {
setAttachments((prev) => prev.filter((_, i) => i !== idx));
toast.error('Failed to upload image');
}
};
const handleRemoveAttachment = (index: number) => {
setAttachments((prev) => prev.filter((_, i) => i !== index));
};
const handleSend = async () => {
const text = input.trim();
if (!text || isGenerating) return;
if (onBeforeSend) {
const handled = await onBeforeSend(text);
if (handled) {
setInput('');
if (textareaRef.current) textareaRef.current.style.height = 'auto';
return;
}
}
// Prepend attachment content to the prompt
let prompt = text;
const ids: string[] = [];
const images: { filename: string; dataUrl: string }[] = [];
for (const a of attachments) {
if (a.loading) continue;
if (a.type === 'webpage' && a.content) {
prompt = `[Attached webpage: ${a.url}]\n${a.content}\n\n${prompt}`;
} else if (a.type === 'image' && a.dataUrl) {
prompt = `[Attached image: ${a.filename}]\n\n${prompt}`;
images.push({ filename: a.filename, dataUrl: a.dataUrl });
}
ids.push(a.attachmentId);
}
// On first message (no sessionId), include attachmentIds so server can relocate tmp files
const cwdForFirst = !sessionId ? cwd : undefined;
sendPrompt(
prompt,
!sessionId && ids.length > 0 ? ids : undefined,
images.length > 0 ? images : undefined,
cwdForFirst,
);
setAttachments([]);
setInput('');
userScrolledRef.current = false;
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
};
const handleKeyDown = (ev: KeyboardEvent<HTMLTextAreaElement>) => {
if (ev.key === 'Enter' && !ev.shiftKey) {
ev.preventDefault();
handleSend();
}
};
// Auto-resize textarea
useEffect(() => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 200) + 'px';
}, [input]);
// Auto-scroll to bottom on new messages
useEffect(() => {
if (!userScrolledRef.current) {
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}
}, [messages, streamingText]);
// Detect user scrolling up
useEffect(() => {
const viewport = scrollViewportRef.current;
if (!viewport) return;
const handleScroll = () => {
const { scrollTop, scrollHeight, clientHeight } = viewport;
const atBottom = scrollHeight - scrollTop - clientHeight < 60;
userScrolledRef.current = !atBottom;
setShowJumpToBottom(!atBottom);
};
viewport.addEventListener('scroll', handleScroll);
return () => viewport.removeEventListener('scroll', handleScroll);
}, []);
const jumpToBottom = () => {
userScrolledRef.current = false;
bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
};
// Focus textarea on mount
useEffect(() => {
textareaRef.current?.focus();
}, []);
// Auto-send first message when autoSend is enabled
const autoSentRef = useRef(false);
useEffect(() => {
if (autoSend && isConnected && !messages.length && input.trim() && !autoSentRef.current) {
autoSentRef.current = true;
handleSend();
}
}, [autoSend, isConnected, messages.length, input]);
return (
<div className={`flex flex-col ${className ?? ''}`}>
<MessageList
messages={messages}
streamingText={streamingText}
isGenerating={isGenerating}
showJumpToBottom={showJumpToBottom}
onJumpToBottom={jumpToBottom}
onQuestionAnswer={(text) => sendPrompt(text)}
scrollViewportRef={scrollViewportRef}
bottomRef={bottomRef}
/>
<InputArea
input={input}
onInputChange={setInput}
onKeyDown={handleKeyDown}
onSend={handleSend}
onStop={stopGeneration}
isGenerating={isGenerating}
isConnected={isConnected}
commandFeedback={commandFeedback}
textareaRef={textareaRef}
provider={provider}
messages={messages}
onProviderChange={onProviderChange}
availableModels={availableModels}
selectedModel={selectedModel}
onModelChange={setSelectedModel}
model={model}
attachments={attachments}
onAttachWebpage={handleAttachWebpage}
onAttachImage={handleAttachImage}
onRemoveAttachment={handleRemoveAttachment}
/>
</div>
);
};
@@ -1,230 +0,0 @@
import type { KeyboardEvent, RefObject } from 'react';
import { useState, useRef } from 'react';
import { FileText, Image, Link, Loader2, Paperclip, Send, Square, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import type { ModelOption } from '@/state/useModels';
import type { ChatMessage } from './types';
import type { Attachment } from './EmbeddableChat';
import { Settings } from './Settings';
type InputAreaProps = {
input: string;
onInputChange: (value: string) => void;
onKeyDown: (ev: KeyboardEvent<HTMLTextAreaElement>) => void;
onSend: () => void;
onStop: () => void;
isGenerating: boolean;
isConnected: boolean;
commandFeedback: string | null;
textareaRef: RefObject<HTMLTextAreaElement | null>;
provider: 'claude' | 'opencode';
messages: ChatMessage[];
onProviderChange?: (provider: 'claude' | 'opencode') => void;
availableModels: ModelOption[];
selectedModel: string | null;
onModelChange: (modelId: string) => void;
model: string | null;
attachments: Attachment[];
onAttachWebpage: (url: string) => void;
onAttachImage: (file: File) => void;
onRemoveAttachment: (index: number) => void;
};
export const InputArea = ({
input,
onInputChange,
onKeyDown,
onSend,
onStop,
isGenerating,
isConnected,
commandFeedback,
textareaRef,
provider,
messages,
onProviderChange,
availableModels,
selectedModel,
onModelChange,
model,
attachments,
onAttachWebpage,
onAttachImage,
onRemoveAttachment,
}: InputAreaProps) => {
const [urlDialogOpen, setUrlDialogOpen] = useState(false);
const [urlInput, setUrlInput] = useState('');
const imageInputRef = useRef<HTMLInputElement>(null);
const handleUrlSubmit = () => {
const url = urlInput.trim();
if (!url) return;
onAttachWebpage(url);
setUrlInput('');
setUrlDialogOpen(false);
};
return (
<div className="shrink-0 border-t border-duck-dark/10 bg-white/60 p-3">
{commandFeedback && (
<div className="mb-2 px-3 py-1.5 text-xs text-duck-teal bg-duck-teal/10 rounded-md">{commandFeedback}</div>
)}
{attachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1.5">
{attachments.map((a, i) => (
<span
key={i}
className="relative inline-flex items-center gap-1 px-2 py-1 text-xs bg-duck-teal/10 text-duck-teal rounded-md max-w-[240px] group"
>
{a.loading ? (
<Loader2 className="h-3 w-3 shrink-0 animate-spin" />
) : a.type === 'image' && a.dataUrl ? (
<img src={a.dataUrl} alt={a.filename} className="h-8 w-8 shrink-0 rounded object-cover" />
) : a.type === 'image' ? (
<Image className="h-3 w-3 shrink-0" />
) : (
<Link className="h-3 w-3 shrink-0" />
)}
<span className="truncate">{a.type === 'image' ? a.filename : a.loading ? a.url : a.title || a.url}</span>
<button
type="button"
onClick={() => onRemoveAttachment(i)}
className="shrink-0 hover:text-duck-dark cursor-pointer"
>
<X className="h-3 w-3" />
</button>
</span>
))}
</div>
)}
<div className="flex items-end gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
className="shrink-0 h-9 w-9 flex items-center justify-center rounded-lg text-duck-dark/40 hover:text-duck-dark/70 hover:bg-duck-dark/5 transition-colors cursor-pointer"
>
<Paperclip className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" className="z-[800]">
<DropdownMenuItem className="cursor-pointer" onSelect={() => imageInputRef.current?.click()}>
<Image className="mr-2 h-4 w-4" />
Image
</DropdownMenuItem>
<DropdownMenuItem className="cursor-pointer">
<FileText className="mr-2 h-4 w-4" />
Text File
</DropdownMenuItem>
<DropdownMenuItem className="cursor-pointer">
<FileText className="mr-2 h-4 w-4" />
PDF
</DropdownMenuItem>
<DropdownMenuItem className="cursor-pointer" onSelect={() => setUrlDialogOpen(true)}>
<Link className="mr-2 h-4 w-4" />
Webpage URL
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<input
ref={imageInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={(ev) => {
const file = ev.target.files?.[0];
if (file) onAttachImage(file);
ev.target.value = '';
}}
/>
<textarea
ref={textareaRef}
value={input}
onChange={(ev) => onInputChange(ev.target.value)}
onKeyDown={onKeyDown}
onPaste={(ev) => {
const items = ev.clipboardData?.items;
if (!items) return;
for (const item of Array.from(items)) {
if (item.type.startsWith('image/')) {
ev.preventDefault();
const file = item.getAsFile();
if (file) onAttachImage(file);
return;
}
}
}}
placeholder="Type a message..."
rows={1}
className="flex-1 resize-none rounded-lg border border-duck-dark/20 bg-white/80 px-3 py-2 text-base md:text-sm text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:ring-2 focus:ring-duck-teal/30 focus:border-duck-teal/50"
/>
{isGenerating ? (
<Button onClick={onStop} variant="destructive" size="icon" className="shrink-0 h-9 w-9 cursor-pointer">
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={onSend}
disabled={!input.trim() || !isConnected}
size="icon"
className="shrink-0 h-9 w-9 bg-duck-teal hover:bg-duck-teal/90 cursor-pointer disabled:opacity-40"
>
<Send className="h-4 w-4" />
</Button>
)}
</div>
<Settings
provider={provider}
messages={messages}
onProviderChange={onProviderChange}
availableModels={availableModels}
selectedModel={selectedModel}
onModelChange={onModelChange}
model={model}
isConnected={isConnected}
isGenerating={isGenerating}
/>
<Dialog open={urlDialogOpen} onOpenChange={setUrlDialogOpen}>
<DialogContent className="sm:max-w-md z-[700]">
<DialogHeader>
<DialogTitle>Attach Webpage</DialogTitle>
<DialogDescription>Enter a URL to scrape and attach as context.</DialogDescription>
</DialogHeader>
<div className="flex gap-2">
<input
type="url"
value={urlInput}
onChange={(ev) => setUrlInput(ev.target.value)}
onKeyDown={(ev) => {
if (ev.key === 'Enter') {
ev.preventDefault();
handleUrlSubmit();
}
}}
placeholder="https://example.com"
className="flex-1 rounded-lg border border-duck-dark/20 bg-white px-3 py-2 text-sm text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:ring-2 focus:ring-duck-teal/30 focus:border-duck-teal/50"
autoFocus
/>
<Button
onClick={handleUrlSubmit}
disabled={!urlInput.trim()}
className="bg-duck-teal hover:bg-duck-teal/90 cursor-pointer disabled:opacity-40"
>
Attach
</Button>
</div>
</DialogContent>
</Dialog>
</div>
);
};
@@ -1,110 +0,0 @@
import { useMemo, useState } from 'react';
import { Check, ChevronsUpDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import type { ModelOption } from '@/state/useModels';
import { useRecentModels } from '@/state/useRecentModels';
type OpenCodeModelPickerProps = {
models: ModelOption[];
selectedModel: string | null;
onSelect: (modelId: string) => void;
isConnected: boolean;
isGenerating: boolean;
};
export const OpenCodeModelPicker = ({
models,
selectedModel,
onSelect,
isConnected,
isGenerating,
}: OpenCodeModelPickerProps) => {
const [open, setOpen] = useState(false);
const { recents, addRecent } = useRecentModels();
const selected = models.find((m) => m.id === selectedModel);
const groupedByProvider = useMemo(() => {
const groups: Record<string, ModelOption[]> = {};
for (const m of models) {
const provider = m.provider ?? 'Other';
if (!groups[provider]) groups[provider] = [];
groups[provider].push(m);
}
return Object.entries(groups)
.sort(([a], [b]) => a.localeCompare(b))
.map(([provider, items]) => ({
provider,
models: items.sort((a, b) => a.name.localeCompare(b.name)),
}));
}, [models]);
const handleSelect = (modelId: string) => {
const model = models.find((m) => m.id === modelId);
if (model) {
onSelect(model.id);
addRecent(model);
}
setOpen(false);
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
disabled={isGenerating || !isConnected}
className="h-auto border-0 bg-transparent p-0 text-xs text-duck-dark/50 shadow-none focus:ring-0 gap-1 cursor-pointer hover:bg-transparent hover:text-duck-dark/70"
>
{selected ? (
<>
{selected.name}
{selected.provider && <span className="hidden md:inline"> ({selected.provider})</span>}
</>
) : (
'select model'
)}
<ChevronsUpDown className="h-3 w-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="z-[800] w-[320px] p-0" align="end" side="top">
<Command>
<CommandInput placeholder="Search models..." />
<CommandList className="max-h-[400px]">
<CommandEmpty>No models found.</CommandEmpty>
{recents.length > 0 && (
<CommandGroup heading="Recent">
{recents.map((m) => (
<CommandItem
key={`recent-${m.id}`}
value={`${m.name} ${m.provider ?? ''}`}
onSelect={() => handleSelect(m.id)}
>
<Check className={`mr-2 h-4 w-4 ${selectedModel === m.id ? 'opacity-100' : 'opacity-0'}`} />
<span className="truncate font-bold">{m.name}</span>
{m.provider && <span className="ml-1 text-xs text-muted-foreground">({m.provider})</span>}
</CommandItem>
))}
</CommandGroup>
)}
{groupedByProvider.map(({ provider, models: providerModels }) => (
<CommandGroup key={provider} heading={provider}>
{providerModels.map((m) => (
<CommandItem key={m.id} value={`${m.name} ${m.provider ?? ''}`} onSelect={() => handleSelect(m.id)}>
<Check className={`mr-2 h-4 w-4 ${selectedModel === m.id ? 'opacity-100' : 'opacity-0'}`} />
<span className="truncate font-bold">{m.name}</span>
{m.provider && <span className="ml-1 text-xs text-muted-foreground">({m.provider})</span>}
</CommandItem>
))}
</CommandGroup>
))}
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
};
@@ -1,87 +0,0 @@
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAuth } from 'hooks/useAuth';
import type { ModelOption } from '@/state/useModels';
import type { ChatMessage } from './types';
import { OpenCodeModelPicker } from './OpenCodeModelPicker';
type SettingsProps = {
provider: 'claude' | 'opencode';
messages: ChatMessage[];
onProviderChange?: (provider: 'claude' | 'opencode') => void;
availableModels: ModelOption[];
selectedModel: string | null;
onModelChange: (modelId: string) => void;
model: string | null;
isConnected: boolean;
isGenerating: boolean;
};
export const Settings = ({
provider,
messages,
onProviderChange,
availableModels,
selectedModel,
onModelChange,
model,
isConnected,
isGenerating,
}: SettingsProps) => {
const { user } = useAuth();
const fallbackModelId = availableModels[0]?.id ?? null;
return (
<div className="flex items-center justify-between mt-2">
{messages.length > 0 ? (
<span className="rounded-md bg-duck-dark/80 px-3 py-1 text-xs font-medium text-white">
{provider === 'claude' ? 'Claude' : 'OpenCode'}
</span>
) : (
<div className="flex items-center gap-1 rounded-lg bg-white/60 p-1">
{(['claude', 'opencode'] as const).map((value) => (
<button
key={value}
onClick={() => onProviderChange?.(value)}
className={`rounded-md px-3 py-1 text-xs font-medium transition-colors ${
provider === value ? 'bg-white text-duck-dark shadow-sm' : 'text-duck-dark/70 hover:text-duck-dark/90'
} ${!onProviderChange ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
>
{value === 'claude' ? 'Claude' : 'OpenCode'}
</button>
))}
</div>
)}
<div className="text-xs text-duck-dark/50">
{availableModels.length > 0 && provider === 'opencode' ? (
<OpenCodeModelPicker
models={availableModels}
selectedModel={selectedModel ?? fallbackModelId}
onSelect={onModelChange}
isConnected={isConnected}
isGenerating={isGenerating}
/>
) : availableModels.length > 0 ? (
<Select
value={selectedModel ?? fallbackModelId ?? undefined}
onValueChange={(v) => onModelChange(v)}
disabled={isGenerating || !isConnected}
>
<SelectTrigger className="h-auto border-0 bg-transparent p-0 text-xs text-duck-dark/50 shadow-none focus:ring-0 gap-1 cursor-pointer">
<SelectValue />
</SelectTrigger>
<SelectContent className="z-[800]" side="top">
{availableModels.map((m) => (
<SelectItem key={m.id} value={m.id}>
{m.name}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<span>{model ?? (provider === 'claude' ? 'Claude' : 'OpenCode')}</span>
)}
</div>
</div>
);
};
@@ -1,227 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { useChatWebSocket } from 'hooks/useChatWebSocket';
import { useSessions } from 'plugins/ChatHistory/client';
import type { ChatMessage, ServerMessage, TaskInfo } from './types';
const SAVE_DEBOUNCE_MS = 1000;
type ResourceChatStorage = {
load: () => Promise<{ sessionId: string | null; messages: ChatMessage[] }>;
save: (sessionId: string, messages: ChatMessage[]) => Promise<void>;
};
type UseClaudeOptions = {
replaceUrl?: boolean;
storage?: ResourceChatStorage;
resourceChatDir?: string;
taskInfo?: TaskInfo;
};
export const useClaude = (initialSessionId?: string, initialModel?: string | null, options?: UseClaudeOptions) => {
const { replaceUrl = true, storage, resourceChatDir, taskInfo } = options ?? {};
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [streamingText, setStreamingText] = useState('');
const [isGenerating, setIsGenerating] = useState(false);
const [sessionId, setSessionId] = useState<string | null>(initialSessionId ?? null);
const [model, setModel] = useState<string | null>(null);
const [selectedModel, setSelectedModel] = useState<string | null>(initialModel ?? null);
const streamingRef = useRef('');
const rafRef = useRef<number | null>(null);
const sessionIdRef = useRef<string | null>(initialSessionId ?? null);
const saveTimerRef = useRef<number | null>(null);
const { getMessages, saveMessages } = useSessions();
const token = localStorage.getItem('BEARER_TOKEN');
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/api/harness/claudecode/ws?token=${token}`;
const flushStreaming = () => {
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => {
setStreamingText(streamingRef.current);
rafRef.current = null;
});
};
const commitStreaming = () => {
if (!streamingRef.current) return;
setMessages((prev) => [...prev, { role: 'assistant', text: streamingRef.current }]);
streamingRef.current = '';
setStreamingText('');
};
const handleMessage = (data: unknown) => {
const msg = data as ServerMessage;
switch (msg.type) {
case 'session:init':
sessionIdRef.current = msg.sessionId;
setSessionId(msg.sessionId);
setModel(msg.model);
if (replaceUrl) window.history.replaceState(null, '', `/chat/${msg.sessionId}`);
break;
case 'assistant:partial':
streamingRef.current += msg.text;
flushStreaming();
break;
case 'assistant:text':
if (streamingRef.current) {
commitStreaming();
} else {
setMessages((prev) => [...prev, { role: 'assistant', text: msg.text }]);
}
break;
case 'tool:use':
setMessages((prev) => [
...prev,
{ role: 'tool', toolName: msg.toolName, toolInput: msg.toolInput, toolUseId: msg.toolUseId },
]);
break;
case 'tool:result':
setMessages((prev) =>
prev.map((m) =>
m.role === 'tool' && m.toolUseId === msg.toolUseId ? { ...m, output: msg.output, isError: msg.isError } : m,
),
);
break;
case 'result':
commitStreaming();
setMessages((prev) => [
...prev,
{
role: 'result',
costUsd: msg.costUsd,
durationMs: msg.durationMs,
numTurns: msg.numTurns,
isError: msg.isError,
},
]);
setIsGenerating(false);
break;
case 'error':
commitStreaming();
setMessages((prev) => [...prev, { role: 'error', text: msg.message }]);
setIsGenerating(false);
break;
case 'stopped':
commitStreaming();
setIsGenerating(false);
break;
}
};
const { isConnected, send } = useChatWebSocket({ url: wsUrl, onMessage: handleMessage });
// Load messages from server on mount when resuming a session
useEffect(() => {
if (storage) {
storage
.load()
.then(({ sessionId: sid, messages: msgs }) => {
if (sid) {
sessionIdRef.current = sid;
setSessionId(sid);
}
if (msgs.length > 0) setMessages(msgs);
})
.catch(() => {});
return;
}
if (!initialSessionId) return;
getMessages(initialSessionId)
.then((data) => {
if (Array.isArray(data) && data.length > 0) setMessages(data);
})
.catch(() => {});
}, [initialSessionId]);
// Debounced save messages to server
useEffect(() => {
if (!sessionIdRef.current || messages.length === 0) return;
if (saveTimerRef.current !== null) clearTimeout(saveTimerRef.current);
const sid = sessionIdRef.current;
const snapshot = messages;
saveTimerRef.current = window.setTimeout(() => {
if (storage) {
storage.save(sid, snapshot).catch(() => {});
} else {
saveMessages(sid, snapshot).catch(() => {});
}
saveTimerRef.current = null;
}, SAVE_DEBOUNCE_MS);
return () => {
if (saveTimerRef.current !== null) {
clearTimeout(saveTimerRef.current);
saveTimerRef.current = null;
}
};
}, [messages]);
// Clean up RAF on unmount
useEffect(() => {
return () => {
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
};
}, []);
const sendPrompt = (
text: string,
attachmentIds?: string[],
images?: { filename: string; dataUrl: string }[],
cwd?: { root?: string; path: string },
) => {
setMessages((prev) => [...prev, { role: 'user', text, ...(images?.length ? { images } : {}) }]);
setIsGenerating(true);
streamingRef.current = '';
setStreamingText('');
// Parse dataUrls into { mediaType, data } for the server
const imageData = images
?.map((img) => {
const match = img.dataUrl.match(/^data:([^;]+);base64,(.+)$/);
return match ? { mediaType: match[1], data: match[2] } : null;
})
.filter((x): x is { mediaType: string; data: string } => x !== null);
send({
type: 'chat',
prompt: text,
sessionId: sessionIdRef.current,
...(selectedModel ? { model: selectedModel } : {}),
...(cwd ? { cwd } : {}),
...(attachmentIds?.length ? { attachmentIds } : {}),
...(imageData?.length ? { images: imageData } : {}),
...(resourceChatDir ? { resourceChatDir } : {}),
...(taskInfo ? { taskInfo } : {}),
});
};
const stopGeneration = () => {
send({ type: 'stop' });
};
return {
messages,
streamingText,
isConnected,
isGenerating,
sessionId,
model,
selectedModel,
setSelectedModel,
sendPrompt,
stopGeneration,
};
};
@@ -1,225 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { useChatWebSocket } from 'hooks/useChatWebSocket';
import { useSettings } from '@/state/useSettings';
import { useVisibleOpenCodeModels } from '@/state/useModels';
import { useOpenCodeSessions } from 'plugins/ChatHistory/client';
import type { ChatMessage, ServerMessage, TaskInfo } from './types';
type UseOpenCodeOptions = {
replaceUrl?: boolean;
taskInfo?: TaskInfo;
};
export const useOpenCode = (initialSessionId?: string, initialModel?: string | null, options?: UseOpenCodeOptions) => {
const { replaceUrl = true, taskInfo } = options ?? {};
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [streamingText, setStreamingText] = useState('');
const [isGenerating, setIsGenerating] = useState(false);
const [sessionId, setSessionId] = useState<string | null>(initialSessionId ?? null);
const [model, setModel] = useState<string | null>(null);
const [selectedModel, setSelectedModel] = useState<string | null>(initialModel ?? null);
const streamingRef = useRef('');
const rafRef = useRef<number | null>(null);
const sessionIdRef = useRef<string | null>(initialSessionId ?? null);
const selectedModelRef = useRef<string | null>(initialModel ?? null);
const updateSelectedModel = (value: string | null) => {
selectedModelRef.current = value;
setSelectedModel(value);
};
const { getMessages } = useOpenCodeSessions();
const { settings } = useSettings();
const openCodeModels = useVisibleOpenCodeModels();
const token = localStorage.getItem('BEARER_TOKEN');
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/api/harness/opencode/ws?token=${token}`;
const flushStreaming = () => {
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => {
setStreamingText(streamingRef.current);
rafRef.current = null;
});
};
const commitStreaming = () => {
// Cancel any pending RAF to prevent stale reads of cleared streamingRef
if (rafRef.current !== null) {
cancelAnimationFrame(rafRef.current);
rafRef.current = null;
}
if (!streamingRef.current) return;
setMessages((prev) => [...prev, { role: 'assistant', text: streamingRef.current }]);
streamingRef.current = '';
setStreamingText('');
};
const handleMessage = (data: unknown) => {
const msg = data as ServerMessage;
switch (msg.type) {
case 'session:init':
sessionIdRef.current = msg.sessionId;
setSessionId(msg.sessionId);
setModel(msg.model);
if (replaceUrl) window.history.replaceState(null, '', `/chat/opencode/${msg.sessionId}`);
break;
case 'assistant:partial':
streamingRef.current += msg.text;
flushStreaming();
break;
case 'assistant:text':
// Server sends the final complete text — discard streaming and use this instead
if (rafRef.current !== null) {
cancelAnimationFrame(rafRef.current);
rafRef.current = null;
}
streamingRef.current = '';
setStreamingText('');
setMessages((prev) => [...prev, { role: 'assistant', text: msg.text }]);
break;
case 'tool:use':
commitStreaming();
setMessages((prev) => {
const existing = prev.find((m) => m.role === 'tool' && m.toolUseId === msg.toolUseId);
if (existing) {
// Update input (running event sends actual input after pending)
return prev.map((m) =>
m.role === 'tool' && m.toolUseId === msg.toolUseId
? { ...m, toolName: msg.toolName, toolInput: msg.toolInput }
: m,
);
}
return [
...prev,
{ role: 'tool', toolName: msg.toolName, toolInput: msg.toolInput, toolUseId: msg.toolUseId },
];
});
break;
case 'tool:result':
setMessages((prev) =>
prev.map((m) =>
m.role === 'tool' && m.toolUseId === msg.toolUseId ? { ...m, output: msg.output, isError: msg.isError } : m,
),
);
break;
case 'result':
commitStreaming();
setMessages((prev) => [
...prev,
{
role: 'result',
costUsd: msg.costUsd,
durationMs: msg.durationMs,
numTurns: msg.numTurns,
isError: msg.isError,
},
]);
setIsGenerating(false);
break;
case 'error':
commitStreaming();
setMessages((prev) => [...prev, { role: 'error', text: msg.message }]);
setIsGenerating(false);
break;
case 'stopped':
commitStreaming();
setIsGenerating(false);
break;
}
};
const { isConnected, send } = useChatWebSocket({ url: wsUrl, onMessage: handleMessage });
// Load messages from OpenCode on mount when resuming a session
useEffect(() => {
if (!initialSessionId) return;
getMessages(initialSessionId)
.then((data) => {
if (Array.isArray(data) && data.length > 0) setMessages(data);
})
.catch(() => {});
}, [initialSessionId]);
useEffect(() => {
selectedModelRef.current = selectedModel;
}, [selectedModel]);
// Seed default model for OpenCode if none selected
useEffect(() => {
if (selectedModel) return;
if (settings.chat.defaultProvider !== 'opencode' || !settings.chat.defaultModel) return;
if (!openCodeModels.some((m) => m.id === settings.chat.defaultModel)) return;
updateSelectedModel(settings.chat.defaultModel);
}, [openCodeModels, selectedModel, settings.chat.defaultModel, settings.chat.defaultProvider]);
// Clean up RAF on unmount
useEffect(() => {
return () => {
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current);
};
}, []);
const sendPrompt = (text: string, attachmentIds?: string[], images?: { filename: string; dataUrl: string }[]) => {
setMessages((prev) => [...prev, { role: 'user', text, ...(images?.length ? { images } : {}) }]);
setIsGenerating(true);
streamingRef.current = '';
setStreamingText('');
// Parse dataUrls into { mediaType, data } for the server
const imageData = images
?.map((img) => {
const match = img.dataUrl.match(/^data:([^;]+);base64,(.+)$/);
return match ? { mediaType: match[1], data: match[2] } : null;
})
.filter((x): x is { mediaType: string; data: string } => x !== null);
const modelId = selectedModelRef.current;
const selectedOption = modelId ? openCodeModels.find((m) => m.id === modelId) : undefined;
const payload = {
type: 'chat',
prompt: text,
sessionId: sessionIdRef.current,
...(modelId
? {
model: {
modelID: modelId,
...(selectedOption?.providerId ? { providerID: selectedOption.providerId } : {}),
},
}
: {}),
...(attachmentIds?.length ? { attachmentIds } : {}),
...(imageData?.length ? { images: imageData } : {}),
...(taskInfo ? { taskInfo } : {}),
};
console.log('[opencode-ui] ws send', payload);
send(payload);
};
const stopGeneration = () => {
send({ type: 'stop' });
};
return {
messages,
streamingText,
isConnected,
isGenerating,
sessionId,
model,
selectedModel,
setSelectedModel: updateSelectedModel,
sendPrompt,
stopGeneration,
};
};
-7
View File
@@ -1,7 +0,0 @@
export * from './client';
export const plugin = {
id: 'Chat',
name: 'Chat',
description: 'Embeddable chat UI',
};
@@ -1,122 +0,0 @@
import { useRef, useEffect, useState } from 'react';
import { useNavigate, useLocation } from 'react-router';
import { useSessions } from './state/useSessions';
import type { ModelOption } from '@/state/useModels';
import { useOpenCodeSessions } from './state/useOpenCodeSessions';
import type { useClaude, Attachment } from 'plugins/Chat/client';
import { EmbeddableChat } from 'plugins/Chat/client';
import { useSlashCommands } from './state/useSlashCommands';
import { Card } from '@/components/Card';
import { SessionBar } from './SessionBar';
export type { Attachment };
type ChatPanelProps = {
chat: ReturnType<typeof useClaude>;
provider?: 'claude' | 'opencode';
availableModels?: ModelOption[];
onProviderChange?: (provider: 'claude' | 'opencode') => void;
};
export const ChatPanel = ({ chat, provider = 'claude', availableModels = [], onProviderChange }: ChatPanelProps) => {
const { isConnected, isGenerating, sessionId, setSelectedModel, sendPrompt } = chat;
const location = useLocation();
const navigate = useNavigate();
const [commandFeedback, setCommandFeedback] = useState<string | null>(null);
const [fullscreen, setFullscreen] = useState(false);
const initialSentRef = useRef(false);
const claudeSessions = useSessions();
const opencodeSessions = useOpenCodeSessions();
const { archiveSession, deleteSession } =
provider === 'claude'
? claudeSessions
: { archiveSession: undefined, deleteSession: opencodeSessions.deleteSession };
const sessions = provider === 'claude' ? claudeSessions.sessions : opencodeSessions.sessions;
const slashCommands = useSlashCommands({ sessionId });
const sessionTitle = sessionId ? sessions.find((s) => s.id === sessionId)?.title : undefined;
const listPath = '/chat';
// Capture prefill input from location.state (one-time, before first render completes)
const locationState = location.state as {
initialMessage?: string;
prefillInput?: string;
model?: string;
cwd?: { root?: string; path: string };
attachmentIds?: string[];
images?: { filename: string; dataUrl: string }[];
} | null;
const initialPrefill = useRef(locationState?.prefillInput ?? '');
const handleBeforeSend = async (text: string) => {
if (text.startsWith('/')) {
const result = await slashCommands.execute(text);
if (result.handled) {
setCommandFeedback(result.feedback);
return true;
}
}
setCommandFeedback(null);
return false;
};
// Auto-send initial message from Home launcher
useEffect(() => {
const state = location.state as typeof locationState;
if (!state || initialSentRef.current) return;
if (state.prefillInput) {
initialSentRef.current = true;
window.history.replaceState({}, '', location.pathname);
return;
}
if (!state.initialMessage || !isConnected) return;
initialSentRef.current = true;
if (state.model) setSelectedModel(state.model);
sendPrompt(state.initialMessage, state.attachmentIds, state.images, state.cwd);
// Clear the location state so refresh doesn't re-send
window.history.replaceState({}, '', location.pathname);
}, [isConnected, location.state]);
return (
<Card
className={`flex flex-col overflow-hidden transition-all duration-200 rounded-none border-0 md:rounded-xl md:border-2 ${
fullscreen ? 'fixed inset-0 m-auto z-50 w-[90vw] h-[calc(90vh-4.5rem)]' : 'h-full'
}`}
>
<SessionBar
listPath={listPath}
provider={provider}
sessionTitle={sessionTitle}
isConnected={isConnected}
isGenerating={isGenerating}
fullscreen={fullscreen}
onArchive={
archiveSession && sessionId
? async () => {
await archiveSession(sessionId);
navigate(listPath);
}
: undefined
}
onDelete={async () => {
if (!sessionId) return;
await deleteSession(sessionId);
navigate(listPath);
}}
onToggleFullscreen={() => setFullscreen((f) => !f)}
/>
<EmbeddableChat
chat={chat}
provider={provider}
availableModels={availableModels}
onProviderChange={onProviderChange}
onBeforeSend={handleBeforeSend}
commandFeedback={commandFeedback}
defaultInput={initialPrefill.current}
className="flex-1 min-h-0"
/>
</Card>
);
};
@@ -1,105 +0,0 @@
import { useMemo, useState } from 'react';
import { Link } from 'react-router';
import { Plus, MessageSquare, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/Card';
import { useSessions } from './state/useSessions';
import { useOpenCodeSessions } from './state/useOpenCodeSessions';
type Filter = 'all' | 'claude' | 'opencode';
export const SessionList = () => {
const [filter, setFilter] = useState<Filter>('all');
const claude = useSessions();
const opencode = useOpenCodeSessions();
const merged = useMemo(
() => [...claude.sessions, ...opencode.sessions].sort((a, b) => b.createdAt - a.createdAt),
[claude.sessions, opencode.sessions],
);
const filtered = filter === 'all' ? merged : merged.filter((s) => s.provider === filter);
const handleDelete = (id: string, provider: 'claude' | 'opencode') => {
if (provider === 'claude') claude.deleteSession(id);
else opencode.deleteSession(id);
};
return (
<div className="flex flex-col h-full items-center p-4 md:p-6">
<Card className="w-full max-w-2xl flex flex-col gap-4 h-full p-4 md:p-6 overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between">
<h2 className="text-lg font-bold text-duck-dark/80">Sessions</h2>
<Button asChild className="bg-duck-teal hover:bg-duck-teal/90 cursor-pointer gap-2">
<Link to="/chat/new">
<Plus className="h-4 w-4" />
New Chat
</Link>
</Button>
</div>
{/* Radio filter */}
<div className="flex items-center gap-1 rounded-lg bg-white/60 p-1">
{(['all', 'claude', 'opencode'] as const).map((value) => (
<button
key={value}
onClick={() => setFilter(value)}
className={`flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors cursor-pointer ${
filter === value ? 'bg-white text-duck-dark shadow-sm' : 'text-duck-dark/70 hover:text-duck-dark/90'
}`}
>
{value === 'all' ? 'All' : value === 'claude' ? 'Claude' : 'OpenCode'}
</button>
))}
</div>
{/* Session list */}
<div className="flex-1 min-h-0 overflow-y-auto space-y-2">
{filtered.length === 0 && (
<div className="text-center py-16 text-duck-dark/30 text-sm">No sessions yet. Start a new chat!</div>
)}
{filtered.map((session) => (
<div
key={`${session.provider}-${session.id}`}
className="group flex items-center gap-3 rounded-lg border border-duck-dark/10 bg-white/80 hover:bg-white/90 transition-colors"
>
<Link
to={session.provider === 'claude' ? `/chat/${session.id}` : `/chat/opencode/${session.id}`}
className="flex-1 flex items-center gap-3 px-4 py-3 min-w-0"
>
<MessageSquare className="h-4 w-4 shrink-0 text-duck-teal/60" />
<div className="min-w-0 flex-1">
<div className="text-sm font-medium text-duck-dark/80 truncate">{session.title}</div>
<div className="text-xs text-duck-dark/40">
{new Date(session.createdAt).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})}
<span
className={`ml-2 text-xs font-medium ${
session.provider === 'claude' ? 'text-duck-teal' : 'text-duck-orange'
}`}
>
{session.provider === 'claude' ? 'Claude' : 'OpenCode'}
</span>
<span className="ml-2 font-mono text-duck-dark/25">{session.id.slice(0, 8)}</span>
</div>
</div>
</Link>
<button
onClick={() => handleDelete(session.id, session.provider)}
className="shrink-0 p-2 mr-2 text-duck-dark/20 hover:text-red-500 md:opacity-0 md:group-hover:opacity-100 transition-opacity cursor-pointer"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
))}
</div>
</Card>
</div>
);
};
@@ -1,90 +0,0 @@
import { useMemo } from 'react';
import { Link } from 'react-router';
import { MessageSquare, Trash2, ChevronDown, ChevronUp } from 'lucide-react';
import { Card } from '@/components/Card';
import { useSessions } from './state/useSessions';
import { useOpenCodeSessions } from './state/useOpenCodeSessions';
import { useUserState } from '@/state/useUserState';
export const ChatHistory = () => {
const [collapsed, setCollapsed] = useUserState('widget:chatHistory:collapsed', true);
const claude = useSessions();
const opencode = useOpenCodeSessions();
const sessions = useMemo(
() => [...claude.sessions, ...opencode.sessions].sort((a, b) => b.createdAt - a.createdAt),
[claude.sessions, opencode.sessions],
);
const handleDelete = (id: string, provider: 'claude' | 'opencode') => {
if (provider === 'claude') claude.deleteSession(id);
else opencode.deleteSession(id);
};
return (
<div className="w-full">
<Card className="overflow-hidden">
<div className={`flex items-center justify-between px-4 pt-3 ${collapsed ? 'pb-3' : 'pb-1'}`}>
<Link to="/chat" className="text-xs font-semibold text-duck-dark/60 uppercase tracking-wide hover:underline">
Chat History
</Link>
<button
onClick={() => setCollapsed((c) => !c)}
className="text-duck-dark/40 hover:text-duck-dark/70 cursor-pointer transition-colors"
>
{collapsed ? <ChevronDown className="h-4 w-4" /> : <ChevronUp className="h-4 w-4" />}
</button>
</div>
{!collapsed && (
<>
<div className="px-4 pb-3 max-h-72 overflow-y-auto">
{sessions.length === 0 ? (
<p className="text-xs text-duck-dark/40 py-4 text-center">No sessions yet</p>
) : (
<ul className="space-y-0.5">
{sessions.map((session) => (
<li
key={`${session.provider}-${session.id}`}
className="flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-duck-dark/5 group"
>
<Link
to={session.provider === 'claude' ? `/chat/${session.id}` : `/chat/opencode/${session.id}`}
className="flex items-center gap-2 flex-1 min-w-0"
>
<MessageSquare className="h-4 w-4 shrink-0 text-duck-teal/60" />
<div className="min-w-0 flex-1">
<span className="text-sm text-duck-dark truncate block">{session.title}</span>
<span className="text-xs text-duck-dark/40 truncate block">
{new Date(session.createdAt).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})}
<span
className={`ml-1.5 font-medium ${
session.provider === 'claude' ? 'text-duck-teal' : 'text-duck-orange'
}`}
>
{session.provider === 'claude' ? 'Claude' : 'OpenCode'}
</span>
</span>
</div>
</Link>
<button
onClick={() => handleDelete(session.id, session.provider)}
className="shrink-0 p-1 rounded text-duck-dark/20 md:opacity-0 md:group-hover:opacity-100 hover:text-red-500 transition-opacity cursor-pointer"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</li>
))}
</ul>
)}
</div>
</>
)}
</Card>
</div>
);
};
@@ -1,7 +0,0 @@
export { ChatHistory as Widget } from './Widget';
export { SessionList as Screen } from './Screen';
export { ChatPanel } from './ChatPanel';
export { SessionBar } from './SessionBar';
export { useSessions } from './state/useSessions';
export { useOpenCodeSessions } from './state/useOpenCodeSessions';
export { useSlashCommands, type SlashCommandResult } from './state/useSlashCommands';
@@ -1,7 +0,0 @@
export { Widget, Screen, ChatPanel, SessionBar } from './client';
export const plugin = {
id: 'ChatHistory',
name: 'Chat History',
description: 'Session management for chat history',
};
-259
View File
@@ -1,259 +0,0 @@
# Building a Plugin
Plugins are self-contained modules that extend Officer with new features. They live under `src/workspaces/plugins/` and are auto-discovered at startup — no registration step required.
## Directory Structure
```
src/workspaces/plugins/
├── package.json # Workspace exports (update when adding a plugin)
└── MyPlugin/
├── index.ts # Metadata + re-exports
├── server/
│ ├── index.ts # Exports router and apiPath
│ └── router.ts # Hono API routes
└── client/
├── index.ts # Exports Widget and/or Screen
├── Widget.tsx # Compact component (dashboard home)
├── Screen/
│ └── index.tsx # Full-page component (dedicated route)
└── state/
└── useMyPlugin.ts # API client hook
```
A plugin can be server-only, client-only, or both. The discovery system checks for the presence of `server/index.ts` and `client/index.ts` to determine what the plugin provides.
## Step-by-Step
### 1. Create the plugin directory
```
mkdir -p src/workspaces/plugins/MyPlugin/{server,client/state,client/Screen}
```
### 2. Plugin metadata — `MyPlugin/index.ts`
Every plugin must export a `plugin` object with metadata. This is read by the settings UI and the `/plugins` API.
```ts
export { Widget, Screen } from './client';
export { router, apiPath } from './server';
export const plugin = {
id: 'MyPlugin', // Must match directory name
name: 'My Plugin', // Display name in settings
description: 'What this plugin does',
};
```
If your plugin is server-only, omit the client export. If client-only, omit the server export.
### 3. Server router — `MyPlugin/server/`
**`server/index.ts`** — Exports the router instance and the API path prefix:
```ts
export * from './router';
export const apiPath = 'my-plugin';
```
The `apiPath` determines the URL prefix. This router gets mounted at `/api/my-plugin`.
**`server/router.ts`** — Define your API endpoints:
```ts
import { createRouter } from '@@/create-router';
import * as errors from '@@/custom-errors';
export const router = createRouter();
router.get('/items', async (ctx) => {
const user = ctx.get('user'); // Authenticated user
// ...
return ctx.json({ items: [] });
});
router.post('/items', async (ctx) => {
const body = ctx.get('body'); // Parsed request body
if (!body.name) throw errors.BAD_REQUEST('Name is required');
// ...
return ctx.json({ created: true });
});
```
Key points:
- `createRouter()` from `@@/create-router` gives you a typed Hono router
- All plugin routes are **protected** — user authentication is enforced automatically
- Access the authenticated user with `ctx.get('user')` (returns `User` from types)
- Access parsed body with `ctx.get('body')`
- Throw `CustomError` instances for error responses — they're caught by the global error handler
**Available error helpers** (`@@/custom-errors`):
- `BAD_REQUEST(msg?)` — 400
- `UNAUTHORIZED(msg?)` — 401
- `FORBIDDEN(msg?)` — 403
- `NOT_FOUND(msg?)` — 404
- `CONFLICT(msg?)` — 409
- `INTERNAL_SERVER_ERROR(msg?)` — 500
- `TOO_MANY_REQUESTS(msg?, retryAfter?)` — 429
**User data helpers** (`@@/data-path`):
- `DATA_PATH` — base data directory
- `getHomeDir(email)` — user's home directory
### 4. Client components — `MyPlugin/client/`
**`client/index.ts`** — Export your components with standardized names:
```ts
export { MyPluginWidget as Widget } from './Widget';
export { MyPluginScreen as Screen } from './Screen';
```
**`client/state/useMyPlugin.ts`** — API client hook:
```ts
import { useClient } from 'hooks/useClient';
type Item = {
id: string;
name: string;
};
export const useMyPlugin = () => {
const client = useClient();
return {
listItems: () => client.get<Item[]>('/my-plugin/items'),
createItem: (name: string) => client.post('/my-plugin/items', { name }),
};
};
```
The `useClient()` hook provides an authenticated HTTP client. The path must match your `apiPath` from the server.
**`client/Widget.tsx`** — Compact component for the dashboard home:
```tsx
import { useState, useEffect } from 'react';
import { useMyPlugin } from './state/useMyPlugin';
export const MyPluginWidget = () => {
// Widget implementation
};
```
**`client/Screen/index.tsx`** — Full-page component:
```tsx
import { DashboardLayout } from '@/Screens/Dashboard/Layout';
export const MyPluginScreen = () => {
return (
<DashboardLayout>
{/* Screen implementation */}
</DashboardLayout>
);
};
```
### 5. Register workspace exports — `plugins/package.json`
Add subpath exports so the monorepo can import your plugin:
```json
{
"exports": {
"./FileBrowser": "./FileBrowser/index.ts",
"./FileBrowser/client": "./FileBrowser/client/index.ts",
"./FileBrowser/server": "./FileBrowser/server/index.ts",
"./MyPlugin": "./MyPlugin/index.ts",
"./MyPlugin/client": "./MyPlugin/client/index.ts",
"./MyPlugin/server": "./MyPlugin/server/index.ts"
}
}
```
This lets other code import your plugin as:
```ts
import { Widget, Screen } from 'plugins/MyPlugin/client';
import { router, apiPath } from 'plugins/MyPlugin/server';
import { plugin } from 'plugins/MyPlugin';
```
### 6. Wire into the app (optional)
The server router is auto-discovered and mounted — no changes needed. But if your plugin has client components that should appear in the main app, you'll need to add them manually:
**Route**`src/apps/officer-web/App.tsx`:
```tsx
import { Screen as MyPluginScreen } from 'plugins/MyPlugin/client';
// Inside the authenticated routes:
{plugins?.MyPlugin !== false && <Route path="/my-plugin" element={<MyPluginScreen />} />}
```
**Nav item**`src/apps/officer-web/Screens/Dashboard/Layout.tsx`:
```tsx
{plugins?.MyPlugin !== false && (
<DropdownMenuItem asChild className="cursor-pointer">
<Link to="/my-plugin">
<SomeIcon className="mr-2 h-4 w-4" />
My Plugin
</Link>
</DropdownMenuItem>
)}
```
**Home widget**`src/apps/officer-web/Screens/Dashboard/Home/index.tsx`:
```tsx
import { Widget as MyPluginWidget } from 'plugins/MyPlugin/client';
// Inside the layout:
{plugins?.MyPlugin !== false && <MyPluginWidget />}
```
The `plugins` object comes from `useServerSettings()` and is `undefined` when no overrides exist — so `plugins?.MyPlugin !== false` defaults to showing the plugin (opt-out model).
## Enable/Disable
Plugins are **enabled by default**. Admins can disable them in Server Settings > Plugins, which writes to `~/.config/officer.dev/server-settings.json`:
```json
{
"plugins": {
"MyPlugin": false
}
}
```
When disabled:
- **Server-side**: The plugin router is not mounted (requires server restart)
- **Client-side**: Routes, nav items, and widgets are hidden immediately
## Import Aliases
| Alias | Resolves to | Use in |
|-------|-------------|--------|
| `@@/` | `src/servers/` | Server code (`createRouter`, `custom-errors`, `data-path`) |
| `@/` | `src/apps/officer-web/` | Client code (`components/ui/*`, `Screens/*`, `state/*`) |
| `hooks/` | `src/workspaces/hooks/src/` | Both (`useClient`, `useAuth`) |
| `types` | `src/workspaces/types/` | Both |
| `config` | `src/workspaces/config/` | Client code |
| `plugins/` | `src/workspaces/plugins/` | Both |
## Checklist
- [ ] `MyPlugin/index.ts` exports `plugin` metadata with `id` matching directory name
- [ ] `MyPlugin/server/index.ts` exports `router` and `apiPath`
- [ ] `MyPlugin/client/index.ts` exports `Widget` and/or `Screen`
- [ ] `plugins/package.json` has subpath exports for the new plugin
- [ ] App routes gated with `plugins?.MyPlugin !== false`
- [ ] Nav items gated with `plugins?.MyPlugin !== false`
- [ ] Home widgets gated with `plugins?.MyPlugin !== false`
- [ ] `bunx tsgo` — no new type errors
-12
View File
@@ -1,12 +0,0 @@
{
"name": "plugins",
"version": "0.0.1",
"private": true,
"type": "module",
"exports": {
"./Chat": "./Chat/index.ts",
"./Chat/client": "./Chat/client/index.ts",
"./ChatHistory": "./ChatHistory/index.ts",
"./ChatHistory/client": "./ChatHistory/client/index.ts"
}
}
@@ -1,11 +1,5 @@
export { EmbeddableChat, type Attachment } from './EmbeddableChat';
export { MessageList } from './MessageList';
export { InputArea } from './InputArea';
export { Settings } from './Settings';
export { MessageBubble, StreamingBubble } from './MessageBubble';
export { ToolActivity } from './ToolActivity';
export { QuestionActivity } from './QuestionActivity';
export { OpenCodeModelPicker } from './OpenCodeModelPicker';
export { useClaude } from './useClaude';
export { useOpenCode } from './useOpenCode';
export type { ChatMessage, SessionEntry, ServerMessage, TaskInfo } from './types';
@@ -0,0 +1,4 @@
export { SessionBar } from './SessionBar';
export { useSessions } from './useSessions';
export { useOpenCodeSessions } from './useOpenCodeSessions';
export { useSlashCommands, type SlashCommandResult } from './useSlashCommands';
@@ -1,4 +1,4 @@
import type { SessionEntry, ChatMessage } from 'plugins/Chat/client';
import type { SessionEntry, ChatMessage } from 'widgets/Chat';
import { useAuth } from 'hooks/useAuth';
import { useClient } from 'hooks/useClient';
import { useQuery, useQueryClient } from '@tanstack/react-query';
@@ -1,4 +1,4 @@
import type { SessionEntry, ChatMessage } from 'plugins/Chat/client';
import type { SessionEntry, ChatMessage } from 'widgets/Chat';
import type { SlashCommandResult } from './useSlashCommands';
import { useAuth } from 'hooks/useAuth';
import { useClient } from 'hooks/useClient';
+3 -1
View File
@@ -3,6 +3,8 @@
"private": true,
"exports": {
"./Terminal": "./Terminal/index.ts",
"./FileBrowser": "./FileBrowser/index.ts"
"./FileBrowser": "./FileBrowser/index.ts",
"./ChatHistory": "./ChatHistory/index.ts",
"./Chat": "./Chat/index.ts"
}
}