fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import posthog from 'posthog-js'
|
||||
import { isAnalyticsEnabled } from '@/lib/analytics/enabled'
|
||||
import {
|
||||
buildPersonProperties,
|
||||
buildGroupProperties,
|
||||
type AnalyticsCompanyInput,
|
||||
type AnalyticsUserInput,
|
||||
} from '@/lib/analytics/properties'
|
||||
|
||||
/**
|
||||
* Attaches the logged-in user and their active company to PostHog.
|
||||
*
|
||||
* Mounted from app/(dashboard)/layout.tsx, which is the only place that has
|
||||
* both the auth user and the resolved company in one render, and gated there
|
||||
* on `!isSandbox` so demo companies never pollute funnels or get surveyed.
|
||||
*
|
||||
* identify() runs on every dashboard load rather than only at login, per
|
||||
* PostHog's guidance: with `persistence: 'memory'` (see
|
||||
* instrumentation-client.ts) nothing survives a hard reload, so re-identifying
|
||||
* on each load is what keeps person-level analytics correct without storing
|
||||
* anything on the device.
|
||||
*
|
||||
* A useEffect is correct here despite the general rule against it: this
|
||||
* synchronises with an external, non-React system (the PostHog SDK).
|
||||
*/
|
||||
export default function AnalyticsIdentify({
|
||||
user,
|
||||
company,
|
||||
identityHash,
|
||||
}: {
|
||||
user: AnalyticsUserInput
|
||||
company: AnalyticsCompanyInput
|
||||
/** Server-computed HMAC of userId (lib/analytics/identity-hash.ts). Null
|
||||
* when POSTHOG_SECRET_API_KEY is unset, which is normal off hosted. */
|
||||
identityHash?: string | null
|
||||
}) {
|
||||
const { userId, email, fullName, role } = user
|
||||
const {
|
||||
id: companyId,
|
||||
name: companyName,
|
||||
entityType,
|
||||
accountingFramework,
|
||||
paysSalaries,
|
||||
trialEndsAt,
|
||||
capabilities,
|
||||
} = company
|
||||
|
||||
// The dashboard layout rebuilds the props objects (and the capabilities
|
||||
// array) on every render, so depending on them directly would re-fire
|
||||
// identify on every navigation. Depend on primitives, and collapse the
|
||||
// array to a stable string key.
|
||||
const capabilityKey = capabilities ? [...capabilities].sort().join(',') : ''
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAnalyticsEnabled()) return
|
||||
|
||||
// Verified identity first: it tells PostHog Support this browser really
|
||||
// is `userId`, so a support ticket follows the person across devices
|
||||
// instead of being scoped to one browser session. Without the secret key
|
||||
// this is skipped and tickets fall back to email recovery.
|
||||
if (identityHash) posthog.setIdentity(userId, identityHash)
|
||||
|
||||
posthog.identify(userId, buildPersonProperties({ userId, email, fullName, role }))
|
||||
posthog.group(
|
||||
'company',
|
||||
companyId,
|
||||
buildGroupProperties({
|
||||
id: companyId,
|
||||
name: companyName,
|
||||
entityType,
|
||||
accountingFramework,
|
||||
paysSalaries,
|
||||
trialEndsAt,
|
||||
capabilities: capabilityKey ? capabilityKey.split(',') : undefined,
|
||||
})
|
||||
)
|
||||
}, [
|
||||
userId,
|
||||
email,
|
||||
fullName,
|
||||
role,
|
||||
companyId,
|
||||
companyName,
|
||||
entityType,
|
||||
accountingFramework,
|
||||
paysSalaries,
|
||||
trialEndsAt,
|
||||
capabilityKey,
|
||||
identityHash,
|
||||
])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
|
||||
// How long after the last scroll event the scrollbar stays visible.
|
||||
const IDLE_MS = 700
|
||||
|
||||
/**
|
||||
* Reveals scrollbars only while their container is actually scrolling.
|
||||
* One capture-phase listener on the document catches scroll events from
|
||||
* every scroll container (panel, sidebar, dialogs, dropdown lists) and
|
||||
* stamps .is-scrolling on the scrolled element; globals.css makes the
|
||||
* thumb visible for that class and transparent otherwise. Renders nothing.
|
||||
*/
|
||||
export function ScrollbarReveal() {
|
||||
useEffect(() => {
|
||||
const timers = new WeakMap<Element, number>()
|
||||
|
||||
const onScroll = (e: Event) => {
|
||||
const target = e.target
|
||||
const el =
|
||||
target === document ? document.documentElement : (target as Element)
|
||||
if (!(el instanceof Element)) return
|
||||
el.classList.add('is-scrolling')
|
||||
const prev = timers.get(el)
|
||||
if (prev) window.clearTimeout(prev)
|
||||
timers.set(
|
||||
el,
|
||||
window.setTimeout(() => el.classList.remove('is-scrolling'), IDLE_MS),
|
||||
)
|
||||
}
|
||||
|
||||
document.addEventListener('scroll', onScroll, {
|
||||
capture: true,
|
||||
passive: true,
|
||||
})
|
||||
return () =>
|
||||
document.removeEventListener('scroll', onScroll, { capture: true })
|
||||
}, [])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import Link from 'next/link'
|
||||
import { Pin, ArrowUpRight } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { SettingsGroup, SettingsRow } from '@/components/settings/SettingsRows'
|
||||
import type { AgentCompetence, AtomTier, FactKind, FactSource } from '@/lib/agent-context/agent-competence'
|
||||
|
||||
/**
|
||||
* Read-only views of the agent's competence (domain-knowledge atoms) and top
|
||||
* learned facts, for the "Vad din agent vet" overview. Each renders as a flat
|
||||
* settings group (Fönster language) with its description behind the group
|
||||
* "?" help. Full editable management lives in /settings/assistant; each
|
||||
* links there.
|
||||
*/
|
||||
|
||||
const TIER_ORDER: AtomTier[] = ['horizontal', 'vertical', 'modifier']
|
||||
|
||||
export function CompetenceCard({ competence }: { competence: AgentCompetence }) {
|
||||
const t = useTranslations('agentKnowledge')
|
||||
const { atoms } = competence
|
||||
const activeAtoms = atoms.filter((a) => a.active).length
|
||||
const tierLabel = (tier: AtomTier) =>
|
||||
tier === 'horizontal' ? t('tier_horizontal') : tier === 'vertical' ? t('tier_vertical') : t('tier_modifier')
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('comp_title')} help={t('comp_desc')}>
|
||||
{atoms.length === 0 ? (
|
||||
<p className="px-1 py-3 text-sm text-muted-foreground">{t('comp_empty')}</p>
|
||||
) : (
|
||||
<>
|
||||
{/* One row per tier: micro-label left, atom chips right. Dormant
|
||||
atoms are the exception the outline chip variant marks. */}
|
||||
{TIER_ORDER.map((tier) => {
|
||||
const items = atoms.filter((a) => a.tier === tier)
|
||||
if (items.length === 0) return null
|
||||
return (
|
||||
<SettingsRow key={tier} label={tierLabel(tier)} align="baseline">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{items.map((a) => (
|
||||
<Badge
|
||||
key={a.id}
|
||||
variant={a.active ? 'secondary' : 'outline'}
|
||||
className={a.active ? '' : 'text-muted-foreground'}
|
||||
title={a.description}
|
||||
>
|
||||
{a.title}
|
||||
{!a.active && tier !== 'horizontal' && (
|
||||
<span className="ml-1.5 opacity-70">· {t('badge_dormant')}</span>
|
||||
)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</SettingsRow>
|
||||
)
|
||||
})}
|
||||
<div className="flex items-center justify-between gap-4 px-1 pt-3 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">{t('comp_count', { total: atoms.length, active: activeAtoms })}</span>
|
||||
<ManageLink href="/settings/assistant?view=skills" label={t('comp_manage')} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
|
||||
export function FactsCard({ competence }: { competence: AgentCompetence }) {
|
||||
const t = useTranslations('agentKnowledge')
|
||||
const { facts, factsActiveTotal } = competence
|
||||
const kindLabel = (k: FactKind) =>
|
||||
k === 'fact' ? t('kind_fact') : k === 'preference' ? t('kind_preference') : k === 'pattern' ? t('kind_pattern') : t('kind_correction')
|
||||
const sourceLabel = (s: FactSource) =>
|
||||
s === 'composer' ? t('source_composer') : s === 'user_taught' ? t('source_user_taught') : s === 'agent_learned' ? t('source_agent_learned') : t('source_derived')
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('facts_title')} help={t('facts_desc')}>
|
||||
{facts.length === 0 ? (
|
||||
<p className="px-1 py-3 text-sm text-muted-foreground">{t('facts_empty')}</p>
|
||||
) : (
|
||||
<>
|
||||
{/* Flat hairline rows: fact content with its kind/source flowing
|
||||
inline as muted text; the pin marks the exception. */}
|
||||
<ul>
|
||||
{facts.map((f) => (
|
||||
<li key={f.id} className="flex items-start gap-2 border-b border-border px-1 py-3">
|
||||
{f.is_pinned ? (
|
||||
<Pin role="img" className="mt-1 h-3.5 w-3.5 shrink-0 fill-current text-muted-foreground" aria-label={t('facts_pinned')} />
|
||||
) : (
|
||||
<span className="mt-1 h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
)}
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-1">
|
||||
<span className="text-sm text-foreground">{f.content}</span>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{kindLabel(f.kind)} · {sourceLabel(f.source)}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex items-center justify-between gap-4 px-1 pt-3 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">
|
||||
{factsActiveTotal > facts.length ? t('facts_more', { n: factsActiveTotal - facts.length }) : ''}
|
||||
</span>
|
||||
<ManageLink href="/settings/assistant?view=memory" label={t('facts_manage')} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
|
||||
function ManageLink({ href, label }: { href: string; label: string }) {
|
||||
return (
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link href={href}>
|
||||
{label}
|
||||
<ArrowUpRight className="ml-1 h-3 w-3" />
|
||||
</Link>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { Brain } from 'lucide-react'
|
||||
import type { LedgerContext } from '@/lib/agent-context/ledger-context'
|
||||
import type { DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
|
||||
import type { AgentCompetence } from '@/lib/agent-context/agent-competence'
|
||||
import { AgentKnowledgeView } from './AgentKnowledgeView'
|
||||
|
||||
interface KnowledgePayload {
|
||||
context: LedgerContext
|
||||
deep: DeepLedgerContext
|
||||
competence: AgentCompetence
|
||||
companyName: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Client wrapper for the "Vad din agent vet" view inside the assistant
|
||||
* settings hub. Fetches the ledger context from /api/agent/knowledge on mount
|
||||
* (lazy: this panel only renders when the Kunskap tab is opened, since Radix
|
||||
* unmounts inactive tabs). Fetching client-side rather than via a server prop
|
||||
* is deliberate: the settings sections mount as propless components in BOTH
|
||||
* the full-page rail and the routed settings modal, so a server fetch wouldn't
|
||||
* reach the modal.
|
||||
*/
|
||||
export function AgentKnowledgePanel() {
|
||||
const t = useTranslations('agentKnowledge')
|
||||
const [payload, setPayload] = useState<KnowledgePayload | null>(null)
|
||||
const [error, setError] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch('/api/agent/knowledge')
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(`knowledge fetch failed: ${res.status}`)
|
||||
return res.json()
|
||||
})
|
||||
.then((json) => {
|
||||
if (!cancelled) setPayload(json.data as KnowledgePayload)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setError(true)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={Brain}
|
||||
title={t('load_error_title')}
|
||||
description={t('load_error_description')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (!payload) {
|
||||
// Mirrors the loaded layout: graph hero, section header, two profile cards.
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<Skeleton className="h-96 w-full rounded-lg" />
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-4 w-40" />
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Skeleton className="h-48 w-full rounded-lg" />
|
||||
<Skeleton className="h-48 w-full rounded-lg" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AgentKnowledgeView
|
||||
context={payload.context}
|
||||
deep={payload.deep}
|
||||
competence={payload.competence}
|
||||
companyName={payload.companyName}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Brain } from 'lucide-react'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsSectionHeader,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { formatDateLong } from '@/lib/utils'
|
||||
import type { LedgerContext } from '@/lib/agent-context/ledger-context'
|
||||
import type { DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
|
||||
import type { AgentCompetence } from '@/lib/agent-context/agent-competence'
|
||||
import { LedgerGraph } from './LedgerGraph'
|
||||
import { CompetenceCard, FactsCard } from './AgentCompetenceSections'
|
||||
|
||||
// Swedish VAT (moms) treatment codes stay Swedish in both locales, like BAS
|
||||
// account names and momsdeklaration labels (.claude/rules/i18n.md).
|
||||
const VAT_LABELS: Record<string, string> = {
|
||||
standard_25: 'Moms 25%',
|
||||
standard_12: 'Moms 12%',
|
||||
standard_6: 'Moms 6%',
|
||||
reduced_12: 'Moms 12%',
|
||||
reduced_6: 'Moms 6%',
|
||||
reverse_charge: 'Omvänd moms',
|
||||
reverse_charge_eu: 'Omvänd moms (EU)',
|
||||
reverse_charge_services: 'Omvänd moms (tjänster)',
|
||||
eu_reverse_charge_services: 'Omvänd moms (EU-tjänster)',
|
||||
eu_goods: 'EU-varor',
|
||||
export: 'Export',
|
||||
exempt: 'Momsfri',
|
||||
no_vat: 'Ingen moms',
|
||||
}
|
||||
|
||||
function vatLabel(code: string | null): string | null {
|
||||
if (!code) return null
|
||||
return VAT_LABELS[code] ?? code
|
||||
}
|
||||
|
||||
export function AgentKnowledgeView({
|
||||
context,
|
||||
deep,
|
||||
competence,
|
||||
companyName,
|
||||
}: {
|
||||
context: LedgerContext
|
||||
deep: DeepLedgerContext
|
||||
competence: AgentCompetence
|
||||
companyName: string
|
||||
}) {
|
||||
const t = useTranslations('agentKnowledge')
|
||||
|
||||
const { meta, explicit_rules, vat_profile, conventions } = context
|
||||
|
||||
const entities = [...deep.counterparty_entities, ...deep.supplier_entities]
|
||||
|
||||
const isEmpty = meta.coverage.posted_entries_window === 0 && entities.length === 0 && explicit_rules.length === 0
|
||||
|
||||
if (isEmpty) {
|
||||
// No bookings yet, but the agent still ships with competence and may
|
||||
// already remember facts: show those rather than a dead end.
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<EmptyState
|
||||
icon={Brain}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
actionLabel={t('empty_action')}
|
||||
actionHref="/transactions"
|
||||
/>
|
||||
<div>
|
||||
<CompetenceCard competence={competence} />
|
||||
<FactsCard competence={competence} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const methodLabel =
|
||||
conventions.accounting_method === 'accrual'
|
||||
? t('method_accrual')
|
||||
: conventions.accounting_method === 'cash'
|
||||
? t('method_cash')
|
||||
: t('method_unknown')
|
||||
|
||||
const periodLabel =
|
||||
vat_profile.moms_period === 'monthly'
|
||||
? t('period_monthly')
|
||||
: vat_profile.moms_period === 'quarterly'
|
||||
? t('period_quarterly')
|
||||
: vat_profile.moms_period === 'yearly'
|
||||
? t('period_yearly')
|
||||
: (vat_profile.moms_period ?? t('unknown'))
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* The cinematic hero: a self-contained dark panel with its own header */}
|
||||
<LedgerGraph deep={deep} companyName={companyName} />
|
||||
|
||||
{/* "Regler & profil": user-authored rules + observed VAT + conventions,
|
||||
in the flat settings language (groups under eyebrow labels, static
|
||||
descriptions behind the group "?"). Minne and Kompetens have their
|
||||
own top-level views, so no second tab row here. */}
|
||||
<section>
|
||||
<SettingsSectionHeader title={t('tab_config')} />
|
||||
|
||||
{explicit_rules.length > 0 && (
|
||||
<SettingsGroup label={t('rules_title')} help={t('rules_description')}>
|
||||
{explicit_rules.map((r, i) => {
|
||||
const vat = vatLabel(r.vat_treatment)
|
||||
return (
|
||||
<div
|
||||
key={r.rule_name + r.match + i}
|
||||
className="flex flex-wrap items-baseline gap-x-3 gap-y-1 border-b border-border px-1 py-3"
|
||||
>
|
||||
<span className="text-sm">{r.rule_name}</span>
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground">
|
||||
{r.match}
|
||||
</span>
|
||||
<span className="flex shrink-0 flex-wrap items-baseline gap-x-2 text-xs text-muted-foreground">
|
||||
{r.account_number ? (
|
||||
<AccountNumber number={r.account_number} showName size="sm" />
|
||||
) : (
|
||||
<span>-</span>
|
||||
)}
|
||||
{vat && <span>· {vat}</span>}
|
||||
<span>· {t('src_rule')}</span>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</SettingsGroup>
|
||||
)}
|
||||
|
||||
<SettingsGroup label={t('vat_title')} help={t('vat_description')}>
|
||||
<SettingsRow label={t('vat_registered_label')}>
|
||||
<span>{vat_profile.registered ? t('yes') : t('no')}</span>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('vat_period_label')}>
|
||||
<span>{periodLabel}</span>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('vat_treatments_label')}>
|
||||
{vat_profile.treatments_used_12m.length === 0 ? (
|
||||
<span className="text-muted-foreground">{t('vat_no_treatments')}</span>
|
||||
) : (
|
||||
<span>{vat_profile.treatments_used_12m.map((code) => vatLabel(code)).join(' · ')}</span>
|
||||
)}
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup label={t('conv_title')} help={t('conv_description')}>
|
||||
<SettingsRow label={t('conv_method_label')}>
|
||||
<span>{methodLabel}</span>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('conv_series_label')}>
|
||||
{conventions.voucher_series_in_use.length === 0 ? (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
) : (
|
||||
<span className="font-mono text-xs">{conventions.voucher_series_in_use.join(', ')}</span>
|
||||
)}
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t('conv_salary_label')}>
|
||||
<span>{conventions.salary_run_active ? t('yes') : t('no')}</span>
|
||||
</SettingsRow>
|
||||
{conventions.typical_booking_lag_days !== null && (
|
||||
<SettingsRow label={t('conv_lag_label')}>
|
||||
<span className="tabular-nums">
|
||||
{t('meta_lag_value', { days: conventions.typical_booking_lag_days })}
|
||||
</span>
|
||||
</SettingsRow>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
</section>
|
||||
|
||||
<p className="text-right text-xs text-muted-foreground">
|
||||
{t('footer_basis', { entries: meta.coverage.posted_entries_window, date: formatDateLong(meta.computed_at) })}
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,163 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
entityMagnitude,
|
||||
selectAccountRing,
|
||||
MAX_ACCOUNTS,
|
||||
} from '@/components/agent-knowledge/ledger-graph-magnitude'
|
||||
import type { DeepEntity } from '@/lib/agent-context/ledger-deep'
|
||||
|
||||
function entity(overrides: Partial<DeepEntity> & { key: string }): DeepEntity {
|
||||
return {
|
||||
name: overrides.key,
|
||||
variants: [overrides.key],
|
||||
variant_count: 1,
|
||||
occurrences: 1,
|
||||
total_amount: 0,
|
||||
first_seen: '2026-01-01',
|
||||
last_seen: '2026-06-01',
|
||||
cadence_days: null,
|
||||
dominant_account_number: '5420',
|
||||
dominant_account_share: 0.8,
|
||||
dominant_account_count: 4,
|
||||
dominant_account_total: 5,
|
||||
kind: 'counterparty',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/** Share of the ring an account gets, ignoring the fixed inter-wedge padding. */
|
||||
function share(weight: number, totalWeight: number): number {
|
||||
return weight / totalWeight
|
||||
}
|
||||
|
||||
describe('selectAccountRing', () => {
|
||||
it('weighs a SEK-only company by amount, exactly as before', () => {
|
||||
const ring = selectAccountRing([
|
||||
entity({ key: 'a', dominant_account_number: '5420', total_amount: 24000, occurrences: 12 }),
|
||||
entity({ key: 'b', dominant_account_number: '5420', total_amount: 6000, occurrences: 3 }),
|
||||
entity({ key: 'c', dominant_account_number: '6540', total_amount: 10000, occurrences: 2 }),
|
||||
])
|
||||
|
||||
expect(ring.basis).toBe('amount')
|
||||
expect(ring.groups.map((g) => g.number)).toEqual(['5420', '6540'])
|
||||
expect(ring.groups.map((g) => g.weight)).toEqual([30000, 10000])
|
||||
expect(ring.totalWeight).toBe(40000)
|
||||
expect(ring.maxMagnitude).toBe(24000)
|
||||
expect(ring.truncated).toBe(false)
|
||||
// Biggest spender first inside the wedge: it lands at the angular centre.
|
||||
expect(ring.groups[0].items.map((e) => e.key)).toEqual(['a', 'b'])
|
||||
})
|
||||
|
||||
it('never puts kronor and booking counts in the same denominator', () => {
|
||||
// 6570 is booked 4 times but carries no usable amount: on the counterparty
|
||||
// side that is a spend of 0, and it used to fall back to its booking count
|
||||
// while 5420 stayed in kronor.
|
||||
const entities = [
|
||||
entity({ key: 'big', dominant_account_number: '5420', total_amount: 250000, occurrences: 6 }),
|
||||
entity({ key: 'nil', dominant_account_number: '6570', total_amount: 0, occurrences: 4 }),
|
||||
]
|
||||
|
||||
const ring = selectAccountRing(entities)
|
||||
|
||||
expect(ring.basis).toBe('volume')
|
||||
expect(ring.groups.map((g) => [g.number, g.weight])).toEqual([
|
||||
['5420', 6],
|
||||
['6570', 4],
|
||||
])
|
||||
expect(ring.totalWeight).toBe(10)
|
||||
// No weight is a kronor figure, so nothing can be summed across units.
|
||||
expect(ring.groups.every((g) => g.weight < 1000)).toBe(true)
|
||||
|
||||
// The pre-fix mix: 250 000 kr against 4 bookings in one denominator gave
|
||||
// 6570 a wedge of 0.0016% of the circle, an invisible sliver. Now it is a
|
||||
// legible tenth of the ring.
|
||||
const mixedShare = share(4, 250000 + 4)
|
||||
expect(mixedShare).toBeLessThan(0.0001)
|
||||
expect(share(ring.groups[1].weight, ring.totalWeight)).toBeCloseTo(0.4, 10)
|
||||
})
|
||||
|
||||
it('keeps an account with no usable amount inside the truncation cap', () => {
|
||||
// Ten accounts, cap is nine. The amount-less one is the most-booked account
|
||||
// the company has, so dropping it is the worst possible choice.
|
||||
const entities: DeepEntity[] = [
|
||||
entity({ key: 'unpriced', dominant_account_number: '4000', total_amount: 0, occurrences: 40 }),
|
||||
]
|
||||
for (let i = 0; i < 9; i++) {
|
||||
entities.push(
|
||||
entity({
|
||||
key: `priced-${i}`,
|
||||
dominant_account_number: `55${10 + i}`,
|
||||
total_amount: 100000 + i,
|
||||
occurrences: 2,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const ring = selectAccountRing(entities)
|
||||
|
||||
expect(ring.groups).toHaveLength(MAX_ACCOUNTS)
|
||||
expect(ring.truncated).toBe(true)
|
||||
expect(ring.groups.map((g) => g.number)).toContain('4000')
|
||||
// It is the largest wedge, not a survivor by luck.
|
||||
const unpriced = ring.groups.find((g) => g.number === '4000')
|
||||
expect(unpriced?.weight).toBe(40)
|
||||
expect(Math.max(...ring.groups.map((g) => g.weight))).toBe(40)
|
||||
})
|
||||
|
||||
it('sizes nodes against a maximum measured in the same unit', () => {
|
||||
const ring = selectAccountRing([
|
||||
entity({ key: 'a', dominant_account_number: '5420', total_amount: 0, occurrences: 9 }),
|
||||
entity({ key: 'b', dominant_account_number: '6540', total_amount: 500, occurrences: 3 }),
|
||||
])
|
||||
|
||||
expect(ring.basis).toBe('volume')
|
||||
expect(ring.maxMagnitude).toBe(9)
|
||||
// The 500 is not compared against 9: under a volume ring it is not read.
|
||||
expect(entityMagnitude(ring.groups[1].items[0], ring.basis)).toBe(3)
|
||||
})
|
||||
|
||||
it('truncates payees per wedge without changing what the wedge weighs', () => {
|
||||
const items = Array.from({ length: 8 }, (_, i) =>
|
||||
entity({ key: `e${i}`, dominant_account_number: '5420', total_amount: 1000, occurrences: 1 }),
|
||||
)
|
||||
|
||||
const ring = selectAccountRing(items, { maxPerAccount: 6 })
|
||||
|
||||
expect(ring.truncated).toBe(true)
|
||||
expect(ring.groups[0].items).toHaveLength(6)
|
||||
expect(ring.groups[0].weight).toBe(8000)
|
||||
})
|
||||
|
||||
it('drops entities with no dominant account and survives an empty ledger', () => {
|
||||
const ring = selectAccountRing([
|
||||
entity({ key: 'orphan', dominant_account_number: null, total_amount: 900, occurrences: 2 }),
|
||||
])
|
||||
|
||||
expect(ring.groups).toEqual([])
|
||||
expect(ring.basis).toBe('volume')
|
||||
// Safe divisors: the layout divides by both.
|
||||
expect(ring.totalWeight).toBe(1)
|
||||
expect(ring.maxMagnitude).toBe(1)
|
||||
})
|
||||
|
||||
it('is deterministic when weights tie', () => {
|
||||
const build = (order: string[]) =>
|
||||
selectAccountRing(
|
||||
order.map((number) =>
|
||||
entity({ key: number, dominant_account_number: number, total_amount: 5000, occurrences: 1 }),
|
||||
),
|
||||
{ maxAccounts: 2 },
|
||||
)
|
||||
|
||||
expect(build(['6000', '5000', '7000']).groups.map((g) => g.number)).toEqual(['5000', '6000'])
|
||||
expect(build(['7000', '6000', '5000']).groups.map((g) => g.number)).toEqual(['5000', '6000'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('entityMagnitude', () => {
|
||||
it('clamps a negative amount rather than subtracting it from a sibling', () => {
|
||||
const e = entity({ key: 'credit', total_amount: -4000, occurrences: 2 })
|
||||
expect(entityMagnitude(e, 'amount')).toBe(0)
|
||||
expect(entityMagnitude(e, 'volume')).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Pure account-ring selection and weighting for `LedgerGraph`.
|
||||
*
|
||||
* Lives outside the component (which is `'use client'` and pure JSX) so the
|
||||
* rule below can be unit tested: this repo runs Vitest in the `node`
|
||||
* environment and never renders components, so logic embedded in a component
|
||||
* is unverifiable by construction. Same arrangement as
|
||||
* `components/transactions/invoice-candidate-ranking.ts`.
|
||||
*
|
||||
* # Why this exists
|
||||
*
|
||||
* The ring weighted each account wedge with:
|
||||
*
|
||||
* const spend = items.reduce((s, i) => s + Math.max(i.total_amount, 0), 0)
|
||||
* return spend > 0 ? spend : items.reduce((s, i) => s + i.occurrences, 0)
|
||||
*
|
||||
* The fallback is per group, but the weights are then summed into one
|
||||
* denominator (`shownWeight`) and ranked against each other. So an account
|
||||
* whose entities carry no usable amount contributed a booking COUNT (say 4)
|
||||
* into a denominator otherwise made of kronor (say 250 000), and:
|
||||
*
|
||||
* - its wedge came out ~0.002% of the circle, i.e. an invisible sliver whose
|
||||
* payee nodes all collapse onto one angle, and
|
||||
* - it sorted below every money-weighted account, so it was the first thing
|
||||
* dropped by the top-`maxAccounts` truncation.
|
||||
*
|
||||
* An account the agent genuinely books to therefore vanished from the map for
|
||||
* no reason other than its magnitude being expressed in a different unit.
|
||||
* Silent exclusion, which is exactly what this surface must not do.
|
||||
*
|
||||
* The rule here: the whole ring is measured in ONE unit. Amount if every
|
||||
* account has a usable amount, booking volume otherwise. Never a mix. The unit
|
||||
* is decided over every account, not just the nine that end up shown, because
|
||||
* the unit is what ranks them: deciding it from the survivors would be circular
|
||||
* and would reintroduce the truncation bug it exists to prevent. The chosen
|
||||
* unit is returned as `basis` so the legend can say which one the sizes
|
||||
* actually mean instead of always claiming "Storlek = belopp".
|
||||
*
|
||||
* # What this does NOT fix
|
||||
*
|
||||
* `DeepEntity.total_amount` arrives from `get_ledger_deep_context` already
|
||||
* summed to a single scalar per entity, built as
|
||||
* `abs(coalesce(t.amount_sek, t.amount))` on the counterparty side and
|
||||
* `coalesce(si.total_sek, si.total, 0)` on the supplier side. That is SEK when
|
||||
* a SEK equivalent was recorded and the RAW FOREIGN AMOUNT otherwise, and the
|
||||
* RPC projects neither `currency` nor a per-row breakdown. A 500 EUR supplier
|
||||
* invoice with no stored exchange rate therefore reaches this file as the
|
||||
* number 500, indistinguishable from 500 kr.
|
||||
*
|
||||
* Nothing here can undo that: by the time the payload exists the currencies
|
||||
* have already been added together upstream, and no field survives that would
|
||||
* let us split them, convert them or even count them. Forming a per-currency
|
||||
* total on this side would mean inventing one. The fix belongs in the RPC
|
||||
* (project `total_amount_sek` + per-currency totals + a count of rows with no
|
||||
* SEK equivalent, and drop the raw-foreign fallback); this file is written so
|
||||
* that the moment those fields exist, `entityMagnitude` is the single place
|
||||
* that has to learn about them.
|
||||
*/
|
||||
import type { DeepEntity } from '@/lib/agent-context/ledger-deep'
|
||||
|
||||
/** How many account wedges the ring shows before it truncates. */
|
||||
export const MAX_ACCOUNTS = 9
|
||||
/** How many payee nodes one wedge shows before it truncates. */
|
||||
export const MAX_PER_ACCOUNT = 6
|
||||
|
||||
/**
|
||||
* The unit the whole ring is measured in.
|
||||
*
|
||||
* - `amount`: `total_amount` as delivered by the RPC (kronor, with the caveat
|
||||
* in the file header). Only chosen when every account has one.
|
||||
* - `volume`: number of bookings. Currency-free, so it is always available and
|
||||
* is what the ring falls back to rather than mixing units.
|
||||
*/
|
||||
export type RingBasis = 'amount' | 'volume'
|
||||
|
||||
export interface RingGroup {
|
||||
/** BAS account number. Strings, never numbers (CLAUDE.md). */
|
||||
number: string
|
||||
/** Entities booked to this account, biggest magnitude first. */
|
||||
items: DeepEntity[]
|
||||
/**
|
||||
* Wedge weight, in `basis` units. Computed over ALL the account's entities,
|
||||
* including the ones `items` truncated away, so the wedge keeps the size the
|
||||
* account actually earned.
|
||||
*/
|
||||
weight: number
|
||||
}
|
||||
|
||||
export interface RingSelection {
|
||||
basis: RingBasis
|
||||
/** Shown accounts, ordered by account number so wedges never swap places. */
|
||||
groups: RingGroup[]
|
||||
/** True when accounts or payees were dropped by the display caps. */
|
||||
truncated: boolean
|
||||
/** Sum of the shown weights, floored at 1 so it is always a safe divisor. */
|
||||
totalWeight: number
|
||||
/** Largest single-entity magnitude among the shown groups, floored at 1. */
|
||||
maxMagnitude: number
|
||||
}
|
||||
|
||||
/**
|
||||
* One entity's magnitude in the ring's unit.
|
||||
*
|
||||
* `total_amount` is whole kronor (`round(...)::bigint` in the RPC), so summing
|
||||
* these is exact integer arithmetic and needs no öre rounding. Negative totals
|
||||
* are clamped to 0 rather than subtracted from a sibling: this drives geometry,
|
||||
* and a negative radius is not a thing.
|
||||
*/
|
||||
export function entityMagnitude(entity: DeepEntity, basis: RingBasis): number {
|
||||
if (basis === 'volume') return Math.max(entity.occurrences, 0)
|
||||
return Math.max(entity.total_amount, 0)
|
||||
}
|
||||
|
||||
function sumMagnitude(items: DeepEntity[], basis: RingBasis): number {
|
||||
return items.reduce((sum, item) => sum + entityMagnitude(item, basis), 0)
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups entities by their dominant account and picks what the ring shows.
|
||||
*
|
||||
* Deterministic end to end: ties break on account number rather than on input
|
||||
* order, so the demo lays out identically on every load.
|
||||
*/
|
||||
export function selectAccountRing(
|
||||
entities: DeepEntity[],
|
||||
options: { maxAccounts?: number; maxPerAccount?: number } = {},
|
||||
): RingSelection {
|
||||
const maxAccounts = options.maxAccounts ?? MAX_ACCOUNTS
|
||||
const maxPerAccount = options.maxPerAccount ?? MAX_PER_ACCOUNT
|
||||
|
||||
const byAccount = new Map<string, DeepEntity[]>()
|
||||
for (const entity of entities) {
|
||||
const account = entity.dominant_account_number
|
||||
if (!account) continue
|
||||
const bucket = byAccount.get(account)
|
||||
if (bucket) bucket.push(entity)
|
||||
else byAccount.set(account, [entity])
|
||||
}
|
||||
|
||||
const buckets = [...byAccount.entries()]
|
||||
|
||||
// The unit decision, made once for the whole ring. An account with no usable
|
||||
// amount would otherwise be weighted in bookings while its siblings are
|
||||
// weighted in kronor, and the two get summed into one denominator below.
|
||||
const basis: RingBasis =
|
||||
buckets.length > 0 && buckets.every(([, items]) => sumMagnitude(items, 'amount') > 0)
|
||||
? 'amount'
|
||||
: 'volume'
|
||||
|
||||
let groups: RingGroup[] = buckets.map(([number, items]) => ({
|
||||
number,
|
||||
items: [...items].sort((a, b) => entityMagnitude(b, basis) - entityMagnitude(a, basis)),
|
||||
weight: sumMagnitude(items, basis),
|
||||
}))
|
||||
|
||||
// Rank to decide what to show, then lay out in account-number order.
|
||||
groups.sort((a, b) => b.weight - a.weight || a.number.localeCompare(b.number))
|
||||
const accountCount = groups.length
|
||||
groups = groups.slice(0, maxAccounts)
|
||||
let truncated = accountCount > groups.length
|
||||
for (const group of groups) {
|
||||
if (group.items.length > maxPerAccount) {
|
||||
truncated = true
|
||||
group.items = group.items.slice(0, maxPerAccount)
|
||||
}
|
||||
}
|
||||
groups.sort((a, b) => a.number.localeCompare(b.number))
|
||||
|
||||
const totalWeight = groups.reduce((sum, group) => sum + group.weight, 0) || 1
|
||||
const maxMagnitude = Math.max(
|
||||
...groups.flatMap((group) => group.items.map((item) => entityMagnitude(item, basis))),
|
||||
1,
|
||||
)
|
||||
|
||||
return { basis, groups, truncated, totalWeight, maxMagnitude }
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
'use client'
|
||||
|
||||
import { MessageCircle } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getAvatarUrl } from './avatars'
|
||||
|
||||
interface Props {
|
||||
avatarId: string | null | undefined
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg'
|
||||
className?: string
|
||||
alt?: string
|
||||
}
|
||||
|
||||
// Renders the agent's avatar: either the chosen SVG from the AVATAR_OPTIONS
|
||||
// registry, or a fallback MessageCircle glyph on a dark circle when no avatar
|
||||
// is set yet (free tier / older profiles).
|
||||
//
|
||||
// `next/image` is intentionally NOT used: these are tiny static SVGs served
|
||||
// from our own /public, and the optimizer does not process SVG anyway, so it
|
||||
// would add a round trip through /_next/image for nothing.
|
||||
export default function AgentAvatar({ avatarId, size = 'sm', className, alt }: Props) {
|
||||
const url = getAvatarUrl(avatarId)
|
||||
const dim = SIZES[size]
|
||||
const altText = alt ?? 'Avatar'
|
||||
|
||||
if (!url) {
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
'inline-flex items-center justify-center rounded-full bg-foreground text-background shrink-0',
|
||||
dim.box,
|
||||
className,
|
||||
)}
|
||||
aria-label={altText}
|
||||
>
|
||||
<MessageCircle className={dim.icon} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
return (
|
||||
<img
|
||||
src={url}
|
||||
alt={altText}
|
||||
className={cn(
|
||||
'rounded-full shrink-0 bg-secondary object-cover',
|
||||
dim.box,
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const SIZES = {
|
||||
xs: { box: 'h-5 w-5', icon: 'h-2.5 w-2.5' },
|
||||
sm: { box: 'h-8 w-8', icon: 'h-3.5 w-3.5' },
|
||||
md: { box: 'h-10 w-10', icon: 'h-4 w-4' },
|
||||
lg: { box: 'h-14 w-14', icon: 'h-5 w-5' },
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,216 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Search, X, Loader2, MessageSquare, Pencil, Pin, PinOff, Archive } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import {
|
||||
type ConversationRow,
|
||||
BUCKET_LABELS,
|
||||
relativeTime,
|
||||
intentLabel,
|
||||
} from './conversation-display'
|
||||
import { useConversationList } from './use-conversation-list'
|
||||
|
||||
interface Props {
|
||||
// Highlight the row for the conversation currently open in the sheet.
|
||||
activeConversationId?: string | null
|
||||
// Fired when the user picks a conversation to resume. The sheet fetches its
|
||||
// messages and swaps back to the chat view: the list itself stays dumb.
|
||||
onSelect: (id: string) => void
|
||||
}
|
||||
|
||||
// In-sheet conversation picker. Renders the same grouped/searchable list as the
|
||||
// /chat sidebar (shared helpers in conversation-display.ts), but instead of
|
||||
// navigating to /chat/[id] it hands the id back so the conversation opens
|
||||
// inline in the sheet and the user keeps chatting without leaving the page.
|
||||
// Rows are renameable inline (PATCH /api/agent/conversations/[id]).
|
||||
export default function AgentSessionList({ activeConversationId, onSelect }: Props) {
|
||||
// Same hook the /chat sidebar uses, so pin/archive/rename behave identically
|
||||
// on both surfaces (optimistic, rolled back on failure, with a message).
|
||||
// Pin and archive are new here: the sheet could only rename before.
|
||||
const {
|
||||
conversations,
|
||||
setConversations,
|
||||
query,
|
||||
setQuery,
|
||||
grouped,
|
||||
togglePin,
|
||||
archive,
|
||||
editingId,
|
||||
editValue,
|
||||
setEditValue,
|
||||
startEdit,
|
||||
cancelEdit,
|
||||
commitEdit,
|
||||
} = useConversationList([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void (async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch('/api/agent/conversations?limit=100')
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
const json = (await res.json()) as { data?: ConversationRow[] }
|
||||
if (!cancelled) setConversations(json.data ?? [])
|
||||
} catch {
|
||||
if (!cancelled) setError('Kunde inte hämta konversationer.')
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
// setConversations is the hook's stable useState setter; listing it would
|
||||
// not change when this runs, and this must fire exactly once on mount.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col min-h-0">
|
||||
<div className="border-b border-border px-5 py-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<input
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Sök konversationer…"
|
||||
className="w-full rounded-lg border border-border bg-background pl-8 pr-7 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
/>
|
||||
{query.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setQuery('')}
|
||||
aria-label="Rensa sökning"
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" /> Hämtar…
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="p-6 text-sm text-destructive">{error}</div>
|
||||
) : grouped.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-2 p-10 text-center text-sm text-muted-foreground">
|
||||
<MessageSquare className="h-6 w-6 opacity-40" />
|
||||
{conversations.length === 0 ? 'Inga konversationer ännu.' : 'Inga träffar.'}
|
||||
</div>
|
||||
) : (
|
||||
grouped.map(({ bucket, rows }) => (
|
||||
<section key={bucket} className="py-2">
|
||||
<p className="px-4 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
{BUCKET_LABELS[bucket]}
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
{rows.map((c) => (
|
||||
<li key={c.id}>
|
||||
{editingId === c.id ? (
|
||||
<div className="px-4 py-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
onBlur={() => void commitEdit(c.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
;(e.target as HTMLInputElement).blur()
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
cancelEdit()
|
||||
}
|
||||
}}
|
||||
placeholder="Namnge konversationen…"
|
||||
maxLength={200}
|
||||
aria-label="Nytt namn på konversationen"
|
||||
className="w-full rounded-lg border border-border bg-background px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={cn(
|
||||
'group flex items-stretch border-l-2 transition-colors',
|
||||
activeConversationId === c.id
|
||||
? 'bg-secondary/50 border-foreground'
|
||||
: 'border-transparent hover:bg-secondary/60',
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(c.id)}
|
||||
className="flex flex-1 min-w-0 items-start gap-2 px-4 py-2 text-left"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-sm font-medium truncate flex-1 min-w-0">
|
||||
{c.title ?? intentLabel(c.intent_id)}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground tabular-nums shrink-0">
|
||||
{relativeTime(c.last_message_at ?? c.created_at)}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">
|
||||
{c.last_message_preview ?? intentLabel(c.intent_id)}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
<div className="shrink-0 flex items-center pr-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void togglePin(c.id, c.pinned)}
|
||||
title={c.pinned ? 'Lossa' : 'Fäst överst'}
|
||||
aria-label={
|
||||
c.pinned ? 'Lossa konversationen' : 'Fäst konversationen överst'
|
||||
}
|
||||
aria-pressed={c.pinned}
|
||||
className="flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors"
|
||||
>
|
||||
{c.pinned ? (
|
||||
<PinOff className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<Pin className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => startEdit(c)}
|
||||
title="Byt namn"
|
||||
aria-label="Byt namn på konversation"
|
||||
className="flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void archive(c.id)}
|
||||
title="Arkivera"
|
||||
aria-label="Arkivera konversationen"
|
||||
className="flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors"
|
||||
>
|
||||
<Archive className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,413 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useReducer,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import type { AgentPanelState } from '@/types'
|
||||
import {
|
||||
resolveAgentPanelPrefs,
|
||||
serializeAgentPanelPrefs,
|
||||
type ResolvedAgentPanelPrefs,
|
||||
} from '@/lib/agent-panel/geometry'
|
||||
import { persistUiState } from '@/lib/ui-state/client'
|
||||
import {
|
||||
clearAgentSheetSession,
|
||||
readAgentSheetSession,
|
||||
} from '@/lib/agent-panel/session-restore'
|
||||
import {
|
||||
INITIAL_AGENT_STATUS,
|
||||
reduceAgentStatus,
|
||||
type AgentStatus,
|
||||
type AgentStatusEvent,
|
||||
} from './agent-status'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
// The sheet is a lazy chunk, and it used to have no loading state at all: a
|
||||
// click on the launcher produced NOTHING until the chunk arrived, then the
|
||||
// whole panel appeared at once. Two fixes: a skeleton in the same geometry so
|
||||
// the surface is there on the first frame, and a prefetch once the page is
|
||||
// idle so the chunk is usually already loaded before anyone clicks.
|
||||
const AgentSheet = dynamic(() => import('./AgentSheet'), {
|
||||
loading: () => <AgentSheetSkeleton />,
|
||||
})
|
||||
|
||||
function AgentSheetSkeleton() {
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="fixed inset-y-0 right-0 z-[60] flex w-full flex-col border-l border-border bg-background shadow-lg"
|
||||
style={{
|
||||
// Tracks the user's persisted dock width (set by the provider below)
|
||||
// so the skeleton has the same geometry as the sheet it stands in for.
|
||||
maxWidth: 'var(--agent-panel-w, 480px)',
|
||||
paddingTop: 'env(safe-area-inset-top, 0px)',
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-border px-4 py-4">
|
||||
<Skeleton className="h-8 w-8 shrink-0 rounded-full" />
|
||||
<Skeleton className="h-4 w-32" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize intent args into the sheet's remount key.
|
||||
*
|
||||
* The key used to be intent + contextRef + seed only, but some callers pass a
|
||||
* CONSTANT contextRef with varying args: bulk-book always uses 'inbox:bulk' and
|
||||
* carries the selected item ids. Selecting A+B, collapsing, then selecting C+D
|
||||
* produced the same key, so the sheet did not remount and the earlier
|
||||
* conversation reopened while the user believed C+D were being booked.
|
||||
*
|
||||
* Key order so the same selection reached by different routes stays one session.
|
||||
*/
|
||||
// Fallback identity for args that cannot be serialized (cycles, non-JSON
|
||||
// values). A timestamp would be wrong twice over: two different objects created
|
||||
// in the same millisecond would collide, and the same object would get a new
|
||||
// key on every render tick, remounting the sheet under the user mid-session.
|
||||
// A WeakMap gives each object one stable id for as long as it exists.
|
||||
const argsFallbackIds = new WeakMap<object, string>()
|
||||
let argsFallbackSeq = 0
|
||||
|
||||
function stableArgsKey(args?: Record<string, unknown>): string {
|
||||
if (!args) return ''
|
||||
try {
|
||||
const keys = Object.keys(args).sort()
|
||||
return JSON.stringify(keys.map((k) => [k, args[k]]))
|
||||
} catch {
|
||||
let id = argsFallbackIds.get(args)
|
||||
if (!id) {
|
||||
id = `unserializable:${++argsFallbackSeq}`
|
||||
argsFallbackIds.set(args, id)
|
||||
}
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
/** Warm the sheet chunk when the browser is idle, never on the critical path. */
|
||||
function useSheetPrefetch() {
|
||||
useEffect(() => {
|
||||
const warm = () => {
|
||||
// Swallow a failed prefetch: the real import on click will surface any
|
||||
// genuine problem, and warming must never produce an unhandled rejection.
|
||||
void import('./AgentSheet').catch(() => {})
|
||||
}
|
||||
const w = window as Window & {
|
||||
requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number
|
||||
cancelIdleCallback?: (id: number) => void
|
||||
}
|
||||
if (typeof w.requestIdleCallback === 'function') {
|
||||
// A busy page can stay non-idle indefinitely, so cap the wait: the point
|
||||
// is to have the chunk ready before the first click, not to hold out for
|
||||
// a quiet moment that may never arrive.
|
||||
const id = w.requestIdleCallback(warm, { timeout: 2000 })
|
||||
return () => w.cancelIdleCallback?.(id)
|
||||
}
|
||||
const t = setTimeout(warm, 2000)
|
||||
return () => clearTimeout(t)
|
||||
}, [])
|
||||
}
|
||||
|
||||
export interface AgentIdentity {
|
||||
displayName: string | null
|
||||
avatarId: string | null
|
||||
// True only after the user has completed Phase B verification in
|
||||
// /onboarding/agent. Consumers (AgentTrigger, page-level Sparkle
|
||||
// buttons) should hide themselves when this is false so the FAB
|
||||
// doesn't pop up before the agent build flow has run.
|
||||
isVerified: boolean
|
||||
}
|
||||
|
||||
// Provider exposes a single imperative function: openAgentSheet({...}). Any
|
||||
// client component (top-nav button, transaction row "Fråga om" button, etc.)
|
||||
// calls it to bring the sheet up with a specific intent + capture args.
|
||||
//
|
||||
// The sheet itself manages its own message list, streaming state, and
|
||||
// dismissal. The provider just owns "what is open" and re-opens or replaces
|
||||
// the panel when called again.
|
||||
|
||||
export interface OpenAgentSheetArgs {
|
||||
intentId: string
|
||||
// Intent-specific args passed to the server's intent.capture(), e.g.
|
||||
// { transaction_id: '...' } for transaction.categorization.
|
||||
intentArgs?: Record<string, unknown>
|
||||
// Optional ref persisted on agent_conversations.context_ref so the UI can
|
||||
// surface a back-pointer ("om transaktion 12 mar / 1 240 kr") later.
|
||||
contextRef?: string
|
||||
// Pre-populated first user message. When set, the chat skips the intent's
|
||||
// promptTemplate and sends this verbatim instead. Used by /chat empty-state
|
||||
// suggestion chips to give the user a one-click starting prompt.
|
||||
seedUserMessage?: string
|
||||
// Reopen an existing thread instead of starting one. Set by the provider
|
||||
// itself when it restores the panel after a page reload (see
|
||||
// lib/agent-panel/session-restore); the sheet loads the thread on mount
|
||||
// exactly as if it had been picked from "Tidigare konversationer".
|
||||
resumeConversationId?: string
|
||||
}
|
||||
|
||||
interface AgentSheetContextValue {
|
||||
openAgentSheet: (args: OpenAgentSheetArgs) => void
|
||||
closeAgentSheet: () => void
|
||||
// Collapse hides the sheet WITHOUT unmounting it, so the in-memory
|
||||
// conversation (messages, streaming, pending approval cards) survives: the
|
||||
// floating trigger re-expands the same session. Distinct from close, which
|
||||
// ends the session entirely.
|
||||
collapseAgentSheet: () => void
|
||||
expandAgentSheet: () => void
|
||||
// Discard the current thread and start a fresh conversation on the same
|
||||
// intent (the header "Ny konversation" control). Implemented by remounting
|
||||
// the sheet via a nonce in its key.
|
||||
restartAgentSheet: () => void
|
||||
// True while a session exists (open or collapsed).
|
||||
isOpen: boolean
|
||||
// True while a session exists but is minimized off-screen.
|
||||
collapsed: boolean
|
||||
// What the assistant is doing, for surfaces outside the panel (today the
|
||||
// floating trigger). See agent-status.ts: one channel, so a durable
|
||||
// background run can publish to it later without a second one.
|
||||
status: AgentStatus
|
||||
publishAgentStatus: (event: AgentStatusEvent) => void
|
||||
// Width in px the docked panel is claiming from the page, or null when it is
|
||||
// overlaying instead. Set by the panel, read by the frame layout.
|
||||
setDockWidth: (px: number | null) => void
|
||||
// Panel geometry preferences (docked width, floating rect, active mode).
|
||||
// Owned here rather than in the sheet so they survive sheet remounts
|
||||
// (intent changes bump the sheet's key) and persist across sessions via
|
||||
// user_preferences.ui_state.agent_panel.
|
||||
panelPrefs: ResolvedAgentPanelPrefs
|
||||
updatePanelPrefs: (patch: Partial<ResolvedAgentPanelPrefs>) => void
|
||||
// Agent name + avatar: set once from the server-loaded agent_profile
|
||||
// and exposed through context so the trigger / chat headers can render
|
||||
// them without their own fetches. Null when the user hasn't verified a
|
||||
// profile yet (free tier or pre-onboarding).
|
||||
identity: AgentIdentity
|
||||
}
|
||||
|
||||
const AgentSheetContext = createContext<AgentSheetContextValue | null>(null)
|
||||
|
||||
interface AgentSheetProviderProps {
|
||||
children: React.ReactNode
|
||||
identity?: AgentIdentity
|
||||
// Server-seeded ui_state.agent_panel, so the panel opens at the user's
|
||||
// persisted size/mode without a first-paint jump.
|
||||
initialPanelPrefs?: AgentPanelState
|
||||
}
|
||||
|
||||
export function AgentSheetProvider({
|
||||
children,
|
||||
identity,
|
||||
initialPanelPrefs,
|
||||
}: AgentSheetProviderProps) {
|
||||
useSheetPrefetch()
|
||||
const [activeArgs, setActiveArgs] = useState<OpenAgentSheetArgs | null>(null)
|
||||
// Collapsed = session alive but hidden. Kept separate from activeArgs so
|
||||
// collapsing never unmounts AgentChat (which would wipe the conversation).
|
||||
const [collapsed, setCollapsed] = useState(false)
|
||||
// Bumped by restartAgentSheet to force a fresh AgentChat mount (a new thread)
|
||||
// on the same intent, without closing the sheet.
|
||||
const [restartNonce, setRestartNonce] = useState(0)
|
||||
const [status, publishAgentStatus] = useReducer(reduceAgentStatus, INITIAL_AGENT_STATUS)
|
||||
const [dockWidth, setDockWidth] = useState<number | null>(null)
|
||||
|
||||
// Geometry preferences. The ref mirrors the state so updatePanelPrefs can
|
||||
// merge and persist from event handlers without a stale closure (drag
|
||||
// commits fire from listeners installed at drag start).
|
||||
const [panelPrefs, setPanelPrefs] = useState<ResolvedAgentPanelPrefs>(() =>
|
||||
resolveAgentPanelPrefs(initialPanelPrefs),
|
||||
)
|
||||
const panelPrefsRef = useRef(panelPrefs)
|
||||
// Trailing debounce on the POST only: local state stays immediate, but key
|
||||
// auto-repeat on the resize handle (one updatePanelPrefs per repeat) must
|
||||
// not become one read-merge-write against user_preferences per repeat.
|
||||
const persistTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const updatePanelPrefs = useCallback((patch: Partial<ResolvedAgentPanelPrefs>) => {
|
||||
const next = { ...panelPrefsRef.current, ...patch }
|
||||
panelPrefsRef.current = next
|
||||
setPanelPrefs(next)
|
||||
// Fire-and-forget: cosmetic preference, a lost write self-corrects on the
|
||||
// next change.
|
||||
if (persistTimerRef.current) clearTimeout(persistTimerRef.current)
|
||||
persistTimerRef.current = setTimeout(() => {
|
||||
// Null before writing: a fired timer is no longer pending, and the
|
||||
// unmount flush below must not replay this (possibly stale) value.
|
||||
persistTimerRef.current = null
|
||||
persistUiState({ agent_panel: serializeAgentPanelPrefs(panelPrefsRef.current) })
|
||||
}, 300)
|
||||
}, [])
|
||||
useEffect(
|
||||
() => () => {
|
||||
// Flush on unmount so a pending debounced write is not lost.
|
||||
if (persistTimerRef.current) {
|
||||
clearTimeout(persistTimerRef.current)
|
||||
persistUiState({ agent_panel: serializeAgentPanelPrefs(panelPrefsRef.current) })
|
||||
}
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// The lazy sheet's loading skeleton renders before the sheet can report any
|
||||
// geometry, so the persisted dock width is published as a CSS variable for
|
||||
// it (and only it) to read.
|
||||
useEffect(() => {
|
||||
document.documentElement.style.setProperty('--agent-panel-w', `${panelPrefs.dockWidth}px`)
|
||||
}, [panelPrefs.dockWidth])
|
||||
|
||||
// Visibility drives whether a finished turn is news or not, so it is derived
|
||||
// from the session state rather than reported by the panel: closing counts as
|
||||
// hidden just like collapsing, and a panel that never opened is neither.
|
||||
const panelVisible = activeArgs !== null && !collapsed
|
||||
useEffect(() => {
|
||||
publishAgentStatus({ type: 'visibility', visible: panelVisible })
|
||||
}, [panelVisible])
|
||||
|
||||
// Dock the panel into the frame instead of over it: the page panel gives up
|
||||
// its right margin so the content the user is asking about stays readable
|
||||
// beside the answer. Written as a CSS variable rather than a class on <main>
|
||||
// because the frame layout is a server component; globals.css seeds the
|
||||
// default so the first paint is not a jump.
|
||||
// --agent-sheet-w is the docked-only sibling: unlike --agent-dock-w it has
|
||||
// NO stylesheet default (globals.css seeds dock-w at the 10px frame gutter),
|
||||
// so consumers that must be a no-op when the sheet is closed (dialog
|
||||
// centering and width caps in ui/dialog.tsx and the wide booking/review
|
||||
// dialogs) read this one and get their 0px fallback.
|
||||
useEffect(() => {
|
||||
const root = document.documentElement
|
||||
if (dockWidth === null) {
|
||||
root.style.removeProperty('--agent-dock-w')
|
||||
root.style.removeProperty('--agent-sheet-w')
|
||||
return
|
||||
}
|
||||
root.style.setProperty('--agent-dock-w', `${dockWidth}px`)
|
||||
root.style.setProperty('--agent-sheet-w', `${dockWidth}px`)
|
||||
return () => {
|
||||
root.style.removeProperty('--agent-dock-w')
|
||||
root.style.removeProperty('--agent-sheet-w')
|
||||
}
|
||||
}, [dockWidth])
|
||||
|
||||
// Bring back the thread this tab had open before a full page reload. The
|
||||
// panel's state is React-only, so the deploy prompt's "Ladda om" (or any
|
||||
// refresh) used to close it and drop the thread from view; the user then
|
||||
// had to find it again under "Tidigare konversationer". The sheet records
|
||||
// the open thread per tab (sessionStorage), and this reopens it on mount.
|
||||
// Only on mount: client-side navigation keeps the provider, and a session
|
||||
// the user closed has already been cleared from storage.
|
||||
useEffect(() => {
|
||||
const stored = readAgentSheetSession()
|
||||
if (!stored) return
|
||||
// sessionStorage is client-only: reading it in the state initializer would
|
||||
// render the panel on the client but not on the server (hydration
|
||||
// mismatch), so it has to be an effect that sets state once.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setActiveArgs({
|
||||
intentId: stored.intentId,
|
||||
contextRef: stored.contextRef ?? undefined,
|
||||
resumeConversationId: stored.conversationId,
|
||||
})
|
||||
setCollapsed(stored.collapsed)
|
||||
}, [])
|
||||
|
||||
const openAgentSheet = useCallback((args: OpenAgentSheetArgs) => {
|
||||
setActiveArgs(args)
|
||||
setCollapsed(false)
|
||||
}, [])
|
||||
|
||||
const closeAgentSheet = useCallback(() => {
|
||||
setActiveArgs(null)
|
||||
setCollapsed(false)
|
||||
setDockWidth(null)
|
||||
// Close ends the session: a reload after this must not bring it back.
|
||||
clearAgentSheetSession()
|
||||
publishAgentStatus({ type: 'reset' })
|
||||
}, [])
|
||||
|
||||
const collapseAgentSheet = useCallback(() => setCollapsed(true), [])
|
||||
const expandAgentSheet = useCallback(() => setCollapsed(false), [])
|
||||
const restartAgentSheet = useCallback(() => {
|
||||
// Discarding the thread: forget it for reload purposes too, so the old
|
||||
// one does not reappear while the new one has no id yet, and drop any
|
||||
// restore id from the args, or the remount would reopen that thread
|
||||
// instead of starting a fresh one.
|
||||
clearAgentSheetSession()
|
||||
setActiveArgs((args) =>
|
||||
args?.resumeConversationId ? { ...args, resumeConversationId: undefined } : args,
|
||||
)
|
||||
setRestartNonce((n) => n + 1)
|
||||
setCollapsed(false)
|
||||
}, [])
|
||||
|
||||
const resolvedIdentity = useMemo<AgentIdentity>(
|
||||
() => identity ?? { displayName: null, avatarId: null, isVerified: false },
|
||||
[identity],
|
||||
)
|
||||
|
||||
const value = useMemo<AgentSheetContextValue>(
|
||||
() => ({
|
||||
openAgentSheet,
|
||||
closeAgentSheet,
|
||||
collapseAgentSheet,
|
||||
expandAgentSheet,
|
||||
restartAgentSheet,
|
||||
isOpen: activeArgs !== null,
|
||||
collapsed,
|
||||
status,
|
||||
publishAgentStatus,
|
||||
setDockWidth,
|
||||
panelPrefs,
|
||||
updatePanelPrefs,
|
||||
identity: resolvedIdentity,
|
||||
}),
|
||||
[
|
||||
openAgentSheet,
|
||||
closeAgentSheet,
|
||||
collapseAgentSheet,
|
||||
expandAgentSheet,
|
||||
restartAgentSheet,
|
||||
activeArgs,
|
||||
collapsed,
|
||||
status,
|
||||
panelPrefs,
|
||||
updatePanelPrefs,
|
||||
resolvedIdentity,
|
||||
],
|
||||
)
|
||||
|
||||
return (
|
||||
<AgentSheetContext.Provider value={value}>
|
||||
{children}
|
||||
{activeArgs && (
|
||||
<AgentSheet
|
||||
key={`${activeArgs.intentId}:${activeArgs.contextRef ?? ''}:${stableArgsKey(activeArgs.intentArgs)}:${activeArgs.seedUserMessage ?? ''}:${activeArgs.resumeConversationId ?? ''}:${restartNonce}`}
|
||||
intentId={activeArgs.intentId}
|
||||
intentArgs={activeArgs.intentArgs}
|
||||
contextRef={activeArgs.contextRef}
|
||||
seedUserMessage={activeArgs.seedUserMessage}
|
||||
resumeConversationId={activeArgs.resumeConversationId}
|
||||
collapsed={collapsed}
|
||||
onStatus={publishAgentStatus}
|
||||
onDockWidthChange={setDockWidth}
|
||||
onCollapse={collapseAgentSheet}
|
||||
onRestart={restartAgentSheet}
|
||||
onClose={closeAgentSheet}
|
||||
/>
|
||||
)}
|
||||
</AgentSheetContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAgentSheet(): AgentSheetContextValue {
|
||||
const ctx = useContext(AgentSheetContext)
|
||||
if (!ctx) {
|
||||
throw new Error('useAgentSheet must be used inside <AgentSheetProvider>')
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
import { Loader2, X } from 'lucide-react'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import { collapsedStatusLabel } from './agent-status'
|
||||
import { routeToIntent } from '@/lib/agent/intents/route-mapping'
|
||||
import { useAssistantAvailable, useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
// Floating trigger sits above the page bottom-right, opens the AgentSheet when
|
||||
// clicked. Hidden when the sheet is already open so the icon doesn't double up.
|
||||
//
|
||||
// Desktop-only for a FRESH open (founder call 2026-08-06). On mobile the pill
|
||||
// landed on top of the bottom nav and covered page content, and the bottom nav
|
||||
// already carries an "Assistent" tab to /chat behind the very same
|
||||
// identity.isVerified gate used here, so the pill was pure redundancy. A
|
||||
// COLLAPSED session keeps its handle on every viewport and on every page except
|
||||
// /chat: see the page-suppression block and the visibility class below.
|
||||
//
|
||||
// Route-aware: routeToIntent(pathname) picks the right intent + intentArgs so
|
||||
// clicking the FAB on /invoices/abc-123 opens invoice.draft with that invoice
|
||||
// id (rather than the page-agnostic general.help with just the URL). The
|
||||
// label suffix renders "Fråga Anna om denna faktura" so the user can tell at
|
||||
// a glance that the agent is going to know which entity they're on.
|
||||
//
|
||||
// Reads the agent's display_name + avatar_id from the AgentSheet context so
|
||||
// the button reads "Fråga Anna" (with Anna's face) rather than the generic
|
||||
// "Fråga min assistent".
|
||||
//
|
||||
// Page-specific triggers (e.g. "Granska med assistent" on a supplier invoice)
|
||||
// still call useAgentSheet() directly from their own buttons because they
|
||||
// know exactly which entity to pass. (Per-transaction help has its own
|
||||
// row-level "Fråga [namn]" button in TransactionInboxCard, and the matching
|
||||
// "Fråga assistenten" in Dokumentinkorgen: both passing a transaction_id the
|
||||
// pathname-only FAB can't know.)
|
||||
// Session-scoped dismissal flag for the non-payer upsell pill. sessionStorage
|
||||
// on purpose: "close" means gone for THIS browser session, and the pill comes
|
||||
// back full-size next session. Anything permanent (localStorage or
|
||||
// user_preferences) would let a non-payer silence the conversion surface
|
||||
// forever with one click (founder call 2026-08-09).
|
||||
const UPSELL_DISMISSED_KEY = 'agent-upsell-dismissed'
|
||||
|
||||
export default function AgentTrigger({ hidden = false }: { hidden?: boolean }) {
|
||||
const { openAgentSheet, expandAgentSheet, isOpen, collapsed, status, identity } = useAgentSheet()
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const hasAi = useCapability(CAPABILITY.ai)
|
||||
const assistantAvailable = useAssistantAvailable()
|
||||
|
||||
// Read the dismissal AFTER hydration (effect, not state initializer): the
|
||||
// server always renders the pill, so an initializer that reads
|
||||
// sessionStorage would mismatch the SSR HTML. Costs one frame of pill
|
||||
// before it hides, which is invisible in practice.
|
||||
const [upsellDismissed, setUpsellDismissed] = useState(false)
|
||||
useEffect(() => {
|
||||
try {
|
||||
if (window.sessionStorage.getItem(UPSELL_DISMISSED_KEY) === '1') setUpsellDismissed(true)
|
||||
} catch {
|
||||
// Storage unavailable (private mode, blocked cookies): the pill simply
|
||||
// stays dismissible per page load instead of per session.
|
||||
}
|
||||
}, [])
|
||||
|
||||
const dismissUpsellForSession = () => {
|
||||
setUpsellDismissed(true)
|
||||
try {
|
||||
window.sessionStorage.setItem(UPSELL_DISMISSED_KEY, '1')
|
||||
} catch {
|
||||
// Same as above: in-memory state still hides it for this page.
|
||||
}
|
||||
}
|
||||
|
||||
// For a non-payer the sheet is a paywall surface, so closing it means "not
|
||||
// now": treat it exactly like dismissing the pill. Otherwise the user closes
|
||||
// the big panel and the wide "Uppgradera för att använda ..." pill pops
|
||||
// right back, which is the residual-overlay complaint this fixes. Collapse
|
||||
// (Minimera) is not a close and never lands here: isOpen stays true.
|
||||
const prevOpenRef = useRef(isOpen)
|
||||
useEffect(() => {
|
||||
const wasOpen = prevOpenRef.current
|
||||
prevOpenRef.current = isOpen
|
||||
if (wasOpen && !isOpen && !hasAi) {
|
||||
setUpsellDismissed(true)
|
||||
try {
|
||||
window.sessionStorage.setItem(UPSELL_DISMISSED_KEY, '1')
|
||||
} catch {
|
||||
// In-memory dismissal still applies.
|
||||
}
|
||||
}
|
||||
}, [isOpen, hasAi])
|
||||
|
||||
// User opt-out (Inställningar → Assistenten): the sidebar entry stays, the
|
||||
// floating button goes. A collapsed session keeps its reopen handle even
|
||||
// when hidden: it's the only way back to a minimized conversation, and its
|
||||
// existence implies the user is actively using the assistant right now.
|
||||
if (hidden && !collapsed) return null
|
||||
|
||||
// Dismissed upsell (non-payer clicked the pill's X, or closed the paywalled
|
||||
// sheet): render nothing at all for the rest of the browser session. A
|
||||
// collapsed session still shows its handle even then: it is the only way
|
||||
// back to the minimized conversation, and its label is a resume action
|
||||
// ("Fortsätt med ..."), not the upsell.
|
||||
if (!hasAi && upsellDismissed && !collapsed) return null
|
||||
|
||||
// Sheet open AND visible → hide the FAB so the icon doesn't double up. When
|
||||
// the session is merely collapsed we KEEP the FAB: it's the handle that
|
||||
// brings the minimized conversation back.
|
||||
if (isOpen && !collapsed) return null
|
||||
// Page suppression, split by WHY the page suppresses. The split is the point:
|
||||
// one rule is about redundancy (the page already IS the conversation), the
|
||||
// other is about crowding (the page is dense and the pill would sit on top of
|
||||
// it). Only the redundancy rule survives into the collapsed state, because
|
||||
// only it leaves the user another route back to the conversation.
|
||||
//
|
||||
// /chat*: suppressed in BOTH states. Fresh open: the surface IS the chat, so
|
||||
// a floating "Fråga …" pill is redundant and overlaps the input. Collapsed:
|
||||
// the /chat layout lists every conversation in its sidebar and renders the
|
||||
// selected one in the main pane, so navigating here IS the way back; a handle
|
||||
// that re-expands the panel on top of it would put two chats on one screen.
|
||||
// Safe because the session lives in AgentSheetProvider in the dashboard
|
||||
// layout, one level above the page: it stays mounted (messages, streaming,
|
||||
// pending approval cards intact) the whole time the user is on /chat, and the
|
||||
// handle reappears the moment they navigate anywhere else, bottom nav
|
||||
// included. Nothing is discarded, the handle is just hidden while the user is
|
||||
// standing inside the surface it would lead to.
|
||||
if (pathname?.startsWith('/chat')) return null
|
||||
// /bookkeeping/[id]: FRESH open only. The verifikation editor is a dense
|
||||
// regulatory surface (debits/credits, BAS codes, period locks) and a floating
|
||||
// "Fråga … om denna verifikation" pill on top of it adds noise without
|
||||
// earning its place. A COLLAPSED session keeps its handle here, and on every
|
||||
// other page in the app: this page offers no other route back to a minimized
|
||||
// conversation, and stranding a half-finished booking is a worse outcome than
|
||||
// a pill over the editor. (/bookkeeping list, /bookkeeping/new and
|
||||
// /bookkeeping/year-end are not the editor and keep the fresh-open FAB.)
|
||||
if (!collapsed) {
|
||||
const segs = pathname?.split('/').filter(Boolean) ?? []
|
||||
if (segs[0] === 'bookkeeping' && segs[1] && segs[1] !== 'year-end' && segs[1] !== 'new') {
|
||||
return null
|
||||
}
|
||||
}
|
||||
// Pre-onboarding: no agent_profile.verified_at yet. The FAB would lead
|
||||
// into a generic chat with no specialization. Better to hide it until
|
||||
// the user has finished /onboarding/agent. (A collapsed session implies the
|
||||
// agent is already in use, so this only gates fresh opens in practice.)
|
||||
if (!identity.isVerified) return null
|
||||
|
||||
const name = identity.displayName?.trim() || 'min assistent'
|
||||
// Without the tool-loop runtime (OpenAI-compatible or unconfigured AI, #2204)
|
||||
// every route dispatches to general.help: the single-call console runs on
|
||||
// any provider, so the pill stays but never opens a chat that would 503.
|
||||
const dispatch = routeToIntent(pathname, { assistantAvailable })
|
||||
// AI assistant runs on a paid cloud service. Without the capability, opening
|
||||
// the sheet would land the user in a chat whose send is dead. Keep the FAB
|
||||
// visible (it's the conversion surface) but route it to billing instead.
|
||||
// A minimized session used to be silent: the agent could be three tool calls
|
||||
// into a booking, or finished ten minutes ago, and the pill said "Fortsätt
|
||||
// med Anna" either way. While hidden, the status channel does the talking.
|
||||
const statusText = collapsed ? collapsedStatusLabel(status, name) : null
|
||||
const working = status.activity === 'working' || status.activity === 'detached'
|
||||
const finished = collapsed && status.activity === 'done'
|
||||
|
||||
const labelText =
|
||||
statusText ??
|
||||
(collapsed
|
||||
? `Fortsätt med ${name}`
|
||||
: !hasAi
|
||||
? `Uppgradera för att använda ${name}`
|
||||
: dispatch.labelSuffix
|
||||
? `Fråga ${name} ${dispatch.labelSuffix}`
|
||||
: `Fråga ${name}`)
|
||||
|
||||
const handleClick = () => {
|
||||
// Collapsed → bring the existing session back, don't start a new one.
|
||||
if (collapsed) {
|
||||
expandAgentSheet()
|
||||
return
|
||||
}
|
||||
if (!hasAi) {
|
||||
router.push('/settings/billing')
|
||||
return
|
||||
}
|
||||
openAgentSheet({
|
||||
intentId: dispatch.intentId,
|
||||
intentArgs: dispatch.intentArgs,
|
||||
contextRef: dispatch.contextRef,
|
||||
})
|
||||
}
|
||||
|
||||
// Mobile visibility, decided per state rather than per viewport alone:
|
||||
//
|
||||
// fresh open -> 'hidden md:flex'. `display: none` (not opacity/visibility)
|
||||
// so the button is genuinely non-interactive on mobile: not
|
||||
// clickable, not tabbable, out of the accessibility tree.
|
||||
// Losing it costs nothing, the bottom nav's "Assistent" tab
|
||||
// reaches the same agent.
|
||||
// collapsed -> 'flex' on every viewport. Off /chat this is the ONLY route
|
||||
// back to a minimized conversation: the bottom-nav tab opens
|
||||
// the /chat surface instead of restoring the in-progress
|
||||
// sheet, so hiding the handle on mobile would strand a
|
||||
// session mid-booking with no way to reopen it. On /chat the
|
||||
// handle is suppressed outright (see above), which is exactly
|
||||
// the case where the nav tab does lead somewhere useful.
|
||||
//
|
||||
// A pure CSS switch on purpose: no useMediaQuery, so no hydration mismatch,
|
||||
// no resize listener, no layout shift on first paint.
|
||||
const visibilityClass = collapsed ? 'flex' : 'hidden md:flex'
|
||||
|
||||
// The upsell pill (fresh state, no capability) carries its own dismiss so a
|
||||
// non-payer is never stuck with an undismissable ad in the corner. Payer and
|
||||
// collapsed states are unchanged: no X there, the pill is functional UI.
|
||||
const dismissible = !hasAi && !collapsed
|
||||
|
||||
return (
|
||||
// Wrapper div carries the pill shell; the two segments inside are separate
|
||||
// buttons because a dismiss nested in the main <button> would be invalid
|
||||
// HTML. Segment hover is a background/10 overlay, visually equivalent to
|
||||
// the old whole-pill foreground/90 shift.
|
||||
<div
|
||||
// Mobile: sit above the bottom nav (h-16 = 64px) AND the iOS home
|
||||
// indicator (env(safe-area-inset-bottom)). Still needed after the FAB
|
||||
// went desktop-only: the collapsed handle above renders on mobile too.
|
||||
// Desktop: standard 20px lift, no mobile nav to worry about, except when
|
||||
// the page declares a bottom action bar (body[data-page-bottom-bar],
|
||||
// set by e.g. the standalone invoice editor): lift above it so the FAB
|
||||
// never covers the bar's primary button.
|
||||
// z-[45]: above the DialogVeil (z-40) so the assistant can be OPENED
|
||||
// while a non-modal dialog (booking, invoice) holds the page inert, but
|
||||
// below dialog content (z-50). Under a true modal dialog Radix sets
|
||||
// pointer-events: none on <body>, which keeps the trigger dead there
|
||||
// regardless of z.
|
||||
// data-agent-ui: opening the assistant must not dismiss an open
|
||||
// non-modal dialog (DialogContent treats this as inside).
|
||||
data-agent-ui=""
|
||||
className={`fixed right-4 z-[45] ${visibilityClass} h-12 max-w-[calc(100vw-2rem)] items-stretch rounded-full bg-foreground text-background shadow-lg bottom-[calc(env(safe-area-inset-bottom,0px)+5rem)] md:bottom-4 md:[body[data-page-bottom-bar]_&]:bottom-20`}
|
||||
>
|
||||
<button
|
||||
onClick={handleClick}
|
||||
className={`flex min-w-0 items-center gap-2 pl-2 ${dismissible ? 'rounded-l-full pr-2' : 'rounded-full pr-4'} hover:bg-background/10 transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`}
|
||||
aria-label={labelText}
|
||||
// The label changes on its own while the panel is hidden, so it has to be
|
||||
// announced rather than only redrawn. Polite: it never interrupts.
|
||||
aria-live="polite"
|
||||
>
|
||||
<span className="relative shrink-0">
|
||||
<AgentAvatar
|
||||
avatarId={identity.avatarId}
|
||||
size="sm"
|
||||
className="ring-2 ring-background/20"
|
||||
alt={name}
|
||||
/>
|
||||
{/* An answer waiting behind a hidden panel is the one thing worth a
|
||||
dot: it is unread, not in progress. */}
|
||||
{finished && (
|
||||
<span className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-success ring-2 ring-foreground" />
|
||||
)}
|
||||
</span>
|
||||
{working && collapsed && (
|
||||
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin motion-reduce:animate-none" />
|
||||
)}
|
||||
<span className="text-sm font-medium truncate">{labelText}</span>
|
||||
</button>
|
||||
{dismissible && (
|
||||
<button
|
||||
onClick={dismissUpsellForSession}
|
||||
aria-label="Dölj tills nästa besök"
|
||||
className="flex items-center rounded-r-full pl-1 pr-3 text-background/70 hover:text-background hover:bg-background/10 transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,106 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { ArrowLeft } from 'lucide-react'
|
||||
import AgentChat, { attachStagedOperations, normalizeStoredMessages } from './AgentChat'
|
||||
import AskConsole, { type AskConsoleMessage } from './AskConsole'
|
||||
import { CHAT_INTENT_ID } from '@/lib/agent/ask/persist'
|
||||
import type { StoredStagedOperation } from '@/types'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import ContextChip from './ContextChip'
|
||||
import SandboxAgentPreview from './SandboxAgentPreview'
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import { useCompanyOptional } from '@/contexts/CompanyContext'
|
||||
|
||||
interface Props {
|
||||
conversationId: string
|
||||
intentId: string
|
||||
contextRef: string | null
|
||||
title: string
|
||||
rawMessages: { role: string; content: unknown; hidden?: boolean }[]
|
||||
// Proposals this conversation staged that are still awaiting an answer, so
|
||||
// the approval card reappears on resume instead of the proposal silently
|
||||
// waiting out its expiry in Granskning.
|
||||
stagedOperations?: StoredStagedOperation[]
|
||||
}
|
||||
|
||||
// Full-page conversation view. Wraps AgentChat with a header that shows the
|
||||
// title (or intent label). AgentChat handles the streaming + input + render.
|
||||
export default function ChatConversationView({
|
||||
conversationId,
|
||||
intentId,
|
||||
contextRef,
|
||||
title,
|
||||
rawMessages,
|
||||
stagedOperations,
|
||||
}: Props) {
|
||||
const initialMessages = useMemo(
|
||||
() => attachStagedOperations(normalizeStoredMessages(rawMessages), stagedOperations ?? []),
|
||||
[rawMessages, stagedOperations],
|
||||
)
|
||||
// general.help runs on the single-call console; it never stages operations,
|
||||
// so the thread is text-only. Empty turns (a historical pure-tool_use row
|
||||
// from the old runtime) are dropped rather than rendered as blank rows.
|
||||
const isSingleCall = intentId === CHAT_INTENT_ID
|
||||
const consoleMessages = useMemo<AskConsoleMessage[]>(
|
||||
() =>
|
||||
normalizeStoredMessages(rawMessages)
|
||||
.filter((m) => m.text.trim().length > 0)
|
||||
.map((m) => ({ role: m.role, text: m.text })),
|
||||
[rawMessages],
|
||||
)
|
||||
const { identity } = useAgentSheet()
|
||||
const companyCtx = useCompanyOptional()
|
||||
const isSandbox = companyCtx?.isSandbox ?? false
|
||||
const agentName = identity.displayName?.trim() || null
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="flex items-center gap-3 border-b border-border px-5 py-4 shrink-0">
|
||||
{/* Mobile-only back-to-list arrow. On desktop the sidebar is always
|
||||
visible so a back button would be redundant. */}
|
||||
<Link
|
||||
href="/chat"
|
||||
className="md:hidden inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors -ml-1"
|
||||
aria-label="Tillbaka till konversationer"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Link>
|
||||
<AgentAvatar
|
||||
avatarId={identity.avatarId}
|
||||
size="sm"
|
||||
alt={identity.displayName ?? 'Assistent'}
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<h1 className="font-display text-lg leading-tight tracking-tight truncate">{title}</h1>
|
||||
{/* Was printing context_ref raw, so the subtitle read
|
||||
"invoice:5f3a-9c21-...": a database identifier, shown to an
|
||||
accountant, under the title of their own conversation. */}
|
||||
<ContextChip contextRef={contextRef} className="mt-0.5" />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 min-h-0 flex flex-col">
|
||||
{isSandbox ? (
|
||||
<SandboxAgentPreview agentName={agentName} />
|
||||
) : isSingleCall ? (
|
||||
<AskConsole
|
||||
initialConversationId={conversationId}
|
||||
initialMessages={consoleMessages}
|
||||
contextRef={contextRef}
|
||||
scrollerClassName="px-6 py-8"
|
||||
/>
|
||||
) : (
|
||||
<AgentChat
|
||||
intentId={intentId}
|
||||
contextRef={contextRef ?? undefined}
|
||||
initialConversationId={conversationId}
|
||||
initialMessages={initialMessages}
|
||||
scrollerClassName="px-6 py-8"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
'use client'
|
||||
|
||||
import { ArrowUpRight, Sparkles } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import { useCompanyOptional, useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
|
||||
// Tiny client component for /chat empty state. Reads the agent identity from
|
||||
// the provider so it can show the user's chosen avatar + name above the
|
||||
// "starta en konversation" CTA.
|
||||
//
|
||||
// The three suggestion chips below the headline give users a one-click way
|
||||
// in. They navigate to /chat/new?intent=…&prompt=… which mounts AgentChat
|
||||
// inline and swaps to /chat/[id] once the conversation is created: so the
|
||||
// flow stays full-screen instead of opening a slide-in sheet.
|
||||
const SUGGESTIONS: { label: string; prompt: string }[] = [
|
||||
{
|
||||
label: 'Vad är min största utgiftspost den här månaden?',
|
||||
prompt: 'Vad är min största utgiftspost den här månaden? Visa de fem största kategorierna.',
|
||||
},
|
||||
{
|
||||
label: 'Hur ser min momsrapport ut för senaste perioden?',
|
||||
prompt: 'Hur ser min momsrapport ut för den senaste perioden? Vad blir moms att betala eller få tillbaka, och ser något ovanligt ut?',
|
||||
},
|
||||
{
|
||||
label: 'När är min nästa skatte- eller momsdeadline?',
|
||||
prompt: 'När är min nästa skatte- eller momsdeadline, och vad behöver jag göra inför den?',
|
||||
},
|
||||
]
|
||||
|
||||
export default function ChatEmptyState() {
|
||||
const { identity } = useAgentSheet()
|
||||
const companyCtx = useCompanyOptional()
|
||||
const router = useRouter()
|
||||
const isSandbox = companyCtx?.isSandbox ?? false
|
||||
const hasAi = useCapability(CAPABILITY.ai)
|
||||
const name = identity.displayName?.trim() || 'din assistent'
|
||||
|
||||
if (isSandbox) {
|
||||
const handleCreateAccount = async () => {
|
||||
const supabase = createClient()
|
||||
// Sign-out is best-effort: navigate even if Supabase is unreachable
|
||||
// so the button never looks dead.
|
||||
try {
|
||||
await supabase.auth.signOut()
|
||||
} catch {
|
||||
// Intentionally swallowed.
|
||||
}
|
||||
router.push('/register')
|
||||
}
|
||||
return (
|
||||
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
|
||||
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
|
||||
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
|
||||
<div className="rounded-lg border border-border bg-secondary/40 px-5 py-4 max-w-md mb-6 text-left">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Avstängd i sandlådan
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
|
||||
AI-assistenten använder en betald molntjänst och är därför
|
||||
inaktiverad här. I den fullständiga produkten kan {name} kategorisera
|
||||
transaktioner, granska leverantörsfakturor och svara på frågor om
|
||||
din bokföring.
|
||||
</p>
|
||||
</div>
|
||||
<Button size="lg" onClick={handleCreateAccount}>
|
||||
Skapa konto för att använda {name}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!hasAi) {
|
||||
return (
|
||||
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
|
||||
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
|
||||
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
|
||||
<div className="rounded-lg border border-border bg-secondary/40 px-5 py-4 max-w-md mb-6 text-left">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Ingår i abonnemanget
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
|
||||
AI-assistenten använder en betald molntjänst. Uppgradera för att låta
|
||||
{' '}{name} kategorisera transaktioner, granska leverantörsfakturor
|
||||
och svara på frågor om din bokföring.
|
||||
</p>
|
||||
</div>
|
||||
<Button size="lg" asChild>
|
||||
<Link href="/settings/billing">Uppgradera för att använda {name}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Hidden on mobile: the sidebar IS the page when no conversation is open.
|
||||
// On desktop, fills the right pane with a centered prompt.
|
||||
return (
|
||||
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
|
||||
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
|
||||
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
|
||||
<p className="text-muted-foreground max-w-md mb-6">
|
||||
Välj en konversation till vänster, eller starta en ny om något har dykt upp.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col gap-2 w-full max-w-md mb-6">
|
||||
{SUGGESTIONS.map((s) => (
|
||||
<Link
|
||||
key={s.label}
|
||||
href={`/chat/new?intent=general.help&prompt=${encodeURIComponent(s.prompt)}`}
|
||||
className="group flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-left text-sm transition-colors hover:border-foreground/30 hover:bg-secondary/30"
|
||||
>
|
||||
<span className="flex-1 text-muted-foreground group-hover:text-foreground transition-colors">
|
||||
{s.label}
|
||||
</span>
|
||||
<ArrowUpRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground/60 group-hover:text-foreground transition-colors" />
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Button size="lg" variant="outline" asChild>
|
||||
<Link href="/chat/new?intent=general.help">Eller skriv din egen fråga</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
'use client'
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useState } from 'react'
|
||||
import AgentChat from './AgentChat'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import SandboxAgentPreview from './SandboxAgentPreview'
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import { useCompanyOptional } from '@/contexts/CompanyContext'
|
||||
|
||||
// Phase C entry surface. Lands here from ReviewCard's "kör" after Phase B
|
||||
// verify succeeds. Renders AgentChat in fresh-start mode: no
|
||||
// initialConversationId, no initialMessages: so the auto-fire effect
|
||||
// kicks the first invoke. As soon as /api/agent/invoke emits the
|
||||
// conversation event, the URL swaps to /chat/[id] so reload / share /
|
||||
// browser-back all work like any other conversation.
|
||||
//
|
||||
// Plan refs: §7 Phase C.
|
||||
export default function ChatIntakeStarter() {
|
||||
const router = useRouter()
|
||||
const { identity } = useAgentSheet()
|
||||
const companyCtx = useCompanyOptional()
|
||||
const isSandbox = companyCtx?.isSandbox ?? false
|
||||
const agentName = identity.displayName?.trim() || 'Din assistent'
|
||||
// Lock the swap to the first id we see: defensive guard against the
|
||||
// AgentChat callback firing twice during React 19 Strict Mode reruns.
|
||||
const [swapped, setSwapped] = useState(false)
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="flex items-center gap-3 border-b border-border px-6 py-4 shrink-0">
|
||||
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName} />
|
||||
<div className="min-w-0">
|
||||
<h1 className="font-display text-lg tracking-tight truncate">{agentName} är redo</h1>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{isSandbox
|
||||
? 'Förhandsvisning: den verkliga konversationen kräver ett konto.'
|
||||
: 'Några frågor för att lära känna din verksamhet: svara i din egen takt, du kan avsluta när du vill.'}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 min-h-0 flex flex-col">
|
||||
{isSandbox ? (
|
||||
<SandboxAgentPreview agentName={agentName} />
|
||||
) : (
|
||||
<AgentChat
|
||||
intentId="onboarding.intake"
|
||||
initialMessages={[]}
|
||||
initialConversationId={null}
|
||||
onFirstTurnComplete={(id) => {
|
||||
// Wait for the greeting to finish streaming AND persist before
|
||||
// swapping the URL. Swapping on the early `conversation` event
|
||||
// unmounts AgentChat mid-stream, so the greeting is never saved
|
||||
// and /chat/[id] hydrates empty: the bug where the chat lands
|
||||
// blank and only shows the intro on a later visit.
|
||||
if (swapped) return
|
||||
setSwapped(true)
|
||||
router.replace(`/chat/${id}`)
|
||||
}}
|
||||
scrollerClassName="px-6 py-8"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
'use client'
|
||||
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useState } from 'react'
|
||||
import AgentChat from './AgentChat'
|
||||
import AskConsole from './AskConsole'
|
||||
import { CHAT_INTENT_ID } from '@/lib/agent/ask/persist'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import SandboxAgentPreview from './SandboxAgentPreview'
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import { useCompanyOptional } from '@/contexts/CompanyContext'
|
||||
|
||||
// Inline starter used by suggestion chips and ⌘K. Mirrors ChatIntakeStarter
|
||||
// but accepts any intent + seed so we don't fork the intake-specific
|
||||
// onboarding path. When AgentChat emits the new conversation_id, the URL
|
||||
// is swapped to /chat/[id] so reload / share / browser-back all work.
|
||||
export default function ChatNewStarter({
|
||||
intentId,
|
||||
seedUserMessage,
|
||||
}: {
|
||||
intentId: string
|
||||
seedUserMessage?: string
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const { identity } = useAgentSheet()
|
||||
const companyCtx = useCompanyOptional()
|
||||
const isSandbox = companyCtx?.isSandbox ?? false
|
||||
const agentName = identity.displayName?.trim() || 'Din assistent'
|
||||
const [swapped, setSwapped] = useState(false)
|
||||
const isSingleCall = intentId === CHAT_INTENT_ID
|
||||
|
||||
const swapToConversation = (id: string) => {
|
||||
// Swap once, after the turn is created. For the single-call console both
|
||||
// the question and the answer are already persisted by the time we get the
|
||||
// id back, so /chat/[id] hydrates the full thread.
|
||||
if (swapped) return
|
||||
setSwapped(true)
|
||||
router.replace(`/chat/${id}`)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="flex items-center gap-3 border-b border-border px-6 py-4 shrink-0">
|
||||
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName} />
|
||||
<div className="min-w-0">
|
||||
<h1 className="font-display text-lg tracking-tight truncate">{agentName}</h1>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{isSandbox ? 'Förhandsvisning: avstängd i sandlådan' : 'Ny konversation'}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 min-h-0 flex flex-col">
|
||||
{isSandbox ? (
|
||||
<SandboxAgentPreview agentName={agentName} />
|
||||
) : isSingleCall ? (
|
||||
<AskConsole
|
||||
seedUserMessage={seedUserMessage}
|
||||
initialConversationId={null}
|
||||
onConversationCreated={swapToConversation}
|
||||
scrollerClassName="px-6 py-8"
|
||||
/>
|
||||
) : (
|
||||
<AgentChat
|
||||
intentId={intentId}
|
||||
seedUserMessage={seedUserMessage}
|
||||
initialMessages={[]}
|
||||
initialConversationId={null}
|
||||
onFirstTurnComplete={(id) => {
|
||||
// Wait for the first turn to finish before swapping the URL:
|
||||
// otherwise the unmount aborts the in-flight stream and
|
||||
// /chat/[id] hydrates with only the user message.
|
||||
swapToConversation(id)
|
||||
}}
|
||||
scrollerClassName="px-6 py-8"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState, useTransition } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
import { Pin, PinOff, Archive, Pencil, Search, X, PanelLeftOpen, PanelLeftClose } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import {
|
||||
type ConversationRow,
|
||||
BUCKET_LABELS,
|
||||
relativeTime,
|
||||
intentLabel,
|
||||
} from './conversation-display'
|
||||
import { useConversationList } from './use-conversation-list'
|
||||
|
||||
interface Props {
|
||||
initialConversations: ConversationRow[]
|
||||
}
|
||||
|
||||
export default function ChatSidebar({ initialConversations }: Props) {
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const { openAgentSheet, identity } = useAgentSheet()
|
||||
const agentName = identity.displayName?.trim() || null
|
||||
// State + all three mutations live in the shared hook so this surface and the
|
||||
// in-sheet list cannot drift apart again. Pin/archive/rename here used to be
|
||||
// fire-and-forget with no rollback.
|
||||
const {
|
||||
conversations,
|
||||
query,
|
||||
setQuery,
|
||||
grouped,
|
||||
togglePin,
|
||||
archive: archiveConversation,
|
||||
editingId,
|
||||
editValue,
|
||||
setEditValue,
|
||||
startEdit,
|
||||
cancelEdit,
|
||||
commitEdit,
|
||||
} = useConversationList(initialConversations)
|
||||
const [, startTransition] = useTransition()
|
||||
// Collapsed by default; persisted across reloads so power users keep
|
||||
// their preference. Hidden behind a thin rail when collapsed so the
|
||||
// conversation pane runs nearly edge-to-edge.
|
||||
const [collapsed, setCollapsed] = useState(true)
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem('Accounted:chat-sidebar-collapsed')
|
||||
if (stored === 'false') setCollapsed(false)
|
||||
}, [])
|
||||
const toggleCollapsed = () => {
|
||||
setCollapsed(c => {
|
||||
const next = !c
|
||||
try { localStorage.setItem('Accounted:chat-sidebar-collapsed', next ? 'true' : 'false') } catch {}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const activeId = pathname?.startsWith('/chat/') ? pathname.split('/')[2] : null
|
||||
const isConversationOpen = !!activeId
|
||||
|
||||
|
||||
async function archive(id: string) {
|
||||
const removed = await archiveConversation(id)
|
||||
if (removed && activeId === id) startTransition(() => router.push('/chat'))
|
||||
}
|
||||
|
||||
// Collapsed rail (desktop only). Mobile keeps the existing behavior where
|
||||
// the sidebar IS the page when no conversation is open, so the rail is
|
||||
// hidden below md. On desktop the rail keeps a thin column with toggle
|
||||
// + new-chat buttons so the conversation pane runs near-edge-to-edge.
|
||||
const railAside = collapsed ? (
|
||||
<aside
|
||||
className="hidden md:flex md:w-12 flex-col items-center border-r border-border bg-card/40 shrink-0 py-3 gap-2"
|
||||
aria-label="Konversationer (hopfälld)"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleCollapsed}
|
||||
aria-label="Visa konversationer"
|
||||
title="Visa konversationer"
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
|
||||
>
|
||||
<PanelLeftOpen className="h-4 w-4" />
|
||||
</button>
|
||||
<div className="h-px w-6 bg-border" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openAgentSheet({ intentId: 'general.help' })}
|
||||
aria-label="Ny konversation"
|
||||
title="Ny konversation"
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors text-lg"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</aside>
|
||||
) : null
|
||||
|
||||
return (
|
||||
<>
|
||||
{railAside}
|
||||
<aside
|
||||
className={cn(
|
||||
'flex-col border-r border-border bg-card/40 shrink-0',
|
||||
// Mobile: sidebar IS the page when no conversation; hidden otherwise.
|
||||
isConversationOpen ? 'hidden' : 'flex w-full',
|
||||
// Desktop: hidden if collapsed (rail takes its place); else 320px.
|
||||
collapsed ? 'md:hidden' : 'md:flex md:w-80',
|
||||
)}
|
||||
>
|
||||
<div className="border-b border-border px-5 py-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName ?? 'Assistent'} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<h2 className="font-display text-base tracking-tight truncate">
|
||||
{agentName ?? 'Din assistent'}
|
||||
</h2>
|
||||
<p className="text-[11px] text-muted-foreground">Konversationer</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={toggleCollapsed}
|
||||
aria-label="Dölj konversationer"
|
||||
title="Dölj konversationer"
|
||||
className="hidden md:inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
|
||||
>
|
||||
<PanelLeftClose className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => openAgentSheet({ intentId: 'general.help' })}
|
||||
className="text-xs uppercase tracking-wider text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
+ Ny
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<input
|
||||
type="text"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Sök…"
|
||||
className="w-full rounded-lg border border-border bg-background pl-8 pr-7 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
/>
|
||||
{query.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setQuery('')}
|
||||
aria-label="Rensa sökning"
|
||||
className="absolute right-1 top-1/2 -translate-y-1/2 inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{grouped.length === 0 ? (
|
||||
<div className="p-6 text-sm text-muted-foreground">
|
||||
{conversations.length === 0
|
||||
? 'Inga konversationer ännu. Klicka på + Ny för att börja.'
|
||||
: 'Inga träffar.'}
|
||||
</div>
|
||||
) : (
|
||||
grouped.map(({ bucket, rows }) => (
|
||||
<section key={bucket} className="py-2">
|
||||
<p className="px-4 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
{BUCKET_LABELS[bucket]}
|
||||
</p>
|
||||
<ul className="space-y-1">
|
||||
{rows.map((c) => (
|
||||
<li key={c.id}>
|
||||
{editingId === c.id ? (
|
||||
<div className="px-4 py-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
onBlur={() => void commitEdit(c.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
;(e.target as HTMLInputElement).blur()
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
cancelEdit()
|
||||
}
|
||||
}}
|
||||
placeholder="Namnge konversationen…"
|
||||
maxLength={200}
|
||||
aria-label="Nytt namn på konversationen"
|
||||
className="w-full rounded-lg border border-border bg-background px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Link
|
||||
href={`/chat/${c.id}`}
|
||||
className={cn(
|
||||
'group flex items-start gap-2 px-4 py-2 hover:bg-secondary/60 transition-colors border-l-2',
|
||||
activeId === c.id
|
||||
? 'bg-secondary/50 border-foreground'
|
||||
: 'border-transparent',
|
||||
)}
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<p className="text-sm font-medium truncate flex-1 min-w-0">
|
||||
{c.title ?? intentLabel(c.intent_id)}
|
||||
</p>
|
||||
<p className="text-[11px] text-muted-foreground tabular-nums shrink-0">
|
||||
{relativeTime(c.last_message_at ?? c.created_at)}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">
|
||||
{c.last_message_preview ?? intentLabel(c.intent_id)}
|
||||
</p>
|
||||
</div>
|
||||
{/* Always-visible action icons. Touch-friendly, no
|
||||
hover-only invisibility on mobile. Laid out
|
||||
horizontally so three icons don't stack and inflate
|
||||
the row height. */}
|
||||
<div className="flex items-center gap-1 shrink-0 -mr-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
startEdit(c)
|
||||
}}
|
||||
title="Byt namn"
|
||||
aria-label="Byt namn på konversation"
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground/50 hover:text-foreground hover:bg-secondary transition-colors"
|
||||
>
|
||||
<Pencil className="h-3 w-3" />
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
void togglePin(c.id, c.pinned)
|
||||
}}
|
||||
title={c.pinned ? 'Avfäst' : 'Fäst'}
|
||||
aria-label={c.pinned ? 'Avfäst konversation' : 'Fäst konversation'}
|
||||
className={cn(
|
||||
'inline-flex h-8 w-8 items-center justify-center rounded-sm transition-colors',
|
||||
c.pinned
|
||||
? 'text-foreground'
|
||||
: 'text-muted-foreground/50 hover:text-foreground hover:bg-secondary',
|
||||
)}
|
||||
>
|
||||
{c.pinned ? (
|
||||
<Pin className="h-3 w-3" fill="currentColor" />
|
||||
) : (
|
||||
<PinOff className="h-3 w-3" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
void archive(c.id)
|
||||
}}
|
||||
title="Arkivera"
|
||||
aria-label="Arkivera konversation"
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground/50 hover:text-foreground hover:bg-secondary transition-colors"
|
||||
>
|
||||
<Archive className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { ArrowUpRight } from 'lucide-react'
|
||||
import { contextRefToTarget } from '@/lib/agent/intents/route-mapping'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* What a conversation is anchored to, as a chip.
|
||||
*
|
||||
* `agent_conversations.context_ref` has been written since the first intents
|
||||
* shipped. The panel ignored it entirely, and /chat printed it raw, so a
|
||||
* resumed thread's subtitle read "invoice:5f3a-9c21-...": a database
|
||||
* identifier shown to an accountant. Both surfaces now render the same chip,
|
||||
* which names the thing and links to it.
|
||||
*
|
||||
* Kind-agnostic on purpose (plan seam 8.4): the mapping lives in
|
||||
* route-mapping.ts, so teaching every surface about a new ref kind is one
|
||||
* entry in that map and no component change. A kind the map does not know
|
||||
* yet, a flow run for instance, renders nothing rather than a broken link.
|
||||
*/
|
||||
export default function ContextChip({
|
||||
contextRef,
|
||||
className,
|
||||
}: {
|
||||
contextRef: string | null | undefined
|
||||
className?: string
|
||||
}) {
|
||||
const target = contextRefToTarget(contextRef)
|
||||
if (!target) return null
|
||||
|
||||
const shape =
|
||||
'inline-flex max-w-full items-center gap-1 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground'
|
||||
|
||||
// Not every context has a page to go to: the document inbox is an extension
|
||||
// route, and core cannot hardcode a path that exists only when the extension
|
||||
// is enabled. Naming it without linking beats a link that 404s.
|
||||
if (!target.href) {
|
||||
return (
|
||||
<span className={cn(shape, className)}>
|
||||
<span className="truncate">{target.label}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={target.href}
|
||||
className={cn(
|
||||
shape,
|
||||
'hover:bg-secondary hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{target.label}</span>
|
||||
<ArrowUpRight className="h-3 w-3 shrink-0" />
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
'use client'
|
||||
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import Link from 'next/link'
|
||||
import { isInternalHref } from './markdown-links'
|
||||
|
||||
/**
|
||||
* Isolated so AgentChat can load the markdown parser (react-markdown +
|
||||
* remark-gfm and their unified/remark dependency tree) via next/dynamic:
|
||||
* the chunk is fetched when the first assistant message renders instead of
|
||||
* being parsed eagerly whenever the chat surface mounts.
|
||||
*/
|
||||
export default function MarkdownMessage({ text }: { text: string }) {
|
||||
return (
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} components={{ a: MarkdownLink }}>
|
||||
{text}
|
||||
</ReactMarkdown>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Links inside an answer.
|
||||
*
|
||||
* These were plain anchors, so following one the agent had written did a full
|
||||
* document load: the whole app rebooted and the conversation went with it, in
|
||||
* the panel and in /chat alike. Internal links now route client-side, which
|
||||
* keeps the thread alive beside the page the user just opened, which is the
|
||||
* point of docking the panel in the first place.
|
||||
*
|
||||
* External links open in a new tab for the same reason, and carry
|
||||
* rel="noopener noreferrer": the href came out of a model that reads customer
|
||||
* documents, and target="_blank" without it hands the opened page a
|
||||
* window.opener handle back into an authenticated session.
|
||||
*/
|
||||
function MarkdownLink({
|
||||
href,
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
href?: string
|
||||
// Markdown carries an optional title: [text](url "title"). Dropping it here
|
||||
// would silently discard something the answer's author wrote.
|
||||
title?: string
|
||||
children?: React.ReactNode
|
||||
}) {
|
||||
if (!href) return <>{children}</>
|
||||
|
||||
if (isInternalHref(href)) {
|
||||
return (
|
||||
<Link href={href} title={title} className="underline underline-offset-2">
|
||||
{children}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
title={title}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="underline underline-offset-2"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { Sparkles, ArrowRight } from 'lucide-react'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
|
||||
/**
|
||||
* Stand-in for AgentChat in the sandbox. The real chat surface POSTs to
|
||||
* /api/agent/invoke which is server-gated by guardSandbox(), so the input
|
||||
* would just produce a 403. Instead of showing that as a raw error, we
|
||||
* render a brief description of what the assistant does in prod and a
|
||||
* single "Skapa konto" CTA. Same chrome (header) as the real chat: only
|
||||
* the body swaps out.
|
||||
*
|
||||
* Mirrors the look of the empty-state but with an explanation block so the
|
||||
* sandbox user understands what they're seeing without typing into a
|
||||
* dead-end input.
|
||||
*/
|
||||
export default function SandboxAgentPreview({
|
||||
agentName,
|
||||
}: {
|
||||
agentName: string | null
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const name = agentName?.trim() || 'din assistent'
|
||||
|
||||
async function handleCreateAccount() {
|
||||
const supabase = createClient()
|
||||
// Sign-out is best-effort: a transient Supabase failure shouldn't
|
||||
// strand the user on a dead button; navigate to /register either way
|
||||
// and let the registration flow re-init auth state.
|
||||
try {
|
||||
await supabase.auth.signOut()
|
||||
} catch {
|
||||
// Intentionally swallowed: see comment above.
|
||||
}
|
||||
router.push('/register')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col">
|
||||
<div className="flex-1 overflow-y-auto px-5 py-8">
|
||||
<div className="mx-auto max-w-md space-y-6">
|
||||
<div className="rounded-lg border border-border bg-secondary/40 p-5">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Förhandsvisning i sandlådan
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
|
||||
{name} är en specialiserad bokföringsassistent som kan
|
||||
kategorisera transaktioner, granska leverantörsfakturor och
|
||||
svara på frågor om din bokföring: kalibrerad mot dina
|
||||
kontoplaner, verksamhet och svensk skattelagstiftning.
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-3 leading-relaxed">
|
||||
I sandlådan är AI-funktionerna avstängda eftersom de använder
|
||||
externa AI-tjänster som kostar pengar att köra. Skapa ett
|
||||
konto för att aktivera assistenten på riktigt.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ul className="space-y-2 text-sm text-muted-foreground">
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-foreground mt-0.5">·</span>
|
||||
<span>
|
||||
<span className="text-foreground">Föreslår bokföring</span>{' '}
|
||||
för oklassificerade transaktioner: du godkänner i ett klick.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-foreground mt-0.5">·</span>
|
||||
<span>
|
||||
<span className="text-foreground">Förklarar momsrutor</span>,
|
||||
årets resultat och vad som driver KPI:erna.
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-foreground mt-0.5">·</span>
|
||||
<span>
|
||||
<span className="text-foreground">Granskar verifikat</span>{' '}
|
||||
och föreslår rättningar enligt BFL och K2.
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border px-5 pt-4 pb-[calc(env(safe-area-inset-bottom,0px)+1rem)]">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
className="flex-1"
|
||||
onClick={handleCreateAccount}
|
||||
>
|
||||
Skapa konto för att använda {name}
|
||||
<ArrowRight className="ml-1.5 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="mt-2 text-[11px] text-muted-foreground">
|
||||
Sandlådedata raderas efter 24 timmar.{' '}
|
||||
<Link href="/register" className="underline underline-offset-2 hover:text-foreground">
|
||||
Skapa konto
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
INITIAL_AGENT_STATUS,
|
||||
collapsedStatusLabel,
|
||||
reduceAgentStatus,
|
||||
type AgentStatus,
|
||||
type AgentStatusEvent,
|
||||
} from '../agent-status'
|
||||
|
||||
/**
|
||||
* What this protects: a user who minimizes the panel mid-answer used to lose
|
||||
* every signal about it. The reducer is what decides whether the trigger says
|
||||
* "arbetar", "är klar", or nothing at all, so these are the real transitions,
|
||||
* not a description of them.
|
||||
*/
|
||||
function run(events: AgentStatusEvent[], from: AgentStatus = INITIAL_AGENT_STATUS): AgentStatus {
|
||||
return events.reduce(reduceAgentStatus, from)
|
||||
}
|
||||
|
||||
describe('reduceAgentStatus', () => {
|
||||
it('reports a finished turn only when it finished out of sight', () => {
|
||||
const onScreen = run([{ type: 'turn_start' }, { type: 'turn_end' }])
|
||||
expect(onScreen.activity).toBe('idle')
|
||||
|
||||
const hidden = run([
|
||||
{ type: 'turn_start' },
|
||||
{ type: 'visibility', visible: false },
|
||||
{ type: 'turn_end' },
|
||||
])
|
||||
expect(hidden.activity).toBe('done')
|
||||
})
|
||||
|
||||
it('clears the finished-turn signal once the panel is back on screen', () => {
|
||||
const seen = run([
|
||||
{ type: 'turn_start' },
|
||||
{ type: 'visibility', visible: false },
|
||||
{ type: 'turn_end' },
|
||||
{ type: 'visibility', visible: true },
|
||||
])
|
||||
expect(seen.activity).toBe('idle')
|
||||
expect(seen.step).toBeNull()
|
||||
})
|
||||
|
||||
it('does not cancel work that is still running when the panel reopens', () => {
|
||||
// Reopening mid-answer must not read as "nothing is happening": the pill
|
||||
// would go quiet while the turn was still streaming.
|
||||
const stillWorking = run([
|
||||
{ type: 'turn_start' },
|
||||
{ type: 'step', label: 'Bokar avskrivningar…' },
|
||||
{ type: 'visibility', visible: false },
|
||||
{ type: 'visibility', visible: true },
|
||||
])
|
||||
expect(stillWorking.activity).toBe('working')
|
||||
expect(stillWorking.step).toBe('Bokar avskrivningar…')
|
||||
})
|
||||
|
||||
it('keeps the latest step and drops it when the turn ends', () => {
|
||||
const mid = run([
|
||||
{ type: 'turn_start' },
|
||||
{ type: 'step', label: 'Hämtar underlag…' },
|
||||
{ type: 'step', label: 'Bokar avskrivningar…' },
|
||||
])
|
||||
expect(mid.step).toBe('Bokar avskrivningar…')
|
||||
expect(reduceAgentStatus(mid, { type: 'turn_end' }).step).toBeNull()
|
||||
})
|
||||
|
||||
it('treats a step for work it never saw start as working', () => {
|
||||
// A stream resumed after a remount can deliver a tool event with no
|
||||
// turn_start behind it; dropping it would leave the pill idle mid-turn.
|
||||
expect(reduceAgentStatus(INITIAL_AGENT_STATUS, { type: 'step', label: 'Bokar…' }).activity).toBe(
|
||||
'working',
|
||||
)
|
||||
})
|
||||
|
||||
it('remembers visibility across a reset so the next turn reports correctly', () => {
|
||||
const afterReset = run([
|
||||
{ type: 'visibility', visible: false },
|
||||
{ type: 'turn_start' },
|
||||
{ type: 'reset' },
|
||||
{ type: 'turn_start' },
|
||||
{ type: 'turn_end' },
|
||||
])
|
||||
expect(afterReset.activity).toBe('done')
|
||||
})
|
||||
|
||||
it('carries the detached state built for durable runs', () => {
|
||||
// Nothing dispatches this in v1. It exists so a background run publishes to
|
||||
// this channel instead of the pill needing a second one.
|
||||
const detached = reduceAgentStatus(INITIAL_AGENT_STATUS, {
|
||||
type: 'detached',
|
||||
label: 'Kör momsavstämning',
|
||||
})
|
||||
expect(detached.activity).toBe('detached')
|
||||
expect(collapsedStatusLabel(detached, 'Anna')).toBe('Kör momsavstämning')
|
||||
})
|
||||
})
|
||||
|
||||
describe('collapsedStatusLabel', () => {
|
||||
it('says nothing when there is nothing to say', () => {
|
||||
expect(collapsedStatusLabel(INITIAL_AGENT_STATUS, 'Anna')).toBeNull()
|
||||
})
|
||||
|
||||
it('drops the narration ellipsis so the pill does not read as two spinners', () => {
|
||||
const working = run([{ type: 'turn_start' }, { type: 'step', label: 'Bokar avskrivningar…' }])
|
||||
expect(collapsedStatusLabel(working, 'Anna')).toBe('Bokar avskrivningar')
|
||||
})
|
||||
|
||||
it('falls back to the agent name while working without a named step', () => {
|
||||
expect(collapsedStatusLabel(run([{ type: 'turn_start' }]), 'Anna')).toBe('Anna arbetar')
|
||||
})
|
||||
|
||||
it('announces a finished turn by name', () => {
|
||||
const done = run([
|
||||
{ type: 'visibility', visible: false },
|
||||
{ type: 'turn_start' },
|
||||
{ type: 'turn_end' },
|
||||
])
|
||||
expect(collapsedStatusLabel(done, 'Anna')).toBe('Anna är klar')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { attachStagedOperations } from '../AgentChat'
|
||||
import type { StoredStagedOperation } from '@/types'
|
||||
|
||||
/**
|
||||
* Approval cards ride on streamed `staged_operation` events, which are never
|
||||
* persisted. Without re-attaching them, reopening a conversation showed the
|
||||
* tool trace and the answer but no card, so an unapproved proposal waited out
|
||||
* its full 30-day expiry in Granskning with nothing in the thread pointing at
|
||||
* it. This is the reattachment.
|
||||
*/
|
||||
|
||||
const op = (overrides: Partial<StoredStagedOperation> = {}): StoredStagedOperation => ({
|
||||
id: 'op-1',
|
||||
// As actually stored: pending_operations.operation_type is the bare action
|
||||
// name, verified against prod (categorize_transaction / create_voucher /
|
||||
// approve_supplier_invoice are the values in the wild).
|
||||
operation_type: 'categorize_transaction',
|
||||
title: 'Kontering: Circle K, 689 kr',
|
||||
risk_level: 'low',
|
||||
preview_data: { lines: [] },
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('attachStagedOperations', () => {
|
||||
it('returns the thread untouched when nothing is pending', () => {
|
||||
const messages = [
|
||||
{ role: 'user' as const, text: 'boka om' },
|
||||
{ role: 'assistant' as const, text: 'klart' },
|
||||
]
|
||||
expect(attachStagedOperations(messages, [])).toBe(messages)
|
||||
})
|
||||
|
||||
it('attaches a pending proposal to the last assistant turn', () => {
|
||||
const messages = [
|
||||
{ role: 'user' as const, text: 'boka om Circle K' },
|
||||
{ role: 'assistant' as const, text: 'Klart att godkänna.' },
|
||||
]
|
||||
|
||||
const [, assistant] = attachStagedOperations(messages, [op()])
|
||||
|
||||
expect(assistant!.staged).toHaveLength(1)
|
||||
expect(assistant!.staged![0]).toMatchObject({
|
||||
operation_id: 'op-1',
|
||||
risk_level: 'low',
|
||||
operation_type: 'categorize_transaction',
|
||||
message: 'Kontering: Circle K, 689 kr',
|
||||
})
|
||||
})
|
||||
|
||||
it('passes the stored operation_type through untranslated, for EVERY type', () => {
|
||||
// The predecessor mapped operation_type onto an MCP tool name here and
|
||||
// ApprovalCard's old preview dispatch only recognized 4 of them, so a
|
||||
// hydrated attach_document_to_transaction card (among others) silently
|
||||
// fell back to the raw generic preview. The stored bare name now drives
|
||||
// the dispatch directly; nothing may rewrite it on the way.
|
||||
for (const t of [
|
||||
'categorize_transaction',
|
||||
'create_invoice',
|
||||
'create_voucher',
|
||||
'correct_entry',
|
||||
'attach_document_to_transaction',
|
||||
'match_transaction_invoice',
|
||||
'create_customer',
|
||||
'create_transaction',
|
||||
]) {
|
||||
const out = attachStagedOperations(
|
||||
[{ role: 'assistant', text: 'svar' }],
|
||||
[op({ operation_type: t })],
|
||||
)
|
||||
expect(out[0]!.staged![0]!.operation_type).toBe(t)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps risk level for medium and high, and floors anything unknown to low', () => {
|
||||
const messages = [{ role: 'assistant' as const, text: 'svar' }]
|
||||
|
||||
const risks = (level: string | null) =>
|
||||
attachStagedOperations(messages, [op({ risk_level: level })])[0]!.staged![0]!.risk_level
|
||||
|
||||
expect(risks('high')).toBe('high')
|
||||
expect(risks('medium')).toBe('medium')
|
||||
// An unrecognized value must not silently render as a one-click low-risk
|
||||
// approval... but it also must not crash: low is the safe render, and the
|
||||
// server re-checks risk on commit regardless.
|
||||
expect(risks('nonsense')).toBe('low')
|
||||
expect(risks(null)).toBe('low')
|
||||
})
|
||||
|
||||
it('preserves staged cards already on the message', () => {
|
||||
const messages = [
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
text: 'svar',
|
||||
staged: [
|
||||
{
|
||||
tool_use_id: 'tu_live',
|
||||
operation_id: 'op-live',
|
||||
risk_level: 'low' as const,
|
||||
message: 'redan här',
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const out = attachStagedOperations(messages, [op({ id: 'op-2' })])
|
||||
|
||||
expect(out[0]!.staged!.map((s) => s.operation_id)).toEqual(['op-live', 'op-2'])
|
||||
})
|
||||
|
||||
it('appends a carrier turn when the thread has no assistant message', () => {
|
||||
// Defensive: a conversation whose assistant turn was never persisted still
|
||||
// has to show its proposal rather than swallow it.
|
||||
const out = attachStagedOperations([{ role: 'user', text: 'boka' }], [op()])
|
||||
|
||||
expect(out).toHaveLength(2)
|
||||
expect(out[1]!.role).toBe('assistant')
|
||||
expect(out[1]!.staged).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('attaches to the LAST assistant turn, not the first', () => {
|
||||
const messages = [
|
||||
{ role: 'assistant' as const, text: 'första' },
|
||||
{ role: 'user' as const, text: 'och sen?' },
|
||||
{ role: 'assistant' as const, text: 'andra' },
|
||||
]
|
||||
|
||||
const out = attachStagedOperations(messages, [op()])
|
||||
|
||||
expect(out[0]!.staged).toBeUndefined()
|
||||
expect(out[2]!.staged).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('gives every hydrated card a distinct tool_use_id key', () => {
|
||||
const out = attachStagedOperations(
|
||||
[{ role: 'assistant', text: 'svar' }],
|
||||
[op({ id: 'op-a' }), op({ id: 'op-b' })],
|
||||
)
|
||||
|
||||
const keys = out[0]!.staged!.map((s) => s.tool_use_id)
|
||||
expect(new Set(keys).size).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { AVATAR_OPTIONS, getAvatarUrl } from '../avatars'
|
||||
|
||||
/**
|
||||
* These avatars used to be fetched from api.dicebear.com on every render, so
|
||||
* every authenticated page view of an accounting product told a third party
|
||||
* who was looking at it, and a firewalled or self-hosted install showed no
|
||||
* faces at all. The point of these tests is that the registry cannot quietly
|
||||
* drift back to a remote URL, and that every entry actually has a file.
|
||||
*/
|
||||
|
||||
const PUBLIC_DIR = join(process.cwd(), 'public')
|
||||
|
||||
describe('AVATAR_OPTIONS', () => {
|
||||
it('serves every avatar from our own origin', () => {
|
||||
for (const option of AVATAR_OPTIONS) {
|
||||
expect(option.url.startsWith('/'), `${option.id} must be a local path`).toBe(true)
|
||||
expect(option.url).not.toMatch(/^https?:/)
|
||||
expect(option.url).not.toContain('dicebear.com')
|
||||
}
|
||||
})
|
||||
|
||||
it('has a real file behind every entry', () => {
|
||||
// A registry entry with no file renders a broken image, which looks like a
|
||||
// bug in the agent rather than a missing asset.
|
||||
for (const option of AVATAR_OPTIONS) {
|
||||
expect(existsSync(join(PUBLIC_DIR, option.url)), `missing file for ${option.id}`).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('ships avatars that make no network requests of their own', () => {
|
||||
// Self-hosting the file is pointless if the file then phones home. This
|
||||
// asserts the PROPERTY (nothing points off-origin) rather than a list of
|
||||
// elements: an allowlist of <image> and xlink:href would still let a
|
||||
// future asset through via <use href>, <feImage href>, or a
|
||||
// scheme-relative //host, which is how this sort of guard rots.
|
||||
for (const option of AVATAR_OPTIONS) {
|
||||
const svg = readFileSync(join(PUBLIC_DIR, option.url), 'utf8')
|
||||
|
||||
// Namespace declarations and the licence metadata legitimately contain
|
||||
// URLs and are never fetched, so they are removed before the check
|
||||
// rather than special-cased inside it.
|
||||
const referencing = svg
|
||||
.replace(/<metadata[\s\S]*?<\/metadata>/gi, '')
|
||||
.replace(/xmlns(:[a-z0-9-]+)?\s*=\s*"[^"]*"/gi, '')
|
||||
.replace(/xsi:type\s*=\s*"[^"]*"/gi, '')
|
||||
|
||||
expect(referencing, `${option.id} references an absolute URL`).not.toMatch(/https?:\/\//i)
|
||||
// Scheme-relative: "//host/x" inherits the page's scheme and still
|
||||
// leaves the origin.
|
||||
expect(referencing, `${option.id} references a scheme-relative URL`).not.toMatch(
|
||||
/(href|src)\s*=\s*"\/\//i,
|
||||
)
|
||||
expect(referencing).not.toMatch(/url\(\s*['"]?\/\//i)
|
||||
expect(referencing, `${option.id} contains a script`).not.toMatch(/<script/i)
|
||||
expect(referencing, `${option.id} contains a foreignObject`).not.toMatch(/<foreignObject/i)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps ids and files one-to-one', () => {
|
||||
const ids = AVATAR_OPTIONS.map((a) => a.id)
|
||||
const urls = AVATAR_OPTIONS.map((a) => a.url)
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
expect(new Set(urls).size).toBe(urls.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAvatarUrl', () => {
|
||||
it('resolves a known id and returns null otherwise', () => {
|
||||
expect(getAvatarUrl('notionists-1')).toBe('/agent-avatars/notionists-1.svg')
|
||||
// Null is what makes AgentAvatar fall back to its glyph, so an id from an
|
||||
// older profile degrades to a placeholder rather than a broken image.
|
||||
expect(getAvatarUrl('notionists-99')).toBeNull()
|
||||
expect(getAvatarUrl(null)).toBeNull()
|
||||
expect(getAvatarUrl(undefined)).toBeNull()
|
||||
expect(getAvatarUrl('')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not resolve inherited Object keys', () => {
|
||||
expect(getAvatarUrl('toString')).toBeNull()
|
||||
expect(getAvatarUrl('constructor')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,246 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { ConversationRow } from '../conversation-display'
|
||||
import {
|
||||
createRevisionGuard,
|
||||
patchConversation,
|
||||
removeRow,
|
||||
restoreRow,
|
||||
runOptimisticPatch,
|
||||
setPinned,
|
||||
setTitle,
|
||||
} from '../conversation-mutations'
|
||||
|
||||
/**
|
||||
* These exercise the REAL transforms and the real write coordinator, not copies
|
||||
* of them: deleting the rollback or the response check makes this suite fail.
|
||||
*
|
||||
* What is being protected: the /chat sidebar used to fire pin, archive and
|
||||
* rename blind, so a failed archive removed a row that still existed on the
|
||||
* server and a failed rename showed a title the server never saved, both until
|
||||
* the next reload.
|
||||
*/
|
||||
|
||||
const row = (over: Partial<ConversationRow> = {}): ConversationRow => ({
|
||||
id: 'c1',
|
||||
intent_id: 'general.help',
|
||||
context_ref: null,
|
||||
title: 'Juli mot juni',
|
||||
pinned: false,
|
||||
archived: false,
|
||||
last_message_at: '2026-07-26T10:00:00Z',
|
||||
last_message_preview: 'Juli gick 12 procent bättre',
|
||||
created_at: '2026-07-26T09:00:00Z',
|
||||
...over,
|
||||
})
|
||||
|
||||
/** Minimal stand-in for React's setState updater contract. */
|
||||
function fakeState(initial: ConversationRow[]) {
|
||||
let current = initial
|
||||
return {
|
||||
set: (updater: (prev: ConversationRow[]) => ConversationRow[]) => {
|
||||
current = updater(current)
|
||||
},
|
||||
get list() {
|
||||
return current
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
// restoreAllMocks does not undo vi.stubGlobal, so the stubbed fetch would
|
||||
// otherwise outlive this file.
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('restoreRow', () => {
|
||||
it('puts an archived row back into the CURRENT list, keeping later changes', () => {
|
||||
const a = row({ id: 'a', last_message_at: '2026-07-26T12:00:00Z' })
|
||||
const b = row({ id: 'b', last_message_at: '2026-07-26T11:00:00Z' })
|
||||
// While the archive of `a` was in flight, the user renamed `b`.
|
||||
const currentAfterOtherEdit = [{ ...b, title: 'Nytt namn' }]
|
||||
|
||||
const restored = restoreRow(currentAfterOtherEdit, a)
|
||||
|
||||
expect(restored.map((c) => c.id)).toEqual(['a', 'b'])
|
||||
// The concurrent rename must survive: restoring a stale snapshot of the
|
||||
// whole list would have thrown it away.
|
||||
expect(restored.find((c) => c.id === 'b')!.title).toBe('Nytt namn')
|
||||
})
|
||||
|
||||
it('re-inserts by the server ordering: pinned first, then most recent', () => {
|
||||
const pinned = row({ id: 'p', pinned: true })
|
||||
const newer = row({ id: 'n', last_message_at: '2026-07-26T12:00:00Z' })
|
||||
const older = row({ id: 'o', last_message_at: '2026-07-20T12:00:00Z' })
|
||||
|
||||
expect(restoreRow([newer, older], pinned).map((c) => c.id)).toEqual(['p', 'n', 'o'])
|
||||
expect(
|
||||
restoreRow([pinned, older], row({ id: 'mid', last_message_at: '2026-07-25T12:00:00Z' })).map(
|
||||
(c) => c.id,
|
||||
),
|
||||
).toEqual(['p', 'mid', 'o'])
|
||||
})
|
||||
|
||||
it('is a no-op when the row is already present', () => {
|
||||
const list = [row({ id: 'a' })]
|
||||
expect(restoreRow(list, row({ id: 'a' }))).toBe(list)
|
||||
})
|
||||
})
|
||||
|
||||
describe('runOptimisticPatch', () => {
|
||||
it('applies immediately and keeps the change when the server accepts it', async () => {
|
||||
const state = fakeState([row({ id: 'c1' })])
|
||||
const ok = await runOptimisticPatch({
|
||||
id: 'c1',
|
||||
body: { pinned: true },
|
||||
apply: (l) => setPinned(l, 'c1', true),
|
||||
revert: (l) => setPinned(l, 'c1', false),
|
||||
setList: state.set,
|
||||
guard: createRevisionGuard(),
|
||||
onError: () => {},
|
||||
patch: async () => true,
|
||||
})
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(state.list[0]!.pinned).toBe(true)
|
||||
})
|
||||
|
||||
it('reverts and reports when the server refuses', async () => {
|
||||
const state = fakeState([row({ id: 'c1', title: 'Original' })])
|
||||
const onError = vi.fn()
|
||||
|
||||
const ok = await runOptimisticPatch({
|
||||
id: 'c1',
|
||||
body: { title: 'Nytt' },
|
||||
apply: (l) => setTitle(l, 'c1', 'Nytt'),
|
||||
revert: (l) => setTitle(l, 'c1', 'Original'),
|
||||
setList: state.set,
|
||||
guard: createRevisionGuard(),
|
||||
onError,
|
||||
patch: async () => false,
|
||||
})
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(state.list[0]!.title).toBe('Original')
|
||||
expect(onError).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('does not roll back over a newer write to the same row', async () => {
|
||||
// Double-click on pin: the first request fails AFTER the second has already
|
||||
// set the newer value. Reverting here would clobber it.
|
||||
const state = fakeState([row({ id: 'c1', pinned: false })])
|
||||
const guard = createRevisionGuard()
|
||||
const onError = vi.fn()
|
||||
|
||||
let releaseFirst: (v: boolean) => void = () => {}
|
||||
const first = runOptimisticPatch({
|
||||
id: 'c1',
|
||||
body: { pinned: true },
|
||||
apply: (l) => setPinned(l, 'c1', true),
|
||||
revert: (l) => setPinned(l, 'c1', false),
|
||||
setList: state.set,
|
||||
guard,
|
||||
onError,
|
||||
patch: () => new Promise<boolean>((resolve) => (releaseFirst = resolve)),
|
||||
})
|
||||
|
||||
// Second write lands and succeeds while the first is still in flight.
|
||||
await runOptimisticPatch({
|
||||
id: 'c1',
|
||||
body: { pinned: false },
|
||||
apply: (l) => setPinned(l, 'c1', false),
|
||||
revert: (l) => setPinned(l, 'c1', true),
|
||||
setList: state.set,
|
||||
guard,
|
||||
onError,
|
||||
patch: async () => true,
|
||||
})
|
||||
|
||||
releaseFirst(false)
|
||||
await first
|
||||
|
||||
// The newer write owns the row: its value stands and no error is shown for
|
||||
// a change the user already superseded.
|
||||
expect(state.list[0]!.pinned).toBe(false)
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still rolls back a stale write to a DIFFERENT row', async () => {
|
||||
const state = fakeState([row({ id: 'a', pinned: false }), row({ id: 'b', pinned: false })])
|
||||
const guard = createRevisionGuard()
|
||||
const onError = vi.fn()
|
||||
|
||||
await runOptimisticPatch({
|
||||
id: 'b',
|
||||
body: { pinned: true },
|
||||
apply: (l) => setPinned(l, 'b', true),
|
||||
revert: (l) => setPinned(l, 'b', false),
|
||||
setList: state.set,
|
||||
guard,
|
||||
onError,
|
||||
patch: async () => true,
|
||||
})
|
||||
await runOptimisticPatch({
|
||||
id: 'a',
|
||||
body: { pinned: true },
|
||||
apply: (l) => setPinned(l, 'a', true),
|
||||
revert: (l) => setPinned(l, 'a', false),
|
||||
setList: state.set,
|
||||
guard,
|
||||
onError,
|
||||
patch: async () => false,
|
||||
})
|
||||
|
||||
expect(state.list.find((c) => c.id === 'a')!.pinned).toBe(false)
|
||||
expect(state.list.find((c) => c.id === 'b')!.pinned).toBe(true)
|
||||
expect(onError).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('restores an archived row into the list as it stands when the request fails', async () => {
|
||||
const archived = row({ id: 'a', last_message_at: '2026-07-26T12:00:00Z' })
|
||||
const other = row({ id: 'b', last_message_at: '2026-07-26T11:00:00Z' })
|
||||
const state = fakeState([archived, other])
|
||||
|
||||
await runOptimisticPatch({
|
||||
id: 'a',
|
||||
body: { archived: true },
|
||||
apply: (l) => removeRow(l, 'a'),
|
||||
revert: (l) => restoreRow(l, archived),
|
||||
setList: state.set,
|
||||
guard: createRevisionGuard(),
|
||||
onError: () => {},
|
||||
patch: async () => false,
|
||||
})
|
||||
|
||||
expect(state.list.map((c) => c.id)).toEqual(['a', 'b'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('patchConversation', () => {
|
||||
it('reports failure for a non-2xx instead of assuming success', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 403 }))
|
||||
expect(await patchConversation('c1', { pinned: true })).toBe(false)
|
||||
})
|
||||
|
||||
it('reports failure when the request throws (offline)', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')))
|
||||
// Must not reject: an unhandled rejection was the old behaviour.
|
||||
expect(await patchConversation('c1', { pinned: true })).toBe(false)
|
||||
})
|
||||
|
||||
it('sends the PATCH to the conversation endpoint', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await patchConversation('c1', { archived: true })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/agent/conversations/c1',
|
||||
expect.objectContaining({ method: 'PATCH', body: JSON.stringify({ archived: true }) }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { sendFeedback } from '../feedback-client'
|
||||
|
||||
/**
|
||||
* The thumbs shipped wired to nothing: they lit up and the vote died in
|
||||
* component state. These pin the contract the button now depends on, in
|
||||
* particular that a failed send reports false, because the pressed state is
|
||||
* set from this return value and must never claim a report that never arrived.
|
||||
*/
|
||||
|
||||
describe('sendFeedback', () => {
|
||||
it('posts the vote to the feedback endpoint', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue({ ok: true })
|
||||
|
||||
const ok = await sendFeedback({
|
||||
conversationId: 'c1',
|
||||
sentiment: 'negative',
|
||||
messageIndex: 3,
|
||||
fetchImpl: fetchImpl as unknown as typeof fetch,
|
||||
})
|
||||
|
||||
expect(ok).toBe(true)
|
||||
const [url, init] = fetchImpl.mock.calls[0]!
|
||||
expect(url).toBe('/api/agent/feedback')
|
||||
expect(init.method).toBe('POST')
|
||||
expect(JSON.parse(init.body)).toEqual({
|
||||
conversation_id: 'c1',
|
||||
sentiment: 'negative',
|
||||
message_index: 3,
|
||||
})
|
||||
})
|
||||
|
||||
it('omits the message index rather than sending null for it', async () => {
|
||||
// The route validates message_index as an integer when present; sending
|
||||
// null would fail validation and lose the vote for no reason.
|
||||
const fetchImpl = vi.fn().mockResolvedValue({ ok: true })
|
||||
await sendFeedback({
|
||||
conversationId: 'c1',
|
||||
sentiment: 'positive',
|
||||
fetchImpl: fetchImpl as unknown as typeof fetch,
|
||||
})
|
||||
expect(JSON.parse(fetchImpl.mock.calls[0]![1].body)).toEqual({
|
||||
conversation_id: 'c1',
|
||||
sentiment: 'positive',
|
||||
})
|
||||
})
|
||||
|
||||
it('reports failure for a non-2xx instead of assuming it landed', async () => {
|
||||
const fetchImpl = vi.fn().mockResolvedValue({ ok: false, status: 404 })
|
||||
expect(
|
||||
await sendFeedback({
|
||||
conversationId: 'c1',
|
||||
sentiment: 'positive',
|
||||
fetchImpl: fetchImpl as unknown as typeof fetch,
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('reports failure instead of throwing when the request dies', async () => {
|
||||
// Offline, or the request cut off by a navigation. An unhandled rejection
|
||||
// here would surface as an error in the middle of reading an answer.
|
||||
const fetchImpl = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))
|
||||
await expect(
|
||||
sendFeedback({
|
||||
conversationId: 'c1',
|
||||
sentiment: 'negative',
|
||||
fetchImpl: fetchImpl as unknown as typeof fetch,
|
||||
}),
|
||||
).resolves.toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { isInternalHref } from '../markdown-links'
|
||||
import { ANNOUNCEMENT_LIMIT, announceableAnswer } from '../AgentChat'
|
||||
import { intentLabel } from '../conversation-display'
|
||||
|
||||
describe('isInternalHref', () => {
|
||||
it('routes app paths client-side', () => {
|
||||
expect(isInternalHref('/invoices/abc-123')).toBe(true)
|
||||
expect(isInternalHref('/bookkeeping/year-end?step=2')).toBe(true)
|
||||
expect(isInternalHref('/kpi#marginal')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not treat a protocol-relative url as internal', () => {
|
||||
// The href comes out of a model that reads customer documents. "//host"
|
||||
// starts with a slash but leaves the site, and handing it to the router as
|
||||
// an app path is the one failure mode worth engineering against.
|
||||
expect(isInternalHref('//evil.example/login')).toBe(false)
|
||||
expect(isInternalHref('/\\evil.example')).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves absolute and non-http schemes external', () => {
|
||||
expect(isInternalHref('https://skatteverket.se')).toBe(false)
|
||||
expect(isInternalHref('http://example.com')).toBe(false)
|
||||
expect(isInternalHref('mailto:[email protected]')).toBe(false)
|
||||
expect(isInternalHref('javascript:alert(1)')).toBe(false)
|
||||
expect(isInternalHref('')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('announceableAnswer', () => {
|
||||
const msg = (role: 'user' | 'assistant', text: string) =>
|
||||
({ role, text }) as Parameters<typeof announceableAnswer>[0][number]
|
||||
|
||||
it('announces the finished answer, not the question', () => {
|
||||
expect(
|
||||
announceableAnswer([msg('user', 'Hur gick juli?'), msg('assistant', 'Juli gick 12 % bättre.')]),
|
||||
).toBe('Juli gick 12 % bättre.')
|
||||
})
|
||||
|
||||
it('reads the LAST assistant turn when the thread has several', () => {
|
||||
expect(
|
||||
announceableAnswer([
|
||||
msg('assistant', 'Första svaret.'),
|
||||
msg('user', 'Och augusti?'),
|
||||
msg('assistant', 'Andra svaret.'),
|
||||
]),
|
||||
).toBe('Andra svaret.')
|
||||
})
|
||||
|
||||
it('caps the WHOLE announcement, suffix included, and says where the rest is', () => {
|
||||
// A screen reader reads a live region straight through: a full bokslut
|
||||
// explanation announced in one uninterruptible burst is worse than not
|
||||
// announcing at all. Asserted against the constant, and at the real limit
|
||||
// rather than a looser number the suffix could sneak past.
|
||||
const out = announceableAnswer([msg('assistant', 'a'.repeat(1000))])
|
||||
expect(out.length).toBeLessThanOrEqual(ANNOUNCEMENT_LIMIT)
|
||||
expect(out).toContain('Svaret fortsätter i meddelandet')
|
||||
})
|
||||
|
||||
it('does not read an interrupted answer as a finished one', () => {
|
||||
// Stop leaves the partial text with a visible marker. Announcing it as the
|
||||
// answer tells a screen-reader user the opposite of what everyone else sees.
|
||||
const out = announceableAnswer([
|
||||
{ role: 'assistant', text: 'Momsen för juli blev 12 4', interrupted: true } as Parameters<
|
||||
typeof announceableAnswer
|
||||
>[0][number],
|
||||
])
|
||||
expect(out).toContain('avbröts')
|
||||
expect(out).not.toContain('12 4')
|
||||
})
|
||||
|
||||
it('never re-announces an earlier answer for a turn that produced no text', () => {
|
||||
// The caller passes only THIS turn's messages. Given the whole thread, a
|
||||
// tool-only turn would find the previous answer and read it out again as
|
||||
// though it were new: the user hears a stale answer to a new question.
|
||||
const thisTurn = [msg('user', 'Boka detta')]
|
||||
expect(announceableAnswer(thisTurn)).toBe('Assistenten är klar.')
|
||||
})
|
||||
|
||||
it('still says something when the turn produced no text', () => {
|
||||
// Silence would be indistinguishable from the request never having been
|
||||
// sent. An assistant bubble that only ever held whitespace counts as none.
|
||||
expect(announceableAnswer([msg('assistant', ' ')])).toBe('Assistenten är klar.')
|
||||
expect(announceableAnswer([])).toBe('Assistenten är klar.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('intentLabel', () => {
|
||||
it('never shows the raw intent id', () => {
|
||||
// It used to return the id itself, so an unmapped intent put
|
||||
// "bokslut.step" in front of the user as the name of their conversation.
|
||||
expect(intentLabel('some.unmapped.intent')).toBe('Fråga din assistent')
|
||||
expect(intentLabel('some.unmapped.intent', 'Anna')).toBe('Fråga Anna')
|
||||
})
|
||||
|
||||
it('gives the panel and the history list the SAME name for a thread', () => {
|
||||
// The two maps had drifted: the panel titled a bokslut thread "Fråga Anna"
|
||||
// while the history list called it "Hjälp med bokslut".
|
||||
expect(intentLabel('bokslut.step')).toBe('Hjälp med bokslut')
|
||||
expect(intentLabel('bokslut.step', 'Anna')).toBe('Hjälp med bokslut')
|
||||
expect(intentLabel('kpi.explain', 'Anna')).toBe('Förklara nyckeltal')
|
||||
})
|
||||
|
||||
it('personalises general help and falls back without a name', () => {
|
||||
expect(intentLabel('general.help', 'Anna')).toBe('Fråga Anna')
|
||||
expect(intentLabel('general.help')).toBe('Fråga din assistent')
|
||||
expect(intentLabel('general.help', ' ')).toBe('Fråga din assistent')
|
||||
})
|
||||
|
||||
it('does not resolve inherited Object keys as labels', () => {
|
||||
// A plain object literal inherits from Object.prototype, so a lookup of
|
||||
// 'toString' returned a FUNCTION, passed the truthiness check and reached
|
||||
// React as a conversation title. intent_id comes from the database.
|
||||
expect(intentLabel('toString')).toBe('Fråga din assistent')
|
||||
expect(intentLabel('constructor', 'Anna')).toBe('Fråga Anna')
|
||||
expect(intentLabel('__proto__')).toBe('Fråga din assistent')
|
||||
})
|
||||
|
||||
it('keeps momsdeklaration spelled correctly through the soft hyphen', () => {
|
||||
// The label carries a U+00AD so it can break across the narrow panel.
|
||||
// Stripping it must leave a real word.
|
||||
expect(intentLabel('vat.review').replace(//g, '')).toBe('Granska momsdeklaration')
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user