moving
This commit is contained in:
@@ -128,6 +128,7 @@ const ChatHostInstance = ({ workspaceId }: { workspaceId: string }) => {
|
||||
templateId={ws?.templateId}
|
||||
storageType={ws?.storageType}
|
||||
initialPersona={personaId}
|
||||
initialModel={ws?.model}
|
||||
initialMessage={seed?.initialMessage}
|
||||
autoSendInitial={seed?.autoSend ?? false}
|
||||
onPersonaChange={setPersona}
|
||||
|
||||
@@ -40,6 +40,8 @@ describe('ModelPilotCard', () => {
|
||||
|
||||
const threshold = screen.getByRole('slider', { name: /budget saver activation threshold/i });
|
||||
expect(threshold).toHaveAttribute('name', 'budgetThreshold');
|
||||
expect(threshold).toHaveAttribute('min', '0.5');
|
||||
expect(threshold).toHaveAttribute('max', '0.95');
|
||||
expect(threshold.className).toContain('focus-visible:ring-2');
|
||||
|
||||
fireEvent.change(threshold, { target: { value: '0.75' } });
|
||||
|
||||
@@ -459,17 +459,17 @@ const ModelPilotCard = ({
|
||||
aria-label="Budget saver activation threshold"
|
||||
name="budgetThreshold"
|
||||
type="range"
|
||||
min={0.1}
|
||||
max={1.0}
|
||||
min={0.5}
|
||||
max={0.95}
|
||||
step={0.05}
|
||||
value={budgetThreshold}
|
||||
onChange={(e) => onUpdate({ budgetThreshold: parseFloat(e.target.value) })}
|
||||
className="w-full h-1.5 rounded-full appearance-none bg-muted/50 accent-[var(--honey)] cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
/>
|
||||
<div className="flex justify-between text-[11px] text-muted-foreground mt-0.5">
|
||||
<span>10%</span>
|
||||
<span>50%</span>
|
||||
<span>100%</span>
|
||||
<span>75%</span>
|
||||
<span>95%</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -597,6 +597,16 @@ const ChatApp = ({
|
||||
const followingRef = useRef(true);
|
||||
useEffect(() => { followingRef.current = following; }, [following]);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const composerEditRevisionRef = useRef(0);
|
||||
const sendSubmissionRef = useRef(0);
|
||||
const composerThreadKey = `${workspaceId ?? ''}\u0000${activeSessionId ?? ''}`;
|
||||
const composerThreadKeyRef = useRef(composerThreadKey);
|
||||
composerThreadKeyRef.current = composerThreadKey;
|
||||
const starterTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(() => () => {
|
||||
if (starterTimeoutRef.current) clearTimeout(starterTimeoutRef.current);
|
||||
starterTimeoutRef.current = null;
|
||||
}, [composerThreadKey]);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const personaPickerRef = useRef<HTMLDivElement>(null);
|
||||
const modelPickerRef = useRef<HTMLDivElement>(null);
|
||||
@@ -625,6 +635,13 @@ const ChatApp = ({
|
||||
if (!last || last.role !== 'assistant' || !last.content) return [];
|
||||
return extractSuggestedActions(last.content);
|
||||
}, [messages, isLoading]);
|
||||
const persistedMessageIndices = useMemo(() => {
|
||||
let persistedIndex = -1;
|
||||
return messages.map(message => {
|
||||
if (!message.draft && !message.queued) persistedIndex += 1;
|
||||
return persistedIndex;
|
||||
});
|
||||
}, [messages]);
|
||||
|
||||
// B3: the latest completed file-write becomes the work-canvas doc; auto-open
|
||||
// the canvas when a NEW artifact appears (the user can close it; reopening is
|
||||
@@ -807,6 +824,37 @@ const ChatApp = ({
|
||||
prevCanSendRef.current = canSend;
|
||||
}, [canSend]);
|
||||
|
||||
const submitComposerMessage = useCallback((content: string, restoreText = content) => {
|
||||
const submission = ++sendSubmissionRef.current;
|
||||
const editRevision = composerEditRevisionRef.current;
|
||||
const threadKey = composerThreadKeyRef.current;
|
||||
const restoreRejected = () => {
|
||||
if (
|
||||
sendSubmissionRef.current === submission
|
||||
&& composerEditRevisionRef.current === editRevision
|
||||
&& composerThreadKeyRef.current === threadKey
|
||||
) {
|
||||
setInput(current => current || restoreText);
|
||||
}
|
||||
};
|
||||
|
||||
setInput('');
|
||||
setShowSlash(false);
|
||||
try {
|
||||
const sendResult = onSendMessage(content);
|
||||
if (sendResult) {
|
||||
void sendResult.then(
|
||||
accepted => {
|
||||
if (accepted === false) restoreRejected();
|
||||
},
|
||||
restoreRejected,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
restoreRejected();
|
||||
}
|
||||
}, [onSendMessage]);
|
||||
|
||||
// F2: mount-once auto-send of the wizard's first task. This fires exactly once,
|
||||
// after the session has landed and history has been fetched (so the optimistic
|
||||
// turn isn't clobbered by the history replace). Once consumed, the untouched
|
||||
@@ -820,12 +868,14 @@ const ChatApp = ({
|
||||
})) return;
|
||||
const text = (initialMessage as string).trim();
|
||||
autoSentRef.current = true; // consume BEFORE dispatch: StrictMode/effect-rerun safe
|
||||
if (inputUnchanged) setInput('');
|
||||
void Promise.resolve(onSendMessage(text)).then((ok) => {
|
||||
// If the send failed, restore the untouched seed so the user can retry.
|
||||
if (ok === false && inputUnchanged) setInput(prev => (prev === '' ? text : prev));
|
||||
});
|
||||
}, [autoSendInitial, initialMessage, activeSessionId, historyLoaded, onSendMessage]);
|
||||
submitComposerMessage(text);
|
||||
}, [
|
||||
autoSendInitial,
|
||||
initialMessage,
|
||||
activeSessionId,
|
||||
historyLoaded,
|
||||
submitComposerMessage,
|
||||
]);
|
||||
|
||||
// Router arc P1-B (B2): composer "Best fit" — POST the composer text to
|
||||
// /api/route-proposals and inject the proposal as a LOCAL route_proposal
|
||||
@@ -907,20 +957,15 @@ const ChatApp = ({
|
||||
if (text === '/models') {
|
||||
// Show available models as a local message
|
||||
const models = availableModels?.join(', ') || 'No models loaded';
|
||||
onSendMessage(`Available models: ${models}`);
|
||||
setInput('');
|
||||
submitComposerMessage(`Available models: ${models}`, text);
|
||||
return;
|
||||
}
|
||||
if (text === '/cost') {
|
||||
onSendMessage('/cost');
|
||||
setInput('');
|
||||
setShowSlash(false);
|
||||
submitComposerMessage('/cost', text);
|
||||
return;
|
||||
}
|
||||
|
||||
onSendMessage(text);
|
||||
setInput('');
|
||||
setShowSlash(false);
|
||||
submitComposerMessage(text);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -954,6 +999,7 @@ const ChatApp = ({
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const val = e.target.value;
|
||||
composerEditRevisionRef.current += 1;
|
||||
setInput(val);
|
||||
if (val.startsWith('/')) {
|
||||
setShowSlash(true);
|
||||
@@ -1098,12 +1144,20 @@ const ChatApp = ({
|
||||
// the first turn is a single click. Pre-filling the input first
|
||||
// gives the user a visible "this is what's about to ship" beat;
|
||||
// editing the input within the 1s cancels the auto-send.
|
||||
composerEditRevisionRef.current += 1;
|
||||
const editRevision = composerEditRevisionRef.current;
|
||||
const threadKey = composerThreadKeyRef.current;
|
||||
setInput(msg);
|
||||
inputRef.current?.focus();
|
||||
setTimeout(() => {
|
||||
if (inputRef.current?.value === msg) {
|
||||
onSendMessage(msg);
|
||||
setInput('');
|
||||
if (starterTimeoutRef.current) clearTimeout(starterTimeoutRef.current);
|
||||
starterTimeoutRef.current = setTimeout(() => {
|
||||
starterTimeoutRef.current = null;
|
||||
if (
|
||||
composerThreadKeyRef.current === threadKey
|
||||
&& composerEditRevisionRef.current === editRevision
|
||||
&& inputRef.current?.value === msg
|
||||
) {
|
||||
submitComposerMessage(msg);
|
||||
}
|
||||
}, 1000);
|
||||
}}
|
||||
@@ -1112,6 +1166,7 @@ const ChatApp = ({
|
||||
// their starter strings end with ": " — the user must finish
|
||||
// the sentence before sending. Cursor lands at end-of-input
|
||||
// so they can type immediately.
|
||||
composerEditRevisionRef.current += 1;
|
||||
setInput(msg);
|
||||
inputRef.current?.focus();
|
||||
// Move caret to end so typing appends instead of replacing.
|
||||
@@ -1141,7 +1196,10 @@ const ChatApp = ({
|
||||
<p className="text-xs text-muted-foreground">Your memory and agents live inside a workspace</p>
|
||||
</div>
|
||||
)}
|
||||
{messages.map((msg, msgIdx) => (
|
||||
{messages.map((msg, msgIdx) => {
|
||||
const messagePersona = msg.persona ? getPersonaById(msg.persona) : undefined;
|
||||
const persistedMessageIndex = persistedMessageIndices[msgIdx];
|
||||
return (
|
||||
<div key={msg.id} className={`group/turn flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'} gap-2`}
|
||||
onDoubleClick={() => {
|
||||
if (onContextRail && msg.content) {
|
||||
@@ -1165,12 +1223,12 @@ const ChatApp = ({
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
{/* I1 fix 2: the active persona's bee sprite on every assistant
|
||||
turn (22 unique mascots); unknown/custom personas fall back
|
||||
to the letter/Bot mark below. */}
|
||||
{persona && <AvatarImage src={getPersonaAvatar(persona.id)} alt={`${persona.name} avatar`} />}
|
||||
{/* The authoring persona is immutable message provenance. A
|
||||
later persona switch must never relabel an earlier turn;
|
||||
legacy/unknown messages fall back to the Bot mark. */}
|
||||
{messagePersona && <AvatarImage src={getPersonaAvatar(messagePersona.id)} alt={`${messagePersona.name} avatar`} />}
|
||||
<AvatarFallback className="text-[11px] bg-primary/20">
|
||||
{persona ? persona.name[0] : <Bot className="w-3.5 h-3.5" aria-hidden="true" />}
|
||||
{messagePersona ? messagePersona.name[0] : <Bot className="w-3.5 h-3.5" aria-hidden="true" />}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)}
|
||||
@@ -1184,8 +1242,13 @@ const ChatApp = ({
|
||||
{msg.role === 'assistant' && (
|
||||
<div className="mb-1 flex items-center gap-1.5 font-mono text-[11.5px] text-[var(--text-muted)]">
|
||||
<span className="font-semibold text-[var(--text-2)]">Waggle</span>
|
||||
{persona?.name && <span>· {persona.name}</span>}
|
||||
{currentModel && <span>· {formatModelLabel(currentModel)}</span>}
|
||||
{messagePersona?.name && <span>· {messagePersona.name}</span>}
|
||||
{msg.model && <span>· {formatModelLabel(msg.model)}</span>}
|
||||
{msg.draft && (
|
||||
<span data-testid="chat-draft-status">
|
||||
· {msg.draft.status === 'stopped' ? 'Stopped draft' : 'Draft'} · not saved
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className={`relative select-text cursor-text group/msg text-sm ${
|
||||
@@ -1200,14 +1263,35 @@ const ChatApp = ({
|
||||
? 'rounded-[12px] bg-[var(--surface-2)] px-3 py-2 text-[12px] italic text-[var(--text-muted)]'
|
||||
: 'rounded-[14px] px-3.5 py-2.5 leading-[1.6] text-[var(--text)]'
|
||||
}`}>
|
||||
{msg.role === 'assistant' && msg.blocks && msg.blocks.length > 0 ? (
|
||||
{msg.role === 'assistant' && msg.draft?.content ? (
|
||||
<div
|
||||
className="whitespace-pre-wrap break-words"
|
||||
data-testid="chat-draft-content"
|
||||
>
|
||||
<BlockRenderer blocks={[{
|
||||
type: 'text',
|
||||
blockId: `draft-${msg.id}`,
|
||||
content: msg.draft.content,
|
||||
}]} />
|
||||
</div>
|
||||
) : msg.role === 'assistant' && msg.blocks && msg.blocks.length > 0 ? (
|
||||
<BlockRenderer
|
||||
blocks={msg.blocks}
|
||||
isStreaming={isLoading && msg === messages[messages.length - 1]}
|
||||
workspaceId={workspaceId}
|
||||
sessionId={activeSessionId}
|
||||
onRetry={msgIdx === messages.length - 1 && !isLoading ? onRetry : undefined}
|
||||
/>
|
||||
) : msg.role === 'assistant' ? (
|
||||
<BlockRenderer blocks={[{
|
||||
type: 'text',
|
||||
blockId: `legacy-${msg.id}`,
|
||||
content: msg.content,
|
||||
}]} />
|
||||
) : (
|
||||
<span className="whitespace-pre-wrap">{msg.content}</span>
|
||||
<span className="whitespace-pre-wrap">
|
||||
{msg.content}
|
||||
</span>
|
||||
)}
|
||||
{/* Copy button — assistant turns get Copy in the hover action
|
||||
row below (round-6 fix 2), so this overlay stays for user/
|
||||
@@ -1262,7 +1346,7 @@ const ChatApp = ({
|
||||
{msg.role === 'assistant' && msg.content && (
|
||||
<FeedbackButtons
|
||||
messageId={msg.id}
|
||||
messageIndex={msgIdx}
|
||||
messageIndex={persistedMessageIndex}
|
||||
sessionId={activeSessionId ?? undefined}
|
||||
feedback={msg.feedback}
|
||||
content={msg.content}
|
||||
@@ -1298,7 +1382,8 @@ const ChatApp = ({
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Router arc B2: locally injected route proposals (composer Best fit). */}
|
||||
{routeProposals.map(rp => (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -6,8 +6,9 @@ const mocks = vi.hoisted(() => ({
|
||||
getModel: vi.fn(),
|
||||
getSettings: vi.fn(),
|
||||
getTeamMembers: vi.fn(),
|
||||
setModel: vi.fn(),
|
||||
patchWorkspace: vi.fn(),
|
||||
useChat: vi.fn(),
|
||||
toast: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/adapter', () => ({ adapter: mocks }));
|
||||
@@ -20,7 +21,25 @@ vi.mock('@/hooks/useSessions', () => ({
|
||||
}),
|
||||
}));
|
||||
vi.mock('@/hooks/useChat', () => ({
|
||||
useChat: () => ({
|
||||
useChat: mocks.useChat,
|
||||
}));
|
||||
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) }));
|
||||
vi.mock('./ChatApp', () => ({
|
||||
default: ({ availableModels, currentModel, onModelChange }: {
|
||||
availableModels: string[];
|
||||
currentModel: string;
|
||||
onModelChange: (model: string) => void;
|
||||
}) => (
|
||||
<div>
|
||||
<div data-testid="models">{availableModels.join(',')}</div>
|
||||
<div data-testid="current-model">{currentModel || 'auto'}</div>
|
||||
<button type="button" onClick={() => onModelChange('openai/model-b')}>Select B</button>
|
||||
<button type="button" onClick={() => onModelChange('openai/model-c')}>Select C</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const chatState = {
|
||||
messages: [],
|
||||
isLoading: false,
|
||||
historyLoaded: true,
|
||||
@@ -30,14 +49,7 @@ vi.mock('@/hooks/useChat', () => ({
|
||||
clearHistory: vi.fn(),
|
||||
pendingApproval: null,
|
||||
approveAction: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: vi.fn() }) }));
|
||||
vi.mock('./ChatApp', () => ({
|
||||
default: ({ availableModels }: { availableModels: string[] }) => (
|
||||
<div data-testid="models">{availableModels.join(',')}</div>
|
||||
),
|
||||
}));
|
||||
};
|
||||
|
||||
import ChatWindowInstance from './ChatWindowInstance';
|
||||
|
||||
@@ -48,8 +60,8 @@ beforeEach(() => {
|
||||
mocks.getModel.mockResolvedValue('openai/existing-model');
|
||||
mocks.getSettings.mockResolvedValue({});
|
||||
mocks.getTeamMembers.mockResolvedValue([]);
|
||||
mocks.setModel.mockResolvedValue(undefined);
|
||||
mocks.patchWorkspace.mockResolvedValue(undefined);
|
||||
mocks.useChat.mockReturnValue(chatState);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -70,4 +82,60 @@ describe('ChatWindowInstance model catalog refresh', () => {
|
||||
.toHaveTextContent('openai/model-released-while-open'));
|
||||
expect(mocks.getModels).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('passes the workspace model into chat and ignores a stale startup result after a user choice', async () => {
|
||||
let resolveStartup!: (model: string) => void;
|
||||
mocks.getModel.mockReturnValueOnce(new Promise<string>((resolve) => { resolveStartup = resolve; }));
|
||||
|
||||
render(<ChatWindowInstance workspaceId="workspace-1" />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select B' }));
|
||||
expect(screen.getByTestId('current-model')).toHaveTextContent('openai/model-b');
|
||||
|
||||
await act(async () => { resolveStartup('openai/stale-startup-model'); });
|
||||
await waitFor(() => expect(mocks.patchWorkspace)
|
||||
.toHaveBeenCalledWith('workspace-1', { model: 'openai/model-b' }));
|
||||
expect(screen.getByTestId('current-model')).toHaveTextContent('openai/model-b');
|
||||
expect(mocks.useChat.mock.calls.at(-1)?.[0]).toMatchObject({ model: 'openai/model-b' });
|
||||
});
|
||||
|
||||
it('reverts a failed latest selection to the last confirmed workspace model', async () => {
|
||||
mocks.patchWorkspace.mockRejectedValueOnce(new Error('offline'));
|
||||
|
||||
render(<ChatWindowInstance workspaceId="workspace-1" initialModel="openai/model-a" />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select B' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('current-model')).toHaveTextContent('openai/model-a'));
|
||||
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({
|
||||
title: 'Model change failed',
|
||||
variant: 'destructive',
|
||||
}));
|
||||
expect(mocks.getModel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('serializes rapid changes and reverts the latest failure to the last successful choice', async () => {
|
||||
let resolveB!: () => void;
|
||||
const persistB = new Promise<void>((resolve) => { resolveB = resolve; });
|
||||
mocks.patchWorkspace
|
||||
.mockReturnValueOnce(persistB)
|
||||
.mockRejectedValueOnce(new Error('second write failed'));
|
||||
|
||||
render(<ChatWindowInstance workspaceId="workspace-1" initialModel="openai/model-a" />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select B' }));
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(mocks.patchWorkspace).toHaveBeenCalledTimes(1);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select C' }));
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(mocks.patchWorkspace).toHaveBeenCalledTimes(1);
|
||||
await act(async () => { resolveB(); });
|
||||
await waitFor(() => expect(mocks.patchWorkspace).toHaveBeenCalledTimes(2));
|
||||
expect(mocks.patchWorkspace.mock.calls).toEqual([
|
||||
['workspace-1', { model: 'openai/model-b' }],
|
||||
['workspace-1', { model: 'openai/model-c' }],
|
||||
]);
|
||||
await waitFor(() => expect(screen.getByTestId('current-model')).toHaveTextContent('openai/model-b'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useChat } from '@/hooks/useChat';
|
||||
import { useSessions } from '@/hooks/useSessions';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
@@ -13,6 +13,8 @@ interface ChatWindowInstanceProps {
|
||||
workspaceId: string;
|
||||
workspaceName?: string;
|
||||
initialPersona?: string;
|
||||
/** Workspace-scoped model already loaded by the shell. */
|
||||
initialModel?: string;
|
||||
/** QW-1: starter prompt prefilled into the chat input once on first mount. */
|
||||
initialMessage?: string;
|
||||
/** F2: auto-send the initialMessage once the chat is ready (wizard "Let's go"). */
|
||||
@@ -39,6 +41,7 @@ const ChatWindowInstance = ({
|
||||
workspaceId,
|
||||
workspaceName,
|
||||
initialPersona,
|
||||
initialModel,
|
||||
initialMessage,
|
||||
autoSendInitial = false,
|
||||
templateId,
|
||||
@@ -61,6 +64,26 @@ const ChatWindowInstance = ({
|
||||
|
||||
const { sessions, activeSessionId, setActiveSessionId, createSession } = useSessions(workspaceId);
|
||||
|
||||
const [currentModel, setCurrentModel] = useState<string>(initialModel ?? '');
|
||||
const currentModelRef = useRef(initialModel ?? '');
|
||||
const confirmedModelRef = useRef(initialModel ?? '');
|
||||
const initialModelRef = useRef(initialModel);
|
||||
const modelRevisionRef = useRef(0);
|
||||
const userSelectedModelRef = useRef(false);
|
||||
const modelPersistenceRef = useRef<Promise<void>>(Promise.resolve());
|
||||
|
||||
// The shell may finish loading the workspace after this kept-alive chat
|
||||
// mounts. Accept that workspace-scoped model until the user makes an
|
||||
// explicit per-window choice; a late shell refresh must not overwrite it.
|
||||
useEffect(() => {
|
||||
initialModelRef.current = initialModel;
|
||||
if (!initialModel || userSelectedModelRef.current) return;
|
||||
modelRevisionRef.current += 1;
|
||||
currentModelRef.current = initialModel;
|
||||
confirmedModelRef.current = initialModel;
|
||||
setCurrentModel(initialModel);
|
||||
}, [initialModel]);
|
||||
|
||||
// chat-session-uuid-title (P2): the server returns a real title derived from the
|
||||
// first user message, or null for a brand-new untitled session. Render a friendly
|
||||
// placeholder instead of the raw `session-<uuid>` id — covering both null/empty
|
||||
@@ -76,10 +99,10 @@ const ChatWindowInstance = ({
|
||||
workspaceId,
|
||||
sessionId: activeSessionId,
|
||||
persona: currentPersona,
|
||||
model: currentModel,
|
||||
autonomy: { level: autonomyLevel, expiresAt: autonomyExpiresAt },
|
||||
});
|
||||
|
||||
const [currentModel, setCurrentModel] = useState<string>('');
|
||||
const [availableModels, setAvailableModels] = useState<string[]>([]);
|
||||
const [teamPresence, setTeamPresence] = useState<TeamMember[]>([]);
|
||||
|
||||
@@ -127,19 +150,34 @@ const ChatWindowInstance = ({
|
||||
// Try fetching the current active model from the sidecar. Also retries on
|
||||
// transient failure — the initial render may race the sidecar spawning.
|
||||
const fetchCurrentModel = async () => {
|
||||
if (initialModelRef.current || userSelectedModelRef.current) {
|
||||
currentLanded = true;
|
||||
return;
|
||||
}
|
||||
const loadRevision = modelRevisionRef.current;
|
||||
try {
|
||||
const model = await adapter.getModel();
|
||||
if (cancelled) return;
|
||||
if (cancelled || userSelectedModelRef.current || loadRevision !== modelRevisionRef.current) {
|
||||
currentLanded = true;
|
||||
return;
|
||||
}
|
||||
if (typeof model === 'string' && model) {
|
||||
currentModelRef.current = model;
|
||||
confirmedModelRef.current = model;
|
||||
setCurrentModel(model);
|
||||
currentLanded = true;
|
||||
return;
|
||||
}
|
||||
const settings = await adapter.getSettings();
|
||||
if (cancelled) return;
|
||||
if (cancelled || userSelectedModelRef.current || loadRevision !== modelRevisionRef.current) {
|
||||
currentLanded = true;
|
||||
return;
|
||||
}
|
||||
const fromSettings = (settings as { defaultModel?: string; model?: string }).defaultModel
|
||||
?? (settings as { model?: string }).model;
|
||||
if (fromSettings) {
|
||||
currentModelRef.current = fromSettings;
|
||||
confirmedModelRef.current = fromSettings;
|
||||
setCurrentModel(fromSettings);
|
||||
currentLanded = true;
|
||||
}
|
||||
@@ -188,11 +226,38 @@ const ChatWindowInstance = ({
|
||||
}, []);
|
||||
|
||||
const handleModelChange = (model: string) => {
|
||||
if (!model || model === currentModelRef.current) return;
|
||||
userSelectedModelRef.current = true;
|
||||
const revision = ++modelRevisionRef.current;
|
||||
currentModelRef.current = model;
|
||||
setCurrentModel(model);
|
||||
adapter.setModel(model).catch((err) => console.error('[ChatWindowInstance] set model failed:', err));
|
||||
adapter.patchWorkspace(workspaceId, { model })
|
||||
.then(() => toast({ title: 'Model updated', description: `Now using ${formatModelLabel(model)}` }))
|
||||
.catch(() => toast({ title: 'Model updated locally', description: 'Backend offline — will sync when connected', variant: 'destructive' }));
|
||||
// Serialize workspace writes so two rapid clicks cannot resolve out of
|
||||
// order. The request itself already carries `model`, so the optimistic
|
||||
// selection is safe for an immediate Send while persistence completes.
|
||||
modelPersistenceRef.current = modelPersistenceRef.current
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
try {
|
||||
await adapter.patchWorkspace(workspaceId, { model });
|
||||
confirmedModelRef.current = model;
|
||||
if (revision === modelRevisionRef.current) {
|
||||
toast({ title: 'Model updated', description: `Now using ${formatModelLabel(model)}` });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[ChatWindowInstance] persist model failed:', err);
|
||||
if (revision !== modelRevisionRef.current) return;
|
||||
const confirmedModel = confirmedModelRef.current;
|
||||
currentModelRef.current = confirmedModel;
|
||||
setCurrentModel(confirmedModel);
|
||||
toast({
|
||||
title: 'Model change failed',
|
||||
description: confirmedModel
|
||||
? `Still using ${formatModelLabel(confirmedModel)}`
|
||||
: 'The previous model remains active.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -79,7 +79,7 @@ const SETUP_HINTS: Record<string, ConnectorSetupHint> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* The token/email inputs are a single shared state reused across every
|
||||
* The credential inputs are a single shared state reused across every
|
||||
* connector row. They must be cleared whenever the expanded connector
|
||||
* changes (but NOT when re-collapsing the same one) so a credential typed
|
||||
* for connector A can never be submitted to connector B. Pure so it can be
|
||||
@@ -118,6 +118,7 @@ const ConnectorsApp = ({ personaId }: ConnectorsAppProps = {}) => {
|
||||
const [expanded, setExpanded] = useState<string | null>(null);
|
||||
const [tokenInput, setTokenInput] = useState('');
|
||||
const [emailInput, setEmailInput] = useState('');
|
||||
const [instanceUrlInput, setInstanceUrlInput] = useState('');
|
||||
const [connecting, setConnecting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [revokeTarget, setRevokeTarget] = useState<ConnectorDefinition | null>(null);
|
||||
@@ -126,12 +127,14 @@ const ConnectorsApp = ({ personaId }: ConnectorsAppProps = {}) => {
|
||||
const { toast } = useToast();
|
||||
|
||||
// Expand a connector (or collapse when re-clicking the open one). Resets the
|
||||
// token/email inputs whenever the target connector changes (R4-007).
|
||||
// credential inputs whenever the target connector changes (R4-007).
|
||||
const selectConnector = (id: string | null) => {
|
||||
if (connecting) return;
|
||||
setExpanded(prev => {
|
||||
if (shouldResetCredentialInputs(prev, id)) {
|
||||
setTokenInput('');
|
||||
setEmailInput('');
|
||||
setInstanceUrlInput('');
|
||||
}
|
||||
return id;
|
||||
});
|
||||
@@ -162,13 +165,17 @@ const ConnectorsApp = ({ personaId }: ConnectorsAppProps = {}) => {
|
||||
if (!tokenInput.trim()) return;
|
||||
setConnecting(true);
|
||||
try {
|
||||
if (emailInput) {
|
||||
await adapter.addVaultSecret({ key: `connector:${id}:email`, value: emailInput });
|
||||
}
|
||||
await adapter.addVaultSecret({ key: `connector:${id}`, value: tokenInput, type: 'bearer' });
|
||||
await adapter.connectConnector(id);
|
||||
await adapter.connectConnector(id, {
|
||||
token: tokenInput.trim(),
|
||||
...(id === 'jira' ? {
|
||||
email: emailInput.trim(),
|
||||
baseUrl: instanceUrlInput.trim(),
|
||||
} : {}),
|
||||
...(id === 'salesforce' ? { instanceUrl: instanceUrlInput.trim() } : {}),
|
||||
});
|
||||
setTokenInput('');
|
||||
setEmailInput('');
|
||||
setInstanceUrlInput('');
|
||||
setExpanded(null);
|
||||
await loadConnectors();
|
||||
} catch (err) {
|
||||
@@ -277,8 +284,10 @@ const ConnectorsApp = ({ personaId }: ConnectorsAppProps = {}) => {
|
||||
onToggle={() => selectConnector(expanded === conn.id ? null : conn.id)}
|
||||
tokenInput={tokenInput}
|
||||
emailInput={emailInput}
|
||||
instanceUrlInput={instanceUrlInput}
|
||||
onTokenChange={setTokenInput}
|
||||
onEmailChange={setEmailInput}
|
||||
onInstanceUrlChange={setInstanceUrlInput}
|
||||
connecting={connecting}
|
||||
onConnect={() => void handleConnect(conn.id)}
|
||||
onDisconnect={() => void handleDisconnect(conn.id)}
|
||||
@@ -366,7 +375,8 @@ const ConnectorsApp = ({ personaId }: ConnectorsAppProps = {}) => {
|
||||
</p>
|
||||
<button
|
||||
onClick={() => selectConnector('composio')}
|
||||
className="px-2.5 py-1 rounded-lg bg-violet-500/20 text-violet-400 text-[11px] font-display hover:bg-violet-500/30 transition-colors"
|
||||
disabled={connecting}
|
||||
className="px-2.5 py-1 rounded-lg bg-violet-500/20 text-violet-400 text-[11px] font-display hover:bg-violet-500/30 disabled:opacity-50 transition-colors"
|
||||
>
|
||||
Set up Composio
|
||||
</button>
|
||||
|
||||
@@ -266,13 +266,16 @@ describe('LauncherApp · captured tasks', () => {
|
||||
expect(onOpenRoom).toHaveBeenCalledWith('room-multi');
|
||||
});
|
||||
|
||||
it('does not offer a captured task for a GUI-only tool', async () => {
|
||||
it('labels a roadmap tool and offers no launch, task, or hook actions', async () => {
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'darwin',
|
||||
detectedAt: '2026-07-11T00:00:00.000Z',
|
||||
tools: [{
|
||||
id: 'cursor',
|
||||
displayName: 'Cursor',
|
||||
id: 'cursor',
|
||||
displayName: 'Cursor',
|
||||
releaseStatus: 'roadmap',
|
||||
launchable: false,
|
||||
hookCapable: false,
|
||||
installed: true,
|
||||
installedPath: '/Applications/Cursor.app',
|
||||
version: '1.0.0',
|
||||
@@ -291,9 +294,96 @@ describe('LauncherApp · captured tasks', () => {
|
||||
|
||||
render(<LauncherApp workspaces={[{ id: 'ws-a', name: 'Alpha' }]} />);
|
||||
|
||||
expect(await screen.findByText('Cursor')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
const card = await screen.findByTestId('launcher-tool-cursor');
|
||||
expect(within(card).getByText('Roadmap')).toBeInTheDocument();
|
||||
expect(within(card).getByText(/detection retained for compatibility/i)).toBeInTheDocument();
|
||||
expect(within(card).queryByText('Detect only')).not.toBeInTheDocument();
|
||||
expect(within(card).queryByText('Hooks active')).not.toBeInTheDocument();
|
||||
expect(within(card).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument();
|
||||
expect(within(card).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
expect(within(card).queryByRole('button', { name: /install hooks/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('launches Hermes Desktop but excludes it and a broken CLI from captured teams', async () => {
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'win32',
|
||||
detectedAt: '2026-07-17T00:00:00.000Z',
|
||||
tools: [
|
||||
{
|
||||
id: 'codex',
|
||||
displayName: 'Codex CLI',
|
||||
installed: true,
|
||||
installedPath: 'C:\\tools\\codex.exe',
|
||||
version: '0.144.1',
|
||||
hooksInstalled: true,
|
||||
hookPointerPath: 'C:\\Users\\test\\.codex\\hooks.json',
|
||||
launchable: true,
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: true,
|
||||
structuredProgress: true,
|
||||
resumable: true,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: ['read-only', 'workspace-write', 'native'],
|
||||
},
|
||||
{
|
||||
id: 'hermes',
|
||||
displayName: 'Hermes Agent CLI',
|
||||
installed: true,
|
||||
installedPath: 'C:\\Users\\test\\AppData\\Local\\hermes\\bin\\hermes.cmd',
|
||||
version: null,
|
||||
hooksInstalled: false,
|
||||
hookPointerPath: null,
|
||||
launchable: false,
|
||||
diagnostic: 'Hermes failed its --version health check.',
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: true,
|
||||
structuredProgress: false,
|
||||
resumable: true,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: ['native'],
|
||||
},
|
||||
{
|
||||
id: 'hermes-desktop',
|
||||
displayName: 'Hermes Desktop',
|
||||
installed: true,
|
||||
installedPath: 'C:\\Users\\test\\AppData\\Local\\hermes\\Hermes.exe',
|
||||
version: null,
|
||||
hooksInstalled: false,
|
||||
hookPointerPath: null,
|
||||
launchable: true,
|
||||
hookCapable: false,
|
||||
capabilities: {
|
||||
interactiveLaunch: true,
|
||||
headlessTask: false,
|
||||
structuredProgress: false,
|
||||
resumable: false,
|
||||
liveWaggleDance: false,
|
||||
},
|
||||
permissionModes: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
render(<LauncherApp workspaces={[{ id: 'ws-a', name: 'Alpha' }]} />);
|
||||
|
||||
const desktopCard = await screen.findByTestId('launcher-tool-hermes-desktop');
|
||||
expect(within(desktopCard).getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
|
||||
expect(within(desktopCard).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
expect(within(desktopCard).queryByRole('button', { name: /install hooks/i })).not.toBeInTheDocument();
|
||||
expect(within(desktopCard).getByText(/launch only/i)).toBeInTheDocument();
|
||||
|
||||
const cliCard = screen.getByTestId('launcher-tool-hermes');
|
||||
expect(within(cliCard).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument();
|
||||
expect(within(cliCard).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
|
||||
expect(within(cliCard).getByText(/failed its --version health check/i)).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(screen.getByTestId('launcher-tool-codex')).getByRole('button', { name: /run task/i }));
|
||||
expect(screen.queryByRole('checkbox', { name: 'Hermes Agent CLI' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('checkbox', { name: 'Hermes Desktop' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -553,7 +643,7 @@ describe('LauncherApp · hook cohort (#3)', () => {
|
||||
expect(screen.queryByText('Install pointer')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('explains that Claude Desktop is launch-only because hooks are not supported yet', async () => {
|
||||
it('offers Claude Desktop launch and hook management from the shared manifest', async () => {
|
||||
mocks.adapter.detectTools.mockResolvedValue({
|
||||
platform: 'darwin',
|
||||
detectedAt: '2026-07-08T00:00:00.000Z',
|
||||
@@ -574,9 +664,9 @@ describe('LauncherApp · hook cohort (#3)', () => {
|
||||
|
||||
expect(await screen.findByText('Claude Desktop')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /install hooks/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /^verify$/i })).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/launch only/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/hooks are not supported for Claude Desktop yet/i)).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /install hooks/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^verify$/i })).toBeInTheDocument();
|
||||
expect(screen.queryByText(/launch only/i)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/hooks are not supported for Claude Desktop yet/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* AI-OS Phase 2B — LauncherApp.
|
||||
*
|
||||
* Dock surface for the AI-OS tool launcher. Lists every supported
|
||||
* AI tool — all 7 are launchable; 6 (all but claude-desktop) also
|
||||
* support hook install/verify/uninstall — with detection status,
|
||||
* hook-install status, and per-tool actions:
|
||||
* Dock surface for the AI-OS tool launcher. Lists registered AI execution
|
||||
* surfaces while keeping roadmap integrations visibly inert. Each card
|
||||
* includes detection status, hook-install status,
|
||||
* and its supported actions:
|
||||
*
|
||||
* Launch in workspace X / Install hooks / Verify hooks / Uninstall hooks
|
||||
*
|
||||
@@ -40,12 +40,13 @@ import {
|
||||
BUILTIN_TOOL_MANIFESTS,
|
||||
type ExternalToolAccess,
|
||||
type ToolCapabilities,
|
||||
type ToolReleaseStatus,
|
||||
} from '@waggle/shared';
|
||||
|
||||
// #5 — derived from the shared manifest registry (single source of truth),
|
||||
// replacing the hand-maintained local copies. LAUNCH_COHORT = launchable tools;
|
||||
// HOOKS_COHORT = tools whose hive-mind hook package ships a bin (hookCapable —
|
||||
// claude-desktop is the only one excluded). Mirrors the backend cohorts, which
|
||||
// HOOKS_COHORT = tools whose hive-mind hook package ships a bin (hookCapable).
|
||||
// Hermes Desktop is intentionally excluded. Mirrors the backend cohorts, which
|
||||
// derive from the same BUILTIN_TOOL_MANIFESTS.
|
||||
const LAUNCH_COHORT = BUILTIN_TOOL_MANIFESTS.filter((m) => m.launchable).map((m) => m.id);
|
||||
const HOOKS_COHORT = BUILTIN_TOOL_MANIFESTS.filter((m) => m.hookCapable).map((m) => m.id);
|
||||
@@ -53,6 +54,7 @@ const HOOKS_COHORT = BUILTIN_TOOL_MANIFESTS.filter((m) => m.hookCapable).map((m)
|
||||
interface DetectedTool {
|
||||
id: string;
|
||||
displayName: string;
|
||||
releaseStatus?: ToolReleaseStatus;
|
||||
launchable?: boolean;
|
||||
hookCapable?: boolean;
|
||||
builtin?: boolean;
|
||||
@@ -116,12 +118,15 @@ const HOOK_PATH_RE = /([A-Za-z]:\\[^\s]+|\/[^\s]+)/;
|
||||
const MAX_VISIBLE_HOOK_DETAILS = 6;
|
||||
|
||||
const toolCanLaunch = (tool: DetectedTool): boolean =>
|
||||
tool.launchable ?? LAUNCH_COHORT.includes(tool.id);
|
||||
tool.releaseStatus !== 'roadmap'
|
||||
&& (tool.launchable ?? LAUNCH_COHORT.includes(tool.id));
|
||||
|
||||
const launchUnavailableMessage = (tool: DetectedTool): string =>
|
||||
tool.installed && tool.diagnostic
|
||||
? 'Launch is blocked for this install. Follow the note above, then refresh.'
|
||||
: 'Detection ready. This adapter is not configured for launch.';
|
||||
tool.releaseStatus === 'roadmap'
|
||||
? 'Roadmap integration. Detection retained for compatibility; launch, tasks, and hooks are deferred.'
|
||||
: tool.installed && tool.diagnostic
|
||||
? 'Launch is blocked for this install. Follow the note above, then refresh.'
|
||||
: 'Detection ready. This adapter is not configured for launch.';
|
||||
|
||||
const toolUsesInlinePrompt = (tool: DetectedTool): boolean =>
|
||||
toolAcceptsInlinePrompt(tool.id) || tool.acceptsInlinePrompt === true;
|
||||
@@ -139,6 +144,7 @@ const defaultAccessForTool = (tool: DetectedTool): ExternalToolAccess | null =>
|
||||
|
||||
const toolCanRunCapturedTask = (tool: DetectedTool): boolean =>
|
||||
tool.installed &&
|
||||
toolCanLaunch(tool) &&
|
||||
tool.capabilities?.headlessTask === true &&
|
||||
(tool.permissionModes?.length ?? 0) > 0;
|
||||
|
||||
@@ -763,7 +769,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
Not installed
|
||||
</Badge>
|
||||
)}
|
||||
{tool.hooksInstalled && (
|
||||
{tool.hooksInstalled && tool.releaseStatus !== 'roadmap' && (
|
||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 h-4" style={{ background: 'var(--honey-wash)', color: 'var(--honey)' }}>
|
||||
Hooks active
|
||||
</Badge>
|
||||
@@ -786,7 +792,11 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
Running
|
||||
</button>
|
||||
)}
|
||||
{!launchable && (
|
||||
{tool.releaseStatus === 'roadmap' ? (
|
||||
<Badge variant="outline" className="text-[10px] px-1.5 py-0 h-4 text-muted-foreground">
|
||||
Roadmap
|
||||
</Badge>
|
||||
) : !launchable && (
|
||||
<Badge variant="outline" className="text-[10px] px-1.5 py-0 h-4 text-muted-foreground">
|
||||
Detect only
|
||||
</Badge>
|
||||
@@ -906,8 +916,8 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
|
||||
</div>
|
||||
{launchOnly && (
|
||||
<div className="text-[11px] text-muted-foreground">
|
||||
{tool.id === 'claude-desktop'
|
||||
? 'Hooks are not supported for Claude Desktop yet.'
|
||||
{tool.id === 'hermes-desktop'
|
||||
? 'Hook management is not supported for Hermes Desktop.'
|
||||
: 'Hook management is not supported for this tool yet.'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -36,6 +36,7 @@ import EraseDataDialog from '@/components/os/overlays/EraseDataDialog';
|
||||
import TelegramDigestCard from '@/components/os/settings/TelegramDigestCard';
|
||||
import ChannelsSettings from '@/components/os/settings/ChannelsSettings';
|
||||
import CoverageCompassCard from '@/components/os/settings/CoverageCompassCard';
|
||||
import BrowserCompanionSettings from '@/components/os/settings/BrowserCompanionSettings';
|
||||
import { AVAILABLE_SHAPES, useSelectedShape, type PromptShape } from '@/lib/shape-selection';
|
||||
import { SectionLabel } from '@/components/os/warm';
|
||||
import { ApprovalModal, type ApprovalRequest } from '@/components/ui/approval-modal';
|
||||
@@ -1110,6 +1111,7 @@ const SettingsApp = () => {
|
||||
<p className="text-[11px] text-muted-foreground font-mono">~/.waggle/</p>
|
||||
<p className="text-[11px] text-muted-foreground mt-1">All workspaces, memory, vault, and config live here.</p>
|
||||
</div>
|
||||
<BrowserCompanionSettings />
|
||||
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30" data-testid="login-briefing-setting">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<p className="text-xs font-display font-medium text-foreground">Show login briefing on each launch</p>
|
||||
|
||||
@@ -236,9 +236,9 @@ const UserProfileApp = () => {
|
||||
].filter((f): f is KnownFact => Boolean(f));
|
||||
|
||||
return (
|
||||
<div className="flex h-full">
|
||||
<div className="flex h-full min-h-0 min-w-0 flex-col sm:flex-row">
|
||||
{/* Sidebar */}
|
||||
<div className="w-36 border-r border-border/50 p-2 space-y-0.5 shrink-0" role="tablist" aria-label="Profile sections">
|
||||
<div className="grid w-full shrink-0 grid-cols-2 gap-0.5 border-b border-border/50 p-2 sm:block sm:w-36 sm:border-b-0 sm:border-r sm:space-y-0.5" role="tablist" aria-label="Profile sections">
|
||||
{tabs.map(t => (
|
||||
<button key={t.id} onClick={() => setTab(t.id)}
|
||||
role="tab"
|
||||
@@ -251,7 +251,7 @@ const UserProfileApp = () => {
|
||||
</button>
|
||||
))}
|
||||
{profile?.questionnaireCompleted && (
|
||||
<div className="mt-3 pt-3 border-t border-border/30 px-2">
|
||||
<div className="col-span-2 mt-3 border-t border-border/30 px-2 pt-3 sm:col-span-1">
|
||||
<div className="flex items-center gap-1.5 text-[11px]" style={{ color: 'var(--healthy)' }}>
|
||||
<CheckCircle2 className="w-3 h-3" /> Profile set up
|
||||
</div>
|
||||
@@ -260,7 +260,7 @@ const UserProfileApp = () => {
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 p-4 overflow-auto" role="tabpanel">
|
||||
<div className="min-h-0 min-w-0 flex-1 overflow-auto p-3 sm:p-4" role="tabpanel">
|
||||
|
||||
{/* ═══ IDENTITY ═══ */}
|
||||
{tab === 'identity' && (
|
||||
@@ -322,7 +322,7 @@ const UserProfileApp = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="profile-name" className="text-xs text-muted-foreground block mb-1">Name</label>
|
||||
<Input id="profile-name" name="name" autoComplete="name" value={name} onChange={e => setName(e.target.value)} placeholder="Marko Markovic"
|
||||
@@ -354,7 +354,7 @@ const UserProfileApp = () => {
|
||||
className="w-full bg-muted/50 border border-border/50 rounded-lg px-3 py-2 text-sm text-foreground resize-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background" />
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button onClick={handleSave} disabled={saving}
|
||||
className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/80 disabled:opacity-50 transition-colors">
|
||||
{saving ? <Loader2 className="w-3 h-3 animate-spin" /> : <Save className="w-3 h-3" />} Save
|
||||
@@ -384,7 +384,7 @@ const UserProfileApp = () => {
|
||||
data-testid="known-fact"
|
||||
>
|
||||
<span className="text-[11px] uppercase tracking-wide text-muted-foreground whitespace-nowrap">{f.label}</span>
|
||||
<span className="text-foreground break-words">{f.value}</span>
|
||||
<span className="min-w-0 break-words text-foreground">{f.value}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -418,7 +418,7 @@ const UserProfileApp = () => {
|
||||
{ws?.analyzed && (
|
||||
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30 space-y-2">
|
||||
<h4 className="text-xs font-display font-semibold text-foreground">Your Style Profile</h4>
|
||||
<div className="grid grid-cols-2 gap-2 text-xs">
|
||||
<div className="grid grid-cols-1 gap-2 text-xs sm:grid-cols-2">
|
||||
<div><span className="text-muted-foreground">Tone:</span> <span className="text-foreground capitalize">{ws.tone}</span></div>
|
||||
<div><span className="text-muted-foreground">Sentences:</span> <span className="text-foreground capitalize">{ws.sentenceLength}</span></div>
|
||||
<div><span className="text-muted-foreground">Vocabulary:</span> <span className="text-foreground capitalize">{ws.vocabulary}</span></div>
|
||||
@@ -430,7 +430,7 @@ const UserProfileApp = () => {
|
||||
|
||||
<div className="p-3 rounded-xl bg-secondary/30 border border-border/30">
|
||||
<h4 className="text-xs font-display font-semibold text-foreground mb-2">Communication Preference</h4>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{['brief', 'balanced', 'detailed'].map(s => (
|
||||
<button key={s} onClick={() => { setCommStyle(s); handleSave(); }}
|
||||
className={`px-3 py-1.5 rounded-lg text-xs font-display transition-colors ${
|
||||
@@ -455,35 +455,35 @@ const UserProfileApp = () => {
|
||||
<p className="text-[11px] text-muted-foreground">Define your brand colors and fonts. These are applied when the agent generates documents.</p>
|
||||
|
||||
{/* Color pickers */}
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-1">Primary</label>
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<input type="color" name="brandPrimaryColor" aria-label="Primary color picker" autoComplete="off" value={primaryColor} onChange={e => setPrimaryColor(e.target.value)} className="w-8 h-8 rounded border-0 cursor-pointer" />
|
||||
<Input name="brandPrimaryColorHex" aria-label="Primary color value" autoComplete="off" spellCheck={false} value={primaryColor} onChange={e => setPrimaryColor(e.target.value)}
|
||||
className="flex-1 bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
className="min-w-0 flex-1 bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-1">Secondary</label>
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<input type="color" name="brandSecondaryColor" aria-label="Secondary color picker" autoComplete="off" value={secondaryColor} onChange={e => setSecondaryColor(e.target.value)} className="w-8 h-8 rounded border-0 cursor-pointer" />
|
||||
<Input name="brandSecondaryColorHex" aria-label="Secondary color value" autoComplete="off" spellCheck={false} value={secondaryColor} onChange={e => setSecondaryColor(e.target.value)}
|
||||
className="flex-1 bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
className="min-w-0 flex-1 bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs text-muted-foreground block mb-1">Accent</label>
|
||||
<div className="flex gap-2 items-center">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<input type="color" name="brandAccentColor" aria-label="Accent color picker" autoComplete="off" value={accentColor} onChange={e => setAccentColor(e.target.value)} className="w-8 h-8 rounded border-0 cursor-pointer" />
|
||||
<Input name="brandAccentColorHex" aria-label="Accent color value" autoComplete="off" spellCheck={false} value={accentColor} onChange={e => setAccentColor(e.target.value)}
|
||||
className="flex-1 bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
className="min-w-0 flex-1 bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Fonts */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="profile-brand-heading-font" className="text-xs text-muted-foreground block mb-1">Heading Font</label>
|
||||
<Input id="profile-brand-heading-font" name="brandHeadingFont" autoComplete="off" value={fontHeading} onChange={e => setFontHeading(e.target.value)} placeholder="Inter"
|
||||
@@ -523,7 +523,7 @@ const UserProfileApp = () => {
|
||||
{/* Document template previews */}
|
||||
<div className="border-t border-border/30 pt-4">
|
||||
<h4 className="text-xs font-display font-semibold text-foreground mb-2">Document Style Previews</h4>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
||||
{[
|
||||
{ icon: FileText, label: 'Word (docx)', desc: `${fontHeading} headings, ${fontBody} body` },
|
||||
{ icon: Presentation, label: 'PowerPoint (pptx)', desc: `${primaryColor} theme` },
|
||||
|
||||
@@ -78,7 +78,7 @@ const GroupDetail = ({ group, agents, onRun, onEdit, onDuplicate }: GroupDetailP
|
||||
};
|
||||
});
|
||||
}
|
||||
if (res.status === 'running') {
|
||||
if (res.status === 'running' && !Array.isArray(workerSnapshots)) {
|
||||
const now = Date.now();
|
||||
updated.members = updated.members.map((m, i) => {
|
||||
if (m.status === 'done' || m.status === 'failed') return m;
|
||||
|
||||
@@ -6,6 +6,8 @@ import ModelSwitchBlock from './ModelSwitchBlock';
|
||||
import ArtifactBlock, { isArtifactBlock } from './ArtifactBlock';
|
||||
import ErrorBlock from './ErrorBlock';
|
||||
import RouteProposalCard from './RouteProposalCard';
|
||||
import CapabilityRequestCard, { type CapabilityRequest } from './CapabilityRequestCard';
|
||||
import { segmentText } from './capability-request-parser';
|
||||
import type { RouteProposalConfirmResponse } from '@/lib/route-proposals';
|
||||
import { ActivityStream, type ActivityStep } from '../../warm';
|
||||
import { frameSourceLabel } from '@/lib/frame-source';
|
||||
@@ -13,6 +15,8 @@ import { frameSourceLabel } from '@/lib/frame-source';
|
||||
interface BlockRendererProps {
|
||||
blocks: ContentBlock[];
|
||||
isStreaming?: boolean;
|
||||
workspaceId?: string | null;
|
||||
sessionId?: string | null;
|
||||
/** F4: re-issue the last failed turn (threaded to error blocks). */
|
||||
onRetry?: () => void;
|
||||
/** Router arc B2: a route_proposal dispatch landed (ChatApp consumes the composer text). */
|
||||
@@ -27,6 +31,29 @@ function getBlockKey(block: ContentBlock, index: number): string {
|
||||
return `${block.type}-${index}`;
|
||||
}
|
||||
|
||||
function trustedCapabilityProposals(blocks: ContentBlock[]): Map<string, CapabilityRequest> {
|
||||
const trusted = new Map<string, CapabilityRequest>();
|
||||
for (const block of blocks) {
|
||||
if (
|
||||
block.type !== 'tool_use'
|
||||
|| block.name !== 'acquire_capability'
|
||||
|| block.status !== 'done'
|
||||
|| typeof block.result !== 'string'
|
||||
) continue;
|
||||
|
||||
const segments = segmentText(block.result.trim());
|
||||
const finalSegment = segments.at(-1);
|
||||
const finalProposal = finalSegment?.kind === 'capability' ? finalSegment : null;
|
||||
if (!finalProposal) continue;
|
||||
|
||||
const { request } = finalProposal;
|
||||
const supportedRoute = (request.source === 'starter-pack' && request.kind === 'skill')
|
||||
|| (request.source === 'marketplace' && request.kind === 'marketplace');
|
||||
if (supportedRoute) trusted.set(block.id, request);
|
||||
}
|
||||
return trusted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Group ALL "thinking" steps of a turn into one collapsible Activity card —
|
||||
* the design's "the magic" surface (SCREENS §02). Default-open on the active
|
||||
@@ -71,7 +98,8 @@ function renderStepGroup(steps: StepContentBlock[], key: string, isStreaming: bo
|
||||
}
|
||||
|
||||
const BlockRenderer = ({
|
||||
blocks, isStreaming, onRetry, onRouteProposalDispatched, onRouteProposalRePropose,
|
||||
blocks, isStreaming, workspaceId, sessionId, onRetry,
|
||||
onRouteProposalDispatched, onRouteProposalRePropose,
|
||||
}: BlockRendererProps) => {
|
||||
const out: ReactNode[] = [];
|
||||
// F11: one Activity card per turn. Collect every step of the turn and render
|
||||
@@ -80,6 +108,7 @@ const BlockRenderer = ({
|
||||
// so a tool_use between two steps no longer splits the run into two cards.
|
||||
const allSteps = blocks.filter((b): b is StepContentBlock => b.type === 'step');
|
||||
const firstStepIdx = blocks.findIndex(b => b.type === 'step');
|
||||
const capabilityProposals = trustedCapabilityProposals(blocks);
|
||||
|
||||
blocks.forEach((block, i) => {
|
||||
if (block.type === 'step') {
|
||||
@@ -92,7 +121,7 @@ const BlockRenderer = ({
|
||||
case 'text':
|
||||
out.push(<TextBlock key={key} block={block} isStreaming={isStreaming && isLast} />);
|
||||
break;
|
||||
case 'tool_use':
|
||||
case 'tool_use': {
|
||||
// C2: a completed file-write IS the deliverable — render an openable
|
||||
// artifact card; in-flight/failed calls keep the generic tool row.
|
||||
out.push(
|
||||
@@ -100,7 +129,19 @@ const BlockRenderer = ({
|
||||
? <ArtifactBlock key={key} block={block} />
|
||||
: <ToolUseBlock key={key} block={block} />,
|
||||
);
|
||||
const capabilityProposal = capabilityProposals.get(block.id);
|
||||
if (capabilityProposal) {
|
||||
out.push(
|
||||
<CapabilityRequestCard
|
||||
key={`${key}-capability`}
|
||||
request={capabilityProposal}
|
||||
workspaceId={workspaceId}
|
||||
sessionId={sessionId}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'model_switch':
|
||||
out.push(<ModelSwitchBlock key={key} block={block} />);
|
||||
break;
|
||||
|
||||
@@ -1,103 +1,118 @@
|
||||
import { useId, useState } from 'react';
|
||||
import { Loader2, Download, Plug, Zap, CheckCircle2, XCircle, Package, ShieldCheck } from 'lucide-react';
|
||||
import { adapter } from '@/lib/adapter';
|
||||
import { useRef, useState } from 'react';
|
||||
import { Loader2, Download, CheckCircle2, XCircle, Package, ShieldCheck } from 'lucide-react';
|
||||
import { adapter, AdapterHttpError } from '@/lib/adapter';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useInstallStore } from '@/providers/InstallProvider';
|
||||
import { describeError, type InstallOutcome, type InstallTarget } from '@/lib/install-store';
|
||||
import { describeError } from '@/lib/install-store';
|
||||
|
||||
export interface CapabilityRequest {
|
||||
name: string;
|
||||
source: string;
|
||||
kind?: 'skill' | 'marketplace' | 'connector' | 'mcp';
|
||||
reason?: string;
|
||||
/** Connector registry id (kind 'connector'); defaults to `name`. */
|
||||
proposalId?: string;
|
||||
expiresAt?: string;
|
||||
packageId?: number;
|
||||
sourceId?: number;
|
||||
publisher?: string;
|
||||
version?: string;
|
||||
installType?: 'skill' | 'plugin' | 'mcp';
|
||||
manifestDigest?: string;
|
||||
riskStatus?: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'CLEAN';
|
||||
riskScore?: number;
|
||||
riskContentHash?: string;
|
||||
riskBlocked?: boolean;
|
||||
riskDigest?: string;
|
||||
/** Reserved parser metadata; not authorized by the current card contract. */
|
||||
connectorId?: string;
|
||||
/** Connector auth method — token-paste vs OAuth-redirect (kind 'connector'). */
|
||||
/** Reserved parser metadata; not authorized by the current card contract. */
|
||||
authType?: string;
|
||||
}
|
||||
|
||||
interface CapabilityRequestCardProps {
|
||||
request: CapabilityRequest;
|
||||
workspaceId?: string | null;
|
||||
sessionId?: string | null;
|
||||
}
|
||||
|
||||
type Phase = 'pending' | 'installing' | 'installed' | 'declined' | 'failed';
|
||||
|
||||
/**
|
||||
* Inline install affordance for agent capability requests (PR4 Variation B,
|
||||
* screen 09). Parsed out of agent text by TextBlock from a
|
||||
* `<!--waggle:capability_request {…}-->` marker (or the legacy phrasing) so the
|
||||
* user can act without leaving the conversation.
|
||||
* screen 09). Rendered only from a completed acquire_capability tool result so
|
||||
* the user can act without leaving the conversation.
|
||||
*
|
||||
* Type-aware, routed through the SHARED install store so a chat install
|
||||
* reflects in the Marketplace grid + count bar immediately ("sync"):
|
||||
* connector → vault-aware token-paste (OAuth → Hub, D3); FE-direct connect —
|
||||
* the token NEVER transits the boolean approval channel.
|
||||
* mcp → store enable (PRO + SecurityGate ride along server-side).
|
||||
* marketplace → resolve packageId by name, then store install.
|
||||
* starter → installPack (bundled; the store does not track on-disk skills).
|
||||
* The current trusted producer contract supports bundled starter-pack skills
|
||||
* and exact-name marketplace packages. Connector and MCP proposals use their
|
||||
* dedicated flows and are rejected here until they carry canonical IDs.
|
||||
*/
|
||||
export default function CapabilityRequestCard({ request }: CapabilityRequestCardProps) {
|
||||
const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
export default function CapabilityRequestCard({
|
||||
request,
|
||||
workspaceId,
|
||||
sessionId,
|
||||
}: CapabilityRequestCardProps) {
|
||||
const [phase, setPhase] = useState<Phase>('pending');
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [showToken, setShowToken] = useState(false);
|
||||
const [token, setToken] = useState('');
|
||||
const tokenInputId = useId();
|
||||
const installStarted = useRef(false);
|
||||
const { toast } = useToast();
|
||||
const { install } = useInstallStore();
|
||||
const { confirmPackageProposal } = useInstallStore();
|
||||
|
||||
const kind: NonNullable<CapabilityRequest['kind']> =
|
||||
request.kind ?? (request.source === 'marketplace' ? 'marketplace' : 'skill');
|
||||
const isConnector = kind === 'connector';
|
||||
const isMcp = kind === 'mcp';
|
||||
const isMarketplace = kind === 'marketplace' || request.source === 'marketplace';
|
||||
const isStarter = !isConnector && !isMcp && !isMarketplace;
|
||||
const kind = request.kind;
|
||||
const marketplaceIdentity = Number.isSafeInteger(request.packageId)
|
||||
&& (request.packageId ?? 0) > 0
|
||||
&& Number.isSafeInteger(request.sourceId)
|
||||
&& (request.sourceId ?? 0) > 0
|
||||
&& typeof request.proposalId === 'string'
|
||||
&& UUID_V4_RE.test(request.proposalId)
|
||||
&& typeof request.expiresAt === 'string'
|
||||
&& Number.isFinite(Date.parse(request.expiresAt))
|
||||
&& Date.parse(request.expiresAt) > Date.now()
|
||||
&& typeof request.publisher === 'string'
|
||||
&& request.publisher.trim().length > 0
|
||||
&& typeof request.version === 'string'
|
||||
&& request.version.trim().length > 0
|
||||
&& typeof request.manifestDigest === 'string'
|
||||
&& /^sha256:[0-9a-f]{64}$/i.test(request.manifestDigest)
|
||||
&& typeof request.riskStatus === 'string'
|
||||
&& ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'CLEAN'].includes(request.riskStatus)
|
||||
&& typeof request.riskScore === 'number'
|
||||
&& Number.isFinite(request.riskScore)
|
||||
&& typeof request.riskContentHash === 'string'
|
||||
&& /^(?:|[0-9a-f]{64})$/i.test(request.riskContentHash)
|
||||
&& typeof request.riskBlocked === 'boolean'
|
||||
&& typeof request.riskDigest === 'string'
|
||||
&& /^sha256:[0-9a-f]{64}$/i.test(request.riskDigest)
|
||||
&& typeof workspaceId === 'string'
|
||||
&& workspaceId.length > 0
|
||||
&& typeof sessionId === 'string'
|
||||
&& sessionId.length > 0
|
||||
&& (request.installType === 'skill'
|
||||
|| request.installType === 'plugin'
|
||||
|| request.installType === 'mcp');
|
||||
const supportedRoute = (request.source === 'starter-pack' && kind === 'skill')
|
||||
|| (request.source === 'marketplace' && kind === 'marketplace' && marketplaceIdentity);
|
||||
const isMarketplace = request.source === 'marketplace' && kind === 'marketplace';
|
||||
const isStarter = request.source === 'starter-pack' && kind === 'skill';
|
||||
|
||||
const verb = isConnector ? 'Connect' : isMcp ? 'Enable' : 'Install';
|
||||
|
||||
/** Map a store outcome → the card's terminal phase (the store already
|
||||
* toasted; tier dispatched the upgrade event via the adapter). */
|
||||
const applyOutcome = (outcome: InstallOutcome) => {
|
||||
if (outcome.ok) { setPhase('installed'); return; }
|
||||
setPhase('failed');
|
||||
setErrorMessage(
|
||||
outcome.reason === 'tier' ? 'Upgrade required'
|
||||
: outcome.reason === 'security' ? 'Blocked by the security scan'
|
||||
: outcome.reason === 'needs-credentials' ? 'A token is required'
|
||||
: 'Install failed',
|
||||
);
|
||||
};
|
||||
if (!supportedRoute) return null;
|
||||
|
||||
const handleInstall = async () => {
|
||||
// Connector: OAuth can't finish inline (D3) → hand off to the Hub; token
|
||||
// connectors reveal an inline paste row (the actual connect runs on submit).
|
||||
if (isConnector) {
|
||||
if (request.authType === 'oauth2') {
|
||||
window.dispatchEvent(new CustomEvent('waggle:open-app', { detail: { appId: 'connectors' } }));
|
||||
return;
|
||||
}
|
||||
setShowToken(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (installStarted.current) return;
|
||||
installStarted.current = true;
|
||||
setPhase('installing');
|
||||
setErrorMessage(null);
|
||||
try {
|
||||
if (isMcp) {
|
||||
applyOutcome(await install({ id: `mcp:${request.name}`, type: 'mcp', kind: 'federated', name: request.name }));
|
||||
return;
|
||||
}
|
||||
if (isMarketplace) {
|
||||
// The agent knows the name, not the numeric package id — resolve it.
|
||||
const searchRes = await adapter.searchMarketplace(request.name, 1);
|
||||
const searchData = await searchRes.json().catch(() => ({ packages: [] }));
|
||||
const pkg = (searchData.packages ?? [])[0] as { id?: number; waggle_install_type?: string } | undefined;
|
||||
if (!pkg?.id) throw new Error(`Marketplace package "${request.name}" not found`);
|
||||
const target: InstallTarget = {
|
||||
id: `pkg:${pkg.id}`, type: pkg.waggle_install_type === 'mcp' ? 'mcp' : 'skill',
|
||||
kind: 'package', name: request.name, packageId: pkg.id,
|
||||
};
|
||||
applyOutcome(await install(target));
|
||||
await confirmPackageProposal(
|
||||
request.packageId!,
|
||||
request.proposalId!,
|
||||
workspaceId!,
|
||||
sessionId!,
|
||||
);
|
||||
setPhase('installed');
|
||||
toast({ title: 'Installed', description: `${request.name} is now active.` });
|
||||
return;
|
||||
}
|
||||
// Starter pack — bundled, no auth; not store-tracked (on-disk skill).
|
||||
@@ -105,29 +120,24 @@ export default function CapabilityRequestCard({ request }: CapabilityRequestCard
|
||||
setPhase('installed');
|
||||
toast({ title: 'Installed', description: `${request.name} is now active.` });
|
||||
} catch (err) {
|
||||
const message = describeError(err);
|
||||
const proposalMessage = err instanceof AdapterHttpError
|
||||
? ({
|
||||
CAPABILITY_PROPOSAL_NOT_AVAILABLE: 'This install request is no longer available.',
|
||||
CAPABILITY_PROPOSAL_EXPIRED: 'This install request expired. Ask Waggle to find it again.',
|
||||
CAPABILITY_PROPOSAL_ALREADY_USED: 'This install request was already used.',
|
||||
} as const)[err.code as 'CAPABILITY_PROPOSAL_NOT_AVAILABLE'
|
||||
| 'CAPABILITY_PROPOSAL_EXPIRED'
|
||||
| 'CAPABILITY_PROPOSAL_ALREADY_USED']
|
||||
: undefined;
|
||||
const message = proposalMessage ?? describeError(err);
|
||||
setPhase('failed');
|
||||
setErrorMessage(message);
|
||||
toast({ title: 'Install failed', description: message, variant: 'destructive' });
|
||||
}
|
||||
};
|
||||
|
||||
const submitToken = async () => {
|
||||
setPhase('installing');
|
||||
setErrorMessage(null);
|
||||
const outcome = await install(
|
||||
{ id: `connector:${request.connectorId ?? request.name}`, type: 'connector', kind: 'federated', name: request.name },
|
||||
{ token: token.trim() },
|
||||
);
|
||||
setShowToken(false);
|
||||
setToken('');
|
||||
applyOutcome(outcome);
|
||||
};
|
||||
|
||||
const handleDecline = () => setPhase('declined');
|
||||
|
||||
const VerbIcon = isConnector ? Plug : isMcp ? Zap : Download;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="capability-request-card"
|
||||
@@ -140,7 +150,7 @@ export default function CapabilityRequestCard({ request }: CapabilityRequestCard
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-display font-semibold text-foreground">
|
||||
{verb} <span className="text-honey">{request.name}</span>?
|
||||
Install <span className="text-honey">{request.name}</span>?
|
||||
</span>
|
||||
<span className="text-[11px] px-1.5 py-0.5 rounded bg-muted/60 text-muted-foreground font-display">
|
||||
{kind}
|
||||
@@ -150,46 +160,8 @@ export default function CapabilityRequestCard({ request }: CapabilityRequestCard
|
||||
<p className="text-xs text-muted-foreground mt-1">{request.reason}</p>
|
||||
)}
|
||||
|
||||
{/* Vault-aware connector token-paste — FE-direct connect; the token
|
||||
never touches the boolean approval channel (D3). */}
|
||||
{showToken && (
|
||||
<div className="flex items-center gap-1.5 mt-2">
|
||||
<label htmlFor={tokenInputId} className="sr-only">
|
||||
{request.name} API token
|
||||
</label>
|
||||
<Input
|
||||
id={tokenInputId}
|
||||
name="capabilityConnectorToken"
|
||||
autoComplete="off"
|
||||
type="password"
|
||||
value={token}
|
||||
onChange={e => setToken(e.target.value)}
|
||||
placeholder="Paste API token — stored in your vault"
|
||||
data-testid="capability-connector-token-input"
|
||||
className="flex-1 h-7 text-[11px]"
|
||||
autoFocus
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void submitToken()}
|
||||
disabled={token.trim() === '' || phase === 'installing'}
|
||||
data-testid="capability-connector-token-submit"
|
||||
className="px-2 py-1 text-[11px] rounded-lg bg-primary text-primary-foreground hover:bg-primary/80 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Connect
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setShowToken(false); setToken(''); }}
|
||||
className="px-2 py-1 text-[11px] rounded-lg text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2 mt-2.5">
|
||||
{phase === 'pending' && !showToken && (
|
||||
{phase === 'pending' && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
@@ -197,7 +169,7 @@ export default function CapabilityRequestCard({ request }: CapabilityRequestCard
|
||||
data-testid="capability-request-install"
|
||||
className="flex items-center gap-1.5 px-2.5 py-1 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/80 font-display transition-colors"
|
||||
>
|
||||
<VerbIcon className="w-3 h-3" /> {verb}
|
||||
<Download className="w-3 h-3" /> Install
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { memo, useMemo, Fragment } from 'react';
|
||||
import { memo, useMemo } from 'react';
|
||||
import type { TextContentBlock } from '@/lib/types';
|
||||
import CapabilityRequestCard from './CapabilityRequestCard';
|
||||
import { segmentText } from './capability-request-parser';
|
||||
import { renderChatMarkdown } from '@/lib/render-markdown';
|
||||
import { useStreamCadence } from '@/hooks/useStreamCadence';
|
||||
|
||||
const CAPABILITY_MARKER_DISPLAY_RE = /<!--\s*waggle:capability_request[\s\S]*?-->/g;
|
||||
|
||||
interface TextBlockProps {
|
||||
block: TextContentBlock;
|
||||
isStreaming?: boolean;
|
||||
@@ -17,44 +17,24 @@ const TextBlock = memo(({ block, isStreaming }: TextBlockProps) => {
|
||||
// first-token latency — `raw` already holds every delivered chunk; this only
|
||||
// paces the paint. Settled/history turns + reduced-motion snap to whole text.
|
||||
const { shown, caretVisible } = useStreamCadence(raw, !!isStreaming);
|
||||
const segments = useMemo(() => segmentText(shown), [shown]);
|
||||
const displayText = useMemo(
|
||||
() => shown.replace(CAPABILITY_MARKER_DISPLAY_RE, ''),
|
||||
[shown],
|
||||
);
|
||||
|
||||
if (!raw && !isStreaming) return null;
|
||||
|
||||
// Streaming caret + bouncing-dot loader behaviour preserved from the original
|
||||
// implementation. We attach the caret to the last text segment so the visual
|
||||
// flow doesn't break when capability cards are interleaved with text.
|
||||
let cursorAttached = false;
|
||||
|
||||
return (
|
||||
<div>
|
||||
{segments.map((seg, i) => {
|
||||
if (seg.kind === 'capability') {
|
||||
return <CapabilityRequestCard key={`cap-${i}`} request={seg.request} />;
|
||||
}
|
||||
const isLastTextSegment = !cursorAttached && i === segments.length - 1;
|
||||
cursorAttached = cursorAttached || isLastTextSegment;
|
||||
return (
|
||||
<Fragment key={`txt-${i}`}>
|
||||
{/* renderChatMarkdown escapes the full input before emitting any
|
||||
tag (S04-hardened pattern) — partial markdown crossing the reveal
|
||||
head forms as escaped text, never raw noise. */}
|
||||
{seg.content && (
|
||||
<span dangerouslySetInnerHTML={{ __html: renderChatMarkdown(seg.content) }} />
|
||||
)}
|
||||
{caretVisible && isLastTextSegment && seg.content && (
|
||||
<span
|
||||
aria-hidden
|
||||
// R21 (design/competitor HIGH): the 2px caret was invisible at
|
||||
// video scale ("no blinking caret"). A 3px rounded honey bar at
|
||||
// ~1.15em reads as a live typing cursor; .stream-caret carries the
|
||||
// token'd blink (reduced-motion → solid, no blink).
|
||||
className="stream-caret inline-block w-[3px] h-[1.15em] rounded-[1.5px] bg-[var(--honey-text)] ml-0.5 align-text-bottom"
|
||||
/>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{/* Assistant text is presentation data only. renderChatMarkdown escapes
|
||||
it before emitting tags; privileged controls come from tool results. */}
|
||||
{displayText && <span dangerouslySetInnerHTML={{ __html: renderChatMarkdown(displayText) }} />}
|
||||
{caretVisible && displayText && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="stream-caret inline-block w-[3px] h-[1.15em] rounded-[1.5px] bg-[var(--honey-text)] ml-0.5 align-text-bottom"
|
||||
/>
|
||||
)}
|
||||
{isStreaming && !shown && (
|
||||
<span className="inline-flex gap-1 ml-1">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-primary/60 animate-bounce" style={{ animationDelay: '0ms' }} />
|
||||
|
||||
@@ -13,15 +13,67 @@ const MARKER_RE = /<!--\s*waggle:capability_request\s+(\{[^}]+\})\s*-->/g;
|
||||
// Falls back to this when the agent hasn't been updated to emit Pattern A.
|
||||
const LEGACY_RE = /`install_capability`\s+with\s+name\s+"([^"]+)"\s+and\s+source\s+"([^"]+)"/gi;
|
||||
|
||||
const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
const SHA256_RE = /^sha256:[0-9a-f]{64}$/i;
|
||||
const CONTENT_HASH_RE = /^(?:|[0-9a-f]{64})$/i;
|
||||
const RISK_STATUSES = new Set(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'CLEAN']);
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.trim().length > 0;
|
||||
}
|
||||
|
||||
function isMarketplaceProposal(obj: Partial<CapabilityRequest>): boolean {
|
||||
return Number.isSafeInteger(obj.packageId)
|
||||
&& (obj.packageId ?? 0) > 0
|
||||
&& Number.isSafeInteger(obj.sourceId)
|
||||
&& (obj.sourceId ?? 0) > 0
|
||||
&& isNonEmptyString(obj.proposalId)
|
||||
&& UUID_V4_RE.test(obj.proposalId)
|
||||
&& isNonEmptyString(obj.expiresAt)
|
||||
&& Number.isFinite(Date.parse(obj.expiresAt))
|
||||
&& Date.parse(obj.expiresAt) > Date.now()
|
||||
&& isNonEmptyString(obj.publisher)
|
||||
&& isNonEmptyString(obj.version)
|
||||
&& (obj.installType === 'skill' || obj.installType === 'plugin' || obj.installType === 'mcp')
|
||||
&& isNonEmptyString(obj.manifestDigest)
|
||||
&& SHA256_RE.test(obj.manifestDigest)
|
||||
&& isNonEmptyString(obj.riskStatus)
|
||||
&& RISK_STATUSES.has(obj.riskStatus)
|
||||
&& typeof obj.riskScore === 'number'
|
||||
&& Number.isFinite(obj.riskScore)
|
||||
&& typeof obj.riskContentHash === 'string'
|
||||
&& CONTENT_HASH_RE.test(obj.riskContentHash)
|
||||
&& typeof obj.riskBlocked === 'boolean'
|
||||
&& isNonEmptyString(obj.riskDigest)
|
||||
&& SHA256_RE.test(obj.riskDigest);
|
||||
}
|
||||
|
||||
function parseRequest(jsonRaw: string): CapabilityRequest | null {
|
||||
try {
|
||||
const obj = JSON.parse(jsonRaw) as Partial<CapabilityRequest>;
|
||||
if (!obj.name || !obj.source) return null;
|
||||
const isMarketplace = obj.source === 'marketplace' && obj.kind === 'marketplace';
|
||||
if (isMarketplace && !isMarketplaceProposal(obj)) return null;
|
||||
return {
|
||||
name: String(obj.name),
|
||||
source: String(obj.source),
|
||||
kind: obj.kind,
|
||||
reason: obj.reason ? String(obj.reason) : undefined,
|
||||
...(isMarketplace ? {
|
||||
proposalId: obj.proposalId,
|
||||
expiresAt: obj.expiresAt,
|
||||
packageId: obj.packageId,
|
||||
sourceId: obj.sourceId,
|
||||
publisher: obj.publisher,
|
||||
version: obj.version,
|
||||
installType: obj.installType,
|
||||
manifestDigest: obj.manifestDigest,
|
||||
riskStatus: obj.riskStatus,
|
||||
riskScore: obj.riskScore,
|
||||
riskContentHash: obj.riskContentHash,
|
||||
riskBlocked: obj.riskBlocked,
|
||||
riskDigest: obj.riskDigest,
|
||||
} : {}),
|
||||
...(obj.connectorId ? { connectorId: String(obj.connectorId) } : {}),
|
||||
...(obj.authType ? { authType: String(obj.authType) } : {}),
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*
|
||||
* Per-row async state (sync, lazy health, audit history) lives HERE; the
|
||||
* shared credential inputs + the revoke confirm stay in the parent so the
|
||||
* R4-007 credential-isolation guarantee (one shared input pair, reset on
|
||||
* R4-007 credential-isolation guarantee (one shared input set, reset on
|
||||
* target change) is preserved.
|
||||
*/
|
||||
import { useState } from 'react';
|
||||
@@ -52,11 +52,13 @@ interface ConnectorCardProps {
|
||||
hint?: ConnectorSetupHint;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
/** Shared credential inputs (single pair, parent-owned — R4-007). */
|
||||
/** Shared credential inputs (single parent-owned set — R4-007). */
|
||||
tokenInput: string;
|
||||
emailInput: string;
|
||||
instanceUrlInput: string;
|
||||
onTokenChange: (v: string) => void;
|
||||
onEmailChange: (v: string) => void;
|
||||
onInstanceUrlChange: (v: string) => void;
|
||||
connecting: boolean;
|
||||
onConnect: () => void;
|
||||
onDisconnect: () => void;
|
||||
@@ -68,7 +70,8 @@ interface ConnectorCardProps {
|
||||
|
||||
const ConnectorCard = ({
|
||||
conn, categoryLabel, hint, expanded, onToggle,
|
||||
tokenInput, emailInput, onTokenChange, onEmailChange,
|
||||
tokenInput, emailInput, instanceUrlInput,
|
||||
onTokenChange, onEmailChange, onInstanceUrlChange,
|
||||
connecting, onConnect, onDisconnect, onRevoke, onSynced,
|
||||
}: ConnectorCardProps) => {
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
@@ -79,6 +82,10 @@ const ConnectorCard = ({
|
||||
const isConnected = conn.status === 'connected';
|
||||
const isExpired = conn.status === 'expired';
|
||||
const needsEmail = conn.id === 'jira';
|
||||
const needsSiteUrl = conn.id === 'jira' || conn.id === 'salesforce';
|
||||
const credentialsComplete = Boolean(tokenInput.trim())
|
||||
&& (!needsEmail || Boolean(emailInput.trim()))
|
||||
&& (!needsSiteUrl || Boolean(instanceUrlInput.trim()));
|
||||
const identity = getBrandIdentity(conn.id, conn.name, categoryLabel);
|
||||
const badge = connectorStatusBadge(conn.status, syncing);
|
||||
|
||||
@@ -113,8 +120,8 @@ const ConnectorCard = ({
|
||||
|
||||
return (
|
||||
<div className="group rounded-xl border border-border/30 overflow-hidden transition-colors hover:border-primary/30 hover:bg-secondary/10">
|
||||
<button onClick={handleExpand} aria-expanded={expanded}
|
||||
className={cn('w-full flex items-center justify-between gap-3 p-2.5 transition-colors', CONTROL_FOCUS_CLASS)}>
|
||||
<button onClick={handleExpand} aria-expanded={expanded} disabled={connecting}
|
||||
className={cn('w-full flex items-center justify-between gap-3 p-2.5 disabled:cursor-not-allowed disabled:opacity-60 transition-colors', CONTROL_FOCUS_CLASS)}>
|
||||
<div className="flex items-center gap-2.5 min-w-0 flex-1">
|
||||
<BrandTile identity={identity} size={36} connected={isConnected} />
|
||||
<div className="text-left min-w-0 flex-1">
|
||||
@@ -220,17 +227,27 @@ const ConnectorCard = ({
|
||||
needs an explicit aria-label. */}
|
||||
{needsEmail && (
|
||||
<Input type="email" name="connectorEmail" autoComplete="email" inputMode="email" spellCheck={false}
|
||||
disabled={connecting}
|
||||
value={emailInput} onChange={e => onEmailChange(e.target.value)} placeholder="Your Atlassian email"
|
||||
aria-label="Atlassian account email"
|
||||
className="w-full bg-muted/50 text-xs h-auto py-1" />
|
||||
)}
|
||||
{needsSiteUrl && (
|
||||
<Input type="url" name={needsEmail ? 'connectorBaseUrl' : 'connectorInstanceUrl'} autoComplete="url" inputMode="url" spellCheck={false}
|
||||
disabled={connecting}
|
||||
value={instanceUrlInput} onChange={e => onInstanceUrlChange(e.target.value)}
|
||||
placeholder={needsEmail ? 'https://your-team.atlassian.net' : 'https://your-domain.my.salesforce.com'}
|
||||
aria-label={needsEmail ? 'Jira site URL' : 'Salesforce instance URL'}
|
||||
className="w-full bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Input type="password" name="connectorToken" autoComplete="off" spellCheck={false}
|
||||
disabled={connecting}
|
||||
value={tokenInput} onChange={e => onTokenChange(e.target.value)}
|
||||
placeholder={hint?.placeholder ?? 'Paste token or API key'}
|
||||
aria-label={`${conn.name} API token`}
|
||||
className="flex-1 bg-muted/50 text-xs h-auto py-1 font-mono" />
|
||||
<button onClick={onConnect} disabled={!tokenInput.trim() || connecting}
|
||||
<button onClick={onConnect} disabled={!credentialsComplete || connecting}
|
||||
className={cn('flex items-center gap-1 px-3 py-1 text-xs rounded-lg bg-primary text-primary-foreground hover:bg-primary/80 disabled:opacity-50 transition-colors', CONTROL_FOCUS_CLASS)}>
|
||||
{connecting ? <Loader2 className="w-3 h-3 animate-spin" /> : <Plug className="w-3 h-3" />} Connect
|
||||
</button>
|
||||
|
||||
@@ -10,6 +10,8 @@ const mocks = vi.hoisted(() => ({
|
||||
adapter: {
|
||||
getProviders: vi.fn(),
|
||||
getLocalInferenceStatus: vi.fn(),
|
||||
getLocalInferenceModels: vi.fn(),
|
||||
bootstrapLocalRuntime: vi.fn(),
|
||||
testApiKey: vi.fn(),
|
||||
setProviderKey: vi.fn(),
|
||||
restartModelRouter: vi.fn(),
|
||||
@@ -46,13 +48,44 @@ const providersResp = (...defs: {
|
||||
activeSearch: 'duckduckgo',
|
||||
});
|
||||
|
||||
const noLocal = { servers: [], ollamaInstalled: false, totalLocalModels: 0 };
|
||||
const noLocal = {
|
||||
servers: [{ type: 'ollama' }],
|
||||
ollamaInstalled: true,
|
||||
ollamaRunning: true,
|
||||
totalLocalModels: 0,
|
||||
offlineReady: false,
|
||||
dockerRequired: false,
|
||||
managedRuntime: {
|
||||
source: 'waggle-managed',
|
||||
supported: true,
|
||||
installed: true,
|
||||
running: true,
|
||||
targetVersion: '0.32.0',
|
||||
version: '0.32.0',
|
||||
artifactSizeBytes: 1_503_047_573,
|
||||
downloadRequired: false,
|
||||
dockerRequired: false,
|
||||
},
|
||||
setupRequired: true,
|
||||
setupMessage: null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.adapter.getProviders.mockResolvedValue(
|
||||
providersResp({ id: 'anthropic', hasKey: false }, { id: 'openai', hasKey: false }, { id: 'ollama', hasKey: false }),
|
||||
);
|
||||
mocks.adapter.getLocalInferenceStatus.mockResolvedValue(noLocal);
|
||||
mocks.adapter.getLocalInferenceModels.mockResolvedValue({
|
||||
source: 'native',
|
||||
models: [{ name: 'qwen3:1.7b', fitLevel: 'perfect', estimatedTps: 32, runMode: 'gpu' }],
|
||||
});
|
||||
mocks.adapter.bootstrapLocalRuntime.mockResolvedValue({
|
||||
ok: true,
|
||||
installedNow: true,
|
||||
startedNow: true,
|
||||
endpoint: 'http://127.0.0.1:11434',
|
||||
dockerRequired: false,
|
||||
});
|
||||
mocks.adapter.testApiKey.mockResolvedValue({ valid: true, verified: true });
|
||||
mocks.adapter.setProviderKey.mockResolvedValue({ router: { managed: true, ready: true } });
|
||||
mocks.adapter.restartModelRouter.mockResolvedValue({
|
||||
@@ -62,7 +95,11 @@ beforeEach(() => {
|
||||
unavailableProviders: [],
|
||||
});
|
||||
mocks.adapter.saveSettings.mockResolvedValue(undefined);
|
||||
mocks.adapter.pullLocalModel.mockResolvedValue({ ok: true });
|
||||
mocks.adapter.pullLocalModel.mockResolvedValue({
|
||||
ok: true,
|
||||
model: 'llama3.2:latest',
|
||||
verifiedGeneration: true,
|
||||
});
|
||||
// F3: default probe = network-degrade neutral (valid, not verified) so the
|
||||
// key-presence tests keep their "You have a working model" wording.
|
||||
mocks.adapter.probeProvider.mockResolvedValue({ configured: true, valid: true, verified: false });
|
||||
@@ -95,7 +132,7 @@ describe('ModelGate', () => {
|
||||
expect(key).toHaveAttribute('autocomplete', 'off');
|
||||
|
||||
fireEvent.click(screen.getByRole('tab', { name: /local model/i }));
|
||||
const pull = await screen.findByLabelText(/pull a model/i);
|
||||
const pull = await screen.findByLabelText(/download and verify a model/i);
|
||||
expect(pull).toHaveAttribute('name', 'modelPullName');
|
||||
expect(pull).toHaveAttribute('autocomplete', 'off');
|
||||
});
|
||||
@@ -373,15 +410,82 @@ describe('ModelGate', () => {
|
||||
expect(mocks.adapter.probeProvider).toHaveBeenCalledWith('anthropic');
|
||||
});
|
||||
|
||||
it('the local tab pulls a model and fires onModelReady', async () => {
|
||||
it('installs and starts Waggle’s managed runtime without Docker or a system Ollama install', async () => {
|
||||
mocks.adapter.getLocalInferenceStatus
|
||||
.mockResolvedValueOnce({
|
||||
...noLocal,
|
||||
servers: [],
|
||||
ollamaInstalled: false,
|
||||
ollamaRunning: false,
|
||||
managedRuntime: {
|
||||
...noLocal.managedRuntime,
|
||||
installed: false,
|
||||
running: false,
|
||||
version: null,
|
||||
downloadRequired: true,
|
||||
},
|
||||
})
|
||||
.mockResolvedValue(noLocal);
|
||||
render(<ModelGate />);
|
||||
fireEvent.click(await screen.findByRole('tab', { name: /local model/i }));
|
||||
|
||||
expect(await screen.findByText(/1\.4 GB/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/no Docker, administrator access, or system Ollama install required/i)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/install Ollama to run models/i)).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /^install runtime$/i }));
|
||||
|
||||
await waitFor(() => expect(mocks.adapter.bootstrapLocalRuntime).toHaveBeenCalledOnce());
|
||||
expect(await screen.findByText(/private runtime ready/i)).toBeInTheDocument();
|
||||
expect(await screen.findByLabelText(/download and verify a model/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not offer a fake managed install on an unsupported platform', async () => {
|
||||
mocks.adapter.getLocalInferenceStatus.mockResolvedValue({
|
||||
...noLocal,
|
||||
servers: [],
|
||||
ollamaInstalled: false,
|
||||
ollamaRunning: false,
|
||||
managedRuntime: {
|
||||
...noLocal.managedRuntime,
|
||||
supported: false,
|
||||
installed: false,
|
||||
running: false,
|
||||
version: null,
|
||||
downloadRequired: true,
|
||||
reason: 'No managed Ollama artifact for linux/x64',
|
||||
},
|
||||
});
|
||||
render(<ModelGate />);
|
||||
fireEvent.click(await screen.findByRole('tab', { name: /local model/i }));
|
||||
|
||||
expect(await screen.findByText(/no managed Ollama artifact for linux\/x64/i)).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /install runtime/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('downloads, generation-verifies, and selects the local model before reporting ready', async () => {
|
||||
const onModelReady = vi.fn();
|
||||
render(<ModelGate onModelReady={onModelReady} />);
|
||||
fireEvent.click(await screen.findByRole('tab', { name: /local model/i }));
|
||||
const input = await screen.findByLabelText(/pull a model/i);
|
||||
const input = await screen.findByLabelText(/download and verify a model/i);
|
||||
fireEvent.change(input, { target: { value: 'llama3.2' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /^pull$/i }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /^install model$/i }));
|
||||
|
||||
await waitFor(() => expect(mocks.adapter.pullLocalModel).toHaveBeenCalledWith('llama3.2'));
|
||||
expect(mocks.adapter.saveSettings).toHaveBeenCalledWith({ defaultModel: 'ollama/llama3.2:latest' });
|
||||
expect(await screen.findByText(/installed and verified "llama3\.2:latest"/i)).toBeInTheDocument();
|
||||
expect(onModelReady).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not report ready when the verified model cannot be selected as default', async () => {
|
||||
const onModelReady = vi.fn();
|
||||
mocks.adapter.saveSettings.mockRejectedValueOnce(new Error('settings unavailable'));
|
||||
render(<ModelGate onModelReady={onModelReady} />);
|
||||
fireEvent.click(await screen.findByRole('tab', { name: /local model/i }));
|
||||
const input = await screen.findByLabelText(/download and verify a model/i);
|
||||
fireEvent.change(input, { target: { value: 'llama3.2' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: /^install model$/i }));
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/could not select it as the default/i);
|
||||
expect(onModelReady).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -41,7 +41,32 @@ interface ModelGateProps {
|
||||
interface LocalStatus {
|
||||
servers: Array<Record<string, unknown>>;
|
||||
ollamaInstalled: boolean;
|
||||
ollamaRunning?: boolean;
|
||||
totalLocalModels: number;
|
||||
dockerRequired?: false;
|
||||
managedRuntime?: {
|
||||
supported: boolean;
|
||||
installed: boolean;
|
||||
running: boolean;
|
||||
targetVersion: string | null;
|
||||
version: string | null;
|
||||
artifactSizeBytes: number | null;
|
||||
downloadRequired: boolean;
|
||||
dockerRequired: false;
|
||||
reason?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface LocalModelRecommendation {
|
||||
name: string;
|
||||
fitLevel?: string;
|
||||
estimatedTps?: number;
|
||||
runMode?: string;
|
||||
}
|
||||
|
||||
function formatDownloadSize(bytes: number | null | undefined): string | null {
|
||||
if (!bytes || bytes <= 0) return null;
|
||||
return `${(bytes / (1024 ** 3)).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
type ValidateState =
|
||||
@@ -98,6 +123,9 @@ export function ModelGate({
|
||||
|
||||
// Local models
|
||||
const [local, setLocal] = useState<LocalStatus | null>(null);
|
||||
const [recommendedLocal, setRecommendedLocal] = useState<LocalModelRecommendation | null>(null);
|
||||
const [bootstrapping, setBootstrapping] = useState(false);
|
||||
const [runtimeMsg, setRuntimeMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
const [pullName, setPullName] = useState('');
|
||||
const [pulling, setPulling] = useState(false);
|
||||
const [pullMsg, setPullMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
@@ -108,6 +136,26 @@ export function ModelGate({
|
||||
} catch {
|
||||
setLocal({ servers: [], ollamaInstalled: false, totalLocalModels: 0 });
|
||||
}
|
||||
try {
|
||||
const result = await adapter.getLocalInferenceModels('general');
|
||||
const candidate = result.models.find((model) => (
|
||||
typeof model.name === 'string'
|
||||
&& model.fitLevel !== 'too_tight'
|
||||
&& model.runMode !== 'no_fit'
|
||||
));
|
||||
const recommendation: LocalModelRecommendation | null = candidate && typeof candidate.name === 'string'
|
||||
? {
|
||||
name: candidate.name,
|
||||
...(typeof candidate.fitLevel === 'string' ? { fitLevel: candidate.fitLevel } : {}),
|
||||
...(typeof candidate.estimatedTps === 'number' ? { estimatedTps: candidate.estimatedTps } : {}),
|
||||
...(typeof candidate.runMode === 'string' ? { runMode: candidate.runMode } : {}),
|
||||
}
|
||||
: null;
|
||||
setRecommendedLocal(recommendation ?? null);
|
||||
if (recommendation?.name) setPullName((current) => current || recommendation.name);
|
||||
} catch {
|
||||
setRecommendedLocal(null);
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => { void refreshLocal(); }, [refreshLocal]);
|
||||
|
||||
@@ -343,21 +391,55 @@ export function ModelGate({
|
||||
setPullMsg(null);
|
||||
try {
|
||||
const res = await adapter.pullLocalModel(name);
|
||||
if (res?.ok) {
|
||||
setPullMsg({ kind: 'ok', text: `Pulled "${name}".` });
|
||||
if (res?.ok && res.verifiedGeneration) {
|
||||
let selectedAsDefault = true;
|
||||
try {
|
||||
await adapter.saveSettings({ defaultModel: `ollama/${res.model}` });
|
||||
} catch {
|
||||
selectedAsDefault = false;
|
||||
}
|
||||
setPullMsg({
|
||||
kind: selectedAsDefault ? 'ok' : 'err',
|
||||
text: selectedAsDefault
|
||||
? `Installed and verified "${res.model}". It is now your default local model.`
|
||||
: `Installed and verified "${res.model}", but Waggle could not select it as the default.`,
|
||||
});
|
||||
setPullName('');
|
||||
await refreshLocal();
|
||||
onModelReady?.();
|
||||
if (selectedAsDefault) onModelReady?.();
|
||||
} else {
|
||||
setPullMsg({ kind: 'err', text: `Could not pull "${name}".` });
|
||||
setPullMsg({ kind: 'err', text: `Could not install and verify "${name}".` });
|
||||
}
|
||||
} catch {
|
||||
setPullMsg({ kind: 'err', text: `Could not pull "${name}" — is Ollama running?` });
|
||||
} catch (error) {
|
||||
setPullMsg({
|
||||
kind: 'err',
|
||||
text: error instanceof Error ? error.message : `Could not install and verify "${name}".`,
|
||||
});
|
||||
} finally {
|
||||
setPulling(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBootstrap = async () => {
|
||||
setBootstrapping(true);
|
||||
setRuntimeMsg(null);
|
||||
try {
|
||||
await adapter.bootstrapLocalRuntime();
|
||||
await refreshLocal();
|
||||
setRuntimeMsg({
|
||||
kind: 'ok',
|
||||
text: 'Private runtime ready. Download the recommended model to finish local setup.',
|
||||
});
|
||||
} catch (error) {
|
||||
setRuntimeMsg({
|
||||
kind: 'err',
|
||||
text: error instanceof Error ? error.message : 'Could not install the private runtime.',
|
||||
});
|
||||
} finally {
|
||||
setBootstrapping(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Round-P provider selector: a real filled-tile grid (not a pill row). The
|
||||
// fill/glyph encode key state at a glance; failing = the live probe rejected
|
||||
// the stored key (same `probe.failedProvider` signal the old chip carried).
|
||||
@@ -672,42 +754,96 @@ export function ModelGate({
|
||||
{tab === 'local' && (
|
||||
<div className="space-y-3" role="tabpanel">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{local?.ollamaInstalled
|
||||
? `Ollama detected — ${local.totalLocalModels} model${local.totalLocalModels === 1 ? '' : 's'} installed.`
|
||||
: 'No local runtime detected. Install Ollama to run models privately on your machine.'}
|
||||
{(local?.ollamaRunning ?? local?.ollamaInstalled)
|
||||
? `Private runtime running — ${local?.totalLocalModels ?? 0} model${local?.totalLocalModels === 1 ? '' : 's'} installed.`
|
||||
: local?.managedRuntime?.installed
|
||||
? 'Private runtime installed but not running. Start it here to use local models.'
|
||||
: local?.managedRuntime?.supported
|
||||
? 'No local runtime yet. Waggle can install and manage it for you.'
|
||||
: local?.managedRuntime?.reason ?? 'Managed runtime status is unavailable. Retry the check before local setup.'}
|
||||
</p>
|
||||
<div className="space-y-2 rounded-lg border border-border bg-card/60 p-3">
|
||||
<label htmlFor="model-gate-pull" className="block text-sm font-medium text-foreground">
|
||||
Pull a model
|
||||
</label>
|
||||
<Input
|
||||
id="model-gate-pull"
|
||||
name="modelPullName"
|
||||
autoComplete="off"
|
||||
value={pullName}
|
||||
onChange={(e) => setPullName(e.target.value)}
|
||||
placeholder="e.g. llama3.2"
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePull}
|
||||
disabled={pulling || !pullName.trim()}
|
||||
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"
|
||||
>
|
||||
{pulling && <Loader2 className="size-3.5 animate-spin" aria-hidden />}
|
||||
{pulling ? 'Pulling…' : 'Pull'}
|
||||
</button>
|
||||
{!(local?.ollamaRunning ?? local?.ollamaInstalled) && local?.managedRuntime?.supported && (
|
||||
<div className="space-y-2 rounded-lg border border-border bg-card/60 p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<Cpu className="mt-0.5 size-4 shrink-0 text-honey" aria-hidden />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-foreground">
|
||||
{local.managedRuntime.installed ? 'Start private runtime' : 'Install private runtime'}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
{local.managedRuntime.installed
|
||||
? 'Starts Waggle’s verified local runtime on this device.'
|
||||
: `Downloads the checksum-verified official runtime${formatDownloadSize(local.managedRuntime.artifactSizeBytes) ? ` (${formatDownloadSize(local.managedRuntime.artifactSizeBytes)})` : ''}. No Docker, administrator access, or system Ollama install required.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleBootstrap}
|
||||
disabled={bootstrapping}
|
||||
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"
|
||||
>
|
||||
{bootstrapping && <Loader2 className="size-3.5 animate-spin" aria-hidden />}
|
||||
{bootstrapping
|
||||
? 'Installing private runtime…'
|
||||
: local.managedRuntime.installed ? 'Start runtime' : 'Install runtime'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{pullMsg && (
|
||||
<p
|
||||
role={pullMsg.kind === 'err' ? 'alert' : 'status'}
|
||||
className={`text-sm ${pullMsg.kind === 'err' ? 'text-destructive' : 'text-honey'}`}
|
||||
>
|
||||
{pullMsg.text}
|
||||
)}
|
||||
{runtimeMsg && (
|
||||
<p
|
||||
role={runtimeMsg.kind === 'err' ? 'alert' : 'status'}
|
||||
className={`text-sm ${runtimeMsg.kind === 'err' ? 'text-destructive' : 'text-honey'}`}
|
||||
>
|
||||
{runtimeMsg.text}
|
||||
</p>
|
||||
)}
|
||||
{(local?.ollamaRunning ?? local?.ollamaInstalled) && (
|
||||
<div className="space-y-2 rounded-lg border border-border bg-card/60 p-3">
|
||||
<label htmlFor="model-gate-pull" className="block text-sm font-medium text-foreground">
|
||||
Download and verify a model
|
||||
</label>
|
||||
{recommendedLocal && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Recommended for this device: <span className="font-medium text-foreground">{recommendedLocal.name}</span>
|
||||
{recommendedLocal.fitLevel ? ` · ${recommendedLocal.fitLevel.replace('_', ' ')} fit` : ''}
|
||||
{typeof recommendedLocal.estimatedTps === 'number' ? ` · ~${recommendedLocal.estimatedTps} tok/s` : ''}
|
||||
</p>
|
||||
)}
|
||||
<Input
|
||||
id="model-gate-pull"
|
||||
name="modelPullName"
|
||||
autoComplete="off"
|
||||
value={pullName}
|
||||
onChange={(e) => setPullName(e.target.value)}
|
||||
placeholder="e.g. llama3.2:3b"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Model weights are downloaded to Waggle’s private data directory. By continuing, you accept the model publisher’s upstream license.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePull}
|
||||
disabled={pulling || !pullName.trim()}
|
||||
className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"
|
||||
>
|
||||
{pulling && <Loader2 className="size-3.5 animate-spin" aria-hidden />}
|
||||
{pulling ? 'Downloading and verifying…' : 'Install model'}
|
||||
</button>
|
||||
</div>
|
||||
{pullMsg && (
|
||||
<p
|
||||
role={pullMsg.kind === 'err' ? 'alert' : 'status'}
|
||||
className={`text-sm ${pullMsg.kind === 'err' ? 'text-destructive' : 'text-honey'}`}
|
||||
>
|
||||
{pullMsg.text}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -805,7 +805,7 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
|
||||
}, [selectedTemplate, templates]);
|
||||
|
||||
const handleCreate = () => {
|
||||
if (!name.trim()) return;
|
||||
if (!name.trim() || (storageType === 'local' && !storagePath.trim())) return;
|
||||
onCreate({
|
||||
name: name.trim(), group,
|
||||
persona: agentMode === 'single' ? selectedPersona : undefined,
|
||||
@@ -1316,7 +1316,7 @@ const CreateWorkspaceDialog = ({ open, onClose, onCreate }: CreateWorkspaceDialo
|
||||
|
||||
<div className="flex justify-end gap-2 px-6 py-4 border-t border-border/30">
|
||||
<button type="button" onClick={onClose} className="px-4 py-2 text-xs font-display rounded-lg text-muted-foreground hover:text-foreground transition-colors">Cancel</button>
|
||||
<button type="button" onClick={handleCreate} disabled={!name.trim()} aria-label="Create workspace"
|
||||
<button type="button" onClick={handleCreate} disabled={!name.trim() || (storageType === 'local' && !storagePath.trim())} aria-label="Create workspace"
|
||||
className="flex items-center gap-1.5 px-4 py-2 text-xs font-display rounded-lg bg-primary text-primary-foreground hover:bg-primary/80 disabled:opacity-50 transition-colors">
|
||||
<Plus className="w-3.5 h-3.5" /> Create
|
||||
</button>
|
||||
|
||||
@@ -175,6 +175,20 @@ describe('SpawnAgentDialog durable launch', () => {
|
||||
expect(modelList).toContainElement(screen.getByTitle('anthropic/claude-3-5-sonnet'));
|
||||
});
|
||||
|
||||
it('shows the retry CTA when a configured provider returns no models', async () => {
|
||||
mocks.adapter.getModels.mockResolvedValue([]);
|
||||
mocks.adapter.getModel.mockResolvedValue('');
|
||||
mocks.adapter.getProviders.mockResolvedValue({
|
||||
providers: [{ id: 'anthropic', name: 'Anthropic', hasKey: true, models: [] }],
|
||||
search: [],
|
||||
activeSearch: '',
|
||||
});
|
||||
renderDialog();
|
||||
|
||||
const retryCta = await screen.findByTestId('spawn-no-models-cta');
|
||||
expect(retryCta).toHaveTextContent('Retry');
|
||||
});
|
||||
|
||||
it('blocks launch and explains how to configure a model when no provider is ready', async () => {
|
||||
mocks.adapter.getModels.mockResolvedValue([]);
|
||||
mocks.adapter.getModel.mockResolvedValue('anthropic/claude-3-5-sonnet');
|
||||
|
||||
@@ -97,9 +97,6 @@ const SpawnAgentDialog = ({ open, onClose, workspaces, activeWorkspaceId, onWork
|
||||
const deduped = Array.from(new Set(fromProviders));
|
||||
if (deduped.length > 0) modelList = deduped;
|
||||
}
|
||||
if (modelList.length === 0 && providers.providers.some((p) => p.hasKey)) {
|
||||
setModelsError('Model list unavailable right now — retry, or check provider keys in Settings.');
|
||||
}
|
||||
setModels(modelList);
|
||||
setPricing(p);
|
||||
setProvidersWithKeys(countProvidersWithKeys(providers.providers));
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getStatus: vi.fn(),
|
||||
createCode: vi.fn(),
|
||||
revoke: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/adapter', () => ({
|
||||
adapter: {
|
||||
getBrowserCompanionPairing: mocks.getStatus,
|
||||
createBrowserCompanionPairingCode: mocks.createCode,
|
||||
revokeBrowserCompanionPairing: mocks.revoke,
|
||||
},
|
||||
}));
|
||||
|
||||
import BrowserCompanionSettings from './BrowserCompanionSettings';
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getStatus.mockResolvedValue({ paired: false, extensionId: null, pairedAt: null });
|
||||
mocks.createCode.mockResolvedValue({ code: 'ABCDEFGH', expiresAt: Date.now() + 600_000 });
|
||||
mocks.revoke.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('BrowserCompanionSettings', () => {
|
||||
it('reports that pairing status is being checked before showing an actionable state', async () => {
|
||||
let resolveStatus!: (value: { paired: boolean; extensionId: null; pairedAt: null }) => void;
|
||||
mocks.getStatus.mockReturnValue(new Promise((resolve) => { resolveStatus = resolve; }));
|
||||
|
||||
render(<BrowserCompanionSettings />);
|
||||
|
||||
expect(screen.getByTestId('browser-companion-status')).toHaveTextContent('Checking…');
|
||||
expect(screen.queryByText('Not paired')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /generate one-time code/i })).not.toBeInTheDocument();
|
||||
|
||||
resolveStatus({ paired: false, extensionId: null, pairedAt: null });
|
||||
expect(await screen.findByText('Not paired')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fails closed when pairing status is unavailable', async () => {
|
||||
mocks.getStatus.mockRejectedValue(new Error('offline'));
|
||||
|
||||
render(<BrowserCompanionSettings />);
|
||||
|
||||
expect(await screen.findByText('Unavailable')).toBeInTheDocument();
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Could not read Browser Companion pairing status.');
|
||||
expect(screen.queryByRole('button', { name: /generate one-time code/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /revoke/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('generates a code, confirms pairing, and revokes it', async () => {
|
||||
mocks.getStatus
|
||||
.mockResolvedValueOnce({ paired: false, extensionId: null, pairedAt: null })
|
||||
.mockResolvedValueOnce({ paired: true, extensionId: 'extension-id', pairedAt: '2026-08-12T00:00:00Z' });
|
||||
render(<BrowserCompanionSettings />);
|
||||
await screen.findByText('Not paired');
|
||||
fireEvent.click(screen.getByRole('button', { name: /generate one-time code/i }));
|
||||
expect(await screen.findByTestId('browser-companion-code')).toHaveTextContent('ABCDEFGH');
|
||||
expect(mocks.createCode).toHaveBeenCalledOnce();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /check pairing/i }));
|
||||
expect(await screen.findByText('Paired')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('browser-companion-code')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /generate one-time code/i })).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /revoke/i }));
|
||||
await waitFor(() => expect(mocks.revoke).toHaveBeenCalledOnce());
|
||||
expect(await screen.findByText('Not paired')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /generate one-time code/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clears an expired pairing code', async () => {
|
||||
mocks.createCode.mockResolvedValue({ code: 'ABCDEFGH', expiresAt: Date.now() - 1 });
|
||||
render(<BrowserCompanionSettings />);
|
||||
await screen.findByText('Not paired');
|
||||
fireEvent.click(screen.getByRole('button', { name: /generate one-time code/i }));
|
||||
await waitFor(() => expect(mocks.createCode).toHaveBeenCalledOnce());
|
||||
await waitFor(() => expect(screen.queryByTestId('browser-companion-code')).not.toBeInTheDocument());
|
||||
});
|
||||
});
|
||||
157
apps/web/src/components/os/settings/BrowserCompanionSettings.tsx
Normal file
157
apps/web/src/components/os/settings/BrowserCompanionSettings.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { CheckCircle2, KeyRound, Loader2, Unplug } from 'lucide-react';
|
||||
import { adapter, type BrowserCompanionPairingStatus } from '@/lib/adapter';
|
||||
|
||||
const BrowserCompanionSettings = () => {
|
||||
const [status, setStatus] = useState<BrowserCompanionPairingStatus | null>(null);
|
||||
const [pairingCode, setPairingCode] = useState<{ code: string; expiresAt: number } | null>(null);
|
||||
const [busy, setBusy] = useState<'generate' | 'check' | 'revoke' | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const refreshId = useRef(0);
|
||||
|
||||
const refresh = useCallback(async (showBusy = false) => {
|
||||
const requestId = ++refreshId.current;
|
||||
if (showBusy) setBusy('check');
|
||||
try {
|
||||
const nextStatus = await adapter.getBrowserCompanionPairing();
|
||||
if (requestId !== refreshId.current) return;
|
||||
setStatus(nextStatus);
|
||||
if (nextStatus.paired) setPairingCode(null);
|
||||
setError('');
|
||||
} catch {
|
||||
if (requestId !== refreshId.current) return;
|
||||
setError('Could not read Browser Companion pairing status.');
|
||||
} finally {
|
||||
if (showBusy && requestId === refreshId.current) setBusy(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
return () => { refreshId.current += 1; };
|
||||
}, [refresh]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pairingCode) return;
|
||||
const remainingMs = pairingCode.expiresAt - Date.now();
|
||||
if (remainingMs <= 0) {
|
||||
setPairingCode(null);
|
||||
return;
|
||||
}
|
||||
const expiryTimer = window.setTimeout(() => setPairingCode(null), remainingMs);
|
||||
return () => window.clearTimeout(expiryTimer);
|
||||
}, [pairingCode]);
|
||||
|
||||
const createCode = async () => {
|
||||
setBusy('generate');
|
||||
setPairingCode(null);
|
||||
try {
|
||||
setPairingCode(await adapter.createBrowserCompanionPairingCode());
|
||||
setError('');
|
||||
} catch {
|
||||
setError('Could not create a pairing code.');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const revoke = async () => {
|
||||
refreshId.current += 1;
|
||||
setBusy('revoke');
|
||||
try {
|
||||
await adapter.revokeBrowserCompanionPairing();
|
||||
setPairingCode(null);
|
||||
setStatus({ paired: false, extensionId: null, pairedAt: null });
|
||||
setError('');
|
||||
} catch {
|
||||
setError('Could not revoke Browser Companion pairing.');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section
|
||||
className="p-3 rounded-xl bg-secondary/30 border border-border/30 space-y-2.5"
|
||||
data-testid="browser-companion-settings"
|
||||
aria-labelledby="browser-companion-title"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h4 id="browser-companion-title" className="text-xs font-display font-medium text-foreground flex items-center gap-1.5">
|
||||
<KeyRound aria-hidden="true" className="w-3.5 h-3.5 text-honey" /> Browser Companion
|
||||
</h4>
|
||||
<p className="text-[11px] text-muted-foreground mt-1">
|
||||
Pair the extension with a short-lived, single-use code. Captures can write only to personal imported memory.
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className="text-[10px] text-muted-foreground shrink-0"
|
||||
data-testid="browser-companion-status"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
{status?.paired ? 'Paired' : status ? 'Not paired' : error ? 'Unavailable' : 'Checking…'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{status?.paired && (
|
||||
<p className="text-[11px] text-status-healthy flex items-center gap-1">
|
||||
<CheckCircle2 aria-hidden="true" className="w-3 h-3" /> Connected extension: {status.extensionId ?? 'Browser Companion'}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{pairingCode && (
|
||||
<div className="rounded-lg border border-honey/40 bg-honey/10 p-2" role="status">
|
||||
<p className="text-[10px] text-muted-foreground">Enter this code in the Browser Companion popup:</p>
|
||||
<p className="mt-1 font-mono text-lg tracking-[0.2em] text-honey" data-testid="browser-companion-code">
|
||||
{pairingCode.code}
|
||||
</p>
|
||||
<p className="text-[10px] text-muted-foreground">Expires {new Date(pairingCode.expiresAt).toLocaleTimeString()}.</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void refresh(true)}
|
||||
disabled={busy !== null}
|
||||
className="mt-2 inline-flex min-h-8 items-center gap-1.5 rounded-md bg-secondary px-2.5 py-1 text-[11px] text-foreground disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
|
||||
>
|
||||
{busy === 'check' && <Loader2 aria-hidden="true" className="w-3 h-3 animate-spin motion-reduce:animate-none" />}
|
||||
{busy === 'check' ? 'Checking…' : 'Check pairing'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p className="text-[11px] text-destructive" role="alert">{error}</p>}
|
||||
|
||||
<div className="flex gap-2">
|
||||
{status && !status.paired && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void createCode()}
|
||||
disabled={busy !== null}
|
||||
className="flex min-h-8 items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
|
||||
>
|
||||
{busy === 'generate'
|
||||
? <Loader2 aria-hidden="true" className="w-3 h-3 animate-spin motion-reduce:animate-none" />
|
||||
: <KeyRound aria-hidden="true" className="w-3 h-3" />}
|
||||
{busy === 'generate' ? 'Generating…' : 'Generate one-time code'}
|
||||
</button>
|
||||
)}
|
||||
{status?.paired && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void revoke()}
|
||||
disabled={busy !== null}
|
||||
className="flex min-h-8 items-center gap-1.5 rounded-lg bg-secondary px-3 py-1.5 text-xs text-foreground disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
|
||||
>
|
||||
{busy === 'revoke'
|
||||
? <Loader2 aria-hidden="true" className="w-3 h-3 animate-spin motion-reduce:animate-none" />
|
||||
: <Unplug aria-hidden="true" className="w-3 h-3" />}
|
||||
{busy === 'revoke' ? 'Revoking…' : 'Revoke'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
export default BrowserCompanionSettings;
|
||||
@@ -8,7 +8,12 @@ const ScrollArea = React.forwardRef<
|
||||
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
|
||||
>(({ className, children, ...props }, ref) => (
|
||||
<ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props}>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
tabIndex={0}
|
||||
className="h-full w-full rounded-[inherit] focus-visible:outline-offset-[-2px]"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
|
||||
Reference in New Issue
Block a user