moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,212 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
getChannels: vi.fn(),
getChannelPairings: vi.fn(),
getWorkspaces: vi.fn(),
saveChannelConfig: vi.fn(),
setChannelRunning: vi.fn(),
createChannelPairingCode: vi.fn(),
revokeChannelSender: vi.fn(),
getServerUrl: vi.fn(() => 'http://127.0.0.1:3333'),
qrToDataUrl: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks }));
vi.mock('qrcode', () => ({ default: { toDataURL: mocks.qrToDataUrl } }));
import ChannelsSettings from './ChannelsSettings';
const channels = [
{
platform: 'telegram',
running: false,
connected: false,
config: { enabled: false, defaultWorkspace: 'ws-1' },
secrets: { telegram_bot_token: null },
},
{
platform: 'discord',
running: false,
connected: false,
config: { enabled: false, defaultWorkspace: 'ws-1' },
secrets: { discord_bot_token: null },
},
{
platform: 'slack',
running: false,
connected: false,
config: { enabled: false, defaultWorkspace: 'ws-1' },
secrets: { slack_app_token: null, slack_bot_token: null },
},
{
platform: 'whatsapp',
running: false,
connected: false,
config: { enabled: false, defaultWorkspace: 'ws-1' },
secrets: {},
},
];
beforeEach(() => {
mocks.getChannels.mockResolvedValue(channels);
mocks.getChannelPairings.mockResolvedValue({});
mocks.getWorkspaces.mockResolvedValue([
{ id: 'ws-1', name: 'Client Alpha' },
{ id: 'ws-2', name: 'Internal Ops' },
]);
mocks.saveChannelConfig.mockResolvedValue({ ok: true });
mocks.setChannelRunning.mockResolvedValue({ ok: true });
mocks.createChannelPairingCode.mockResolvedValue({ code: 'ABCDEFGH', expiresAt: Date.now() + 600_000 });
mocks.revokeChannelSender.mockResolvedValue({ ok: true });
mocks.qrToDataUrl.mockResolvedValue('data:image/png;base64,channel-qr');
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('ChannelsSettings protected API integration', () => {
it('loads through the authenticated adapter and exposes labelled setup controls', async () => {
render(<ChannelsSettings />);
expect(await screen.findByRole('heading', { name: 'Channels' })).toBeInTheDocument();
await waitFor(() => expect(mocks.getChannels).toHaveBeenCalledTimes(1));
expect(mocks.getChannelPairings).toHaveBeenCalledTimes(1);
expect(mocks.getWorkspaces).toHaveBeenCalledTimes(1);
expect(screen.getByLabelText('Telegram bot token')).toBeInTheDocument();
expect(screen.getByLabelText('Telegram default workspace')).toHaveValue('ws-1');
expect(screen.getAllByRole('option', { name: 'Client Alpha' })).toHaveLength(4);
});
it('keeps a token draft when the protected save request fails', async () => {
mocks.saveChannelConfig.mockRejectedValueOnce(new Error('Token was rejected'));
render(<ChannelsSettings />);
const input = await screen.findByLabelText('Telegram bot token');
fireEvent.change(input, { target: { value: '123456:keep-this-draft' } });
const telegram = screen.getByRole('region', { name: 'Telegram' });
fireEvent.click(within(telegram).getByRole('button', { name: 'Save' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Token was rejected');
expect(input).toHaveValue('123456:keep-this-draft');
});
it('gates start on required secrets and clears a saved token from the UI', async () => {
render(<ChannelsSettings />);
const telegram = await screen.findByRole('region', { name: 'Telegram' });
const start = within(telegram).getByRole('button', { name: 'Start' });
expect(start).toBeDisabled();
expect(start).toHaveAttribute('title', 'Save Bot token first');
const input = within(telegram).getByLabelText('Telegram bot token');
fireEvent.change(input, { target: { value: '123456:secret-token' } });
fireEvent.click(within(telegram).getByRole('button', { name: 'Save' }));
await waitFor(() => expect(mocks.saveChannelConfig).toHaveBeenCalledWith('telegram', {
secrets: { telegram_bot_token: '123456:secret-token' },
}));
await waitFor(() => expect(input).toHaveValue(''));
expect(screen.queryByText('123456:secret-token')).not.toBeInTheDocument();
});
it('saves both Slack credentials before enabling start', async () => {
const slackWith = (appToken: string | null, botToken: string | null) => channels.map(channel => (
channel.platform === 'slack'
? { ...channel, secrets: { slack_app_token: appToken, slack_bot_token: botToken } }
: channel
));
mocks.getChannels
.mockResolvedValueOnce(channels)
.mockResolvedValueOnce(slackWith('xapp...(18)', null))
.mockResolvedValue(slackWith('xapp...(18)', 'xoxb...(17)'));
render(<ChannelsSettings />);
const slack = await screen.findByRole('region', { name: 'Slack' });
const start = within(slack).getByRole('button', { name: 'Start' });
expect(start).toBeDisabled();
fireEvent.change(within(slack).getByLabelText('Slack app token'), {
target: { value: 'xapp-private-value' },
});
fireEvent.click(within(slack).getAllByRole('button', { name: 'Save' })[0]);
await waitFor(() => expect(mocks.saveChannelConfig).toHaveBeenCalledWith('slack', {
secrets: { slack_app_token: 'xapp-private-value' },
}));
fireEvent.change(within(slack).getByLabelText('Slack bot token'), {
target: { value: 'xoxb-private-value' },
});
fireEvent.click(within(slack).getAllByRole('button', { name: 'Save' })[1]);
await waitFor(() => expect(start).toBeEnabled());
expect(screen.queryByText(/private-value/)).not.toBeInTheDocument();
fireEvent.click(start);
await waitFor(() => expect(mocks.setChannelRunning).toHaveBeenCalledWith('slack', true));
});
it('starts WhatsApp, renders the rotating QR, and can stop the transport', async () => {
const runningChannels = channels.map(channel => channel.platform === 'whatsapp'
? { ...channel, running: true, qr: 'whatsapp-pairing-payload' }
: channel);
mocks.getChannels.mockResolvedValueOnce(channels).mockResolvedValue(runningChannels);
render(<ChannelsSettings />);
const whatsapp = await screen.findByRole('region', { name: 'WhatsApp' });
fireEvent.click(within(whatsapp).getByRole('button', { name: 'Start' }));
expect(await within(whatsapp).findByRole('img', { name: 'WhatsApp pairing QR code' }))
.toHaveAttribute('src', 'data:image/png;base64,channel-qr');
expect(mocks.qrToDataUrl).toHaveBeenCalledWith('whatsapp-pairing-payload', expect.any(Object));
fireEvent.click(within(whatsapp).getByRole('button', { name: 'Stop' }));
await waitFor(() => expect(mocks.setChannelRunning).toHaveBeenCalledWith('whatsapp', false));
});
it('shows a lifecycle failure and clears it after a successful retry', async () => {
mocks.setChannelRunning
.mockRejectedValueOnce(new Error('WhatsApp transport unavailable'))
.mockResolvedValueOnce({ ok: true });
render(<ChannelsSettings />);
const whatsapp = await screen.findByRole('region', { name: 'WhatsApp' });
fireEvent.click(within(whatsapp).getByRole('button', { name: 'Start' }));
expect(await screen.findByRole('alert')).toHaveTextContent('WhatsApp transport unavailable');
fireEvent.click(within(whatsapp).getByRole('button', { name: 'Start' }));
await waitFor(() => expect(mocks.setChannelRunning).toHaveBeenCalledTimes(2));
await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
});
it('switches workspaces, generates a pairing code, and revokes access', async () => {
mocks.getChannels.mockResolvedValue(channels.map(channel => channel.platform === 'telegram'
? {
...channel,
running: true,
connected: true,
secrets: { telegram_bot_token: '1234…(32)' },
}
: channel));
mocks.getChannelPairings.mockResolvedValue({
telegram: [{ senderId: 'sender-1', senderName: 'Marko', pairedAt: Date.now() }],
});
render(<ChannelsSettings />);
const telegram = await screen.findByRole('region', { name: 'Telegram' });
fireEvent.change(within(telegram).getByLabelText('Telegram default workspace'), {
target: { value: 'ws-2' },
});
await waitFor(() => expect(mocks.saveChannelConfig)
.toHaveBeenCalledWith('telegram', { defaultWorkspace: 'ws-2' }));
fireEvent.click(within(telegram).getByRole('button', { name: 'Generate pairing code' }));
expect(await within(telegram).findByText(/ABCDEFGH/)).toBeInTheDocument();
expect(mocks.createChannelPairingCode).toHaveBeenCalledWith('telegram');
fireEvent.click(within(telegram).getByRole('button', { name: 'Revoke' }));
await waitFor(() => expect(mocks.revokeChannelSender)
.toHaveBeenCalledWith('telegram', 'sender-1'));
});
});

View File

@@ -0,0 +1,392 @@
/**
* Settings → Channels — connect Waggle to Slack / Telegram / WhatsApp /
* Discord (docs/plans/CHANNELS-ARC-2026-07-09.md P4).
*
* Talks to the sidecar's /api/channels surface. Security model mirrored in
* copy: deny-by-default pairing (mint a code here, DM it to the bot), bot
* tokens go straight to the vault (reads come back masked). WhatsApp shows
* the founder-mandated ban-risk disclosure and renders Baileys' pairing QR.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { Loader2, MessageCircle, Play, RefreshCw, Square, Trash2 } from 'lucide-react';
import QRCode from 'qrcode';
import {
adapter,
type ChannelPairings,
type ChannelPlatform,
type ChannelStatus,
} from '@/lib/adapter';
import type { Workspace } from '@/lib/types';
const PLATFORM_META: Record<ChannelPlatform, {
label: string;
secretFields: Array<{ key: string; label: string; placeholder: string }>;
setupHint: string;
}> = {
telegram: {
label: 'Telegram',
secretFields: [{ key: 'telegram_bot_token', label: 'Bot token', placeholder: '123456:ABC… (from @BotFather)' }],
setupHint: 'Create a bot with @BotFather, paste its token, then DM your bot /pair <code>.',
},
discord: {
label: 'Discord',
secretFields: [{ key: 'discord_bot_token', label: 'Bot token', placeholder: 'Bot token from the developer portal' }],
setupHint: 'Create an app at discord.com/developers, enable the MESSAGE CONTENT intent, invite the bot to your server, then send /pair <code>.',
},
slack: {
label: 'Slack',
secretFields: [
{ key: 'slack_app_token', label: 'App token', placeholder: 'xapp-… (Socket Mode, connections:write)' },
{ key: 'slack_bot_token', label: 'Bot token', placeholder: 'xoxb-… (chat:write)' },
],
setupHint: 'Enable Socket Mode on your Slack app, subscribe to message.im / message.channels, then DM the bot /pair <code>.',
},
whatsapp: {
label: 'WhatsApp',
secretFields: [],
setupHint: 'Enable and start, then scan the QR with WhatsApp → Linked Devices. Message yourself or the linked number /pair <code>.',
},
};
function actionError(error: unknown, fallback: string): string {
return error instanceof Error && error.message ? error.message : fallback;
}
function StatusBadge({ s }: { s: ChannelStatus }) {
const tone = s.connected
? 'bg-green-500/15 text-green-500'
: s.running
? 'bg-primary/15 text-honey'
: 'bg-muted text-muted-foreground';
const label = s.connected ? 'Connected' : s.running ? 'Connecting…' : 'Off';
return <span className={`px-2 py-0.5 rounded-full text-[11px] font-display ${tone}`}>{label}</span>;
}
/** Renders a Baileys pairing string as a QR image. */
function WhatsAppQr({ qr }: { qr: string }) {
const [dataUrl, setDataUrl] = useState<string | null>(null);
useEffect(() => {
let alive = true;
QRCode.toDataURL(qr, { margin: 1, width: 220 })
.then(url => { if (alive) setDataUrl(url); })
.catch(() => { if (alive) setDataUrl(null); });
return () => { alive = false; };
}, [qr]);
if (!dataUrl) return null;
return (
<div className="flex max-w-full w-fit flex-col items-center gap-2 rounded-lg bg-white p-3">
<img className="h-auto max-w-full" src={dataUrl} alt="WhatsApp pairing QR code" width={220} height={220} />
</div>
);
}
const ChannelsSettings = () => {
const [channels, setChannels] = useState<ChannelStatus[]>([]);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [secretDrafts, setSecretDrafts] = useState<Record<string, string>>({});
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
const [pairingCode, setPairingCode] = useState<{ platform: ChannelPlatform; code: string; expiresAt: number } | null>(null);
const [paired, setPaired] = useState<ChannelPairings>({});
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const refresh = useCallback(async (clearError = true) => {
try {
const [channelRows, pairedRows] = await Promise.all([
adapter.getChannels(),
adapter.getChannelPairings(),
]);
setChannels(channelRows);
setPaired(pairedRows);
if (clearError) setError(null);
} catch (err) {
setError(actionError(err, 'Could not reach the Waggle service.'));
} finally {
setLoading(false);
}
}, []);
// Poll while the tab is open — WhatsApp QR rotates and transports flap.
useEffect(() => {
void refresh(true);
void adapter.getWorkspaces()
.then(setWorkspaces)
.catch(err => setError(actionError(err, 'Could not load workspaces.')));
pollRef.current = setInterval(() => { void refresh(false); }, 5000);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, [refresh]);
const saveConfig = async (
platform: ChannelPlatform,
body: { enabled?: boolean; defaultWorkspace?: string; secrets?: Record<string, string> },
): Promise<boolean> => {
setBusy(platform);
try {
await adapter.saveChannelConfig(platform, body);
setError(null);
await refresh(false);
return true;
} catch (err) {
setError(actionError(err, 'Saving channel settings failed.'));
return false;
} finally {
setBusy(null);
}
};
const lifecycle = async (platform: ChannelPlatform, running: boolean) => {
setBusy(platform);
try {
await adapter.setChannelRunning(platform, running);
setError(null);
await refresh(false);
} catch (err) {
setError(actionError(
err,
`Could not ${running ? 'start' : 'stop'} ${PLATFORM_META[platform].label}.`,
));
} finally {
setBusy(null);
}
};
const mintPairingCode = async (platform: ChannelPlatform) => {
setBusy(platform);
try {
const body = await adapter.createChannelPairingCode(platform);
setPairingCode({ platform, ...body });
setError(null);
} catch (err) {
setError(actionError(err, 'Could not generate a pairing code.'));
} finally {
setBusy(null);
}
};
const revokeSender = async (platform: ChannelPlatform, senderId: string) => {
setBusy(platform);
try {
await adapter.revokeChannelSender(platform, senderId);
setError(null);
await refresh(false);
} catch (err) {
setError(actionError(err, 'Could not revoke channel access.'));
} finally {
setBusy(null);
}
};
if (loading) {
return (
<div className="flex items-center gap-2 text-xs text-muted-foreground" role="status">
<Loader2 className="w-3.5 h-3.5 animate-spin" /> Loading channels…
</div>
);
}
return (
<div className="space-y-5" data-testid="settings-channels">
<div>
<h3 className="text-sm font-display font-semibold text-foreground flex items-center gap-2">
<MessageCircle className="w-4 h-4" /> Channels
</h3>
<p className="text-[11px] text-muted-foreground mt-1 leading-relaxed">
Talk to your Waggle agent from Slack, Telegram, WhatsApp, or Discord. Nobody can reach it
until they pair: generate a code below and send <code className="text-foreground">/pair &lt;code&gt;</code> to
the bot from your own account. In any chat, <code className="text-foreground">/workspace</code> switches
which workspace answers.
</p>
</div>
{error && (
<div className="p-2.5 rounded-lg border border-destructive/40 bg-destructive/5 text-[11px] text-destructive" role="alert">
{error}
</div>
)}
{channels.map(ch => {
const meta = PLATFORM_META[ch.platform];
const isBusy = busy === ch.platform;
const missingSecrets = meta.secretFields.filter(field => !ch.secrets[field.key]);
const workspaceKnown = workspaces.some(workspace => workspace.id === ch.config.defaultWorkspace);
return (
<section key={ch.platform} className="p-3 rounded-lg bg-secondary/30 border border-border/30 space-y-3" aria-labelledby={`channel-${ch.platform}-title`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<h4 id={`channel-${ch.platform}-title`} className="text-xs font-display font-medium text-foreground">{meta.label}</h4>
<StatusBadge s={ch} />
</div>
<div className="flex items-center gap-1.5">
{ch.running ? (
<button
type="button"
onClick={() => void lifecycle(ch.platform, false)}
disabled={isBusy}
className="flex min-h-8 items-center gap-1 px-2 py-1 rounded-lg text-[11px] bg-muted/60 text-foreground hover:bg-muted disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
<Square className="w-3 h-3" /> Stop
</button>
) : (
<button
type="button"
onClick={() => void lifecycle(ch.platform, true)}
disabled={isBusy || missingSecrets.length > 0}
title={missingSecrets.length > 0 ? `Save ${missingSecrets.map(field => field.label).join(' and ')} first` : undefined}
className="flex min-h-8 items-center gap-1 px-2 py-1 rounded-lg text-[11px] bg-primary/20 text-honey hover:bg-primary/30 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
<Play className="w-3 h-3" /> Start
</button>
)}
</div>
</div>
{ch.platform === 'whatsapp' && (
<div className="p-2.5 rounded-lg border border-destructive/40 bg-destructive/5 text-[11px] text-destructive leading-relaxed">
<strong>Heads-up:</strong> WhatsApp support uses an unofficial client (Baileys) that
violates WhatsApp&rsquo;s Terms of Service. Accounts can be <strong>banned</strong>.
Strongly consider linking a <strong>secondary number</strong>, not your personal one.
</div>
)}
<p className="text-[11px] text-muted-foreground leading-relaxed">{meta.setupHint}</p>
{ch.lastError && !ch.connected && (
<p className="text-[11px] text-destructive">Last error: {ch.lastError}</p>
)}
{!ch.running && missingSecrets.length > 0 && (
<p className="text-[11px] text-muted-foreground">
Save {missingSecrets.map(field => field.label.toLowerCase()).join(' and ')} to enable Start.
</p>
)}
{/* WhatsApp pairing QR (Baileys) */}
{ch.platform === 'whatsapp' && ch.running && !ch.connected && ch.qr && (
<WhatsAppQr qr={ch.qr} />
)}
{/* Secrets → vault */}
{meta.secretFields.map(field => (
<div key={field.key} className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-end">
<div className="min-w-0 flex-1">
<label htmlFor={`${ch.platform}-${field.key}`} className="block text-[11px] text-muted-foreground mb-0.5">
{field.label}{ch.secrets[field.key] ? ` — saved (${ch.secrets[field.key]})` : ''}
</label>
<input
id={`${ch.platform}-${field.key}`}
name={field.key}
type="password"
aria-label={`${meta.label} ${field.label.toLowerCase()}`}
autoComplete="off"
value={secretDrafts[field.key] ?? ''}
onChange={e => setSecretDrafts(d => ({ ...d, [field.key]: e.target.value }))}
placeholder={field.placeholder}
className="w-full px-2.5 py-1.5 rounded-lg bg-background border border-border/40 text-xs text-foreground placeholder:text-muted-foreground/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
/>
</div>
<button
type="button"
onClick={() => {
const value = secretDrafts[field.key]?.trim();
if (!value) return;
void saveConfig(ch.platform, { secrets: { [field.key]: value } })
.then(saved => {
if (saved) setSecretDrafts(d => ({ ...d, [field.key]: '' }));
});
}}
disabled={isBusy || !secretDrafts[field.key]?.trim()}
className="min-h-8 w-full rounded-lg bg-primary/20 px-2.5 py-1.5 text-[11px] text-honey hover:bg-primary/30 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] sm:w-auto"
>
Save
</button>
</div>
))}
{/* Non-secret config */}
<div className="flex flex-col items-stretch gap-2 sm:flex-row sm:items-center sm:gap-3">
<label className="flex items-center gap-1.5 text-[11px] text-foreground sm:shrink-0">
<input
aria-label={`${meta.label} start automatically`}
type="checkbox"
checked={ch.config.enabled}
onChange={e => void saveConfig(ch.platform, { enabled: e.target.checked })}
disabled={isBusy}
className="focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
/>
Start automatically
</label>
<div className="flex min-w-0 flex-1 flex-col items-stretch gap-1 sm:flex-row sm:items-center sm:gap-1.5">
<label htmlFor={`${ch.platform}-workspace`} className="text-[11px] text-muted-foreground whitespace-nowrap">Default workspace</label>
<select
id={`${ch.platform}-workspace`}
name={`${ch.platform}DefaultWorkspace`}
aria-label={`${meta.label} default workspace`}
value={ch.config.defaultWorkspace}
onChange={e => void saveConfig(ch.platform, { defaultWorkspace: e.target.value })}
disabled={isBusy || workspaces.length === 0}
className="min-w-0 flex-1 px-2 py-1 rounded-lg bg-background border border-border/40 text-[11px] text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
{!workspaceKnown && (
<option value={ch.config.defaultWorkspace}>{ch.config.defaultWorkspace} (current)</option>
)}
{workspaces.map(workspace => (
<option key={workspace.id} value={workspace.id}>{workspace.name}</option>
))}
</select>
</div>
</div>
{/* Pairing */}
<div className="pt-1 border-t border-border/30 space-y-2">
<div className="flex flex-col items-start gap-2 sm:flex-row sm:items-center">
<button
type="button"
onClick={() => void mintPairingCode(ch.platform)}
disabled={isBusy || !ch.running}
className="flex min-h-8 w-full items-center justify-center gap-1 rounded-lg bg-muted/60 px-2 py-1 text-[11px] text-foreground hover:bg-muted disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] sm:w-auto"
>
<RefreshCw className="w-3 h-3" /> Generate pairing code
</button>
{pairingCode?.platform === ch.platform && pairingCode.expiresAt > Date.now() && (
<span className="text-[11px] text-foreground">
Send <code className="px-1.5 py-0.5 rounded bg-primary/15 text-honey font-mono">/pair {pairingCode.code}</code>
{' '}to the bot (valid ~10 min)
</span>
)}
</div>
{!ch.running && (
<p className="text-[11px] text-muted-foreground">Start the channel before generating a pairing code.</p>
)}
{(paired[ch.platform] ?? []).length > 0 && (
<div className="space-y-1">
{(paired[ch.platform] ?? []).map(s => (
<div key={s.senderId} className="flex items-center justify-between gap-2 text-[11px]">
<span className="min-w-0 break-all text-muted-foreground">
{s.senderName ? `${s.senderName} · ` : ''}{s.senderId}
</span>
<button
type="button"
onClick={() => void revokeSender(ch.platform, s.senderId)}
disabled={isBusy}
className="flex min-h-8 items-center gap-1 px-1.5 py-0.5 rounded text-destructive hover:bg-destructive/10 disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
title="Revoke access"
>
<Trash2 className="w-3 h-3" /> Revoke
</button>
</div>
))}
</div>
)}
</div>
</section>
);
})}
</div>
);
};
export default ChannelsSettings;

View File

@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import CoverageCompassCard from './CoverageCompassCard';
describe('CoverageCompassCard', () => {
it('does not claim Browser Companion coverage before native entry points are proven', () => {
render(<CoverageCompassCard />);
const partialRows = screen.getAllByTestId('coverage-compass-row-partial');
const browserRow = partialRows.find((row) => row.textContent?.includes('Browser AI extensions'));
expect(browserRow).toBeDefined();
expect(browserRow).toHaveTextContent(/native toolbar\/context menu pending/i);
});
});

View File

@@ -0,0 +1,105 @@
/**
* Coverage compass card — Settings → Billing.
*
* F4 polish from the 2026-05-28 addictiveness audit. Answers the
* "what am I getting for what I pay?" question that personas P3 (Sarah,
* marketing), P4 (Imran, consultant), and P7 (Anya, writer) all hit
* when comparing Waggle to their current ChatGPT Plus / Notion AI /
* Gamma stack.
*
* Items split into three groups: COVERED (Waggle does this), PARTIAL
* (Waggle has the substrate but the UX isn't first-class yet), and
* NOT YET (out of scope for now). Honest categorisation matters — if
* we mark something COVERED that the user opens another tool for,
* trust evaporates fast.
*/
import { Check, CircleDashed, X } from 'lucide-react';
type Coverage = 'covered' | 'partial' | 'not-yet';
interface CompetingTool {
name: string;
category: string;
coverage: Coverage;
via?: string; // how Waggle covers it (short noun phrase)
}
const TOOLS: CompetingTool[] = [
{ name: 'ChatGPT / Claude.ai', category: 'general AI chat', coverage: 'covered', via: 'Chat app + persona switcher' },
{ name: 'Mem.ai / Heyday', category: 'personal memory', coverage: 'covered', via: 'FrameStore + Knowledge Graph + Harvest' },
{ name: 'Browser AI extensions', category: 'save-to-memory from web', coverage: 'partial', via: 'Companion popup + capture flow; native toolbar/context menu pending' },
{ name: 'Notion AI', category: 'notes + AI in notes', coverage: 'covered', via: 'Memory app + Wiki compiler' },
{ name: 'Granola / Otter.ai', category: 'meeting transcripts', coverage: 'partial', via: 'Voice app + transcript ingest (no native recording yet)' },
{ name: 'Gamma / Beautiful.ai', category: 'AI-generated decks', coverage: 'partial', via: 'pptx / presentation-design skills (no native deck editor)' },
{ name: 'Telegram bot for cron updates', category: 'outbound digests', coverage: 'covered', via: 'Scheduled Jobs → Telegram channel' },
{ name: 'Zapier / n8n', category: 'workflow automation', coverage: 'partial', via: 'Scheduled Jobs + Skills marketplace (limited triggers)' },
{ name: 'Excel Copilot', category: 'spreadsheet AI', coverage: 'not-yet', via: 'xlsx skill exists; native editor planned' },
{ name: 'GitHub Copilot / Cursor', category: 'in-editor coding', coverage: 'not-yet', via: 'intentional — use Claude Code for coding, Waggle for everything else' },
];
const ICONS: Record<Coverage, { Icon: typeof Check; className: string; label: string }> = {
'covered': { Icon: Check, className: 'text-emerald-400', label: 'Covered' },
'partial': { Icon: CircleDashed, className: 'text-amber-400', label: 'Partial' },
'not-yet': { Icon: X, className: 'text-muted-foreground/60', label: 'Not yet' },
};
const CoverageCompassCard = () => {
const counts = TOOLS.reduce<Record<Coverage, number>>(
(acc, t) => ({ ...acc, [t.coverage]: (acc[t.coverage] ?? 0) + 1 }),
{ 'covered': 0, 'partial': 0, 'not-yet': 0 },
);
return (
<div
className="p-4 rounded-xl bg-secondary/30 border border-border/30 space-y-3"
data-testid="coverage-compass-card"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-xs font-display font-medium text-foreground">What Waggle replaces</p>
<p className="text-[11px] text-muted-foreground mt-0.5">
Honest scoring — only items that genuinely don't need another tool open are marked covered.
</p>
</div>
<div className="flex items-center gap-2 shrink-0 text-[10px] font-display">
<span className="inline-flex items-center gap-1 text-emerald-400">
<Check className="w-2.5 h-2.5" />{counts['covered']}
</span>
<span className="inline-flex items-center gap-1 text-amber-400">
<CircleDashed className="w-2.5 h-2.5" />{counts['partial']}
</span>
<span className="inline-flex items-center gap-1 text-muted-foreground/60">
<X className="w-2.5 h-2.5" />{counts['not-yet']}
</span>
</div>
</div>
<ul className="space-y-1.5" role="list">
{TOOLS.map(tool => {
const { Icon, className, label } = ICONS[tool.coverage];
return (
<li
key={tool.name}
className="flex items-start gap-2.5 text-[11px]"
data-testid={`coverage-compass-row-${tool.coverage}`}
>
<Icon className={`w-3 h-3 mt-0.5 shrink-0 ${className}`} aria-label={label} />
<div className="min-w-0 flex-1">
<p className="text-foreground">
{tool.name}
<span className="text-muted-foreground"> · {tool.category}</span>
</p>
{tool.via && (
<p className="text-[10px] text-muted-foreground/80 mt-0.5">via {tool.via}</p>
)}
</div>
</li>
);
})}
</ul>
</div>
);
};
export default CoverageCompassCard;

View File

@@ -0,0 +1,44 @@
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
toast: vi.fn(),
}));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) }));
vi.mock('@/lib/adapter', () => ({
adapter: {
getServerUrl: () => 'http://localhost:7317',
},
}));
import TelegramDigestCard from './TelegramDigestCard';
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn(async () => new Response(
JSON.stringify({ configured: false, hasToken: false, hasChatId: false }),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
)));
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
vi.clearAllMocks();
});
describe('TelegramDigestCard', () => {
it('a11y: credential controls expose labels and stable form metadata', async () => {
render(<TelegramDigestCard />);
await screen.findByTestId('telegram-status-badge');
const token = screen.getByLabelText(/bot token/i);
expect(token).toHaveAttribute('name', 'telegramBotToken');
expect(token).toHaveAttribute('autocomplete', 'off');
const chatId = screen.getByLabelText(/chat id/i);
expect(chatId).toHaveAttribute('name', 'telegramChatId');
expect(chatId).toHaveAttribute('autocomplete', 'off');
});
});

