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,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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { ChatMessage } from '../AgentChat'
|
||||
|
||||
/**
|
||||
* The pure state transitions behind PR4's message anatomy. The rendering is
|
||||
* covered by a visual pass (this repo has no component tests), but the state
|
||||
* rules are exactly where the regressions would hide, so they are pinned here.
|
||||
*/
|
||||
|
||||
/** Mirrors handleStop: mark the last assistant turn as interrupted, once. */
|
||||
function markInterrupted(prev: ChatMessage[]): ChatMessage[] {
|
||||
const last = prev[prev.length - 1]
|
||||
if (!last || last.role !== 'assistant' || last.interrupted) return prev
|
||||
return [...prev.slice(0, -1), { ...last, interrupted: true }]
|
||||
}
|
||||
|
||||
/** Mirrors handleSend's recovery: drop the bubble that was never persisted. */
|
||||
function dropUnsentBubble(prev: ChatMessage[], text: string): ChatMessage[] {
|
||||
const last = prev[prev.length - 1]
|
||||
return last?.role === 'user' && last.text === text ? prev.slice(0, -1) : prev
|
||||
}
|
||||
|
||||
describe('stop keeps partial content', () => {
|
||||
it('marks the streaming assistant turn as interrupted', () => {
|
||||
const out = markInterrupted([
|
||||
{ role: 'user', text: 'hur gick juli?' },
|
||||
{ role: 'assistant', text: 'Juli gick 12 procent' },
|
||||
])
|
||||
|
||||
expect(out[1]!.interrupted).toBe(true)
|
||||
// The partial text must survive: a truncated answer is still useful, it
|
||||
// just must not look complete.
|
||||
expect(out[1]!.text).toBe('Juli gick 12 procent')
|
||||
})
|
||||
|
||||
it('is idempotent', () => {
|
||||
const once = markInterrupted([{ role: 'assistant', text: 'delvis' }])
|
||||
expect(markInterrupted(once)).toBe(once)
|
||||
})
|
||||
|
||||
it('does not mark a user turn', () => {
|
||||
const messages: ChatMessage[] = [{ role: 'user', text: 'vänta' }]
|
||||
expect(markInterrupted(messages)).toBe(messages)
|
||||
})
|
||||
|
||||
it('does nothing on an empty thread', () => {
|
||||
const messages: ChatMessage[] = []
|
||||
expect(markInterrupted(messages)).toBe(messages)
|
||||
})
|
||||
})
|
||||
|
||||
describe('failed send returns the text', () => {
|
||||
it('removes the bubble that was never persisted', () => {
|
||||
const out = dropUnsentBubble(
|
||||
[
|
||||
{ role: 'assistant', text: 'tidigare svar' },
|
||||
{ role: 'user', text: 'boka om Circle K' },
|
||||
],
|
||||
'boka om Circle K',
|
||||
)
|
||||
|
||||
// Nothing reached the server, so nothing was persisted: leaving the bubble
|
||||
// would show a question that vanishes on the next reload.
|
||||
expect(out).toHaveLength(1)
|
||||
expect(out[0]!.role).toBe('assistant')
|
||||
})
|
||||
|
||||
it('leaves the thread alone when the last turn is something else', () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: 'user', text: 'boka om Circle K' },
|
||||
{ role: 'assistant', text: 'hann svara' },
|
||||
]
|
||||
expect(dropUnsentBubble(messages, 'boka om Circle K')).toBe(messages)
|
||||
})
|
||||
|
||||
it('only removes the matching text', () => {
|
||||
const messages: ChatMessage[] = [{ role: 'user', text: 'en annan fråga' }]
|
||||
expect(dropUnsentBubble(messages, 'boka om Circle K')).toBe(messages)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* One channel for "what is the assistant doing right now".
|
||||
*
|
||||
* Today the only publisher is the streaming turn inside AgentSheet, and the
|
||||
* only subscriber is the floating trigger. Both used to be blind: collapsing
|
||||
* the panel mid-answer hid the fact that the agent was still working, and the
|
||||
* moment it finished nothing said so, so the user either sat watching a static
|
||||
* pill or reopened the panel repeatedly to check.
|
||||
*
|
||||
* It is a reducer over a small event set rather than a pair of booleans in the
|
||||
* provider because the same channel has to carry a durable background run
|
||||
* later: a run publishes the same turn_start / step / turn_end events from a
|
||||
* poll or a socket, and the pill needs no changes. `detached` is that state,
|
||||
* built and rendered now even though v1 never dispatches it, so adding runs is
|
||||
* a publisher and not a redesign.
|
||||
*
|
||||
* React-free on purpose: this repo's unit project is node-only, so the state
|
||||
* machine is tested directly rather than through a component harness.
|
||||
*/
|
||||
|
||||
export type AgentActivity =
|
||||
/** Nothing running, nothing waiting to be read. */
|
||||
| 'idle'
|
||||
/** A turn is streaming and the user can see it. */
|
||||
| 'working'
|
||||
/** A turn finished while the panel was hidden: there is something to read. */
|
||||
| 'done'
|
||||
/** Work is running somewhere the user cannot see it (durable runs, later). */
|
||||
| 'detached'
|
||||
|
||||
export interface AgentStatus {
|
||||
activity: AgentActivity
|
||||
/** What the agent is doing, already human-readable, e.g. "Bokar…". */
|
||||
step: string | null
|
||||
/** True while the panel showing this work is on screen. */
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
export type AgentStatusEvent =
|
||||
| { type: 'turn_start' }
|
||||
| { type: 'step'; label: string }
|
||||
| { type: 'turn_end' }
|
||||
| { type: 'visibility'; visible: boolean }
|
||||
/** Reserved for durable runs; v1 never dispatches it. */
|
||||
| { type: 'detached'; label?: string }
|
||||
/** Session ended (panel closed): forget everything. */
|
||||
| { type: 'reset' }
|
||||
|
||||
export const INITIAL_AGENT_STATUS: AgentStatus = {
|
||||
activity: 'idle',
|
||||
step: null,
|
||||
visible: true,
|
||||
}
|
||||
|
||||
export function reduceAgentStatus(state: AgentStatus, event: AgentStatusEvent): AgentStatus {
|
||||
switch (event.type) {
|
||||
case 'turn_start':
|
||||
return { ...state, activity: 'working', step: null }
|
||||
|
||||
case 'step':
|
||||
// A step can arrive for work that started before this channel was
|
||||
// listening (a resumed stream), so it implies working rather than
|
||||
// requiring it.
|
||||
return { ...state, activity: 'working', step: event.label }
|
||||
|
||||
case 'turn_end':
|
||||
// Finishing on screen is not news: the answer is right there. Finishing
|
||||
// behind a collapsed panel is the whole point of this channel.
|
||||
return state.visible
|
||||
? { ...state, activity: 'idle', step: null }
|
||||
: { ...state, activity: 'done', step: null }
|
||||
|
||||
case 'visibility':
|
||||
if (!event.visible) return { ...state, visible: false }
|
||||
// Coming back into view consumes the notification, but must not cancel
|
||||
// work that is still running.
|
||||
return {
|
||||
...state,
|
||||
visible: true,
|
||||
activity: state.activity === 'done' ? 'idle' : state.activity,
|
||||
step: state.activity === 'done' ? null : state.step,
|
||||
}
|
||||
|
||||
case 'detached':
|
||||
return { ...state, activity: 'detached', step: event.label ?? null }
|
||||
|
||||
case 'reset':
|
||||
return { ...INITIAL_AGENT_STATUS, visible: state.visible }
|
||||
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The trigger's label for a session that is hidden but alive.
|
||||
*
|
||||
* Returns null when the status has nothing to add, so the caller keeps its
|
||||
* ordinary "Fråga X" / "Fortsätt med X" wording instead of this function
|
||||
* inventing a second copy of it.
|
||||
*/
|
||||
export function collapsedStatusLabel(status: AgentStatus, name: string): string | null {
|
||||
switch (status.activity) {
|
||||
case 'working':
|
||||
case 'detached':
|
||||
return status.step ? stripEllipsis(status.step) : `${name} arbetar`
|
||||
case 'done':
|
||||
return `${name} är klar`
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool labels are written as live narration ("Bokar avskrivningar…") because
|
||||
* they sit in the message trace. On the pill the same text is a state, and the
|
||||
* trailing ellipsis reads as a second spinner next to the real one.
|
||||
*/
|
||||
function stripEllipsis(label: string): string {
|
||||
return label.replace(/[….]+$/, '').trim()
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Avatar registry for the specialized accountant agent.
|
||||
//
|
||||
// The dicebear "notionists" style: clean line illustrations that match the
|
||||
// editorial monochrome brand without the cartoony feel of most avatar
|
||||
// libraries. 8 hand-picked seeds give distinct faces without being
|
||||
// overwhelming. The user picks one during Phase B review; the choice is
|
||||
// persisted as agent_profiles.avatar_id.
|
||||
//
|
||||
// The SVGs are SELF-HOSTED under public/agent-avatars, generated once from the
|
||||
// dicebear API with the seeds recorded below. They used to be loaded from
|
||||
// api.dicebear.com on every render, which meant every authenticated page view
|
||||
// of an accounting product sent the user's IP, user-agent and referer to a
|
||||
// third party, and put a CDN this app does not control on the path of a
|
||||
// logged-in surface. A self-hosted or firewalled install simply showed no
|
||||
// faces at all.
|
||||
//
|
||||
// Licence: the Notionists set is by Zoish under CC0 1.0 (public domain, no
|
||||
// attribution required). Each file carries that statement in its own RDF
|
||||
// metadata, so the terms travel with the asset.
|
||||
//
|
||||
// To regenerate or add a seed:
|
||||
// curl -o public/agent-avatars/<id>.svg \
|
||||
// "https://api.dicebear.com/9.x/notionists/svg?seed=<seed>&radius=50&backgroundColor=f5f3ed"
|
||||
|
||||
export interface AvatarOption {
|
||||
id: string
|
||||
label: string
|
||||
url: string
|
||||
/** The dicebear seed this file was generated from. Documentation, not runtime. */
|
||||
seed: string
|
||||
}
|
||||
|
||||
// Labels are just for the picker tooltip; the user names the agent themselves
|
||||
// in the adjacent text field. `seed` is not read at runtime: it records what
|
||||
// each file was generated from, so the set can be regenerated reproducibly.
|
||||
export const AVATAR_OPTIONS: readonly AvatarOption[] = [
|
||||
{ id: 'notionists-1', label: 'Linn', url: '/agent-avatars/notionists-1.svg', seed: 'linn-revisor-1' },
|
||||
{ id: 'notionists-2', label: 'Erik', url: '/agent-avatars/notionists-2.svg', seed: 'erik-revisor-2' },
|
||||
{ id: 'notionists-3', label: 'Maja', url: '/agent-avatars/notionists-3.svg', seed: 'maja-revisor-3' },
|
||||
{ id: 'notionists-4', label: 'Anders', url: '/agent-avatars/notionists-4.svg', seed: 'anders-revisor-4' },
|
||||
{ id: 'notionists-5', label: 'Karin', url: '/agent-avatars/notionists-5.svg', seed: 'karin-revisor-5' },
|
||||
{ id: 'notionists-6', label: 'Johan', url: '/agent-avatars/notionists-6.svg', seed: 'johan-revisor-6' },
|
||||
{ id: 'notionists-7', label: 'Eva', url: '/agent-avatars/notionists-7.svg', seed: 'eva-revisor-7' },
|
||||
{ id: 'notionists-8', label: 'Per', url: '/agent-avatars/notionists-8.svg', seed: 'per-revisor-8' },
|
||||
]
|
||||
|
||||
export function getAvatarUrl(avatarId: string | null | undefined): string | null {
|
||||
if (!avatarId) return null
|
||||
return AVATAR_OPTIONS.find((a) => a.id === avatarId)?.url ?? null
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Shared display helpers for the agent conversation list: used by both the
|
||||
// full-page /chat sidebar (ChatSidebar) and the in-sheet "resume conversation"
|
||||
// list (AgentSessionList). Pure functions; no React. Keeping them in one place
|
||||
// means the Idag / Igår / Denna vecka / Äldre grouping and the relative-time
|
||||
// labels stay identical across both surfaces.
|
||||
|
||||
export interface ConversationRow {
|
||||
id: string
|
||||
intent_id: string
|
||||
context_ref: string | null
|
||||
title: string | null
|
||||
pinned: boolean
|
||||
archived: boolean
|
||||
last_message_at: string | null
|
||||
last_message_preview: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
// Time buckets for date grouping. Computed once per render against now().
|
||||
// Mirrors the Idag / Igår / Denna vecka / Äldre pattern users know from
|
||||
// Mail and iMessage.
|
||||
export type DateBucket = 'pinned' | 'today' | 'yesterday' | 'thisWeek' | 'older'
|
||||
|
||||
export const BUCKET_LABELS: Record<DateBucket, string> = {
|
||||
pinned: 'Fästade',
|
||||
today: 'Idag',
|
||||
yesterday: 'Igår',
|
||||
thisWeek: 'Denna vecka',
|
||||
older: 'Äldre',
|
||||
}
|
||||
|
||||
export const BUCKET_ORDER: DateBucket[] = ['pinned', 'today', 'yesterday', 'thisWeek', 'older']
|
||||
|
||||
export function bucketFor(c: ConversationRow): DateBucket {
|
||||
if (c.pinned) return 'pinned'
|
||||
const when = c.last_message_at ?? c.created_at
|
||||
if (!when) return 'older'
|
||||
const t = new Date(when)
|
||||
const now = new Date()
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000)
|
||||
const weekStart = new Date(todayStart.getTime() - 6 * 24 * 60 * 60 * 1000)
|
||||
if (t >= todayStart) return 'today'
|
||||
if (t >= yesterdayStart) return 'yesterday'
|
||||
if (t >= weekStart) return 'thisWeek'
|
||||
return 'older'
|
||||
}
|
||||
|
||||
// Compact relative-time label shown to the right of each row. Locale-tuned
|
||||
// to feel native in Swedish without going full date-fns.
|
||||
export function relativeTime(iso: string | null | undefined): string {
|
||||
if (!iso) return ''
|
||||
const t = new Date(iso).getTime()
|
||||
const now = Date.now()
|
||||
const diffMin = Math.round((now - t) / 60000)
|
||||
if (diffMin < 1) return 'nu'
|
||||
if (diffMin < 60) return `${diffMin} min`
|
||||
const diffHr = Math.round(diffMin / 60)
|
||||
if (diffHr < 24) return `${diffHr} h`
|
||||
const diffDay = Math.round(diffHr / 24)
|
||||
if (diffDay < 7) return `${diffDay} d`
|
||||
return new Date(iso).toLocaleDateString('sv-SE', { month: 'short', day: 'numeric' })
|
||||
}
|
||||
|
||||
/**
|
||||
* One label per intent, for every surface that names a conversation.
|
||||
*
|
||||
* There were two of these: this map and an intentToTitle in AgentSheet. They
|
||||
* had already drifted, so the panel opened on the bokslut wizard titled
|
||||
* "Fråga Anna" while the same thread in the history list read "Hjälp med
|
||||
* bokslut", and this one's fallback returned the raw intent id, putting
|
||||
* "bokslut.step" in front of the user as the name of their own conversation.
|
||||
*/
|
||||
// Null-prototype: a plain literal inherits from Object.prototype, so
|
||||
// intentLabel('toString') would resolve to a FUNCTION, pass the truthiness
|
||||
// check, and be handed to React as a title. intent_id comes from the database.
|
||||
const INTENT_LABELS: Record<string, string> = Object.assign(Object.create(null), {
|
||||
'transaction.categorization': 'Hjälp med transaktion',
|
||||
'invoice.draft': 'Hjälp med faktura',
|
||||
'supplier_invoice.review': 'Granska leverantörsfaktura',
|
||||
'vat.review': 'Granska moms\u00addeklaration',
|
||||
'bokslut.step': 'Hjälp med bokslut',
|
||||
'verifikation.draft': 'Hjälp med verifikation',
|
||||
'kpi.explain': 'Förklara nyckeltal',
|
||||
'settings.help': 'Hjälp med inställningar',
|
||||
'inbox.bulk-book': 'Bokför från inkorgen',
|
||||
})
|
||||
|
||||
/**
|
||||
* `agentName` personalises the general-help and unknown cases ("Fråga Anna").
|
||||
* Omit it where the agent's name is not to hand: the wording stays correct,
|
||||
* just less personal. An unknown intent NEVER falls through to its id.
|
||||
*/
|
||||
export function intentLabel(intentId: string, agentName?: string | null): string {
|
||||
const known = INTENT_LABELS[intentId]
|
||||
if (known) return known
|
||||
const name = agentName?.trim()
|
||||
return name ? `Fråga ${name}` : 'Fråga din assistent'
|
||||
}
|
||||
|
||||
// Group a flat (already server-sorted: pinned first, then last_message_at desc)
|
||||
// list into ordered, non-empty buckets. Shared so both list surfaces render
|
||||
// the same section order.
|
||||
export function groupConversations(
|
||||
rows: ConversationRow[],
|
||||
): { bucket: DateBucket; rows: ConversationRow[] }[] {
|
||||
const buckets: Record<DateBucket, ConversationRow[]> = {
|
||||
pinned: [],
|
||||
today: [],
|
||||
yesterday: [],
|
||||
thisWeek: [],
|
||||
older: [],
|
||||
}
|
||||
for (const c of rows) buckets[bucketFor(c)].push(c)
|
||||
return BUCKET_ORDER.map((b) => ({ bucket: b, rows: buckets[b] })).filter((g) => g.rows.length > 0)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import type { ConversationRow } from './conversation-display'
|
||||
|
||||
/**
|
||||
* The list transforms and the optimistic-write coordinator behind
|
||||
* useConversationList. Pure and React-free so they can be tested directly:
|
||||
* the hook is a thin binding over these, which means a test that deletes the
|
||||
* rollback here fails, rather than passing against a copy of the logic.
|
||||
*/
|
||||
|
||||
export function setPinned(
|
||||
list: ConversationRow[],
|
||||
id: string,
|
||||
pinned: boolean,
|
||||
): ConversationRow[] {
|
||||
return list.map((c) => (c.id === id ? { ...c, pinned } : c))
|
||||
}
|
||||
|
||||
export function setTitle(
|
||||
list: ConversationRow[],
|
||||
id: string,
|
||||
title: string | null,
|
||||
): ConversationRow[] {
|
||||
return list.map((c) => (c.id === id ? { ...c, title } : c))
|
||||
}
|
||||
|
||||
export function removeRow(list: ConversationRow[], id: string): ConversationRow[] {
|
||||
return list.filter((c) => c.id !== id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Put a row back after a failed archive, into whatever the list looks like NOW.
|
||||
*
|
||||
* Restoring a render-time snapshot of the whole list would discard any pin,
|
||||
* rename or archive the user made while the request was in flight. Position
|
||||
* follows the server's ordering (pinned first, then most recent first) so the
|
||||
* row reappears where it belongs rather than at the end.
|
||||
*/
|
||||
export function restoreRow(list: ConversationRow[], row: ConversationRow): ConversationRow[] {
|
||||
if (list.some((c) => c.id === row.id)) return list
|
||||
const sortKey = (c: ConversationRow) => c.last_message_at ?? c.created_at ?? ''
|
||||
const idx = list.findIndex((c) => {
|
||||
if (row.pinned !== c.pinned) return row.pinned && !c.pinned
|
||||
return sortKey(row) > sortKey(c)
|
||||
})
|
||||
if (idx === -1) return [...list, row]
|
||||
return [...list.slice(0, idx), row, ...list.slice(idx)]
|
||||
}
|
||||
|
||||
/** PATCH one conversation. Resolves false for a non-2xx AND for a thrown fetch. */
|
||||
export async function patchConversation(
|
||||
id: string,
|
||||
body: Record<string, unknown>,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`/api/agent/conversations/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
return res.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-row revision guard.
|
||||
*
|
||||
* Two writes to the same row can overlap (a double-click on pin, a rename
|
||||
* while an archive is in flight). Without this, a failing FIRST request would
|
||||
* roll back over the SECOND request's newer value. Each write claims a
|
||||
* revision; a rollback only applies while its revision is still the latest for
|
||||
* that row.
|
||||
*/
|
||||
export function createRevisionGuard() {
|
||||
const revisions = new Map<string, number>()
|
||||
return {
|
||||
claim(id: string): number {
|
||||
const next = (revisions.get(id) ?? 0) + 1
|
||||
revisions.set(id, next)
|
||||
return next
|
||||
},
|
||||
isCurrent(id: string, revision: number): boolean {
|
||||
return revisions.get(id) === revision
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export interface OptimisticPatchArgs {
|
||||
id: string
|
||||
body: Record<string, unknown>
|
||||
/** Optimistic transform, applied immediately. */
|
||||
apply: (list: ConversationRow[]) => ConversationRow[]
|
||||
/** Undo, applied to the CURRENT list only if this write is still the latest. */
|
||||
revert: (list: ConversationRow[]) => ConversationRow[]
|
||||
setList: (updater: (prev: ConversationRow[]) => ConversationRow[]) => void
|
||||
guard: ReturnType<typeof createRevisionGuard>
|
||||
onError: () => void
|
||||
patch?: typeof patchConversation
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a change optimistically, send it, and undo it if the server refuses.
|
||||
* Returns whether the change stuck.
|
||||
*/
|
||||
export async function runOptimisticPatch({
|
||||
id,
|
||||
body,
|
||||
apply,
|
||||
revert,
|
||||
setList,
|
||||
guard,
|
||||
onError,
|
||||
patch = patchConversation,
|
||||
}: OptimisticPatchArgs): Promise<boolean> {
|
||||
const revision = guard.claim(id)
|
||||
setList(apply)
|
||||
|
||||
const ok = await patch(id, body)
|
||||
if (ok) return true
|
||||
|
||||
// A newer write for this row has since been issued: undoing here would clobber
|
||||
// it. That write owns the row's state and will report its own failure.
|
||||
if (!guard.isCurrent(id, revision)) return false
|
||||
|
||||
setList(revert)
|
||||
onError()
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Send one thumbs vote on an assistant answer.
|
||||
*
|
||||
* Kept out of the component so it is testable without a React harness (this
|
||||
* repo's unit project is node-only), and so the failure contract is stated in
|
||||
* one place: this resolves false rather than throwing, because a vote that
|
||||
* cannot be sent must never interrupt reading the answer it was about.
|
||||
*/
|
||||
export type FeedbackSentiment = 'positive' | 'negative'
|
||||
|
||||
export async function sendFeedback(args: {
|
||||
conversationId: string
|
||||
sentiment: FeedbackSentiment
|
||||
messageIndex?: number
|
||||
fetchImpl?: typeof fetch
|
||||
}): Promise<boolean> {
|
||||
const { conversationId, sentiment, messageIndex, fetchImpl = fetch } = args
|
||||
try {
|
||||
const res = await fetchImpl('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
conversation_id: conversationId,
|
||||
sentiment,
|
||||
...(messageIndex === undefined ? {} : { message_index: messageIndex }),
|
||||
}),
|
||||
})
|
||||
return res.ok
|
||||
} catch {
|
||||
// Offline, or the request was cut off by a navigation. Reported as a
|
||||
// failed vote so the button can go back to unpressed rather than claiming
|
||||
// a report that never arrived.
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Is this href a link back into the app?
|
||||
*
|
||||
* Kept out of MarkdownMessage so it is testable without the markdown parser
|
||||
* (that component exists to be lazily imported, and this repo's unit project
|
||||
* is node-only).
|
||||
*
|
||||
* The href comes from a language model that reads customer documents and
|
||||
* supplier invoices, so "starts with a slash" is not a sufficient test:
|
||||
* "//evil.example" is protocol-relative and leaves the site entirely. Anything
|
||||
* this returns false for is rendered as an external link, which is the safe
|
||||
* direction to be wrong in: an external link that could have been routed
|
||||
* costs a page load, whereas an external URL treated as internal would be
|
||||
* handed to the router as an app path.
|
||||
*/
|
||||
export function isInternalHref(href: string): boolean {
|
||||
if (!href.startsWith('/')) return false
|
||||
// Protocol-relative ("//host/path"), and the backslash variant browsers
|
||||
// normalise to the same thing.
|
||||
if (href.startsWith('//') || href.startsWith('/\\')) return false
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useMemo, useRef, useState } from 'react'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { type ConversationRow, type DateBucket, groupConversations } from './conversation-display'
|
||||
import {
|
||||
createRevisionGuard,
|
||||
removeRow,
|
||||
restoreRow,
|
||||
runOptimisticPatch,
|
||||
setPinned,
|
||||
setTitle,
|
||||
} from './conversation-mutations'
|
||||
|
||||
/**
|
||||
* Shared state and mutations for the agent conversation list.
|
||||
*
|
||||
* The two surfaces that show conversations (the full-page /chat sidebar and the
|
||||
* in-sheet resume list) had drifted apart in behaviour, not just chrome: the
|
||||
* sheet rolled a failed rename back and toasted, while the sidebar fired pin,
|
||||
* archive and rename blind, with no res.ok check, no rollback and no message.
|
||||
* A failed archive there removed a conversation from the list while it still
|
||||
* existed on the server, and a failed rename displayed a title the server never
|
||||
* saved, both until the next reload.
|
||||
*
|
||||
* Owning the state and all three mutations here means the two surfaces cannot
|
||||
* diverge again, and the sheet gains pin/archive it never had. The chrome
|
||||
* stays with each surface: a 320px sidebar that collapses to a rail and a sheet
|
||||
* panel are legitimately different shapes.
|
||||
*
|
||||
* The transforms and the write coordinator live in conversation-mutations.ts so
|
||||
* they are testable without a React harness (this repo's unit project is
|
||||
* node-only).
|
||||
*/
|
||||
export interface ConversationListApi {
|
||||
conversations: ConversationRow[]
|
||||
setConversations: React.Dispatch<React.SetStateAction<ConversationRow[]>>
|
||||
query: string
|
||||
setQuery: (q: string) => void
|
||||
grouped: { bucket: DateBucket; rows: ConversationRow[] }[]
|
||||
togglePin: (id: string, current: boolean) => Promise<void>
|
||||
archive: (id: string) => Promise<boolean>
|
||||
rename: (id: string, title: string) => Promise<void>
|
||||
// Inline rename plumbing, shared so Esc-to-cancel behaves identically.
|
||||
editingId: string | null
|
||||
editValue: string
|
||||
setEditValue: (v: string) => void
|
||||
startEdit: (c: ConversationRow) => void
|
||||
cancelEdit: () => void
|
||||
commitEdit: (id: string) => Promise<void>
|
||||
}
|
||||
|
||||
export function useConversationList(initial: ConversationRow[]): ConversationListApi {
|
||||
const [conversations, setConversations] = useState<ConversationRow[]>(initial)
|
||||
const [query, setQuery] = useState('')
|
||||
const { toast } = useToast()
|
||||
const guard = useRef(createRevisionGuard()).current
|
||||
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [editValue, setEditValue] = useState('')
|
||||
// Set by Esc so the blur fired when the input unmounts doesn't save.
|
||||
const cancelRef = useRef(false)
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return conversations
|
||||
return conversations.filter(
|
||||
(c) =>
|
||||
(c.title ?? '').toLowerCase().includes(q) ||
|
||||
(c.last_message_preview ?? '').toLowerCase().includes(q) ||
|
||||
(c.context_ref ?? '').toLowerCase().includes(q) ||
|
||||
c.intent_id.toLowerCase().includes(q),
|
||||
)
|
||||
}, [conversations, query])
|
||||
|
||||
const grouped = useMemo(() => groupConversations(filtered), [filtered])
|
||||
|
||||
const togglePin = useCallback(
|
||||
async (id: string, current: boolean) => {
|
||||
await runOptimisticPatch({
|
||||
id,
|
||||
body: { pinned: !current },
|
||||
apply: (list) => setPinned(list, id, !current),
|
||||
revert: (list) => setPinned(list, id, current),
|
||||
setList: setConversations,
|
||||
guard,
|
||||
onError: () => toast({ variant: 'destructive', title: 'Kunde inte ändra fästningen.' }),
|
||||
})
|
||||
},
|
||||
[guard, toast],
|
||||
)
|
||||
|
||||
/** Resolves true when the row is really archived, so callers can navigate. */
|
||||
const archive = useCallback(
|
||||
async (id: string) => {
|
||||
const row = conversations.find((c) => c.id === id)
|
||||
return runOptimisticPatch({
|
||||
id,
|
||||
body: { archived: true },
|
||||
apply: (list) => removeRow(list, id),
|
||||
// Restore into the CURRENT list, not a snapshot: changes made while the
|
||||
// request was in flight must survive.
|
||||
revert: (list) => (row ? restoreRow(list, row) : list),
|
||||
setList: setConversations,
|
||||
guard,
|
||||
onError: () => toast({ variant: 'destructive', title: 'Kunde inte arkivera konversationen.' }),
|
||||
})
|
||||
},
|
||||
[conversations, guard, toast],
|
||||
)
|
||||
|
||||
const rename = useCallback(
|
||||
async (id: string, title: string) => {
|
||||
const previousTitle = conversations.find((c) => c.id === id)?.title ?? null
|
||||
await runOptimisticPatch({
|
||||
id,
|
||||
body: { title },
|
||||
apply: (list) => setTitle(list, id, title),
|
||||
revert: (list) => setTitle(list, id, previousTitle),
|
||||
setList: setConversations,
|
||||
guard,
|
||||
onError: () =>
|
||||
toast({ variant: 'destructive', title: 'Kunde inte byta namn på konversationen.' }),
|
||||
})
|
||||
},
|
||||
[conversations, guard, toast],
|
||||
)
|
||||
|
||||
const startEdit = useCallback((c: ConversationRow) => {
|
||||
setEditingId(c.id)
|
||||
setEditValue(c.title ?? '')
|
||||
cancelRef.current = false
|
||||
}, [])
|
||||
|
||||
const cancelEdit = useCallback(() => {
|
||||
cancelRef.current = true
|
||||
setEditingId(null)
|
||||
}, [])
|
||||
|
||||
const commitEdit = useCallback(
|
||||
async (id: string) => {
|
||||
if (cancelRef.current) {
|
||||
cancelRef.current = false
|
||||
return
|
||||
}
|
||||
setEditingId(null)
|
||||
const title = editValue.trim()
|
||||
const current = conversations.find((c) => c.id === id)
|
||||
if (!title || title === current?.title) return
|
||||
await rename(id, title)
|
||||
},
|
||||
[conversations, editValue, rename],
|
||||
)
|
||||
|
||||
return {
|
||||
conversations,
|
||||
setConversations,
|
||||
query,
|
||||
setQuery,
|
||||
grouped,
|
||||
togglePin,
|
||||
archive,
|
||||
rename,
|
||||
editingId,
|
||||
editValue,
|
||||
setEditValue,
|
||||
startEdit,
|
||||
cancelEdit,
|
||||
commitEdit,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user