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:
Maurice
2026-10-21 18:52:44 +02:00
parent 31859651d7
commit b64da26651
505 changed files with 51841 additions and 227 deletions
@@ -22,6 +22,7 @@ import {
} from '../../../components/Admin/addons/addonModel'
import { useAddonManager } from '../../../components/Admin/addons/useAddonManager'
import { useLlmParsingConfig } from '../../../components/Admin/addons/useLlmParsingConfig'
import MAdminAiConfig from './MAdminAiConfig'
import { ImmichIcon, SynologyIcon } from '../../../components/Admin/addons/PhotoProviderIcons'
import { MAdminButton, MAdminCard, MAdminClampedText, MAdminField, MAdminInput, MAdminSecretInput } from './MAdminUi'
import WandererMark from '../../../components/Tours/wanderer/WandererMark'
@@ -181,6 +182,11 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
<LlmParsingConfig addon={addon} />
</div>
)}
{addon.id === 'ai_assistant' && addon.enabled && (
<div className="mt-1 border-t border-[color:var(--m-rowbr)] pt-3">
<MAdminAiConfig />
</div>
)}
</div>
))}
</MAdminCard>
@@ -0,0 +1,65 @@
// FE-MOB-AI-ADMIN-001 to FE-MOB-AI-ADMIN-002: the AI assistant's form under its tile on the phone.
import userEvent from '@testing-library/user-event';
import type { AiAdminSettings } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '../../../../tests/helpers/render';
import { useAssistantStore } from '../../../store/assistantStore';
const repo = vi.hoisted(() => ({
status: vi.fn(),
adminSettings: vi.fn(),
saveAdminSettings: vi.fn(),
adminConnection: vi.fn(),
saveAdminConnection: vi.fn(),
removeAdminConnection: vi.fn(),
adminModels: vi.fn(),
}));
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
const { default: MAdminAiConfig } = await import('./MAdminAiConfig');
const SETTINGS: AiAdminSettings = { policy: 'instance', dailyTurns: 25, retention: { mode: 'days', days: 30 } };
beforeEach(() => {
vi.clearAllMocks();
useAssistantStore.setState({ status: null });
repo.status.mockRejectedValue(new Error('not needed'));
repo.adminSettings.mockResolvedValue(SETTINGS);
repo.saveAdminSettings.mockImplementation(async (next: AiAdminSettings) => next);
repo.adminConnection.mockResolvedValue({
connection: {
scope: 'instance',
kind: 'gemini',
model: 'gemini-flash',
hint: '…77aa',
status: 'ok',
host: 'generativelanguage.googleapis.com',
baseUrl: null,
},
prefill: null,
});
repo.adminModels.mockResolvedValue([
{ id: 'gemini-flash', label: 'Gemini Flash', supportsTools: true },
{ id: 'gemini-pro', label: 'Gemini Pro', supportsTools: true },
]);
});
describe('MAdminAiConfig', () => {
it('FE-MOB-AI-ADMIN-001: shows the policy, the live connection with its models, the limit and the retention', async () => {
render(<MAdminAiConfig />);
expect(await screen.findByRole('radio', { name: 'I pay for everyone' })).toHaveAttribute('aria-checked', 'true');
expect(screen.getByText('Gemini')).toBeInTheDocument();
await waitFor(() => expect(screen.getByRole('option', { name: 'Gemini Pro' })).toBeInTheDocument());
expect(screen.getByDisplayValue('25')).toBeInTheDocument();
expect(screen.getByRole('combobox', { name: 'Keep chats' })).toHaveValue('30');
});
it('FE-MOB-AI-ADMIN-002: a retention picked from the list is saved at once', async () => {
const user = userEvent.setup();
render(<MAdminAiConfig />);
await user.selectOptions(await screen.findByRole('combobox', { name: 'Keep chats' }), 'forever');
await waitFor(() =>
expect(repo.saveAdminSettings).toHaveBeenCalledWith({ ...SETTINGS, retention: { mode: 'forever' } })
);
});
});
@@ -0,0 +1,174 @@
import { Check, Loader2 } from 'lucide-react';
import React from 'react';
import { POLICY_CHOICES, useAiAdminConfig } from '../../../components/Admin/addons/useAiAdminConfig';
import AiConnectPanel from '../../../components/Settings/ai/AiConnectPanel';
import { CONNECTION_STATUS } from '../../../components/Settings/ai/aiConnectModel';
import { StatusPill } from '../../../components/Settings/settingsKit';
import { NumericInput } from '../../../components/shared/NumericInput';
import { useTranslation } from '../../../i18n';
import MConfirmSheet from '../settings/MConfirmSheet';
import { MAdminButton, MAdminField, MAdminRow } from './MAdminUi';
type AiAdmin = ReturnType<typeof useAiAdminConfig>;
const SELECT =
'h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-body text-m-ink outline-none';
/** Who pays, as stacked rows like the AI parsing provider list. */
function MPolicyChoice({ A }: { A: AiAdmin }) {
const { t } = useTranslation();
return (
<MAdminField label={t('assistant.admin.policy')} hint={A.policyHintKey ? t(A.policyHintKey) : undefined}>
<div role="radiogroup" aria-label={t('assistant.admin.policy')} className="space-y-[6px]">
{POLICY_CHOICES.map((choice) => {
const on = A.policy === choice.value;
return (
<button
key={choice.value}
type="button"
role="radio"
aria-checked={on}
onClick={() => A.setPolicy(choice.value)}
className={`flex w-full items-center gap-2 rounded-xl border px-3 py-[10px] text-start ${on ? 'border-[color:var(--m-act)] bg-[color:var(--m-ic)]' : 'border-[color:var(--m-rowbr)]'}`}
>
<span className="min-w-0 flex-1 truncate text-body font-semibold text-m-ink">{t(choice.labelKey)}</span>
{on && <Check size={15} strokeWidth={2.4} className="flex-none text-m-ink" />}
</button>
);
})}
</div>
</MAdminField>
);
}
/** The connection everyone runs on: the live one with its model, or the panel to set one up. */
function MInstanceConnection({ A }: { A: AiAdmin }) {
const { t } = useTranslation();
const {
live,
connection,
provider,
models,
busy,
setModel,
replacing,
replace,
cancelReplace,
askRemove,
onConnected,
} = A.instance;
return (
<MAdminField label={t('assistant.admin.connection')}>
{live && !replacing && (
<>
<MAdminRow
first
title={provider}
hint={live.hint ?? live.host}
trailing={
<StatusPill tone={CONNECTION_STATUS[live.status].tone}>
{t(CONNECTION_STATUS[live.status].labelKey)}
</StatusPill>
}
/>
{live.status === 'ok' && (
<select
aria-label={t('assistant.connect.model')}
className={SELECT}
value={live.model}
disabled={busy}
onChange={(e) => setModel(e.target.value)}
>
{models.map((m) => (
<option key={m.value} value={m.value}>
{m.label}
</option>
))}
</select>
)}
<div className="mt-3 flex flex-wrap gap-2">
<MAdminButton variant="ghost" disabled={busy} onClick={replace}>
{t('common.change')}
</MAdminButton>
<MAdminButton variant="danger" disabled={busy} onClick={askRemove}>
{t('assistant.admin.connectionRemove')}
</MAdminButton>
</div>
</>
)}
{A.showPanel && (
<div className="space-y-3">
{!live && <p className="font-geist text-caption text-m-faint">{t('assistant.admin.connectionNone')}</p>}
<AiConnectPanel scope="instance" onConnected={onConnected} prefill={connection?.prefill ?? null} />
{replacing && (
<MAdminButton variant="ghost" onClick={cancelReplace}>
{t('common.cancel')}
</MAdminButton>
)}
</div>
)}
</MAdminField>
);
}
/**
* Phone twin of components/Admin/addons/AiAdminConfig, on the same
* useAiAdminConfig hook, in the AI parsing form's layout under its tile.
*/
export default function MAdminAiConfig(): React.ReactElement {
const { t } = useTranslation();
const A = useAiAdminConfig();
if (!A.loaded) {
return (
<div className="grid place-items-center py-4 ps-[50px]">
<Loader2 size={18} className="animate-spin text-m-faint" />
</div>
);
}
return (
<div className="space-y-5 ps-[50px]">
<MPolicyChoice A={A} />
{A.instancePays && <MInstanceConnection A={A} />}
{A.instancePays && (
<MAdminField label={t('assistant.admin.dailyLimit')} hint={t('assistant.admin.dailyLimitHint')}>
<NumericInput
mode="integer"
aria-label={t('assistant.admin.dailyLimit')}
className={`${SELECT} tabular-nums`}
value={A.dailyDraft}
onValueChange={A.setDailyDraft}
onBlur={A.commitDailyLimit}
/>
</MAdminField>
)}
<MAdminField label={t('assistant.admin.retention')}>
<select
aria-label={t('assistant.admin.retention')}
className={SELECT}
value={A.retention}
onChange={(e) => A.setRetention(e.target.value)}
>
{A.retentionOptions.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
</MAdminField>
<MConfirmSheet
open={A.instance.confirmingRemove}
onClose={A.instance.cancelRemove}
title={t('assistant.admin.connectionRemove')}
message={t('assistant.connect.disconnectConfirm', { provider: A.instance.provider })}
confirmLabel={t('assistant.admin.connectionRemove')}
cancelLabel={t('common.cancel')}
danger
busy={A.instance.busy}
onConfirm={A.instance.remove}
/>
</div>
);
}
@@ -0,0 +1,86 @@
// FE-MOB-AI-CONNECTION-001 to FE-MOB-AI-CONNECTION-003: the phone's AI assistant card.
import userEvent from '@testing-library/user-event';
import type { AiConnectionView, AiStatusResponse } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '../../../../tests/helpers/render';
import { useAssistantStore } from '../../../store/assistantStore';
const repo = vi.hoisted(() => ({
status: vi.fn(),
models: vi.fn(),
setModel: vi.fn(),
disconnect: vi.fn(),
chatgptSignOut: vi.fn(),
}));
vi.mock('../../../repo/aiConnectionsRepo', () => ({ aiConnectionsRepo: repo }));
const { default: MAiConnectionSection } = await import('./MAiConnectionSection');
const OWN: AiConnectionView = {
scope: 'user',
kind: 'gemini',
model: 'gemini-flash',
hint: '…77aa',
status: 'ok',
host: 'generativelanguage.googleapis.com',
};
function status(over: Partial<AiStatusResponse> = {}): AiStatusResponse {
return {
available: true,
policy: 'instance_or_user',
canConnectOwn: true,
effective: null,
own: null,
instance: null,
quota: null,
privacyAcked: true,
retention: { mode: 'forever' },
openrouterOAuth: false,
...over,
};
}
beforeEach(() => {
vi.clearAllMocks();
useAssistantStore.setState({ status: null });
repo.models.mockResolvedValue([
{ id: 'gemini-flash', label: 'Gemini Flash', supportsTools: true, free: true },
{ id: 'gemini-pro', label: 'Gemini Pro', supportsTools: true },
]);
repo.setModel.mockResolvedValue({ ...OWN, model: 'gemini-pro' });
});
describe('MAiConnectionSection', () => {
it('FE-MOB-AI-CONNECTION-001: an own connection shows its model and picks another from a sheet', async () => {
const user = userEvent.setup();
repo.status.mockResolvedValue(status({ own: OWN }));
render(<MAiConnectionSection />);
expect(await screen.findByText('Connected to Gemini')).toBeInTheDocument();
expect(screen.getByText('Chats are kept until you delete them.')).toBeInTheDocument();
await waitFor(() => expect(repo.models).toHaveBeenCalledTimes(1));
await user.click(screen.getByRole('button', { name: 'gemini-flash' }));
await user.click(await screen.findByText('Gemini Pro'));
await waitFor(() => expect(repo.setModel).toHaveBeenCalledWith('gemini-pro'));
});
it('FE-MOB-AI-CONNECTION-002: the admin connection shows with today’s share', async () => {
repo.status.mockResolvedValue(
status({
instance: { kind: 'anthropic', model: 'claude-haiku', host: 'api.anthropic.com' },
quota: { used: 1, limit: 1 },
})
);
render(<MAiConnectionSection />);
expect(await screen.findByText('Provided by your admin')).toBeInTheDocument();
expect(screen.getByText('Anthropic, claude-haiku')).toBeInTheDocument();
expect(screen.getByText('1 of 1 message used today')).toBeInTheDocument();
});
it('FE-MOB-AI-CONNECTION-003: nothing connected shows the shared setup', async () => {
repo.status.mockResolvedValue(status({ available: false }));
render(<MAiConnectionSection />);
expect(await screen.findByText('What would you like to chat with?')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Paste an API key/ })).toBeInTheDocument();
});
});
@@ -0,0 +1,204 @@
import type { AiConnectionView } from '@trek/shared';
import { ChevronDown, Loader2, LogOut, MessageCircle, Sparkles, Unplug } from 'lucide-react';
import React, { useState } from 'react';
import AiConnectPanel from '../../../components/Settings/ai/AiConnectPanel';
import { CONNECTION_STATUS } from '../../../components/Settings/ai/aiConnectModel';
import { useAiConnections } from '../../../components/Settings/ai/useAiConnections';
import { useAssistantMapFollow } from '../../../components/Assistant/useAssistantMapFollow';
import { StatusPill } from '../../../components/Settings/settingsKit';
import { useTranslation } from '../../../i18n';
import MToggle from '../../components/MToggle';
import MConfirmSheet from './MConfirmSheet';
import MSetPickerSheet from './MSetPickerSheet';
import { MSetButton, MSetCard, MSetEyebrow, MSetHint, MSetRow, MSetSelectRow } from './MSettingsUi';
type AiConnections = ReturnType<typeof useAiConnections>;
/** The phone's own connection: who answers, which model, and the way out or back in. */
function MOwnConnection({ S, own }: { S: AiConnections; own: AiConnectionView }) {
const { t } = useTranslation();
const [modelOpen, setModelOpen] = useState(false);
const { provider, models, busy, setModel, signOut, askDisconnect } = S.ownActions;
const repairMode = S.repairMode;
const status = CONNECTION_STATUS[own.status];
return (
<>
<MSetRow
first
label={t('assistant.connect.connected', { provider })}
sub={own.hint ?? undefined}
trailing={<StatusPill tone={status.tone}>{t(status.labelKey)}</StatusPill>}
/>
{own.status === 'needs_reauth' && (
<MSetHint className="text-[color:var(--m-st-danger)]">
{t('assistant.error.needsReauth', { provider })}
</MSetHint>
)}
{own.status === 'error' && (
<MSetHint className="text-[color:var(--m-st-danger)]">{t('assistant.error.invalidKey', { provider })}</MSetHint>
)}
{own.status === 'ok' && (
<>
<MSetEyebrow className="mb-[5px] mt-3">{t('assistant.connect.model')}</MSetEyebrow>
<MSetSelectRow
label={own.model}
trailing={
busy ? (
<Loader2 size={13} className="flex-none animate-spin text-m-faint" />
) : (
<ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
)
}
onClick={() => setModelOpen(true)}
/>
<MSetHint>{t('assistant.connect.modelHint')}</MSetHint>
</>
)}
<div className="mt-3 flex flex-wrap gap-2">
{repairMode ? (
<MSetButton onClick={() => S.repair(repairMode)}>
{t(repairMode === 'chatgpt' ? 'assistant.errorAction.signIn' : 'assistant.errorAction.replaceKey')}
</MSetButton>
) : (
S.canOpen && (
<MSetButton onClick={S.openAssistant}>
<MessageCircle size={14} /> {t('assistant.connect.openAssistant')}
</MSetButton>
)
)}
{own.kind === 'chatgpt' && own.status === 'ok' ? (
<MSetButton variant="ghost" disabled={busy} onClick={() => void signOut()}>
<LogOut size={14} /> {t('assistant.connect.signOut')}
</MSetButton>
) : (
<MSetButton variant="danger" disabled={busy} onClick={askDisconnect}>
<Unplug size={14} /> {t('assistant.connect.disconnect')}
</MSetButton>
)}
</div>
<MSetPickerSheet
open={modelOpen}
onClose={() => setModelOpen(false)}
title={t('assistant.connect.model')}
value={own.model}
onSelect={(v) => void setModel(v)}
options={models.map((m) => ({ value: m.value, label: m.label }))}
/>
</>
);
}
/** The admin's connection the phone runs on, with today's share while the instance pays. */
function MInstanceConnection({ S }: { S: AiConnections }) {
const { t } = useTranslation();
const instance = S.status?.instance;
if (!instance) return null;
return (
<>
<MSetRow first label={t('assistant.connect.providedByAdmin')} sub={`${S.instanceProvider}, ${instance.model}`} />
{S.quota && <MSetHint>{t('assistant.connect.quota', { used: S.quota.used, count: S.quota.limit })}</MSetHint>}
<div className="mt-3 flex flex-wrap gap-2">
{S.canOpen && (
<MSetButton onClick={S.openAssistant}>
<MessageCircle size={14} /> {t('assistant.connect.openAssistant')}
</MSetButton>
)}
{S.status?.canConnectOwn && !S.panel && (
<MSetButton variant="ghost" onClick={S.connectOwn}>
{t('assistant.errorAction.connectOwn')}
</MSetButton>
)}
</div>
</>
);
}
/** Whether the trip map follows the assistant, the phone's row for the shared switch. */
function MAssistantBehaviour() {
const { t } = useTranslation();
const follow = useAssistantMapFollow();
return (
<div className="mt-3 border-t border-[color:var(--m-rowbr)]">
<MSetRow
label={t('assistant.settings.followMap')}
sub={t('assistant.settings.followMapHint')}
trailing={
<MToggle
checked={follow.on}
onChange={(on) => void follow.set(on)}
ariaLabel={t('assistant.settings.followMap')}
/>
}
/>
</div>
);
}
/**
* Phone twin of components/Settings/ai/AiConnectionSection, on the same
* useAiConnections hook. The connect panel itself is the shared one: it is
* already a single column at phone width, and a second copy of the key and
* sign-in steps would only drift.
*/
export default function MAiConnectionSection(): React.ReactElement | null {
const { t } = useTranslation();
const S = useAiConnections({ phone: true });
if (S.view === 'hidden') return null;
return (
<MSetCard title={t('assistant.connect.title')} icon={Sparkles} className="mt-3">
<MSetHint className="mb-3">{t('assistant.connect.description')}</MSetHint>
{S.view === 'loading' && (
<div className="grid place-items-center py-4">
<Loader2 size={18} className="animate-spin text-m-faint" />
</div>
)}
{S.view === 'own' && S.own && <MOwnConnection S={S} own={S.own} />}
{S.view === 'instance' && <MInstanceConnection S={S} />}
{(S.view === 'own' || S.view === 'instance') && <MAssistantBehaviour />}
{S.view === 'adminOnly' && <MSetHint>{t('assistant.setup.adminOnly')}</MSetHint>}
{S.panel && (
<div
className={`flex flex-col gap-3 ${S.view === 'setup' ? '' : 'mt-3 border-t border-[color:var(--m-rowbr)] pt-3'}`}
>
<AiConnectPanel
key={S.panelMode ?? 'any'}
scope="user"
onConnected={S.onConnected}
initialMode={S.panelMode}
/>
{S.view !== 'setup' && (
<MSetButton variant="ghost" className="self-start" onClick={S.closePanel}>
{t('common.cancel')}
</MSetButton>
)}
</div>
)}
{S.view !== 'setup' && S.retentionText && <MSetHint className="mt-3">{S.retentionText}</MSetHint>}
{S.isAdmin && (
<MSetButton variant="ghost" className="mt-3" onClick={S.openAdmin}>
{t('assistant.setup.forEveryone')}
</MSetButton>
)}
<MConfirmSheet
open={S.ownActions.confirmingDisconnect}
onClose={S.ownActions.cancelDisconnect}
title={t('assistant.connect.disconnect')}
message={t('assistant.connect.disconnectConfirm', { provider: S.ownActions.provider })}
confirmLabel={t('assistant.connect.disconnect')}
cancelLabel={t('common.cancel')}
danger
busy={S.ownActions.busy}
onConfirm={() => void S.ownActions.disconnect()}
/>
</MSetCard>
);
}
@@ -1,9 +1,15 @@
import { Check, Copy, ExternalLink, MessagesSquare } from 'lucide-react'
import { useTranslation } from '../../../i18n'
import MPhotoProvidersSection from './MPhotoProvidersSection'
import MAirTrailConnectionSection from './MAirTrailConnectionSection'
import MDawarichConnectionSection from './MDawarichConnectionSection'
import MLlmConnectionSection from './MLlmConnectionSection'
import MAiConnectionSection from './MAiConnectionSection'
import MSettingsMcp from './MSettingsMcp'
import { MSetButton, MSetCard, MSetHint } from './MSettingsUi'
import { useIntegrationGates } from '../../../components/Settings/useIntegrationGates'
import { useClaudeConnector } from '../../../components/Settings/ai/useClaudeConnector'
import { CLAUDE_CONNECTOR_ANCHOR } from '../../../components/Settings/ai/aiConnectModel'
/**
* "Integrations" section. The photo-provider / AirTrail / LLM connection forms
@@ -12,7 +18,7 @@ import { useIntegrationGates } from '../../../components/Settings/useIntegration
* function audit is rebuilt natively in the mobile design language.
*/
export default function MSettingsIntegrations() {
const { mcpEnabled, airtrailEnabled, llmEnabled, dawarichEnabled, managed } = useIntegrationGates({ reloadAddons: true })
const { mcpEnabled, airtrailEnabled, llmEnabled, aiAssistantEnabled, dawarichEnabled, managed } = useIntegrationGates({ reloadAddons: true })
return (
<>
@@ -22,11 +28,40 @@ export default function MSettingsIntegrations() {
{!managed && <MPhotoProvidersSection />}
{airtrailEnabled && !managed && <MAirTrailConnectionSection />}
{dawarichEnabled && !managed && <MDawarichConnectionSection />}
{aiAssistantEnabled && !managed && <MAiConnectionSection />}
{/* 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. */}
{llmEnabled && !managed && <MLlmConnectionSection />}
{mcpEnabled && <MClaudeConnectorCard />}
{mcpEnabled && <MSettingsMcp />}
</>
)
}
/**
* "Connect with Claude" on the phone: the button and the address only. The QR
* code is for reaching a phone from a desktop, and this is the phone.
*/
function MClaudeConnectorCard() {
const { t } = useTranslation()
const { connector, reachable, copied, copyUrl } = useClaudeConnector()
return (
<div id={CLAUDE_CONNECTOR_ANCHOR}>
<MSetCard title={t('assistant.claude.title')} icon={MessagesSquare} className="mt-3">
<MSetHint className="mb-3">{t('assistant.claude.description')}</MSetHint>
{connector && !reachable && <MSetHint>{t('assistant.claude.notPublic')}</MSetHint>}
{connector && reachable && (
<div className="flex flex-wrap gap-2">
<MSetButton onClick={() => window.open(connector.deepLink, '_blank', 'noopener,noreferrer')}>
<ExternalLink size={14} /> {t('assistant.claude.open')}
</MSetButton>
<MSetButton variant="ghost" onClick={() => void copyUrl()}>
{copied ? <Check size={14} /> : <Copy size={14} />} {copied ? t('common.copied') : t('assistant.claude.copyUrl')}
</MSetButton>
</div>
)}
</MSetCard>
</div>
)
}
@@ -0,0 +1,336 @@
import type { AssistantApplied } from '@trek/shared';
import {
ChevronLeft,
Ellipsis,
History,
Lightbulb,
LightbulbOff,
Plus,
Settings,
Sparkles,
Trash2,
} from 'lucide-react';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import AssistantCompareSwitch from '../../../../components/Assistant/AssistantCompareSwitch';
import AssistantSurfaceLazy from '../../../../components/Assistant/AssistantSurfaceLazy';
import { AI_SETTINGS_PATH } from '../../../../components/Assistant/assistantParts';
import { showOnMapTarget } from '../../../../components/Assistant/assistantShowOnMap';
import { useAssistantHintsSetting } from '../../../../components/Assistant/useAssistantHints';
import { useAssistantLiveStep } from '../../../../components/Assistant/useAssistantLiveStep';
import { useAssistantThread } from '../../../../components/Assistant/useAssistantThread';
import { useKeyboardInset } from '../../../../hooks/useKeyboardInset';
import { useTranslation } from '../../../../i18n';
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
import MDropdownPanel from '../../../components/MDropdownPanel';
import MIconBtn from '../../../components/MIconBtn';
import MListRow from '../../../components/MListRow';
import MConfirmSheet from '../../settings/MConfirmSheet';
import type { MTripSheetsProps } from '../MTripShell';
const HISTORY_MARK = 'trekAssistant';
const ownEntryOnTop = () => (window.history.state as Record<string, unknown> | null)?.[HISTORY_MARK] === true;
/**
* The phone's back gesture closes the screen instead of leaving the trip: an
* entry of our own goes onto the history while it is open, and going back
* pops it. Closed from inside, the entry is taken back off, unless a
* navigation has already put another one on top. The step back waits a
* tick, so an effect that only re-runs (React's development double run)
* keeps its entry instead of losing it.
*/
function useBackCloses(open: boolean, onClose: () => void): void {
const onCloseRef = useRef(onClose);
const openRef = useRef(false);
useLayoutEffect(() => {
onCloseRef.current = onClose;
});
useEffect(() => {
if (!open) return;
openRef.current = true;
if (!ownEntryOnTop()) {
window.history.pushState({ ...(window.history.state as object | null), [HISTORY_MARK]: true }, '');
}
const onPop = () => {
if (!ownEntryOnTop()) onCloseRef.current();
};
window.addEventListener('popstate', onPop);
return () => {
openRef.current = false;
window.removeEventListener('popstate', onPop);
setTimeout(() => {
if (!openRef.current && ownEntryOnTop()) window.history.back();
}, 0);
};
}, [open]);
}
/** The ways the chat hands the screen to the map. */
interface MapHops {
/** "Show on map" on an applied change: the change is selected there. */
showOnMap: (applied: AssistantApplied) => void;
/** A day picked in the chat (its weather): the day is selected. */
focusDay: (dayId: number) => void;
/** Before the map moves to something the chat points at, such as a found place. */
revealMap: () => void;
}
/**
* Whatever the chat shows on the map, the chat steps aside to a pill and the
* map comes up on the plan tab, then the change or the day is selected there.
* Read through a ref, so the chat does not re-render with every render of the
* trip screen.
*/
function useMapHops({ planner, shell }: MTripSheetsProps): MapHops {
const setMinimized = useAssistantStore((s) => s.setMinimized);
const reveal = () => {
setMinimized(true);
if (shell.trTab !== 'plan') shell.setTrTab('plan');
if (shell.view !== 'map') shell.toggleView();
};
const show = (applied: AssistantApplied) => {
const { placeId, dayId } = showOnMapTarget(applied);
reveal();
if (dayId !== null) planner.handleSelectDay(dayId, false);
if (placeId !== null) planner.setSelectedPlaceId(placeId);
};
const focus = (dayId: number) => {
reveal();
planner.handleSelectDay(dayId, false);
};
const latest = useRef({ reveal, show, focus });
useLayoutEffect(() => {
latest.current = { reveal, show, focus };
});
const showOnMap = useCallback((applied: AssistantApplied) => latest.current.show(applied), []);
const focusDay = useCallback((dayId: number) => latest.current.focus(dayId), []);
const revealMap = useCallback(() => latest.current.reveal(), []);
return useMemo(() => ({ showOnMap, focusDay, revealMap }), [showOnMap, focusDay, revealMap]);
}
interface ScreenProps {
tripId: number;
tripTitle: string;
hidden: boolean;
hops: MapHops;
}
function AssistantScreen({ tripId, tripTitle, hidden, hops }: ScreenProps) {
const { t, locale } = useTranslation();
const navigate = useNavigate();
const thread = useAssistantThread(tripId);
const close = useAssistantStore((s) => s.close);
const keyboard = useKeyboardInset();
const [panel, setPanel] = useState<'history' | 'menu' | null>(null);
const [confirming, setConfirming] = useState(false);
const hints = useAssistantHintsSetting();
useBackCloses(!hidden, close);
const pick = (run: () => void) => {
setPanel(null);
run();
};
const openHistory = () => {
thread.refreshThreads();
setPanel('history');
};
const threads = thread.threads ?? [];
return (
<section
role="dialog"
aria-modal="true"
aria-label={t('assistant.window.title')}
hidden={hidden}
className={`fixed inset-0 z-[var(--z-bar)] ${hidden ? 'hidden' : 'flex'} flex-col bg-[var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink`}
style={{ paddingBottom: `max(env(safe-area-inset-bottom, 0px), ${keyboard}px)` }}
>
<header className="flex flex-none items-center gap-2 px-4 pb-2 pt-[var(--m-safe-top,12px)]">
<MIconBtn ariaLabel={t('common.back')} onClick={close}>
<ChevronLeft size={19} strokeWidth={2.2} />
</MIconBtn>
<div className="min-w-0 flex-1">
<h2 className="m-0 truncate text-body font-semibold">
<bdi>{thread.title ?? tripTitle}</bdi>
</h2>
{thread.title && (
<div className="truncate text-caption text-m-muted">
<bdi>{tripTitle}</bdi>
</div>
)}
</div>
<MIconBtn ariaLabel={t('assistant.history.open')} onClick={openHistory}>
<History size={16} strokeWidth={2} />
</MIconBtn>
<MIconBtn
ariaLabel={t('assistant.history.new')}
onClick={thread.newThread}
disabled={thread.threadId === null && !thread.isRunning}
>
<Plus size={17} strokeWidth={2.2} />
</MIconBtn>
<MIconBtn ariaLabel={t('assistant.window.menu')} onClick={() => setPanel('menu')}>
<Ellipsis size={17} strokeWidth={2.2} />
</MIconBtn>
</header>
<MDropdownPanel
open={panel === 'history'}
onClose={() => setPanel(null)}
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)] max-h-[60vh] overflow-y-auto"
>
<MListRow icon={Plus} label={t('assistant.history.new')} onClick={() => pick(thread.newThread)} />
{threads.length === 0 ? (
<p className="m-0 px-[10px] py-2 text-caption text-m-muted">{t('assistant.history.empty')}</p>
) : (
threads.map((th) => (
<MListRow
key={th.id}
label={th.title}
className={th.id === thread.threadId ? 'bg-[color:var(--m-ic)]' : ''}
onClick={() => pick(() => thread.openThread(th.id))}
trailing={
<span className="flex-none text-caption text-m-muted">
{new Date(th.lastMessageAt).toLocaleDateString(locale, { day: 'numeric', month: 'short' })}
</span>
}
/>
))
)}
{thread.retentionNote && (
<p className="m-0 px-[10px] pb-1 pt-2 text-caption text-m-muted">{thread.retentionNote}</p>
)}
</MDropdownPanel>
<MDropdownPanel
open={panel === 'menu'}
onClose={() => setPanel(null)}
className="end-4 top-[calc(var(--m-safe-top,12px)+48px)]"
>
<MListRow
icon={hints.on ? LightbulbOff : Lightbulb}
label={t(hints.on ? 'assistant.hint.menuOff' : 'assistant.hint.menuOn')}
onClick={() => pick(hints.toggle)}
/>
<MListRow
icon={Settings}
label={t('assistant.window.settings')}
onClick={() =>
pick(() => {
close();
void navigate(AI_SETTINGS_PATH);
})
}
/>
{thread.threadId !== null && !thread.isRunning && (
<MListRow
icon={Trash2}
danger
label={t('assistant.window.deleteThread')}
onClick={() => pick(() => setConfirming(true))}
/>
)}
</MDropdownPanel>
<div className="flex min-h-0 flex-1 flex-col">
<AssistantSurfaceLazy
tripId={tripId}
tripTitle={tripTitle}
variant="fullscreen"
onShowOnMap={hops.showOnMap}
onFocusDay={hops.focusDay}
onRevealMap={hops.revealMap}
/>
</div>
<MConfirmSheet
open={confirming}
onClose={() => setConfirming(false)}
title={t('assistant.window.deleteThread')}
message={t('assistant.window.deleteConfirm')}
confirmLabel={t('common.delete')}
cancelLabel={t('common.cancel')}
danger
onConfirm={() => {
setConfirming(false);
void thread.removeThread();
}}
/>
</section>
);
}
/**
* While the chat stands aside for the map, the way back to it, above the
* dock. While a step looks somewhere it says where ("Searching near
* Trastevere"), so the map moving there has its reason in view. While a block
* of changes can be compared, its before/after switch sits beside it, so the
* plan can be flipped where it shows.
*/
function BackToChat({ tripId, running }: { tripId: number; running: boolean }) {
const { t } = useTranslation();
const setMinimized = useAssistantStore((s) => s.setMinimized);
const comparing = useAssistantStore((s) => chatOf(s, tripId).compare !== null);
const live = useAssistantLiveStep(tripId);
const glass =
'rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] shadow-elevated backdrop-blur-[30px] backdrop-saturate-[1.8]';
return (
<div className="absolute inset-x-0 bottom-[calc(env(safe-area-inset-bottom,0px)+86px)] z-[42] mx-auto flex w-fit max-w-[calc(100%-2rem)] items-center gap-2">
<button
type="button"
onClick={() => setMinimized(false)}
aria-label={t('assistant.mobile.backToChat')}
className={`flex h-11 min-w-0 items-center gap-2 pe-4 ps-3 text-m-ink ${glass}`}
>
<Sparkles size={15} strokeWidth={2} aria-hidden="true" className="flex-none text-m-muted" />
<span className={`truncate text-body font-semibold ${running ? 'trek-assistant-shimmer' : ''}`}>
{live?.text ?? t('assistant.mobile.backToChat')}
</span>
</button>
{comparing && (
<div className={`flex h-11 flex-none items-center px-1 ${glass}`}>
<AssistantCompareSwitch tripId={tripId} tall />
</div>
)}
</div>
);
}
/**
* The assistant on the phone: a full-screen chat over the trip, opened from
* the Mehr sheet's tile or "Ask" on a place. It stays mounted while "Show on
* map" hands the screen to the map, so an answer being written goes on and
* the pill above the dock brings the chat back as it was. The keyboard lifts
* the composer, and the back gesture closes the chat rather than the trip.
*
* Nothing shows until the assistant has a connection this user can use.
*/
export default function MAssistantScreen({ planner, shell }: MTripSheetsProps) {
const available = useAssistantStore((s) => s.status?.available === true);
const open = useAssistantStore((s) => s.window.open);
const minimized = useAssistantStore((s) => s.window.minimized);
const running = useAssistantStore((s) => s.byTrip[planner.tripId]?.isRunning === true);
const loadStatus = useAssistantStore((s) => s.loadStatus);
const hops = useMapHops({ planner, shell });
// The desktop window loads this itself; on the phone the trip screen asks once.
useEffect(() => {
void loadStatus();
}, [loadStatus]);
if (!available || !open || !planner.trip) return null;
return (
<>
<AssistantScreen
tripId={planner.tripId}
tripTitle={planner.trip.title}
hidden={minimized}
hops={hops}
/>
{minimized && <BackToChat tripId={planner.tripId} running={running} />}
</>
);
}
@@ -425,6 +425,11 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) {
// and the leave would put out the road the tap has just lit.
onChooseAlternative={onStage ? planner.setHighlightedAlternative : undefined}
fitPadding={fitPadding}
// The assistant's suggestions on the plan map. A tap marks one, as a hover does on
// the desk; the hover itself stays off, since the emulated leave after a tap would
// take the mark straight off again.
{...(onStage ? {} : planner.assistantMap)}
onAssistantGhostHover={undefined}
/>
{/* Floating map chrome — only while the map view is front-most. The POI bar
@@ -1,9 +1,11 @@
import { ChevronRight, FileDown, Settings, Settings2 } from 'lucide-react'
import { ChevronRight, FileDown, Settings, Settings2, Sparkles } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import type { MTripSheetsProps } from '../MTripShell'
import { dockTabIds } from '../dockTabs'
import { useTranslation } from '../../../../i18n'
import { useAssistantAsk } from '../../../../components/Assistant/useAssistantAsk'
import { useAssistantHints } from '../../../../components/Assistant/useAssistantHints'
/** Demo tile tints per legacy tab id; plugins share the files neutral. */
const TILE_COLORS: Record<string, string> = {
@@ -26,6 +28,9 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
const { t } = useTranslation()
const open = shell.sheet?.id === 'mehr'
const canEditTrip = planner.can('trip_edit', planner.trip)
const assistant = useAssistantAsk(planner.tripId)
// Warnings not shown yet turn the tile's line into a count; the dock gets no dot.
const hints = useAssistantHints(planner.tripId, { withStays: false })
// Derived from the same priority list the dock seats itself from, so a section
// can never show up in both places at once.
@@ -59,6 +64,31 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
return (
<MSheet open={open} onClose={shell.closeSheet} variant="bottom" dimTransparent ariaLabel={t('mobileTrip.more')}>
<div className="overflow-y-auto p-[10px]">
{/* The assistant leads the sheet: the one way into it on the phone besides "Ask" on a place. */}
{assistant.available && (
<button
type="button"
onClick={() => {
shell.closeSheet()
hints.markWarnsSeen()
assistant.open()
}}
className="mb-2 flex w-full items-center gap-[13px] rounded-[18px] bg-[color:var(--m-ic)] px-4 py-[14px] text-start"
>
<div className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-[11px] bg-m-act text-m-actfg">
<Sparkles size={19} strokeWidth={1.9} />
</div>
<div className="min-w-0 flex-1">
<div className="truncate text-body font-bold">{t('assistant.mobile.tile')}</div>
<div className="truncate text-caption text-m-muted">
{hints.unseenWarn > 0
? t('assistant.mobile.tileHints', { count: hints.unseenWarn })
: t('assistant.mobile.tileHint')}
</div>
</div>
<ChevronRight size={16} strokeWidth={2} className="flex-none text-m-faint" />
</button>
)}
{gridTabs.length > 0 && (
<div className="grid grid-cols-2 gap-2">
{gridTabs.map(tab => {
@@ -1,6 +1,8 @@
import { render, screen } from '../../../../../tests/helpers/render'
import { fireEvent, render, screen } from '../../../../../tests/helpers/render'
import type { AiStatusResponse } from '@trek/shared'
import { chatOf, useAssistantStore } from '../../../../store/assistantStore'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { buildPlace } from '../../../../../tests/helpers/factories'
import type { TripPlanner, MTripShellApi } from '../MTripShell'
import MPlaceSheet from './MPlaceSheet'
@@ -100,3 +102,23 @@ describe('MPlaceSheet tour exclusion', () => {
expect(screen.queryByRole('button', { name: 'inspector.addToDay' })).not.toBeInTheDocument()
})
})
describe('MPlaceSheet ask the assistant', () => {
const initial = useAssistantStore.getState()
afterEach(() => useAssistantStore.setState(initial, true))
it('offers no ask until the assistant has a connection to use', () => {
render(<MPlaceSheet planner={planner({ tripId: 5, setSelectedPlaceId: vi.fn() })} shell={shell} />)
expect(screen.queryByRole('button', { name: 'Ask' })).not.toBeInTheDocument()
})
it('closes the sheet and opens the chat about the place', () => {
useAssistantStore.setState({ status: { available: true } as AiStatusResponse })
const setSelectedPlaceId = vi.fn()
render(<MPlaceSheet planner={planner({ tripId: 5, setSelectedPlaceId })} shell={shell} />)
fireEvent.click(screen.getByRole('button', { name: 'Ask' }))
expect(setSelectedPlaceId).toHaveBeenCalledWith(null)
expect(useAssistantStore.getState().window.open).toBe(true)
expect(chatOf(useAssistantStore.getState(), 5).focus).toEqual({ placeIds: [42] })
})
})
@@ -2,7 +2,7 @@ import { useMemo, useRef, useState } from 'react'
import DawarichIcon from '../../../../components/shared/DawarichIcon'
import {
Bookmark, Camera, ChevronRight, ExternalLink, Loader2, Map as MapIcon, Navigation, Paperclip,
Pencil, Phone, Plus, Route, RouteOff, Trash2, Upload, X,
Pencil, Phone, Plus, Route, RouteOff, Sparkles, Trash2, Upload, X,
} from 'lucide-react'
import MSheet from '../../../components/MSheet'
import type { MTripSheetsProps } from '../MTripShell'
@@ -10,6 +10,7 @@ import { useTranslation, translateApiError } from '../../../../i18n'
import { useAddonStore } from '../../../../store/addonStore'
import { useSaveToCollectionStore } from '../../../../store/saveToCollectionStore'
import { placeToSaveTarget } from '../../../../components/Collections/saveTarget'
import { useAssistantAsk } from '../../../../components/Assistant/useAssistantAsk'
import {
participantsWith, participantsWithout, placeActions, splitParticipants, usePlaceFileUpload, usePlaceImagePick,
} from '../../../../components/Planner/usePlaceActions'
@@ -49,6 +50,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
const canManagePlace = canEditPlaces && !isTourPlace
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const openSavePicker = useSaveToCollectionStore(s => s.open)
const assistant = useAssistantAsk(planner.tripId)
const actions = placeActions({ tripId: planner.tripId, tripActions: planner.tripActions, toast: planner.toast, t })
const {
@@ -569,6 +571,11 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
{/* ── Action row ── */}
<div className="mt-[14px] flex items-center gap-[7px]">
{assistant.available && (
<ActionCircle onClick={() => { close(); assistant.askAbout(place.id) }} label={t('assistant.context.ask')}>
<Sparkles size={15} strokeWidth={2} />
</ActionCircle>
)}
{collectionsEnabled && !isTourPlace && (
<ActionCircle onClick={saveToCollection} label={t('inspector.saveToCollection')}>
<Bookmark size={15} strokeWidth={2} />
@@ -26,6 +26,7 @@ import MExportSheet from './MExportSheet'
import MMehrSheet from './MMehrSheet'
import MTripSettingsSheet from './MTripSettingsSheet'
import MNewTripSheet from '../../dashboard/MNewTripSheet'
import MAssistantScreen from '../assistant/MAssistantScreen'
import MPlacesFilterSheet from '../places/MPlacesFilterSheet'
import MRtStopSheet from '../roadtrip/MRtStopSheet'
import MRtStaySheet from '../roadtrip/MRtStaySheet'
@@ -123,6 +124,8 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
<MTransportSheet planner={planner} shell={shell} />
<MBrowseActionsSheet planner={planner} shell={shell} />
<MMehrSheet planner={planner} shell={shell} />
{/* The assistant's full-screen chat, mounted with the trip so it keeps going while the map is up. */}
<MAssistantScreen planner={planner} shell={shell} />
{/* The stage's own sheets. Each one checks shell.sheet?.id itself, the draft
sheet hangs off planner.stopDraft the way the place editor hangs off its flag. */}
<MRtStopSheet planner={planner} shell={shell} />
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { ArrowUp, ChevronUp, ImagePlus, Loader2, Reply, Trash2 } from 'lucide-react'
import MDancingTrek from '../../../components/MDancingTrek'
import CollabAssistantBadge from '../../../../components/Collab/CollabAssistantBadge'
import { useCollabChatData } from '../../../../components/Collab/useCollabChatData'
import { useAuthStore } from '../../../../store/authStore'
import { useTranslation } from '../../../../i18n'
@@ -13,6 +14,7 @@ import {
formatChatClockTime,
formatChatDateSeparator,
isEmojiOnlyText,
isFromAssistant,
isSameSender,
shouldShowChatDateSeparator,
type ChatMessage,
@@ -302,6 +304,11 @@ function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h,
{showHeader && (
<span className="mb-[2px] ps-1 font-geist text-[0.59375rem] font-bold text-m-faint">{msg.username}</span>
)}
{isFromAssistant(msg) && (
<span className="mb-[2px] ps-1">
<CollabAssistantBadge name={msg.username} phone />
</span>
)}
<button
type="button"