View File

@@ -0,0 +1,203 @@
/**
* Telegram digest configuration card — Settings → Advanced.
*
* FR-2 §UI from the 2026-05-28 addictiveness audit. Wraps the four
* /api/telegram/* endpoints so a user can self-serve the connection
* without curl. Persona uplift comes when ScheduledJobs grows an
* "output channel" dropdown that routes job results to /api/telegram/send;
* this card is the prerequisite trust + connection surface.
*/
import { useState, useEffect } from 'react';
import { Send, Loader2, CheckCircle2, AlertCircle, Eye, EyeOff } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { useToast } from '@/hooks/use-toast';
import { adapter } from '@/lib/adapter';
interface TelegramStatus {
configured: boolean;
hasToken: boolean;
hasChatId: boolean;
}
async function fetchStatus(): Promise<TelegramStatus | null> {
try {
const r = await fetch(`${adapter.getServerUrl()}/api/telegram/status`);
if (!r.ok) return null;
return await r.json();
} catch {
return null;
}
}
const TelegramDigestCard = () => {
const { toast } = useToast();
const [status, setStatus] = useState<TelegramStatus | null>(null);
const [token, setToken] = useState('');
const [chatId, setChatId] = useState('');
const [showToken, setShowToken] = useState(false);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
useEffect(() => { fetchStatus().then(setStatus); }, []);
const save = async () => {
if (!token && !chatId) {
toast({ title: 'Nothing to save', description: 'Enter a bot token or chat ID first.' });
return;
}
setSaving(true);
try {
const body: Record<string, string> = {};
if (token) body.botToken = token;
if (chatId) body.chatId = chatId;
const r = await fetch(`${adapter.getServerUrl()}/api/telegram/config`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const data = await r.json();
if (!r.ok) {
toast({ title: 'Save failed', description: data?.error || `HTTP ${r.status}`, variant: 'destructive' });
} else {
toast({ title: 'Saved', description: 'Telegram credentials stored in vault.' });
setToken('');
setChatId('');
setStatus(await fetchStatus());
}
} catch (err) {
toast({ title: 'Save failed', description: String(err), variant: 'destructive' });
} finally {
setSaving(false);
}
};
const sendTest = async () => {
setTesting(true);
try {
const r = await fetch(`${adapter.getServerUrl()}/api/telegram/test`, { method: 'POST' });
const data = await r.json();
if (!r.ok || data?.ok === false) {
toast({
title: 'Test failed',
description: data?.error || `HTTP ${r.status}`,
variant: 'destructive',
});
} else {
toast({ title: 'Sent ✓', description: 'Check your Telegram for the test message.' });
}
} catch (err) {
toast({ title: 'Test failed', description: String(err), variant: 'destructive' });
} finally {
setTesting(false);
}
};
const configured = status?.configured ?? false;
return (
<div
className="p-3 rounded-xl bg-secondary/30 border border-border/30 space-y-2.5"
data-testid="telegram-digest-card"
>
<div className="flex items-center justify-between">
<p className="text-xs font-display font-medium text-foreground flex items-center gap-1.5">
<Send className="w-3.5 h-3.5 text-honey" /> Telegram digest
</p>
<span
data-testid="telegram-status-badge"
className={`text-[10px] px-1.5 py-0.5 rounded-full font-display inline-flex items-center gap-1 ${
configured
? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'
: 'bg-muted text-muted-foreground border border-border/40'
}`}
>
{configured ? <CheckCircle2 className="w-2.5 h-2.5" /> : <AlertCircle className="w-2.5 h-2.5" />}
{configured ? 'Connected' : 'Not configured'}
</span>
</div>
<p className="text-[11px] text-muted-foreground leading-relaxed">
Push scheduled-job results and daily digests to your Telegram. Create a bot via{' '}
<a
href="https://t.me/BotFather"
target="_blank" rel="noreferrer noopener"
className="text-honey hover:underline"
>
@BotFather
</a>{' '}
to get a token, then DM your bot once and read the chat ID from{' '}
<code className="text-[10px] bg-muted/40 px-1 rounded">api.telegram.org/bot&lt;TOKEN&gt;/getUpdates</code>.
</p>
<div className="space-y-2">
<div>
<label htmlFor="telegram-bot-token" className="text-[10px] font-display text-muted-foreground block mb-1">
Bot token {status?.hasToken && <span className="text-status-healthy">(saved)</span>}
</label>
<div className="relative">
<Input
id="telegram-bot-token"
name="telegramBotToken"
autoComplete="off"
type={showToken ? 'text' : 'password'}
value={token}
onChange={e => setToken(e.target.value)}
placeholder={status?.hasToken ? '••••••••••• (leave blank to keep)' : 'e.g. 123456789:AAH…'}
className="text-[11px] pr-7"
data-testid="telegram-bot-token-input"
/>
<button
type="button"
onClick={() => setShowToken(v => !v)}
aria-label={showToken ? 'Hide token' : 'Show token'}
className="absolute right-1 top-1/2 -translate-y-1/2 p-1 text-muted-foreground hover:text-foreground"
>
{showToken ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
</button>
</div>
</div>
<div>
<label htmlFor="telegram-chat-id" className="text-[10px] font-display text-muted-foreground block mb-1">
Chat ID {status?.hasChatId && <span className="text-status-healthy">(saved)</span>}
</label>
<Input
id="telegram-chat-id"
name="telegramChatId"
autoComplete="off"
type="text"
value={chatId}
onChange={e => setChatId(e.target.value)}
placeholder={status?.hasChatId ? '••••••' : 'e.g. 123456789 or -1001234567890'}
className="text-[11px]"
data-testid="telegram-chat-id-input"
/>
</div>
</div>
<div className="flex gap-2 pt-1">
<button
onClick={save}
disabled={saving || (!token && !chatId)}
data-testid="telegram-save-btn"
className="text-[11px] px-3 py-1.5 rounded-lg bg-primary text-primary-foreground hover:bg-primary/85 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
>
{saving && <Loader2 className="w-3 h-3 animate-spin" />}
Save
</button>
<button
onClick={sendTest}
disabled={testing || !configured}
data-testid="telegram-test-btn"
className="text-[11px] px-3 py-1.5 rounded-lg bg-secondary border border-border/40 text-foreground hover:bg-secondary/70 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
>
{testing && <Loader2 className="w-3 h-3 animate-spin" />}
Send test message
</button>
</div>
</div>
);
};
export default TelegramDigestCard;