pi-mono
This commit is contained in:
@@ -37,8 +37,7 @@ export function App() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Dashboard.HomeScreen />} />
|
<Route path="/" element={<Dashboard.HomeScreen />} />
|
||||||
<Route path="/settings/profile" element={<Dashboard.ProfileSettings />} />
|
<Route path="/settings/profile" element={<Dashboard.ProfileSettings />} />
|
||||||
<Route path="/settings/ai" element={<Dashboard.AISettings />} />
|
<Route path="/settings/system" element={<Dashboard.SystemSettings />} />
|
||||||
<Route path="/settings/server" element={<Dashboard.ServerSettings />} />
|
|
||||||
<Route path="/settings/resources" element={<Dashboard.ResourceSettings />} />
|
<Route path="/settings/resources" element={<Dashboard.ResourceSettings />} />
|
||||||
<Route path="/automation" element={<Dashboard.Automation />} />
|
<Route path="/automation" element={<Dashboard.Automation />} />
|
||||||
<Route path="/chat" element={<Dashboard.SessionListPage />} />
|
<Route path="/chat" element={<Dashboard.SessionListPage />} />
|
||||||
@@ -46,6 +45,8 @@ export function App() {
|
|||||||
<Route path="/chat/:sessionId" element={<Dashboard.SessionListPage />} />
|
<Route path="/chat/:sessionId" element={<Dashboard.SessionListPage />} />
|
||||||
<Route path="/chat/opencode/new" element={<Dashboard.SessionListPage provider="opencode" isNew />} />
|
<Route path="/chat/opencode/new" element={<Dashboard.SessionListPage provider="opencode" isNew />} />
|
||||||
<Route path="/chat/opencode/:sessionId" element={<Dashboard.SessionListPage provider="opencode" />} />
|
<Route path="/chat/opencode/:sessionId" element={<Dashboard.SessionListPage provider="opencode" />} />
|
||||||
|
<Route path="/chat/pi-mono/new" element={<Dashboard.SessionListPage provider="pi-mono" isNew />} />
|
||||||
|
<Route path="/chat/pi-mono/:sessionId" element={<Dashboard.SessionListPage provider="pi-mono" />} />
|
||||||
<Route path="/plans" element={<Dashboard.Plans />} />
|
<Route path="/plans" element={<Dashboard.Plans />} />
|
||||||
<Route path="/files" element={<Dashboard.FilesPage />} />
|
<Route path="/files" element={<Dashboard.FilesPage />} />
|
||||||
|
|
||||||
|
|||||||
@@ -8,12 +8,13 @@ import { ArrowLeft, Pencil, Plus, Check, X, Trash2, Search, ChevronRight } from
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||||
import { useClient } from 'hooks/useClient';
|
import { useClient } from 'hooks/useClient';
|
||||||
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';
|
import { useVisibleClaudeModels, useVisibleOpenCodeModels, useVisiblePiMonoModels } from '@/state/useModels';
|
||||||
import { useSettings } from '@/state/useSettings';
|
import { useSettings } from '@/state/useSettings';
|
||||||
import { Card } from '@/components/Card';
|
import { Card } from '@/components/Card';
|
||||||
import type { ChatMessage } from 'apps/Chat';
|
import type { ChatMessage } from 'apps/Chat';
|
||||||
import { useClaude } from '@/Screens/Dashboard/Chat/useClaude';
|
import { useClaude } from '@/Screens/Dashboard/Chat/useClaude';
|
||||||
import { useOpenCode } from '@/Screens/Dashboard/Chat/useOpenCode';
|
import { useOpenCode } from '@/Screens/Dashboard/Chat/useOpenCode';
|
||||||
|
import { usePiMono } from '@/Screens/Dashboard/Chat/usePiMono';
|
||||||
import { EmbeddableChat } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
import { EmbeddableChat } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
||||||
type CapabilitySummary = {
|
type CapabilitySummary = {
|
||||||
dirName: string;
|
dirName: string;
|
||||||
@@ -60,7 +61,7 @@ type CapabilityChatProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
type CapabilityChatInnerProps = CapabilityChatProps & {
|
type CapabilityChatInnerProps = CapabilityChatProps & {
|
||||||
onProviderChange: (p: 'claude' | 'opencode') => void;
|
onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const CapabilityChatClaude = ({
|
const CapabilityChatClaude = ({
|
||||||
@@ -174,15 +175,59 @@ const CapabilityChatOpenCode = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const CapabilityChatPiMono = ({
|
||||||
|
kind,
|
||||||
|
filePath,
|
||||||
|
resourceDir,
|
||||||
|
isNew,
|
||||||
|
description,
|
||||||
|
onResponseEnd,
|
||||||
|
onProviderChange,
|
||||||
|
}: CapabilityChatInnerProps) => {
|
||||||
|
const piMonoModels = useVisiblePiMonoModels();
|
||||||
|
const seedFile = `${kind.toUpperCase()}.md`;
|
||||||
|
const promptFrontmatter = `<frontmatter>\ninput file: ${filePath}\n${seedFile}: ${filePath}\ndir: ${resourceDir}\n\nBe aware of any extra files alongside the same dir as the ${kind} file we're handling, for possible extra context. You can also, if pertinent, create scripts or other files that will help you in the future.\n</frontmatter>`;
|
||||||
|
const defaultInput = isNew
|
||||||
|
? description ?? `Help me create the content for this new ${kind} file`
|
||||||
|
: `Help me understand and improve this ${kind} file`;
|
||||||
|
|
||||||
|
const piMono = usePiMono(undefined, undefined, { replaceUrl: false });
|
||||||
|
|
||||||
|
const onResponseEndRef = useRef(onResponseEnd);
|
||||||
|
onResponseEndRef.current = onResponseEnd;
|
||||||
|
|
||||||
|
const wasGenerating = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (wasGenerating.current && !piMono.isGenerating) {
|
||||||
|
onResponseEndRef.current?.();
|
||||||
|
}
|
||||||
|
wasGenerating.current = piMono.isGenerating;
|
||||||
|
}, [piMono.isGenerating]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<EmbeddableChat
|
||||||
|
chat={piMono}
|
||||||
|
provider="pi-mono"
|
||||||
|
availableModels={piMonoModels}
|
||||||
|
onProviderChange={onProviderChange}
|
||||||
|
defaultInput={defaultInput}
|
||||||
|
promptPrefix={promptFrontmatter}
|
||||||
|
className="h-full"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const CapabilityChat = (props: CapabilityChatProps) => {
|
export const CapabilityChat = (props: CapabilityChatProps) => {
|
||||||
const { settings } = useSettings();
|
const { settings } = useSettings();
|
||||||
const [provider, setProvider] = useState<'claude' | 'opencode'>(settings.chat.defaultProvider);
|
const [provider, setProvider] = useState<'claude' | 'opencode' | 'pi-mono'>(settings.chat.defaultProvider);
|
||||||
|
|
||||||
return provider === 'claude' ? (
|
if (provider === 'claude') {
|
||||||
<CapabilityChatClaude key="claude" {...props} onProviderChange={setProvider} />
|
return <CapabilityChatClaude key="claude" {...props} onProviderChange={setProvider} />;
|
||||||
) : (
|
}
|
||||||
<CapabilityChatOpenCode key="opencode" {...props} onProviderChange={setProvider} />
|
if (provider === 'opencode') {
|
||||||
);
|
return <CapabilityChatOpenCode key="opencode" {...props} onProviderChange={setProvider} />;
|
||||||
|
}
|
||||||
|
return <CapabilityChatPiMono key="pi-mono" {...props} onProviderChange={setProvider} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const FrontmatterBlock = ({ yaml }: { yaml: string }) => {
|
export const FrontmatterBlock = ({ yaml }: { yaml: string }) => {
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ export type { Attachment };
|
|||||||
|
|
||||||
type ChatPanelProps = {
|
type ChatPanelProps = {
|
||||||
chat: ReturnType<typeof useClaude>;
|
chat: ReturnType<typeof useClaude>;
|
||||||
provider?: 'claude' | 'opencode';
|
provider?: 'claude' | 'opencode' | 'pi-mono';
|
||||||
availableModels?: ModelOption[];
|
availableModels?: ModelOption[];
|
||||||
onProviderChange?: (provider: 'claude' | 'opencode') => void;
|
onProviderChange?: (provider: 'claude' | 'opencode' | 'pi-mono') => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ChatPanel = ({ chat, provider = 'claude', availableModels = [], onProviderChange }: ChatPanelProps) => {
|
export const ChatPanel = ({ chat, provider = 'claude', availableModels = [], onProviderChange }: ChatPanelProps) => {
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ export type Attachment =
|
|||||||
|
|
||||||
type EmbeddableChatProps = {
|
type EmbeddableChatProps = {
|
||||||
chat: ReturnType<typeof useClaude>;
|
chat: ReturnType<typeof useClaude>;
|
||||||
provider?: 'claude' | 'opencode';
|
provider?: 'claude' | 'opencode' | 'pi-mono';
|
||||||
availableModels?: ModelOption[];
|
availableModels?: ModelOption[];
|
||||||
onProviderChange?: (provider: 'claude' | 'opencode') => void;
|
onProviderChange?: (provider: 'claude' | 'opencode' | 'pi-mono') => void;
|
||||||
onBeforeSend?: (text: string) => boolean | Promise<boolean>;
|
onBeforeSend?: (text: string) => boolean | Promise<boolean>;
|
||||||
commandFeedback?: string | null;
|
commandFeedback?: string | null;
|
||||||
defaultInput?: string;
|
defaultInput?: string;
|
||||||
|
|||||||
@@ -61,9 +61,9 @@ type InputAreaProps = {
|
|||||||
isConnected: boolean;
|
isConnected: boolean;
|
||||||
commandFeedback: string | null;
|
commandFeedback: string | null;
|
||||||
textareaRef: RefObject<HTMLTextAreaElement | null>;
|
textareaRef: RefObject<HTMLTextAreaElement | null>;
|
||||||
provider: 'claude' | 'opencode';
|
provider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
messages: ChatMessage[];
|
messages: ChatMessage[];
|
||||||
onProviderChange?: (provider: 'claude' | 'opencode') => void;
|
onProviderChange?: (provider: 'claude' | 'opencode' | 'pi-mono') => void;
|
||||||
availableModels: ModelOption[];
|
availableModels: ModelOption[];
|
||||||
selectedModel: string | null;
|
selectedModel: string | null;
|
||||||
onModelChange: (modelId: string) => void;
|
onModelChange: (modelId: string) => void;
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ import type { ChatMessage } from 'apps/Chat';
|
|||||||
import { OpenCodeModelPicker } from './OpenCodeModelPicker';
|
import { OpenCodeModelPicker } from './OpenCodeModelPicker';
|
||||||
|
|
||||||
type SettingsProps = {
|
type SettingsProps = {
|
||||||
provider: 'claude' | 'opencode';
|
provider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
messages: ChatMessage[];
|
messages: ChatMessage[];
|
||||||
onProviderChange?: (provider: 'claude' | 'opencode') => void;
|
onProviderChange?: (provider: 'claude' | 'opencode' | 'pi-mono') => void;
|
||||||
availableModels: ModelOption[];
|
availableModels: ModelOption[];
|
||||||
selectedModel: string | null;
|
selectedModel: string | null;
|
||||||
onModelChange: (modelId: string) => void;
|
onModelChange: (modelId: string) => void;
|
||||||
@@ -35,11 +35,11 @@ export const Settings = ({
|
|||||||
<div className="flex items-center justify-between mt-2">
|
<div className="flex items-center justify-between mt-2">
|
||||||
{messages.length > 0 ? (
|
{messages.length > 0 ? (
|
||||||
<span className="rounded-md bg-duck-dark/80 px-3 py-1 text-xs font-medium text-white">
|
<span className="rounded-md bg-duck-dark/80 px-3 py-1 text-xs font-medium text-white">
|
||||||
{provider === 'claude' ? 'Claude' : 'OpenCode'}
|
{provider === 'claude' ? 'Claude' : provider === 'opencode' ? 'OpenCode' : 'Pi'}
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex items-center gap-1 rounded-lg bg-background/60 p-1">
|
<div className="flex items-center gap-1 rounded-lg bg-background/60 p-1">
|
||||||
{(['claude', 'opencode'] as const).map((value) => (
|
{(['claude', 'opencode', 'pi-mono'] as const).map((value) => (
|
||||||
<button
|
<button
|
||||||
key={value}
|
key={value}
|
||||||
onClick={() => onProviderChange?.(value)}
|
onClick={() => onProviderChange?.(value)}
|
||||||
@@ -47,7 +47,7 @@ export const Settings = ({
|
|||||||
provider === value ? 'bg-background text-duck-dark shadow-sm' : 'text-duck-dark/70 hover:text-duck-dark/90'
|
provider === value ? 'bg-background text-duck-dark shadow-sm' : 'text-duck-dark/70 hover:text-duck-dark/90'
|
||||||
} ${!onProviderChange ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
|
} ${!onProviderChange ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
|
||||||
>
|
>
|
||||||
{value === 'claude' ? 'Claude' : 'OpenCode'}
|
{value === 'claude' ? 'Claude' : value === 'opencode' ? 'OpenCode' : 'Pi'}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import { useState, useEffect, useRef } from 'react';
|
||||||
|
import { useChatWebSocket } from 'hooks/useChatWebSocket';
|
||||||
|
import { useChatSessions } from '@/state/useChatSessions';
|
||||||
|
import type { ChatMessage, ServerMessage, TaskInfo } from 'apps/Chat';
|
||||||
|
|
||||||
|
const SAVE_DEBOUNCE_MS = 1000;
|
||||||
|
|
||||||
|
type UsePiMonoOptions = {
|
||||||
|
replaceUrl?: boolean;
|
||||||
|
taskInfo?: TaskInfo;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const usePiMono = (initialSessionId?: string, initialModel?: string | null, options?: UsePiMonoOptions) => {
|
||||||
|
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 saveTimerRef = useRef<number | null>(null);
|
||||||
|
|
||||||
|
const { getMessages, saveMessages } = useChatSessions();
|
||||||
|
|
||||||
|
const token = localStorage.getItem('BEARER_TOKEN');
|
||||||
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
|
const wsUrl = `${protocol}//${window.location.host}/api/harness/pi-mono/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/pi-mono/${msg.sessionId}`);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'system:prompt':
|
||||||
|
setMessages((prev) => [...prev, { role: 'system', text: msg.text }]);
|
||||||
|
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 (!initialSessionId) return;
|
||||||
|
getMessages('pi-mono', 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(() => {
|
||||||
|
saveMessages('pi-mono', 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('');
|
||||||
|
|
||||||
|
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 } : {}),
|
||||||
|
...(taskInfo ? { taskInfo } : {}),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopGeneration = () => {
|
||||||
|
send({ type: 'stop' });
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
messages,
|
||||||
|
streamingText,
|
||||||
|
isConnected,
|
||||||
|
isGenerating,
|
||||||
|
sessionId,
|
||||||
|
model,
|
||||||
|
selectedModel,
|
||||||
|
setSelectedModel,
|
||||||
|
sendPrompt,
|
||||||
|
stopGeneration,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -3,14 +3,15 @@ import { useLocation } from 'react-router';
|
|||||||
import { Trash2, Archive } from 'lucide-react';
|
import { Trash2, Archive } from 'lucide-react';
|
||||||
import { usePanelChannel } from 'hooks/usePanelChannel';
|
import { usePanelChannel } from 'hooks/usePanelChannel';
|
||||||
import { useChatSessions } from '@/state/useChatSessions';
|
import { useChatSessions } from '@/state/useChatSessions';
|
||||||
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';
|
import { useVisibleClaudeModels, useVisibleOpenCodeModels, useVisiblePiMonoModels } from '@/state/useModels';
|
||||||
import { useClaude } from '@/Screens/Dashboard/Chat/useClaude';
|
import { useClaude } from '@/Screens/Dashboard/Chat/useClaude';
|
||||||
import { useOpenCode } from '@/Screens/Dashboard/Chat/useOpenCode';
|
import { useOpenCode } from '@/Screens/Dashboard/Chat/useOpenCode';
|
||||||
|
import { usePiMono } from '@/Screens/Dashboard/Chat/usePiMono';
|
||||||
import { EmbeddableChat } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
import { EmbeddableChat } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
||||||
|
|
||||||
export type SelectedSession = {
|
export type SelectedSession = {
|
||||||
id: string;
|
id: string;
|
||||||
provider: 'claude' | 'opencode';
|
provider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
model?: string | null;
|
model?: string | null;
|
||||||
} | null;
|
} | null;
|
||||||
|
|
||||||
@@ -26,7 +27,7 @@ type ChatLocationState = {
|
|||||||
} | null;
|
} | null;
|
||||||
|
|
||||||
type DetailBarProps = {
|
type DetailBarProps = {
|
||||||
provider: 'claude' | 'opencode';
|
provider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
sessionTitle: string | undefined;
|
sessionTitle: string | undefined;
|
||||||
isConnected: boolean;
|
isConnected: boolean;
|
||||||
isGenerating: boolean;
|
isGenerating: boolean;
|
||||||
@@ -138,7 +139,33 @@ const OpenCodeInner = ({ sessionId, model }: InnerProps) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const NewClaudeInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode') => void }) => {
|
const PiMonoInner = ({ sessionId, model }: InnerProps) => {
|
||||||
|
const chat = usePiMono(sessionId, model, { replaceUrl: false });
|
||||||
|
const models = useVisiblePiMonoModels();
|
||||||
|
const { sessions, deleteSession } = useChatSessions();
|
||||||
|
const [, setSelected] = usePanelChannel<SelectedSession>(CHANNEL, null);
|
||||||
|
const sessionTitle = sessions.find((s) => s.id === sessionId)?.title;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<DetailBar
|
||||||
|
provider="pi-mono"
|
||||||
|
sessionTitle={sessionTitle}
|
||||||
|
isConnected={chat.isConnected}
|
||||||
|
isGenerating={chat.isGenerating}
|
||||||
|
onArchive={undefined}
|
||||||
|
onDelete={async () => {
|
||||||
|
await deleteSession('pi-mono', sessionId);
|
||||||
|
setSelected(null);
|
||||||
|
window.history.replaceState(null, '', '/chat');
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<EmbeddableChat chat={chat} provider="pi-mono" availableModels={models} className="flex-1 min-h-0" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const NewClaudeInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void }) => {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const locationState = location.state as ChatLocationState;
|
const locationState = location.state as ChatLocationState;
|
||||||
const initialSentRef = useRef(false);
|
const initialSentRef = useRef(false);
|
||||||
@@ -189,7 +216,7 @@ const NewClaudeInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' |
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const NewOpenCodeInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode') => void }) => {
|
const NewOpenCodeInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void }) => {
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const locationState = location.state as ChatLocationState;
|
const locationState = location.state as ChatLocationState;
|
||||||
const initialSentRef = useRef(false);
|
const initialSentRef = useRef(false);
|
||||||
@@ -239,8 +266,58 @@ const NewOpenCodeInner = ({ onProviderChange }: { onProviderChange: (p: 'claude'
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const NewPiMonoInner = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void }) => {
|
||||||
|
const location = useLocation();
|
||||||
|
const locationState = location.state as ChatLocationState;
|
||||||
|
const initialSentRef = useRef(false);
|
||||||
|
const chat = usePiMono();
|
||||||
|
const models = useVisiblePiMonoModels();
|
||||||
|
const [, setSelected] = usePanelChannel<SelectedSession>(CHANNEL, null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (chat.sessionId) {
|
||||||
|
setSelected({ id: chat.sessionId, provider: 'pi-mono', model: chat.model });
|
||||||
|
}
|
||||||
|
}, [chat.sessionId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!locationState || initialSentRef.current || !chat.isConnected) return;
|
||||||
|
if (locationState.prefillInput) {
|
||||||
|
initialSentRef.current = true;
|
||||||
|
window.history.replaceState({}, '', location.pathname);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!locationState.initialMessage) return;
|
||||||
|
initialSentRef.current = true;
|
||||||
|
if (locationState.model) chat.setSelectedModel(locationState.model);
|
||||||
|
chat.sendPrompt(locationState.initialMessage, locationState.attachmentIds, locationState.images);
|
||||||
|
window.history.replaceState({}, '', location.pathname);
|
||||||
|
}, [chat.isConnected, location.state]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full">
|
||||||
|
<DetailBar
|
||||||
|
provider="pi-mono"
|
||||||
|
sessionTitle={undefined}
|
||||||
|
isConnected={chat.isConnected}
|
||||||
|
isGenerating={chat.isGenerating}
|
||||||
|
onArchive={undefined}
|
||||||
|
onDelete={undefined}
|
||||||
|
/>
|
||||||
|
<EmbeddableChat
|
||||||
|
chat={chat}
|
||||||
|
provider="pi-mono"
|
||||||
|
availableModels={models}
|
||||||
|
onProviderChange={onProviderChange}
|
||||||
|
defaultInput={locationState?.prefillInput ?? ''}
|
||||||
|
className="flex-1 min-h-0"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
type NewChatPanelProps = {
|
type NewChatPanelProps = {
|
||||||
initialProvider?: 'claude' | 'opencode';
|
initialProvider?: 'claude' | 'opencode' | 'pi-mono';
|
||||||
};
|
};
|
||||||
|
|
||||||
const NewChatPanel = ({ initialProvider = 'claude' }: NewChatPanelProps) => {
|
const NewChatPanel = ({ initialProvider = 'claude' }: NewChatPanelProps) => {
|
||||||
@@ -248,24 +325,28 @@ const NewChatPanel = ({ initialProvider = 'claude' }: NewChatPanelProps) => {
|
|||||||
|
|
||||||
const provider = selected?.provider ?? initialProvider;
|
const provider = selected?.provider ?? initialProvider;
|
||||||
|
|
||||||
const handleProviderChange = (p: 'claude' | 'opencode') => {
|
const handleProviderChange = (p: 'claude' | 'opencode' | 'pi-mono') => {
|
||||||
setSelected({ id: 'new', provider: p });
|
setSelected({ id: 'new', provider: p });
|
||||||
};
|
};
|
||||||
|
|
||||||
// Once a session is created, the inner component updates selected via the channel
|
// Once a session is created, the inner component updates selected via the channel
|
||||||
if (selected && selected.id !== 'new') {
|
if (selected && selected.id !== 'new') {
|
||||||
return selected.provider === 'claude' ? (
|
if (selected.provider === 'claude') {
|
||||||
<ClaudeInner key={selected.id} sessionId={selected.id} model={selected.model} />
|
return <ClaudeInner key={selected.id} sessionId={selected.id} model={selected.model} />;
|
||||||
) : (
|
}
|
||||||
<OpenCodeInner key={selected.id} sessionId={selected.id} model={selected.model} />
|
if (selected.provider === 'opencode') {
|
||||||
);
|
return <OpenCodeInner key={selected.id} sessionId={selected.id} model={selected.model} />;
|
||||||
|
}
|
||||||
|
return <PiMonoInner key={selected.id} sessionId={selected.id} model={selected.model} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return provider === 'claude' ? (
|
if (provider === 'claude') {
|
||||||
<NewClaudeInner key="new-claude" onProviderChange={handleProviderChange} />
|
return <NewClaudeInner key="new-claude" onProviderChange={handleProviderChange} />;
|
||||||
) : (
|
}
|
||||||
<NewOpenCodeInner key="new-opencode" onProviderChange={handleProviderChange} />
|
if (provider === 'opencode') {
|
||||||
);
|
return <NewOpenCodeInner key="new-opencode" onProviderChange={handleProviderChange} />;
|
||||||
|
}
|
||||||
|
return <NewPiMonoInner key="new-pi-mono" onProviderChange={handleProviderChange} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ChatDetailPanel = () => {
|
export const ChatDetailPanel = () => {
|
||||||
@@ -283,9 +364,11 @@ export const ChatDetailPanel = () => {
|
|||||||
return <NewChatPanel key="new" initialProvider={selected.provider} />;
|
return <NewChatPanel key="new" initialProvider={selected.provider} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return selected.provider === 'claude' ? (
|
if (selected.provider === 'claude') {
|
||||||
<ClaudeInner key={selected.id} sessionId={selected.id} model={selected.model} />
|
return <ClaudeInner key={selected.id} sessionId={selected.id} model={selected.model} />;
|
||||||
) : (
|
}
|
||||||
<OpenCodeInner key={selected.id} sessionId={selected.id} model={selected.model} />
|
if (selected.provider === 'opencode') {
|
||||||
);
|
return <OpenCodeInner key={selected.id} sessionId={selected.id} model={selected.model} />;
|
||||||
|
}
|
||||||
|
return <PiMonoInner key={selected.id} sessionId={selected.id} model={selected.model} />;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { usePanelChannel } from 'hooks/usePanelChannel';
|
|||||||
import { useChatSessions } from '@/state/useChatSessions';
|
import { useChatSessions } from '@/state/useChatSessions';
|
||||||
import type { SelectedSession } from './ChatDetailPanel';
|
import type { SelectedSession } from './ChatDetailPanel';
|
||||||
|
|
||||||
type Filter = 'all' | 'claude' | 'opencode';
|
type Filter = 'all' | 'claude' | 'opencode' | 'pi-mono';
|
||||||
|
|
||||||
export const SessionList = () => {
|
export const SessionList = () => {
|
||||||
const [filter, setFilter] = useState<Filter>('all');
|
const [filter, setFilter] = useState<Filter>('all');
|
||||||
@@ -29,11 +29,16 @@ export const SessionList = () => {
|
|||||||
|
|
||||||
const handleSelect = (session: (typeof sessions)[number]) => {
|
const handleSelect = (session: (typeof sessions)[number]) => {
|
||||||
setSelected({ id: session.id, provider: session.provider, model: session.model ?? null });
|
setSelected({ id: session.id, provider: session.provider, model: session.model ?? null });
|
||||||
const path = session.provider === 'claude' ? `/chat/${session.id}` : `/chat/opencode/${session.id}`;
|
const path =
|
||||||
|
session.provider === 'claude'
|
||||||
|
? `/chat/${session.id}`
|
||||||
|
: session.provider === 'opencode'
|
||||||
|
? `/chat/opencode/${session.id}`
|
||||||
|
: `/chat/pi-mono/${session.id}`;
|
||||||
window.history.replaceState(null, '', path);
|
window.history.replaceState(null, '', path);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (provider: 'claude' | 'opencode', id: string) => {
|
const handleDelete = async (provider: 'claude' | 'opencode' | 'pi-mono', id: string) => {
|
||||||
if (selected?.id === id && selected?.provider === provider) {
|
if (selected?.id === id && selected?.provider === provider) {
|
||||||
setSelected(null);
|
setSelected(null);
|
||||||
window.history.replaceState(null, '', '/chat');
|
window.history.replaceState(null, '', '/chat');
|
||||||
@@ -49,7 +54,7 @@ export const SessionList = () => {
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{/* Radio filter */}
|
{/* Radio filter */}
|
||||||
<div className="flex items-center gap-0.5 rounded-lg bg-duck-dark/5 dark:bg-foreground/5 p-0.5">
|
<div className="flex items-center gap-0.5 rounded-lg bg-duck-dark/5 dark:bg-foreground/5 p-0.5">
|
||||||
{(['all', 'claude', 'opencode'] as const).map((value) => (
|
{(['all', 'claude', 'opencode', 'pi-mono'] as const).map((value) => (
|
||||||
<button
|
<button
|
||||||
key={value}
|
key={value}
|
||||||
onClick={() => setFilter(value)}
|
onClick={() => setFilter(value)}
|
||||||
@@ -59,7 +64,7 @@ export const SessionList = () => {
|
|||||||
: 'text-duck-dark/50 dark:text-foreground/50 hover:text-duck-dark/80 dark:hover:text-foreground/80'
|
: 'text-duck-dark/50 dark:text-foreground/50 hover:text-duck-dark/80 dark:hover:text-foreground/80'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{value === 'all' ? 'All' : value === 'claude' ? 'Claude' : 'OpenCode'}
|
{value === 'all' ? 'All' : value === 'claude' ? 'Claude' : value === 'opencode' ? 'OpenCode' : 'Pi'}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -114,10 +119,14 @@ export const SessionList = () => {
|
|||||||
})}
|
})}
|
||||||
<span
|
<span
|
||||||
className={`ml-2 text-xs font-medium ${
|
className={`ml-2 text-xs font-medium ${
|
||||||
session.provider === 'claude' ? 'text-duck-teal' : 'text-duck-orange'
|
session.provider === 'claude'
|
||||||
|
? 'text-duck-teal'
|
||||||
|
: session.provider === 'opencode'
|
||||||
|
? 'text-duck-orange'
|
||||||
|
: 'text-purple-500'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{session.provider === 'claude' ? 'Claude' : 'OpenCode'}
|
{session.provider === 'claude' ? 'Claude' : session.provider === 'opencode' ? 'OpenCode' : 'Pi'}
|
||||||
</span>
|
</span>
|
||||||
<span className="ml-2 font-mono text-duck-dark/25 dark:text-foreground/25">
|
<span className="ml-2 font-mono text-duck-dark/25 dark:text-foreground/25">
|
||||||
{session.id.slice(0, 8)}
|
{session.id.slice(0, 8)}
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ const layout: LayoutNode = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
type SessionListPageProps = {
|
type SessionListPageProps = {
|
||||||
provider?: 'claude' | 'opencode';
|
provider?: 'claude' | 'opencode' | 'pi-mono';
|
||||||
isNew?: boolean;
|
isNew?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,9 @@ import { cardStyle } from '@/components/Card';
|
|||||||
import type { TaskInfo } from 'apps/Chat';
|
import type { TaskInfo } from 'apps/Chat';
|
||||||
import { useClaude } from '@/Screens/Dashboard/Chat/useClaude';
|
import { useClaude } from '@/Screens/Dashboard/Chat/useClaude';
|
||||||
import { useOpenCode } from '@/Screens/Dashboard/Chat/useOpenCode';
|
import { useOpenCode } from '@/Screens/Dashboard/Chat/useOpenCode';
|
||||||
|
import { usePiMono } from '@/Screens/Dashboard/Chat/usePiMono';
|
||||||
import { EmbeddableChat } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
import { EmbeddableChat } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
||||||
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';
|
import { useVisibleClaudeModels, useVisibleOpenCodeModels, useVisiblePiMonoModels } from '@/state/useModels';
|
||||||
import { useSettings } from '@/state/useSettings';
|
import { useSettings } from '@/state/useSettings';
|
||||||
import type { TaskSummary } from 'apps/FileBrowser';
|
import type { TaskSummary } from 'apps/FileBrowser';
|
||||||
|
|
||||||
@@ -39,7 +40,7 @@ type InnerProps = {
|
|||||||
defaultInput: string;
|
defaultInput: string;
|
||||||
cwd: { root?: string; path: string };
|
cwd: { root?: string; path: string };
|
||||||
initialModel: string | null;
|
initialModel: string | null;
|
||||||
onProviderChange: (p: 'claude' | 'opencode') => void;
|
onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const ClaudeInner = ({
|
const ClaudeInner = ({
|
||||||
@@ -100,6 +101,35 @@ const OpenCodeInner = ({
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const PiMonoInner = ({
|
||||||
|
defaultInput,
|
||||||
|
cwd,
|
||||||
|
initialModel,
|
||||||
|
onProviderChange,
|
||||||
|
taskInfo,
|
||||||
|
}: InnerProps & { taskInfo: TaskInfo }) => {
|
||||||
|
const chat = usePiMono(undefined, initialModel, { replaceUrl: false, taskInfo });
|
||||||
|
const models = useVisiblePiMonoModels();
|
||||||
|
|
||||||
|
const wasGenerating = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (wasGenerating.current && !chat.isGenerating) playDing();
|
||||||
|
wasGenerating.current = chat.isGenerating;
|
||||||
|
}, [chat.isGenerating]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<EmbeddableChat
|
||||||
|
chat={chat}
|
||||||
|
provider="pi-mono"
|
||||||
|
availableModels={models}
|
||||||
|
onProviderChange={onProviderChange}
|
||||||
|
defaultInput={defaultInput}
|
||||||
|
cwd={cwd}
|
||||||
|
className="flex-1 min-h-0"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
type TaskRunnerModalProps = {
|
type TaskRunnerModalProps = {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
@@ -113,7 +143,7 @@ type TaskRunnerModalProps = {
|
|||||||
export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryType, cwd = { path: '' }, promptOverride }: TaskRunnerModalProps) => {
|
export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryType, cwd = { path: '' }, promptOverride }: TaskRunnerModalProps) => {
|
||||||
const { settings } = useSettings();
|
const { settings } = useSettings();
|
||||||
const taskSettings = settings.tasks;
|
const taskSettings = settings.tasks;
|
||||||
const [provider, setProvider] = useState<'claude' | 'opencode'>(taskSettings.defaultProvider);
|
const [provider, setProvider] = useState<'claude' | 'opencode' | 'pi-mono'>(taskSettings.defaultProvider);
|
||||||
const defaultInput = promptOverride
|
const defaultInput = promptOverride
|
||||||
?? (entryName && entryType
|
?? (entryName && entryType
|
||||||
? `Read the task instructions at ${task.filePath} and execute them on the ${entryType}: ${entryName}`
|
? `Read the task instructions at ${task.filePath} and execute them on the ${entryType}: ${entryName}`
|
||||||
@@ -150,7 +180,7 @@ export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryType
|
|||||||
onProviderChange={setProvider}
|
onProviderChange={setProvider}
|
||||||
taskInfo={taskInfo}
|
taskInfo={taskInfo}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : provider === 'opencode' ? (
|
||||||
<OpenCodeInner
|
<OpenCodeInner
|
||||||
key="opencode"
|
key="opencode"
|
||||||
defaultInput={defaultInput}
|
defaultInput={defaultInput}
|
||||||
@@ -159,6 +189,15 @@ export const TaskRunnerModal = ({ open, onOpenChange, task, entryName, entryType
|
|||||||
onProviderChange={setProvider}
|
onProviderChange={setProvider}
|
||||||
taskInfo={taskInfo}
|
taskInfo={taskInfo}
|
||||||
/>
|
/>
|
||||||
|
) : (
|
||||||
|
<PiMonoInner
|
||||||
|
key="pi-mono"
|
||||||
|
defaultInput={defaultInput}
|
||||||
|
cwd={cwd}
|
||||||
|
initialModel={taskSettings.defaultProvider === 'pi-mono' ? taskSettings.defaultModel : null}
|
||||||
|
onProviderChange={setProvider}
|
||||||
|
taskInfo={taskInfo}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</DialogPrimitive.Content>
|
</DialogPrimitive.Content>
|
||||||
</DialogPortal>
|
</DialogPortal>
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { useSettings } from '@/state/useSettings';
|
import { useSettings } from '@/state/useSettings';
|
||||||
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';
|
import { useVisibleClaudeModels, useVisibleOpenCodeModels, useVisiblePiMonoModels } from '@/state/useModels';
|
||||||
import type { Attachment } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
import type { Attachment } from '@/Screens/Dashboard/Chat/EmbeddableChat';
|
||||||
|
|
||||||
export const ChatLauncher = () => {
|
export const ChatLauncher = () => {
|
||||||
@@ -31,9 +31,10 @@ export const ChatLauncher = () => {
|
|||||||
const { settings } = useSettings();
|
const { settings } = useSettings();
|
||||||
const claudeModels = useVisibleClaudeModels();
|
const claudeModels = useVisibleClaudeModels();
|
||||||
const openCodeModels = useVisibleOpenCodeModels();
|
const openCodeModels = useVisibleOpenCodeModels();
|
||||||
|
const piMonoModels = useVisiblePiMonoModels();
|
||||||
|
|
||||||
const client = useClient();
|
const client = useClient();
|
||||||
const [provider, setProvider] = useState<'claude' | 'opencode'>(settings.chat.defaultProvider);
|
const [provider, setProvider] = useState<'claude' | 'opencode' | 'pi-mono'>(settings.chat.defaultProvider);
|
||||||
const [model, setModel] = useState<string | null>(settings.chat.defaultModel);
|
const [model, setModel] = useState<string | null>(settings.chat.defaultModel);
|
||||||
const [input, setInput] = useState('');
|
const [input, setInput] = useState('');
|
||||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||||
@@ -47,7 +48,7 @@ export const ChatLauncher = () => {
|
|||||||
setModel(settings.chat.defaultModel);
|
setModel(settings.chat.defaultModel);
|
||||||
}, [settings.chat.defaultProvider, settings.chat.defaultModel]);
|
}, [settings.chat.defaultProvider, settings.chat.defaultModel]);
|
||||||
|
|
||||||
const models = provider === 'claude' ? claudeModels : openCodeModels;
|
const models = provider === 'claude' ? claudeModels : provider === 'opencode' ? openCodeModels : piMonoModels;
|
||||||
|
|
||||||
const handleAttachWebpage = async (url: string) => {
|
const handleAttachWebpage = async (url: string) => {
|
||||||
const idx = attachments.length;
|
const idx = attachments.length;
|
||||||
@@ -124,7 +125,8 @@ export const ChatLauncher = () => {
|
|||||||
attachmentIds.push(a.attachmentId);
|
attachmentIds.push(a.attachmentId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const route = provider === 'claude' ? '/chat/new' : '/chat/opencode/new';
|
const route =
|
||||||
|
provider === 'claude' ? '/chat/new' : provider === 'opencode' ? '/chat/opencode/new' : '/chat/pi-mono/new';
|
||||||
navigate(route, {
|
navigate(route, {
|
||||||
state: {
|
state: {
|
||||||
initialMessage: prompt,
|
initialMessage: prompt,
|
||||||
@@ -257,7 +259,7 @@ export const ChatLauncher = () => {
|
|||||||
|
|
||||||
<div className="flex items-center justify-between px-4 pb-3">
|
<div className="flex items-center justify-between px-4 pb-3">
|
||||||
<div className="flex items-center gap-1 rounded-lg bg-duck-dark/5 p-1">
|
<div className="flex items-center gap-1 rounded-lg bg-duck-dark/5 p-1">
|
||||||
{(['claude', 'opencode'] as const).map((value) => (
|
{(['claude', 'opencode', 'pi-mono'] as const).map((value) => (
|
||||||
<button
|
<button
|
||||||
key={value}
|
key={value}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -270,7 +272,7 @@ export const ChatLauncher = () => {
|
|||||||
: 'text-duck-dark/50 hover:text-duck-dark/70'
|
: 'text-duck-dark/50 hover:text-duck-dark/70'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{value === 'claude' ? 'Claude' : 'OpenCode'}
|
{value === 'claude' ? 'Claude' : value === 'opencode' ? 'OpenCode' : 'Pi'}
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Link } from 'react-router';
|
import { Link } from 'react-router';
|
||||||
import * as Dropdown from '@/components/ui/dropdown-menu';
|
import * as Dropdown from '@/components/ui/dropdown-menu';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
import { User, LogOut, Server, Package, Bot, Sun, Moon } from 'lucide-react';
|
import { User, LogOut, Settings, Package, Sun, Moon } from 'lucide-react';
|
||||||
import { useAuth } from 'hooks/useAuth';
|
import { useAuth } from 'hooks/useAuth';
|
||||||
import { useTranslation } from '@/lib/i18n';
|
import { useTranslation } from '@/lib/i18n';
|
||||||
import { useColorMode } from '@/components/ui/ThemeProvider';
|
import { useColorMode } from '@/components/ui/ThemeProvider';
|
||||||
@@ -42,15 +42,9 @@ export function UserMenu() {
|
|||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild className="cursor-pointer">
|
<DropdownMenuItem asChild className="cursor-pointer">
|
||||||
<Link to="/settings/ai">
|
<Link to="/settings/system">
|
||||||
<Bot className="mr-2 h-4 w-4" />
|
<Settings className="mr-2 h-4 w-4" />
|
||||||
{t('header.userMenu.aiSettings')}
|
{t('header.userMenu.systemSettings')}
|
||||||
</Link>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem asChild className="cursor-pointer">
|
|
||||||
<Link to="/settings/server">
|
|
||||||
<Server className="mr-2 h-4 w-4" />
|
|
||||||
{t('header.userMenu.serverSettings')}
|
|
||||||
</Link>
|
</Link>
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem asChild className="cursor-pointer">
|
<DropdownMenuItem asChild className="cursor-pointer">
|
||||||
|
|||||||
@@ -12,12 +12,13 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/components/ui/select';
|
} from '@/components/ui/select';
|
||||||
import { useSettings } from '@/state/useSettings';
|
import { useSettings } from '@/state/useSettings';
|
||||||
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';
|
import { useVisibleClaudeModels, useVisibleOpenCodeModels, useVisiblePiMonoModels } from '@/state/useModels';
|
||||||
|
|
||||||
export const TaskDefaults = () => {
|
export const TaskDefaults = () => {
|
||||||
const { settings, saveSettings } = useSettings();
|
const { settings, saveSettings } = useSettings();
|
||||||
const claudeModels = useVisibleClaudeModels();
|
const claudeModels = useVisibleClaudeModels();
|
||||||
const openCodeModels = useVisibleOpenCodeModels();
|
const openCodeModels = useVisibleOpenCodeModels();
|
||||||
|
const piMonoModels = useVisiblePiMonoModels();
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
|
||||||
const [model, setModel] = useState<string | null>(settings.tasks.defaultModel);
|
const [model, setModel] = useState<string | null>(settings.tasks.defaultModel);
|
||||||
@@ -26,24 +27,28 @@ export const TaskDefaults = () => {
|
|||||||
setModel(settings.tasks.defaultModel);
|
setModel(settings.tasks.defaultModel);
|
||||||
}, [settings]);
|
}, [settings]);
|
||||||
|
|
||||||
const openCodeGroups = useMemo(() => {
|
const buildGroups = (models: { id: string; name: string; provider?: string }[], fallback: string) => {
|
||||||
const groups: Record<string, { id: string; name: string }[]> = {};
|
const groups: Record<string, { id: string; name: string }[]> = {};
|
||||||
for (const m of openCodeModels) {
|
for (const m of models) {
|
||||||
const provider = m.provider ?? 'OpenCode';
|
const provider = m.provider ?? fallback;
|
||||||
if (!groups[provider]) groups[provider] = [];
|
if (!groups[provider]) groups[provider] = [];
|
||||||
groups[provider].push({ id: m.id, name: m.name });
|
groups[provider].push({ id: m.id, name: m.name });
|
||||||
}
|
}
|
||||||
return Object.entries(groups)
|
return Object.entries(groups)
|
||||||
.sort(([a], [b]) => a.localeCompare(b))
|
.sort(([a], [b]) => a.localeCompare(b))
|
||||||
.map(([provider, models]) => ({ provider, models: models.sort((a, b) => a.name.localeCompare(b.name)) }));
|
.map(([provider, models]) => ({ provider, models: models.sort((a, b) => a.name.localeCompare(b.name)) }));
|
||||||
}, [openCodeModels]);
|
};
|
||||||
|
|
||||||
|
const openCodeGroups = useMemo(() => buildGroups(openCodeModels, 'OpenCode'), [openCodeModels]);
|
||||||
|
const piMonoGroups = useMemo(() => buildGroups(piMonoModels, 'Pi'), [piMonoModels]);
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (isSaving) return;
|
if (isSaving) return;
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
try {
|
try {
|
||||||
|
const isPiMono = piMonoModels.some((m) => m.id === model);
|
||||||
const isOpenCode = openCodeModels.some((m) => m.id === model);
|
const isOpenCode = openCodeModels.some((m) => m.id === model);
|
||||||
const defaultProvider = isOpenCode ? ('opencode' as const) : ('claude' as const);
|
const defaultProvider = isPiMono ? ('pi-mono' as const) : isOpenCode ? ('opencode' as const) : ('claude' as const);
|
||||||
await saveSettings({ ...settings, tasks: { defaultProvider, defaultModel: model } });
|
await saveSettings({ ...settings, tasks: { defaultProvider, defaultModel: model } });
|
||||||
toast.success('Task defaults saved');
|
toast.success('Task defaults saved');
|
||||||
} catch {
|
} catch {
|
||||||
@@ -82,6 +87,16 @@ export const TaskDefaults = () => {
|
|||||||
))}
|
))}
|
||||||
</SelectGroup>
|
</SelectGroup>
|
||||||
))}
|
))}
|
||||||
|
{piMonoGroups.map(({ provider, models }) => (
|
||||||
|
<SelectGroup key={`pi-${provider}`}>
|
||||||
|
<SelectLabel>{provider} (Pi)</SelectLabel>
|
||||||
|
{models.map((m) => (
|
||||||
|
<SelectItem key={`pi:${provider}:${m.id}`} value={m.id}>
|
||||||
|
{m.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectGroup>
|
||||||
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</Label>
|
</Label>
|
||||||
|
|||||||
+57
-2
@@ -14,9 +14,10 @@ export const AIHarnessesSection = () => {
|
|||||||
const client = useClient();
|
const client = useClient();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { aiHarnesses, saveSettings } = useServerSettings();
|
const { aiHarnesses, saveSettings } = useServerSettings();
|
||||||
const [installing, setInstalling] = useState<{ claudeCode: boolean; opencode: boolean }>({
|
const [installing, setInstalling] = useState<{ claudeCode: boolean; opencode: boolean; piMono: boolean }>({
|
||||||
claudeCode: false,
|
claudeCode: false,
|
||||||
opencode: false,
|
opencode: false,
|
||||||
|
piMono: false,
|
||||||
});
|
});
|
||||||
const [copied, setCopied] = useState<string | null>(null);
|
const [copied, setCopied] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -40,6 +41,16 @@ export const AIHarnessesSection = () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const { data: piMonoVersion, isLoading: piMonoLoading } = useQuery({
|
||||||
|
queryKey: ['PI_MONO_VERSION'],
|
||||||
|
queryFn: () => client.get<VersionInfo>('/server-settings/pi-mono/version'),
|
||||||
|
enabled: !!aiHarnesses?.piMono,
|
||||||
|
refetchInterval: (query) => {
|
||||||
|
const data = query.state.data;
|
||||||
|
return data?.version && !data?.globalPath ? 1000 : false;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const { data: opencodeAuth } = useQuery({
|
const { data: opencodeAuth } = useQuery({
|
||||||
queryKey: ['OPENCODE_AUTH'],
|
queryKey: ['OPENCODE_AUTH'],
|
||||||
queryFn: () => client.get<OpencodeAuthInfo>('/server-settings/opencode/auth'),
|
queryFn: () => client.get<OpencodeAuthInfo>('/server-settings/opencode/auth'),
|
||||||
@@ -54,7 +65,7 @@ export const AIHarnessesSection = () => {
|
|||||||
refetchInterval: (query) => (!query.state.data?.authenticated ? 2000 : false),
|
refetchInterval: (query) => (!query.state.data?.authenticated ? 2000 : false),
|
||||||
});
|
});
|
||||||
|
|
||||||
const toggleHarness = (key: 'claudeCode' | 'opencode', checked: boolean) => {
|
const toggleHarness = (key: 'claudeCode' | 'opencode' | 'piMono', checked: boolean) => {
|
||||||
const updated = { ...aiHarnesses, [key]: checked };
|
const updated = { ...aiHarnesses, [key]: checked };
|
||||||
saveSettings({ aiHarnesses: updated });
|
saveSettings({ aiHarnesses: updated });
|
||||||
};
|
};
|
||||||
@@ -79,6 +90,16 @@ export const AIHarnessesSection = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const installPiMono = async () => {
|
||||||
|
setInstalling((prev) => ({ ...prev, piMono: true }));
|
||||||
|
try {
|
||||||
|
const result = await client.post<VersionInfo>('/server-settings/pi-mono/install');
|
||||||
|
queryClient.setQueryData(['PI_MONO_VERSION'], result);
|
||||||
|
} finally {
|
||||||
|
setInstalling((prev) => ({ ...prev, piMono: false }));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const copyToClipboard = (text: string) => {
|
const copyToClipboard = (text: string) => {
|
||||||
navigator.clipboard.writeText(text);
|
navigator.clipboard.writeText(text);
|
||||||
setCopied(text);
|
setCopied(text);
|
||||||
@@ -210,6 +231,40 @@ export const AIHarnessesSection = () => {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="flex items-center gap-3 cursor-pointer">
|
||||||
|
<Checkbox
|
||||||
|
checked={!!aiHarnesses?.piMono}
|
||||||
|
onCheckedChange={(checked) => toggleHarness('piMono', !!checked)}
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium text-duck-dark">Pi</span>
|
||||||
|
</label>
|
||||||
|
{aiHarnesses?.piMono && (
|
||||||
|
<div className="ml-7 mt-2 text-xs text-duck-dark/50">
|
||||||
|
{piMonoLoading ? (
|
||||||
|
'Checking version...'
|
||||||
|
) : piMonoVersion?.version ? (
|
||||||
|
<>
|
||||||
|
<div>{piMonoVersion.version}</div>
|
||||||
|
<div>{piMonoVersion.path}</div>
|
||||||
|
{!piMonoVersion.globalPath && piMonoVersion.path && (
|
||||||
|
<CopyCommand command={`sudo ln -s ${piMonoVersion.path} /usr/local/bin/pi`} />
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
className="bg-duck-teal text-duck-yellow hover:bg-duck-teal/90"
|
||||||
|
onClick={installPiMono}
|
||||||
|
disabled={installing.piMono}
|
||||||
|
>
|
||||||
|
{installing.piMono ? 'Installing...' : 'Install'}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,46 +0,0 @@
|
|||||||
import { useMemo } from 'react';
|
|
||||||
import { Terminal, Server } from 'lucide-react';
|
|
||||||
import type { LayoutNode, PanelComponents } from '@/components/Workspace';
|
|
||||||
import { WorkspaceLayout } from '@/components/Workspace';
|
|
||||||
import { appRegistry } from '../../Workspaces/app-registry';
|
|
||||||
import { createSettingsPanelComponents, type SettingsSection } from '../SettingsPanel';
|
|
||||||
import { AIHarnessesSection } from './AIHarnessesSection';
|
|
||||||
|
|
||||||
const GLOBAL_KEY = 'SERVER_SETTINGS_SELECTED';
|
|
||||||
|
|
||||||
const sections: SettingsSection[] = [
|
|
||||||
{ key: 'ai-harnesses', icon: Terminal, title: 'AI Harnesses', description: 'AI coding tools setup', content: <AIHarnessesSection /> },
|
|
||||||
];
|
|
||||||
|
|
||||||
const { Sidebar, Content } = createSettingsPanelComponents({
|
|
||||||
globalKey: GLOBAL_KEY,
|
|
||||||
sidebarIcon: Server,
|
|
||||||
sidebarLabel: 'Server',
|
|
||||||
sections,
|
|
||||||
});
|
|
||||||
|
|
||||||
const layout: LayoutNode = {
|
|
||||||
type: 'group',
|
|
||||||
id: 'server-root',
|
|
||||||
direction: 'horizontal',
|
|
||||||
children: [
|
|
||||||
{ node: { type: 'panel', id: 'server-left', appType: null }, size: 20 },
|
|
||||||
{ node: { type: 'panel', id: 'server-right', appType: null }, size: 80 },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ServerSettings = () => {
|
|
||||||
const panelComponents: PanelComponents = useMemo(
|
|
||||||
() => ({
|
|
||||||
'server-left': Sidebar,
|
|
||||||
'server-right': Content,
|
|
||||||
}),
|
|
||||||
[],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="h-full w-full pt-2">
|
|
||||||
<WorkspaceLayout layout={layout} onLayoutChange={() => {}} registry={appRegistry} components={panelComponents} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -12,21 +12,52 @@ export type SettingsSection = {
|
|||||||
content: ReactNode;
|
content: ReactNode;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type SettingsSectionGroup = {
|
||||||
|
label: string;
|
||||||
|
icon: LucideIcon;
|
||||||
|
sections: SettingsSection[];
|
||||||
|
};
|
||||||
|
|
||||||
type SettingsSidebarProps = {
|
type SettingsSidebarProps = {
|
||||||
globalKey: string;
|
globalKey: string;
|
||||||
icon: LucideIcon;
|
icon: LucideIcon;
|
||||||
label: string;
|
label: string;
|
||||||
sections: SettingsSection[];
|
sections: SettingsSection[];
|
||||||
|
groups?: SettingsSectionGroup[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export const SettingsSidebar = ({ globalKey, icon: Icon, label, sections }: SettingsSidebarProps) => {
|
const SectionButton = ({
|
||||||
const [selectedKey, setSelectedKey] = useGlobal<string | null>(globalKey, sections[0]?.key ?? null);
|
section,
|
||||||
|
isActive,
|
||||||
|
onClick,
|
||||||
|
}: {
|
||||||
|
section: SettingsSection;
|
||||||
|
isActive: boolean;
|
||||||
|
onClick: () => void;
|
||||||
|
}) => (
|
||||||
|
<button
|
||||||
|
key={section.key}
|
||||||
|
onClick={onClick}
|
||||||
|
className={`flex items-start gap-2.5 py-2 px-3 rounded-lg text-left cursor-pointer transition-colors ${
|
||||||
|
isActive ? 'bg-duck-teal/10 text-duck-dark dark:text-foreground' : 'text-duck-dark/70 dark:text-foreground/70 hover:bg-duck-dark/5 dark:hover:bg-foreground/5 hover:text-duck-dark dark:hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<section.icon className={`h-3.5 w-3.5 shrink-0 mt-0.5 ${isActive ? 'text-duck-teal' : 'text-duck-dark/40 dark:text-foreground/40'}`} />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="text-sm font-medium truncate">{section.title}</div>
|
||||||
|
<div className="text-xs text-duck-dark/40 dark:text-foreground/40 truncate">{section.description}</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
|
||||||
|
export const SettingsSidebar = ({ globalKey, icon: Icon, label, sections, groups }: SettingsSidebarProps) => {
|
||||||
|
const allSections = groups ? groups.flatMap((g) => g.sections) : sections;
|
||||||
|
const [selectedKey, setSelectedKey] = useGlobal<string | null>(globalKey, allSections[0]?.key ?? null);
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
|
|
||||||
const query = search.toLowerCase();
|
const query = search.toLowerCase();
|
||||||
const filtered = sections.filter(
|
const matchesSearch = (s: SettingsSection) =>
|
||||||
(s) => s.title.toLowerCase().includes(query) || s.description.toLowerCase().includes(query),
|
s.title.toLowerCase().includes(query) || s.description.toLowerCase().includes(query);
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full overflow-y-auto">
|
<div className="flex flex-col h-full overflow-y-auto">
|
||||||
@@ -40,24 +71,37 @@ export const SettingsSidebar = ({ globalKey, icon: Icon, label, sections }: Sett
|
|||||||
<Input placeholder="Search..." value={search} onChange={(ev) => setSearch(ev.target.value)} className="h-8 text-xs" />
|
<Input placeholder="Search..." value={search} onChange={(ev) => setSearch(ev.target.value)} className="h-8 text-xs" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-0.5 px-3 overflow-y-auto flex-1">
|
<div className="flex flex-col gap-0.5 px-3 overflow-y-auto flex-1">
|
||||||
{filtered.map((s) => {
|
{groups
|
||||||
const isActive = selectedKey === s.key;
|
? groups.map((group) => {
|
||||||
return (
|
const filtered = group.sections.filter(matchesSearch);
|
||||||
<button
|
if (filtered.length === 0) return null;
|
||||||
key={s.key}
|
return (
|
||||||
onClick={() => setSelectedKey(s.key)}
|
<div key={group.label}>
|
||||||
className={`flex items-start gap-2.5 py-2 px-3 rounded-lg text-left cursor-pointer transition-colors ${
|
<div className="flex items-center gap-2 px-3 pt-3 pb-1">
|
||||||
isActive ? 'bg-duck-teal/10 text-duck-dark dark:text-foreground' : 'text-duck-dark/70 dark:text-foreground/70 hover:bg-duck-dark/5 dark:hover:bg-foreground/5 hover:text-duck-dark dark:hover:text-foreground'
|
<group.icon className="h-3 w-3 text-duck-dark/30 dark:text-foreground/30" />
|
||||||
}`}
|
<span className="text-[11px] font-semibold uppercase tracking-wider text-duck-dark/30 dark:text-foreground/30">
|
||||||
>
|
{group.label}
|
||||||
<s.icon className={`h-3.5 w-3.5 shrink-0 mt-0.5 ${isActive ? 'text-duck-teal' : 'text-duck-dark/40 dark:text-foreground/40'}`} />
|
</span>
|
||||||
<div className="min-w-0 flex-1">
|
</div>
|
||||||
<div className="text-sm font-medium truncate">{s.title}</div>
|
{filtered.map((s) => (
|
||||||
<div className="text-xs text-duck-dark/40 dark:text-foreground/40 truncate">{s.description}</div>
|
<SectionButton
|
||||||
</div>
|
key={s.key}
|
||||||
</button>
|
section={s}
|
||||||
);
|
isActive={selectedKey === s.key}
|
||||||
})}
|
onClick={() => setSelectedKey(s.key)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
: sections.filter(matchesSearch).map((s) => (
|
||||||
|
<SectionButton
|
||||||
|
key={s.key}
|
||||||
|
section={s}
|
||||||
|
isActive={selectedKey === s.key}
|
||||||
|
onClick={() => setSelectedKey(s.key)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -96,13 +140,15 @@ type CreateSettingsPanelParams = {
|
|||||||
globalKey: string;
|
globalKey: string;
|
||||||
sidebarIcon: LucideIcon;
|
sidebarIcon: LucideIcon;
|
||||||
sidebarLabel: string;
|
sidebarLabel: string;
|
||||||
sections: SettingsSection[];
|
sections?: SettingsSection[];
|
||||||
|
groups?: SettingsSectionGroup[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createSettingsPanelComponents = ({ globalKey, sidebarIcon, sidebarLabel, sections }: CreateSettingsPanelParams) => {
|
export const createSettingsPanelComponents = ({ globalKey, sidebarIcon, sidebarLabel, sections = [], groups }: CreateSettingsPanelParams) => {
|
||||||
|
const allSections = groups ? groups.flatMap((g) => g.sections) : sections;
|
||||||
const Sidebar: ComponentType = () => (
|
const Sidebar: ComponentType = () => (
|
||||||
<SettingsSidebar globalKey={globalKey} icon={sidebarIcon} label={sidebarLabel} sections={sections} />
|
<SettingsSidebar globalKey={globalKey} icon={sidebarIcon} label={sidebarLabel} sections={allSections} groups={groups} />
|
||||||
);
|
);
|
||||||
const Content: ComponentType = () => <SettingsContent globalKey={globalKey} sections={sections} />;
|
const Content: ComponentType = () => <SettingsContent globalKey={globalKey} sections={allSections} />;
|
||||||
return { Sidebar, Content };
|
return { Sidebar, Content };
|
||||||
};
|
};
|
||||||
|
|||||||
+175
-79
@@ -1,6 +1,6 @@
|
|||||||
import { useState, useEffect, useMemo } from 'react';
|
import { useState, useEffect, useMemo } from 'react';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { Terminal, Eye, Trash2, Bot } from 'lucide-react';
|
import { Terminal, Eye, Trash2, Bot, Server, Puzzle, Settings } from 'lucide-react';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@@ -13,46 +13,62 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
|||||||
import type { LayoutNode, PanelComponents } from '@/components/Workspace';
|
import type { LayoutNode, PanelComponents } from '@/components/Workspace';
|
||||||
import { WorkspaceLayout } from '@/components/Workspace';
|
import { WorkspaceLayout } from '@/components/Workspace';
|
||||||
import { appRegistry } from '../Workspaces/app-registry';
|
import { appRegistry } from '../Workspaces/app-registry';
|
||||||
import { createSettingsPanelComponents, type SettingsSection } from './SettingsPanel';
|
import { createSettingsPanelComponents, type SettingsSectionGroup } from './SettingsPanel';
|
||||||
import { useSettings } from '@/state/useSettings';
|
import { useSettings } from '@/state/useSettings';
|
||||||
import { useUserState } from '@/state/useUserState';
|
import { useUserState } from '@/state/useUserState';
|
||||||
import {
|
import {
|
||||||
useClaudeModels,
|
useClaudeModels,
|
||||||
useOpenCodeModels,
|
useOpenCodeModels,
|
||||||
|
usePiMonoModels,
|
||||||
useVisibleClaudeModels,
|
useVisibleClaudeModels,
|
||||||
useVisibleOpenCodeModels,
|
useVisibleOpenCodeModels,
|
||||||
|
useVisiblePiMonoModels,
|
||||||
} from '@/state/useModels';
|
} from '@/state/useModels';
|
||||||
import type { UserSettings } from '@/state/types/user-settings';
|
import type { UserSettings } from '@/state/types/user-settings';
|
||||||
|
import { AIHarnessesSection } from './ServerSettings/AIHarnessesSection';
|
||||||
|
import { PluginsSection } from './ServerSettings/PluginsSection';
|
||||||
|
|
||||||
const GLOBAL_KEY = 'AI_SETTINGS_SELECTED';
|
const groups: SettingsSectionGroup[] = [
|
||||||
|
{
|
||||||
const sections: SettingsSection[] = [
|
label: 'Server',
|
||||||
{ key: 'chat-defaults', icon: Terminal, title: 'Chat Defaults', description: 'Model, prompt, and temperature', content: <ChatDefaultsSection /> },
|
icon: Server,
|
||||||
{ key: 'model-visibility', icon: Eye, title: 'Model Visibility', description: 'Enable or disable models', content: <ModelVisibilitySection /> },
|
sections: [
|
||||||
|
{ key: 'ai-harnesses', icon: Terminal, title: 'AI Harnesses', description: 'AI coding tools setup', content: <AIHarnessesSection /> },
|
||||||
|
{ key: 'plugins', icon: Puzzle, title: 'Plugins', description: 'Enable or disable plugins', content: <PluginsSection /> },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'AI',
|
||||||
|
icon: Bot,
|
||||||
|
sections: [
|
||||||
|
{ key: 'chat-defaults', icon: Terminal, title: 'Chat Defaults', description: 'Model, prompt, and temperature', content: <ChatDefaultsSection /> },
|
||||||
|
{ key: 'model-visibility', icon: Eye, title: 'Model Visibility', description: 'Enable or disable models', content: <ModelVisibilitySection /> },
|
||||||
|
],
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const { Sidebar, Content } = createSettingsPanelComponents({
|
const { Sidebar, Content } = createSettingsPanelComponents({
|
||||||
globalKey: GLOBAL_KEY,
|
globalKey: 'SYSTEM_SETTINGS_SELECTED',
|
||||||
sidebarIcon: Bot,
|
sidebarIcon: Settings,
|
||||||
sidebarLabel: 'AI',
|
sidebarLabel: 'System',
|
||||||
sections,
|
groups,
|
||||||
});
|
});
|
||||||
|
|
||||||
const layout: LayoutNode = {
|
const layout: LayoutNode = {
|
||||||
type: 'group',
|
type: 'group',
|
||||||
id: 'ai-root',
|
id: 'system-root',
|
||||||
direction: 'horizontal',
|
direction: 'horizontal',
|
||||||
children: [
|
children: [
|
||||||
{ node: { type: 'panel', id: 'ai-left', appType: null }, size: 20 },
|
{ node: { type: 'panel', id: 'system-left', appType: null }, size: 20 },
|
||||||
{ node: { type: 'panel', id: 'ai-right', appType: null }, size: 80 },
|
{ node: { type: 'panel', id: 'system-right', appType: null }, size: 80 },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
export const AISettings = () => {
|
export const SystemSettings = () => {
|
||||||
const panelComponents: PanelComponents = useMemo(
|
const panelComponents: PanelComponents = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
'ai-left': Sidebar,
|
'system-left': Sidebar,
|
||||||
'ai-right': Content,
|
'system-right': Content,
|
||||||
}),
|
}),
|
||||||
[],
|
[],
|
||||||
);
|
);
|
||||||
@@ -64,10 +80,13 @@ export const AISettings = () => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- AI sections ---
|
||||||
|
|
||||||
function ChatDefaultsSection() {
|
function ChatDefaultsSection() {
|
||||||
const { settings, saveSettings } = useSettings();
|
const { settings, saveSettings } = useSettings();
|
||||||
const claudeModels = useVisibleClaudeModels();
|
const claudeModels = useVisibleClaudeModels();
|
||||||
const openCodeModels = useVisibleOpenCodeModels();
|
const openCodeModels = useVisibleOpenCodeModels();
|
||||||
|
const piMonoModels = useVisiblePiMonoModels();
|
||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
|
||||||
const [model, setModel] = useState<string | null>(settings.chat.defaultModel);
|
const [model, setModel] = useState<string | null>(settings.chat.defaultModel);
|
||||||
@@ -86,16 +105,18 @@ function ChatDefaultsSection() {
|
|||||||
() => [
|
() => [
|
||||||
...claudeModels.map((m) => ({ ...m, provider: 'Claude' })),
|
...claudeModels.map((m) => ({ ...m, provider: 'Claude' })),
|
||||||
...openCodeModels.map((m) => ({ ...m, provider: m.provider ?? 'OpenCode' })),
|
...openCodeModels.map((m) => ({ ...m, provider: m.provider ?? 'OpenCode' })),
|
||||||
|
...piMonoModels.map((m) => ({ ...m, provider: m.provider ?? 'Pi' })),
|
||||||
],
|
],
|
||||||
[claudeModels, openCodeModels],
|
[claudeModels, openCodeModels, piMonoModels],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = async () => {
|
||||||
if (isSaving) return;
|
if (isSaving) return;
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
try {
|
try {
|
||||||
|
const isPiMono = piMonoModels.some((m) => m.id === model);
|
||||||
const isOpenCode = openCodeModels.some((m) => m.id === model);
|
const isOpenCode = openCodeModels.some((m) => m.id === model);
|
||||||
const defaultProvider = isOpenCode ? ('opencode' as const) : ('claude' as const);
|
const defaultProvider = isPiMono ? ('pi-mono' as const) : isOpenCode ? ('opencode' as const) : ('claude' as const);
|
||||||
const updated: UserSettings = {
|
const updated: UserSettings = {
|
||||||
...settings,
|
...settings,
|
||||||
chat: { defaultProvider, defaultModel: model, systemPrompt, temperature, defaultPwd },
|
chat: { defaultProvider, defaultModel: model, systemPrompt, temperature, defaultPwd },
|
||||||
@@ -172,7 +193,8 @@ function ModelVisibilitySection() {
|
|||||||
const { settings, saveSettings } = useSettings();
|
const { settings, saveSettings } = useSettings();
|
||||||
const claudeModels = useClaudeModels();
|
const claudeModels = useClaudeModels();
|
||||||
const openCodeModels = useOpenCodeModels();
|
const openCodeModels = useOpenCodeModels();
|
||||||
const [subTab, setSubTab] = useUserState('ai-settings-visibility-tab', 'opencode');
|
const piMonoModels = usePiMonoModels();
|
||||||
|
const [subTab, setSubTab] = useUserState('ai-settings-visibility-tab', 'claude');
|
||||||
|
|
||||||
const enabledModels = settings.ai?.enabledModels ?? [];
|
const enabledModels = settings.ai?.enabledModels ?? [];
|
||||||
const enabledProviders = settings.ai?.enabledProviders ?? [];
|
const enabledProviders = settings.ai?.enabledProviders ?? [];
|
||||||
@@ -183,9 +205,9 @@ function ModelVisibilitySection() {
|
|||||||
await saveSettings({ ...settings, ai: { ...settings.ai, enabledModels: newEnabled } });
|
await saveSettings({ ...settings, ai: { ...settings.ai, enabledModels: newEnabled } });
|
||||||
};
|
};
|
||||||
|
|
||||||
const ocGroups = useMemo(() => {
|
const buildProviderGroups = (models: { id: string; name: string; provider?: string }[]) => {
|
||||||
const groups: Record<string, { id: string; name: string }[]> = {};
|
const groups: Record<string, { id: string; name: string }[]> = {};
|
||||||
for (const m of openCodeModels) {
|
for (const m of models) {
|
||||||
const provider = m.provider ?? 'Other';
|
const provider = m.provider ?? 'Other';
|
||||||
if (!groups[provider]) groups[provider] = [];
|
if (!groups[provider]) groups[provider] = [];
|
||||||
groups[provider].push({ id: m.id, name: m.name });
|
groups[provider].push({ id: m.id, name: m.name });
|
||||||
@@ -193,11 +215,16 @@ function ModelVisibilitySection() {
|
|||||||
return Object.entries(groups)
|
return Object.entries(groups)
|
||||||
.sort(([a], [b]) => a.localeCompare(b))
|
.sort(([a], [b]) => a.localeCompare(b))
|
||||||
.map(([provider, models]) => ({ provider, models: models.sort((a, b) => a.name.localeCompare(b.name)) }));
|
.map(([provider, models]) => ({ provider, models: models.sort((a, b) => a.name.localeCompare(b.name)) }));
|
||||||
}, [openCodeModels]);
|
};
|
||||||
|
|
||||||
|
const ocGroups = useMemo(() => buildProviderGroups(openCodeModels), [openCodeModels]);
|
||||||
|
const piGroups = useMemo(() => buildProviderGroups(piMonoModels), [piMonoModels]);
|
||||||
|
|
||||||
const [addingProvider, setAddingProvider] = useState(false);
|
const [addingProvider, setAddingProvider] = useState(false);
|
||||||
const [selectedNewProvider, setSelectedNewProvider] = useState<string>('');
|
const [selectedNewProvider, setSelectedNewProvider] = useState<string>('');
|
||||||
const disabledProviders = ocGroups.filter((g) => !enabledProviders.includes(g.provider));
|
|
||||||
|
const currentGroups = subTab === 'opencode' ? ocGroups : piGroups;
|
||||||
|
const disabledProviders = currentGroups.filter((g) => !enabledProviders.includes(g.provider));
|
||||||
|
|
||||||
const handleEnableProvider = async () => {
|
const handleEnableProvider = async () => {
|
||||||
if (!selectedNewProvider) return;
|
if (!selectedNewProvider) return;
|
||||||
@@ -219,11 +246,14 @@ function ModelVisibilitySection() {
|
|||||||
return (
|
return (
|
||||||
<Tabs value={subTab} onValueChange={setSubTab}>
|
<Tabs value={subTab} onValueChange={setSubTab}>
|
||||||
<TabsList className="w-full mb-4">
|
<TabsList className="w-full mb-4">
|
||||||
|
<TabsTrigger value="claude" className="flex-1 cursor-pointer">
|
||||||
|
Claude
|
||||||
|
</TabsTrigger>
|
||||||
<TabsTrigger value="opencode" className="flex-1 cursor-pointer">
|
<TabsTrigger value="opencode" className="flex-1 cursor-pointer">
|
||||||
OpenCode
|
OpenCode
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="claude" className="flex-1 cursor-pointer">
|
<TabsTrigger value="pi-mono" className="flex-1 cursor-pointer">
|
||||||
Claude
|
Pi
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
@@ -242,63 +272,129 @@ function ModelVisibilitySection() {
|
|||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="opencode">
|
<TabsContent value="opencode">
|
||||||
<div className="flex justify-end items-center gap-2 mb-3">
|
<ProviderGroupTab
|
||||||
{addingProvider ? (
|
groups={ocGroups}
|
||||||
<>
|
enabledProviders={enabledProviders}
|
||||||
<Select value={selectedNewProvider} onValueChange={setSelectedNewProvider}>
|
enabledModels={enabledModels}
|
||||||
<SelectTrigger className="h-9 flex-1 bg-background/60 border-duck-dark/20 text-duck-dark text-sm">
|
disabledProviders={disabledProviders}
|
||||||
<SelectValue placeholder="Select provider..." />
|
addingProvider={addingProvider}
|
||||||
</SelectTrigger>
|
selectedNewProvider={selectedNewProvider}
|
||||||
<SelectContent className="z-[600]">
|
emptyLabel="No OpenCode models available."
|
||||||
{disabledProviders.map((g) => (
|
onSetAddingProvider={setAddingProvider}
|
||||||
<SelectItem key={g.provider} value={g.provider}>
|
onSetSelectedNewProvider={setSelectedNewProvider}
|
||||||
{g.provider}
|
onEnableProvider={handleEnableProvider}
|
||||||
</SelectItem>
|
onToggleModel={toggleModel}
|
||||||
))}
|
onRemoveProvider={handleRemoveProvider}
|
||||||
</SelectContent>
|
/>
|
||||||
</Select>
|
</TabsContent>
|
||||||
<Button
|
|
||||||
type="button"
|
<TabsContent value="pi-mono">
|
||||||
size="sm"
|
<ProviderGroupTab
|
||||||
disabled={!selectedNewProvider}
|
groups={piGroups}
|
||||||
onClick={handleEnableProvider}
|
enabledProviders={enabledProviders}
|
||||||
className="cursor-pointer bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold disabled:opacity-50"
|
enabledModels={enabledModels}
|
||||||
>
|
disabledProviders={subTab === 'pi-mono' ? piGroups.filter((g) => !enabledProviders.includes(g.provider)) : disabledProviders}
|
||||||
Enable
|
addingProvider={addingProvider}
|
||||||
</Button>
|
selectedNewProvider={selectedNewProvider}
|
||||||
</>
|
emptyLabel="No Pi models available."
|
||||||
) : (
|
onSetAddingProvider={setAddingProvider}
|
||||||
<Button
|
onSetSelectedNewProvider={setSelectedNewProvider}
|
||||||
type="button"
|
onEnableProvider={handleEnableProvider}
|
||||||
variant="outline"
|
onToggleModel={toggleModel}
|
||||||
size="sm"
|
onRemoveProvider={handleRemoveProvider}
|
||||||
className="cursor-pointer"
|
/>
|
||||||
onClick={() => setAddingProvider(true)}
|
|
||||||
disabled={disabledProviders.length === 0}
|
|
||||||
>
|
|
||||||
Add Provider
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{ocGroups.length === 0 ? (
|
|
||||||
<p className="text-sm text-duck-dark/40">No OpenCode models available.</p>
|
|
||||||
) : (
|
|
||||||
<OpenCodeProviderList
|
|
||||||
groups={ocGroups}
|
|
||||||
enabledProviders={enabledProviders}
|
|
||||||
enabledModels={enabledModels}
|
|
||||||
onToggleModel={toggleModel}
|
|
||||||
onRemoveProvider={handleRemoveProvider}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</Tabs>
|
</Tabs>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Shared components ---
|
||||||
|
|
||||||
type ProviderGroup = { provider: string; models: { id: string; name: string }[] };
|
type ProviderGroup = { provider: string; models: { id: string; name: string }[] };
|
||||||
|
|
||||||
type OpenCodeProviderListProps = {
|
type ProviderGroupTabProps = {
|
||||||
|
groups: ProviderGroup[];
|
||||||
|
enabledProviders: string[];
|
||||||
|
enabledModels: string[];
|
||||||
|
disabledProviders: ProviderGroup[];
|
||||||
|
addingProvider: boolean;
|
||||||
|
selectedNewProvider: string;
|
||||||
|
emptyLabel: string;
|
||||||
|
onSetAddingProvider: (v: boolean) => void;
|
||||||
|
onSetSelectedNewProvider: (v: string) => void;
|
||||||
|
onEnableProvider: () => void;
|
||||||
|
onToggleModel: (key: string) => void;
|
||||||
|
onRemoveProvider: (provider: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ProviderGroupTab = ({
|
||||||
|
groups,
|
||||||
|
enabledProviders,
|
||||||
|
enabledModels,
|
||||||
|
disabledProviders,
|
||||||
|
addingProvider,
|
||||||
|
selectedNewProvider,
|
||||||
|
emptyLabel,
|
||||||
|
onSetAddingProvider,
|
||||||
|
onSetSelectedNewProvider,
|
||||||
|
onEnableProvider,
|
||||||
|
onToggleModel,
|
||||||
|
onRemoveProvider,
|
||||||
|
}: ProviderGroupTabProps) => (
|
||||||
|
<>
|
||||||
|
<div className="flex justify-end items-center gap-2 mb-3">
|
||||||
|
{addingProvider ? (
|
||||||
|
<>
|
||||||
|
<Select value={selectedNewProvider} onValueChange={onSetSelectedNewProvider}>
|
||||||
|
<SelectTrigger className="h-9 flex-1 bg-background/60 border-duck-dark/20 text-duck-dark text-sm">
|
||||||
|
<SelectValue placeholder="Select provider..." />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent className="z-[600]">
|
||||||
|
{disabledProviders.map((g) => (
|
||||||
|
<SelectItem key={g.provider} value={g.provider}>
|
||||||
|
{g.provider}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
disabled={!selectedNewProvider}
|
||||||
|
onClick={onEnableProvider}
|
||||||
|
className="cursor-pointer bg-duck-yellow hover:bg-duck-yellow/90 text-duck-teal font-bold disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Enable
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="cursor-pointer"
|
||||||
|
onClick={() => onSetAddingProvider(true)}
|
||||||
|
disabled={disabledProviders.length === 0}
|
||||||
|
>
|
||||||
|
Add Provider
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{groups.length === 0 ? (
|
||||||
|
<p className="text-sm text-duck-dark/40">{emptyLabel}</p>
|
||||||
|
) : (
|
||||||
|
<ProviderList
|
||||||
|
groups={groups}
|
||||||
|
enabledProviders={enabledProviders}
|
||||||
|
enabledModels={enabledModels}
|
||||||
|
onToggleModel={onToggleModel}
|
||||||
|
onRemoveProvider={onRemoveProvider}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
type ProviderListProps = {
|
||||||
groups: ProviderGroup[];
|
groups: ProviderGroup[];
|
||||||
enabledProviders: string[];
|
enabledProviders: string[];
|
||||||
enabledModels: string[];
|
enabledModels: string[];
|
||||||
@@ -306,14 +402,14 @@ type OpenCodeProviderListProps = {
|
|||||||
onRemoveProvider: (provider: string) => void;
|
onRemoveProvider: (provider: string) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const OpenCodeProviderList = ({
|
const ProviderList = ({
|
||||||
groups,
|
groups,
|
||||||
enabledProviders,
|
enabledProviders,
|
||||||
enabledModels,
|
enabledModels,
|
||||||
onToggleModel,
|
onToggleModel,
|
||||||
onRemoveProvider,
|
onRemoveProvider,
|
||||||
}: OpenCodeProviderListProps) => {
|
}: ProviderListProps) => {
|
||||||
const [openProvider, setOpenProvider] = useUserState<string>('ai-settings-oc-accordion', '');
|
const [openProvider, setOpenProvider] = useUserState<string>('ai-settings-provider-accordion', '');
|
||||||
const enabled = groups.filter((g) => enabledProviders.includes(g.provider));
|
const enabled = groups.filter((g) => enabledProviders.includes(g.provider));
|
||||||
|
|
||||||
if (enabled.length === 0) {
|
if (enabled.length === 0) {
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
export * from './ProfileSettings';
|
export * from './ProfileSettings';
|
||||||
export * from './AISettings';
|
export * from './SystemSettings';
|
||||||
export * from './ServerSettings';
|
|
||||||
export * from './ResourceSettings';
|
export * from './ResourceSettings';
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ import { TerminalView } from 'apps/Terminal';
|
|||||||
import { useWorkspacesState } from '@/state/useWorkspacesState';
|
import { useWorkspacesState } from '@/state/useWorkspacesState';
|
||||||
import { useClaude } from '../Chat/useClaude';
|
import { useClaude } from '../Chat/useClaude';
|
||||||
import { useOpenCode } from '../Chat/useOpenCode';
|
import { useOpenCode } from '../Chat/useOpenCode';
|
||||||
|
import { usePiMono } from '../Chat/usePiMono';
|
||||||
import { ChatPanel } from '../Chat/ChatPanel';
|
import { ChatPanel } from '../Chat/ChatPanel';
|
||||||
import { useVisibleClaudeModels, useVisibleOpenCodeModels } from '@/state/useModels';
|
import { useVisibleClaudeModels, useVisibleOpenCodeModels, useVisiblePiMonoModels } from '@/state/useModels';
|
||||||
import { ChatHistoryApp as ChatHistory } from '../ChatHistory';
|
import { ChatHistoryApp as ChatHistory } from '../ChatHistory';
|
||||||
import { Files } from '../Files';
|
import { Files } from '../Files';
|
||||||
import { Catalog } from 'sounds';
|
import { Catalog } from 'sounds';
|
||||||
@@ -19,26 +20,34 @@ import { widgetRegistry } from 'widgets/widget-registry';
|
|||||||
import { WidgetPanel } from 'widgets/WidgetPanel';
|
import { WidgetPanel } from 'widgets/WidgetPanel';
|
||||||
|
|
||||||
const ChatWidget = () => {
|
const ChatWidget = () => {
|
||||||
const [provider, setProvider] = useState<'claude' | 'opencode'>('claude');
|
const [provider, setProvider] = useState<'claude' | 'opencode' | 'pi-mono'>('claude');
|
||||||
return provider === 'claude' ? (
|
if (provider === 'claude') {
|
||||||
<ClaudeChatWidget key="claude" onProviderChange={setProvider} />
|
return <ClaudeChatWidget key="claude" onProviderChange={setProvider} />;
|
||||||
) : (
|
}
|
||||||
<OpenCodeChatWidget key="opencode" onProviderChange={setProvider} />
|
if (provider === 'opencode') {
|
||||||
);
|
return <OpenCodeChatWidget key="opencode" onProviderChange={setProvider} />;
|
||||||
|
}
|
||||||
|
return <PiMonoChatWidget key="pi-mono" onProviderChange={setProvider} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
const ClaudeChatWidget = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode') => void }) => {
|
const ClaudeChatWidget = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void }) => {
|
||||||
const claude = useClaude();
|
const claude = useClaude();
|
||||||
const models = useVisibleClaudeModels();
|
const models = useVisibleClaudeModels();
|
||||||
return <ChatPanel chat={claude} provider="claude" availableModels={models} onProviderChange={onProviderChange} />;
|
return <ChatPanel chat={claude} provider="claude" availableModels={models} onProviderChange={onProviderChange} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
const OpenCodeChatWidget = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode') => void }) => {
|
const OpenCodeChatWidget = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void }) => {
|
||||||
const opencode = useOpenCode();
|
const opencode = useOpenCode();
|
||||||
const models = useVisibleOpenCodeModels();
|
const models = useVisibleOpenCodeModels();
|
||||||
return <ChatPanel chat={opencode} provider="opencode" availableModels={models} onProviderChange={onProviderChange} />;
|
return <ChatPanel chat={opencode} provider="opencode" availableModels={models} onProviderChange={onProviderChange} />;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const PiMonoChatWidget = ({ onProviderChange }: { onProviderChange: (p: 'claude' | 'opencode' | 'pi-mono') => void }) => {
|
||||||
|
const piMono = usePiMono();
|
||||||
|
const models = useVisiblePiMonoModels();
|
||||||
|
return <ChatPanel chat={piMono} provider="pi-mono" availableModels={models} onProviderChange={onProviderChange} />;
|
||||||
|
};
|
||||||
|
|
||||||
const CodeEditorWrapper = () => <CodeEditorView className="h-full w-full" />;
|
const CodeEditorWrapper = () => <CodeEditorView className="h-full w-full" />;
|
||||||
|
|
||||||
const TerminalWrapper = ({ panelId }: { panelId: string }) => {
|
const TerminalWrapper = ({ panelId }: { panelId: string }) => {
|
||||||
|
|||||||
@@ -51,8 +51,7 @@
|
|||||||
"header": {
|
"header": {
|
||||||
"userMenu": {
|
"userMenu": {
|
||||||
"profile": "Profile",
|
"profile": "Profile",
|
||||||
"aiSettings": "AI Settings",
|
"systemSettings": "System Settings",
|
||||||
"serverSettings": "Server Settings",
|
|
||||||
"resources": "Resources",
|
"resources": "Resources",
|
||||||
"signOut": "Sign Out"
|
"signOut": "Sign Out"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,8 +51,7 @@
|
|||||||
"header": {
|
"header": {
|
||||||
"userMenu": {
|
"userMenu": {
|
||||||
"profile": "Perfil",
|
"profile": "Perfil",
|
||||||
"aiSettings": "Definições de IA",
|
"systemSettings": "Definições do Sistema",
|
||||||
"serverSettings": "Definições do Servidor",
|
|
||||||
"resources": "Recursos",
|
"resources": "Recursos",
|
||||||
"signOut": "Terminar Sessão"
|
"signOut": "Terminar Sessão"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
export type UserSettings = {
|
export type UserSettings = {
|
||||||
chat: {
|
chat: {
|
||||||
defaultProvider: 'claude' | 'opencode';
|
defaultProvider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
defaultModel: string | null;
|
defaultModel: string | null;
|
||||||
systemPrompt: string;
|
systemPrompt: string;
|
||||||
temperature: number;
|
temperature: number;
|
||||||
@@ -11,7 +11,7 @@ export type UserSettings = {
|
|||||||
enabledProviders: string[];
|
enabledProviders: string[];
|
||||||
};
|
};
|
||||||
tasks: {
|
tasks: {
|
||||||
defaultProvider: 'claude' | 'opencode';
|
defaultProvider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
defaultModel: string | null;
|
defaultModel: string | null;
|
||||||
};
|
};
|
||||||
appearance: {
|
appearance: {
|
||||||
|
|||||||
@@ -15,14 +15,14 @@ export const useChatSessions = () => {
|
|||||||
queryFn: () => client.get<SessionEntry[]>('/sessions'),
|
queryFn: () => client.get<SessionEntry[]>('/sessions'),
|
||||||
});
|
});
|
||||||
|
|
||||||
const getMessages = (provider: 'claude' | 'opencode', sessionId: string) =>
|
const getMessages = (provider: 'claude' | 'opencode' | 'pi-mono', sessionId: string) =>
|
||||||
client.get<ChatMessage[]>(`/sessions/${provider}/${sessionId}/messages`);
|
client.get<ChatMessage[]>(`/sessions/${provider}/${sessionId}/messages`);
|
||||||
|
|
||||||
const saveMessages = (provider: 'claude' | 'opencode', sessionId: string, messages: ChatMessage[]) =>
|
const saveMessages = (provider: 'claude' | 'opencode' | 'pi-mono', sessionId: string, messages: ChatMessage[]) =>
|
||||||
client.put(`/sessions/${provider}/${sessionId}/messages`, messages);
|
client.put(`/sessions/${provider}/${sessionId}/messages`, messages);
|
||||||
|
|
||||||
const renameSession = async (
|
const renameSession = async (
|
||||||
provider: 'claude' | 'opencode',
|
provider: 'claude' | 'opencode' | 'pi-mono',
|
||||||
sessionId: string | null,
|
sessionId: string | null,
|
||||||
args: string,
|
args: string,
|
||||||
): Promise<SlashCommandResult> => {
|
): Promise<SlashCommandResult> => {
|
||||||
@@ -42,12 +42,12 @@ export const useChatSessions = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const archiveSession = async (provider: 'claude' | 'opencode', sessionId: string) => {
|
const archiveSession = async (provider: 'claude' | 'opencode' | 'pi-mono', sessionId: string) => {
|
||||||
await client.post(`/sessions/${provider}/${sessionId}/archive`);
|
await client.post(`/sessions/${provider}/${sessionId}/archive`);
|
||||||
queryClient.setQueryData<SessionEntry[]>(['SESSIONS'], (prev) => prev?.filter((s) => s.id !== sessionId) ?? []);
|
queryClient.setQueryData<SessionEntry[]>(['SESSIONS'], (prev) => prev?.filter((s) => s.id !== sessionId) ?? []);
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteSession = async (provider: 'claude' | 'opencode', sessionId: string) => {
|
const deleteSession = async (provider: 'claude' | 'opencode' | 'pi-mono', sessionId: string) => {
|
||||||
await client.delete(`/sessions/${provider}/${sessionId}`);
|
await client.delete(`/sessions/${provider}/${sessionId}`);
|
||||||
queryClient.setQueryData<SessionEntry[]>(['SESSIONS'], (prev) => prev?.filter((s) => s.id !== sessionId) ?? []);
|
queryClient.setQueryData<SessionEntry[]>(['SESSIONS'], (prev) => prev?.filter((s) => s.id !== sessionId) ?? []);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -66,3 +66,24 @@ export const useVisibleOpenCodeModels = () => {
|
|||||||
[models, providers, enabled],
|
[models, providers, enabled],
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const usePiMonoModels = () => {
|
||||||
|
const client = useClient();
|
||||||
|
const { isAuthenticated } = useAuth();
|
||||||
|
|
||||||
|
const { data: models = [] } = useQuery<ModelOption[]>({
|
||||||
|
queryKey: ['PI_MONO_MODELS'],
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
queryFn: () => client.get<ModelOption[]>('/pi-mono/models'),
|
||||||
|
staleTime: 5 * 60 * 1000,
|
||||||
|
});
|
||||||
|
|
||||||
|
return models;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useVisiblePiMonoModels = () => {
|
||||||
|
const models = usePiMonoModels();
|
||||||
|
const { settings } = useSettings();
|
||||||
|
const enabled = settings.ai?.enabledModels ?? [];
|
||||||
|
return useMemo(() => models.filter((m) => enabled.includes(modelKey(m))), [models, enabled]);
|
||||||
|
};
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useClient } from 'hooks/useClient';
|
|||||||
type AIHarnesses = {
|
type AIHarnesses = {
|
||||||
claudeCode: boolean;
|
claudeCode: boolean;
|
||||||
opencode: boolean;
|
opencode: boolean;
|
||||||
|
piMono: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type ServerSettings = {
|
type ServerSettings = {
|
||||||
|
|||||||
+5
-2
@@ -7,6 +7,7 @@ import { verify } from './servers/jwt';
|
|||||||
import { officerdb, TokenBlacklist } from 'officerdb';
|
import { officerdb, TokenBlacklist } from 'officerdb';
|
||||||
import { claudeWebsocket } from './servers/api/claude/websocket';
|
import { claudeWebsocket } from './servers/api/claude/websocket';
|
||||||
import { opencodeWebsocket } from './servers/api/opencode/websocket';
|
import { opencodeWebsocket } from './servers/api/opencode/websocket';
|
||||||
|
import { piMonoWebsocket } from './servers/api/pi-mono/websocket';
|
||||||
import { terminalWebsocket, initTerminalSidecars } from './servers/api/terminal/websocket';
|
import { terminalWebsocket, initTerminalSidecars } from './servers/api/terminal/websocket';
|
||||||
import officerWeb from './apps/officer-web/index.html';
|
import officerWeb from './apps/officer-web/index.html';
|
||||||
|
|
||||||
@@ -16,7 +17,7 @@ type WSData = {
|
|||||||
userId: number;
|
userId: number;
|
||||||
email: string;
|
email: string;
|
||||||
role: string;
|
role: string;
|
||||||
provider: 'claude' | 'opencode' | 'terminal';
|
provider: 'claude' | 'opencode' | 'pi-mono' | 'terminal';
|
||||||
sandboxed: boolean;
|
sandboxed: boolean;
|
||||||
sessionId?: string;
|
sessionId?: string;
|
||||||
};
|
};
|
||||||
@@ -24,10 +25,11 @@ type WSData = {
|
|||||||
const handlers: Record<string, typeof claudeWebsocket> = {
|
const handlers: Record<string, typeof claudeWebsocket> = {
|
||||||
claude: claudeWebsocket,
|
claude: claudeWebsocket,
|
||||||
opencode: opencodeWebsocket,
|
opencode: opencodeWebsocket,
|
||||||
|
'pi-mono': piMonoWebsocket,
|
||||||
terminal: terminalWebsocket,
|
terminal: terminalWebsocket,
|
||||||
};
|
};
|
||||||
|
|
||||||
async function upgradeWs(req: Request, server: any, provider: 'claude' | 'opencode' | 'terminal') {
|
async function upgradeWs(req: Request, server: any, provider: 'claude' | 'opencode' | 'pi-mono' | 'terminal') {
|
||||||
const token = new URL(req.url).searchParams.get('token');
|
const token = new URL(req.url).searchParams.get('token');
|
||||||
if (!token) return new Response('Unauthorized', { status: 401 });
|
if (!token) return new Response('Unauthorized', { status: 401 });
|
||||||
|
|
||||||
@@ -67,6 +69,7 @@ const server = serve({
|
|||||||
},
|
},
|
||||||
'/api/harness/claudecode/ws': (req, server) => upgradeWs(req, server, 'claude'),
|
'/api/harness/claudecode/ws': (req, server) => upgradeWs(req, server, 'claude'),
|
||||||
'/api/harness/opencode/ws': (req, server) => upgradeWs(req, server, 'opencode'),
|
'/api/harness/opencode/ws': (req, server) => upgradeWs(req, server, 'opencode'),
|
||||||
|
'/api/harness/pi-mono/ws': (req, server) => upgradeWs(req, server, 'pi-mono'),
|
||||||
'/api/terminal/ws': (req, server) => upgradeWs(req, server, 'terminal'),
|
'/api/terminal/ws': (req, server) => upgradeWs(req, server, 'terminal'),
|
||||||
'/': officerWeb,
|
'/': officerWeb,
|
||||||
'/*': officerWeb,
|
'/*': officerWeb,
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { HonoVariables } from '@@/create-router';
|
||||||
|
|
||||||
|
export const piMonoModelsRouter = new Hono<{ Variables: HonoVariables }>();
|
||||||
|
|
||||||
|
// Hardcoded fallback models — pi supports many providers but these are the most common
|
||||||
|
const FALLBACK_MODELS = [
|
||||||
|
{ id: 'claude-sonnet-4-5-20250514', name: 'Claude Sonnet 4.5', provider: 'anthropic', providerId: 'anthropic' },
|
||||||
|
{ id: 'claude-opus-4-20250918', name: 'Claude Opus 4', provider: 'anthropic', providerId: 'anthropic' },
|
||||||
|
{ id: 'gpt-4.1', name: 'GPT-4.1', provider: 'openai', providerId: 'openai' },
|
||||||
|
{ id: 'o3', name: 'o3', provider: 'openai', providerId: 'openai' },
|
||||||
|
{ id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro', provider: 'google', providerId: 'google' },
|
||||||
|
{ id: 'gemini-2.5-flash', name: 'Gemini 2.5 Flash', provider: 'google', providerId: 'google' },
|
||||||
|
];
|
||||||
|
|
||||||
|
piMonoModelsRouter.get('/pi-mono/models', async (ctx) => {
|
||||||
|
// Spawn a short-lived pi process to query available models
|
||||||
|
try {
|
||||||
|
const proc = Bun.spawn(['pi', '--list-models', '--mode', 'json'], {
|
||||||
|
stdout: 'pipe',
|
||||||
|
stderr: 'pipe',
|
||||||
|
env: { ...process.env },
|
||||||
|
});
|
||||||
|
|
||||||
|
const output = await new Response(proc.stdout).text();
|
||||||
|
await proc.exited;
|
||||||
|
|
||||||
|
if (proc.exitCode !== 0) return ctx.json(FALLBACK_MODELS);
|
||||||
|
|
||||||
|
// Parse the output — pi --list-models outputs model info
|
||||||
|
const lines = output.trim().split('\n').filter(Boolean);
|
||||||
|
const models: { id: string; name: string; provider: string; providerId: string }[] = [];
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(line);
|
||||||
|
if (data.id && data.provider) {
|
||||||
|
models.push({
|
||||||
|
id: data.id,
|
||||||
|
name: data.name ?? data.id,
|
||||||
|
provider: data.provider,
|
||||||
|
providerId: data.provider,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// skip non-JSON lines
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ctx.json(models.length > 0 ? models : FALLBACK_MODELS);
|
||||||
|
} catch {
|
||||||
|
return ctx.json(FALLBACK_MODELS);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,448 @@
|
|||||||
|
import type { ServerWebSocket } from 'bun';
|
||||||
|
import type { Subprocess } from 'bun';
|
||||||
|
import { mkdir, rename } from 'node:fs/promises';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
import {
|
||||||
|
getPiMonoSessionDir,
|
||||||
|
getTmpAttachmentsDir,
|
||||||
|
getAttachmentsDir,
|
||||||
|
getHomeDir,
|
||||||
|
getNativeSkillsDir,
|
||||||
|
getGlobalSkillsDir,
|
||||||
|
getUserSkillsDir,
|
||||||
|
} from '@@/data-path';
|
||||||
|
import { readSkillDirs, parseFrontmatter } from '@@/api/skills/skills';
|
||||||
|
import type { ClientMessage, ServerMessage, ImageData, TaskInfo } from '@@/api/chat-types';
|
||||||
|
import { createTaskLog, appendToLog, finalizeLog } from '@@/api/task-logger';
|
||||||
|
|
||||||
|
type WSData = { userId: number; email: string };
|
||||||
|
|
||||||
|
type ConnectionState = {
|
||||||
|
piProcess: Subprocess | null;
|
||||||
|
sessionId: string | null;
|
||||||
|
pendingTitle: string | null;
|
||||||
|
selectedModel: string | null;
|
||||||
|
pendingAttachmentIds: string[];
|
||||||
|
cwd: string | null;
|
||||||
|
resourceChatDir: string | null;
|
||||||
|
logId: string | null;
|
||||||
|
fullText: string;
|
||||||
|
rpcReady: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const connections = new Map<ServerWebSocket<WSData>, ConnectionState>();
|
||||||
|
|
||||||
|
function send(ws: ServerWebSocket<WSData>, msg: ServerMessage) {
|
||||||
|
if (ws.readyState === 1) ws.send(JSON.stringify(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveRootDir(email: string, root?: string): string {
|
||||||
|
if (!root || root === 'home') return getHomeDir(email);
|
||||||
|
if (root === '~') return homedir();
|
||||||
|
if (root === 'officer.dev') return join(process.cwd(), '..');
|
||||||
|
return getHomeDir(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildSkillsPrompt(email: string): Promise<string> {
|
||||||
|
const nativeSkills = await readSkillDirs(getNativeSkillsDir());
|
||||||
|
const globalSkills = await readSkillDirs(getGlobalSkillsDir());
|
||||||
|
const userSkills = await readSkillDirs(getUserSkillsDir(email));
|
||||||
|
|
||||||
|
const merged = new Map(nativeSkills);
|
||||||
|
for (const [name, path] of globalSkills) merged.set(name, path);
|
||||||
|
for (const [name, path] of userSkills) merged.set(name, path);
|
||||||
|
|
||||||
|
if (merged.size === 0) return '';
|
||||||
|
|
||||||
|
const lines = await Promise.all(
|
||||||
|
Array.from(merged.entries()).map(async ([dirName, filePath]) => {
|
||||||
|
const raw = await Bun.file(filePath).text();
|
||||||
|
const { frontmatter } = parseFrontmatter(raw);
|
||||||
|
const name = frontmatter.name || dirName;
|
||||||
|
return `- ${name}: ${frontmatter.description} (read ${filePath} for full instructions)`;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return `\n\nYou have access to the following skills. When a user's request matches a skill, read its SKILL.md file for detailed instructions before proceeding.\n\nAvailable skills:\n${lines.join('\n')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeRpcCommand(proc: Subprocess, command: Record<string, unknown>) {
|
||||||
|
const writer = proc.stdin as WritableStream;
|
||||||
|
const textEncoder = new TextEncoder();
|
||||||
|
const w = writer.getWriter();
|
||||||
|
w.write(textEncoder.encode(JSON.stringify(command) + '\n'));
|
||||||
|
w.releaseLock();
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnPiProcess(ws: ServerWebSocket<WSData>, state: ConnectionState, workingDir: string) {
|
||||||
|
const args = ['pi', '--mode', 'rpc', '--no-extensions', '--no-skills', '--no-prompt-templates', '--no-themes'];
|
||||||
|
|
||||||
|
if (state.selectedModel) {
|
||||||
|
args.push('--model', state.selectedModel);
|
||||||
|
}
|
||||||
|
|
||||||
|
const proc = Bun.spawn(args, {
|
||||||
|
cwd: workingDir,
|
||||||
|
stdin: 'pipe',
|
||||||
|
stdout: 'pipe',
|
||||||
|
stderr: 'pipe',
|
||||||
|
env: { ...process.env },
|
||||||
|
});
|
||||||
|
|
||||||
|
state.piProcess = proc;
|
||||||
|
|
||||||
|
// Read stdout line-by-line for JSON events
|
||||||
|
const reader = proc.stdout.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
|
||||||
|
const readLoop = async () => {
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
|
||||||
|
buffer += decoder.decode(value, { stream: true });
|
||||||
|
const lines = buffer.split('\n');
|
||||||
|
buffer = lines.pop() ?? '';
|
||||||
|
|
||||||
|
for (const line of lines) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
try {
|
||||||
|
const event = JSON.parse(line);
|
||||||
|
handlePiEvent(ws, state, event);
|
||||||
|
} catch {
|
||||||
|
// skip unparseable lines
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// process ended
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
readLoop();
|
||||||
|
|
||||||
|
// Read stderr for debugging
|
||||||
|
const stderrReader = proc.stderr.getReader();
|
||||||
|
const stderrDecoder = new TextDecoder();
|
||||||
|
const readStderr = async () => {
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await stderrReader.read();
|
||||||
|
if (done) break;
|
||||||
|
const text = stderrDecoder.decode(value, { stream: true });
|
||||||
|
if (text.trim()) console.log('[pi-mono-ws] stderr:', text.trim());
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// process ended
|
||||||
|
}
|
||||||
|
};
|
||||||
|
readStderr();
|
||||||
|
|
||||||
|
// Handle process exit
|
||||||
|
proc.exited.then((code) => {
|
||||||
|
console.log(`[pi-mono-ws] pi process exited with code ${code}`);
|
||||||
|
if (state.piProcess === proc) {
|
||||||
|
state.piProcess = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePiEvent(ws: ServerWebSocket<WSData>, state: ConnectionState, event: Record<string, unknown>) {
|
||||||
|
const type = event.type as string;
|
||||||
|
|
||||||
|
// RPC responses (type === 'response')
|
||||||
|
if (type === 'response') {
|
||||||
|
const command = event.command as string;
|
||||||
|
if (command === 'get_available_models' && event.success) {
|
||||||
|
// Models are handled by the REST endpoint, not here
|
||||||
|
}
|
||||||
|
if (command === 'prompt' && !event.success) {
|
||||||
|
send(ws, { type: 'error', message: (event.error as string) ?? 'Prompt failed' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case 'agent_start':
|
||||||
|
state.fullText = '';
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'message_update': {
|
||||||
|
// message_update contains assistantMessageEvent with content deltas
|
||||||
|
const ame = event.assistantMessageEvent as Record<string, unknown> | undefined;
|
||||||
|
if (!ame) break;
|
||||||
|
|
||||||
|
const ameType = ame.type as string;
|
||||||
|
if (ameType === 'text_delta') {
|
||||||
|
const delta = ame.delta as string;
|
||||||
|
state.fullText += delta;
|
||||||
|
send(ws, { type: 'assistant:partial', text: delta });
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'message_end': {
|
||||||
|
// Full assistant message complete
|
||||||
|
if (state.fullText) {
|
||||||
|
send(ws, { type: 'assistant:text', text: state.fullText });
|
||||||
|
if (state.logId) appendToLog(state.logId, { role: 'assistant', text: state.fullText });
|
||||||
|
state.fullText = '';
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'tool_execution_start': {
|
||||||
|
const toolCallId = (event.toolCallId as string) ?? '';
|
||||||
|
const toolName = (event.toolName as string) ?? 'unknown';
|
||||||
|
const args = (event.args as Record<string, unknown>) ?? {};
|
||||||
|
|
||||||
|
// Commit any streaming text before tool use
|
||||||
|
if (state.fullText) {
|
||||||
|
send(ws, { type: 'assistant:text', text: state.fullText });
|
||||||
|
if (state.logId) appendToLog(state.logId, { role: 'assistant', text: state.fullText });
|
||||||
|
state.fullText = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
send(ws, { type: 'tool:use', toolName, toolInput: args, toolUseId: toolCallId });
|
||||||
|
if (state.logId) appendToLog(state.logId, { role: 'tool', toolName, toolInput: args, toolUseId: toolCallId });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'tool_execution_end': {
|
||||||
|
const toolCallId = (event.toolCallId as string) ?? '';
|
||||||
|
const result = event.result;
|
||||||
|
const isError = (event.isError as boolean) ?? false;
|
||||||
|
const output = result != null ? (typeof result === 'string' ? result : JSON.stringify(result)) : '';
|
||||||
|
|
||||||
|
send(ws, { type: 'tool:result', toolUseId: toolCallId, output, isError });
|
||||||
|
if (state.logId)
|
||||||
|
appendToLog(state.logId, {
|
||||||
|
role: 'tool',
|
||||||
|
toolName: '',
|
||||||
|
toolInput: {},
|
||||||
|
toolUseId: toolCallId,
|
||||||
|
output,
|
||||||
|
isError,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'agent_end': {
|
||||||
|
// Commit any remaining streaming text
|
||||||
|
if (state.fullText) {
|
||||||
|
send(ws, { type: 'assistant:text', text: state.fullText });
|
||||||
|
if (state.logId) appendToLog(state.logId, { role: 'assistant', text: state.fullText });
|
||||||
|
state.fullText = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
send(ws, { type: 'result', costUsd: 0, durationMs: 0, numTurns: 0, isError: false });
|
||||||
|
if (state.logId) {
|
||||||
|
appendToLog(state.logId, { role: 'result', costUsd: 0, durationMs: 0, numTurns: 0, isError: false });
|
||||||
|
finalizeLog(state.logId);
|
||||||
|
state.logId = null;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'extension_ui_request': {
|
||||||
|
// Auto-cancel extension UI requests since we don't support them
|
||||||
|
if (state.piProcess && event.id) {
|
||||||
|
writeRpcCommand(state.piProcess, { type: 'extension_ui_response', id: event.id, cancelled: true });
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type HandleChatParams = {
|
||||||
|
ws: ServerWebSocket<WSData>;
|
||||||
|
prompt: string;
|
||||||
|
sessionId?: string;
|
||||||
|
model?: string;
|
||||||
|
cwd?: { root?: string; path: string };
|
||||||
|
attachmentIds?: string[];
|
||||||
|
images?: ImageData[];
|
||||||
|
resourceChatDir?: string;
|
||||||
|
taskInfo?: TaskInfo;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function handleChat({
|
||||||
|
ws,
|
||||||
|
prompt,
|
||||||
|
sessionId,
|
||||||
|
model,
|
||||||
|
cwd,
|
||||||
|
attachmentIds,
|
||||||
|
images,
|
||||||
|
resourceChatDir,
|
||||||
|
taskInfo,
|
||||||
|
}: HandleChatParams) {
|
||||||
|
const state = connections.get(ws);
|
||||||
|
if (!state) return;
|
||||||
|
|
||||||
|
if (taskInfo && !state.logId) {
|
||||||
|
state.logId = createTaskLog(ws.data.email, taskInfo, 'pi-mono', model ?? 'unknown');
|
||||||
|
appendToLog(state.logId, { role: 'user', text: prompt });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resourceChatDir) state.resourceChatDir = resourceChatDir;
|
||||||
|
if (model) state.selectedModel = model;
|
||||||
|
|
||||||
|
if (!sessionId && !state.sessionId) {
|
||||||
|
// New session — generate our own sessionId for officer tracking
|
||||||
|
const newSessionId = crypto.randomUUID();
|
||||||
|
state.sessionId = newSessionId;
|
||||||
|
state.pendingTitle = prompt.slice(0, 100);
|
||||||
|
if (attachmentIds?.length) state.pendingAttachmentIds = attachmentIds;
|
||||||
|
|
||||||
|
send(ws, { type: 'session:init', sessionId: newSessionId, model: model ?? 'pi-mono' });
|
||||||
|
|
||||||
|
if (state.resourceChatDir) {
|
||||||
|
const chatDir = join(state.resourceChatDir, 'chat');
|
||||||
|
const meta = { id: newSessionId, model: model ?? 'pi-mono' };
|
||||||
|
mkdir(chatDir, { recursive: true })
|
||||||
|
.then(() => Bun.write(join(chatDir, 'meta.json'), JSON.stringify(meta)))
|
||||||
|
.catch(() => {});
|
||||||
|
} else {
|
||||||
|
const dir = getPiMonoSessionDir(ws.data.email, newSessionId);
|
||||||
|
const meta = {
|
||||||
|
id: newSessionId,
|
||||||
|
title: state.pendingTitle ?? 'New chat',
|
||||||
|
createdAt: Date.now(),
|
||||||
|
model: model ?? 'pi-mono',
|
||||||
|
};
|
||||||
|
mkdir(dir, { recursive: true })
|
||||||
|
.then(() => Bun.write(join(dir, 'meta.json'), JSON.stringify(meta)))
|
||||||
|
.catch(() => {});
|
||||||
|
|
||||||
|
// Move tmp attachments to session dir
|
||||||
|
if (state.pendingAttachmentIds.length > 0) {
|
||||||
|
const tmpDir = getTmpAttachmentsDir(ws.data.email);
|
||||||
|
const destDir = getAttachmentsDir(ws.data.email, 'pi-mono', newSessionId);
|
||||||
|
mkdir(destDir, { recursive: true })
|
||||||
|
.then(() =>
|
||||||
|
Promise.all(
|
||||||
|
state.pendingAttachmentIds.map((id) => rename(join(tmpDir, id), join(destDir, id)).catch(() => {})),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.catch(() => {});
|
||||||
|
state.pendingAttachmentIds = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.pendingTitle = null;
|
||||||
|
} else if (sessionId && !state.sessionId) {
|
||||||
|
state.sessionId = sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure pi process is running
|
||||||
|
const homeDir = getHomeDir(ws.data.email);
|
||||||
|
if (cwd) state.cwd = join(resolveRootDir(ws.data.email, cwd.root), cwd.path);
|
||||||
|
const workingDir = state.cwd ?? homeDir;
|
||||||
|
|
||||||
|
if (!state.piProcess) {
|
||||||
|
spawnPiProcess(ws, state, workingDir);
|
||||||
|
// Give pi a moment to initialize
|
||||||
|
await new Promise((r) => setTimeout(r, 500));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!state.piProcess) {
|
||||||
|
send(ws, { type: 'error', message: 'Failed to start pi process' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set model if specified
|
||||||
|
if (model && model !== state.selectedModel) {
|
||||||
|
state.selectedModel = model;
|
||||||
|
// Model is set via CLI args on spawn, would need a new process to change
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build context and send prompt
|
||||||
|
const skillsAppend = await buildSkillsPrompt(ws.data.email);
|
||||||
|
const contextAppend = `\n\nThe user's home directory is: ${homeDir}` + skillsAppend;
|
||||||
|
send(ws, { type: 'system:prompt', text: contextAppend });
|
||||||
|
|
||||||
|
const fullPrompt = `<system>${contextAppend}</system>\n\n${prompt}`;
|
||||||
|
|
||||||
|
const rpcCommand: Record<string, unknown> = {
|
||||||
|
type: 'prompt',
|
||||||
|
id: `req_${Date.now()}`,
|
||||||
|
message: fullPrompt,
|
||||||
|
};
|
||||||
|
|
||||||
|
writeRpcCommand(state.piProcess, rpcCommand);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleStop(ws: ServerWebSocket<WSData>) {
|
||||||
|
const state = connections.get(ws);
|
||||||
|
if (!state?.piProcess) return;
|
||||||
|
|
||||||
|
writeRpcCommand(state.piProcess, { type: 'abort', id: `abort_${Date.now()}` });
|
||||||
|
send(ws, { type: 'stopped' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function killPiProcess(state: ConnectionState) {
|
||||||
|
if (state.piProcess) {
|
||||||
|
try {
|
||||||
|
state.piProcess.kill();
|
||||||
|
} catch {
|
||||||
|
// already dead
|
||||||
|
}
|
||||||
|
state.piProcess = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const piMonoWebsocket = {
|
||||||
|
open(ws: ServerWebSocket<WSData>) {
|
||||||
|
connections.set(ws, {
|
||||||
|
piProcess: null,
|
||||||
|
sessionId: null,
|
||||||
|
pendingTitle: null,
|
||||||
|
selectedModel: null,
|
||||||
|
pendingAttachmentIds: [],
|
||||||
|
cwd: null,
|
||||||
|
resourceChatDir: null,
|
||||||
|
logId: null,
|
||||||
|
fullText: '',
|
||||||
|
rpcReady: false,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
message(ws: ServerWebSocket<WSData>, raw: string | Buffer) {
|
||||||
|
let msg: ClientMessage;
|
||||||
|
try {
|
||||||
|
msg = JSON.parse(typeof raw === 'string' ? raw : raw.toString()) as ClientMessage;
|
||||||
|
} catch {
|
||||||
|
send(ws, { type: 'error', message: 'Invalid JSON' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.type === 'chat') {
|
||||||
|
handleChat({
|
||||||
|
ws,
|
||||||
|
prompt: msg.prompt,
|
||||||
|
sessionId: msg.sessionId,
|
||||||
|
model: typeof msg.model === 'string' ? msg.model : undefined,
|
||||||
|
cwd: msg.cwd,
|
||||||
|
attachmentIds: msg.attachmentIds,
|
||||||
|
images: msg.images,
|
||||||
|
resourceChatDir: msg.resourceChatDir,
|
||||||
|
taskInfo: msg.taskInfo,
|
||||||
|
});
|
||||||
|
} else if (msg.type === 'stop') {
|
||||||
|
handleStop(ws);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
close(ws: ServerWebSocket<WSData>) {
|
||||||
|
const state = connections.get(ws);
|
||||||
|
if (state) {
|
||||||
|
killPiProcess(state);
|
||||||
|
}
|
||||||
|
connections.delete(ws);
|
||||||
|
},
|
||||||
|
|
||||||
|
drain() {},
|
||||||
|
};
|
||||||
@@ -33,7 +33,7 @@ scrapeRouter.post('/', async (ctx) => {
|
|||||||
const { url, sessionId, provider } = ctx.get('body') as {
|
const { url, sessionId, provider } = ctx.get('body') as {
|
||||||
url: string;
|
url: string;
|
||||||
sessionId?: string;
|
sessionId?: string;
|
||||||
provider?: 'claude' | 'opencode';
|
provider?: 'claude' | 'opencode' | 'pi-mono';
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!url) return ctx.json({ error: 'url is required' }, 400);
|
if (!url) return ctx.json({ error: 'url is required' }, 400);
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { createRouter } from '../../create-router';
|
||||||
|
|
||||||
|
export const piMonoRouter = createRouter();
|
||||||
|
|
||||||
|
const GLOBAL_DIRS = ['/usr/local/bin', '/usr/bin'];
|
||||||
|
|
||||||
|
const getPaths = async () => {
|
||||||
|
try {
|
||||||
|
const proc = Bun.spawn(['which', '-a', 'pi'], { stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
const output = await new Response(proc.stdout).text();
|
||||||
|
await proc.exited;
|
||||||
|
if (proc.exitCode !== 0) return { path: null, globalPath: null };
|
||||||
|
const paths = [...new Set(output.trim().split('\n'))];
|
||||||
|
const path = paths[0] ?? null;
|
||||||
|
const globalPath = paths.find((p) => GLOBAL_DIRS.some((dir) => p.startsWith(dir))) ?? null;
|
||||||
|
return { path, globalPath };
|
||||||
|
} catch {
|
||||||
|
return { path: null, globalPath: null };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
piMonoRouter.get('/version', async (ctx) => {
|
||||||
|
try {
|
||||||
|
const proc = Bun.spawn(['pi', '--version'], { stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
const output = await new Response(proc.stdout).text();
|
||||||
|
await proc.exited;
|
||||||
|
if (proc.exitCode !== 0) return ctx.json({ version: null, path: null, globalPath: null });
|
||||||
|
const { path, globalPath } = await getPaths();
|
||||||
|
return ctx.json({ version: output.trim(), path, globalPath });
|
||||||
|
} catch {
|
||||||
|
return ctx.json({ version: null, path: null, globalPath: null });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
piMonoRouter.post('/install', async (ctx) => {
|
||||||
|
try {
|
||||||
|
const proc = Bun.spawn(['npm', 'install', '-g', '@mariozechner/pi-coding-agent'], {
|
||||||
|
stdout: 'pipe',
|
||||||
|
stderr: 'pipe',
|
||||||
|
});
|
||||||
|
await proc.exited;
|
||||||
|
if (proc.exitCode !== 0) {
|
||||||
|
const stderr = await new Response(proc.stderr).text();
|
||||||
|
return ctx.json({ version: null, path: null, globalPath: null, error: stderr.trim() }, 500);
|
||||||
|
}
|
||||||
|
const versionProc = Bun.spawn(['pi', '--version'], { stdout: 'pipe', stderr: 'pipe' });
|
||||||
|
const output = await new Response(versionProc.stdout).text();
|
||||||
|
await versionProc.exited;
|
||||||
|
const { path, globalPath } = await getPaths();
|
||||||
|
return ctx.json({ version: output.trim(), path, globalPath });
|
||||||
|
} catch {
|
||||||
|
return ctx.json({ version: null, path: null, globalPath: null, error: 'Installation failed' }, 500);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -6,6 +6,7 @@ import { join } from 'node:path';
|
|||||||
import { officerdb, count, Users } from 'officerdb';
|
import { officerdb, count, Users } from 'officerdb';
|
||||||
import { claudeCodeRouter } from './claude-code';
|
import { claudeCodeRouter } from './claude-code';
|
||||||
import { opencodeRouter } from './opencode';
|
import { opencodeRouter } from './opencode';
|
||||||
|
import { piMonoRouter } from './pi-mono';
|
||||||
import { applicationsRouter } from './applications';
|
import { applicationsRouter } from './applications';
|
||||||
import { resourcesRouter } from './resources';
|
import { resourcesRouter } from './resources';
|
||||||
|
|
||||||
@@ -22,6 +23,7 @@ export const serverSettingsRouter = createRouter();
|
|||||||
|
|
||||||
serverSettingsRouter.route('/claude-code', claudeCodeRouter);
|
serverSettingsRouter.route('/claude-code', claudeCodeRouter);
|
||||||
serverSettingsRouter.route('/opencode', opencodeRouter);
|
serverSettingsRouter.route('/opencode', opencodeRouter);
|
||||||
|
serverSettingsRouter.route('/pi-mono', piMonoRouter);
|
||||||
serverSettingsRouter.route('/applications', applicationsRouter);
|
serverSettingsRouter.route('/applications', applicationsRouter);
|
||||||
serverSettingsRouter.route('/resources', resourcesRouter);
|
serverSettingsRouter.route('/resources', resourcesRouter);
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import { mkdir, readdir, rename, rm } from 'node:fs/promises';
|
import { mkdir, readdir, rename, rm } from 'node:fs/promises';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { getClaudeDir, getSessionDir, getArchivedSessionDir, getOpencodeDir, getOpencodeSessionDir } from '@@/data-path';
|
import { getClaudeDir, getSessionDir, getArchivedSessionDir, getOpencodeDir, getOpencodeSessionDir, getPiMonoDir, getPiMonoSessionDir } from '@@/data-path';
|
||||||
import type { HonoVariables } from '@@/create-router';
|
import type { HonoVariables } from '@@/create-router';
|
||||||
|
|
||||||
const OPENCODE_PORT = process.env.OPENCODE_PORT ?? '10006';
|
const OPENCODE_PORT = process.env.OPENCODE_PORT ?? '10006';
|
||||||
@@ -14,9 +14,13 @@ export const sessionsRouter = new Hono<{ Variables: HonoVariables }>();
|
|||||||
sessionsRouter.get('/sessions', async (ctx) => {
|
sessionsRouter.get('/sessions', async (ctx) => {
|
||||||
const { email } = ctx.get('user');
|
const { email } = ctx.get('user');
|
||||||
|
|
||||||
const [claudeSessions, opencodeSessions] = await Promise.all([fetchClaudeSessions(email), fetchOpencodeSessions(email)]);
|
const [claudeSessions, opencodeSessions, piMonoSessions] = await Promise.all([
|
||||||
|
fetchClaudeSessions(email),
|
||||||
|
fetchOpencodeSessions(email),
|
||||||
|
fetchPiMonoSessions(email),
|
||||||
|
]);
|
||||||
|
|
||||||
const merged = [...claudeSessions, ...opencodeSessions].sort((a, b) => b.createdAt - a.createdAt);
|
const merged = [...claudeSessions, ...opencodeSessions, ...piMonoSessions].sort((a, b) => b.createdAt - a.createdAt);
|
||||||
return ctx.json(merged);
|
return ctx.json(merged);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -37,6 +41,12 @@ sessionsRouter.get('/sessions/:provider/:id/messages', async (ctx) => {
|
|||||||
return ctx.json(await fetchOpencodeMessages(id));
|
return ctx.json(await fetchOpencodeMessages(id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (provider === 'pi-mono') {
|
||||||
|
const file = Bun.file(join(getPiMonoSessionDir(email, id), 'messages.json'));
|
||||||
|
if (!(await file.exists())) return ctx.json([]);
|
||||||
|
return ctx.json(await file.json());
|
||||||
|
}
|
||||||
|
|
||||||
return ctx.json({ error: 'invalid provider' }, 400);
|
return ctx.json({ error: 'invalid provider' }, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -46,10 +56,10 @@ sessionsRouter.put('/sessions/:provider/:id/messages', async (ctx) => {
|
|||||||
const id = ctx.req.param('id');
|
const id = ctx.req.param('id');
|
||||||
|
|
||||||
if (provider === 'opencode') return ctx.json({ error: 'opencode sessions are read-only' }, 400);
|
if (provider === 'opencode') return ctx.json({ error: 'opencode sessions are read-only' }, 400);
|
||||||
if (provider !== 'claude') return ctx.json({ error: 'invalid provider' }, 400);
|
if (provider !== 'claude' && provider !== 'pi-mono') return ctx.json({ error: 'invalid provider' }, 400);
|
||||||
|
|
||||||
const messages = ctx.get('body');
|
const messages = ctx.get('body');
|
||||||
const dir = getSessionDir(email, id);
|
const dir = provider === 'pi-mono' ? getPiMonoSessionDir(email, id) : getSessionDir(email, id);
|
||||||
await Bun.write(join(dir, 'messages.json'), JSON.stringify(messages));
|
await Bun.write(join(dir, 'messages.json'), JSON.stringify(messages));
|
||||||
return ctx.json({ ok: true });
|
return ctx.json({ ok: true });
|
||||||
});
|
});
|
||||||
@@ -92,6 +102,16 @@ sessionsRouter.put('/sessions/:provider/:id', async (ctx) => {
|
|||||||
return ctx.json({ ok: true });
|
return ctx.json({ ok: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (provider === 'pi-mono') {
|
||||||
|
const dir = getPiMonoSessionDir(email, id);
|
||||||
|
const metaFile = Bun.file(join(dir, 'meta.json'));
|
||||||
|
if (!(await metaFile.exists())) return ctx.json({ error: 'session not found' }, 404);
|
||||||
|
const meta = await metaFile.json();
|
||||||
|
meta.title = body.title.slice(0, 200);
|
||||||
|
await Bun.write(join(dir, 'meta.json'), JSON.stringify(meta));
|
||||||
|
return ctx.json({ ok: true });
|
||||||
|
}
|
||||||
|
|
||||||
return ctx.json({ error: 'invalid provider' }, 400);
|
return ctx.json({ error: 'invalid provider' }, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -124,6 +144,16 @@ sessionsRouter.delete('/sessions/:provider/:id', async (ctx) => {
|
|||||||
return ctx.json({ ok: true });
|
return ctx.json({ ok: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (provider === 'pi-mono') {
|
||||||
|
const dir = getPiMonoSessionDir(email, id);
|
||||||
|
try {
|
||||||
|
await rm(dir, { recursive: true });
|
||||||
|
} catch {
|
||||||
|
// dir may not exist
|
||||||
|
}
|
||||||
|
return ctx.json({ ok: true });
|
||||||
|
}
|
||||||
|
|
||||||
return ctx.json({ error: 'invalid provider' }, 400);
|
return ctx.json({ error: 'invalid provider' }, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -134,7 +164,7 @@ sessionsRouter.post('/sessions/:provider/:id/archive', async (ctx) => {
|
|||||||
const provider = ctx.req.param('provider');
|
const provider = ctx.req.param('provider');
|
||||||
const id = ctx.req.param('id');
|
const id = ctx.req.param('id');
|
||||||
|
|
||||||
if (provider === 'opencode') return ctx.json({ error: 'opencode sessions cannot be archived' }, 400);
|
if (provider === 'opencode' || provider === 'pi-mono') return ctx.json({ error: `${provider} sessions cannot be archived` }, 400);
|
||||||
if (provider !== 'claude') return ctx.json({ error: 'invalid provider' }, 400);
|
if (provider !== 'claude') return ctx.json({ error: 'invalid provider' }, 400);
|
||||||
|
|
||||||
const src = getSessionDir(email, id);
|
const src = getSessionDir(email, id);
|
||||||
@@ -150,7 +180,7 @@ type SessionMeta = {
|
|||||||
id: string;
|
id: string;
|
||||||
title: string;
|
title: string;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
provider: 'claude' | 'opencode';
|
provider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
model?: string | null;
|
model?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -200,6 +230,28 @@ async function fetchOpencodeSessions(email: string): Promise<SessionMeta[]> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function fetchPiMonoSessions(email: string): Promise<SessionMeta[]> {
|
||||||
|
const dir = getPiMonoDir(email);
|
||||||
|
try {
|
||||||
|
const entries = await readdir(dir);
|
||||||
|
const sessions = await Promise.all(
|
||||||
|
entries.map(async (id) => {
|
||||||
|
try {
|
||||||
|
const metaFile = Bun.file(join(dir, id, 'meta.json'));
|
||||||
|
if (!(await metaFile.exists())) return null;
|
||||||
|
const meta = await metaFile.json();
|
||||||
|
return { ...meta, provider: 'pi-mono' as const };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return sessions.filter((s): s is SessionMeta => s !== null);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchOpencodeMessages(id: string) {
|
async function fetchOpencodeMessages(id: string) {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${OPENCODE_BASE}/session/${id}/message`);
|
const res = await fetch(`${OPENCODE_BASE}/session/${id}/message`);
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ uploadRouter.post('/', async (ctx) => {
|
|||||||
|
|
||||||
const file = body.file as File | null;
|
const file = body.file as File | null;
|
||||||
const sessionId = (body.sessionId as string) || null;
|
const sessionId = (body.sessionId as string) || null;
|
||||||
const provider = (body.provider as 'claude' | 'opencode') || null;
|
const provider = (body.provider as 'claude' | 'opencode' | 'pi-mono') || null;
|
||||||
|
|
||||||
if (!file || !(file instanceof File)) {
|
if (!file || !(file instanceof File)) {
|
||||||
return ctx.json({ error: 'file is required' }, 400);
|
return ctx.json({ error: 'file is required' }, 400);
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ export const getOpencodeDir = (email: string) => join(DATA_PATH, email, 'chat_se
|
|||||||
export const getOpencodeSessionDir = (email: string, sessionId: string) =>
|
export const getOpencodeSessionDir = (email: string, sessionId: string) =>
|
||||||
join(DATA_PATH, email, 'chat_sessions', 'opencode', sessionId);
|
join(DATA_PATH, email, 'chat_sessions', 'opencode', sessionId);
|
||||||
|
|
||||||
|
export const getPiMonoDir = (email: string) => join(DATA_PATH, email, 'chat_sessions', 'pi-mono');
|
||||||
|
|
||||||
|
export const getPiMonoSessionDir = (email: string, sessionId: string) =>
|
||||||
|
join(DATA_PATH, email, 'chat_sessions', 'pi-mono', sessionId);
|
||||||
|
|
||||||
export const getArchivedSessionDir = (email: string, sessionId: string) =>
|
export const getArchivedSessionDir = (email: string, sessionId: string) =>
|
||||||
join(DATA_PATH, email, 'chat_sessions', 'claude', 'archived', sessionId);
|
join(DATA_PATH, email, 'chat_sessions', 'claude', 'archived', sessionId);
|
||||||
|
|
||||||
@@ -53,5 +58,5 @@ export const getTaskLogsDir = (email: string) => join(DATA_PATH, email, 'logs',
|
|||||||
|
|
||||||
export const getTmpAttachmentsDir = (email: string) => join(DATA_PATH, email, 'chat_sessions', 'tmp_attachments');
|
export const getTmpAttachmentsDir = (email: string) => join(DATA_PATH, email, 'chat_sessions', 'tmp_attachments');
|
||||||
|
|
||||||
export const getAttachmentsDir = (email: string, provider: 'claude' | 'opencode', sessionId: string) =>
|
export const getAttachmentsDir = (email: string, provider: 'claude' | 'opencode' | 'pi-mono', sessionId: string) =>
|
||||||
join(DATA_PATH, email, 'chat_sessions', provider, sessionId, 'attachments');
|
join(DATA_PATH, email, 'chat_sessions', provider, sessionId, 'attachments');
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { tasksRouter } from './api/tasks/tasks';
|
|||||||
import { processesRouter } from './api/processes/processes';
|
import { processesRouter } from './api/processes/processes';
|
||||||
import { claudeModelsRouter } from './api/claude/sessions';
|
import { claudeModelsRouter } from './api/claude/sessions';
|
||||||
import { opencodeModelsRouter } from './api/opencode/sessions';
|
import { opencodeModelsRouter } from './api/opencode/sessions';
|
||||||
|
import { piMonoModelsRouter } from './api/pi-mono/sessions';
|
||||||
import { sessionsRouter } from './api/sessions/sessions';
|
import { sessionsRouter } from './api/sessions/sessions';
|
||||||
import { scrapeRouter } from './api/scrape/scrape';
|
import { scrapeRouter } from './api/scrape/scrape';
|
||||||
import { uploadRouter } from './api/upload/upload';
|
import { uploadRouter } from './api/upload/upload';
|
||||||
@@ -53,6 +54,7 @@ protectedRouter.route('/processes', processesRouter);
|
|||||||
protectedRouter.route('/', sessionsRouter);
|
protectedRouter.route('/', sessionsRouter);
|
||||||
protectedRouter.route('/', claudeModelsRouter);
|
protectedRouter.route('/', claudeModelsRouter);
|
||||||
protectedRouter.route('/', opencodeModelsRouter);
|
protectedRouter.route('/', opencodeModelsRouter);
|
||||||
|
protectedRouter.route('/', piMonoModelsRouter);
|
||||||
protectedRouter.route('/scrape', scrapeRouter);
|
protectedRouter.route('/scrape', scrapeRouter);
|
||||||
protectedRouter.route('/upload', uploadRouter);
|
protectedRouter.route('/upload', uploadRouter);
|
||||||
protectedRouter.route('/user', settingsRouter);
|
protectedRouter.route('/user', settingsRouter);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ export type SessionEntry = {
|
|||||||
id: string;
|
id: string;
|
||||||
title: string;
|
title: string;
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
provider: 'claude' | 'opencode';
|
provider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
model?: string | null;
|
model?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { ArrowLeft, Archive, Trash2, Maximize2, Minimize2 } from 'lucide-react';
|
|||||||
|
|
||||||
type SessionBarProps = {
|
type SessionBarProps = {
|
||||||
listPath: string;
|
listPath: string;
|
||||||
provider: 'claude' | 'opencode';
|
provider: 'claude' | 'opencode' | 'pi-mono';
|
||||||
sessionTitle: string | undefined;
|
sessionTitle: string | undefined;
|
||||||
isConnected: boolean;
|
isConnected: boolean;
|
||||||
isGenerating: boolean;
|
isGenerating: boolean;
|
||||||
|
|||||||
Reference in New Issue
Block a user