Merge branch 'main' into fix/1913-intake-skip-disabled
Quality / check (pull_request) Successful in 8m11s

This commit is contained in:
sam committed 2026-11-12 13:43:34 +00:00
commit 76be7b87b2
43 files changed
+1898 -230

No files matched your search

+2 -1
View File
@@ -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.
+42
View File
@@ -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');
};
+27
View File
@@ -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');
};
+46
View File
@@ -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');
};
+41
View File
@@ -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);
}
};
+59
View File
@@ -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' });
};
+52
View File
@@ -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');
};
+37
View File
@@ -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);
}
};
+63
View File
@@ -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 };
+1 -120
View File
@@ -2,13 +2,9 @@ package archiegateway
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"path/filepath"
"strings"
"time"
"unicode/utf8"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
@@ -220,7 +216,7 @@ func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, op
if err != nil {
return "", chat.Usage{}, fmt.Errorf("llm chat stream: %w", err)
}
text := drainChatStream(stream.FullStream, turn, icons)
text := gateway.DrainStreamParts(stream.FullStream, turn, icons)
var used chat.Usage
if stream.Usage != nil {
used, _ = stream.Usage()
@@ -231,121 +227,6 @@ func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, op
return text, used, nil
}
// pendingToolCall is a tool invocation awaiting its result.
type pendingToolCall struct {
name string
parameters string
started time.Time
offset int
}
// took is the call's running time so far, zero for a result with no
// recorded invocation.
func (c pendingToolCall) took() int64 {
if c.started.IsZero() {
return 0
}
return time.Since(c.started).Milliseconds()
}
// drainChatStream consumes a model stream to close, reporting assistant text
// and each completed tool call to turn, and returns the assembled reply.
//
// FullStream is authoritative and its writes are synchronous, so it must be
// drained to close even when turn is nil -- an unread stream stalls the
// generating goroutine.
//
// A tool is reported on its result, never on its call: the call part carries
// no outcome yet, so reporting both would show every tool twice, once with
// nothing to say.
func drainChatStream(parts <-chan core.StreamPart, turn gateway.TurnStream, icons map[string]string) string {
var sb strings.Builder
pending := make(map[string]pendingToolCall)
runes := 0
for part := range parts {
switch part.Type {
case core.StreamPartTextDelta:
if part.TextDelta == "" {
continue
}
sb.WriteString(part.TextDelta)
runes += utf8.RuneCountInString(part.TextDelta)
if turn != nil {
turn.Delta(part.TextDelta)
}
case core.StreamPartToolCall:
if part.ToolCall == nil || part.ToolCall.ToolCallID == "" {
continue
}
pending[part.ToolCall.ToolCallID] = pendingToolCall{
name: part.ToolCall.ToolName,
parameters: gateway.SummarizeToolParameters(part.ToolCall.Input),
started: time.Now(),
offset: runes,
}
case core.StreamPartToolResult:
if part.ToolResult == nil || turn == nil {
continue
}
call := pending[part.ToolResult.ToolCallID]
delete(pending, part.ToolResult.ToolCallID)
name := part.ToolResult.ToolName
if name == "" {
name = call.name
}
turn.ToolCall(gateway.ToolCallEvent{
ID: part.ToolResult.ToolCallID,
Name: name,
Emoji: icons[name],
Parameters: call.parameters,
Output: part.ToolResult.Output,
Err: part.ToolResult.Error,
DurationMS: call.took(),
TextOffset: call.offset,
})
for _, ref := range multimodalMediaRefs(part.ToolResult.Output) {
// Path and URL are alternatives, not a pair: the channel
// uploads one and fetches the other. A ref carrying
// neither names nothing deliverable, so it is dropped
// rather than sent as an empty attachment.
if ref.URL == "" && ref.Path == "" {
continue
}
turn.Media(gateway.MediaEvent{
ToolName: name,
Attachment: gateway.MediaAttachment{
Type: ref.Type,
URL: ref.URL,
Path: ref.Path,
FileName: ref.FileName,
},
})
}
}
}
return sb.String()
}
// multimodalMediaRefs extracts the URLs a tool result carries when its
// output is a tools.MultimodalResult, so drainChatStream can report each as
// a gateway.MediaEvent alongside the ordinary ToolCall event.
//
// output is decoded with json.Unmarshal directly rather than checked
// against a schema first: most tool output is plain text or unrelated
// JSON, and unmarshalling into MultimodalResult simply leaves IsMultimodal
// false for anything that doesn't match, which is exactly "not multimodal"
// -- no separate detection step earns its keep here.
func multimodalMediaRefs(output string) []tools.MediaRef {
if output == "" {
return nil
}
var result tools.MultimodalResult
if err := json.Unmarshal([]byte(output), &result); err != nil || !result.IsMultimodal {
return nil
}
return result.URLs
}
// chatTitleGenerator proposes session titles through the chat model. It
// is a pure proposal: it persists nothing, so a failed or slow title
// call can never corrupt conversation history or fail the turn. The
+6
View File
@@ -331,6 +331,12 @@ func (s localChatStream) Delta(text string) {
s.send(ChatEvent{Kind: "delta", Text: text})
}
// Reasoning forwards one fragment of the model's thinking as its own event
// kind; the dashboard renders it as the live turn's thinking trace.
func (s localChatStream) Reasoning(text string) {
s.send(ChatEvent{Kind: "reasoning", Text: text})
}
func (s localChatStream) ToolCall(event ToolCallEvent) {
s.send(ChatEvent{Kind: "tool", Tool: event})
}
+124
View File
@@ -0,0 +1,124 @@
package gateway
import (
"reflect"
"testing"
"github.com/samcharles93/ai-sdk/core"
)
// A fake ai-sdk FullStream drives the drain: every part must reach the turn
// stream in order, and a reasoning delta must surface as a Kind "reasoning"
// ChatEvent carrying its text. Text deltas and tool results keep working.
func TestDrainStreamPartsForwardsStreamParts(t *testing.T) {
cases := []struct {
name string
parts []core.StreamPart
want []ChatEvent
wantText string
}{
{
name: "reasoning deltas become reasoning events",
parts: []core.StreamPart{
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "considering "},
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "the request"},
},
want: []ChatEvent{
{Kind: "reasoning", Text: "considering ", SessionID: "s1"},
{Kind: "reasoning", Text: "the request", SessionID: "s1"},
},
},
{
name: "text deltas still stream and assemble the reply",
parts: []core.StreamPart{
{Type: core.StreamPartTextDelta, TextDelta: "Hello, "},
{Type: core.StreamPartTextDelta, TextDelta: "world"},
},
want: []ChatEvent{
{Kind: "delta", Text: "Hello, ", SessionID: "s1"},
{Kind: "delta", Text: "world", SessionID: "s1"},
},
wantText: "Hello, world",
},
{
name: "reasoning ahead of the answer text",
parts: []core.StreamPart{
{Type: core.StreamPartReasoningDelta, ReasoningDelta: "hmm"},
{Type: core.StreamPartTextDelta, TextDelta: "answer"},
},
want: []ChatEvent{
{Kind: "reasoning", Text: "hmm", SessionID: "s1"},
{Kind: "delta", Text: "answer", SessionID: "s1"},
},
wantText: "answer",
},
{
name: "an empty reasoning delta is dropped",
parts: []core.StreamPart{
{Type: core.StreamPartReasoningDelta, ReasoningDelta: ""},
{Type: core.StreamPartTextDelta, TextDelta: "hi"},
},
want: []ChatEvent{{Kind: "delta", Text: "hi", SessionID: "s1"}},
wantText: "hi",
},
{
name: "a completed tool call still reports its tool event",
parts: []core.StreamPart{
{Type: core.StreamPartToolCall, ToolCall: &core.ToolCall{ToolCallID: "t1", ToolName: "search", Input: `{"q":"archie"}`}},
{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolCallID: "t1", ToolName: "search", Output: "42"}},
},
want: []ChatEvent{{
Kind: "tool",
SessionID: "s1",
Tool: ToolCallEvent{
ID: "t1",
Name: "search",
Emoji: "🔍",
Parameters: SummarizeToolParameters(`{"q":"archie"}`),
Output: "42",
},
}},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
parts := make(chan core.StreamPart, len(tc.parts))
for _, part := range tc.parts {
parts <- part
}
close(parts)
events := make(chan ChatEvent, len(tc.parts)+1)
stream := localChatStream{done: make(chan struct{}), events: events, sessionID: "s1"}
text := DrainStreamParts(parts, stream, map[string]string{"search": "🔍"})
var got []ChatEvent
for {
select {
case event := <-events:
got = append(got, event)
default:
if !reflect.DeepEqual(got, tc.want) {
t.Fatalf("events = %+v, want %+v", got, tc.want)
}
if text != tc.wantText {
t.Fatalf("reply text = %q, want %q", text, tc.wantText)
}
return
}
}
})
}
}
// A stream nobody renders still has to be drained to close: an unread
// FullStream stalls the generating goroutine, reasoning included.
func TestDrainStreamPartsWithoutStreamStillDrains(t *testing.T) {
parts := make(chan core.StreamPart, 3)
parts <- core.StreamPart{Type: core.StreamPartReasoningDelta, ReasoningDelta: "thinking"}
parts <- core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "reply"}
close(parts)
if text := DrainStreamParts(parts, nil, nil); text != "reply" {
t.Fatalf("reply text = %q, want %q", text, "reply")
}
}
+161 -1
View File
@@ -1,12 +1,30 @@
package gateway
import "github.com/samcharles93/archie-core/internal/domain/messaging"
import (
"encoding/json"
"strings"
"time"
"unicode/utf8"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/tools"
)
// SummarizeToolParameters returns a bounded JSON shape of tool input.
func SummarizeToolParameters(input string) string {
return messaging.SummarizeToolParameters(input)
}
// ReasoningStream is the optional TurnStream extension for the model's
// thinking. It is separate from TurnStream so streams that cannot render
// reasoning keep satisfying TurnStream unchanged; producers type-assert.
type ReasoningStream interface {
// Reasoning appends the next fragment of the model's reasoning.
Reasoning(text string)
}
type toolCallRecorder struct {
next TurnStream
events []ToolCallEvent
@@ -18,6 +36,12 @@ func (r *toolCallRecorder) Delta(text string) {
}
}
func (r *toolCallRecorder) Reasoning(text string) {
if rs, ok := r.next.(ReasoningStream); ok {
rs.Reasoning(text)
}
}
func (r *toolCallRecorder) ToolCall(event ToolCallEvent) {
r.events = append(r.events, event)
if r.next != nil {
@@ -30,3 +54,139 @@ func (r *toolCallRecorder) Media(event MediaEvent) {
r.next.Media(event)
}
}
// pendingToolCall is a tool invocation awaiting its result.
type pendingToolCall struct {
name string
parameters string
started time.Time
offset int
}
// took is the call's running time so far, zero for a result with no
// recorded invocation.
func (c pendingToolCall) took() int64 {
if c.started.IsZero() {
return 0
}
return time.Since(c.started).Milliseconds()
}
// DrainStreamParts consumes an ai-sdk FullStream to close, reporting the
// model's reasoning, assistant text and each completed tool call to turn,
// and returns the assembled reply.
//
// The parts channel is authoritative and its writes are synchronous, so it
// must be drained to close even when turn is nil -- an unread stream stalls
// the generating goroutine.
//
// A tool is reported on its result, never on its call: the call part carries
// no outcome yet, so reporting both would show every tool twice, once with
// nothing to say.
func DrainStreamParts(parts <-chan core.StreamPart, turn TurnStream, icons map[string]string) string {
var sb strings.Builder
pending := make(map[string]pendingToolCall)
runes := 0
for part := range parts {
switch part.Type {
case core.StreamPartReasoningDelta:
reportReasoning(turn, part.ReasoningDelta)
case core.StreamPartTextDelta:
if part.TextDelta == "" {
continue
}
sb.WriteString(part.TextDelta)
runes += utf8.RuneCountInString(part.TextDelta)
if turn != nil {
turn.Delta(part.TextDelta)
}
case core.StreamPartToolCall:
if part.ToolCall == nil || part.ToolCall.ToolCallID == "" {
continue
}
pending[part.ToolCall.ToolCallID] = pendingToolCall{
name: part.ToolCall.ToolName,
parameters: SummarizeToolParameters(part.ToolCall.Input),
started: time.Now(),
offset: runes,
}
case core.StreamPartToolResult:
reportToolResult(turn, part.ToolResult, pending, icons)
}
}
return sb.String()
}
// reportReasoning forwards one reasoning fragment to a stream that can
// render thinking. Reasoning is not part of the reply text, so it travels on
// its own stream method; a stream without that method simply gets none.
func reportReasoning(turn TurnStream, delta string) {
if delta == "" {
return
}
if rs, ok := turn.(ReasoningStream); ok {
rs.Reasoning(delta)
}
}
// reportToolResult reports one finished tool invocation, plus any media
// attachment its output carries, to the turn.
func reportToolResult(turn TurnStream, result *core.ToolResult, pending map[string]pendingToolCall, icons map[string]string) {
if result == nil || turn == nil {
return
}
call := pending[result.ToolCallID]
delete(pending, result.ToolCallID)
name := result.ToolName
if name == "" {
name = call.name
}
turn.ToolCall(ToolCallEvent{
ID: result.ToolCallID,
Name: name,
Emoji: icons[name],
Parameters: call.parameters,
Output: result.Output,
Err: result.Error,
DurationMS: call.took(),
TextOffset: call.offset,
})
for _, ref := range multimodalMediaRefs(result.Output) {
// Path and URL are alternatives, not a pair: the channel uploads one
// and fetches the other. A ref carrying neither names nothing
// deliverable, so it is dropped rather than sent as an empty
// attachment.
if ref.URL == "" && ref.Path == "" {
continue
}
turn.Media(MediaEvent{
ToolName: name,
Attachment: MediaAttachment{
Type: ref.Type,
URL: ref.URL,
Path: ref.Path,
FileName: ref.FileName,
},
})
}
}
// multimodalMediaRefs extracts the URLs a tool result carries when its
// output is a tools.MultimodalResult, so DrainStreamParts can report each as
// a MediaEvent alongside the ordinary ToolCall event.
//
// output is decoded with json.Unmarshal directly rather than checked
// against a schema first: most tool output is plain text or unrelated
// JSON, and unmarshalling into MultimodalResult simply leaves IsMultimodal
// false for anything that doesn't match, which is exactly "not multimodal"
// -- no separate detection step earns its keep here.
func multimodalMediaRefs(output string) []tools.MediaRef {
if output == "" {
return nil
}
var result tools.MultimodalResult
if err := json.Unmarshal([]byte(output), &result); err != nil || !result.IsMultimodal {
return nil
}
return result.URLs
}
+51 -14
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"path/filepath"
"strings"
@@ -141,6 +142,7 @@ type chatToolView struct {
// waiting for the browser's answer and files a turn offered for download.
type chatAPI struct {
chat *ChatService
log *slog.Logger
updateReportPath string
configSource func() ConfigViewSource
@@ -149,7 +151,7 @@ type chatAPI struct {
}
func newChatAPI(s *Server) *chatAPI {
return &chatAPI{chat: s.Chat, updateReportPath: s.UpdateReportPath, configSource: s.configSource}
return &chatAPI{chat: s.Chat, log: s.Log, updateReportPath: s.UpdateReportPath, configSource: s.configSource}
}
func (a *chatAPI) register(mux *http.ServeMux) {
@@ -173,6 +175,21 @@ func (a *chatAPI) chatReady(w http.ResponseWriter) (*ChatService, bool) {
return a.chat, true
}
// chatFailureText is what the browser sees when a chat backend call fails.
// The cause can carry SQL, gRPC status details or host paths, so failChat
// logs it server-side and sends this sentence instead, in the same plain
// wording the gateway gives chat readers for a failed turn.
const chatFailureText = "something went wrong on Archie's side. Try again; the server log has the cause."
// failChat logs the real cause with the request's trace and answers with the
// plain sentence. A nil logger is tolerated, as tests build servers without one.
func (a *chatAPI) failChat(ctx context.Context, w http.ResponseWriter, status int, err error) {
if a.log != nil {
a.log.ErrorContext(ctx, "chat endpoint failed", "error", err, "status", status)
}
http.Error(w, chatFailureText, status)
}
func chatUpdateServiceConfigured(updates ChatUpdateService) bool {
return !lifecycle.IsNil(updates)
}
@@ -184,7 +201,7 @@ func (a *chatAPI) handleChatSessions(w http.ResponseWriter, r *http.Request) {
}
snapshot, err := chat.Contract.Snapshot(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
out := make([]messaging.SessionContext, 0, len(snapshot.Sessions))
@@ -218,7 +235,7 @@ func (a *chatAPI) handleChatMessages(w http.ResponseWriter, r *http.Request) {
sessionID := r.PathValue("id")
session, found, err := chat.Contract.GetSession(r.Context(), sessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !found || !a.ownsChatSession(r.Context(), session) {
@@ -227,7 +244,7 @@ func (a *chatAPI) handleChatMessages(w http.ResponseWriter, r *http.Request) {
}
messages, err := chat.Contract.RecentMessages(r.Context(), sessionID, 200)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
views := make([]chatMessageView, 0, len(messages))
@@ -249,7 +266,7 @@ func (a *chatAPI) handleChatTurns(w http.ResponseWriter, r *http.Request) {
sessionID := r.PathValue("id")
session, found, err := chat.Contract.GetSession(r.Context(), sessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !found || !a.ownsChatSession(r.Context(), session) {
@@ -258,7 +275,7 @@ func (a *chatAPI) handleChatTurns(w http.ResponseWriter, r *http.Request) {
}
turns, err := chat.Contract.RecentTurns(r.Context(), sessionID, 200)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
views := make([]chatTurnView, 0, len(turns))
@@ -475,7 +492,7 @@ func (a *chatAPI) handleChatStream(w http.ResponseWriter, r *http.Request) {
asker := dashboardAsker{asks: &a.asks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
events, err := chat.Contract.Stream(withDashboardAsks(r.Context(), asker), msg)
if err != nil {
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
a.failChatStream(r.Context(), writeChatEvent, err)
return
}
sink := chatStreamSink{showToolCalls: a.chatShowToolCalls(r.Context()), files: &a.files, owner: chatUser(r.Context())}
@@ -492,6 +509,15 @@ func (a *chatAPI) handleChatStream(w http.ResponseWriter, r *http.Request) {
}
}
// failChatStream answers a stream that never opened with the plain sentence
// as its error frame, logging the real cause server-side.
func (a *chatAPI) failChatStream(ctx context.Context, write func(chatStreamEvent, string), err error) {
if a.log != nil {
a.log.ErrorContext(ctx, "chat stream failed to start", "error", err)
}
write(chatStreamEvent{Type: "error", Text: chatFailureText}, "")
}
func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
@@ -499,7 +525,7 @@ func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
}
snapshot, err := chat.Contract.Snapshot(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !snapshot.CancellationAvailable {
@@ -513,7 +539,7 @@ func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
}
session, found, err := chat.Contract.GetSession(r.Context(), req.SessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !found || !a.ownsChatSession(r.Context(), session) {
@@ -522,7 +548,7 @@ func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
}
result, err := chat.Contract.Cancel(r.Context(), req.SessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
writeJSON(w, map[string]any{"cancelled": result.Cancelled, "dropped": result.Dropped})
@@ -538,6 +564,17 @@ func writeUpdateCheckError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadGateway)
}
// failUpdateCheck is the chat endpoints' version of writeUpdateCheckError: any
// other cause can carry registry URLs or host paths, so it gets the plain
// sentence and the log rather than the raw error.
func (a *chatAPI) failUpdateCheck(ctx context.Context, w http.ResponseWriter, err error) {
if errors.Is(err, releaseupdate.ErrNotConfigured) {
http.Error(w, "updates are not configured", http.StatusNotImplemented)
return
}
a.failChat(ctx, w, http.StatusBadGateway, err)
}
func (a *chatAPI) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
@@ -549,7 +586,7 @@ func (a *chatAPI) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
}
snapshot, err := chat.Updates.Check(r.Context(), 0)
if err != nil {
writeUpdateCheckError(w, err)
a.failUpdateCheck(r.Context(), w, err)
return
}
// The snapshot carries when the installed release was committed on this
@@ -586,7 +623,7 @@ func (a *chatAPI) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request)
return
}
if err := chat.Updates.Defer(r.Context(), 0, req.Snapshot); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
a.failChat(r.Context(), w, http.StatusConflict, err)
return
}
writeJSON(w, map[string]bool{"ok": true})
@@ -608,7 +645,7 @@ func (a *chatAPI) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request
}
fresh, err := chat.Updates.Check(r.Context(), 0)
if err != nil {
writeUpdateCheckError(w, err)
a.failUpdateCheck(r.Context(), w, err)
return
}
if !releaseupdate.SameAvailable(fresh, req.Snapshot) {
@@ -633,7 +670,7 @@ func (a *chatAPI) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: a.updateReportPath}
result, err := chat.Updates.Install(r.Context(), fresh, meta, func(message string) { progress = append(progress, message) })
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
a.failChat(r.Context(), w, http.StatusBadGateway, err)
return
}
writeJSON(w, map[string]any{"ok": true, "progress": progress, "result": result})
+202
View File
@@ -0,0 +1,202 @@
package webui
import (
"bytes"
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
// internalDetail stands in for the SQL fragments, gRPC status details and host
// paths a real contract failure carries; none of it may reach the browser.
const internalDetail = `pq: relation "chat_messages" does not exist: SELECT * FROM chat_messages WHERE session_id=$1 (/var/lib/archie/state.db): rpc error: code = Internal desc = session store unavailable`
var errInternal = errors.New(internalDetail)
// plainChatFailure is the sentence the browser must see instead; spelled out
// here so the test also compiles, and fails, against the unsanitised handlers.
const plainChatFailure = "something went wrong on Archie's side. Try again; the server log has the cause."
// failingChat fails the contract methods its fields name, so one fake covers
// every chat endpoint.
type failingChat struct {
messaging.ChatContract
snapshotErr, sessionErr, messagesErr, turnsErr, cancelErr, streamErr error
}
func (f failingChat) Snapshot(context.Context) (messaging.ChatSnapshot, error) {
if f.snapshotErr != nil {
return messaging.ChatSnapshot{}, f.snapshotErr
}
return messaging.ChatSnapshot{CancellationAvailable: true}, nil
}
func (f failingChat) GetSession(context.Context, string) (messaging.SessionContext, bool, error) {
if f.sessionErr != nil {
return messaging.SessionContext{}, false, f.sessionErr
}
return messaging.SessionContext{SessionID: "s1", Source: messaging.SessionSource{Platform: "web", ThreadID: "alice"}}, true, nil
}
func (f failingChat) RecentMessages(context.Context, string, int) ([]messaging.Message, error) {
if f.messagesErr != nil {
return nil, f.messagesErr
}
return []messaging.Message{}, nil
}
func (f failingChat) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) {
if f.turnsErr != nil {
return nil, f.turnsErr
}
return []messaging.TurnRecord{}, nil
}
func (f failingChat) Stream(context.Context, messaging.Inbound) (<-chan messaging.ChatEvent, error) {
return nil, f.streamErr
}
func (f failingChat) Cancel(context.Context, string) (messaging.ChatCancellation, error) {
if f.cancelErr != nil {
return messaging.ChatCancellation{}, f.cancelErr
}
return messaging.ChatCancellation{Cancelled: true}, nil
}
type failingUpdates struct {
ChatUpdateService
err error
}
func (f failingUpdates) Check(context.Context, int64) (releaseupdate.Snapshot, error) {
return releaseupdate.Snapshot{}, f.err
}
func chatErrorRequest(t *testing.T, method, target, body string) *http.Request {
t.Helper()
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: identity.IdentityID("alice")})
req := httptest.NewRequestWithContext(ctx, method, target, strings.NewReader(body))
req.SetPathValue("id", "s1")
return req
}
func assertSanitised(t *testing.T, body, log string) {
t.Helper()
if strings.Contains(body, internalDetail) {
t.Errorf("response leaks the internal error: %s", body)
}
for _, fragment := range []string{"pq:", "chat_messages", "/var/lib", "rpc error"} {
if strings.Contains(body, fragment) {
t.Errorf("response leaks internal fragment %q: %s", fragment, body)
}
}
if !strings.Contains(body, plainChatFailure) {
t.Errorf("response is missing the plain message, got: %s", body)
}
if !strings.Contains(log, "session store unavailable") {
t.Errorf("the real error was not logged server-side, log: %s", log)
}
}
func TestChatEndpointErrorsAreSanitised(t *testing.T) {
for _, tc := range []struct {
name string
contract failingChat
handler func(*chatAPI, http.ResponseWriter, *http.Request)
body string
wantStatus int
}{
{"sessions snapshot", failingChat{snapshotErr: errInternal}, (*chatAPI).handleChatSessions, "", http.StatusInternalServerError},
{"messages session lookup", failingChat{sessionErr: errInternal}, (*chatAPI).handleChatMessages, "", http.StatusInternalServerError},
{"messages history", failingChat{messagesErr: errInternal}, (*chatAPI).handleChatMessages, "", http.StatusInternalServerError},
{"turns session lookup", failingChat{sessionErr: errInternal}, (*chatAPI).handleChatTurns, "", http.StatusInternalServerError},
{"turns history", failingChat{turnsErr: errInternal}, (*chatAPI).handleChatTurns, "", http.StatusInternalServerError},
{"cancel snapshot", failingChat{snapshotErr: errInternal}, (*chatAPI).handleChatCancel, `{"session_id":"s1"}`, http.StatusInternalServerError},
{"cancel session lookup", failingChat{sessionErr: errInternal}, (*chatAPI).handleChatCancel, `{"session_id":"s1"}`, http.StatusInternalServerError},
{"cancel call", failingChat{cancelErr: errInternal}, (*chatAPI).handleChatCancel, `{"session_id":"s1"}`, http.StatusInternalServerError},
} {
t.Run(tc.name, func(t *testing.T) {
var logBuf bytes.Buffer
srv := &Server{Log: slog.New(slog.NewTextHandler(&logBuf, nil)), Chat: &ChatService{Contract: tc.contract}}
rec := httptest.NewRecorder()
tc.handler(newChatAPI(srv), rec, chatErrorRequest(t, "POST", "https://archie.example/api/chat/x", tc.body))
if rec.Code != tc.wantStatus {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tc.wantStatus, rec.Body.String())
}
assertSanitised(t, rec.Body.String(), logBuf.String())
})
}
}
func TestChatStreamErrorFrameIsSanitised(t *testing.T) {
var logBuf bytes.Buffer
srv := &Server{Log: slog.New(slog.NewTextHandler(&logBuf, nil)), Chat: &ChatService{Contract: failingChat{streamErr: errInternal}}}
rec := httptest.NewRecorder()
req := chatErrorRequest(t, "POST", "https://archie.example/api/chat/stream", `{"channel_id":"c","text":"hi"}`)
newChatAPI(srv).handleChatStream(rec, req)
body := rec.Body.String()
if !strings.Contains(body, `"type":"error"`) {
t.Fatalf("no error frame in stream: %s", body)
}
assertSanitised(t, body, logBuf.String())
}
func TestChatUpdateCheckErrorIsSanitised(t *testing.T) {
for _, tc := range []struct {
name string
err error
wantStatus int
wantBody string
}{
{"internal cause", errInternal, http.StatusBadGateway, plainChatFailure},
{"not configured", releaseupdate.ErrNotConfigured, http.StatusNotImplemented, "updates are not configured"},
} {
t.Run(tc.name, func(t *testing.T) {
var logBuf bytes.Buffer
srv := &Server{Log: slog.New(slog.NewTextHandler(&logBuf, nil)), Chat: &ChatService{Contract: failingChat{}, Updates: failingUpdates{err: tc.err}}}
rec := httptest.NewRecorder()
newChatAPI(srv).handleChatUpdate(rec, chatErrorRequest(t, "GET", "https://archie.example/api/chat/update", ""))
if rec.Code != tc.wantStatus {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tc.wantStatus, rec.Body.String())
}
if got := strings.TrimSpace(rec.Body.String()); got != tc.wantBody {
t.Fatalf("body=%q want=%q", got, tc.wantBody)
}
if errors.Is(tc.err, errInternal) {
assertSanitised(t, rec.Body.String(), logBuf.String())
}
})
}
}
func TestChatValidationMessagesStayUserFacing(t *testing.T) {
for _, tc := range []struct {
name, body, want string
}{
{"missing fields", `{"channel_id":"","text":""}`, "text and channel_id are required"},
{"undecodable", `{`, "invalid chat message"},
{"empty voice", `{"channel_id":"c","text":"hi","voice":{"data":"","mime_type":"audio/ogg"}}`, "voice clip is empty or too long"},
} {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := chatErrorRequest(t, "POST", "https://archie.example/api/chat/stream", tc.body)
if _, ok := newChatAPI(&Server{}).decodeChatMessage(rec, req); ok {
t.Fatal("message accepted")
}
if rec.Code != http.StatusBadRequest {
t.Fatalf("status=%d want=400", rec.Code)
}
if got := strings.TrimSpace(rec.Body.String()); got != tc.want {
t.Fatalf("body=%q want=%q", got, tc.want)
}
})
}
}
+1 -1
View File
@@ -116,7 +116,7 @@ watch(() => accounts.status?.user, (user) => {
<span class="max-md:hidden"><AccountMenu /></span>
</div>
</header>
<div id="main-content" ref="main" tabindex="-1" class="scroll-mt-16 w-full flex-1 px-6 py-5 pb-[calc(var(--chat-dock-clear,6rem)+1rem)] outline-none max-lg:p-4 max-lg:pb-[calc(var(--chat-dock-clear,6rem)+1rem)]"
<div id="main-content" ref="main" tabindex="-1" class="@container scroll-mt-16 w-full flex-1 px-6 py-5 pb-[calc(var(--chat-dock-clear,6rem)+1rem)] outline-none max-lg:p-4 max-lg:pb-[calc(var(--chat-dock-clear,6rem)+1rem)]"
:class="workflowsPage && 'max-md:flex max-md:min-h-0 max-md:flex-col'">
<!--
Keyed on the path and its parameters but not the query: a query-only
+11 -1
View File
@@ -7,6 +7,7 @@ import { CodeBlockCopyButton } from "@/components/ui/code-block";
import { Message, MessageContent, MessageFooter } from "@/components/ui/message";
import ChatAttachment from "./ChatAttachment.vue";
import ChatMarkdown from "./ChatMarkdown.vue";
import ChatThinking from "./ChatThinking.vue";
import ChatToolCall from "./ChatToolCall.vue";
import ChatToolGroup from "./ChatToolGroup.vue";
import type { ChatMedia, ChatToolCall as ToolCall } from "./state";
@@ -27,8 +28,12 @@ const props = withDefaults(
assistant?: boolean;
/** The turn is still arriving: a tool call with no outcome is running. */
streaming?: boolean;
/** The live turn's thinking so far, rendered as a collapsible trace. */
reasoning?: string;
/** The live turn is still arriving and has not reasoned yet. */
thinkingPending?: boolean;
}>(),
{ tools: () => [], media: () => [], assistant: false, streaming: false },
{ tools: () => [], media: () => [], assistant: false, streaming: false, reasoning: "", thinkingPending: false },
);
// The reply in the order it happened: text up to each call's offset, then the
@@ -73,6 +78,11 @@ const segments = computed(() => {
/>
</div>
<template v-if="assistant">
<ChatThinking
v-if="reasoning || thinkingPending"
:text="reasoning"
:pending="thinkingPending"
/>
<template v-for="(segment, i) in segments" :key="i">
<ChatMarkdown v-if="'text' in segment" :text="segment.text" />
<Trace v-else class="my-2">
+6 -1
View File
@@ -9,6 +9,7 @@ import { cn } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
import { isExactCommand, replaceToken } from "./commands";
import ChatSlashPalette from "./ChatSlashPalette.vue";
import ChatSuggestions from "./ChatSuggestions.vue";
import {
closeCommandMenu,
commandMatches,
@@ -242,6 +243,10 @@ function onKeydown(event: KeyboardEvent): void {
/></Button>
</li>
</ul>
<!-- Beside the field, not in the empty transcript, so the prompts stay
reachable without scrolling up; hidden in the collapsed bar on a
phone-width screen, where the strip would crowd the field. -->
<ChatSuggestions :class="flat ? 'max-md:hidden' : ''" />
<div
:class="
cn(
@@ -260,7 +265,7 @@ function onKeydown(event: KeyboardEvent): void {
aria-controls="slash-palette"
:aria-expanded="isCommandMenuOpen ? 'true' : 'false'"
:aria-activedescendant="isCommandMenuOpen && commandMatches.length ? `slash-palette-option-${commandSelection}` : undefined"
class="max-h-40 min-h-11 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 py-1 text-label shadow-none focus-visible:ring-0"
class="max-h-40 min-h-11 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 py-1 text-label pointer-coarse:text-base shadow-none focus-visible:ring-0"
@input="onInput"
@keydown="onKeydown"
/>
+63 -12
View File
@@ -1,15 +1,18 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ChevronDown, ChevronUp } from "@lucide/vue";
import { useMediaQuery, useStorage, useWindowSize } from "@vueuse/core";
import { useEventListener, useMediaQuery, useStorage, useWindowSize } from "@vueuse/core";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useLiveResource } from "@/stores/session";
import { cn } from "@/lib/utils";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatTranscript from "./ChatTranscript.vue";
import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
import { composerText, escapeOwnedByLayer, isSending, reloadTranscript, useChat } from "./state";
import { setDockOpen, unseenCount } from "./unseen";
/**
* Chat is a bar docked at the bottom of every page, not a route: the operator
@@ -26,6 +29,9 @@ import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
* Dragging the header to an edge pins it; dragging it away, or double-clicking
* the header, unpins it. The side and width are remembered per browser.
*
* On a phone the bar rides above the on-screen keyboard, which iOS does not
* resize the page for, and swiping down on the conversation header hides it.
*
* It stays mounted, so the session and any turn in flight survive a navigation.
* It is mounted outside the app shell: `.shell`'s backdrop-filter makes it a
* containing block for `position: fixed`, so a bar nested inside would anchor to
@@ -33,7 +39,12 @@ import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
*/
useChat();
// A task this conversation started reports its outcome into it. The dock stays
// mounted while collapsed, so a reply that lands then is still read and counted.
useLiveResource("chat", () => void reloadTranscript());
const expanded = ref(false);
watch(expanded, setDockOpen, { immediate: true });
const MIN_WIDTH = 320;
const EDGE = 64;
type Side = "left" | "right";
@@ -49,6 +60,20 @@ const width = computed(() =>
Math.round(Math.min(Math.max(saved.value.width, MIN_WIDTH), Math.max(MIN_WIDTH, Math.min(720, viewport.value - 480)))),
);
const side = computed(() => (desktop.value && expanded.value ? saved.value.side : null));
// The part of the layout viewport the on-screen keyboard covers, and the height
// left above it. Fixed elements stay anchored to the layout viewport, so without
// this the bar sits under the keyboard.
const keyboard = ref(0);
const visibleHeight = ref(window.innerHeight);
function followViewport(): void {
const vv = window.visualViewport;
keyboard.value = vv ? Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop)) : 0;
visibleHeight.value = vv ? vv.height : window.innerHeight;
}
useEventListener(() => window.visualViewport, ["resize", "scroll"], followViewport);
const phoneBottom = computed(() =>
keyboard.value > 0 ? `${keyboard.value + 8}px` : "max(0.5rem, env(safe-area-inset-bottom))",
);
const composer = ref<InstanceType<typeof ChatComposer> | null>(null);
// Nothing outside the dock closes it: every navigation control is outside it,
@@ -113,12 +138,13 @@ function edgeAt(x: number): Side | null {
// Pointer travel before a press on the header becomes a drag, so a click or a
// double-click on it never moves the dock.
const INTERACTIVE = "button, a, input, select, textarea, [role=combobox]";
const DRAG_START = 4;
const offset = ref<{ x: number; y: number } | null>(null);
const target = ref<Side | null>(null);
function startDrag(event: PointerEvent): void {
if (!desktop.value || event.button !== 0) return;
if ((event.target as HTMLElement).closest("button, a, input, select, textarea, [role=combobox]")) return;
if (event.button !== 0 || (event.target as HTMLElement).closest(INTERACTIVE)) return;
if (!desktop.value) return startSwipe(event);
const grip = event.currentTarget as HTMLElement;
const { clientX: x0, clientY: y0 } = event;
grip.setPointerCapture(event.pointerId);
@@ -141,8 +167,27 @@ function startDrag(event: PointerEvent): void {
grip.addEventListener("pointerup", end);
grip.addEventListener("pointercancel", end);
}
// A downward flick on the header hides the conversation. It must be mostly
// vertical so a sideways slip does not collapse it.
const SWIPE = 48;
function startSwipe(event: PointerEvent): void {
const grip = event.currentTarget as HTMLElement;
const { clientX: x0, clientY: y0 } = event;
const end = (e: PointerEvent): void => {
grip.removeEventListener("pointerup", end);
grip.removeEventListener("pointercancel", end);
const dy = e.clientY - y0;
if (e.type === "pointerup" && dy >= SWIPE && dy > Math.abs(e.clientX - x0) * 1.5) {
// The keyboard is for the composer, which is no longer in front of it.
(document.activeElement as HTMLElement | null)?.blur();
expanded.value = false;
}
};
grip.addEventListener("pointerup", end);
grip.addEventListener("pointercancel", end);
}
function togglePin(event: MouseEvent): void {
if (!desktop.value || (event.target as HTMLElement).closest("button, a, input, select, textarea, [role=combobox]")) return;
if (!desktop.value || (event.target as HTMLElement).closest(INTERACTIVE)) return;
saved.value.side = saved.value.side ? null : "right";
}
@@ -185,15 +230,15 @@ function usePrompt(text: string): void {
<div
:class="cn(
'pointer-events-none fixed z-40',
side ? cn('inset-y-0', side === 'left' ? 'left-0' : 'right-0') : 'inset-x-0 bottom-4 flex justify-center px-3 max-md:bottom-2',
side ? cn('inset-y-0', side === 'left' ? 'left-0' : 'right-0') : 'inset-x-0 bottom-4 flex justify-center px-3',
)"
:style="side ? { width: `${width}px` } : undefined"
:style="side ? { width: `${width}px` } : desktop ? undefined : { bottom: phoneBottom }"
>
<aside
ref="dock"
aria-label="Chat with Archie"
:class="cn(
'pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
'touch-hit pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
side
? cn('h-full w-full', side === 'left' ? 'border-r' : 'border-l')
: 'w-full max-w-xl rounded-lg border',
@@ -216,11 +261,11 @@ function usePrompt(text: string): void {
/>
<div
v-if="expanded"
:class="desktop && 'cursor-grab select-none active:cursor-grabbing'"
:class="desktop ? 'cursor-grab select-none active:cursor-grabbing' : 'touch-none'"
@pointerdown="startDrag"
@dblclick="togglePin"
>
<div v-if="desktop" class="flex justify-center pt-1.5" aria-hidden="true">
<div class="flex justify-center pt-1.5" aria-hidden="true">
<span class="h-1 w-8 rounded-full bg-border-strong" />
</div>
<ChatBar>
@@ -240,7 +285,11 @@ function usePrompt(text: string): void {
</Tooltip>
</ChatBar>
</div>
<div v-if="expanded" :class="cn('flex min-h-0 flex-col', side ? 'flex-1' : 'h-[min(28rem,55dvh)]')">
<div
v-if="expanded"
:class="cn('flex min-h-0 flex-col', side ? 'flex-1' : 'h-[min(28rem,55dvh)]')"
:style="side || desktop ? undefined : { height: `min(28rem, ${Math.round(visibleHeight * 0.55)}px)` }"
>
<ChatTranscript @prompt="usePrompt" />
</div>
<div @focusin="expanded = true">
@@ -251,10 +300,12 @@ function usePrompt(text: string): void {
<Button
variant="ghost"
size="icon-sm"
aria-label="Show conversation"
:class="cn(unseenCount && 'w-auto gap-1 px-2')"
:aria-label="unseenCount ? `Show conversation, ${unseenCount} new` : 'Show conversation'"
@click="expanded = true"
>
<ChevronUp />
<Badge v-if="unseenCount" variant="default" aria-hidden="true">{{ unseenCount }}</Badge>
</Button>
</TooltipTrigger>
<TooltipContent>Show conversation</TooltipContent>
+3 -24
View File
@@ -1,21 +1,11 @@
<script setup lang="ts">
import Logo from "@/components/topbar/Logo.vue";
import { Button } from "@/components/ui/button";
/**
* What the panel opens on before there is a conversation: an invitation, and
* three prompts that fill the composer. The text is handed up rather than
* typed into the composer here, because the composer owns its own focus.
* What the panel opens on before there is a conversation: the mark. The
* suggested prompts live beside the composer (ChatSuggestions), where they
* are reachable whether or not the transcript is empty.
*/
const emit = defineEmits<{ prompt: [text: string] }>();
// Prompts an operator might actually ask, rather than demonstrations of the
// feature.
const PROMPTS = [
"Summarise active tasks",
"Show running agents",
"Check system status",
];
</script>
<template>
@@ -23,16 +13,5 @@ const PROMPTS = [
<div aria-hidden="true" class="mb-3 flex justify-center">
<Logo :open="false" />
</div>
<div class="flex flex-wrap justify-center gap-2">
<Button
v-for="prompt in PROMPTS"
:key="prompt"
variant="outline"
size="sm"
@click="emit('prompt', prompt)"
>
{{ prompt }}
</Button>
</div>
</div>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { ArrowDownIcon } from "@lucide/vue";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
import { MessageScrollerButton, useMessageScrollerScrollable } from "@/components/ui/message-scroller";
import { setAtEnd, unseenCount } from "./unseen";
/**
* The scroller's jump-to-latest button. It reads where the reader is for the
* unseen count and says how many replies are waiting below.
*
* The scroller measures on the frames after it mounts, and until then it
* reports "not scrollable", which would look like the end. The reader counts
* as at the end only once it has measured.
*/
const scrollable = useMessageScrollerScrollable();
const measured = ref(false);
let frame = 0;
onMounted(() => {
frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
measured.value = true;
});
});
});
onUnmounted(() => {
cancelAnimationFrame(frame);
setAtEnd(false);
});
watch(
() => measured.value && !scrollable.value.end,
(end) => setAtEnd(end),
{ immediate: true },
);
const label = computed(() => `${unseenCount.value} new ${unseenCount.value === 1 ? "reply" : "replies"}`);
</script>
<template>
<MessageScrollerButton :size="unseenCount ? 'sm' : 'icon-sm'" :class="unseenCount ? 'gap-1.5 whitespace-nowrap' : undefined">
<ArrowDownIcon />
<template v-if="unseenCount">{{ label }}</template>
<span v-else class="sr-only">Scroll to end</span>
</MessageScrollerButton>
</template>
+22 -15
View File
@@ -16,6 +16,7 @@ import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import {
Popover,
PopoverAnchor,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
@@ -100,21 +101,27 @@ function submitPrompt(): void {
<template>
<Popover v-model:open="open">
<Tooltip>
<TooltipTrigger as-child>
<PopoverTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
aria-label="More"
>
<Ellipsis />
</Button>
</PopoverTrigger>
</TooltipTrigger>
<TooltipContent>More</TooltipContent>
</Tooltip>
<!-- The anchor sits outside the tooltip chain on purpose: nested inside
TooltipTrigger, the popper anchor ref resolves to a component object
rather than the button, the content is never positioned, and the menu
stays parked off-screen. -->
<PopoverAnchor as-child>
<Tooltip>
<TooltipTrigger as-child>
<PopoverTrigger as-child>
<Button
variant="ghost"
size="icon-sm"
class="flex-none"
aria-label="More"
>
<Ellipsis />
</Button>
</PopoverTrigger>
</TooltipTrigger>
<TooltipContent>More</TooltipContent>
</Tooltip>
</PopoverAnchor>
<PopoverContent align="end" class="grid w-64 gap-0.5 p-1">
<template v-if="currentSession">
<Button
+42
View File
@@ -0,0 +1,42 @@
<script setup lang="ts">
import { computed } from "vue";
import { useRoute } from "vue-router";
import { Button } from "@/components/ui/button";
import { sendMessage } from "./state";
import { suggestionsForRoute } from "./suggestions";
/**
* The suggested prompts for the page the operator is on, rendered beside the
* composer so they stay reachable with a conversation already open, without
* scrolling to the top of the transcript. A click sends the prompt as its own
* message (sendMessage's textOverride path sends at once while no turn runs)
* rather than filling the field.
*/
const route = useRoute();
const prompts = computed(() => suggestionsForRoute(route));
function send(prompt: string): void {
void sendMessage({ textOverride: prompt });
}
</script>
<template>
<div
v-if="prompts.length"
class="mb-2 flex flex-wrap gap-1.5"
role="group"
aria-label="Suggested prompts"
>
<Button
v-for="prompt in prompts"
:key="prompt"
variant="outline"
size="sm"
class="h-auto max-w-full whitespace-normal text-left"
@click="send(prompt)"
>
{{ prompt }}
</Button>
</div>
</template>
+47
View File
@@ -0,0 +1,47 @@
<script setup lang="ts">
import { BrainIcon } from "@lucide/vue";
import { Spinner } from "@/components/ui/spinner";
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
/**
* The live turn's thinking: the model's reasoning as it streams, in the same
* collapsible trace a tool call uses. While the turn has not produced any
* reasoning yet, the icon spins and the title shimmers; once text arrives it
* streams into the open trace. A turn that never reasons renders nothing,
* which the caller decides by not mounting this at all.
*/
withDefaults(
defineProps<{
text?: string;
/** The turn is still arriving and has not reasoned yet. */
pending?: boolean;
}>(),
{ text: "", pending: false },
);
</script>
<template>
<Trace class="my-2">
<TraceCollapsible default-open>
<TraceCollapsibleTrigger>
<TraceLine :status="pending && !text ? 'running' : undefined">
<TraceIcon>
<Spinner v-if="pending && !text" />
<BrainIcon v-else />
</TraceIcon>
<TraceTitle>Thinking</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent v-if="text" class="whitespace-pre-wrap [overflow-wrap:anywhere]">{{ text }}</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
</template>
+24 -15
View File
@@ -4,18 +4,17 @@ import { computed } from "vue";
import { Button } from "@/components/ui/button";
import {
MessageScroller,
MessageScrollerButton,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import { useLiveResource } from "@/stores/session";
import ChatAskCard from "./ChatAskCard.vue";
import ChatBubble from "./ChatBubble.vue";
import ChatChooseCard from "./ChatChooseCard.vue";
import ChatUpdateCard from "./ChatUpdateCard.vue";
import ChatEmptyState from "./ChatEmptyState.vue";
import ChatJumpButton from "./ChatJumpButton.vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import {
@@ -27,7 +26,6 @@ import {
sessionError,
streamingTurn,
type ChatMessage,
reloadTranscript,
} from "./state";
/**
@@ -39,8 +37,6 @@ import {
* that set scrollTop by hand would have no "reader scrolled away" state and no
* way back down, so MessageScroller owns this.
*/
const emit = defineEmits<{ prompt: [text: string] }>();
function parts(message: ChatMessage, index: number) {
const from = message.from ?? message.From ?? "";
// Anything this browser's composer did not send is Archie's answer.
@@ -63,9 +59,21 @@ const bubbles = computed(() => messages.value.map(parts));
// the scroller sees one row grow and settle, not one leave and another arrive.
const rows = computed(() => {
const turn = streamingTurn.value;
if (!turn) return bubbles.value.map((bubble) => ({ ...bubble, live: false }));
if (!turn) {
return bubbles.value.map((bubble) => ({
...bubble,
live: false,
reasoning: "",
thinkingPending: false,
}));
}
return [
...bubbles.value.map((bubble) => ({ ...bubble, live: false })),
...bubbles.value.map((bubble) => ({
...bubble,
live: false,
reasoning: "",
thinkingPending: false,
})),
{
id: `m${bubbles.value.length}`,
text: turn.text || "…",
@@ -75,12 +83,14 @@ const rows = computed(() => {
update: undefined,
choose: undefined,
live: true,
reasoning: turn.reasoning ?? "",
// Nothing said and nothing reasoned yet: the turn may still be thinking,
// so the row shows the pending thinking trace. Once the answer's text
// arrives without any reasoning, the trace is not rendered at all.
thinkingPending: !turn.text && !(turn.reasoning ?? ""),
},
];
});
// A task this conversation started reports its outcome into it.
useLiveResource("chat", () => void reloadTranscript());
</script>
<template>
@@ -102,10 +112,7 @@ useLiveResource("chat", () => void reloadTranscript());
<Button variant="outline" size="sm" @click="selectSession(currentSession)">Retry</Button>
</div>
<ChatEmptyState
v-else-if="!bubbles.length && !streamingTurn"
@prompt="emit('prompt', $event)"
/>
<ChatEmptyState v-else-if="!bubbles.length && !streamingTurn" />
<template v-else>
<MessageScrollerItem
@@ -120,6 +127,8 @@ useLiveResource("chat", () => void reloadTranscript());
:media="row.media"
:assistant="row.assistant"
:streaming="row.live"
:reasoning="row.reasoning"
:thinking-pending="row.thinkingPending"
>
<template v-if="row.live && streamingTurn">
<Button
@@ -141,7 +150,7 @@ useLiveResource("chat", () => void reloadTranscript());
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton />
<ChatJumpButton />
</MessageScroller>
</MessageScrollerProvider>
</template>
+15 -1
View File
@@ -124,6 +124,8 @@ export interface StreamingTurn {
isError: boolean;
turn?: ChatTurn;
isRetry: boolean;
/** The model's thinking so far, streamed on `reasoning` frames. */
reasoning?: string;
/** A question the turn waits on until the operator answers it. */
ask?: ChatAsk;
}
@@ -731,10 +733,11 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
}
let activeTools: ChatToolCall[] = [];
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry };
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry, reasoning: "" };
askError.value = "";
let streamedText = "";
let streamedReasoning = "";
let finished = false;
let timedOut = false;
let detached = false;
@@ -806,6 +809,15 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
? { ...streamingTurn.value, text: streamedText }
: null;
}
// The model's thinking streams ahead of the answer on its own frame
// kind; it accumulates like the text, but renders as the live turn's
// thinking trace rather than as reply text.
if (event.type === "reasoning") {
streamedReasoning += event.text;
streamingTurn.value = streamingTurn.value
? { ...streamingTurn.value, reasoning: streamedReasoning }
: null;
}
// A navigate result is appended to the same list as the tool calls: it
// is one more thing the turn did, and it renders as a chip rather than
// a tool line.
@@ -873,6 +885,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
isError: false,
turn,
isRetry,
reasoning: streamedReasoning,
};
statusText.value = "Stopped";
} else {
@@ -886,6 +899,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
isError: true,
turn: turn ? retryChatTurn(turn) : undefined,
isRetry,
reasoning: streamedReasoning,
};
statusText.value = "Error. Retry available.";
}
+103
View File
@@ -0,0 +1,103 @@
/**
* The suggested prompts shown beside the chat composer, keyed off the page
* the operator is on. The page identity is the same one the composer's page
* tag uses: the route's name, with the task id on a task detail page.
*
* Prompts are questions an operator would actually ask on that page, not
* demonstrations of the feature.
*/
/** The route as the page tag reads it; only these fields are consulted. */
export interface SuggestionRoute {
name?: unknown;
path?: string;
params?: Record<string, unknown>;
meta?: Record<string, unknown>;
}
/** The pages that get their own prompt set. */
export type SuggestionPage =
| "task"
| "tasks"
| "events"
| "workflows"
| "schedules"
| "settings"
| "default";
/** Which prompt set a route gets, by route name like the page tag's. */
export function suggestionPage(route: SuggestionRoute): SuggestionPage {
const name = typeof route.name === "string" ? route.name : "";
switch (name) {
case "task-detail":
return "task";
case "tasks":
return "tasks";
case "events":
return "events";
case "workflows":
return "workflows";
case "schedules":
case "org-schedules":
case "org-schedule-runs":
return "schedules";
default:
break;
}
const path = route.path ?? "";
if (route.meta?.settings === true || name.startsWith("settings-") || path.startsWith("/settings")) {
return "settings";
}
return "default";
}
/** The prompts for a route; a task page names the task it is open on. */
export function suggestionsForRoute(route: SuggestionRoute): string[] {
switch (suggestionPage(route)) {
case "task": {
const id = route.params?.id;
const ref = id === undefined || id === "" ? "this task" : `task #${String(id)}`;
return [
`What is ${ref} doing right now?`,
`Summarise what ${ref} did`,
`Which files did ${ref} change?`,
];
}
case "tasks":
return [
"Which tasks are waiting on me?",
"What failed in the last hour?",
"Show tasks that need review",
];
case "events":
return [
"Which events fired today?",
"Why didn't my last event start a workflow?",
"Show recent event deliveries",
];
case "workflows":
return [
"Which workflow ran most recently?",
"What did the last run change?",
"Which workflows failed recently?",
];
case "schedules":
return [
"When is the next scheduled run?",
"Did the last scheduled run succeed?",
"Which schedules are enabled?",
];
case "settings":
return [
"Which model is Archie using right now?",
"How do I connect a new repository?",
"Show recent access denials",
];
default:
return [
"Summarise active tasks",
"Show running agents",
"Check system status",
];
}
}
+47
View File
@@ -0,0 +1,47 @@
import { computed, ref, watch } from "vue";
import { isLoadingSession, messages, type ChatMessage } from "./state";
/**
* Counts the replies the operator has not seen. A reply is seen once the
* conversation is open and scrolled to its end; one that lands before that,
* such as a finished task's outcome while the dock is collapsed or the reader
* is scrolled up, adds to the count until then.
*
* It counts replies by position, not by id: a streamed reply is appended
* locally without an id and a later reload returns it with one, and that must
* not count twice.
*/
const dockOpen = ref(false);
const atEnd = ref(false);
const seen = ref(0);
function isReply(message: ChatMessage): boolean {
// Cards the operator's own command produced are not something Archie said.
return (message.from ?? message.From ?? "") !== "web" && !message.update && !message.choose;
}
const total = computed(() => messages.value.filter(isReply).length);
const viewing = computed(() => dockOpen.value && atEnd.value);
export const unseenCount = computed(() => Math.max(0, total.value - seen.value));
// Opening or switching a conversation loads it, which is not news; a reload
// that drops a message must also lower the mark so the next reply still counts.
watch(
[total, viewing, isLoadingSession],
([count, watching, loading], [, , wasLoading]) => {
if (watching || loading || wasLoading || count < seen.value) seen.value = count;
},
{ immediate: true },
);
/** The dock reports whether the conversation is open above the composer. */
export function setDockOpen(open: boolean): void {
dockOpen.value = open;
}
/** The scroller's jump button reports whether the reader is at the end. */
export function setAtEnd(end: boolean): void {
atEnd.value = end;
}
+2 -2
View File
@@ -23,12 +23,12 @@ const setupIncomplete = computed(() => setupPanelState(setup.value).kind === "in
<template>
<h1 class="sr-only">Dashboard</h1>
<Alert v-if="error" variant="destructive" class="mb-4"><AlertDescription>Archie is not responding: {{ error }}</AlertDescription></Alert>
<div :class="setupIncomplete ? 'grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_320px]' : 'mx-auto max-w-5xl'">
<div :class="setupIncomplete ? 'grid items-start gap-4 @3xl:grid-cols-[minmax(0,1fr)_320px]' : 'mx-auto max-w-5xl'">
<div class="grid min-w-0 gap-4">
<QuickTask class="mb-2" />
<NeedsAttentionCard />
<LiveActivityCard v-if="summary" />
</div>
<SetupPanel v-if="setupIncomplete" class="max-lg:-order-1" />
<SetupPanel v-if="setupIncomplete" class="@max-3xl:-order-1" />
</div>
</template>
+2 -2
View File
@@ -80,10 +80,10 @@ async function run() {
<template>
<div>
<form class="grid gap-1.5" @submit.prevent="run">
<div class="flex gap-2 max-sm:flex-wrap">
<div class="flex gap-2 @max-xl:flex-wrap">
<Input v-model="prompt" class="min-w-0 flex-1" placeholder="Describe what Archie should do" aria-label="Task" />
<Select v-model="workflow" :disabled="!definitions.length">
<SelectTrigger class="w-56 max-sm:flex-1" aria-label="Workflow"><span class="flex min-w-0 items-center gap-1.5"><span class="text-fg-muted">Workflow</span><SelectValue /></span></SelectTrigger>
<SelectTrigger class="w-56 @max-xl:flex-1" aria-label="Workflow"><span class="flex min-w-0 items-center gap-1.5"><span class="text-fg-muted">Workflow</span><SelectValue /></span></SelectTrigger>
<SelectContent position="popper">
<SelectGroup>
<SelectItem v-for="d in definitions" :key="d.id" :value="d.id">{{ d.name || d.id }}</SelectItem>
+1 -1
View File
@@ -58,7 +58,7 @@ const groups = computed(() => {
{{ group.label }}
<span class="font-normal text-fg-subtle">{{ group.entries.length }}</span>
</h2>
<ul class="grid gap-2 lg:grid-cols-2">
<ul class="grid gap-2 @3xl:grid-cols-2">
<li v-for="entry in group.entries" :key="entry.name" class="flex">
<Item variant="outline" class="h-full flex-nowrap items-start bg-card">
<ItemMedia class="mt-0.5 size-8 rounded-md bg-muted">
+1 -1
View File
@@ -95,7 +95,7 @@ const tones = {
<Section>
<ItemGroup aria-label="Extensions">
<Item v-for="extension in store.extensions" :key="extension.name" as="li" variant="outline">
<div class="min-w-0 w-full lg:w-auto lg:flex-1">
<div class="min-w-0 w-full @3xl:w-auto @3xl:flex-1">
<p class="truncate text-label font-medium">
{{ extension.display_name || extension.name }}
<span class="font-mono text-caption text-fg-subtle">{{ extension.version }}</span>
+2 -2
View File
@@ -56,14 +56,14 @@ function removeIdentity(id: string) {
<KindGate v-if="!grants" :kind="KIND" />
<ItemGroup v-if="grants">
<Item as="div" role="listitem" variant="outline" size="sm" class="flex-wrap">
<span class="w-40 shrink-0 text-label max-sm:w-24 max-sm:truncate">Default</span>
<span class="w-40 shrink-0 text-label @max-xl:w-24 @max-xl:truncate">Default</span>
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="grants.identities?.[SYSTEM_ID] ?? []" aria-label="Default grants" @update:model-value="(v) => setIdentity(SYSTEM_ID, v as string[])">
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
</ToggleGroup>
<DraftHint :kind="KIND" path="identities" />
</Item>
<Item v-for="[id, services] in others" :key="id" as="div" role="listitem" variant="outline" size="sm">
<span class="w-40 shrink-0 truncate text-label max-sm:w-24">{{ org.identityName(String(id)) }}</span>
<span class="w-40 shrink-0 truncate text-label @max-xl:w-24">{{ org.identityName(String(id)) }}</span>
<ToggleGroup class="flex-wrap" type="multiple" variant="outline" size="sm" :model-value="services ?? []" :aria-label="`${org.identityName(String(id))} grants`" @update:model-value="(v) => setIdentity(String(id), v as string[])">
<ToggleGroupItem v-for="service in store.credentialServices" :key="service" :value="service" class="font-mono text-caption">{{ service }}</ToggleGroupItem>
</ToggleGroup>
+5 -5
View File
@@ -26,18 +26,18 @@ const items = computed(() =>
</script>
<template>
<div class="flex gap-8 max-lg:flex-col max-lg:gap-4">
<div class="flex gap-8 @max-3xl:flex-col @max-3xl:gap-4">
<nav
id="config-sidebar"
:aria-label="props.scope === 'org' ? 'Organisation' : 'Instance'"
class="shrink-0 lg:w-48 max-lg:-mx-4 max-lg:w-auto max-lg:scroll-fade-x max-lg:overflow-x-auto max-lg:[scrollbar-width:none] max-lg:border-b max-lg:px-4"
class="shrink-0 @3xl:w-48 @max-3xl:-mx-4 @max-3xl:w-auto @max-3xl:scroll-fade-x @max-3xl:overflow-x-auto @max-3xl:[scrollbar-width:none] @max-3xl:border-b @max-3xl:px-4"
>
<ul class="flex flex-col gap-0.5 lg:sticky lg:top-20 max-lg:flex-row max-lg:gap-1">
<ul class="flex flex-col gap-0.5 @3xl:sticky @3xl:top-20 @max-3xl:flex-row @max-3xl:gap-1">
<li v-for="(item, index) in items" :key="item.path" class="contents">
<Separator v-if="item.dividerBefore === ''" class="my-4 max-lg:hidden" />
<Separator v-if="item.dividerBefore === ''" class="my-4 @max-3xl:hidden" />
<p
v-else-if="item.dividerBefore"
:class="cn('mb-1 px-3 text-caption font-medium tracking-[0.06em] text-fg-subtle uppercase max-lg:hidden', index > 0 && 'mt-4')"
:class="cn('mb-1 px-3 text-caption font-medium tracking-[0.06em] text-fg-subtle uppercase @max-3xl:hidden', index > 0 && 'mt-4')"
>
{{ item.dividerBefore }}
</p>
+4 -4
View File
@@ -175,7 +175,7 @@ function setAllowed(id: string, text: string) {
<Section title="Aliases">
<p v-if="!aliases.default" class="mb-3 text-label text-warn" role="alert">Set the default alias.</p>
<div v-for="alias in aliasNames" :key="alias" class="flex flex-wrap items-center gap-3 border-b border-border py-2.5 last-of-type:border-b-0">
<Label :for="`alias-${alias}`" class="w-28 text-label font-medium max-sm:w-full">{{ alias }}</Label>
<Label :for="`alias-${alias}`" class="w-28 text-label font-medium @max-xl:w-full">{{ alias }}</Label>
<template v-if="alias === 'embedding'">
<Select :model-value="embeddingProvider" @update:model-value="(v) => setEmbedding(String(v), embeddingModel)">
<SelectTrigger class="w-44 font-mono" aria-label="Embedding provider"><SelectValue placeholder="unset" /></SelectTrigger>
@@ -198,7 +198,7 @@ function setAllowed(id: string, text: string) {
:id="`alias-${alias}`"
:model-value="aliases[alias] ?? ''"
:options="modelOptions"
class="min-w-0 max-w-md flex-1 font-mono max-sm:max-w-none max-sm:basis-full"
class="min-w-0 max-w-md flex-1 font-mono @max-xl:max-w-none @max-xl:basis-full"
placeholder="unset"
:aria-invalid="!!aliasIssue(alias)"
@update:model-value="(v) => setAlias(alias, String(v))"
@@ -221,10 +221,10 @@ function setAllowed(id: string, text: string) {
<template v-if="policies && otherOrgs.length">
<Section title="Org access">
<div v-for="o in otherOrgs" :key="o.id" class="flex flex-wrap items-center gap-3 border-b border-border py-2.5 last-of-type:border-b-0">
<span class="w-28 truncate text-label font-medium max-sm:w-full" :title="o.id">{{ o.name }}</span>
<span class="w-28 truncate text-label font-medium @max-xl:w-full" :title="o.id">{{ o.name }}</span>
<Input
:model-value="allowedText(o.id)"
class="min-w-0 max-w-md flex-1 font-mono max-sm:max-w-none max-sm:basis-full"
class="min-w-0 max-w-md flex-1 font-mono @max-xl:max-w-none @max-xl:basis-full"
placeholder="no models"
:aria-label="`Models ${o.name} may use`"
@update:model-value="(v) => setAllowed(o.id, String(v))"
+16
View File
@@ -351,3 +351,19 @@
transition-duration: 0.01ms !important;
}
}
/* Widens a control's tap area to 44px on a phone without changing how it looks
or what space it takes. Apply it to a container of buttons. */
@utility touch-hit {
@media (max-width: 767px) {
& button:not(.absolute) {
position: relative;
}
& button::after {
content: "";
position: absolute;
inset-block: min(0px, calc((100% - 44px) / 2));
inset-inline: min(0px, calc((100% - 44px) / 2));
}
}
}
+1 -1
View File
@@ -57,7 +57,7 @@ const changeVariant: Record<string, "ok" | "info" | "danger"> = {
</ul>
</section>
<div class="grid gap-5 sm:grid-cols-2">
<div class="grid gap-5 @xl:grid-cols-2">
<section v-if="doc.acceptance?.length" class="flex min-w-0 flex-col gap-2">
<h3 class="text-title font-semibold">Acceptance criteria</h3>
<ul class="list-disc space-y-1 pl-5 text-label">
+2 -2
View File
@@ -56,13 +56,13 @@ const nodeClass = computed(() =>
<template>
<li
class="relative grid grid-cols-[1.75rem_1fr] gap-2 pb-4 before:absolute before:top-4 before:bottom-0 before:left-[0.6875rem] before:w-px before:bg-border-strong last:before:hidden max-md:grid-cols-1 max-md:border-b max-md:border-border max-md:pb-3 max-md:before:hidden"
class="relative grid grid-cols-[1.75rem_1fr] gap-2 pb-4 before:absolute before:top-4 before:bottom-0 before:left-[0.6875rem] before:w-px before:bg-border-strong last:before:hidden @max-2xl:grid-cols-1 @max-2xl:border-b @max-2xl:border-border @max-2xl:pb-3 @max-2xl:before:hidden"
>
<span
:class="nodeClass"
:title="meta.label"
aria-hidden="true"
class="max-md:hidden"
class="@max-2xl:hidden"
/>
<div class="min-w-0">
<!--
+2 -2
View File
@@ -52,7 +52,7 @@ const run = provideTaskRun(taskId);
<TaskNotes :id="rawId" />
<TaskReviewGate v-if="run.task" :task="run.task" @done="run.refreshAll()" />
<div class="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_20rem]">
<div class="grid items-start gap-6 @3xl:grid-cols-[minmax(0,1fr)_20rem]">
<div class="flex min-w-0 flex-col gap-6">
<TaskApproval
v-if="run.task?.approval === 'plan' && run.task.plan"
@@ -72,7 +72,7 @@ const run = provideTaskRun(taskId);
</CardContent>
</Card>
</div>
<TaskRail class="order-first lg:order-none" />
<TaskRail class="order-first @3xl:order-none" />
</div>
</div>
</template>
+2 -2
View File
@@ -46,13 +46,13 @@ function selectStatus(value: unknown) {
:model-value="props.search"
aria-label="Search tasks by title or repository"
placeholder="Search by title or repo…"
class="w-55 max-sm:w-full"
class="w-55 @max-xl:w-full"
@update:model-value="emit('update:search', String($event))"
/>
<Select :model-value="selected" @update:model-value="selectStatus">
<SelectTrigger
aria-label="Filter by status"
class="w-45 max-sm:w-full"
class="w-45 @max-xl:w-full"
>
<SelectValue />
</SelectTrigger>
+333
View File
@@ -0,0 +1,333 @@
import assert from "node:assert/strict";
import { spawn, execFileSync, type ChildProcess } from "node:child_process";
import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import net from "node:net";
import test from "node:test";
/**
* Behaviour check for the chat bar's "More" menu (issue #1862): the button
* must open its popover on screen, the tooltip must keep its accessible name,
* and the menu items must run. Rendered behavior needs a real browser, so this
* drives the dev server in headless Chrome over CDP and mocks only the HTTP
* API inside the page. It skips when no Chrome binary is installed.
*/
const uiDir = fileURLToPath(new URL("..", import.meta.url));
// The page refuses to paint the chat dock until /api/auth/status answers with
// a signed-in user, and the composer palette reads the session list, so the
// mock answers just those and lets everything else fall through to empty JSON.
const PAGE_MOCK = `(() => {
const realFetch = window.fetch.bind(window);
window.__archieSent = [];
window.fetch = (input, init) => {
const url = typeof input === "string" ? input : input.url;
const json = (body, type = "application/json") =>
Promise.resolve(new Response(typeof body === "string" ? body : JSON.stringify(body), { status: 200, headers: { "Content-Type": type } }));
if (url.includes("/api/chat/stream")) {
window.__archieSent.push(JSON.parse(init.body).text);
return json('data: {"type":"delta","text":"ok","session_id":"s1"}\\n\\ndata: {"type":"done","text":"ok","session_id":"s1"}\\n\\n', "text/event-stream");
}
if (url.includes("/api/auth/status"))
return json({ setup_required: false, user: { id: "u1", display_name: "Operator", kind: "operator" }, oidc: false, public_url: location.origin + "/", instance: "archie" });
if (url.includes("/api/chat/sessions"))
return json({ providers: ["test"], models: ["test-model"], models_by_provider: { test: ["test-model"] }, active_provider: "test", active_model: "test-model", commands: ["/retry", "/undo", "/title", "/branch", "/compress"], voice_available: false, sessions: [{ session_id: "s1", title: "Test session", created_at: "2026-01-01T00:00:00Z" }] });
if (url.includes("/turns")) return json({ turns: [] });
if (url.includes("/health")) return json({ status: "ok" });
if (url.includes("/api/")) return json({});
return realFetch(input, init);
};
window.EventSource = class {
close() {}
addEventListener() {}
removeEventListener() {}
};
})();`;
function freePort(): Promise<number> {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const { port } = server.address() as net.AddressInfo;
server.close(() => resolve(port));
});
});
}
function findChrome(): string | null {
const candidates = [
process.env.CHROME_BIN,
"google-chrome",
"google-chrome-stable",
"chromium",
"chromium-browser",
].filter((c): c is string => !!c);
for (const candidate of candidates) {
if (candidate.includes("/")) {
if (existsSync(candidate)) return candidate;
continue;
}
try {
const found = execFileSync("which", [candidate], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
if (found) return found;
} catch {
// not on PATH
}
}
return null;
}
interface Cdp {
send(method: string, params?: Record<string, unknown>): Promise<any>;
evaluate(expression: string): Promise<any>;
close(): void;
}
async function connectChrome(debugPort: number): Promise<Cdp> {
let target: any;
for (let attempt = 0; attempt < 60 && !target; attempt++) {
try {
const list = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json();
target = (list as any[]).find((t) => t.type === "page");
} catch {
// devtools not up yet
}
if (!target) await new Promise((r) => setTimeout(r, 250));
}
if (!target) throw new Error("chrome devtools endpoint never came up");
const ws = new WebSocket(target.webSocketDebuggerUrl);
await new Promise<void>((resolve, reject) => {
ws.onopen = () => resolve();
ws.onerror = () => reject(new Error("chrome websocket failed"));
});
let nextId = 0;
const pending = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>();
ws.onmessage = (event) => {
const message = JSON.parse(String(event.data));
if (message.id && pending.has(message.id)) {
const { resolve, reject } = pending.get(message.id)!;
pending.delete(message.id);
if (message.error) reject(new Error(JSON.stringify(message.error)));
else resolve(message.result);
}
};
const send = (method: string, params: Record<string, unknown> = {}) =>
new Promise<any>((resolve, reject) => {
const id = ++nextId;
pending.set(id, { resolve, reject });
ws.send(JSON.stringify({ id, method, params }));
});
return {
send,
evaluate: async (expression) => {
const result = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
if (result.exceptionDetails) throw new Error("page error: " + JSON.stringify(result.exceptionDetails).slice(0, 500));
return result.result.value;
},
close: () => ws.close(),
};
}
async function startVite(): Promise<{ port: number; child: ChildProcess }> {
const viteBin = join(uiDir, "node_modules", "vite", "bin", "vite.js");
if (!existsSync(viteBin)) throw new Error("ui dependencies are not installed (run pnpm install)");
let lastError = "";
for (let attempt = 0; attempt < 5; attempt++) {
const port = await freePort();
const child = spawn(process.execPath, [viteBin, "--port", String(port), "--strictPort", "--host", "127.0.0.1"], {
cwd: uiDir,
stdio: ["ignore", "pipe", "pipe"],
});
child.stderr?.on("data", (chunk) => { lastError += chunk; });
for (let poll = 0; poll < 60; poll++) {
if (child.exitCode !== null) break;
try {
const response = await fetch(`http://127.0.0.1:${port}/`);
if (response.ok) return { port, child };
} catch {
// not listening yet
}
await new Promise((r) => setTimeout(r, 250));
}
child.kill("SIGKILL");
}
throw new Error("vite dev server did not start: " + lastError.slice(0, 400));
}
test("chat More menu opens on screen and its items run", { timeout: 90000 }, async (t) => {
const chrome = findChrome();
if (!chrome) {
t.skip("no Chrome/Chromium binary available for the browser check");
return;
}
const { port: vitePort, child: vite } = await startVite();
const debugPort = await freePort();
const profile = join(tmpdir(), `archie-more-menu-test-${process.pid}-${Date.now()}`);
const chromeChild = spawn(chrome, [
"--headless=new",
`--remote-debugging-port=${debugPort}`,
"--no-sandbox",
"--disable-gpu",
"--disable-dev-shm-usage",
`--user-data-dir=${profile}`,
"--window-size=1280,900",
"about:blank",
], { stdio: "ignore" });
try {
const cdp = await connectChrome(debugPort);
try {
await cdp.send("Page.enable");
await cdp.send("Runtime.enable");
await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: PAGE_MOCK });
await cdp.send("Emulation.setDeviceMetricsOverride", { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
await cdp.send("Page.navigate", { url: `http://127.0.0.1:${vitePort}/` });
// Wait for the app shell and the collapsed dock, then expand it.
await cdp.evaluate(`(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
for (let i = 0; i < 60; i++) {
if (document.querySelector('button[aria-label="Show conversation"]')) {
document.querySelector('button[aria-label="Show conversation"]').click();
for (let j = 0; j < 40 && !document.querySelector('button[aria-label="More"]'); j++) await sleep(250);
return !!document.querySelector('button[aria-label="More"]');
}
await sleep(250);
}
return false;
})()`).then((expanded: unknown) => assert.equal(expanded, true, "the chat dock expanded and rendered the More button"));
// Pick the open conversation first, so the menu's commands have a
// session to act on (selectSession itself streams /resume s1).
await cdp.evaluate(`(() => {
document.querySelector('button[aria-label="Conversation"]').click();
})()`);
await new Promise((r) => setTimeout(r, 800));
await cdp.evaluate(`(() => {
const item = [...document.querySelectorAll('[data-slot="select-item"]')].find((el) => el.innerText.includes("Test session"));
if (item) item.click();
})()`);
await cdp.evaluate(`(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
for (let i = 0; i < 40 && !window.__archieSent.includes("/resume s1"); i++) await sleep(250);
return window.__archieSent.includes("/resume s1");
})()`).then((selected: unknown) => assert.equal(selected, true, "selecting the conversation opened it on the server"));
// Hover the More button: the tooltip keeps its accessible name.
const moreBox = await cdp.evaluate(`(() => { const r = document.querySelector('button[aria-label="More"]').getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`);
await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: moreBox.x, y: moreBox.y });
await new Promise((r) => setTimeout(r, 1200));
const tooltip = await cdp.evaluate(`(() => {
const tip = document.querySelector('[data-slot="tooltip-content"]');
return tip && (tip.offsetWidth || tip.offsetHeight) ? tip.innerText.trim() : null;
})()`);
assert.ok(tooltip && tooltip.includes("More"), `hovering the More button shows the More tooltip, got ${JSON.stringify(tooltip)}`);
// Click it: the popover must open inside the viewport.
await cdp.send("Input.dispatchMouseEvent", { type: "mousePressed", x: moreBox.x, y: moreBox.y, button: "left", clickCount: 1 });
await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: moreBox.x, y: moreBox.y, button: "left", clickCount: 1 });
const opened = await cdp.evaluate(`(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
for (let i = 0; i < 40 && !document.querySelector('[data-slot="popover-content"]'); i++) await sleep(250);
const pop = document.querySelector('[data-slot="popover-content"]');
if (!pop) return { exists: false };
const r = pop.getBoundingClientRect();
return {
exists: true,
inViewport: r.x >= 0 && r.y >= 0 && r.right <= innerWidth && r.bottom <= innerHeight,
rect: { x: r.x, y: r.y, right: r.right, bottom: r.bottom },
text: pop.innerText.replace(/\\s+/g, " ").trim(),
ariaExpanded: document.querySelector('button[aria-label="More"]').getAttribute("aria-expanded"),
};
})()`);
assert.equal(opened.exists, true, "clicking More opens the popover");
assert.equal(opened.ariaExpanded, "true");
assert.equal(opened.inViewport, true, `the menu must render on screen, got ${JSON.stringify(opened.rect)}`);
for (const item of ["Retry", "Undo", "Rename", "Branch", "Preview compression", "Copy as Markdown"]) {
assert.ok(opened.text.includes(item), `the menu lists ${item}`);
}
// Run Retry from the menu: the command goes over the chat stream and
// the menu closes.
await cdp.evaluate(`(() => {
const retry = [...document.querySelectorAll('[data-slot="popover-content"] button')].find((el) => el.innerText.includes("Retry"));
if (retry) retry.click();
})()`);
await cdp.evaluate(`(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
for (let i = 0; i < 40 && !window.__archieSent.includes("/retry"); i++) await sleep(250);
return window.__archieSent.includes("/retry");
})()`).then((sent: unknown) => assert.equal(sent, true, `Retry sends /retry over the chat stream, got ${JSON.stringify(sent)}`));
const afterRetry = await cdp.evaluate(`(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
for (let i = 0; i < 40; i++) {
const pop = document.querySelector('[data-slot="popover-content"]');
if (!pop || pop.getAttribute("data-state") === "closed") break;
await sleep(250);
}
return {
popoverClosed: !document.querySelector('[data-slot="popover-content"]') || document.querySelector('[data-slot="popover-content"]').getAttribute("data-state") === "closed",
ariaExpanded: document.querySelector('button[aria-label="More"]').getAttribute("aria-expanded"),
dockStillThere: !!document.querySelector('button[aria-label="More"]'),
};
})()`);
assert.equal(afterRetry.popoverClosed, true, "running a command closes the menu");
assert.equal(afterRetry.ariaExpanded, "false");
assert.equal(afterRetry.dockStillThere, true);
// Reopen and use Rename: the labelled dialog opens from the menu.
await cdp.evaluate(`(() => { document.querySelector('button[aria-label="More"]').click(); })()`);
await new Promise((r) => setTimeout(r, 1000));
await cdp.evaluate(`(() => {
const rename = [...document.querySelectorAll('[data-slot="popover-content"] button')].find((el) => el.innerText.includes("Rename"));
if (rename) rename.click();
})()`);
await new Promise((r) => setTimeout(r, 1000));
const dialog = await cdp.evaluate(`(() => {
const d = [...document.querySelectorAll('[role="dialog"]')].find((el) => !el.hasAttribute("data-slot") || el.getAttribute("data-slot") !== "popover-content");
return d ? d.innerText.replace(/\\s+/g, " ").trim() : null;
})()`);
assert.ok(dialog && dialog.includes("Session title"), `Rename opens the session-title dialog, got ${JSON.stringify(dialog)}`);
// Cancel the dialog, reopen the menu, then Escape: it dismisses the menu
// but leaves the conversation open.
await cdp.evaluate(`(() => {
const cancel = [...document.querySelectorAll('[role="dialog"] button')].find((el) => el.innerText.trim() === "Cancel");
if (cancel) cancel.click();
})()`);
await new Promise((r) => setTimeout(r, 800));
await cdp.evaluate(`(() => { document.querySelector('button[aria-label="More"]').click(); })()`);
await new Promise((r) => setTimeout(r, 1000));
await cdp.send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: "Escape", windowsVirtualKeyCode: 27 });
await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: "Escape", windowsVirtualKeyCode: 27 });
await new Promise((r) => setTimeout(r, 800));
const afterEscape = await cdp.evaluate(`(async () => {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
for (let i = 0; i < 40; i++) {
const pop = document.querySelector('[data-slot="popover-content"]');
if (!pop || pop.getAttribute("data-state") === "closed") break;
await sleep(250);
}
return {
popoverClosed: !document.querySelector('[data-slot="popover-content"]') || document.querySelector('[data-slot="popover-content"]').getAttribute("data-state") === "closed",
dockStillThere: !!document.querySelector('button[aria-label="More"]'),
ariaExpanded: document.querySelector('button[aria-label="More"]').getAttribute("aria-expanded"),
};
})()`);
assert.equal(afterEscape.popoverClosed, true, "Escape closes the menu");
assert.equal(afterEscape.ariaExpanded, "false");
assert.equal(afterEscape.dockStillThere, true, "Escape leaves the conversation open");
} finally {
cdp.close();
}
} finally {
chromeChild.kill("SIGKILL");
vite.kill("SIGKILL");
}
});
+79
View File
@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
suggestionPage,
suggestionsForRoute,
type SuggestionRoute,
} from "../src/chat/suggestions.ts";
// One route per page the prompts distinguish, in the shape the page tag reads.
const pages: Array<[SuggestionRoute, string]> = [
[{ name: "task-detail", path: "/tasks/42", params: { id: "42" } }, "task"],
[{ name: "tasks", path: "/tasks" }, "tasks"],
[{ name: "events", path: "/events" }, "events"],
[{ name: "workflows", path: "/workflows" }, "workflows"],
[{ name: "schedules", path: "/schedules" }, "schedules"],
[{ name: "org-schedules", path: "/org/schedules" }, "schedules"],
[{ name: "org-schedule-runs", path: "/org/schedules/7/runs", params: { id: "7" } }, "schedules"],
[{ name: "system-models", path: "/settings/models", meta: { settings: true, label: "Models" } }, "settings"],
[{ name: "settings-tools", path: "/settings/tools" }, "settings"],
[{ path: "/settings/secret-engines" }, "settings"],
[{ name: "dashboard", path: "/" }, "default"],
[{ name: "org-members", path: "/org/members" }, "default"],
[{ name: "not-found", path: "/nope" }, "default"],
[{}, "default"],
];
test("each page route resolves to its own prompt set", () => {
for (const [route, page] of pages) {
assert.equal(suggestionPage(route), page, JSON.stringify(route));
}
});
test("the prompts follow the page", () => {
const byPage = new Map<string, string[]>();
for (const [route, page] of pages) {
const prompts = suggestionsForRoute(route);
const seen = byPage.get(page);
if (seen) assert.deepEqual(prompts, seen, page);
else byPage.set(page, prompts);
}
const sets = [...byPage.values()];
for (let i = 0; i < sets.length; i++) {
for (let j = i + 1; j < sets.length; j++) {
assert.notDeepEqual(sets[i], sets[j], `pages ${[...byPage.keys()][i]} and ${[...byPage.keys()][j]} share a prompt set`);
}
}
});
test("every route yields distinct, well-formed prompts", () => {
for (const [route] of pages) {
const prompts = suggestionsForRoute(route);
assert.ok(prompts.length >= 2, JSON.stringify(route));
assert.equal(new Set(prompts).size, prompts.length, JSON.stringify(route));
for (const prompt of prompts) {
assert.ok(prompt.trim().length > 0, JSON.stringify(route));
assert.ok(!prompt.includes("undefined"), prompt);
}
}
});
test("a task page names the task it is open on", () => {
const withId = suggestionsForRoute({ name: "task-detail", path: "/tasks/42", params: { id: "42" } });
assert.ok(withId.some((prompt) => prompt.includes("#42")));
assert.ok(withId.every((prompt) => !prompt.includes("undefined")));
const withoutId = suggestionsForRoute({ name: "task-detail", path: "/tasks" });
assert.ok(withoutId.some((prompt) => prompt.includes("this task")));
assert.ok(withoutId.every((prompt) => !prompt.includes("#")));
});
test("settings is recognised by flag, by name and by path alike", () => {
const byFlag = suggestionsForRoute({ name: "system-status", path: "/settings/status", meta: { settings: true } });
const byName = suggestionsForRoute({ name: "settings-plugins", path: "/settings/plugins" });
const byPath = suggestionsForRoute({ path: "/settings/container-runtime" });
assert.deepEqual(byName, byFlag);
assert.deepEqual(byPath, byFlag);
assert.notDeepEqual(byFlag, suggestionsForRoute({ name: "dashboard", path: "/" }));
});
+103
View File
@@ -0,0 +1,103 @@
import assert from "node:assert/strict";
import test from "node:test";
import { register } from "node:module";
import { pathToFileURL } from "node:url";
import { resolve as resolvePath } from "node:path";
// state.ts reads the dashboard through "@/lib/api" and "@/router", which node
// cannot resolve on its own (and which pull in the whole SPA). A resolve hook
// maps the alias into src/ for the pure modules and stubs the two browser-only
// ones, so the real frame handling in state.ts runs under node.
const srcRoot = resolvePath(import.meta.dirname, "../src");
const apiStub =
"data:text/javascript," +
encodeURIComponent(
"export const api = new Proxy({}, { get: (_, p) => globalThis.__archieChatTestApi[p] });",
);
const routerStub =
"data:text/javascript," +
encodeURIComponent(
"export const router = { currentRoute: { value: { fullPath: '/', name: 'home', meta: {}, params: {} } } };",
);
register(
"data:text/javascript," +
encodeURIComponent(`
const SRC = ${JSON.stringify(pathToFileURL(srcRoot + "/").href)};
export async function resolve(specifier, context, next) {
if (specifier === "@/lib/api") return { url: ${JSON.stringify(apiStub)}, shortCircuit: true };
if (specifier === "@/router") return { url: ${JSON.stringify(routerStub)}, shortCircuit: true };
if (specifier.startsWith("@/")) return { url: SRC + specifier.slice(2) + ".ts", shortCircuit: true };
if ((specifier.startsWith("./") || specifier.startsWith("../")) && !/\\.[a-z0-9]+$/i.test(specifier)) {
return { url: new URL(specifier + ".ts", context.parentURL).href, shortCircuit: true };
}
return next(specifier, context);
}
`),
);
interface Frame {
type: string;
text?: string;
session_id?: string;
}
/** One SSE body: each frame as the server writes it, `data: {...}\n\n`. */
function sseBody(frames: Frame[]): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
const payload = frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join("");
return new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode(payload));
controller.close();
},
});
}
const started = { type: "started", session_id: "s1" };
// The stream stub: chatStream answers with the given frames, sessions reads
// back an empty list so the finished turn does not trigger a reload.
function stubApi(frames: Frame[]): void {
(globalThis as Record<string, unknown>).__archieChatTestApi = {
chatStream: () => ({ body: sseBody(frames) }),
chatSessions: () => ({ sessions: [], commands: [] }),
};
}
const state = await import("../src/chat/state.ts");
test("reasoning frames accumulate on the live turn as its thinking", async () => {
stubApi([
started,
{ type: "reasoning", text: "considering " },
{ type: "reasoning", text: "the request" },
{ type: "error", text: "provider exploded" },
]);
await state.sendMessage({ textOverride: "hello" });
const turn = state.streamingTurn.value;
assert.ok(turn, "the failed turn stays on the panel");
assert.equal(turn.isError, true);
assert.equal(turn.reasoning, "considering the request");
});
test("reasoning never leaks into the reply text", async () => {
stubApi([
started,
{ type: "reasoning", text: "secret chain of thought" },
{ type: "delta", text: "Hello" },
{ type: "done", text: "Hello", session_id: "s1" },
]);
await state.sendMessage({ textOverride: "hi" });
assert.equal(state.streamingTurn.value, null);
const last = state.messages.value.at(-1);
assert.equal(last?.from, "assistant");
assert.equal(last?.text, "Hello");
});
test("a turn without reasoning frames completes normally", async () => {
stubApi([started, { type: "delta", text: "Hi" }, { type: "done", text: "Hi", session_id: "s1" }]);
await state.sendMessage({ textOverride: "hey" });
assert.equal(state.streamingTurn.value, null);
assert.equal(state.messages.value.at(-1)?.text, "Hi");
assert.equal(state.statusText.value, "Ready");
});