fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Å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:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -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)
})
})