mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 05:21:15 +00:00
feat(assistant): trip assistant chat with your own AI connection
Adds an in-app assistant that reads and plans the open trip. Users connect their own provider (Sign in with ChatGPT, or an Anthropic, OpenAI, Gemini or OpenRouter key) or use the one the admin set up, including a custom OpenAI-compatible server. It is an addon and only shows while a connection is usable. The chat runs on the existing MCP tools, pinned to the trip. Every change is held as a change card the user applies or discards, and applied changes can be undone. On the desktop it is a floating window that can be moved and resized; on the phone it is fullscreen. Search results show as place cards that can go onto a day, weather lookups as a strip, proposed places as ghost markers on the map with a before/after switch, and an answer can be shared into the trip chat. Booking files can be dropped in and are read into change cards.
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
// FE-COMP-INTEGRATIONS-001 to FE-COMP-INTEGRATIONS-047
|
||||
// FE-COMP-INTEGRATIONS-001 to FE-COMP-INTEGRATIONS-050
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useAddonStore } from '../../store/addonStore';
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
|
||||
import { buildUser } from '../../../tests/helpers/factories';
|
||||
import { ToastContainer } from '../shared/Toast';
|
||||
@@ -32,6 +33,20 @@ function mcpEndpointRow() {
|
||||
|
||||
const clipboardWriteText = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
const LAN_CONNECTOR = {
|
||||
mcpUrl: 'http://192.168.1.20:3000/mcp',
|
||||
deepLink: 'https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=TREK&connectorUrl=x',
|
||||
qrSvg: '<svg xmlns="http://www.w3.org/2000/svg"></svg>',
|
||||
};
|
||||
|
||||
function enableAddons(ids: string[]) {
|
||||
seedStore(useAddonStore, {
|
||||
addons: ids.map(id => ({ id, name: id, type: 'integration', icon: '', enabled: true })),
|
||||
loaded: true,
|
||||
loadAddons: vi.fn(),
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: { writeText: clipboardWriteText },
|
||||
@@ -43,6 +58,7 @@ beforeAll(() => {
|
||||
beforeEach(() => {
|
||||
clipboardWriteText.mockClear();
|
||||
resetAllStores();
|
||||
useAssistantStore.setState({ status: null });
|
||||
vi.clearAllMocks();
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
seedStore(useAddonStore, {
|
||||
@@ -55,6 +71,7 @@ beforeEach(() => {
|
||||
http.get('/api/addons', () => HttpResponse.json({ addons: [] })),
|
||||
http.get('/api/oauth/clients', () => HttpResponse.json({ clients: [] })),
|
||||
http.get('/api/oauth/sessions', () => HttpResponse.json({ sessions: [] })),
|
||||
http.get('/api/integrations/claude-connector', () => HttpResponse.json(LAN_CONNECTOR)),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -978,4 +995,55 @@ describe('IntegrationsTab – failure toasts', () => {
|
||||
await screen.findByText('Failed to revoke session');
|
||||
expect(screen.getByText('Session App')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-048: the AI assistant card follows its addon and stays off a managed install', async () => {
|
||||
server.use(
|
||||
http.get('/api/ai/status', () =>
|
||||
HttpResponse.json({
|
||||
available: false,
|
||||
policy: 'instance_or_user',
|
||||
canConnectOwn: true,
|
||||
effective: null,
|
||||
own: null,
|
||||
instance: null,
|
||||
quota: null,
|
||||
privacyAcked: false,
|
||||
retention: { mode: 'days', days: 90 },
|
||||
openrouterOAuth: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
render(<IntegrationsTab />);
|
||||
expect(screen.queryByText('AI assistant')).not.toBeInTheDocument();
|
||||
|
||||
enableAddons(['ai_assistant']);
|
||||
const { unmount } = render(<IntegrationsTab />);
|
||||
expect(await screen.findByText('What would you like to chat with?')).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
seedStore(useAuthStore, { managed: true });
|
||||
render(<IntegrationsTab />);
|
||||
expect(screen.queryByText('What would you like to chat with?')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-049: the Claude card explains why a LAN install cannot be added', async () => {
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
expect(await screen.findByText('Claude can only reach TREK when it is available over https on the internet.')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: /Open in Claude/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATIONS-050: the Claude card links a public install into Claude', async () => {
|
||||
server.use(
|
||||
http.get('/api/integrations/claude-connector', () =>
|
||||
HttpResponse.json({ ...LAN_CONNECTOR, mcpUrl: 'https://trip.example.org/mcp' }),
|
||||
),
|
||||
);
|
||||
enableMcp();
|
||||
render(<IntegrationsTab />);
|
||||
const link = await screen.findByRole('link', { name: /Open in Claude/ });
|
||||
expect(link).toHaveAttribute('href', LAN_CONNECTOR.deepLink);
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
expect(screen.getByText('https://trip.example.org/mcp')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ import PhotoProvidersSection from './PhotoProvidersSection'
|
||||
import AirTrailConnectionSection from './AirTrailConnectionSection'
|
||||
import DawarichConnectionSection from './DawarichConnectionSection'
|
||||
import LlmConnectionSection from './LlmConnectionSection'
|
||||
import AiConnectionSection from './ai/AiConnectionSection'
|
||||
import ClaudeConnectorCard from './ai/ClaudeConnectorCard'
|
||||
import ApiKeysSection from './ApiKeysSection'
|
||||
import ScopeGroupPicker from '../OAuth/ScopeGroupPicker'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
@@ -33,10 +35,15 @@ export default function IntegrationsTab(): React.ReactElement {
|
||||
{/* Which model reads a booking, and what that costs, comes with the instance on
|
||||
a managed install. The per-user fallback exists for people who supply their
|
||||
own key, and there nobody does. */}
|
||||
{/* The assistant in TREK, with the same managed rule as AI parsing: there the
|
||||
operator decides which model the install talks to. */}
|
||||
{S.aiAssistantEnabled && !managed && <AiConnectionSection />}
|
||||
{S.llmEnabled && !managed && <LlmConnectionSection />}
|
||||
{/* Above MCP on purpose: an API key needs no addon, and someone looking for
|
||||
one should not have to read past a section about AI assistants. */}
|
||||
<ApiKeysSection />
|
||||
{/* TREK inside Claude rides on the MCP server, so it follows that addon. */}
|
||||
{S.mcpEnabled && <ClaudeConnectorCard />}
|
||||
{S.mcpEnabled && <IntegrationsMcpSection S={S} />}
|
||||
<McpTokenModals S={S} />
|
||||
<OAuthClientModals S={S} />
|
||||
@@ -47,11 +54,11 @@ export default function IntegrationsTab(): React.ReactElement {
|
||||
function useIntegrations() {
|
||||
const { t, locale } = useTranslation()
|
||||
const toast = useToast()
|
||||
const { mcpEnabled, airtrailEnabled, llmEnabled, dawarichEnabled, wandererEnabled, managed } = useIntegrationGates({ reloadAddons: true })
|
||||
const { mcpEnabled, airtrailEnabled, llmEnabled, aiAssistantEnabled, dawarichEnabled, wandererEnabled, managed } = useIntegrationGates({ reloadAddons: true })
|
||||
|
||||
const mcp = useMcpIntegration({ enabled: mcpEnabled, reloadClientsAfterWrite: false })
|
||||
|
||||
return { t, locale, toast, mcpEnabled, airtrailEnabled, llmEnabled, dawarichEnabled,
|
||||
return { t, locale, toast, mcpEnabled, airtrailEnabled, llmEnabled, aiAssistantEnabled, dawarichEnabled,
|
||||
wandererEnabled,
|
||||
managed, ...mcp,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// FE-COMP-AI-CONNECT-PANEL-001 to FE-COMP-AI-CONNECT-PANEL-008: the two tiles, the key field, the ChatGPT paste step.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { AiStatusResponse } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, waitFor } from '../../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { useAddonStore } from '../../../store/addonStore';
|
||||
import { useAssistantStore } from '../../../store/assistantStore';
|
||||
|
||||
const repo = vi.hoisted(() => ({
|
||||
connectKey: vi.fn(),
|
||||
saveAdminConnection: vi.fn(),
|
||||
chatgptStart: vi.fn(),
|
||||
chatgptFinish: vi.fn(),
|
||||
openrouterStart: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
|
||||
|
||||
const { default: AiConnectPanel } = await import('./AiConnectPanel');
|
||||
|
||||
const FLOW = {
|
||||
flowId: '7d9f2c1e-3b4a-4c5d-8e6f-0a1b2c3d4e5f',
|
||||
authorizeUrl: 'https://auth.openai.com/api/accounts/authorize?x=1',
|
||||
expiresAt: new Date(Date.now() + 600_000).toISOString(),
|
||||
};
|
||||
const CALLBACK = 'http://127.0.0.1:1455/auth/callback?code=c1&state=s1&client_id=oaiapp_abc';
|
||||
|
||||
function seedStatus(over: Partial<AiStatusResponse> = {}) {
|
||||
useAssistantStore.setState({
|
||||
status: {
|
||||
available: false,
|
||||
policy: 'instance_or_user',
|
||||
canConnectOwn: true,
|
||||
effective: null,
|
||||
own: null,
|
||||
instance: null,
|
||||
quota: null,
|
||||
privacyAcked: false,
|
||||
retention: { mode: 'days', days: 90 },
|
||||
openrouterOAuth: false,
|
||||
...over,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
seedStatus();
|
||||
repo.connectKey.mockResolvedValue({});
|
||||
repo.chatgptStart.mockResolvedValue(FLOW);
|
||||
repo.chatgptFinish.mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe('AiConnectPanel', () => {
|
||||
it('FE-COMP-AI-CONNECT-PANEL-001: a user picks between ChatGPT and a key, nothing opens by itself', () => {
|
||||
render(<AiConnectPanel scope="user" onConnected={vi.fn()} />);
|
||||
expect(screen.getByRole('button', { name: /Sign in with ChatGPT/ })).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(screen.getByText('Beta')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Paste an API key/ })).toBeInTheDocument();
|
||||
expect(screen.queryByText('Own server')).not.toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('Paste your key here')).not.toBeInTheDocument();
|
||||
expect(repo.chatgptStart).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECT-PANEL-002: the admin picks between a key and an own server, prefilled from AI parsing', () => {
|
||||
render(
|
||||
<AiConnectPanel
|
||||
scope="instance"
|
||||
onConnected={vi.fn()}
|
||||
prefill={{ kind: 'custom', baseUrl: 'http://ollama:11434/v1', model: 'qwen3:8b' }}
|
||||
/>
|
||||
);
|
||||
expect(screen.queryByText('Sign in with ChatGPT')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Own server/ })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByText('Taken over from AI Parsing.')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('http://ollama:11434/v1')).toBeInTheDocument();
|
||||
expect(screen.getByDisplayValue('qwen3:8b')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Your messages and the trip data the assistant reads go to ollama:11434.')
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECT-PANEL-003: a typed key names its provider and the privacy line names it too', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<AiConnectPanel scope="user" onConnected={vi.fn()} />);
|
||||
await user.click(screen.getByRole('button', { name: /Paste an API key/ }));
|
||||
expect(screen.getByRole('link', { name: /Gemini/ })).toHaveAttribute(
|
||||
'href',
|
||||
'https://aistudio.google.com/app/apikey'
|
||||
);
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Paste your key here'), 'sk-ant-api03-abc');
|
||||
expect(screen.getByText('Detected: Anthropic')).toBeInTheDocument();
|
||||
expect(screen.getByText('Claude Max and Team include API credits.')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText('Your messages and the trip data the assistant reads go to Anthropic.')
|
||||
).toBeInTheDocument();
|
||||
expect(repo.connectKey).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECT-PANEL-004: pasting a key connects without a click', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onConnected = vi.fn();
|
||||
render(<AiConnectPanel scope="user" onConnected={onConnected} initialMode="key" />);
|
||||
await user.click(screen.getByPlaceholderText('Paste your key here'));
|
||||
await user.paste('sk-or-v1-0123456789');
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.connectKey).toHaveBeenCalledWith({ kind: 'openrouter', apiKey: 'sk-or-v1-0123456789' });
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECT-PANEL-005: the ChatGPT step links the prefetched sign-in and finishes on paste', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onConnected = vi.fn();
|
||||
render(<AiConnectPanel scope="user" onConnected={onConnected} />);
|
||||
await user.click(screen.getByRole('button', { name: /Sign in with ChatGPT/ }));
|
||||
const open = await screen.findByRole('link', { name: /Open ChatGPT sign-in/ });
|
||||
await waitFor(() => expect(open).toHaveAttribute('href', FLOW.authorizeUrl));
|
||||
expect(open).toHaveAttribute('target', '_blank');
|
||||
|
||||
await user.click(screen.getByRole('textbox', { name: 'Paste address' }));
|
||||
await user.paste(CALLBACK);
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: CALLBACK });
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECT-PANEL-006: an account ChatGPT will not share offers another provider, which opens the key field', async () => {
|
||||
repo.chatgptFinish.mockRejectedValueOnce({
|
||||
response: { status: 403, data: { error: 'no', code: 'not_eligible' } },
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
render(<AiConnectPanel scope="user" onConnected={vi.fn()} initialMode="chatgpt" />);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('link', { name: /Open ChatGPT sign-in/ })).toHaveAttribute('href', FLOW.authorizeUrl)
|
||||
);
|
||||
await user.click(screen.getByRole('textbox', { name: 'Paste address' }));
|
||||
await user.paste(CALLBACK);
|
||||
|
||||
expect(await screen.findByText('This ChatGPT account can’t be used here.')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Choose another provider' }));
|
||||
expect(screen.getByPlaceholderText('Paste your key here')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECT-PANEL-007: OpenRouter sign-in shows only where OpenRouter can return to', async () => {
|
||||
const { unmount } = render(<AiConnectPanel scope="user" onConnected={vi.fn()} initialMode="key" />);
|
||||
expect(screen.queryByRole('button', { name: /Connect OpenRouter/ })).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
seedStatus({ openrouterOAuth: true });
|
||||
render(<AiConnectPanel scope="user" onConnected={vi.fn()} initialMode="key" />);
|
||||
expect(screen.getByRole('button', { name: /Connect OpenRouter/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECT-PANEL-008: "Using Claude?" shows with the MCP addon and the sharing details fold out', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { unmount } = render(<AiConnectPanel scope="user" onConnected={vi.fn()} />);
|
||||
expect(screen.queryByText('Using Claude? Connect in Claude')).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: /What gets shared\?/ }));
|
||||
expect(screen.getByText('Not your password, your files or your other trips.')).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
seedStore(useAddonStore, { addons: [{ id: 'mcp', name: 'MCP', type: 'integration', icon: '', enabled: true }] });
|
||||
render(<AiConnectPanel scope="user" onConnected={vi.fn()} />);
|
||||
expect(screen.getByRole('button', { name: 'Using Claude? Connect in Claude' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,451 @@
|
||||
import type { AiApiKeyKind, AiConnectionScope, AiParsingPrefill } from '@trek/shared';
|
||||
import { ChevronRight, KeyRound, Loader2, Server, ShieldCheck } from 'lucide-react';
|
||||
import React, { useId, useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { useAddonStore } from '../../../store/addonStore';
|
||||
import { useAssistantStore } from '../../../store/assistantStore';
|
||||
import { AI_PROVIDERS, API_KEY_KINDS, providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { EditorField, GRID_2, INPUT } from '../../shared/dialogParts';
|
||||
import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SettingsHint, StatusPill } from '../settingsKit';
|
||||
import ChatGptPasteStep, { ConnectErrorNote } from './ChatGptPasteStep';
|
||||
import { CLAUDE_CONNECTOR_ANCHOR, type AiConnectMode } from './aiConnectModel';
|
||||
import { useChatgptConnect, useCustomConnect, useKeyConnect, useOpenrouterStart } from './useAiConnect';
|
||||
|
||||
interface AiConnectPanelProps {
|
||||
/** A user's own connection, or the one the admin sets up for everyone. */
|
||||
scope: AiConnectionScope;
|
||||
onConnected: () => void;
|
||||
/** Opens on one way at once: the sign-in to renew, the key to replace. */
|
||||
initialMode?: AiConnectMode;
|
||||
/** What AI parsing runs on, filled into the instance form while it has no connection (R14). */
|
||||
prefill?: AiParsingPrefill | null;
|
||||
}
|
||||
|
||||
/** The neutral letter tile a provider shows instead of a logo. */
|
||||
export function ProviderMark({ kind, size = 'md' }: { kind: keyof typeof AI_PROVIDERS; size?: 'sm' | 'md' }) {
|
||||
const monogram = AI_PROVIDERS[kind].monogram;
|
||||
return (
|
||||
<span
|
||||
className={`grid flex-none place-items-center bg-surface-tertiary font-bold text-content-secondary ${
|
||||
size === 'sm' ? 'h-7 w-7 rounded-lg' : 'h-8 w-8 rounded-[10px]'
|
||||
}`}
|
||||
style={fs(size === 'sm' ? 12 : 13, 'body')}
|
||||
aria-hidden
|
||||
>
|
||||
{monogram ?? <Server size={15} strokeWidth={2} />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The key tile's mark, in the provider tiles' shape. */
|
||||
function KeyMark() {
|
||||
return (
|
||||
<span
|
||||
className="grid h-8 w-8 flex-none place-items-center rounded-[10px] bg-surface-tertiary text-content-secondary"
|
||||
aria-hidden
|
||||
>
|
||||
<KeyRound size={15} strokeWidth={2} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** One way to connect, as a tile that opens its form below the pair. */
|
||||
function ModeTile({
|
||||
active,
|
||||
onClick,
|
||||
mark,
|
||||
title,
|
||||
subtitle,
|
||||
badge,
|
||||
}: {
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
mark: React.ReactNode;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
badge?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-pressed={active}
|
||||
className={`flex min-w-0 items-start gap-3 rounded-xl border bg-surface-card p-3 text-start transition-colors ${active ? 'border-[color:var(--text-primary)] shadow-sm' : 'border-edge hover:border-edge-secondary'}`}
|
||||
>
|
||||
{mark}
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex flex-wrap items-center gap-1.5">
|
||||
<span className="font-semibold text-content" style={fs(13, 'body')}>
|
||||
{title}
|
||||
</span>
|
||||
{badge}
|
||||
</span>
|
||||
<span className="mt-0.5 block leading-snug text-content-faint" style={fs(11.5)}>
|
||||
{subtitle}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The four providers a key can be for, as a quiet two-by-two grid: the mark,
|
||||
* the name and what it costs. Before a key is pasted each one links to where
|
||||
* its keys are made and remembers the choice; for a pasted key whose prefix
|
||||
* we don't know the same grid asks which provider it belongs to.
|
||||
*/
|
||||
function ProviderChips({
|
||||
ask,
|
||||
picked,
|
||||
onPick,
|
||||
}: {
|
||||
ask: boolean;
|
||||
picked: AiApiKeyKind | null;
|
||||
onPick: (kind: AiApiKeyKind) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tile = (kind: AiApiKeyKind) =>
|
||||
`flex min-w-0 items-center gap-2 rounded-lg border px-2 py-1.5 text-start transition-colors hover:bg-surface-hover ${
|
||||
picked === kind ? 'border-accent bg-surface-card ring-1 ring-accent' : 'border-edge-faint bg-surface-card hover:border-edge'
|
||||
}`;
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="font-geist font-bold uppercase tracking-[.08em] text-content-faint" style={fs(9.5)}>
|
||||
{t(ask ? 'assistant.connect.whichProvider' : 'assistant.connect.getKey')}
|
||||
</span>
|
||||
<div className="grid grid-cols-2 gap-1.5">
|
||||
{API_KEY_KINDS.map((kind) => {
|
||||
const info = AI_PROVIDERS[kind];
|
||||
const body = (
|
||||
<>
|
||||
<ProviderMark kind={kind} size="sm" />
|
||||
<span className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{info.label}
|
||||
</span>
|
||||
<span className={`truncate ${info.free ? 'text-success' : 'text-content-muted'}`} style={fs(11)}>
|
||||
{t(info.free ? 'assistant.connect.free' : 'assistant.connect.paid')}
|
||||
</span>
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
return ask ? (
|
||||
<button key={kind} type="button" onClick={() => onPick(kind)} className={tile(kind)}>
|
||||
{body}
|
||||
</button>
|
||||
) : (
|
||||
<a
|
||||
key={kind}
|
||||
href={info.keyUrl ?? undefined}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={() => onPick(kind)}
|
||||
aria-current={picked === kind ? 'true' : undefined}
|
||||
className={tile(kind)}
|
||||
>
|
||||
{body}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The key field (K2): the prefix names the provider, a paste tests the key at once. */
|
||||
function KeyForm({ scope, keyConnect }: { scope: AiConnectionScope; keyConnect: ReturnType<typeof useKeyConnect> }) {
|
||||
const { t } = useTranslation();
|
||||
const fieldId = useId();
|
||||
const { key, kind, detected, picked, change, paste, pick, submit, testing, error, needsProvider } = keyConnect;
|
||||
const openrouter = useOpenrouterStart(scope);
|
||||
const openrouterOAuth = useAssistantStore((s) => s.status?.openrouterOAuth ?? false);
|
||||
// Only a key that names its provider is "detected"; a chosen tile just stays selected below.
|
||||
const info = detected ? AI_PROVIDERS[detected] : null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<EditorField label={t('assistant.connect.key')} htmlFor={fieldId}>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id={fieldId}
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
dir="ltr"
|
||||
value={key}
|
||||
onChange={(e) => change(e.target.value)}
|
||||
onPaste={(e) => {
|
||||
if (paste(e.clipboardData.getData('text'))) e.preventDefault();
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
}}
|
||||
placeholder={t('assistant.connect.keyPlaceholder')}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void submit()}
|
||||
disabled={!kind || testing}
|
||||
className={`${SETTINGS_BUTTON_PRIMARY} whitespace-nowrap`}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{testing && <Loader2 size={14} className="animate-spin" />}
|
||||
{testing ? t('assistant.connect.testing') : t('assistant.connect.save')}
|
||||
</button>
|
||||
</div>
|
||||
</EditorField>
|
||||
|
||||
{info?.label ? (
|
||||
<div className="flex items-start gap-2.5">
|
||||
<ProviderMark kind={info.kind} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="m-0 font-medium text-content" style={fs(12.5, 'body')}>
|
||||
{t('assistant.connect.detected', { provider: info.label })}
|
||||
</p>
|
||||
{info.kind !== 'openrouter' && <SettingsHint>{t(info.hintKey)}</SettingsHint>}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<ProviderChips ask={needsProvider} picked={picked} onPick={pick} />
|
||||
)}
|
||||
|
||||
{error && <ConnectErrorNote error={error} provider={kind ? (AI_PROVIDERS[kind].label ?? '') : ''} />}
|
||||
|
||||
{/* OpenRouter can hand over a key itself, but only back to an https address. */}
|
||||
{openrouterOAuth && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-t border-edge-faint pt-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void openrouter.start()}
|
||||
disabled={openrouter.busy}
|
||||
className={SETTINGS_BUTTON}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{openrouter.busy ? (
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
) : (
|
||||
<span className="font-bold text-content-secondary" aria-hidden>
|
||||
{AI_PROVIDERS.openrouter.monogram}
|
||||
</span>
|
||||
)}
|
||||
{t('assistant.connect.openrouter')}
|
||||
</button>
|
||||
<SettingsHint>{t('assistant.connect.hintOpenrouter')}</SettingsHint>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** An own OpenAI-compatible server, for the instance only (#1772). */
|
||||
function CustomForm({ custom }: { custom: ReturnType<typeof useCustomConnect> }) {
|
||||
const { t } = useTranslation();
|
||||
const fieldId = useId();
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<EditorField
|
||||
label={t('assistant.admin.baseUrl')}
|
||||
htmlFor={`${fieldId}-url`}
|
||||
hint={t('assistant.admin.customHint')}
|
||||
>
|
||||
<input
|
||||
id={`${fieldId}-url`}
|
||||
type="url"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
dir="ltr"
|
||||
className={INPUT}
|
||||
value={custom.baseUrl}
|
||||
onChange={(e) => custom.setBaseUrl(e.target.value)}
|
||||
placeholder="http://localhost:11434/v1"
|
||||
/>
|
||||
</EditorField>
|
||||
<div className={GRID_2}>
|
||||
<EditorField label={t('assistant.admin.apiKeyOptional')} htmlFor={`${fieldId}-key`}>
|
||||
<input
|
||||
id={`${fieldId}-key`}
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
dir="ltr"
|
||||
className={`${INPUT} font-mono`}
|
||||
value={custom.apiKey}
|
||||
onChange={(e) => custom.setApiKey(e.target.value)}
|
||||
/>
|
||||
</EditorField>
|
||||
<EditorField label={t('assistant.connect.model')} htmlFor={`${fieldId}-model`}>
|
||||
<input
|
||||
id={`${fieldId}-model`}
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
dir="ltr"
|
||||
className={`${INPUT} font-geist`}
|
||||
value={custom.model}
|
||||
onChange={(e) => custom.setModel(e.target.value)}
|
||||
placeholder="qwen3:8b"
|
||||
/>
|
||||
</EditorField>
|
||||
</div>
|
||||
{custom.error && <ConnectErrorNote error={custom.error} provider={custom.host} />}
|
||||
<div className="flex">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void custom.submit()}
|
||||
disabled={!custom.ready || custom.saving}
|
||||
className={SETTINGS_BUTTON_PRIMARY}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{custom.saving && <Loader2 size={14} className="animate-spin" />}
|
||||
{custom.saving ? t('assistant.connect.testing') : t('assistant.connect.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What leaves TREK, said before anything is saved: the provider by name once
|
||||
* it is known, and the three lines behind "What gets shared?".
|
||||
*/
|
||||
function PrivacyNote({ provider }: { provider: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div className="rounded-[12px] bg-surface-tertiary px-3 py-2.5">
|
||||
{provider && (
|
||||
<p className="m-0 mb-1.5 leading-snug text-content-secondary" style={fs(12, 'body')}>
|
||||
{t('assistant.privacy.banner', { provider })}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
aria-expanded={open}
|
||||
className="inline-flex items-center gap-1.5 font-medium text-content-muted hover:text-content"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<ShieldCheck size={13} strokeWidth={2.2} />
|
||||
{t('assistant.privacy.what')}
|
||||
<ChevronRight
|
||||
size={13}
|
||||
strokeWidth={2.2}
|
||||
className={`transition-transform ${open ? 'rotate-90' : 'rtl:rotate-180'}`}
|
||||
/>
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="m-0 mt-2 flex list-disc flex-col gap-1 ps-5 text-content-faint" style={fs(11.5)}>
|
||||
<li>{t('assistant.privacy.shared')}</li>
|
||||
<li>{t('assistant.privacy.notShared')}</li>
|
||||
{provider && <li>{t('assistant.privacy.provider', { provider })}</li>}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The two ways each scope offers: ChatGPT is never an instance's, an own server never a user's (#1772). */
|
||||
const SCOPE_MODES: Record<AiConnectionScope, readonly AiConnectMode[]> = {
|
||||
user: ['chatgpt', 'key'],
|
||||
instance: ['key', 'custom'],
|
||||
};
|
||||
|
||||
const MODE_TILES: Record<
|
||||
AiConnectMode,
|
||||
{ titleKey: string; subtitleKey: string; mark: React.ReactNode; beta?: boolean }
|
||||
> = {
|
||||
chatgpt: {
|
||||
titleKey: 'assistant.connect.chatgpt',
|
||||
subtitleKey: 'assistant.connect.chatgptHint',
|
||||
mark: <ProviderMark kind="chatgpt" />,
|
||||
beta: true,
|
||||
},
|
||||
key: { titleKey: 'assistant.connect.key', subtitleKey: 'assistant.setup.keySubtitle', mark: <KeyMark /> },
|
||||
custom: {
|
||||
titleKey: 'assistant.admin.custom',
|
||||
subtitleKey: 'assistant.admin.customHint',
|
||||
mark: <ProviderMark kind="custom" />,
|
||||
},
|
||||
};
|
||||
|
||||
/** The form a prefill from AI parsing opens on. */
|
||||
function prefillModeOf(prefill: AiParsingPrefill | null): AiConnectMode | null {
|
||||
if (!prefill) return null;
|
||||
return prefill.kind === 'custom' ? 'custom' : 'key';
|
||||
}
|
||||
|
||||
/**
|
||||
* Connecting a provider in under a minute: two tiles, and the form of the one
|
||||
* picked below them. A user picks between signing in with ChatGPT and pasting
|
||||
* a key; the admin, setting up the connection for everyone, between a key and
|
||||
* an own server. ChatGPT is never shared across an instance, an own server
|
||||
* never named by a user (#1772): the server refuses both, so they are not offered.
|
||||
*/
|
||||
export default function AiConnectPanel({ scope, onConnected, initialMode, prefill = null }: AiConnectPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const [mode, setMode] = useState<AiConnectMode | null>(() => {
|
||||
const first = initialMode ?? prefillModeOf(prefill);
|
||||
return first && SCOPE_MODES[scope].includes(first) ? first : null;
|
||||
});
|
||||
const chatgpt = useChatgptConnect({ active: scope === 'user' && mode === 'chatgpt', onConnected });
|
||||
const keyConnect = useKeyConnect({ scope, prefill, onConnected });
|
||||
const custom = useCustomConnect({ prefill, onConnected });
|
||||
const mcpEnabled = useAddonStore((s) => s.isEnabled('mcp'));
|
||||
|
||||
// The privacy line names whoever would receive the messages, once that is known.
|
||||
const receivers: Record<AiConnectMode, string> = {
|
||||
chatgpt: providerLabel('chatgpt', ''),
|
||||
key: keyConnect.kind ? providerLabel(keyConnect.kind, '') : '',
|
||||
custom: custom.host,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="m-0 font-medium text-content" style={fs(13, 'body')}>
|
||||
{t('assistant.setup.question')}
|
||||
</p>
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t('assistant.setup.question')}
|
||||
className="grid grid-cols-2 gap-2 max-sm:grid-cols-1"
|
||||
>
|
||||
{SCOPE_MODES[scope].map((m) => {
|
||||
const tile = MODE_TILES[m];
|
||||
return (
|
||||
<ModeTile
|
||||
key={m}
|
||||
active={mode === m}
|
||||
onClick={() => setMode(m)}
|
||||
mark={tile.mark}
|
||||
title={t(tile.titleKey)}
|
||||
subtitle={t(tile.subtitleKey)}
|
||||
badge={tile.beta ? <StatusPill>{t('assistant.setup.beta')}</StatusPill> : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{scope === 'instance' && prefill && <SettingsHint>{t('assistant.admin.prefilled')}</SettingsHint>}
|
||||
|
||||
{mode === 'chatgpt' && <ChatGptPasteStep chatgpt={chatgpt} onOtherProvider={() => setMode('key')} />}
|
||||
{mode === 'key' && <KeyForm scope={scope} keyConnect={keyConnect} />}
|
||||
{mode === 'custom' && <CustomForm custom={custom} />}
|
||||
|
||||
<PrivacyNote provider={mode ? receivers[mode] : ''} />
|
||||
{scope === 'user' && mcpEnabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
document.getElementById(CLAUDE_CONNECTOR_ANCHOR)?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
}
|
||||
className="self-start font-medium text-content-muted underline underline-offset-2 hover:text-content"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
{t('assistant.connect.claudeLink')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// FE-COMP-AI-FOLLOW-001 to 003: the "map follows the assistant" switch, in both AI settings shells.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { AiStatusResponse } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildUser } from '../../../../tests/helpers/factories';
|
||||
import { render, screen } from '../../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { useAssistantStore } from '../../../store/assistantStore';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
|
||||
const repo = vi.hoisted(() => ({ status: vi.fn(), models: vi.fn() }));
|
||||
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
|
||||
|
||||
const { default: AiConnectionSection } = await import('./AiConnectionSection');
|
||||
const { default: MAiConnectionSection } = await import('../../../mobile/screens/settings/MAiConnectionSection');
|
||||
|
||||
const INSTANCE: AiStatusResponse = {
|
||||
available: true,
|
||||
policy: 'instance',
|
||||
canConnectOwn: false,
|
||||
effective: { source: 'instance', kind: 'openai', model: 'gpt', host: 'api.openai.com', paidBy: 'instance' },
|
||||
own: null,
|
||||
instance: { kind: 'openai', model: 'gpt', host: 'api.openai.com' },
|
||||
quota: null,
|
||||
privacyAcked: true,
|
||||
retention: { mode: 'days', days: 90 },
|
||||
openrouterOAuth: false,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
useAssistantStore.setState({ status: null });
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
repo.models.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
describe('AI settings: the map follows the assistant', () => {
|
||||
it('FE-COMP-AI-FOLLOW-001: on by default once the assistant runs, and switching it off saves the setting', async () => {
|
||||
const user = userEvent.setup();
|
||||
repo.status.mockResolvedValue(INSTANCE);
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
useSettingsStore.setState({ updateSetting });
|
||||
render(<AiConnectionSection />);
|
||||
|
||||
const toggle = await screen.findByRole('button', { name: 'Map follows the assistant' });
|
||||
expect(toggle).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByText('The map pans to where the assistant searches and suggests places.')).toBeInTheDocument();
|
||||
await user.click(toggle);
|
||||
expect(updateSetting).toHaveBeenCalledWith('assistant_map_follow', false);
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-FOLLOW-002: not offered before there is an assistant to follow', async () => {
|
||||
repo.status.mockResolvedValue({
|
||||
...INSTANCE,
|
||||
available: false,
|
||||
instance: null,
|
||||
effective: null,
|
||||
policy: 'instance_or_user',
|
||||
canConnectOwn: true,
|
||||
});
|
||||
render(<AiConnectionSection />);
|
||||
expect(await screen.findByText('What would you like to chat with?')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Map follows the assistant' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-FOLLOW-003: the phone card has the same switch on the same setting', async () => {
|
||||
const user = userEvent.setup();
|
||||
repo.status.mockResolvedValue(INSTANCE);
|
||||
const updateSetting = vi.fn().mockResolvedValue(undefined);
|
||||
useSettingsStore.setState((s) => ({ updateSetting, settings: { ...s.settings, assistant_map_follow: false } }));
|
||||
render(<MAiConnectionSection />);
|
||||
|
||||
const toggle = await screen.findByRole('switch', { name: 'Map follows the assistant' });
|
||||
expect(toggle).toHaveAttribute('aria-checked', 'false');
|
||||
await user.click(toggle);
|
||||
expect(updateSetting).toHaveBeenCalledWith('assistant_map_follow', true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
// FE-COMP-AI-CONNECTION-001 to FE-COMP-AI-CONNECTION-007: Settings → Integrations → AI assistant.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { AiConnectionView, AiStatusResponse } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { buildAdmin, buildUser } from '../../../../tests/helpers/factories';
|
||||
import { render, screen, waitFor } from '../../../../tests/helpers/render';
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { useAssistantStore } from '../../../store/assistantStore';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
|
||||
const repo = vi.hoisted(() => ({
|
||||
status: vi.fn(),
|
||||
models: vi.fn(),
|
||||
setModel: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
chatgptSignOut: vi.fn(),
|
||||
connectKey: vi.fn(),
|
||||
chatgptStart: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
|
||||
|
||||
const { default: AiConnectionSection } = await import('./AiConnectionSection');
|
||||
|
||||
const OWN: AiConnectionView = {
|
||||
scope: 'user',
|
||||
kind: 'anthropic',
|
||||
model: 'claude-sonnet',
|
||||
hint: '…a1b2',
|
||||
status: 'ok',
|
||||
host: 'api.anthropic.com',
|
||||
};
|
||||
|
||||
function status(over: Partial<AiStatusResponse> = {}): AiStatusResponse {
|
||||
return {
|
||||
available: false,
|
||||
policy: 'instance_or_user',
|
||||
canConnectOwn: true,
|
||||
effective: null,
|
||||
own: null,
|
||||
instance: null,
|
||||
quota: null,
|
||||
privacyAcked: false,
|
||||
retention: { mode: 'days', days: 90 },
|
||||
openrouterOAuth: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
useAssistantStore.setState({ status: null });
|
||||
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
|
||||
repo.models.mockResolvedValue([{ id: 'claude-sonnet', label: 'Claude Sonnet', supportsTools: true }]);
|
||||
repo.disconnect.mockResolvedValue(undefined);
|
||||
repo.chatgptStart.mockResolvedValue({
|
||||
flowId: '7d9f2c1e-3b4a-4c5d-8e6f-0a1b2c3d4e5f',
|
||||
authorizeUrl: 'https://auth.openai.com/api/accounts/authorize?x=1',
|
||||
expiresAt: new Date(Date.now() + 600_000).toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
describe('AiConnectionSection', () => {
|
||||
it('FE-COMP-AI-CONNECTION-001: without a connection the card is the setup', async () => {
|
||||
repo.status.mockResolvedValue(status());
|
||||
render(<AiConnectionSection />);
|
||||
expect(await screen.findByText('What would you like to chat with?')).toBeInTheDocument();
|
||||
expect(screen.getByText('AI assistant')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Set up for everyone')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECTION-002: an own key shows who answers, its model, and disconnects after asking', async () => {
|
||||
const user = userEvent.setup();
|
||||
repo.status.mockResolvedValueOnce(status({ own: OWN, available: true })).mockResolvedValue(status());
|
||||
render(<AiConnectionSection />);
|
||||
expect(await screen.findByText('Connected to Anthropic')).toBeInTheDocument();
|
||||
expect(screen.getByText('…a1b2')).toBeInTheDocument();
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument();
|
||||
expect(screen.getByText('Model')).toBeInTheDocument();
|
||||
expect(screen.getByText('Chats are deleted after 90 days.')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Disconnect/ }));
|
||||
expect(screen.getByText('Disconnect Anthropic? Your chats stay.')).toBeInTheDocument();
|
||||
const confirm = screen.getAllByRole('button', { name: /Disconnect/ });
|
||||
await user.click(confirm[confirm.length - 1]);
|
||||
await waitFor(() => expect(repo.disconnect).toHaveBeenCalledTimes(1));
|
||||
expect(await screen.findByText('What would you like to chat with?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECTION-003: a ChatGPT sign-in signs out instead of disconnecting', async () => {
|
||||
repo.status.mockResolvedValue(
|
||||
status({ own: { ...OWN, kind: 'chatgpt', hint: 'me@example.org', host: 'api.openai.com' }, available: true })
|
||||
);
|
||||
render(<AiConnectionSection />);
|
||||
expect(await screen.findByText('Connected to ChatGPT')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Sign out/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Disconnect/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECTION-004: a key that stopped working says so and opens the key field to replace it', async () => {
|
||||
const user = userEvent.setup();
|
||||
repo.status.mockResolvedValue(status({ own: { ...OWN, status: 'error' } }));
|
||||
render(<AiConnectionSection />);
|
||||
expect(await screen.findByText('Your Anthropic key doesn’t work anymore.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Model')).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Replace key' }));
|
||||
expect(screen.getByPlaceholderText('Paste your key here')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
expect(screen.queryByPlaceholderText('Paste your key here')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECTION-005: the admin connection shows with today’s share, and one’s own can still be added', async () => {
|
||||
const user = userEvent.setup();
|
||||
repo.status.mockResolvedValue(
|
||||
status({
|
||||
instance: { kind: 'openai', model: 'gpt-5.5', host: 'api.openai.com' },
|
||||
quota: { used: 3, limit: 50 },
|
||||
available: true,
|
||||
})
|
||||
);
|
||||
render(<AiConnectionSection />);
|
||||
expect(await screen.findByText('Provided by your admin')).toBeInTheDocument();
|
||||
expect(screen.getByText('OpenAI, gpt-5.5')).toBeInTheDocument();
|
||||
expect(screen.getByText('3 of 50 messages used today')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Connect your own provider' }));
|
||||
expect(screen.getByText('What would you like to chat with?')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECTION-006: only the admin policy hides the setup, and an admin is sent to set it up for everyone', async () => {
|
||||
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
|
||||
repo.status.mockResolvedValue(status({ policy: 'instance', canConnectOwn: false }));
|
||||
render(<AiConnectionSection />);
|
||||
expect(await screen.findByText('Your admin sets this up.')).toBeInTheDocument();
|
||||
expect(screen.queryByText('What would you like to chat with?')).not.toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Set up for everyone' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-AI-CONNECTION-007: a refused status keeps the card away', async () => {
|
||||
repo.status.mockRejectedValue(new Error('404'));
|
||||
const { container } = render(<AiConnectionSection />);
|
||||
await waitFor(() => expect(container).toBeEmptyDOMElement());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,273 @@
|
||||
import type { AiConnectionKind, AiConnectionView } from '@trek/shared';
|
||||
import { Loader2, LogOut, MessageCircle, Sparkles, Unplug } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import ConfirmDialog from '../../shared/ConfirmDialog';
|
||||
import CustomSelect from '../../shared/CustomSelect';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { useAssistantMapFollow } from '../../Assistant/useAssistantMapFollow';
|
||||
import Section from '../Section';
|
||||
import {
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_BUTTON_DANGER,
|
||||
SETTINGS_BUTTON_PRIMARY,
|
||||
SettingRow,
|
||||
SettingRows,
|
||||
SettingsHint,
|
||||
StatusPill,
|
||||
} from '../settingsKit';
|
||||
import ToggleSwitch from '../ToggleSwitch';
|
||||
import AiConnectPanel, { ProviderMark } from './AiConnectPanel';
|
||||
import { CONNECTION_STATUS } from './aiConnectModel';
|
||||
import { useAiConnections } from './useAiConnections';
|
||||
|
||||
type AiConnections = ReturnType<typeof useAiConnections>;
|
||||
|
||||
/** What a connection that stopped working says before its one way back. */
|
||||
const BROKEN: Partial<Record<AiConnectionView['status'], { messageKey: string }>> = {
|
||||
needs_reauth: { messageKey: 'assistant.error.needsReauth' },
|
||||
error: { messageKey: 'assistant.error.invalidKey' },
|
||||
};
|
||||
|
||||
/** A connection as one row: the provider's tile, who it is and the detail under it, the actions on the right. */
|
||||
function ConnectionRow({
|
||||
kind,
|
||||
title,
|
||||
detail,
|
||||
children,
|
||||
}: {
|
||||
kind: AiConnectionKind;
|
||||
title: string;
|
||||
detail?: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2.5 px-3.5 py-3">
|
||||
<ProviderMark kind={kind} />
|
||||
<div className="min-w-0 flex-1 basis-40">
|
||||
<p className="m-0 truncate font-medium text-content" style={fs(13, 'body')}>
|
||||
{title}
|
||||
</p>
|
||||
{detail && (
|
||||
<p className="m-0 mt-0.5 truncate font-geist text-content-faint" style={fs(11.5)}>
|
||||
{detail}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{children && <div className="flex flex-wrap items-center gap-2">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OpenAssistantButton({ S }: { S: AiConnections }) {
|
||||
const { t } = useTranslation();
|
||||
if (!S.canOpen) return null;
|
||||
return (
|
||||
<button type="button" onClick={S.openAssistant} className={SETTINGS_BUTTON_PRIMARY} style={fs(13, 'body')}>
|
||||
<MessageCircle size={14} strokeWidth={2.2} /> {t('assistant.connect.openAssistant')}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The user's own connection: who answers, which model, and the way out (or back in, once it broke). */
|
||||
function OwnConnection({ S, own }: { S: AiConnections; own: AiConnectionView }) {
|
||||
const { t } = useTranslation();
|
||||
const { provider, models, busy, setModel, signOut, askDisconnect } = S.ownActions;
|
||||
const broken = BROKEN[own.status];
|
||||
const repairMode = S.repairMode;
|
||||
return (
|
||||
<SettingRows>
|
||||
<ConnectionRow kind={own.kind} title={t('assistant.connect.connected', { provider })} detail={own.hint}>
|
||||
{repairMode ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => S.repair(repairMode)}
|
||||
className={SETTINGS_BUTTON_PRIMARY}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{t(repairMode === 'chatgpt' ? 'assistant.errorAction.signIn' : 'assistant.errorAction.replaceKey')}
|
||||
</button>
|
||||
) : (
|
||||
<OpenAssistantButton S={S} />
|
||||
)}
|
||||
{own.kind === 'chatgpt' && own.status === 'ok' ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void signOut()}
|
||||
disabled={busy}
|
||||
className={SETTINGS_BUTTON}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
<LogOut size={14} strokeWidth={2} /> {t('assistant.connect.signOut')}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={askDisconnect}
|
||||
disabled={busy}
|
||||
className={SETTINGS_BUTTON_DANGER}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
<Unplug size={14} strokeWidth={2} /> {t('assistant.connect.disconnect')}
|
||||
</button>
|
||||
)}
|
||||
</ConnectionRow>
|
||||
{broken && (
|
||||
<p role="alert" className="m-0 px-3.5 py-2.5 text-danger" style={fs(12, 'body')}>
|
||||
{t(broken.messageKey, { provider })}
|
||||
</p>
|
||||
)}
|
||||
{own.status === 'ok' && (
|
||||
<SettingRow
|
||||
label={t('assistant.connect.model')}
|
||||
hint={t('assistant.connect.modelHint')}
|
||||
dimmed={busy}
|
||||
control={
|
||||
<div className="w-56 max-w-full">
|
||||
<CustomSelect
|
||||
ariaLabel={t('assistant.connect.model')}
|
||||
value={own.model}
|
||||
onChange={(v) => void setModel(String(v))}
|
||||
options={models}
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
searchable={models.length > 8}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</SettingRows>
|
||||
);
|
||||
}
|
||||
|
||||
/** The admin's connection this user runs on, with today's share of the limit while the instance pays. */
|
||||
function InstanceConnection({ S }: { S: AiConnections }) {
|
||||
const { t } = useTranslation();
|
||||
const instance = S.status?.instance;
|
||||
if (!instance) return null;
|
||||
return (
|
||||
<SettingRows>
|
||||
<ConnectionRow
|
||||
kind={instance.kind}
|
||||
title={t('assistant.connect.providedByAdmin')}
|
||||
detail={`${S.instanceProvider}, ${instance.model}`}
|
||||
>
|
||||
<OpenAssistantButton S={S} />
|
||||
{S.status?.canConnectOwn && !S.panel && (
|
||||
<button type="button" onClick={S.connectOwn} className={SETTINGS_BUTTON} style={fs(13, 'body')}>
|
||||
{t('assistant.errorAction.connectOwn')}
|
||||
</button>
|
||||
)}
|
||||
</ConnectionRow>
|
||||
{S.quota && (
|
||||
<p className="m-0 px-3.5 py-2.5 tabular-nums text-content-muted" style={fs(12, 'body')}>
|
||||
{t('assistant.connect.quota', { used: S.quota.used, count: S.quota.limit })}
|
||||
</p>
|
||||
)}
|
||||
</SettingRows>
|
||||
);
|
||||
}
|
||||
|
||||
/** How the assistant behaves once it runs: whether the trip map follows it. */
|
||||
function AssistantBehaviour() {
|
||||
const { t } = useTranslation();
|
||||
const follow = useAssistantMapFollow();
|
||||
return (
|
||||
<SettingRows>
|
||||
<SettingRow
|
||||
label={t('assistant.settings.followMap')}
|
||||
hint={t('assistant.settings.followMapHint')}
|
||||
control={
|
||||
<ToggleSwitch
|
||||
on={follow.on}
|
||||
onToggle={() => void follow.set(!follow.on)}
|
||||
label={t('assistant.settings.followMap')}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingRows>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings → Integrations → AI assistant: connect a provider, see which one
|
||||
* answers, pick its model, leave again. The only place a user sets the
|
||||
* assistant up; once it works, one button takes them to it.
|
||||
*/
|
||||
export default function AiConnectionSection(): React.ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
const S = useAiConnections();
|
||||
if (S.view === 'hidden') return null;
|
||||
const own = S.own;
|
||||
|
||||
return (
|
||||
<Section
|
||||
title={t('assistant.connect.title')}
|
||||
icon={Sparkles}
|
||||
hint={t('assistant.connect.description')}
|
||||
badge={
|
||||
own ? (
|
||||
<StatusPill tone={CONNECTION_STATUS[own.status].tone}>{t(CONNECTION_STATUS[own.status].labelKey)}</StatusPill>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{S.view === 'loading' && (
|
||||
<div className="grid place-items-center py-6">
|
||||
<Loader2 size={18} className="animate-spin text-content-faint" />
|
||||
</div>
|
||||
)}
|
||||
{S.view === 'own' && own && <OwnConnection S={S} own={own} />}
|
||||
{S.view === 'instance' && <InstanceConnection S={S} />}
|
||||
{(S.view === 'own' || S.view === 'instance') && <AssistantBehaviour />}
|
||||
{S.view === 'adminOnly' && <SettingsHint>{t('assistant.setup.adminOnly')}</SettingsHint>}
|
||||
|
||||
{S.panel && (
|
||||
<div className={`flex flex-col gap-3 ${S.view === 'setup' ? '' : 'border-t border-edge-faint pt-4'}`}>
|
||||
<AiConnectPanel
|
||||
key={S.panelMode ?? 'any'}
|
||||
scope="user"
|
||||
onConnected={S.onConnected}
|
||||
initialMode={S.panelMode}
|
||||
/>
|
||||
{S.view !== 'setup' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={S.closePanel}
|
||||
className={`${SETTINGS_BUTTON} self-start`}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(S.isAdmin || (S.retentionText && S.view !== 'setup')) && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-1">
|
||||
{S.view !== 'setup' && <SettingsHint>{S.retentionText}</SettingsHint>}
|
||||
{S.isAdmin && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={S.openAdmin}
|
||||
className="font-medium text-content-muted underline underline-offset-2 hover:text-content"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
{t('assistant.setup.forEveryone')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={S.ownActions.confirmingDisconnect}
|
||||
onClose={S.ownActions.cancelDisconnect}
|
||||
onConfirm={() => void S.ownActions.disconnect()}
|
||||
title={t('assistant.connect.disconnect')}
|
||||
message={t('assistant.connect.disconnectConfirm', { provider: S.ownActions.provider })}
|
||||
confirmLabel={t('assistant.connect.disconnect')}
|
||||
danger
|
||||
/>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { ClipboardPaste, ExternalLink, Loader2 } from 'lucide-react';
|
||||
import React, { useId } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { CHATGPT_USAGE_URL, providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { INPUT } from '../../shared/dialogParts';
|
||||
import { SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, SettingsHint } from '../settingsKit';
|
||||
import type { ConnectError, useChatgptConnect } from './useAiConnect';
|
||||
|
||||
type ChatgptConnect = ReturnType<typeof useChatgptConnect>;
|
||||
|
||||
/** A numbered step: the number, what to do, and the control that does it. */
|
||||
function Step({ n, text, children }: { n: number; text: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<li className="flex gap-3">
|
||||
<span
|
||||
className="grid h-6 w-6 flex-none place-items-center rounded-full bg-surface-tertiary font-semibold tabular-nums text-content-secondary"
|
||||
style={fs(11.5, 'body')}
|
||||
>
|
||||
{n}
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
<p className="m-0 leading-snug text-content" style={fs(12.5, 'body')}>
|
||||
{text}
|
||||
</p>
|
||||
{children}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A refused connect in one line, with the one action that helps: another
|
||||
* provider for an account ChatGPT will not share, its usage page when the plan
|
||||
* ran out. Everything else is fixed by trying again in place.
|
||||
*/
|
||||
export function ConnectErrorNote({
|
||||
error,
|
||||
provider,
|
||||
onOtherProvider,
|
||||
}: {
|
||||
error: ConnectError;
|
||||
provider: string;
|
||||
onOtherProvider?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div role="alert" className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<p className="m-0 min-w-0 flex-1 basis-48 leading-snug text-danger" style={fs(11.5)}>
|
||||
{t(error.messageKey, { provider })}
|
||||
</p>
|
||||
{error.code === 'not_eligible' && onOtherProvider && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOtherProvider}
|
||||
className="font-medium text-content underline underline-offset-2"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
{t('assistant.errorAction.otherProvider')}
|
||||
</button>
|
||||
)}
|
||||
{error.code === 'usage_limit' && (
|
||||
<a
|
||||
href={CHATGPT_USAGE_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="font-medium text-content underline underline-offset-2"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
{t('assistant.errorAction.viewUsage')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ChatGPT sign-in as two steps: open the sign-in (a prefetched link, so no
|
||||
* popup blocker), then paste the address the browser ends on. A pasted
|
||||
* address is sent at once; on a phone the button reads it off the clipboard.
|
||||
*/
|
||||
export default function ChatGptPasteStep({
|
||||
chatgpt,
|
||||
onOtherProvider,
|
||||
}: {
|
||||
chatgpt: ChatgptConnect;
|
||||
onOtherProvider: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const inputId = useId();
|
||||
const { flow, markOpened, pasted, change, paste, pasteFromClipboard, submit, busy, error, inputRef } = chatgpt;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<ol className="m-0 flex list-none flex-col gap-3.5 p-0">
|
||||
<Step n={1} text={t('assistant.connect.chatgptStep1')}>
|
||||
<div className="flex">
|
||||
<a
|
||||
href={flow?.authorizeUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={markOpened}
|
||||
aria-disabled={!flow}
|
||||
className={`${SETTINGS_BUTTON_PRIMARY} ${flow ? '' : 'pointer-events-none opacity-50'}`}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{flow ? <ExternalLink size={14} strokeWidth={2.2} /> : <Loader2 size={14} className="animate-spin" />}
|
||||
{t('assistant.connect.chatgptOpen')}
|
||||
</a>
|
||||
</div>
|
||||
</Step>
|
||||
<Step n={2} text={t('assistant.connect.chatgptStep2')}>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
id={inputId}
|
||||
ref={inputRef}
|
||||
type="url"
|
||||
inputMode="url"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
dir="ltr"
|
||||
value={pasted}
|
||||
onChange={(e) => change(e.target.value)}
|
||||
onPaste={(e) => {
|
||||
if (paste(e.clipboardData.getData('text'))) e.preventDefault();
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
}}
|
||||
placeholder="http://127.0.0.1:1455/auth/callback?code=…"
|
||||
aria-label={t('assistant.connect.chatgptPaste')}
|
||||
className={`${INPUT} font-mono`}
|
||||
/>
|
||||
{pasted.trim() ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void submit()}
|
||||
disabled={busy || !flow}
|
||||
className={SETTINGS_BUTTON_PRIMARY}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
{busy && <Loader2 size={14} className="animate-spin" />}
|
||||
{t('assistant.connect.save')}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={pasteFromClipboard}
|
||||
disabled={!flow}
|
||||
className={`${SETTINGS_BUTTON} whitespace-nowrap`}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
<ClipboardPaste size={14} strokeWidth={2} />
|
||||
{t('assistant.connect.chatgptPaste')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</Step>
|
||||
</ol>
|
||||
{error && (
|
||||
<ConnectErrorNote error={error} provider={providerLabel('chatgpt', '')} onOtherProvider={onOtherProvider} />
|
||||
)}
|
||||
<SettingsHint>{t('assistant.setup.chatgptNote')}</SettingsHint>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// FE-COMP-CLAUDE-CONNECTOR-001 to FE-COMP-CLAUDE-CONNECTOR-003: adding TREK to Claude as a connector.
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen, waitFor } from '../../../../tests/helpers/render';
|
||||
|
||||
const repo = vi.hoisted(() => ({ claudeConnector: vi.fn() }));
|
||||
const clipboard = vi.hoisted(() => ({ copyText: vi.fn() }));
|
||||
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
|
||||
vi.mock('../../../utils/clipboard', () => clipboard);
|
||||
|
||||
const { default: ClaudeConnectorCard } = await import('./ClaudeConnectorCard');
|
||||
|
||||
const CONNECTOR = {
|
||||
mcpUrl: 'https://trip.example.org/mcp',
|
||||
deepLink:
|
||||
'https://claude.ai/customize/connectors?modal=add-custom-connector&connectorName=TREK&connectorUrl=https%3A%2F%2Ftrip.example.org%2Fmcp',
|
||||
qrSvg: '<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
clipboard.copyText.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
describe('ClaudeConnectorCard', () => {
|
||||
it('FE-COMP-CLAUDE-CONNECTOR-001: links a public install into Claude, with a QR code that is an image, not markup', async () => {
|
||||
repo.claudeConnector.mockResolvedValue(CONNECTOR);
|
||||
const { container } = render(<ClaudeConnectorCard />);
|
||||
const link = await screen.findByRole('link', { name: /Open in Claude/ });
|
||||
expect(link).toHaveAttribute('href', CONNECTOR.deepLink);
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
const qr = screen.getByAltText('QR code to add TREK in Claude');
|
||||
expect(qr.getAttribute('src')).toMatch(/^data:image\/svg\+xml;charset=utf-8,/);
|
||||
expect(container.querySelector('rect')).toBeNull();
|
||||
expect(document.getElementById('claude-connector')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-CLAUDE-CONNECTOR-002: copies the address and shows the tick for a moment', async () => {
|
||||
const user = userEvent.setup();
|
||||
repo.claudeConnector.mockResolvedValue(CONNECTOR);
|
||||
render(<ClaudeConnectorCard />);
|
||||
await user.click(await screen.findByRole('button', { name: 'Copy address' }));
|
||||
expect(clipboard.copyText).toHaveBeenCalledWith(CONNECTOR.mcpUrl);
|
||||
await waitFor(() => expect(document.querySelector('.text-success')).not.toBeNull());
|
||||
});
|
||||
|
||||
it('FE-COMP-CLAUDE-CONNECTOR-003: a plain-http or LAN install gets the reason instead of a link, and a failed read only the description', async () => {
|
||||
repo.claudeConnector.mockResolvedValueOnce({ ...CONNECTOR, mcpUrl: 'http://192.168.1.20:3000/mcp' });
|
||||
const { unmount } = render(<ClaudeConnectorCard />);
|
||||
expect(
|
||||
await screen.findByText('Claude can only reach TREK when it is available over https on the internet.')
|
||||
).toBeInTheDocument();
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
repo.claudeConnector.mockRejectedValueOnce(new Error('404'));
|
||||
render(<ClaudeConnectorCard />);
|
||||
expect(screen.getByText('Use TREK right inside Claude: add it as a connector, sign in, done.')).toBeInTheDocument();
|
||||
await waitFor(() => expect(repo.claudeConnector).toHaveBeenCalledTimes(2));
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Check, Copy, ExternalLink, MessagesSquare } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { SETTINGS_BUTTON_PRIMARY, SETTINGS_ICON_BUTTON, SettingsCard, SettingsHint } from '../settingsKit';
|
||||
import { CLAUDE_CONNECTOR_ANCHOR } from './aiConnectModel';
|
||||
import { useClaudeConnector } from './useClaudeConnector';
|
||||
|
||||
type ClaudeConnector = ReturnType<typeof useClaudeConnector>;
|
||||
|
||||
/** The way in: the button that adds TREK on claude.ai, the address to copy, and the QR code for a phone. */
|
||||
function ConnectorLinks({
|
||||
connector,
|
||||
qrSrc,
|
||||
copied,
|
||||
copyUrl,
|
||||
}: Omit<ClaudeConnector, 'connector' | 'reachable'> & { connector: NonNullable<ClaudeConnector['connector']> }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-5">
|
||||
<div className="flex min-w-0 flex-1 basis-64 flex-col gap-3">
|
||||
<div className="flex">
|
||||
<a
|
||||
href={connector.deepLink}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={SETTINGS_BUTTON_PRIMARY}
|
||||
style={fs(13, 'body')}
|
||||
>
|
||||
<ExternalLink size={14} strokeWidth={2.2} /> {t('assistant.claude.open')}
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<code
|
||||
dir="ltr"
|
||||
className="block min-w-0 flex-1 truncate rounded-[10px] border border-edge-faint bg-surface-tertiary px-3 py-2 font-mono text-content"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
{connector.mcpUrl}
|
||||
</code>
|
||||
<Tooltip label={copied ? t('common.copied') : t('assistant.claude.copyUrl')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copyUrl()}
|
||||
aria-label={t('assistant.claude.copyUrl')}
|
||||
className={SETTINGS_ICON_BUTTON}
|
||||
>
|
||||
{copied ? (
|
||||
<Check size={15} strokeWidth={2.2} className="text-success" />
|
||||
) : (
|
||||
<Copy size={15} strokeWidth={2} />
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<figure className="m-0 flex flex-none flex-col items-center gap-1.5 max-sm:hidden">
|
||||
<img
|
||||
src={qrSrc}
|
||||
alt={t('assistant.claude.qrAlt')}
|
||||
width={112}
|
||||
height={112}
|
||||
className="rounded-[10px] shadow-sm ring-1 ring-edge-faint"
|
||||
/>
|
||||
<figcaption className="text-content-faint" style={fs(11)}>
|
||||
{t('assistant.claude.scan')}
|
||||
</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Connect with Claude": TREK as a connector inside Claude, over the MCP
|
||||
* server and its OAuth. One button adds it on claude.ai; the QR code does the
|
||||
* same from a phone, so it only shows where a phone is not already in hand.
|
||||
*/
|
||||
export default function ClaudeConnectorCard(): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { connector, reachable, ...links } = useClaudeConnector();
|
||||
|
||||
// Null keeps the card to its band until the address is known.
|
||||
let body: React.ReactNode = null;
|
||||
if (connector && reachable) body = <ConnectorLinks connector={connector} {...links} />;
|
||||
else if (connector) body = <SettingsHint>{t('assistant.claude.notPublic')}</SettingsHint>;
|
||||
|
||||
return (
|
||||
<SettingsCard
|
||||
id={CLAUDE_CONNECTOR_ANCHOR}
|
||||
icon={MessagesSquare}
|
||||
title={t('assistant.claude.title')}
|
||||
hint={t('assistant.claude.description')}
|
||||
>
|
||||
{body}
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// FE-AI-CONNECT-MODEL-001 to FE-AI-CONNECT-MODEL-007: the pure rules behind connecting an AI provider.
|
||||
import type { AiConnectionView } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { OnlineOnlyError } from '../../../repo/onlineOnly';
|
||||
import {
|
||||
connectErrorKey,
|
||||
httpHostOf,
|
||||
isPublicHttpsUrl,
|
||||
refusalCode,
|
||||
rememberOpenrouterFlow,
|
||||
repairModeOf,
|
||||
svgDataUrl,
|
||||
takeOpenrouterFlow,
|
||||
} from './aiConnectModel';
|
||||
|
||||
const refused = (code: unknown) => ({ response: { status: 422, data: { error: 'nope', code } } });
|
||||
|
||||
const VIEW: AiConnectionView = {
|
||||
scope: 'user',
|
||||
kind: 'anthropic',
|
||||
model: 'claude-sonnet',
|
||||
hint: '…a1b2',
|
||||
status: 'ok',
|
||||
host: 'api.anthropic.com',
|
||||
};
|
||||
|
||||
describe('aiConnectModel', () => {
|
||||
it('FE-AI-CONNECT-MODEL-001: reads the code of a refusal, offline included', () => {
|
||||
expect(refusalCode(refused('invalid_key'))).toBe('invalid_key');
|
||||
expect(refusalCode(new OnlineOnlyError())).toBe('offline');
|
||||
expect(refusalCode(refused(42))).toBeNull();
|
||||
expect(refusalCode(new Error('boom'))).toBeNull();
|
||||
expect(refusalCode(null)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-AI-CONNECT-MODEL-002: names the line each refusal shows, and the generic one for the rest', () => {
|
||||
expect(connectErrorKey(refused('invalid_key'))).toBe('assistant.connect.badKey');
|
||||
expect(connectErrorKey(refused('unknown_model'))).toBe('assistant.connect.unknownModel');
|
||||
expect(connectErrorKey(refused('account_mismatch'))).toBe('assistant.connect.chatgptOtherAccount');
|
||||
expect(connectErrorKey(refused('wrong_url'))).toBe('assistant.connect.chatgptWrong');
|
||||
expect(connectErrorKey(refused('expired'))).toBe('assistant.connect.chatgptExpired');
|
||||
expect(connectErrorKey(refused('not_eligible'))).toBe('assistant.error.notEligible');
|
||||
expect(connectErrorKey(refused('provider_unavailable'))).toBe('assistant.error.providerDown');
|
||||
expect(connectErrorKey(new OnlineOnlyError())).toBe('assistant.error.offline');
|
||||
expect(connectErrorKey(refused('forbidden'))).toBe('assistant.error.generic');
|
||||
expect(connectErrorKey(new Error('boom'))).toBe('assistant.error.generic');
|
||||
});
|
||||
|
||||
it('FE-AI-CONNECT-MODEL-003: offers the way back into a broken connection, none for a working one', () => {
|
||||
expect(repairModeOf(VIEW)).toBeNull();
|
||||
expect(repairModeOf({ ...VIEW, status: 'error' })).toBe('key');
|
||||
expect(repairModeOf({ ...VIEW, kind: 'chatgpt', status: 'needs_reauth' })).toBe('chatgpt');
|
||||
expect(repairModeOf({ ...VIEW, kind: 'chatgpt', status: 'signed_out' })).toBe('chatgpt');
|
||||
expect(repairModeOf({ ...VIEW, scope: 'instance', kind: 'custom', status: 'error' })).toBe('custom');
|
||||
});
|
||||
|
||||
it('FE-AI-CONNECT-MODEL-004: keeps the OpenRouter flow for exactly one return', () => {
|
||||
expect(takeOpenrouterFlow()).toBeNull();
|
||||
rememberOpenrouterFlow('flow-1');
|
||||
expect(takeOpenrouterFlow()).toBe('flow-1');
|
||||
expect(takeOpenrouterFlow()).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-AI-CONNECT-MODEL-005: only an https address on a public name counts as reachable for Claude', () => {
|
||||
expect(isPublicHttpsUrl('https://trip.example.org/mcp')).toBe(true);
|
||||
for (const url of [
|
||||
'http://trip.example.org/mcp',
|
||||
'https://localhost/mcp',
|
||||
'https://nas.local/mcp',
|
||||
'https://trek/mcp',
|
||||
'https://192.168.1.20/mcp',
|
||||
'https://10.0.0.5/mcp',
|
||||
'https://172.20.1.1/mcp',
|
||||
'https://127.0.0.1/mcp',
|
||||
'https://[::1]/mcp',
|
||||
'not a url',
|
||||
]) {
|
||||
expect(isPublicHttpsUrl(url), url).toBe(false);
|
||||
}
|
||||
expect(isPublicHttpsUrl('https://172.32.0.1/mcp')).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-AI-CONNECT-MODEL-006: reads the host of an address while it is typed', () => {
|
||||
expect(httpHostOf(' http://localhost:11434/v1 ')).toBe('localhost:11434');
|
||||
expect(httpHostOf('https://llm.example.org')).toBe('llm.example.org');
|
||||
expect(httpHostOf('localhost:11434')).toBe('');
|
||||
expect(httpHostOf('http://')).toBe('');
|
||||
});
|
||||
|
||||
it('FE-AI-CONNECT-MODEL-007: turns SVG markup into an image source, never into markup', () => {
|
||||
const src = svgDataUrl('<svg><path d="M0 0"/></svg>');
|
||||
expect(src.startsWith('data:image/svg+xml;charset=utf-8,')).toBe(true);
|
||||
expect(src).not.toContain('<');
|
||||
expect(decodeURIComponent(src.split(',')[1])).toBe('<svg><path d="M0 0"/></svg>');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { AiConnectionStatus, AiConnectionView } from '@trek/shared';
|
||||
import { OnlineOnlyError } from '../../../repo/onlineOnly';
|
||||
|
||||
/**
|
||||
* Pure helpers behind connecting an AI provider, shared by the settings card,
|
||||
* the admin's instance connection and both phone twins. No React here.
|
||||
*/
|
||||
|
||||
/** How a connection is being set up: a ChatGPT sign-in, a pasted key, or (admin only) an own server. */
|
||||
export type AiConnectMode = 'chatgpt' | 'key' | 'custom';
|
||||
|
||||
/** Where the Claude connector card sits, for the "Using Claude?" line to jump to. */
|
||||
export const CLAUDE_CONNECTOR_ANCHOR = 'claude-connector';
|
||||
|
||||
/** The `code` of a refused AI request (`{ error, code }`), or null when the failure carries none. */
|
||||
export function refusalCode(err: unknown): string | null {
|
||||
if (err instanceof OnlineOnlyError) return 'offline';
|
||||
const code = (err as { response?: { data?: { code?: unknown } } } | null)?.response?.data?.code;
|
||||
return typeof code === 'string' ? code : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a refused connect says, per code. Everything the server can answer while
|
||||
* a key is tested or a sign-in finishes; anything else reads as the generic line.
|
||||
*/
|
||||
const CONNECT_ERRORS: Record<string, { messageKey: string }> = {
|
||||
invalid_key: { messageKey: 'assistant.connect.badKey' },
|
||||
unknown_model: { messageKey: 'assistant.connect.unknownModel' },
|
||||
rate_limited: { messageKey: 'assistant.error.rateLimited' },
|
||||
provider_unavailable: { messageKey: 'assistant.error.providerDown' },
|
||||
not_eligible: { messageKey: 'assistant.error.notEligible' },
|
||||
usage_limit: { messageKey: 'assistant.error.usageLimit' },
|
||||
expired: { messageKey: 'assistant.connect.chatgptExpired' },
|
||||
wrong_url: { messageKey: 'assistant.connect.chatgptWrong' },
|
||||
account_mismatch: { messageKey: 'assistant.connect.chatgptOtherAccount' },
|
||||
offline: { messageKey: 'assistant.error.offline' },
|
||||
};
|
||||
|
||||
/** The line a failed connect shows. Takes `{provider}` where the line names one. */
|
||||
export function connectErrorKey(err: unknown): string {
|
||||
return CONNECT_ERRORS[refusalCode(err) ?? '']?.messageKey ?? 'assistant.error.generic';
|
||||
}
|
||||
|
||||
/** How each connection state reads on its pill. */
|
||||
export const CONNECTION_STATUS: Record<
|
||||
AiConnectionStatus,
|
||||
{ labelKey: string; tone: 'success' | 'warning' | 'danger' | 'neutral' }
|
||||
> = {
|
||||
ok: { labelKey: 'assistant.connect.statusOk', tone: 'success' },
|
||||
needs_reauth: { labelKey: 'assistant.connect.statusNeedsReauth', tone: 'warning' },
|
||||
signed_out: { labelKey: 'assistant.connect.statusSignedOut', tone: 'neutral' },
|
||||
error: { labelKey: 'assistant.connect.statusError', tone: 'danger' },
|
||||
};
|
||||
|
||||
/** The way back into a connection that no longer works: a ChatGPT sign-in again, or a new key. */
|
||||
export function repairModeOf(view: AiConnectionView): AiConnectMode | null {
|
||||
if (view.status === 'ok') return null;
|
||||
if (view.kind === 'chatgpt') return 'chatgpt';
|
||||
return view.kind === 'custom' ? 'custom' : 'key';
|
||||
}
|
||||
|
||||
// The OpenRouter sign-in leaves the page and comes back with a code only; the
|
||||
// flow it belongs to waits here for that one return. Tab-scoped on purpose.
|
||||
const OPENROUTER_FLOW_KEY = 'trek.ai.openrouterFlow';
|
||||
|
||||
export function rememberOpenrouterFlow(flowId: string): void {
|
||||
try {
|
||||
sessionStorage.setItem(OPENROUTER_FLOW_KEY, flowId);
|
||||
} catch {
|
||||
// Storage refused (private mode): the return then reads as an expired sign-in.
|
||||
}
|
||||
}
|
||||
|
||||
/** The flow the OpenRouter sign-in started, read once. */
|
||||
export function takeOpenrouterFlow(): string | null {
|
||||
try {
|
||||
const flowId = sessionStorage.getItem(OPENROUTER_FLOW_KEY);
|
||||
sessionStorage.removeItem(OPENROUTER_FLOW_KEY);
|
||||
return flowId;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const PRIVATE_V4 = [/^10\./, /^127\./, /^169\.254\./, /^192\.168\./, /^172\.(1[6-9]|2\d|3[01])\./, /^0\./];
|
||||
|
||||
/**
|
||||
* Whether Claude can reach this address from the internet: https on a public
|
||||
* name. A LAN address, a loopback, a single-label host or `.local` cannot be
|
||||
* reached from claude.ai, so the connector would fail after the user did
|
||||
* everything right.
|
||||
*/
|
||||
export function isPublicHttpsUrl(raw: string): boolean {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (url.protocol !== 'https:') return false;
|
||||
const host = url.hostname.toLowerCase();
|
||||
if (host.startsWith('[')) return false;
|
||||
if (!host.includes('.') || host === 'localhost' || host.endsWith('.local') || host.endsWith('.localhost')) {
|
||||
return false;
|
||||
}
|
||||
return !PRIVATE_V4.some((range) => range.test(host));
|
||||
}
|
||||
|
||||
/** The host of an http(s) address as typed, or '' while it is not one yet. */
|
||||
export function httpHostOf(raw: string): string {
|
||||
const value = raw.trim();
|
||||
if (!/^https?:\/\//i.test(value)) return '';
|
||||
try {
|
||||
return new URL(value).host;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/** An SVG as an `<img>` source, so its markup never lands in the page's DOM. */
|
||||
export function svgDataUrl(svg: string): string {
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-012: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { createElement, type ReactNode } from 'react';
|
||||
import { MemoryRouter, useLocation } from 'react-router';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TranslationProvider } from '../../../i18n/TranslationContext';
|
||||
|
||||
const repo = vi.hoisted(() => ({
|
||||
connectKey: vi.fn(),
|
||||
saveAdminConnection: vi.fn(),
|
||||
chatgptStart: vi.fn(),
|
||||
chatgptFinish: vi.fn(),
|
||||
openrouterStart: vi.fn(),
|
||||
openrouterFinish: vi.fn(),
|
||||
}));
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
|
||||
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
|
||||
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||
|
||||
const { useChatgptConnect, useCustomConnect, useKeyConnect, useOpenrouterReturn, useOpenrouterStart } =
|
||||
await import('./useAiConnect');
|
||||
const { rememberOpenrouterFlow } = await import('./aiConnectModel');
|
||||
|
||||
function wrapperAt(url = '/settings') {
|
||||
return ({ children }: { children: ReactNode }) =>
|
||||
createElement(MemoryRouter, { initialEntries: [url] }, createElement(TranslationProvider, null, children));
|
||||
}
|
||||
|
||||
const refused = (code: string) =>
|
||||
Object.assign(new Error(code), { response: { status: 422, data: { error: code, code } } });
|
||||
|
||||
const FLOW = {
|
||||
flowId: '7d9f2c1e-3b4a-4c5d-8e6f-0a1b2c3d4e5f',
|
||||
authorizeUrl: 'https://auth.openai.com/api/accounts/authorize?x=1',
|
||||
expiresAt: new Date(Date.now() + 600_000).toISOString(),
|
||||
};
|
||||
const CALLBACK = 'http://127.0.0.1:1455/auth/callback?code=c1&state=s1&client_id=oaiapp_abc';
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo.connectKey.mockResolvedValue({});
|
||||
repo.saveAdminConnection.mockResolvedValue({ connection: null, prefill: null });
|
||||
repo.chatgptStart.mockResolvedValue(FLOW);
|
||||
repo.chatgptFinish.mockResolvedValue({});
|
||||
repo.openrouterFinish.mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe('useKeyConnect', () => {
|
||||
it('FE-HOOK-AI-CONNECT-001: a pasted key that names its provider is tested and saved at once', async () => {
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useKeyConnect({ scope: 'user', prefill: null, onConnected }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
|
||||
let taken = false;
|
||||
act(() => {
|
||||
taken = result.current.paste(' sk-ant-api03-abcdef ');
|
||||
});
|
||||
expect(taken).toBe(true);
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.connectKey).toHaveBeenCalledWith({ kind: 'anthropic', apiKey: 'sk-ant-api03-abcdef' });
|
||||
expect(toast.success).toHaveBeenCalledWith('Connected. Let’s go.');
|
||||
expect(result.current.key).toBe('');
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-002: a key with an unknown prefix asks for its provider, and naming it tests the key', async () => {
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useKeyConnect({ scope: 'user', prefill: null, onConnected }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
expect(result.current.paste('hello world')).toBe(false);
|
||||
act(() => result.current.change('abc'));
|
||||
expect(result.current.needsProvider).toBe(false);
|
||||
act(() => result.current.change('XY.new-format-key'));
|
||||
expect(result.current.kind).toBeNull();
|
||||
expect(result.current.needsProvider).toBe(true);
|
||||
expect(result.current.error).toBeNull();
|
||||
await act(() => result.current.submit());
|
||||
expect(repo.connectKey).not.toHaveBeenCalled();
|
||||
act(() => result.current.pick('gemini'));
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.connectKey).toHaveBeenCalledWith({ kind: 'gemini', apiKey: 'XY.new-format-key' });
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-002b: a provider chosen before pasting takes an unknown key at once; Google’s AQ. keys are known', async () => {
|
||||
const { result } = renderHook(() => useKeyConnect({ scope: 'user', prefill: null, onConnected: vi.fn() }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
act(() => result.current.change('AQ.Ab8RN6-example'));
|
||||
expect(result.current.kind).toBe('gemini');
|
||||
act(() => result.current.change(''));
|
||||
act(() => result.current.pick('openrouter'));
|
||||
expect(repo.connectKey).not.toHaveBeenCalled();
|
||||
let taken = false;
|
||||
act(() => {
|
||||
taken = result.current.paste('unknown-format-key');
|
||||
});
|
||||
expect(taken).toBe(true);
|
||||
await waitFor(() =>
|
||||
expect(repo.connectKey).toHaveBeenCalledWith({ kind: 'openrouter', apiKey: 'unknown-format-key' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-003: a refused key keeps the form and says why', async () => {
|
||||
repo.connectKey.mockRejectedValueOnce(refused('invalid_key'));
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useKeyConnect({ scope: 'user', prefill: null, onConnected }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
act(() => result.current.change('AIzaSyD-example-key'));
|
||||
expect(result.current.kind).toBe('gemini');
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error).toEqual({ messageKey: 'assistant.connect.badKey', code: 'invalid_key' });
|
||||
expect(result.current.key).toBe('AIzaSyD-example-key');
|
||||
expect(onConnected).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-004: the admin saves for everyone and keeps the model AI parsing used for that provider', async () => {
|
||||
const prefill = { kind: 'openai' as const, baseUrl: null, model: 'gpt-5.5' };
|
||||
const { result } = renderHook(() => useKeyConnect({ scope: 'instance', prefill, onConnected: vi.fn() }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
act(() => result.current.change('sk-proj-123456789'));
|
||||
await act(() => result.current.submit());
|
||||
expect(repo.saveAdminConnection).toHaveBeenCalledWith({
|
||||
kind: 'openai',
|
||||
apiKey: 'sk-proj-123456789',
|
||||
model: 'gpt-5.5',
|
||||
});
|
||||
expect(repo.connectKey).not.toHaveBeenCalled();
|
||||
|
||||
act(() => result.current.change('sk-ant-123456789'));
|
||||
await act(() => result.current.submit());
|
||||
expect(repo.saveAdminConnection).toHaveBeenLastCalledWith({ kind: 'anthropic', apiKey: 'sk-ant-123456789' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCustomConnect', () => {
|
||||
it('FE-HOOK-AI-CONNECT-005: an own server needs an http address and a model, the key stays optional', async () => {
|
||||
const onConnected = vi.fn();
|
||||
const prefill = { kind: 'custom' as const, baseUrl: 'http://ollama:11434/v1', model: 'qwen3:8b' };
|
||||
const { result } = renderHook(() => useCustomConnect({ prefill, onConnected }), { wrapper: wrapperAt() });
|
||||
expect(result.current.baseUrl).toBe('http://ollama:11434/v1');
|
||||
expect(result.current.host).toBe('ollama:11434');
|
||||
expect(result.current.ready).toBe(true);
|
||||
|
||||
act(() => result.current.setBaseUrl('ollama:11434'));
|
||||
expect(result.current.ready).toBe(false);
|
||||
act(() => result.current.setBaseUrl('http://ollama:11434/v1'));
|
||||
await act(() => result.current.submit());
|
||||
expect(repo.saveAdminConnection).toHaveBeenCalledWith({
|
||||
kind: 'custom',
|
||||
baseUrl: 'http://ollama:11434/v1',
|
||||
model: 'qwen3:8b',
|
||||
});
|
||||
expect(onConnected).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useChatgptConnect', () => {
|
||||
it('FE-HOOK-AI-CONNECT-006: fetches the sign-in address only while its step shows', async () => {
|
||||
const { result, rerender } = renderHook(({ active }) => useChatgptConnect({ active, onConnected: vi.fn() }), {
|
||||
wrapper: wrapperAt(),
|
||||
initialProps: { active: false },
|
||||
});
|
||||
expect(repo.chatgptStart).not.toHaveBeenCalled();
|
||||
rerender({ active: true });
|
||||
await waitFor(() => expect(result.current.flow).toEqual(FLOW));
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-007: a pasted callback address finishes the sign-in without a click', async () => {
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
|
||||
expect(result.current.paste('https://chatgpt.com/')).toBe(false);
|
||||
act(() => {
|
||||
result.current.paste(CALLBACK);
|
||||
});
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: CALLBACK });
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-008: another address is refused here, before the server is asked', async () => {
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected: vi.fn() }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
act(() => result.current.change('http://localhost:1455/auth/callback?code=x'));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error).toEqual({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
|
||||
expect(repo.chatgptFinish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-009: a sign-in that ran out starts a fresh one', async () => {
|
||||
repo.chatgptStart.mockResolvedValueOnce({ ...FLOW, expiresAt: new Date(Date.now() - 1000).toISOString() });
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected: vi.fn() }), {
|
||||
wrapper: wrapperAt(),
|
||||
});
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error?.code).toBe('expired');
|
||||
expect(result.current.pasted).toBe('');
|
||||
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
|
||||
expect(repo.chatgptFinish).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so and keeps the flow', async () => {
|
||||
repo.chatgptFinish.mockRejectedValueOnce(refused('not_eligible'));
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
|
||||
await waitFor(() => expect(result.current.flow).not.toBeNull());
|
||||
act(() => result.current.change(CALLBACK));
|
||||
await act(() => result.current.submit());
|
||||
expect(result.current.error).toEqual({ messageKey: 'assistant.error.notEligible', code: 'not_eligible' });
|
||||
expect(onConnected).not.toHaveBeenCalled();
|
||||
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('OpenRouter', () => {
|
||||
it('FE-HOOK-AI-CONNECT-011: a refused start tells the user and frees the button', async () => {
|
||||
repo.openrouterStart.mockRejectedValueOnce(refused('forbidden'));
|
||||
const { result } = renderHook(() => useOpenrouterStart('user'), { wrapper: wrapperAt() });
|
||||
await act(() => result.current.start());
|
||||
expect(repo.openrouterStart).toHaveBeenCalledWith('user');
|
||||
expect(toast.error).toHaveBeenCalledWith('Something went wrong.');
|
||||
expect(result.current.busy).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECT-012: the return finishes the remembered flow once and clears the address', async () => {
|
||||
rememberOpenrouterFlow(FLOW.flowId);
|
||||
const onConnected = vi.fn();
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
useOpenrouterReturn(onConnected);
|
||||
return useLocation();
|
||||
},
|
||||
{ wrapper: wrapperAt('/settings?tab=integrations&ai=openrouter&code=or-code') }
|
||||
);
|
||||
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
|
||||
expect(repo.openrouterFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, code: 'or-code' });
|
||||
expect(result.current.search).toBe('?tab=integrations');
|
||||
|
||||
vi.clearAllMocks();
|
||||
renderHook(() => useOpenrouterReturn(onConnected), { wrapper: wrapperAt('/settings?ai=openrouter&code=again') });
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
|
||||
expect(repo.openrouterFinish).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
import type { AiApiKeyKind, AiAuthStartResponse, AiConnectionScope, AiParsingPrefill } from '@trek/shared';
|
||||
import { useEffect, useEffectEvent, useRef, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
|
||||
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import { connectErrorKey, httpHostOf, refusalCode, rememberOpenrouterFlow, takeOpenrouterFlow } from './aiConnectModel';
|
||||
|
||||
/**
|
||||
* The ways to connect a provider, one hook each, behind `AiConnectPanel`: a
|
||||
* pasted key (tested as it is pasted), an own server (admin only), the
|
||||
* ChatGPT sign-in that ends on a pasted address, and the OpenRouter sign-in
|
||||
* that leaves the page and comes back with a code.
|
||||
*/
|
||||
|
||||
/** The schema's shortest key; anything shorter is still being typed. */
|
||||
const MIN_KEY_LENGTH = 8;
|
||||
|
||||
/** A refusal shown under a form: the line, and the code it came from for the one action it offers. */
|
||||
export interface ConnectError {
|
||||
messageKey: string;
|
||||
code: string | null;
|
||||
}
|
||||
|
||||
const OPENROUTER = providerLabel('openrouter', '');
|
||||
|
||||
export function useKeyConnect({
|
||||
scope,
|
||||
prefill,
|
||||
onConnected,
|
||||
}: {
|
||||
scope: AiConnectionScope;
|
||||
/** What AI parsing runs on: its model is kept when the key is for the same provider. */
|
||||
prefill: AiParsingPrefill | null;
|
||||
onConnected: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [key, setKey] = useState('');
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [error, setError] = useState<ConnectError | null>(null);
|
||||
// The provider the user named, by opening its key page or answering "which provider?":
|
||||
// it stands in when a key's prefix is one we don't know, so a new key format never locks anyone out.
|
||||
const [picked, setPicked] = useState<AiApiKeyKind | null>(null);
|
||||
const kindOf = (value: string) => detectKeyKind(value) ?? picked;
|
||||
const kind = kindOf(key);
|
||||
|
||||
const submit = async (raw: string, target = kindOf(raw.trim())) => {
|
||||
const apiKey = raw.trim();
|
||||
if (testing || !target || apiKey.length < MIN_KEY_LENGTH) return;
|
||||
setTesting(true);
|
||||
setError(null);
|
||||
const model = prefill?.kind === target ? { model: prefill.model } : {};
|
||||
try {
|
||||
// Saving is the test: the server lists the provider's models with the key first.
|
||||
if (scope === 'user') await aiConnectionsRepo.connectKey({ kind: target, apiKey, ...model });
|
||||
else await aiConnectionsRepo.saveAdminConnection({ kind: target, apiKey, ...model });
|
||||
setKey('');
|
||||
setPicked(null);
|
||||
toast.success(t('assistant.connect.ok'));
|
||||
onConnected();
|
||||
} catch (err) {
|
||||
setError({ messageKey: connectErrorKey(err), code: refusalCode(err) });
|
||||
} finally {
|
||||
setTesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const change = (value: string) => {
|
||||
setKey(value);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
/** A pasted key whose provider is known is tested at once; true when it was taken. */
|
||||
const paste = (text: string): boolean => {
|
||||
const value = text.trim();
|
||||
if (value.length < MIN_KEY_LENGTH || !kindOf(value)) return false;
|
||||
setKey(value);
|
||||
void submit(value);
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Names the provider; with a complete key already in the field, that tests it right away. */
|
||||
const pick = (next: AiApiKeyKind) => {
|
||||
setPicked(next);
|
||||
setError(null);
|
||||
if (!detectKeyKind(key)) void submit(key, next);
|
||||
};
|
||||
|
||||
return {
|
||||
key,
|
||||
kind,
|
||||
/** The provider the pasted key itself names; what "Detected" may say. */
|
||||
detected: detectKeyKind(key),
|
||||
/** The provider tile the user chose, shown as selected. */
|
||||
picked,
|
||||
change,
|
||||
paste,
|
||||
pick,
|
||||
submit: () => submit(key),
|
||||
testing,
|
||||
error,
|
||||
/** A full key whose prefix names no provider: the form asks which one it is. */
|
||||
needsProvider: !kind && key.trim().length >= MIN_KEY_LENGTH,
|
||||
};
|
||||
}
|
||||
|
||||
/** An OpenAI-compatible server only the admin may name (#1772): its address, an optional key and the model. */
|
||||
export function useCustomConnect({
|
||||
prefill,
|
||||
onConnected,
|
||||
}: {
|
||||
prefill: AiParsingPrefill | null;
|
||||
onConnected: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const fromParsing = prefill?.kind === 'custom' ? prefill : null;
|
||||
const [baseUrl, setBaseUrl] = useState(fromParsing?.baseUrl ?? '');
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [model, setModel] = useState(fromParsing?.model ?? '');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<ConnectError | null>(null);
|
||||
|
||||
const host = httpHostOf(baseUrl);
|
||||
const ready = host !== '' && model.trim() !== '';
|
||||
|
||||
const submit = async () => {
|
||||
if (!ready || saving) return;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
const key = apiKey.trim();
|
||||
await aiConnectionsRepo.saveAdminConnection({
|
||||
kind: 'custom',
|
||||
baseUrl: baseUrl.trim(),
|
||||
model: model.trim(),
|
||||
...(key ? { apiKey: key } : {}),
|
||||
});
|
||||
toast.success(t('assistant.connect.ok'));
|
||||
onConnected();
|
||||
} catch (err) {
|
||||
setError({ messageKey: connectErrorKey(err), code: refusalCode(err) });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { baseUrl, setBaseUrl, apiKey, setApiKey, model, setModel, host, ready, saving, error, submit };
|
||||
}
|
||||
|
||||
/**
|
||||
* Signing in with ChatGPT (K3). The sign-in address is fetched as soon as the
|
||||
* step shows, so opening it is a plain link and no popup blocker interferes.
|
||||
* ChatGPT then sends the browser to a loopback address that shows an error
|
||||
* page; pasting that address back finishes the sign-in at once, and coming
|
||||
* back to this tab puts the cursor in the field.
|
||||
*/
|
||||
export function useChatgptConnect({ active, onConnected }: { active: boolean; onConnected: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [flow, setFlow] = useState<AiAuthStartResponse | null>(null);
|
||||
const [opened, setOpened] = useState(false);
|
||||
const [pasted, setPasted] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<ConnectError | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
let cancelled = false;
|
||||
void aiConnectionsRepo.chatgptStart().then(
|
||||
(next) => {
|
||||
if (!cancelled) setFlow(next);
|
||||
},
|
||||
(err: unknown) => {
|
||||
if (!cancelled) setError({ messageKey: connectErrorKey(err), code: refusalCode(err) });
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [active, attempt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!opened) return;
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === 'visible') inputRef.current?.focus();
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
return () => document.removeEventListener('visibilitychange', onVisible);
|
||||
}, [opened]);
|
||||
|
||||
/** A fresh sign-in: the old one ran out or was used up. */
|
||||
const restart = () => {
|
||||
setFlow(null);
|
||||
setOpened(false);
|
||||
setPasted('');
|
||||
setAttempt((n) => n + 1);
|
||||
};
|
||||
|
||||
const finish = async (raw: string) => {
|
||||
const url = raw.trim();
|
||||
if (!flow || busy) return;
|
||||
if (!isChatgptCallback(url)) {
|
||||
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
|
||||
return;
|
||||
}
|
||||
if (Date.parse(flow.expiresAt) <= Date.now()) {
|
||||
setError({ messageKey: 'assistant.connect.chatgptExpired', code: 'expired' });
|
||||
restart();
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await aiConnectionsRepo.chatgptFinish({ flowId: flow.flowId, pastedUrl: url });
|
||||
toast.success(t('assistant.connect.ok'));
|
||||
onConnected();
|
||||
} catch (err) {
|
||||
const code = refusalCode(err);
|
||||
setError({ messageKey: connectErrorKey(err), code });
|
||||
if (code === 'expired') restart();
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const change = (value: string) => {
|
||||
setPasted(value);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
/** The callback address pasted into the field is sent without a click; true when it was taken. */
|
||||
const paste = (text: string): boolean => {
|
||||
if (!isChatgptCallback(text)) return false;
|
||||
setPasted(text.trim());
|
||||
void finish(text);
|
||||
return true;
|
||||
};
|
||||
|
||||
/** Reads the address off the clipboard where the browser allows it, else hands the field the cursor. */
|
||||
const pasteFromClipboard = () => {
|
||||
if (!navigator.clipboard?.readText || !window.isSecureContext) {
|
||||
inputRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
navigator.clipboard.readText().then(
|
||||
(text) => {
|
||||
if (!paste(text)) change(text);
|
||||
},
|
||||
() => inputRef.current?.focus()
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
flow,
|
||||
opened,
|
||||
markOpened: () => setOpened(true),
|
||||
pasted,
|
||||
change,
|
||||
paste,
|
||||
pasteFromClipboard,
|
||||
submit: () => finish(pasted),
|
||||
busy,
|
||||
error,
|
||||
restart,
|
||||
inputRef,
|
||||
};
|
||||
}
|
||||
|
||||
/** Starts the OpenRouter sign-in: the page leaves for OpenRouter and returns to the settings or the admin addons. */
|
||||
export function useOpenrouterStart(scope: AiConnectionScope) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const start = async () => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const flow = await aiConnectionsRepo.openrouterStart(scope);
|
||||
rememberOpenrouterFlow(flow.flowId);
|
||||
window.location.assign(flow.authorizeUrl);
|
||||
} catch (err) {
|
||||
toast.error(t(connectErrorKey(err), { provider: OPENROUTER }));
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return { start, busy };
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes an OpenRouter sign-in the page came back from (`?ai=openrouter&code=…`)
|
||||
* once, and takes both parameters out of the address so a reload does not try again.
|
||||
*/
|
||||
export function useOpenrouterReturn(onConnected: () => void) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const handled = useRef(false);
|
||||
|
||||
const finish = useEffectEvent(async (code: string | null) => {
|
||||
const flowId = takeOpenrouterFlow();
|
||||
if (!code || !flowId) {
|
||||
toast.error(t('assistant.connect.chatgptExpired'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await aiConnectionsRepo.openrouterFinish({ flowId, code });
|
||||
toast.success(t('assistant.connect.ok'));
|
||||
onConnected();
|
||||
} catch (err) {
|
||||
toast.error(t(connectErrorKey(err), { provider: OPENROUTER }));
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (handled.current || params.get('ai') !== 'openrouter') return;
|
||||
handled.current = true;
|
||||
const code = params.get('code');
|
||||
setParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
next.delete('ai');
|
||||
next.delete('code');
|
||||
return next;
|
||||
},
|
||||
{ replace: true }
|
||||
);
|
||||
void finish(code);
|
||||
}, [params, setParams]);
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
// FE-HOOK-AI-CONNECTIONS-001 to FE-HOOK-AI-CONNECTIONS-010: the AI connection card's states and actions.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { AiConnectionView, AiStatusResponse } from '@trek/shared';
|
||||
import { createElement, type ReactNode } from 'react';
|
||||
import { MemoryRouter, useLocation } from 'react-router';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TranslationProvider } from '../../../i18n/TranslationContext';
|
||||
import { useAssistantStore } from '../../../store/assistantStore';
|
||||
|
||||
const repo = vi.hoisted(() => ({
|
||||
status: vi.fn(),
|
||||
models: vi.fn(),
|
||||
setModel: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
chatgptSignOut: vi.fn(),
|
||||
}));
|
||||
const trips = vi.hoisted(() => ({ active: vi.fn() }));
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn() }));
|
||||
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
|
||||
vi.mock('../../../repo/tripRepo', () => ({ tripRepo: trips }));
|
||||
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||
|
||||
const { modelOptions, useAiConnections } = await import('./useAiConnections');
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
createElement(
|
||||
MemoryRouter,
|
||||
{ initialEntries: ['/settings?tab=integrations'] },
|
||||
createElement(TranslationProvider, null, children)
|
||||
);
|
||||
|
||||
const OWN: AiConnectionView = {
|
||||
scope: 'user',
|
||||
kind: 'anthropic',
|
||||
model: 'claude-sonnet',
|
||||
hint: '…a1b2',
|
||||
status: 'ok',
|
||||
host: 'api.anthropic.com',
|
||||
};
|
||||
|
||||
function status(over: Partial<AiStatusResponse> = {}): AiStatusResponse {
|
||||
return {
|
||||
available: false,
|
||||
policy: 'instance_or_user',
|
||||
canConnectOwn: true,
|
||||
effective: null,
|
||||
own: null,
|
||||
instance: null,
|
||||
quota: null,
|
||||
privacyAcked: false,
|
||||
retention: { mode: 'days', days: 90 },
|
||||
openrouterOAuth: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function renderConnections(phone = false) {
|
||||
return renderHook(() => ({ hook: useAiConnections({ phone }), location: useLocation() }), { wrapper });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
useAssistantStore.setState({ status: null, window: { open: false, minimized: false } });
|
||||
repo.status.mockResolvedValue(status());
|
||||
repo.models.mockResolvedValue([
|
||||
{ id: 'claude-sonnet', label: 'Claude Sonnet', supportsTools: true },
|
||||
{ id: 'claude-haiku', label: 'Claude Haiku', supportsTools: true },
|
||||
]);
|
||||
repo.setModel.mockResolvedValue({ ...OWN, model: 'claude-haiku' });
|
||||
repo.disconnect.mockResolvedValue(undefined);
|
||||
repo.chatgptSignOut.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe('useAiConnections', () => {
|
||||
it('FE-HOOK-AI-CONNECTIONS-001: nothing connected opens the setup right away', async () => {
|
||||
const { result } = renderConnections();
|
||||
expect(result.current.hook.view).toBe('loading');
|
||||
await waitFor(() => expect(result.current.hook.view).toBe('setup'));
|
||||
expect(result.current.hook.panel).toBe(true);
|
||||
expect(result.current.hook.retentionText).toBe('Chats are deleted after 90 days.');
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-002: tells the admin connection, the admin-only policy and a refused status apart', async () => {
|
||||
const instance = { kind: 'openai' as const, model: 'gpt-5.5', host: 'api.openai.com' };
|
||||
repo.status.mockResolvedValueOnce(status({ instance, quota: { used: 3, limit: 50 }, available: true }));
|
||||
const a = renderConnections();
|
||||
await waitFor(() => expect(a.result.current.hook.view).toBe('instance'));
|
||||
expect(a.result.current.hook.instanceProvider).toBe('OpenAI');
|
||||
expect(a.result.current.hook.panel).toBe(false);
|
||||
act(() => a.result.current.hook.connectOwn());
|
||||
expect(a.result.current.hook.panel).toBe(true);
|
||||
a.unmount();
|
||||
|
||||
repo.status.mockResolvedValueOnce(status({ policy: 'instance', canConnectOwn: false }));
|
||||
const b = renderConnections();
|
||||
await waitFor(() => expect(b.result.current.hook.view).toBe('adminOnly'));
|
||||
b.unmount();
|
||||
|
||||
repo.status.mockRejectedValueOnce(new Error('404'));
|
||||
useAssistantStore.setState({ status: null });
|
||||
const c = renderConnections();
|
||||
await waitFor(() => expect(c.result.current.hook.view).toBe('hidden'));
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-003: an own connection lists its models with the current one first known', async () => {
|
||||
repo.status.mockResolvedValue(status({ own: OWN, available: true }));
|
||||
const { result } = renderConnections();
|
||||
await waitFor(() => expect(result.current.hook.ownActions.models).toHaveLength(2));
|
||||
expect(result.current.hook.view).toBe('own');
|
||||
expect(result.current.hook.ownActions.provider).toBe('Anthropic');
|
||||
expect(result.current.hook.repairMode).toBeNull();
|
||||
expect(repo.models).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-004: switching the model saves it and reads the status again', async () => {
|
||||
repo.status.mockResolvedValue(status({ own: OWN, available: true }));
|
||||
const { result } = renderConnections();
|
||||
await waitFor(() => expect(result.current.hook.view).toBe('own'));
|
||||
await act(() => result.current.hook.ownActions.setModel('claude-haiku'));
|
||||
expect(repo.setModel).toHaveBeenCalledWith('claude-haiku');
|
||||
expect(repo.status).toHaveBeenCalledTimes(2);
|
||||
expect(toast.success).toHaveBeenCalledWith('Saved');
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-005: disconnecting asks first, then removes the connection', async () => {
|
||||
repo.status.mockResolvedValue(status({ own: OWN, available: true }));
|
||||
const { result } = renderConnections();
|
||||
await waitFor(() => expect(result.current.hook.view).toBe('own'));
|
||||
act(() => result.current.hook.ownActions.askDisconnect());
|
||||
expect(result.current.hook.ownActions.confirmingDisconnect).toBe(true);
|
||||
repo.status.mockResolvedValue(status());
|
||||
await act(() => result.current.hook.ownActions.disconnect());
|
||||
expect(repo.disconnect).toHaveBeenCalledTimes(1);
|
||||
expect(result.current.hook.ownActions.confirmingDisconnect).toBe(false);
|
||||
expect(result.current.hook.view).toBe('setup');
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-006: a refused action keeps the connection and names the provider', async () => {
|
||||
repo.status.mockResolvedValue(status({ own: OWN, available: true }));
|
||||
repo.setModel.mockRejectedValueOnce({
|
||||
response: { status: 502, data: { error: 'down', code: 'provider_unavailable' } },
|
||||
});
|
||||
const { result } = renderConnections();
|
||||
await waitFor(() => expect(result.current.hook.view).toBe('own'));
|
||||
await act(() => result.current.hook.ownActions.setModel('claude-haiku'));
|
||||
expect(toast.error).toHaveBeenCalledWith('Anthropic isn’t responding right now.');
|
||||
expect(result.current.hook.ownActions.busy).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-007: a broken sign-in offers the way back in on its own form', async () => {
|
||||
repo.status.mockResolvedValue(
|
||||
status({ own: { ...OWN, kind: 'chatgpt', status: 'needs_reauth', host: 'api.openai.com' } })
|
||||
);
|
||||
const { result } = renderConnections();
|
||||
await waitFor(() => expect(result.current.hook.repairMode).toBe('chatgpt'));
|
||||
expect(repo.models).not.toHaveBeenCalled();
|
||||
act(() => result.current.hook.repair('chatgpt'));
|
||||
expect(result.current.hook.panel).toBe(true);
|
||||
expect(result.current.hook.panelMode).toBe('chatgpt');
|
||||
act(() => result.current.hook.closePanel());
|
||||
expect(result.current.hook.panel).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-008: "Open assistant" opens the chat on the trip under way, else on the dashboard', async () => {
|
||||
repo.status.mockResolvedValue(status({ own: OWN, available: true }));
|
||||
trips.active.mockResolvedValueOnce({ trip: { id: 7, title: 'Kyoto', start_date: null, end_date: null } });
|
||||
const { result } = renderConnections();
|
||||
await waitFor(() => expect(result.current.hook.canOpen).toBe(true));
|
||||
act(() => result.current.hook.openAssistant());
|
||||
await waitFor(() => expect(result.current.location.pathname).toBe('/trips/7'));
|
||||
expect(result.current.location.search).toBe('?assistant=1');
|
||||
// The planner opens it from the link, so a trip that never loads leaves nothing open.
|
||||
expect(useAssistantStore.getState().window.open).toBe(false);
|
||||
|
||||
trips.active.mockResolvedValueOnce({ trip: null });
|
||||
act(() => result.current.hook.openAssistant());
|
||||
await waitFor(() => expect(result.current.location.pathname).toBe('/dashboard'));
|
||||
expect(useAssistantStore.getState().window.open).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-HOOK-AI-CONNECTIONS-010: on the phone without a trip it says to make one, and opens nothing', async () => {
|
||||
repo.status.mockResolvedValue(status({ own: OWN, available: true }));
|
||||
trips.active.mockResolvedValueOnce({ trip: null });
|
||||
const { result } = renderConnections(true);
|
||||
await waitFor(() => expect(result.current.hook.canOpen).toBe(true));
|
||||
act(() => result.current.hook.openAssistant());
|
||||
await waitFor(() =>
|
||||
expect(toast.info).toHaveBeenCalledWith('Create a trip first, then the assistant can help you plan it.')
|
||||
);
|
||||
expect(result.current.location.pathname).toBe('/settings');
|
||||
expect(useAssistantStore.getState().window.open).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('modelOptions', () => {
|
||||
it('FE-HOOK-AI-CONNECTIONS-009: keeps the current model selectable when the provider no longer lists it, and marks free ones', () => {
|
||||
const models = [{ id: 'a', label: 'A', supportsTools: true, free: true }];
|
||||
const labels = { free: 'Free', recommended: 'Recommended' };
|
||||
expect(modelOptions(models, 'a', labels)).toEqual([{ value: 'a', label: 'A', badge: 'Free' }]);
|
||||
expect(modelOptions([{ id: 'b', label: 'B', supportsTools: true, recommended: true }], 'b', labels)).toEqual([
|
||||
{ value: 'b', label: 'B', badge: 'Recommended' },
|
||||
]);
|
||||
expect(modelOptions(models, 'old', labels)).toEqual([
|
||||
{ value: 'old', label: 'old', badge: undefined },
|
||||
{ value: 'a', label: 'A', badge: 'Free' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import type { AiConnectionView, AiModelInfo, AiRetention, AiStatusResponse } from '@trek/shared';
|
||||
import { useEffect, useEffectEvent, useState } from 'react';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
|
||||
import { tripRepo } from '../../../repo/tripRepo';
|
||||
import { useAssistantStore } from '../../../store/assistantStore';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
import { providerLabel } from '../../Assistant/providerCatalog';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import { type AiConnectMode, connectErrorKey, repairModeOf } from './aiConnectModel';
|
||||
import { useOpenrouterReturn } from './useAiConnect';
|
||||
|
||||
/**
|
||||
* What the AI connection card shows:
|
||||
* - `own`: the user's own connection, with its model and its way out
|
||||
* - `instance`: the admin's connection, which this user runs on
|
||||
* - `adminOnly`: only the admin connects one, and has not yet
|
||||
* - `setup`: nothing yet, connect one here
|
||||
* - `hidden`: the assistant is not offered here (addon off, managed, refused)
|
||||
*/
|
||||
type AiConnectionsView = 'loading' | 'own' | 'instance' | 'adminOnly' | 'setup' | 'hidden';
|
||||
|
||||
function viewOf(status: AiStatusResponse | null, loaded: boolean): AiConnectionsView {
|
||||
if (!status) return loaded ? 'hidden' : 'loading';
|
||||
if (status.own) return 'own';
|
||||
if (status.instance && status.policy !== 'user') return 'instance';
|
||||
return status.canConnectOwn ? 'setup' : 'adminOnly';
|
||||
}
|
||||
|
||||
/** How long chats are kept, as the card's last line says it. */
|
||||
function retentionLine(
|
||||
t: (key: string, params?: Record<string, number>) => string,
|
||||
retention: AiRetention | null
|
||||
): string {
|
||||
if (!retention) return '';
|
||||
if (retention.mode === 'forever') return t('assistant.history.forever');
|
||||
return t('assistant.history.retention', { count: retention.days });
|
||||
}
|
||||
|
||||
/**
|
||||
* The models a connection offers, for its model picker. Loaded again only when
|
||||
* the connection (not its model) changes; a provider that does not answer
|
||||
* leaves the list empty and the picker shows the current model alone.
|
||||
*/
|
||||
export function useAiModels(load: (() => Promise<AiModelInfo[]>) | null, connectionKey: string) {
|
||||
const [models, setModels] = useState<AiModelInfo[]>([]);
|
||||
const fetchModels = useEffectEvent((isCancelled: () => boolean) => {
|
||||
if (!load) return;
|
||||
load().then(
|
||||
(list) => {
|
||||
if (!isCancelled()) setModels(list);
|
||||
},
|
||||
() => {
|
||||
if (!isCancelled()) setModels([]);
|
||||
}
|
||||
);
|
||||
});
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetchModels(() => cancelled);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connectionKey]);
|
||||
return models;
|
||||
}
|
||||
|
||||
/**
|
||||
* The choices of a model picker: what the provider offers, the recommended
|
||||
* one first with its badge, and the current model kept when it is not listed.
|
||||
*/
|
||||
export function modelOptions(
|
||||
models: AiModelInfo[],
|
||||
current: string,
|
||||
labels: { free: string; recommended: string }
|
||||
) {
|
||||
const options = models.map((m) => ({
|
||||
value: m.id,
|
||||
label: m.label,
|
||||
badge: m.recommended ? labels.recommended : m.free ? labels.free : undefined,
|
||||
}));
|
||||
return options.some((o) => o.value === current)
|
||||
? options
|
||||
: [{ value: current, label: current, badge: undefined }, ...options];
|
||||
}
|
||||
|
||||
/** The actions on the user's own connection: its model, signing out of ChatGPT, removing it. */
|
||||
function useOwnConnection(own: AiConnectionView | null, reload: () => Promise<void>) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [confirmingDisconnect, setConfirmingDisconnect] = useState(false);
|
||||
const provider = own ? providerLabel(own.kind, own.host) : '';
|
||||
const models = useAiModels(
|
||||
own?.status === 'ok' ? () => aiConnectionsRepo.models() : null,
|
||||
own ? `${own.kind}@${own.host}` : ''
|
||||
);
|
||||
|
||||
const run = async (action: () => Promise<unknown>, doneKey: string | null) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await action();
|
||||
await reload();
|
||||
if (doneKey) toast.success(t(doneKey));
|
||||
} catch (err) {
|
||||
toast.error(t(connectErrorKey(err), { provider }));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
provider,
|
||||
models: own
|
||||
? modelOptions(models, own.model, { free: t('assistant.model.free'), recommended: t('assistant.model.recommended') })
|
||||
: [],
|
||||
busy,
|
||||
setModel: (model: string) => run(() => aiConnectionsRepo.setModel(model), 'common.saved'),
|
||||
signOut: () => run(() => aiConnectionsRepo.chatgptSignOut(), 'assistant.connect.statusSignedOut'),
|
||||
confirmingDisconnect,
|
||||
askDisconnect: () => setConfirmingDisconnect(true),
|
||||
cancelDisconnect: () => setConfirmingDisconnect(false),
|
||||
disconnect: () => {
|
||||
setConfirmingDisconnect(false);
|
||||
return run(() => aiConnectionsRepo.disconnect(), null);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings → Integrations → AI assistant, behind the desktop card and its
|
||||
* phone twin. The status comes from the assistant store, so connecting here
|
||||
* shows the launcher everywhere at once. Connecting happens only here (and
|
||||
* for everyone in the admin addons); the chat window holds no setup.
|
||||
*
|
||||
* `phone` is the phone twin, whose chat lives inside a trip.
|
||||
*/
|
||||
export function useAiConnections({ phone = false }: { phone?: boolean } = {}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const navigate = useNavigate();
|
||||
const status = useAssistantStore((s) => s.status);
|
||||
const loadStatus = useAssistantStore((s) => s.loadStatus);
|
||||
const openWindow = useAssistantStore((s) => s.open);
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === 'admin');
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
/** The panel opened on purpose: to renew a sign-in, replace a key, or connect one's own beside the admin's. */
|
||||
const [connecting, setConnecting] = useState<AiConnectMode | 'any' | null>(null);
|
||||
|
||||
const reload = async () => {
|
||||
await loadStatus();
|
||||
setLoaded(true);
|
||||
};
|
||||
const loadOnMount = useEffectEvent(() => void reload());
|
||||
useEffect(() => {
|
||||
loadOnMount();
|
||||
}, []);
|
||||
|
||||
const onConnected = () => {
|
||||
setConnecting(null);
|
||||
void reload();
|
||||
};
|
||||
useOpenrouterReturn(onConnected);
|
||||
|
||||
const own = status?.own ?? null;
|
||||
const view = viewOf(status, loaded);
|
||||
const ownActions = useOwnConnection(own, reload);
|
||||
|
||||
/**
|
||||
* Opens the chat on the trip under way or the next one (the planner opens it
|
||||
* for `?assistant=1`). Without one the desktop window asks for a trip on the
|
||||
* dashboard; the phone has no chat outside a trip, so it says to make one.
|
||||
*/
|
||||
const openAssistant = () => {
|
||||
const withoutTrip = () => {
|
||||
if (phone) {
|
||||
toast.info(t('assistant.picker.empty'));
|
||||
return;
|
||||
}
|
||||
openWindow();
|
||||
void navigate('/dashboard');
|
||||
};
|
||||
tripRepo.active().then(
|
||||
({ trip }) => (trip ? void navigate(`/trips/${trip.id}?assistant=1`) : withoutTrip()),
|
||||
withoutTrip
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
status,
|
||||
view,
|
||||
own,
|
||||
ownActions,
|
||||
instanceProvider: status?.instance ? providerLabel(status.instance.kind, status.instance.host) : '',
|
||||
quota: status?.quota ?? null,
|
||||
retentionText: retentionLine(t, status?.retention ?? null),
|
||||
/** The panel shows, and on which way it opens. */
|
||||
panel: view === 'setup' || connecting !== null,
|
||||
panelMode: connecting === 'any' || connecting === null ? undefined : connecting,
|
||||
repairMode: own ? repairModeOf(own) : null,
|
||||
connectOwn: () => setConnecting('any'),
|
||||
repair: (mode: AiConnectMode) => setConnecting(mode),
|
||||
closePanel: () => setConnecting(null),
|
||||
onConnected,
|
||||
canOpen: status?.available === true,
|
||||
openAssistant,
|
||||
isAdmin,
|
||||
openAdmin: () => navigate('/admin?tab=addons'),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { AiClaudeConnectorResponse } from '@trek/shared';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
|
||||
import { copyText } from '../../../utils/clipboard';
|
||||
import { isPublicHttpsUrl, svgDataUrl } from './aiConnectModel';
|
||||
|
||||
/**
|
||||
* Adding TREK to Claude as a connector (no AI connection of TREK's own
|
||||
* involved): the MCP address, the claude.ai link that adds it, and a QR code
|
||||
* for doing it from a phone. Claude reaches TREK from the internet, so on a
|
||||
* LAN or plain-http install the card explains that instead of offering a link
|
||||
* that would fail after the user did everything right.
|
||||
*/
|
||||
export function useClaudeConnector() {
|
||||
const [connector, setConnector] = useState<AiClaudeConnectorResponse | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
aiConnectionsRepo.claudeConnector().then(
|
||||
(next) => {
|
||||
if (!cancelled) setConnector(next);
|
||||
},
|
||||
() => {
|
||||
// Without an answer the card keeps to its description; nothing to link to.
|
||||
if (!cancelled) setConnector(null);
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (copiedTimer.current) clearTimeout(copiedTimer.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const copyUrl = async () => {
|
||||
if (!connector || !(await copyText(connector.mcpUrl))) return;
|
||||
setCopied(true);
|
||||
if (copiedTimer.current) clearTimeout(copiedTimer.current);
|
||||
copiedTimer.current = setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return {
|
||||
connector,
|
||||
reachable: connector ? isPublicHttpsUrl(connector.mcpUrl) : false,
|
||||
qrSrc: connector ? svgDataUrl(connector.qrSvg) : '',
|
||||
copied,
|
||||
copyUrl,
|
||||
};
|
||||
}
|
||||
@@ -24,13 +24,14 @@ describe('useIntegrationGates', () => {
|
||||
mcpEnabled: true,
|
||||
airtrailEnabled: false,
|
||||
llmEnabled: true,
|
||||
aiAssistantEnabled: false,
|
||||
dawarichEnabled: false,
|
||||
hasIntegrations: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-INTEGRATION-GATES-002: any one integration addon opens the tab, none keeps it closed', () => {
|
||||
for (const id of ['memories', 'mcp', 'airtrail', 'llm_parsing', 'dawarich']) {
|
||||
for (const id of ['memories', 'mcp', 'airtrail', 'llm_parsing', 'ai_assistant', 'dawarich']) {
|
||||
seedAddons([id]);
|
||||
expect(renderHook(() => useIntegrationGates({ reloadAddons: false })).result.current.hasIntegrations).toBe(true);
|
||||
}
|
||||
|
||||
@@ -18,10 +18,12 @@ export function useIntegrationGates({ reloadAddons }: { reloadAddons: boolean })
|
||||
const mcpEnabled = addonEnabled('mcp');
|
||||
const airtrailEnabled = addonEnabled('airtrail');
|
||||
const llmEnabled = addonEnabled('llm_parsing');
|
||||
const aiAssistantEnabled = addonEnabled('ai_assistant');
|
||||
const dawarichEnabled = addonEnabled('dawarich');
|
||||
// The wanderer connection feeds the Tours workspace, while the admin allows it there.
|
||||
const wandererEnabled = useAddonStore((s) => s.toursWanderer);
|
||||
const hasIntegrations = memoriesEnabled || mcpEnabled || airtrailEnabled || llmEnabled || dawarichEnabled;
|
||||
const hasIntegrations =
|
||||
memoriesEnabled || mcpEnabled || airtrailEnabled || llmEnabled || aiAssistantEnabled || dawarichEnabled;
|
||||
|
||||
useEffect(() => {
|
||||
if (reloadAddons) loadAddons();
|
||||
@@ -32,6 +34,7 @@ export function useIntegrationGates({ reloadAddons }: { reloadAddons: boolean })
|
||||
mcpEnabled,
|
||||
airtrailEnabled,
|
||||
llmEnabled,
|
||||
aiAssistantEnabled,
|
||||
dawarichEnabled,
|
||||
wandererEnabled,
|
||||
hasIntegrations,
|
||||
|
||||
Reference in New Issue
Block a user