diff --git a/e2e/README.md b/e2e/README.md index eb7e7239a..2ca639d1a 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -84,7 +84,8 @@ console or page error fails the check. One module covers one behaviour; families share a prefix: `audit-*` for the audit page (redirect, filters, revert, runtime, views-export, retention-live, phone), `workflow-*` for the canvas (loading, validation, phone-layout, logic), -`chat-composer` for chat input. +`chat-composer` for chat input, `chat-dock-*` for the chat dock (pin, drag-cancel, +layout, resize, drafts, picker, phone). `routes` loads every static route and flags text with stray leading, trailing or doubled spaces. `seeded` checks the seed is visible. diff --git a/e2e/checks/chat-composer.cjs b/e2e/checks/chat-composer.cjs index eecd42165..c3bda1cab 100644 --- a/e2e/checks/chat-composer.cjs +++ b/e2e/checks/chat-composer.cjs @@ -1,10 +1,11 @@ // The chat composer: IME confirmation never submits the draft, Shift+Enter -// inserts a newline, and ordinary Enter submits and clears. +// inserts a newline, ordinary Enter submits and clears, and # attaches a task. const assert = require('node:assert/strict'); -module.exports = async ({ page, go, shot }) => { +module.exports = async ({ page, go, shot, tolerate }) => { + tolerate(/api\/tasks/); await go('/events'); - const composer = page.getByRole('textbox', { name: 'Message Archie', exact: true }); + const composer = page.getByRole('combobox', { name: 'Message Archie', exact: true }); await composer.waitFor(); await composer.fill('Composition in progress'); const sent = []; @@ -24,5 +25,46 @@ module.exports = async ({ page, go, shot }) => { await composer.press('Enter'); assert.equal((await request).postDataJSON().text, 'Ordinary Enter submits'); assert.equal(await composer.inputValue(), ''); + + let failTasks = true; + await page.route('**/api/tasks?*', async route => { + if (failTasks) return route.fulfill({ status: 500, contentType: 'text/plain', body: 'task store down' }); + await route.fulfill({ + contentType: 'application/json', + body: JSON.stringify([ + { id: 1861, title: "Chat composer: '#' context dropdown", status: 'running' }, + { id: 1842, title: 'Retry stalled task runs', status: 'done' }, + ]), + }); + }); + + const tasksPalette = page.getByRole('listbox', { name: 'Tasks' }); + await composer.fill('Look at #'); + await tasksPalette.getByRole('alert').waitFor(); + assert.equal(await tasksPalette.getByRole('option').count(), 0); + + failTasks = false; + await tasksPalette.getByRole('button', { name: 'Retry' }).click(); + await tasksPalette.getByRole('option').first().waitFor(); + assert.equal(await tasksPalette.getByRole('option').count(), 2); + + await composer.press('Escape'); + await tasksPalette.waitFor({ state: 'hidden' }); + + await composer.fill('Look at #184 now'); + await composer.evaluate(el => el.setSelectionRange(12, 12)); + await composer.dispatchEvent('input'); + await tasksPalette.getByRole('option').first().waitFor(); + assert.equal(await tasksPalette.getByRole('option').count(), 1); + await composer.press('Tab'); + await tasksPalette.waitFor({ state: 'hidden' }); + assert.equal(await composer.inputValue(), 'Look at now'); + await page.getByRole('list', { name: 'Attached tasks' }).getByText('#1842').waitFor(); + + const tagged = page.waitForRequest('**/api/chat/stream'); + await composer.press('Enter'); + const text = (await tagged).postDataJSON().text; + assert.ok(text.startsWith('Look at now') && text.includes('#1842 Retry stalled task runs'), text); + assert.equal(await page.getByRole('list', { name: 'Attached tasks' }).count(), 0); await shot('chat-composition'); }; diff --git a/e2e/checks/chat-dock-drafts.cjs b/e2e/checks/chat-dock-drafts.cjs new file mode 100644 index 000000000..d7285a6b3 --- /dev/null +++ b/e2e/checks/chat-dock-drafts.cjs @@ -0,0 +1,42 @@ +// Each conversation keeps its own unsent text and attached tasks. Starting a +// new chat opens an empty composer, switching back restores the earlier +// draft, and hiding and reopening the conversation loses nothing. +const assert = require('node:assert/strict'); +const h = require('./helpers/chat-dock.cjs'); + +module.exports = async ({ page, go, shot }) => { + await page.route('**/api/tasks?*', (route) => + route.fulfill({ contentType: 'application/json', body: JSON.stringify([{ id: 1861, title: 'Task picker', status: 'running' }]) }), + ); + await h.load(page, go); + await h.expand(page); + const composer = h.composerOf(page); + const tags = page.getByRole('list', { name: 'Attached tasks' }); + + await composer.fill('draft for the first chat'); + await composer.fill('#'); + await page.getByRole('listbox', { name: 'Tasks' }).getByRole('option').first().click(); + await tags.getByText('#1861').waitFor(); + await composer.fill('draft for the first chat'); + + await page.getByRole('button', { name: 'New chat' }).click(); + await h.until(async () => (await composer.inputValue()) === '' && (await tags.count()) === 0, 'a new chat inherited the first chat draft'); + await composer.fill('draft for the second chat'); + + await h.hideOf(page).click(); + await h.expand(page); + assert.equal(await composer.inputValue(), 'draft for the second chat', 'hiding the conversation lost the draft'); + + const pick = async (index) => { + await page.getByRole('combobox', { name: 'Conversation' }).click(); + await page.getByRole('option').nth(index).click(); + }; + await pick(1); + await h.until(async () => (await composer.inputValue()) === 'draft for the first chat', 'switching back did not restore the first draft'); + await tags.getByText('#1861').waitFor(); + await shot('first-chat-draft'); + + await pick(0); + await h.until(async () => (await composer.inputValue()) === 'draft for the second chat', 'switching forward did not restore the second draft'); + assert.equal(await tags.count(), 0, 'the first chat task tag leaked into the second chat'); +}; diff --git a/e2e/checks/chat-dock-drag-cancel.cjs b/e2e/checks/chat-dock-drag-cancel.cjs new file mode 100644 index 000000000..46be294aa --- /dev/null +++ b/e2e/checks/chat-dock-drag-cancel.cjs @@ -0,0 +1,27 @@ +// A drag the browser cancels (a touch turned into a scroll, a lost pointer) +// leaves the dock where it was: nothing pins, nothing stays offset, and the +// next drag still works. +const assert = require('node:assert/strict'); +const h = require('./helpers/chat-dock.cjs'); + +module.exports = async ({ page, go }) => { + await h.load(page, go); + await h.expand(page); + const dock = h.dockOf(page); + const before = await dock.boundingBox(); + const header = dock.locator('div.cursor-grab'); + + await h.dragTo(page, 1430); + const dragging = await dock.getAttribute('style'); + assert.ok(/translate/.test(dragging || ''), 'the drag never started, so cancelling it proves nothing'); + await header.dispatchEvent('pointercancel'); + await page.mouse.up(); + + await h.until(async () => !/translate/.test((await dock.getAttribute('style')) || ''), 'the dock stayed offset after the drag was cancelled'); + assert.deepEqual(await dock.boundingBox(), before, 'cancelling the drag moved the dock'); + assert.equal((await h.saved(page)).side, null, 'a cancelled drag pinned the dock'); + + await h.dragTo(page, 1430); + await page.mouse.up(); + await h.until(async () => (await h.saved(page)).side === 'right', 'a drag after a cancelled one did not pin'); +}; diff --git a/e2e/checks/chat-dock-layout.cjs b/e2e/checks/chat-dock-layout.cjs new file mode 100644 index 000000000..3707982a5 --- /dev/null +++ b/e2e/checks/chat-dock-layout.cjs @@ -0,0 +1,46 @@ +// The saved dock layout: a stored side and width are honoured, widths outside +// the allowed range are clamped, unreadable JSON falls back to a usable +// floating dock that saves again, and visiting phone width never overwrites +// the desktop choice. +const assert = require('node:assert/strict'); +const h = require('./helpers/chat-dock.cjs'); + +module.exports = async ({ page, go, shot, tolerate }) => { + tolerate(/JSON|SyntaxError/); + const dock = h.dockOf(page); + + await h.load(page, go, JSON.stringify({ side: 'left', width: 500 })); + await h.expand(page); + let box = await dock.boundingBox(); + h.near(box.x, 0, 'saved left side'); + h.near(box.width, 500, 'saved width'); + assert.ok((await h.mainRect(page)).x >= 499, 'page did not reflow beside the restored dock'); + + await h.load(page, go, JSON.stringify({ side: 'right', width: -4 })); + await h.expand(page); + h.near((await dock.boundingBox()).width, 320, 'a negative width clamps to the minimum'); + + await h.load(page, go, JSON.stringify({ side: 'right', width: 9999 })); + await h.expand(page); + h.near((await dock.boundingBox()).width, 720, 'a huge width clamps to the maximum'); + + await h.load(page, go, '{broken'); + await h.expand(page); + box = await dock.boundingBox(); + assert.ok(box.height < 900 && box.x > 0 && box.x + box.width < 1440, 'unreadable layout did not fall back to a floating dock'); + await h.composerOf(page).fill('still usable'); + await h.dragTo(page, 1430); + await page.mouse.up(); + await h.until(async () => (await h.saved(page)).side === 'right', 'the dock did not save a layout over the unreadable one'); + await shot('recovered'); + + await h.load(page, go, JSON.stringify({ side: 'left', width: 460 })); + const layout = await h.stored(page); + await page.setViewportSize({ width: 390, height: 844 }); + await h.expand(page); + box = await dock.boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= 390, 'the dock overflows the phone viewport'); + await page.setViewportSize({ width: 1440, height: 900 }); + assert.equal(await h.stored(page), layout, 'visiting phone width rewrote the saved layout'); + await h.until(async () => Math.abs((await dock.boundingBox()).width - 460) <= 1, 'the desktop layout did not return after phone width'); +}; diff --git a/e2e/checks/chat-dock-phone.cjs b/e2e/checks/chat-dock-phone.cjs new file mode 100644 index 000000000..a955fd9a5 --- /dev/null +++ b/e2e/checks/chat-dock-phone.cjs @@ -0,0 +1,41 @@ +// The chat dock at phone width: the bar and the open conversation fit the +// screen on a few pages, a stored desktop pin is ignored, the composer stays +// reachable, and the dock adds no sideways scroll. The page's own overflow is +// phone-overflow's to report, so the dock is measured against the page +// without it. +const assert = require('node:assert/strict'); +const h = require('./helpers/chat-dock.cjs'); + +module.exports = async ({ page, go, shot, tolerate }) => { + tolerate(/extensions\/catalogue/); + await page.setViewportSize({ width: 390, height: 844 }); + const fits = async (label) => { + const { scroll, bare, inner } = await page.evaluate(() => { + const root = document.querySelector('aside[aria-label="Chat with Archie"]').parentElement; + const scroll = document.documentElement.scrollWidth; + root.style.display = 'none'; + const bare = document.documentElement.scrollWidth; + root.style.display = ''; + return { scroll, bare, inner: window.innerWidth }; + }); + assert.ok(scroll <= Math.max(bare, inner), `${label}: the dock widens the page (${scroll} > ${Math.max(bare, inner)})`); + const box = await h.dockOf(page).boundingBox(); + assert.ok(box.x >= 0 && box.x + box.width <= inner, `${label}: dock leaves the screen (${box.x}..${box.x + box.width})`); + assert.ok(box.y >= 0 && box.y + box.height <= 844, `${label}: dock leaves the screen vertically`); + }; + + for (const path of ['/events', '/account', '/org/agents']) { + await h.load(page, go, JSON.stringify({ side: 'right', width: 420 })); + await go(path); + await fits(`${path} collapsed`); + await h.expand(page); + await fits(`${path} open`); + assert.equal(await page.evaluate(() => document.documentElement.style.getPropertyValue('--chat-pin-r')), '0px', `${path}: the page reserved room for a pin on a phone`); + const composer = await h.composerOf(page).boundingBox(); + assert.ok(composer.y + composer.height <= 844 && composer.x >= 0 && composer.x + composer.width <= 390, `${path}: composer is off screen`); + assert.equal(await h.dividerOf(page).count(), 0, `${path}: a phone shows the pin divider`); + await h.composerOf(page).fill('A long unbroken line '.repeat(20)); + await fits(`${path} long draft`); + await shot(path); + } +}; diff --git a/e2e/checks/chat-dock-picker.cjs b/e2e/checks/chat-dock-picker.cjs new file mode 100644 index 000000000..8e0460477 --- /dev/null +++ b/e2e/checks/chat-dock-picker.cjs @@ -0,0 +1,59 @@ +// The # task picker by keyboard: arrows move the selection and wrap, Enter +// attaches the selected task, Escape closes the picker and leaves the +// conversation open, and an IME confirmation Enter never picks. +const assert = require('node:assert/strict'); +const h = require('./helpers/chat-dock.cjs'); + +const tasks = [ + { id: 1861, title: 'Task picker', status: 'running' }, + { id: 1842, title: 'Retry stalled task runs', status: 'done' }, + { id: 1830, title: 'Filter forge text', status: 'queued' }, +]; + +module.exports = async ({ page, go, shot }) => { + await page.route('**/api/tasks?*', (route) => route.fulfill({ contentType: 'application/json', body: JSON.stringify(tasks) })); + await h.load(page, go); + await h.expand(page); + const composer = h.composerOf(page); + const palette = page.getByRole('listbox', { name: 'Tasks' }); + const options = palette.getByRole('option'); + const selected = () => options.evaluateAll((els) => els.findIndex((el) => el.getAttribute('aria-selected') === 'true')); + const tags = page.getByRole('list', { name: 'Attached tasks' }); + + await composer.fill('Look at #'); + await options.first().waitFor(); + assert.equal(await options.count(), 3); + assert.equal(await selected(), 0); + await shot('picker'); + + await composer.press('ArrowDown'); + assert.equal(await selected(), 1); + assert.equal(await composer.getAttribute('aria-activedescendant'), 'slash-palette-option-1'); + await composer.press('ArrowUp'); + await composer.press('ArrowUp'); + assert.equal(await selected(), 2, 'ArrowUp from the first row did not wrap to the last'); + await composer.press('ArrowDown'); + assert.equal(await selected(), 0, 'ArrowDown from the last row did not wrap to the first'); + await composer.press('ArrowDown'); + + for (const event of [{ isComposing: true }, { keyCode: 229 }]) { + await composer.dispatchEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true, ...event }); + assert.equal(await options.count(), 3, 'an IME confirmation closed the picker'); + assert.equal(await tags.count(), 0, 'an IME confirmation attached a task'); + } + + await composer.press('Enter'); + await palette.waitFor({ state: 'hidden' }); + await tags.getByText('#1842').waitFor(); + assert.equal(await tags.getByRole('listitem').count(), 1); + assert.equal(await composer.inputValue(), 'Look at ', 'the # token stayed in the text'); + assert.ok(await composer.evaluate((el) => document.activeElement === el), 'focus left the composer'); + + await composer.fill('Look at #'); + await options.first().waitFor(); + await composer.press('Escape'); + await palette.waitFor({ state: 'hidden' }); + assert.equal(await h.hideOf(page).isVisible(), true, 'Escape on the picker also closed the conversation'); + await composer.press('Escape'); + await h.hideOf(page).waitFor({ state: 'hidden' }); +}; diff --git a/e2e/checks/chat-dock-pin.cjs b/e2e/checks/chat-dock-pin.cjs new file mode 100644 index 000000000..797069c82 --- /dev/null +++ b/e2e/checks/chat-dock-pin.cjs @@ -0,0 +1,52 @@ +// Pinning the chat dock: dragging its header to an edge pins it there and the +// page reflows beside it; double-clicking the header unpins it; hiding the +// conversation gives the page back its width; the choice survives a reload. +const assert = require('node:assert/strict'); +const h = require('./helpers/chat-dock.cjs'); + +module.exports = async ({ page, go, shot }) => { + await h.load(page, go); + await h.expand(page); + const dock = h.dockOf(page); + const free = await h.mainRect(page); + const floating = await dock.boundingBox(); + assert.ok(floating.height < 900, 'the dock starts as a floating card'); + + await h.dragTo(page, 1430); + await page.mouse.up(); + await h.until(async () => (await h.saved(page)).side === 'right', 'dragging to the right edge did not pin right'); + const right = await dock.boundingBox(); + h.near(right.x + right.width, 1440, 'right pin touches the right edge'); + h.near(right.height, 900, 'a pinned dock is full height'); + const reflowed = await h.mainRect(page); + assert.ok(reflowed.x + reflowed.width <= right.x + 1, `page content runs under the pinned dock: ${reflowed.x + reflowed.width} > ${right.x}`); + assert.ok(reflowed.width < free.width, 'the page did not give up any width'); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), 'pinning made the page scroll sideways'); + await shot('pinned-right'); + + await page.reload(); + await h.expand(page); + await h.until(async () => Math.abs((await dock.boundingBox()).x - right.x) <= 1, 'the right pin did not survive a reload'); + + await h.hideOf(page).click(); + await h.until(async () => Math.abs((await h.mainRect(page)).width - free.width) <= 1, 'hiding the conversation kept the page narrowed'); + await h.expand(page); + await h.until(async () => Math.abs((await dock.boundingBox()).x - right.x) <= 1, 'reopening did not restore the pin'); + + const strip = await h.grip(page); + await page.mouse.dblclick(strip.x, strip.y); + await h.until(async () => (await h.saved(page)).side === null, 'double-clicking the header did not unpin'); + assert.ok((await dock.boundingBox()).height < 900, 'an unpinned dock is a floating card again'); + h.near((await h.mainRect(page)).width, free.width, 'the page returns to its full width'); + + await h.dragTo(page, 10); + await page.mouse.up(); + await h.until(async () => (await h.saved(page)).side === 'left', 'dragging to the left edge did not pin left'); + const left = await dock.boundingBox(); + h.near(left.x, 0, 'left pin touches the left edge'); + assert.ok((await h.mainRect(page)).x >= left.x + left.width - 1, 'page content runs under the left-pinned dock'); + await shot('pinned-left'); + + await page.mouse.dblclick((await h.grip(page)).x, (await h.grip(page)).y); + await h.until(async () => (await h.saved(page)).side === null, 'double-clicking did not unpin the left pin'); +}; diff --git a/e2e/checks/chat-dock-resize.cjs b/e2e/checks/chat-dock-resize.cjs new file mode 100644 index 000000000..958e31a2d --- /dev/null +++ b/e2e/checks/chat-dock-resize.cjs @@ -0,0 +1,37 @@ +// The pinned dock's divider is a keyboard separator: the arrow toward the +// page widens the dock, the arrow away narrows it, both stop at the allowed +// range, and the width is saved. +const assert = require('node:assert/strict'); +const h = require('./helpers/chat-dock.cjs'); + +const width = (page) => h.dockOf(page).boundingBox().then((b) => Math.round(b.width)); +const value = (page) => h.dividerOf(page).getAttribute('aria-valuenow').then(Number); + +module.exports = async ({ page, go }) => { + const divider = h.dividerOf(page); + for (const [side, grow, shrink] of [['right', 'ArrowLeft', 'ArrowRight'], ['left', 'ArrowRight', 'ArrowLeft']]) { + await h.load(page, go, JSON.stringify({ side, width: 420 })); + await h.expand(page); + await divider.focus(); + assert.equal(await value(page), 420); + assert.equal(await divider.getAttribute('aria-valuemin'), '320'); + + await page.keyboard.press(grow); + await h.until(async () => (await value(page)) === 436 && (await width(page)) === 436, `${side}: ${grow} did not widen by 16`); + await page.keyboard.press(shrink); + await page.keyboard.press(shrink); + await h.until(async () => (await value(page)) === 404 && (await width(page)) === 404, `${side}: ${shrink} did not narrow by 16`); + assert.equal((await h.saved(page)).width, 404, `${side}: the width was not saved`); + + await page.keyboard.press('ArrowUp'); + assert.equal(await value(page), 404, `${side}: a vertical arrow resized the dock`); + + for (let i = 0; i < 12; i++) await page.keyboard.press(shrink); + await h.until(async () => (await width(page)) === 320, `${side}: the dock narrowed past its minimum`); + assert.equal(await value(page), 320); + + for (let i = 0; i < 30; i++) await page.keyboard.press(grow); + await h.until(async () => (await width(page)) === 720, `${side}: the dock widened past its maximum`); + assert.equal(await value(page), 720); + } +}; diff --git a/e2e/checks/helpers/chat-dock.cjs b/e2e/checks/helpers/chat-dock.cjs new file mode 100644 index 000000000..e21b3154a --- /dev/null +++ b/e2e/checks/helpers/chat-dock.cjs @@ -0,0 +1,63 @@ +// Shared handles for the chat dock checks: the dock's own storage key, its +// landmarks, and the pointer gestures that pin it. +const assert = require('node:assert/strict'); + +const KEY = 'archie.chat.dock'; + +const dockOf = (page) => page.getByRole('complementary', { name: 'Chat with Archie' }); +const composerOf = (page) => page.getByRole('combobox', { name: 'Message Archie', exact: true }); +const hideOf = (page) => page.getByRole('button', { name: 'Hide conversation' }); +const dividerOf = (page) => page.getByRole('separator', { name: 'Resize chat' }); + +const stored = (page) => page.evaluate((key) => localStorage.getItem(key), KEY); +const saved = async (page) => JSON.parse(await stored(page)); + +// Loads /events with the given stored layout (a string, or null for none). +async function load(page, go, layout = null) { + await go('/events'); + await page.evaluate(([key, value]) => (value === null ? localStorage.removeItem(key) : localStorage.setItem(key, value)), [KEY, layout]); + await go('/events'); +} + +// Focusing the composer is how the operator opens the conversation. +async function expand(page) { + await composerOf(page).focus(); + await hideOf(page).waitFor(); +} + +// Retries an assertion until it holds: the dock settles over a few frames. +async function until(check, message, timeout = 5000) { + const end = Date.now() + timeout; + let last; + for (;;) { + try { + const ok = await check(); + if (ok) return; + last = ok; + } catch (e) { + last = e; + } + if (Date.now() > end) throw new Error(`${message}${last instanceof Error ? `: ${last.message}` : ''}`); + await new Promise((r) => setTimeout(r, 50)); + } +} + +const near = (a, b, message, tolerance = 1) => assert.ok(Math.abs(a - b) <= tolerance, `${message}: ${a} is not within ${tolerance} of ${b}`); + +// The empty strip at the top of the header, where a drag starts. +async function grip(page) { + const box = await dockOf(page).boundingBox(); + return { x: box.x + box.width / 2, y: box.y + 8 }; +} + +async function dragTo(page, x, steps = 10) { + const from = await grip(page); + await page.mouse.move(from.x, from.y); + await page.mouse.down(); + await page.mouse.move(x, from.y, { steps }); + return from; +} + +const mainRect = (page) => page.locator('#main-content').boundingBox(); + +module.exports = { KEY, dockOf, composerOf, hideOf, dividerOf, stored, saved, load, expand, until, near, grip, dragTo, mainRect }; diff --git a/internal/gateway/chat_local.go b/internal/gateway/chat_local.go index 03e75edaf..884011e3f 100644 --- a/internal/gateway/chat_local.go +++ b/internal/gateway/chat_local.go @@ -230,7 +230,7 @@ func (a *LocalChatAdapter) runStreamedTurn(ctx context.Context, in Inbound, id s run := func(turnCtx context.Context) ChatEvent { reply, err := a.Router.streamTurn(turnCtx, in, stream) if err != nil { - return ChatEvent{Kind: "error", Text: err.Error(), SessionID: id} + return ChatEvent{Kind: "error", Text: turnFailureText(err), SessionID: id} } resolvedID := id if resolved, err := a.Router.ResolveSessionKey(turnCtx, in); err == nil { @@ -306,7 +306,7 @@ func (a *LocalChatAdapter) prelude(ctx context.Context, in Inbound, id string) s } ready, mine, err := a.Router.CollectTurn(ctx, in) if err != nil { - return streamPrelude{event: &ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}} + return streamPrelude{event: &ChatEvent{Kind: "error", Text: turnFailureText(err), SessionID: id}} } return streamPrelude{ready: ready, proceeds: mine} } diff --git a/internal/gateway/turn.go b/internal/gateway/turn.go index 1a2cc474a..106e926c1 100644 --- a/internal/gateway/turn.go +++ b/internal/gateway/turn.go @@ -580,7 +580,7 @@ func (r *TurnRunner) failTurn(ctx context.Context, turn TurnRecord, cause error) } else { turn.Status = TurnStatusFailed } - turn.Error = cause.Error() + turn.Error = turnFailureText(cause) turn.UpdatedAt = time.Now().UTC() if r.Log != nil { level := slog.LevelError diff --git a/internal/gateway/turn_failure.go b/internal/gateway/turn_failure.go new file mode 100644 index 000000000..19964d5bb --- /dev/null +++ b/internal/gateway/turn_failure.go @@ -0,0 +1,30 @@ +package gateway + +import ( + "context" + "errors" + + "github.com/samcharles93/ai-sdk/chat" +) + +// turnFailureText is what a chat reader sees when a turn fails. The cause +// carries provider bodies, URLs and wrapping that belong in the log, which +// failTurn writes, not in front of whoever is chatting. +func turnFailureText(err error) string { + switch { + case errors.Is(err, chat.ErrRateLimited): + return "the model provider is refusing requests (rate limit or spending cap). Try again later, or switch model with /model." + case errors.Is(err, chat.ErrAuthFailed): + return "the model provider rejected Archie's credentials. Check the provider key in settings." + case errors.Is(err, chat.ErrProviderUnavailable): + return "the model provider is unavailable. Try again in a moment." + case errors.Is(err, chat.ErrContextLength): + return "this conversation is too long for the model. Start a new chat, or shorten it with /compress." + case errors.Is(err, chat.ErrUnsupportedContent): + return "the model can't read one of the attachments. Remove it, or switch model with /model." + case errors.Is(err, context.DeadlineExceeded): + return "the model took too long to answer. Try again." + default: + return "something went wrong on Archie's side. Try again; the gateway log has the cause." + } +} diff --git a/internal/gateway/turn_failure_test.go b/internal/gateway/turn_failure_test.go new file mode 100644 index 000000000..1eead81aa --- /dev/null +++ b/internal/gateway/turn_failure_test.go @@ -0,0 +1,50 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/samcharles93/ai-sdk/chat" + + "github.com/samcharles93/archie-core/internal/domain/messaging" +) + +// A failed turn shows the reader what to do, never the provider's response +// body or the error's wrapping. +func TestStreamedTurnFailureHidesCause(t *testing.T) { + for _, tc := range []struct { + name string + cause error + want string + }{ + {name: "spending cap", cause: chat.ErrRateLimited, want: "rate limit or spending cap"}, + {name: "bad key", cause: chat.ErrAuthFailed, want: "credentials"}, + {name: "unknown", cause: errors.New("dial tcp 10.0.0.1:5432: refused"), want: "gateway log"}, + } { + t.Run(tc.name, func(t *testing.T) { + raw := fmt.Errorf(`llm chat stream: gemini: status 429: {"message":"https://ai.studio/spend"}: %w`, tc.cause) + router := &Router{LLMStream: func(context.Context, Inbound, TurnStream) (string, error) { return "", raw }} + adapter := &LocalChatAdapter{Router: router} + events := make(chan ChatEvent, 32) + go adapter.runStreamedTurn(context.Background(), Inbound{Message: messaging.Message{Text: "hi"}}, "s1", events) + for event := range events { + if event.Kind != "error" { + continue + } + for _, leak := range []string{"gemini", "429", "ai.studio", "10.0.0.1", "llm chat stream"} { + if strings.Contains(event.Text, leak) { + t.Fatalf("error text %q exposes %q", event.Text, leak) + } + } + if !strings.Contains(event.Text, tc.want) { + t.Fatalf("error text %q, want it to mention %q", event.Text, tc.want) + } + return + } + t.Fatal("no error event") + }) + } +} diff --git a/internal/infrastructure/controlplanestore/telegram_connection.go b/internal/infrastructure/controlplanestore/telegram_connection.go index 9274ac941..eee4468c0 100644 --- a/internal/infrastructure/controlplanestore/telegram_connection.go +++ b/internal/infrastructure/controlplanestore/telegram_connection.go @@ -100,6 +100,9 @@ func splitLegacyChannelSettings(orgID string, stored []byte) (rewritten []byte, return nil, telegramConnection{}, false, fmt.Errorf("decode telegram: %w", err) } delete(doc, "telegram") + // A document old enough to carry telegram can also carry the per-channel + // models that model aliases replaced, which the current schema rejects. + delete(doc, "models") if orgID == storecontract.DefaultOrgID { moved = telegramConnection{Token: legacy.TokenRef, Users: legacy.AllowedUserIDs} } else if len(legacy.AllowedUserIDs) > 0 { diff --git a/ui/src/App.vue b/ui/src/App.vue index d640dea9d..0c2fd567a 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -96,7 +96,7 @@ watch(() => accounts.status?.user, (user) => { Skip to main content - +
diff --git a/ui/src/chat/ChatComposer.vue b/ui/src/chat/ChatComposer.vue index 2aba045a8..2c0f237d7 100644 --- a/ui/src/chat/ChatComposer.vue +++ b/ui/src/chat/ChatComposer.vue @@ -7,15 +7,24 @@ import { Clock, Mic, Pencil, X } from "@lucide/vue"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { Textarea } from "@/components/ui/textarea"; -import { applyCommand, isExactCommand } from "./commands"; +import { isExactCommand, replaceToken } from "./commands"; import ChatSlashPalette from "./ChatSlashPalette.vue"; import { closeCommandMenu, commandMatches, commandSelection, commandSpecs, + addTaskTag, + clearPageTag, + pageTag, composerText, editQueued, + menuTrigger, + removeTaskTag, + retryTasks, + taskForKey, + taskLoadError, + taskTags, isCommandMenuOpen, isSending, moveCommandSelection, @@ -110,21 +119,27 @@ function onInput(event: Event): void { } function choose(index: number): void { - const spec = commandMatches.value[index]; + const item = commandMatches.value[index]; const input = field.value?.$el; - if (!spec || !input) return; - // Completing the command replaces the token the caret sits in, which is - // decided by the same rule that found the matches. - const { text, cursor } = applyCommand( - input.value, - input.selectionStart ?? input.value.length, - spec.command, - ); - composerText.value = text; + if (!item || !input) return; + const caret = input.selectionStart ?? input.value.length; + // Completing replaces the token the caret sits in, which is decided by the + // same rule that found the matches. A task leaves no text behind: it becomes + // a tag above the field. + let edit: { text: string; cursor: number }; + if (menuTrigger.value === "#") { + const task = taskForKey(item.key); + if (!task) return; + addTaskTag(task); + edit = replaceToken(input.value, caret, ""); + } else { + edit = replaceToken(input.value, caret, item.label); + } + composerText.value = edit.text; closeCommandMenu(); void nextTick(() => { input.focus(); - input.setSelectionRange(cursor, cursor); + input.setSelectionRange(edit.cursor, edit.cursor); }); } @@ -132,12 +147,13 @@ function onKeydown(event: KeyboardEvent): void { // Safari may end composition before delivering its confirming Enter. if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) return; const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey; - if (isCommandMenuOpen.value && commandMatches.value.length) { + if (isCommandMenuOpen.value) { // A command typed in full is sent rather than completed, so Enter never // re-enters the command the palette was offering. if ( event.key === "Enter" && plain && + menuTrigger.value === "/" && isExactCommand(commandSpecs.value, composerText.value) ) { event.preventDefault(); @@ -155,7 +171,10 @@ function onKeydown(event: KeyboardEvent): void { moveCommandSelection(-1); return; } - if (event.key === "Enter" && plain) { + if ( + commandMatches.value.length && + ((event.key === "Enter" && plain) || (event.key === "Tab" && !event.shiftKey)) + ) { event.preventDefault(); choose(commandSelection.value); return; @@ -202,6 +221,27 @@ function onKeydown(event: KeyboardEvent): void { +
    +
  • + {{ pageTag.label }} + +
  • +
  • + #{{ tag.id }}{{ tag.title ? ` ${tag.title}` : "" }} + +
  • +
diff --git a/ui/src/chat/ChatDock.vue b/ui/src/chat/ChatDock.vue index 6d9947731..1cc9f9d1a 100644 --- a/ui/src/chat/ChatDock.vue +++ b/ui/src/chat/ChatDock.vue @@ -1,13 +1,18 @@