Merge branch 'main' into fix/1892-container-queries
ci/woodpecker/pr/quality Pipeline was successful
Quality / check (pull_request) Successful in 10m46s

This commit is contained in:
sam committed 2026-11-12 12:14:54 +00:00
commit af02cbe832
30 files changed
+1266 -94

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.
+45 -3
View File
@@ -1,10 +1,11 @@
// The chat composer: IME confirmation never submits the draft, Shift+Enter
// inserts a newline, and ordinary Enter submits and clears.
// inserts a newline, ordinary Enter submits and clears, and # attaches a task.
const assert = require('node:assert/strict');
module.exports = async ({ page, go, shot }) => {
module.exports = async ({ page, go, shot, tolerate }) => {
tolerate(/api\/tasks/);
await go('/events');
const composer = page.getByRole('textbox', { name: 'Message Archie', exact: true });
const composer = page.getByRole('combobox', { name: 'Message Archie', exact: true });
await composer.waitFor();
await composer.fill('Composition in progress');
const sent = [];
@@ -24,5 +25,46 @@ module.exports = async ({ page, go, shot }) => {
await composer.press('Enter');
assert.equal((await request).postDataJSON().text, 'Ordinary Enter submits');
assert.equal(await composer.inputValue(), '');
let failTasks = true;
await page.route('**/api/tasks?*', async route => {
if (failTasks) return route.fulfill({ status: 500, contentType: 'text/plain', body: 'task store down' });
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify([
{ id: 1861, title: "Chat composer: '#' context dropdown", status: 'running' },
{ id: 1842, title: 'Retry stalled task runs', status: 'done' },
]),
});
});
const tasksPalette = page.getByRole('listbox', { name: 'Tasks' });
await composer.fill('Look at #');
await tasksPalette.getByRole('alert').waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 0);
failTasks = false;
await tasksPalette.getByRole('button', { name: 'Retry' }).click();
await tasksPalette.getByRole('option').first().waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 2);
await composer.press('Escape');
await tasksPalette.waitFor({ state: 'hidden' });
await composer.fill('Look at #184 now');
await composer.evaluate(el => el.setSelectionRange(12, 12));
await composer.dispatchEvent('input');
await tasksPalette.getByRole('option').first().waitFor();
assert.equal(await tasksPalette.getByRole('option').count(), 1);
await composer.press('Tab');
await tasksPalette.waitFor({ state: 'hidden' });
assert.equal(await composer.inputValue(), 'Look at now');
await page.getByRole('list', { name: 'Attached tasks' }).getByText('#1842').waitFor();
const tagged = page.waitForRequest('**/api/chat/stream');
await composer.press('Enter');
const text = (await tagged).postDataJSON().text;
assert.ok(text.startsWith('Look at now') && text.includes('#1842 Retry stalled task runs'), text);
assert.equal(await page.getByRole('list', { name: 'Attached tasks' }).count(), 0);
await shot('chat-composition');
};
+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 };
+2 -2
View File
@@ -230,7 +230,7 @@ func (a *LocalChatAdapter) runStreamedTurn(ctx context.Context, in Inbound, id s
run := func(turnCtx context.Context) ChatEvent {
reply, err := a.Router.streamTurn(turnCtx, in, stream)
if err != nil {
return ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}
return ChatEvent{Kind: "error", Text: turnFailureText(err), SessionID: id}
}
resolvedID := id
if resolved, err := a.Router.ResolveSessionKey(turnCtx, in); err == nil {
@@ -306,7 +306,7 @@ func (a *LocalChatAdapter) prelude(ctx context.Context, in Inbound, id string) s
}
ready, mine, err := a.Router.CollectTurn(ctx, in)
if err != nil {
return streamPrelude{event: &ChatEvent{Kind: "error", Text: err.Error(), SessionID: id}}
return streamPrelude{event: &ChatEvent{Kind: "error", Text: turnFailureText(err), SessionID: id}}
}
return streamPrelude{ready: ready, proceeds: mine}
}
+1 -1
View File
@@ -580,7 +580,7 @@ func (r *TurnRunner) failTurn(ctx context.Context, turn TurnRecord, cause error)
} else {
turn.Status = TurnStatusFailed
}
turn.Error = cause.Error()
turn.Error = turnFailureText(cause)
turn.UpdatedAt = time.Now().UTC()
if r.Log != nil {
level := slog.LevelError
+30
View File
@@ -0,0 +1,30 @@
package gateway
import (
"context"
"errors"
"github.com/samcharles93/ai-sdk/chat"
)
// turnFailureText is what a chat reader sees when a turn fails. The cause
// carries provider bodies, URLs and wrapping that belong in the log, which
// failTurn writes, not in front of whoever is chatting.
func turnFailureText(err error) string {
switch {
case errors.Is(err, chat.ErrRateLimited):
return "the model provider is refusing requests (rate limit or spending cap). Try again later, or switch model with /model."
case errors.Is(err, chat.ErrAuthFailed):
return "the model provider rejected Archie's credentials. Check the provider key in settings."
case errors.Is(err, chat.ErrProviderUnavailable):
return "the model provider is unavailable. Try again in a moment."
case errors.Is(err, chat.ErrContextLength):
return "this conversation is too long for the model. Start a new chat, or shorten it with /compress."
case errors.Is(err, chat.ErrUnsupportedContent):
return "the model can't read one of the attachments. Remove it, or switch model with /model."
case errors.Is(err, context.DeadlineExceeded):
return "the model took too long to answer. Try again."
default:
return "something went wrong on Archie's side. Try again; the gateway log has the cause."
}
}
+50
View File
@@ -0,0 +1,50 @@
package gateway
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
// A failed turn shows the reader what to do, never the provider's response
// body or the error's wrapping.
func TestStreamedTurnFailureHidesCause(t *testing.T) {
for _, tc := range []struct {
name string
cause error
want string
}{
{name: "spending cap", cause: chat.ErrRateLimited, want: "rate limit or spending cap"},
{name: "bad key", cause: chat.ErrAuthFailed, want: "credentials"},
{name: "unknown", cause: errors.New("dial tcp 10.0.0.1:5432: refused"), want: "gateway log"},
} {
t.Run(tc.name, func(t *testing.T) {
raw := fmt.Errorf(`llm chat stream: gemini: status 429: {"message":"https://ai.studio/spend"}: %w`, tc.cause)
router := &Router{LLMStream: func(context.Context, Inbound, TurnStream) (string, error) { return "", raw }}
adapter := &LocalChatAdapter{Router: router}
events := make(chan ChatEvent, 32)
go adapter.runStreamedTurn(context.Background(), Inbound{Message: messaging.Message{Text: "hi"}}, "s1", events)
for event := range events {
if event.Kind != "error" {
continue
}
for _, leak := range []string{"gemini", "429", "ai.studio", "10.0.0.1", "llm chat stream"} {
if strings.Contains(event.Text, leak) {
t.Fatalf("error text %q exposes %q", event.Text, leak)
}
}
if !strings.Contains(event.Text, tc.want) {
t.Fatalf("error text %q, want it to mention %q", event.Text, tc.want)
}
return
}
t.Fatal("no error event")
})
}
}
@@ -100,6 +100,9 @@ func splitLegacyChannelSettings(orgID string, stored []byte) (rewritten []byte,
return nil, telegramConnection{}, false, fmt.Errorf("decode telegram: %w", err)
}
delete(doc, "telegram")
// A document old enough to carry telegram can also carry the per-channel
// models that model aliases replaced, which the current schema rejects.
delete(doc, "models")
if orgID == storecontract.DefaultOrgID {
moved = telegramConnection{Token: legacy.TokenRef, Users: legacy.AllowedUserIDs}
} else if len(legacy.AllowedUserIDs) > 0 {
+1 -1
View File
@@ -96,7 +96,7 @@ watch(() => accounts.status?.user, (user) => {
<SidebarProvider class="bg-[var(--workspace)]">
<a href="#main-content" class="sr-only focus:not-sr-only focus:fixed focus:top-2 focus:left-4 focus:z-[60] focus:rounded-md focus:bg-card focus:px-3 focus:py-2">Skip to main content</a>
<AppSidebar :hidden="hidden" />
<SidebarInset class="min-w-0 bg-[var(--workspace)]" :class="workflowsPage && 'max-md:h-dvh'">
<SidebarInset class="min-w-0 bg-[var(--workspace)] md:ml-[var(--chat-pin-l,0px)] md:mr-[var(--chat-pin-r,0px)]" :class="workflowsPage && 'max-md:h-dvh'">
<header class="bg-card border-border-strong sticky top-0 z-30 flex h-14 shrink-0 items-center gap-2 border-b px-3 shadow-[var(--shadow-sm)] sm:px-4">
<SidebarTrigger class="-ml-1 md:hidden" />
<Brand />
+60 -17
View File
@@ -7,15 +7,24 @@ import { Clock, Mic, Pencil, X } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
import { applyCommand, isExactCommand } from "./commands";
import { isExactCommand, replaceToken } from "./commands";
import ChatSlashPalette from "./ChatSlashPalette.vue";
import {
closeCommandMenu,
commandMatches,
commandSelection,
commandSpecs,
addTaskTag,
clearPageTag,
pageTag,
composerText,
editQueued,
menuTrigger,
removeTaskTag,
retryTasks,
taskForKey,
taskLoadError,
taskTags,
isCommandMenuOpen,
isSending,
moveCommandSelection,
@@ -110,21 +119,27 @@ function onInput(event: Event): void {
}
function choose(index: number): void {
const spec = commandMatches.value[index];
const item = commandMatches.value[index];
const input = field.value?.$el;
if (!spec || !input) return;
// Completing the command replaces the token the caret sits in, which is
// decided by the same rule that found the matches.
const { text, cursor } = applyCommand(
input.value,
input.selectionStart ?? input.value.length,
spec.command,
);
composerText.value = text;
if (!item || !input) return;
const caret = input.selectionStart ?? input.value.length;
// Completing replaces the token the caret sits in, which is decided by the
// same rule that found the matches. A task leaves no text behind: it becomes
// a tag above the field.
let edit: { text: string; cursor: number };
if (menuTrigger.value === "#") {
const task = taskForKey(item.key);
if (!task) return;
addTaskTag(task);
edit = replaceToken(input.value, caret, "");
} else {
edit = replaceToken(input.value, caret, item.label);
}
composerText.value = edit.text;
closeCommandMenu();
void nextTick(() => {
input.focus();
input.setSelectionRange(cursor, cursor);
input.setSelectionRange(edit.cursor, edit.cursor);
});
}
@@ -132,12 +147,13 @@ function onKeydown(event: KeyboardEvent): void {
// Safari may end composition before delivering its confirming Enter.
if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) return;
const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey;
if (isCommandMenuOpen.value && commandMatches.value.length) {
if (isCommandMenuOpen.value) {
// A command typed in full is sent rather than completed, so Enter never
// re-enters the command the palette was offering.
if (
event.key === "Enter" &&
plain &&
menuTrigger.value === "/" &&
isExactCommand(commandSpecs.value, composerText.value)
) {
event.preventDefault();
@@ -155,7 +171,10 @@ function onKeydown(event: KeyboardEvent): void {
moveCommandSelection(-1);
return;
}
if (event.key === "Enter" && plain) {
if (
commandMatches.value.length &&
((event.key === "Enter" && plain) || (event.key === "Tab" && !event.shiftKey))
) {
event.preventDefault();
choose(commandSelection.value);
return;
@@ -202,6 +221,27 @@ function onKeydown(event: KeyboardEvent): void {
</Tooltip>
</li>
</ul>
<ul v-if="pageTag || taskTags.length" aria-label="Message context" class="mb-2 flex flex-wrap gap-1">
<li
v-if="pageTag"
class="flex max-w-full items-center gap-1 rounded-md border border-border bg-muted px-2 py-0.5 text-label"
>
<span class="truncate">{{ pageTag.label }}</span>
<Button variant="ghost" size="icon" class="size-5" aria-label="Remove page context" @click="clearPageTag"
><X
/></Button>
</li>
<li
v-for="tag in taskTags"
:key="tag.id"
class="flex max-w-full items-center gap-1 rounded-md border border-border bg-muted px-2 py-0.5 text-label"
>
<span class="truncate">#{{ tag.id }}{{ tag.title ? ` ${tag.title}` : "" }}</span>
<Button variant="ghost" size="icon" class="size-5" :aria-label="`Remove task ${tag.id}`" @click="removeTaskTag(tag.id)"
><X
/></Button>
</li>
</ul>
<div
:class="
cn(
@@ -218,18 +258,21 @@ function onKeydown(event: KeyboardEvent): void {
aria-label="Message Archie"
role="combobox"
aria-controls="slash-palette"
:aria-expanded="isCommandMenuOpen && commandMatches.length ? 'true' : 'false'"
: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"
/>
<ChatSlashPalette
v-if="isCommandMenuOpen && commandMatches.length"
v-if="isCommandMenuOpen"
:matches="commandMatches"
:selection="commandSelection"
:label="menuTrigger === '#' ? 'Tasks' : 'Commands'"
:error="menuTrigger === '#' ? taskLoadError : ''"
@choose="choose"
@retry="retryTasks"
/>
<!-- Centred on the field's first line, then kept at the bottom as it grows. -->
+197 -7
View File
@@ -1,13 +1,18 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { ChevronDown, ChevronUp } from "@lucide/vue";
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
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
@@ -19,6 +24,14 @@ import { composerText, escapeOwnedByLayer, isSending, useChat } from "./state";
* the conversation opens above it. Hiding the conversation leaves the bar. It is
* deliberately not a modal: no scrim, no scroll lock, no focus trap.
*
* On a desktop-width screen the expanded conversation can be pinned to the left
* or right edge, where the page reflows beside it instead of sitting under it.
* 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
@@ -26,7 +39,41 @@ 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";
const saved = useStorage<{ side: Side | null; width: number }>(
"archie.chat.dock",
{ side: null, width: 420 },
localStorage,
{ mergeDefaults: true },
);
const desktop = useMediaQuery("(min-width: 768px)");
const { width: viewport } = useWindowSize();
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,
@@ -72,6 +119,101 @@ onUnmounted(() => {
document.documentElement.style.removeProperty("--chat-dock-clear");
});
// The page makes room for a pinned dock through these two variables.
watch([side, width], ([s, w]) => {
const root = document.documentElement.style;
root.setProperty("--chat-pin-l", s === "left" ? `${w}px` : "0px");
root.setProperty("--chat-pin-r", s === "right" ? `${w}px` : "0px");
}, { immediate: true });
onUnmounted(() => {
document.documentElement.style.removeProperty("--chat-pin-l");
document.documentElement.style.removeProperty("--chat-pin-r");
});
function edgeAt(x: number): Side | null {
if (x <= EDGE) return "left";
if (x >= window.innerWidth - EDGE) return "right";
return 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 (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);
const move = (e: PointerEvent): void => {
const dx = e.clientX - x0;
const dy = e.clientY - y0;
if (!offset.value && Math.hypot(dx, dy) < DRAG_START) return;
offset.value = { x: dx, y: dy };
target.value = edgeAt(e.clientX);
};
const end = (e: PointerEvent): void => {
grip.removeEventListener("pointermove", move);
grip.removeEventListener("pointerup", end);
grip.removeEventListener("pointercancel", end);
if (offset.value && e.type === "pointerup") saved.value.side = edgeAt(e.clientX);
offset.value = null;
target.value = null;
};
grip.addEventListener("pointermove", move);
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(INTERACTIVE)) return;
saved.value.side = saved.value.side ? null : "right";
}
function resize(event: PointerEvent): void {
const handle = event.currentTarget as HTMLElement;
handle.setPointerCapture(event.pointerId);
const move = (e: PointerEvent): void => {
saved.value.width = side.value === "right" ? window.innerWidth - e.clientX : e.clientX;
};
const end = (): void => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
handle.removeEventListener("pointercancel", end);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
handle.addEventListener("pointercancel", end);
}
function resizeByKey(event: KeyboardEvent): void {
const grow = event.key === (side.value === "right" ? "ArrowLeft" : "ArrowRight");
const shrink = event.key === (side.value === "right" ? "ArrowRight" : "ArrowLeft");
if (!grow && !shrink) return;
event.preventDefault();
saved.value.width = width.value + (grow ? 16 : -16);
}
function usePrompt(text: string): void {
composerText.value = text;
composer.value?.focus();
@@ -79,13 +221,54 @@ function usePrompt(text: string): void {
</script>
<template>
<div class="pointer-events-none fixed inset-x-0 bottom-4 z-40 flex justify-center px-3 max-md:bottom-2">
<div
v-if="target"
aria-hidden="true"
:class="cn('pointer-events-none fixed inset-y-0 z-40 border-primary/40 bg-primary/10', target === 'left' ? 'left-0 border-r-2' : 'right-0 border-l-2')"
:style="{ width: `${width}px` }"
/>
<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',
)"
:style="side ? { width: `${width}px` } : desktop ? undefined : { bottom: phoneBottom }"
>
<aside
ref="dock"
aria-label="Chat with Archie"
class="pointer-events-auto flex w-full max-w-xl flex-col rounded-lg border border-border-strong bg-popover shadow-[var(--shadow-md)]"
:class="cn(
'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',
offset && 'z-50 opacity-90',
)"
:style="offset ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : undefined"
>
<ChatBar v-if="expanded">
<div
v-if="side"
role="separator"
aria-orientation="vertical"
aria-label="Resize chat"
tabindex="0"
:aria-valuenow="width"
:aria-valuemin="MIN_WIDTH"
class="absolute inset-y-0 z-10 w-1.5 cursor-col-resize hover:bg-primary/30 focus-visible:bg-primary/30 focus-visible:outline-none"
:class="side === 'left' ? '-right-0.5' : '-left-0.5'"
@pointerdown.prevent="resize"
@keydown="resizeByKey"
/>
<div
v-if="expanded"
:class="desktop ? 'cursor-grab select-none active:cursor-grabbing' : 'touch-none'"
@pointerdown="startDrag"
@dblclick="togglePin"
>
<div class="flex justify-center pt-1.5" aria-hidden="true">
<span class="h-1 w-8 rounded-full bg-border-strong" />
</div>
<ChatBar>
<Tooltip>
<TooltipTrigger as-child>
<Button
@@ -101,7 +284,12 @@ function usePrompt(text: string): void {
<TooltipContent>Hide conversation</TooltipContent>
</Tooltip>
</ChatBar>
<div v-if="expanded" class="flex h-[min(28rem,55dvh)] min-h-0 flex-col">
</div>
<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">
@@ -112,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>
+2
View File
@@ -1,4 +1,5 @@
<script setup lang="ts">
import ChatTaskRef from "./ChatTaskRef.vue";
import type { ChatInline } from "./markdown";
/** One inline run: the spans of a paragraph, a heading or a table cell. */
@@ -29,6 +30,7 @@ defineProps<{ inline: ChatInline[] }>();
class="text-link underline-offset-4 hover:underline"
>{{ span.text }}</a
>
<ChatTaskRef v-else-if="span.kind === 'taskref'" :id="span.id" />
<em v-else-if="span.kind === 'em'">{{ span.text }}</em>
<template v-else>{{ span.text }}</template>
</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>
+35
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import {
Copy,
Ellipsis,
GitBranch,
Pencil,
@@ -9,6 +10,7 @@ import {
Undo2,
} from "@lucide/vue";
import { ref } from "vue";
import { toast } from "vue-sonner";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
@@ -28,6 +30,7 @@ import { Input } from "@/components/ui/input";
import ChatSettings from "./ChatSettings.vue";
import {
currentSession,
messages,
runSessionCommand,
useEscapeLayer,
} from "./state";
@@ -51,6 +54,31 @@ function run(command: string): void {
void runSessionCommand(command);
}
// Reply text is already Markdown, so the transcript is the messages under a
// heading per speaker. Empty turns (tool-only replies) have nothing to paste.
async function copyMarkdown(): Promise<void> {
open.value = false;
const text = messages.value
.map((m) => {
const body = (m.text ?? m.Text ?? "").trim();
if (!body) return "";
return `### ${(m.from ?? m.From) === "web" ? "You" : "Archie"}\n\n${body}`;
})
.filter(Boolean)
.join("\n\n");
if (!text) {
toast.error("Nothing to copy");
return;
}
try {
await navigator.clipboard.writeText(text);
} catch (err) {
toast.error(`Not copied: ${(err as Error).message || "clipboard unavailable"}`);
return;
}
toast.success("Copied as Markdown");
}
// Rename and branch ask for a value in a labelled dialog, not window.prompt.
const promptOpen = ref(false);
const promptCommand = ref("");
@@ -124,6 +152,13 @@ function submitPrompt(): void {
@click="run('/compress --preview')"
><Shrink data-icon="inline-start" />Preview compression</Button
>
<Button
variant="ghost"
size="sm"
class="justify-start"
@click="copyMarkdown"
><Copy data-icon="inline-start" />Copy as Markdown</Button
>
<Separator class="my-1" />
</template>
<ChatSettings />
+21 -11
View File
@@ -2,15 +2,21 @@
import { nextTick, ref, watch } from "vue";
import { commandScrollTop } from "./command-scroll";
import type { ChatCommandSpec } from "./state";
import { Button } from "@/components/ui/button";
import type { Completion } from "./commands";
/**
* The slash palette: the commands the server accepts, floating above the
* composer. It is the only command surface -- there is no second list anywhere
* in the panel -- so the arrow keys and the pointer both land here.
* The composer palette, floating above it: the commands the server accepts
* after `/`, the tasks that can be attached after `#`. The arrow keys and the
* pointer both land here. A failed read shows in place of the rows.
*/
const props = defineProps<{ matches: ChatCommandSpec[]; selection: number }>();
const emit = defineEmits<{ choose: [index: number] }>();
const props = defineProps<{
matches: Completion[];
selection: number;
label: string;
error?: string;
}>();
const emit = defineEmits<{ choose: [index: number]; retry: [] }>();
const menu = ref<HTMLElement | null>(null);
@@ -41,12 +47,16 @@ watch(
ref="menu"
id="slash-palette"
role="listbox"
aria-label="Commands"
:aria-label="label"
class="absolute inset-x-3 bottom-[calc(100%-0.25rem)] z-30 grid max-h-72 gap-0.5 overflow-auto rounded-lg border border-border-strong bg-popover p-1.5 shadow-md"
>
<div v-if="error" role="alert" class="flex items-center justify-between gap-2 px-2.5 py-2 text-danger">
<span class="truncate">{{ error }}</span>
<Button variant="outline" size="sm" @mousedown.prevent @click="emit('retry')">Retry</Button>
</div>
<button
v-for="(spec, index) in matches"
:key="spec.command"
v-for="(item, index) in matches"
:key="item.key"
type="button"
role="option"
:id="`slash-palette-option-${index}`"
@@ -55,8 +65,8 @@ watch(
@mousedown.prevent
@click="emit('choose', index)"
>
<code class="truncate text-foreground">{{ spec.command }}</code>
<span class="truncate">{{ spec.description || spec.usage || "" }}</span>
<code class="truncate text-foreground">{{ item.label }}</code>
<span class="truncate">{{ item.detail }}</span>
</button>
</div>
</template>
+59
View File
@@ -0,0 +1,59 @@
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { revealTaskRow, taskExists } from "./task-ref";
/**
* A #N in a reply. It becomes a link only once the tasks API confirms the
* task exists, so an issue number or a stray count stays plain text. On the
* Tasks page, where the row is already listed, it scrolls there instead of
* leaving the page.
*/
const props = defineProps<{ id: number }>();
const route = useRoute();
const exists = ref(false);
// A streaming reply shows #1 before #12; the short wait skips the partial one.
let timer = 0;
watch(
() => props.id,
(id) => {
exists.value = false;
window.clearTimeout(timer);
timer = window.setTimeout(async () => {
const found = await taskExists(id);
if (id === props.id) exists.value = found === true;
}, 250);
},
{ immediate: true },
);
onBeforeUnmount(() => window.clearTimeout(timer));
function onClick(event: MouseEvent, navigate: (e: MouseEvent) => void) {
if (route.path === "/tasks" && revealTaskRow(props.id)) {
event.preventDefault();
return;
}
navigate(event);
}
</script>
<template>
<RouterLink
v-if="exists"
v-slot="{ href, navigate }"
:to="`/tasks/${id}`"
custom
>
<a
:href="href"
:title="`Task ${id}`"
class="rounded bg-primary-soft px-1 py-0.5 font-mono text-[0.9em] text-link hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
@click="onClick($event, navigate)"
>#{{ id }}</a
>
</RouterLink>
<template v-else>#{{ id }}</template>
</template>
+2 -7
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";
/**
@@ -78,9 +76,6 @@ const rows = computed(() => {
},
];
});
// A task this conversation started reports its outcome into it.
useLiveResource("chat", () => void reloadTranscript());
</script>
<template>
@@ -141,7 +136,7 @@ useLiveResource("chat", () => void reloadTranscript());
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton />
<ChatJumpButton />
</MessageScroller>
</MessageScrollerProvider>
</template>
+61 -25
View File
@@ -1,54 +1,90 @@
import type { ChatCommandSpec } from "./state";
import type { ChatCommandSpec, TaskRef } from "./state";
/**
* The slash palette's arithmetic, kept out of the composer so it is decided in
* one place rather than reconstructed from DOM positions twice.
* The composer palette's arithmetic, kept out of the composer so it is decided
* in one place rather than reconstructed from DOM positions twice. Two
* triggers share it: `/` completes a command, `#` picks a task.
*/
/** The command token the caret sits in: a slash word at the start or after a space. */
const OPEN_TOKEN = /(?:^|\s)\/([^\s]*)$/;
const ANY_TOKEN = /(?:^|\s)\/[^\s]*$/;
export type Trigger = "/" | "#";
/** One row of the palette: what is shown, and the key that identifies it. */
export interface Completion {
key: string;
label: string;
detail: string;
}
/** The trigger word the caret sits in: at the start or after whitespace. */
const OPEN_TOKEN = /(?:^|\s)([/#])([^\s]*)$/;
/** How many matches the palette will show at once. */
const MAX_MATCHES = 8;
/**
* matchesFor returns the commands worth offering for the text before the
* caret, matched on the command and its description together so a word from
* either finds it.
*/
export function matchesFor(
specs: ChatCommandSpec[],
/** detectTrigger returns the trigger and the text typed after it, if any. */
export function detectTrigger(
value: string,
caret: number,
): ChatCommandSpec[] {
): { trigger: Trigger; query: string } | null {
const match = value.slice(0, caret).match(OPEN_TOKEN);
if (!match) return [];
const query = match[1].toLowerCase();
if (!match) return null;
return { trigger: match[1] as Trigger, query: match[2].toLowerCase() };
}
/** Commands matched on the command and its description together. */
export function commandCompletions(
specs: ChatCommandSpec[],
query: string,
): Completion[] {
return specs
.filter((spec) =>
`${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(query),
)
.slice(0, MAX_MATCHES);
.slice(0, MAX_MATCHES)
.map((spec) => ({
key: spec.command,
label: spec.command,
detail: spec.description || spec.usage || "",
}));
}
/** Tasks matched on id and title, so `#12` and a title word both find one. */
export function taskCompletions(tasks: TaskRef[], query: string): Completion[] {
return tasks
.filter((task) =>
`${task.id} ${task.title ?? ""}`.toLowerCase().includes(query),
)
.slice(0, MAX_MATCHES)
.map((task) => ({
key: String(task.id),
label: `#${task.id}`,
detail: task.title ?? "",
}));
}
/**
* applyCommand replaces the token being completed with the chosen command and
* returns the cursor position just after it, ready for the next word.
* replaceToken swaps the trigger word the caret sits in for `insert` and
* returns the caret just after it. A space follows the insert unless one
* already does, so completing mid-sentence never doubles it. An empty insert
* removes the token.
*/
export function applyCommand(
export function replaceToken(
value: string,
caret: number,
command: string,
insert: string,
): { text: string; cursor: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const start = before.search(ANY_TOKEN);
const start = before.search(/(?:^|\s)[/#][^\s]*$/);
const tokenStart =
start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
start < 0 ? before.length : start + (/\s/.test(before[start]) ? 1 : 0);
const head = before.slice(0, tokenStart);
const gap = insert === "" || /^\s/.test(after) ? "" : " ";
// Removing the token must not leave the words either side of it two spaces apart.
const tail = insert === "" && /\s$/.test(head) ? after.replace(/^[ \t]/, "") : after;
return {
text: `${before.slice(0, tokenStart)}${command} ${after}`,
cursor: tokenStart + command.length + 1,
text: `${head}${insert}${gap}${tail}`,
cursor: tokenStart + insert.length + gap.length,
};
}
+20 -2
View File
@@ -15,6 +15,7 @@ export type ChatInline =
| { kind: "del"; text: string }
| { kind: "code"; text: string }
| { kind: "link"; text: string; href: string }
| { kind: "taskref"; id: number }
| { kind: "image"; alt: string; src: string };
/** One block of the document. Lists carry their items as inline runs. */
@@ -27,6 +28,23 @@ export type ChatBlock =
const INLINE =
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
// A #N the model wrote about a task. Not part of a word, entity or path.
const TASK_REF = /(?<![\w&#/])#(\d{1,9})(?!\w)/g;
// plainText splits a run of plain text around its task references.
function plainText(text: string): ChatInline[] {
const out: ChatInline[] = [];
let cursor = 0;
for (const match of text.matchAll(TASK_REF)) {
if (match.index > cursor)
out.push({ kind: "text", text: text.slice(cursor, match.index) });
out.push({ kind: "taskref", id: Number(match[1]) });
cursor = match.index + match[0].length;
}
if (cursor < text.length) out.push({ kind: "text", text: text.slice(cursor) });
return out;
}
// inlineMarkdown returns the children of one line: plain text and the element
// each matched span becomes, in order.
function inlineMarkdown(text: string): ChatInline[] {
@@ -34,7 +52,7 @@ function inlineMarkdown(text: string): ChatInline[] {
let cursor = 0;
for (const match of String(text).matchAll(INLINE)) {
if (match.index > cursor)
children.push({ kind: "text", text: text.slice(cursor, match.index) });
children.push(...plainText(text.slice(cursor, match.index)));
const value = match[0];
if (value.startsWith("![")) {
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
@@ -57,7 +75,7 @@ function inlineMarkdown(text: string): ChatInline[] {
cursor = match.index + value.length;
}
if (cursor < text.length)
children.push({ kind: "text", text: text.slice(cursor) });
children.push(...plainText(text.slice(cursor)));
return children;
}
+150 -17
View File
@@ -1,9 +1,10 @@
import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
import { router } from "@/router";
import { randomUUID } from "@/lib/uuid";
import { channelID } from "./channel";
import { matchesFor } from "./commands";
import { commandCompletions, detectTrigger, taskCompletions, type Completion, type Trigger } from "./commands";
import {
resolveTurn,
retryChatTurn,
@@ -35,6 +36,13 @@ export interface ChatCommandSpec {
description?: string;
}
/** A task the operator can attach to a message as context. */
export interface TaskRef {
id: number | string;
title?: string;
status?: string;
}
/**
* A tool the assistant called. A live frame names the tool in `tool` and
* carries its outcome in `text`; a recorded turn uses `name` and `summary`.
@@ -203,6 +211,40 @@ export const composerText = computed({
drafts.value = { ...drafts.value, [currentSession.value]: value };
},
});
const tagDrafts = ref<Record<string, TaskRef[]>>({});
/** The tasks attached to the unsent message; each conversation keeps its own. */
export const taskTags = computed(() => tagDrafts.value[currentSession.value] ?? []);
export function addTaskTag(task: TaskRef): void {
if (taskTags.value.some((tag) => tag.id === task.id)) return;
tagDrafts.value = { ...tagDrafts.value, [currentSession.value]: [...taskTags.value, task] };
}
export function removeTaskTag(id: TaskRef["id"]): void {
tagDrafts.value = {
...tagDrafts.value,
[currentSession.value]: taskTags.value.filter((tag) => tag.id !== id),
};
}
function clearDraft(): void {
composerText.value = "";
removeAllTags();
}
function removeAllTags(): void {
tagDrafts.value = { ...tagDrafts.value, [currentSession.value]: [] };
}
/** The message as sent: the typed text, then the tasks it is about. */
function withTaskContext(text: string): string {
if (!taskTags.value.length) return text;
const refs = taskTags.value
.map((task) => `#${task.id}${task.title ? ` ${task.title}` : ""}`)
.join("; ");
return `${text}\n\nContext, tasks: ${refs}`;
}
export const statusText = ref("Ready");
export const isSending = ref(false);
export const isLoadingSession = ref(false);
@@ -215,7 +257,11 @@ export const selectorData = ref<ChatSelectorData>({});
export const selectedModel = ref("");
export const commandSpecs = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<Completion[]>([]);
/** Which trigger the open menu was opened by. */
export const menuTrigger = ref<Trigger>("/");
/** Why the task list could not be read; shown in the menu, with a retry. */
export const taskLoadError = ref("");
export const commandSelection = ref(0);
export const isCommandMenuOpen = ref(false);
@@ -290,7 +336,7 @@ async function sendCommand(
channel_id: channelID(),
source_id: randomUUID(),
text,
page: currentPage(),
page: sentPage(),
});
if (!response.body) throw new Error("the chat stream returned no body");
const reader = response.body.getReader();
@@ -509,17 +555,71 @@ export function editQueued(index: number): void {
composerText.value = composerText.value.trim() ? `${composerText.value}\n${text}` : text;
}
/** Opens the palette for the slash word the caret sits in, or closes it. */
let taskChoices: TaskRef[] = [];
let loadGeneration = 0;
let lastInput = { value: "", caret: 0 };
async function loadTasks(): Promise<void> {
const generation = ++loadGeneration;
try {
const page = await api.taskPage<TaskRef>({ limit: 100 });
if (generation !== loadGeneration) return;
taskChoices = page.tasks;
taskLoadError.value = "";
} catch (err) {
if (generation !== loadGeneration) return;
taskLoadError.value = (err as Error).message || "Could not load tasks";
}
renderMenu();
}
/** Reads the task list again after a failure, for the menu's Retry. */
export function retryTasks(): void {
taskLoadError.value = "";
void loadTasks();
}
/** Opens the palette for the trigger word the caret sits in, or closes it. */
export function syncCommandMenu(value: string, caret: number): void {
const matches = matchesFor(commandSpecs.value, value, caret);
if (matches.length) {
commandMatches.value = matches;
commandSelection.value = 0;
isCommandMenuOpen.value = true;
lastInput = { value, caret };
// The list is read when # is first typed, so it is never older than the
// moment the operator reached for it.
if (
detectTrigger(value, caret)?.trigger === "#" &&
(!isCommandMenuOpen.value || menuTrigger.value !== "#")
) {
taskLoadError.value = "";
void loadTasks();
}
renderMenu();
}
function renderMenu(): void {
const found = detectTrigger(lastInput.value, lastInput.caret);
let matches: Completion[] = [];
if (found?.trigger === "/") {
matches = commandCompletions(commandSpecs.value, found.query);
} else if (found?.trigger === "#") {
matches = taskCompletions(taskChoices, found.query);
}
const showsError = found?.trigger === "#" && !!taskLoadError.value;
if (!found || (!matches.length && !showsError)) {
isCommandMenuOpen.value = false;
commandMatches.value = [];
return;
}
isCommandMenuOpen.value = false;
commandMatches.value = [];
if (!isCommandMenuOpen.value || menuTrigger.value !== found.trigger) {
commandSelection.value = 0;
}
menuTrigger.value = found.trigger;
commandMatches.value = matches;
commandSelection.value = Math.min(commandSelection.value, Math.max(matches.length - 1, 0));
isCommandMenuOpen.value = true;
}
/** The task a menu row stands for. */
export function taskForKey(key: string): TaskRef | undefined {
return taskChoices.find((task) => String(task.id) === key);
}
export function closeCommandMenu(): void {
@@ -532,9 +632,39 @@ export function moveCommandSelection(delta: number): void {
commandSelection.value = (commandSelection.value + delta + length) % length;
}
/** The page the operator asked from, so an answer can be about what they saw. */
/** The page the operator is on, without the hash the server never sees. */
function currentPage(): string {
return location.pathname + location.search || "/";
return router.currentRoute.value.fullPath.split("#")[0] || "/";
}
// The page whose tag the operator removed. Navigating elsewhere shows the tag
// again, so the dismissal never outlives the page it was made on.
const clearedPage = ref("");
watch(currentPage, () => {
clearedPage.value = "";
});
/** What the next message is about, named for the tag above the composer. */
export const pageTag = computed(() => {
const page = currentPage();
if (page === clearedPage.value) return null;
const route = router.currentRoute.value;
const label =
route.name === "task-detail"
? `Task #${route.params.id}`
: typeof route.meta.label === "string"
? route.meta.label
: page;
return { page, label };
});
export function clearPageTag(): void {
clearedPage.value = currentPage();
}
/** The page sent with a message: the tag's page, or none once it is cleared. */
function sentPage(): string | undefined {
return pageTag.value?.page;
}
export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
@@ -542,8 +672,11 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
// detaches the turn, so its writes stop landing.
const epoch = sessionEpoch;
const explicitText = retryOpts?.textOverride;
const typed = explicitText !== undefined ? explicitText : composerText.value;
const rawValue =
explicitText !== undefined ? explicitText : composerText.value;
explicitText === undefined && !retryOpts?.turn && typed.trim()
? withTaskContext(typed.trim())
: typed;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawValue);
if (!text) return;
if (isSending.value) {
@@ -555,7 +688,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
return;
}
queuedMessages.value = [...queuedMessages.value, text];
if (explicitText === undefined) composerText.value = "";
if (explicitText === undefined) clearDraft();
closeCommandMenu();
return;
}
@@ -567,7 +700,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
if (!isRetry) {
messages.value = [...messages.value, { from: "web", text }];
// A queued or command send must not clear what is being typed.
if (explicitText === undefined) composerText.value = "";
if (explicitText === undefined) clearDraft();
}
// A bare /model offers its choices as buttons, as Telegram does; with an
@@ -629,7 +762,7 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
page: sentPage(),
voice: turn.voice,
},
{ signal: ctrl.signal },
+50
View File
@@ -0,0 +1,50 @@
import { api, ApiError } from "@/lib/api";
const FOUND_TTL_MS = 10 * 60_000;
const MISSING_TTL_MS = 30_000;
const lookups = new Map<number, { at: number; found: boolean }>();
const inflight = new Map<number, Promise<boolean | null>>();
/**
* Whether task `id` exists, asked of the tasks API. Answers are kept briefly
* so a reply that re-renders every frame asks once. A task that was missing a
* moment ago may have been created since, so that answer expires quickly. A
* failed lookup is null and is not kept: the reference stays plain text.
*/
export function taskExists(id: number): Promise<boolean | null> {
const known = lookups.get(id);
if (known && Date.now() - known.at < (known.found ? FOUND_TTL_MS : MISSING_TTL_MS))
return Promise.resolve(known.found);
let pending = inflight.get(id);
if (!pending) {
pending = api
.task(String(id))
.then(() => true)
.catch((err) => (err instanceof ApiError && err.status === 404 ? false : null))
.then((found) => {
if (found !== null) lookups.set(id, { at: Date.now(), found });
inflight.delete(id);
return found;
});
inflight.set(id, pending);
}
return pending;
}
const HIGHLIGHT = ["bg-primary-soft", "motion-safe:transition-colors", "motion-safe:duration-700"];
/**
* Scrolls to task `id`'s row when the page lists it and marks it once.
* Returns false when no such row is on screen.
*/
export function revealTaskRow(id: number): boolean {
const row = document.querySelector<HTMLElement>(`tr[data-row-key="${id}"]`);
if (!row) return false;
const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
row.scrollIntoView({ block: "center", behavior: still ? "auto" : "smooth" });
row.classList.add(...HIGHLIGHT);
window.setTimeout(() => row.classList.remove("bg-primary-soft"), 1600);
window.setTimeout(() => row.classList.remove(...HIGHLIGHT), 2400);
return true;
}
+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;
}
+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));
}
}
}