Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
refactor(ui): read the shared message type catalog instead of a hand-kept mirror (#1048)
Call White1a2d29d02b1e
diff --git a/Dockerfile b/Dockerfileindex 100544632..09f265bed 100644--- a/Dockerfile+++ b/Dockerfile@@ -6,6 +6,11 @@ FROM node:20-slim AS ui-builderWORKDIR /app/uiCOPY ui/package.json ui/package-lock.json ./RUN npm ci --ignore-scripts+# ``ui/src/lib/messageTypes.ts`` imports the repo-root message-type policy catalog so+# the Web UI and the Python readers share one declaration. This stage copies only+# ``ui/``, so the catalog has to be placed at the repository-relative path the import+# expects, or ``npm run build`` fails to resolve it.+COPY vibe/message_types.json /app/vibe/message_types.jsonCOPY ui/ .RUN npm run builddiff --git a/ui/package.json b/ui/package.jsonindex 6ec1dd6a7..6116ef8d2 100644--- a/ui/package.json+++ b/ui/package.json@@ -8,7 +8,8 @@},"scripts": {"dev": "vite",- "build": "tsc -b && vite build",+ "validate:imports": "node scripts/validate-out-of-tree-imports.mjs",+ "build": "npm run validate:imports && tsc -b && vite build","lint": "eslint .","preview": "vite preview","test:crypto": "vitest run src/lib/vaultCrypto.test.ts",diff --git a/ui/scripts/validate-out-of-tree-imports.mjs b/ui/scripts/validate-out-of-tree-imports.mjsnew file mode 100644index 000000000..66c848004--- /dev/null+++ b/ui/scripts/validate-out-of-tree-imports.mjs@@ -0,0 +1,104 @@+// The Docker ``ui-builder`` stage runs ``npm run build`` with only ``ui/`` copied into the+// image, so any import that escapes ``ui/`` — the shared message-type catalog at the+// repository root, for one — fails to resolve there unless the Dockerfile also places that+// file at the path the import expects. No CI job builds that image, so nothing else in the+// pipeline catches the breakage: this check is the guard, and it runs as part of+// ``npm run build`` so every existing build path enforces it.++import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));+const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url));+const DOCKERFILE = fileURLToPath(new URL('../../Dockerfile', import.meta.url));++// Stage 1 builds from ``/app/ui``, so the repository root maps to ``/app`` in that image.+const STAGE_WORKDIR = '/app/ui';+const IMAGE_REPO_ROOT = '/app';++const RELATIVE_SPECIFIER = /(?:from|import)\s*\(?\s*['"](\.[^'"]+)['"]/g;++const sourceFiles = (dir) =>+ fs+ .readdirSync(dir, { withFileTypes: true })+ .flatMap((entry) => {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) return sourceFiles(full);+ return /\.tsx?$/.test(entry.name) ? [full] : [];+ });++/** Repository-relative paths that ``ui/src`` imports from outside ``ui/``. */+function escapingImports() {+ const found = new Set();+ for (const file of sourceFiles(path.join(UI_ROOT, 'src'))) {+ const source = fs.readFileSync(file, 'utf8');+ for (const [, specifier] of source.matchAll(RELATIVE_SPECIFIER)) {+ const resolved = path.resolve(path.dirname(file), specifier);+ if (!resolved.startsWith(UI_ROOT)) found.add(path.relative(REPO_ROOT, resolved));+ }+ }+ return [...found].sort();+}++/** ``COPY`` instructions in the ``ui-builder`` stage that read from the build context. */+function uiBuilderCopies() {+ const stage = fs+ .readFileSync(DOCKERFILE, 'utf8')+ .split(/^FROM /m)+ .find((block) => /^\S+\s+AS\s+ui-builder\b/i.test(block));+ if (!stage) throw new Error('Dockerfile no longer declares a ui-builder stage');+ return [...stage.matchAll(/^COPY\s+(?!--from)(.+)$/gm)].flatMap(([, args]) => {+ const parts = args.trim().split(/\s+/);+ const destination = parts.pop();+ if (!destination) return [];+ return parts.map((source) => ({ source: source.replace(/\/$/, ''), destination }));+ });+}++/** Where *target* ends up inside the image, or undefined when no ``COPY`` provides it. */+function imagePathOf(target, copies) {+ for (const { source, destination } of copies) {+ const isSameFile = target === source;+ if (!isSameFile && !target.startsWith(`${source}/`)) continue;+ const base = destination.startsWith('/')+ ? destination+ : path.posix.join(STAGE_WORKDIR, destination);+ // Docker copies a directory's *contents* into the destination.+ return isSameFile ? base : path.posix.join(base, path.posix.relative(source, target));+ }+ return undefined;+}++if (!fs.existsSync(DOCKERFILE)) {+ // Expected inside the ``ui-builder`` stage itself, which copies only ``ui/``. A missing+ // catalog there fails the build anyway, at the import that needs it.+ console.log('Out-of-tree import validation skipped: no Dockerfile in this checkout.');+ process.exit(0);+}++const escaping = escapingImports();+// Guard against a vacuous pass if the scan above ever stops finding anything.+if (escaping.length === 0) {+ throw new Error(+ 'No imports escaping ui/ were found — the scan is no longer testing anything. ' ++ 'Delete this check if the last such import is gone, otherwise fix the scan.',+ );+}++const copies = uiBuilderCopies();+for (const target of escaping) {+ const expected = path.posix.join(IMAGE_REPO_ROOT, target);+ const actual = imagePathOf(target, copies);+ if (actual !== expected) {+ throw new Error(+ `ui/src imports ${target} from outside ui/, but the Dockerfile's ui-builder stage ` ++ `puts it at ${actual ?? 'no path at all'} instead of ${expected}. ` ++ `Add "COPY ${target} ${expected}" to that stage.`,+ );+ }+}++console.log(+ `Out-of-tree import validation passed: ${escaping.join(', ')} reachable in the ui-builder stage.`,+);diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex d4bc642f2..eb1f5356d 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -13,6 +13,7 @@ import type { SessionActivityItemKind, SessionActivityState, SessionRuntimeStateimport { apiFetch } from '../../lib/apiFetch';import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';import { isNotifyMessageType, isTerminalAgentMessage } from '../../lib/chatMessageTypes';+import { specFor } from '../../lib/messageTypes';import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';import { isProxyMediaUrl } from '../../lib/mediaProxy';import { localPath, type ShowPageLinkInfo } from '../../lib/showPageLinks';@@ -102,15 +103,15 @@ const emptyRuntimeState = (): SessionRuntimeState => ({connection: 'unknown',});-// The transcript-visible message types — mirrors the server filter on-// ``GET /api/sessions/{id}/messages`` so the live ``message.new`` feed appends-// the same rows the initial load shows (assistant / tool_call are process log).+// The transcript-visible message types — the shared catalog's ``transcript``+// property, the same declaration the server filter on+// ``GET /api/sessions/{id}/messages`` reads, so the live ``message.new`` feed+// appends the same rows the initial load shows (assistant / tool_call are process+// log). The ``show_page`` clause is NOT a message type: it is a metadata side+// channel standing in for a Show-Page message type the server does not emit yet,+// and it stays until the annotation rollout gives those rows a real type.const isTranscriptMessage = (msg: WorkbenchMessage): boolean =>- msg.type === 'user' ||- msg.type === 'harness' ||- msg.type === 'result' ||- msg.type === 'error' ||- msg.type === 'notify' ||+ specFor(msg.type).transcript ||(msg.metadata as { source?: string } | null)?.source === 'show_page';// Bounded retained transcript window: cap how many message rows stay mounted so adiff --git a/ui/src/components/workbench/search/messageSearchRole.ts b/ui/src/components/workbench/search/messageSearchRole.tsindex 41b145e59..6a2a71670 100644--- a/ui/src/components/workbench/search/messageSearchRole.ts+++ b/ui/src/components/workbench/search/messageSearchRole.ts@@ -1,11 +1,18 @@import type { MessageSearchMatch } from '../../../context/ApiContext';+import { specFor } from '../../../lib/messageTypes';export type MessageSearchRole = 'you' | 'automated' | 'agent';export const messageSearchRole = (match: Pick<MessageSearchMatch, 'author' | 'source' | 'type'>,): MessageSearchRole => {- if (match.author === 'harness' || match.source === 'harness' || match.type === 'harness') {+ // The type test is the catalog's input-turn identity: a type accepted as harness+ // input (``inputAuthors`` contains ``harness``), not a bare name comparison.+ if (+ match.author === 'harness' ||+ match.source === 'harness' ||+ specFor(match.type).inputAuthors.includes('harness')+ ) {return 'automated';}return match.author === 'user' ? 'you' : 'agent';diff --git a/ui/src/lib/agentActivity.ts b/ui/src/lib/agentActivity.tsindex 78ae8e8c4..a18d1b6cf 100644--- a/ui/src/lib/agentActivity.ts+++ b/ui/src/lib/agentActivity.ts@@ -1,4 +1,5 @@import type { WorkbenchMessage } from '../context/ApiContext';+import { specFor } from './messageTypes';// One turn's activity, as rendered by the Chat Activity panel. Mirrors the// backend ``storage/agent_activity_service.py`` shape (see the /activity endpoint).@@ -149,8 +150,9 @@ export const liveActivityReducer = (}};+// Process-log rows for the Activity panel — the catalog's ``activity`` render kind.export const isActivityMessageType = (type: string): boolean =>- type === 'assistant' || type === 'tool_call';+ specFor(type).render === 'activity';// ``format_toolcall`` stores "🔧 `ToolName` `{json params}`" (one string, backend// formatter output). Parse the tool name (first backtick token, else first worddiff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.tsindex 376ab9c9a..74655e779 100644--- a/ui/src/lib/chatMessageTypes.ts+++ b/ui/src/lib/chatMessageTypes.ts@@ -1,5 +1,7 @@-export const isNotifyMessageType = (type: string): boolean =>- type === 'notify' || type === 'error';+import { specFor } from './messageTypes';++// Status pills rather than authored answers — the catalog's ``status`` render kind.+export const isNotifyMessageType = (type: string): boolean => specFor(type).render === 'status';type TerminalMessageCandidate = {author: string;@@ -7,8 +9,14 @@ type TerminalMessageCandidate = {metadata?: Record<string, unknown> | null;};-export const isTerminalAgentMessage = (message: TerminalMessageCandidate): boolean =>- message.author === 'agent' &&- (message.type === 'result' ||- message.type === 'error' ||- (message.type === 'notify' && message.metadata?.event === 'backend_failure'));+// A terminal reply the TRANSCRIPT shows: the catalog's terminal activity role+// intersected with transcript visibility (``silent`` is terminal for activity+// bookkeeping but never rendered), plus the conditional terminals that only settle+// a turn for specific metadata events (``notify`` + ``backend_failure``).+export const isTerminalAgentMessage = (message: TerminalMessageCandidate): boolean => {+ if (message.author !== 'agent') return false;+ const spec = specFor(message.type);+ if (spec.transcript && spec.activityRole === 'terminal') return true;+ const event = message.metadata?.event;+ return typeof event === 'string' && spec.terminalWhenEvents.includes(event);+};diff --git a/ui/src/lib/messageTypes.test.ts b/ui/src/lib/messageTypes.test.tsnew file mode 100644index 000000000..9d0fdfa59--- /dev/null+++ b/ui/src/lib/messageTypes.test.ts@@ -0,0 +1,136 @@+import { describe, expect, it } from 'vitest';++import catalog from '../../../vibe/message_types.json';+import { messageSearchRole } from '../components/workbench/search/messageSearchRole';+import { isActivityMessageType } from './agentActivity';+import { isNotifyMessageType, isTerminalAgentMessage } from './chatMessageTypes';+import { messageTypeNames, specFor } from './messageTypes';++describe('message type catalog reader', () => {+ it('reads the same tracked file the Python readers read', () => {+ // Not a re-declaration: the assertion compares the reader against the very+ // bytes it loaded, which is what makes a hand-kept TypeScript copy impossible.+ expect(messageTypeNames()).toEqual(Object.keys(catalog.types));+ });++ it('resolves every declared property, defaults included', () => {+ // ``user`` declares 6 of the properties; the other 7 must come from defaults.+ expect(Object.keys(specFor('user'))).toEqual(Object.keys(catalog.defaults));+ expect(specFor('user').transcript).toBe(true);+ expect(specFor('user').unread).toBe(false);+ });++ it('gives unknown types the catalog defaults', () => {+ expect(specFor('a_type_the_catalog_never_declares')).toEqual(specFor(''));+ expect(specFor('a_type_the_catalog_never_declares')).toMatchObject(catalog.defaults);+ });+});++// ===== One-time equivalence oracle =====+// The five predicates as they read BEFORE this lane replaced their inline type-name+// lists with catalog lookups. This is frozen historical behavior, NOT a catalog+// mirror to maintain: it is asserted only over ``PRE_REFACTOR_TYPES`` — the names+// that existed at the refactor — so a type added to the catalog later is out of its+// scope by construction. A failure here means a catalog value and the frontend's+// former behavior disagree, which is a drift finding to raise, not a snapshot to+// quietly update.+const PRE_REFACTOR_TYPES = [+ 'user',+ 'harness',+ 'result',+ 'notify',+ 'error',+ 'assistant',+ 'tool_call',+ 'queued',+ 'draft',+ 'pending',+ 'harness_dedupe',+ 'silent',+] as const;++// Unknown / non-type strings the predicates must also agree on.+const PROBE_TYPES: readonly string[] = [...PRE_REFACTOR_TYPES, 'show_annotation', 'future_type', ''];++const wasTranscript = (type: string): boolean =>+ type === 'user' ||+ type === 'harness' ||+ type === 'result' ||+ type === 'error' ||+ type === 'notify';++const wasNotify = (type: string): boolean => type === 'notify' || type === 'error';++const wasActivity = (type: string): boolean => type === 'assistant' || type === 'tool_call';++const wasHarnessInputType = (type: string): boolean => type === 'harness';++type TerminalCandidate = { author: string; type: string; metadata?: Record<string, unknown> | null };++const wasTerminalAgentMessage = (message: TerminalCandidate): boolean =>+ message.author === 'agent' &&+ (message.type === 'result' ||+ message.type === 'error' ||+ (message.type === 'notify' && message.metadata?.event === 'backend_failure'));++describe('catalog-derived predicates match pre-refactor behavior', () => {+ it('transcript visibility (ChatPage isTranscriptMessage)', () => {+ // ``isTranscriptMessage`` is ``specFor(type).transcript`` OR the unchanged+ // ``metadata.source === 'show_page'`` side channel, so the catalog property is+ // the whole type-driven half of that predicate.+ for (const type of PROBE_TYPES) {+ expect(specFor(type).transcript, type).toBe(wasTranscript(type));+ }+ });++ it('status-pill rendering (isNotifyMessageType)', () => {+ for (const type of PROBE_TYPES) {+ expect(isNotifyMessageType(type), type).toBe(wasNotify(type));+ }+ });++ it('activity-step identity (isActivityMessageType)', () => {+ for (const type of PROBE_TYPES) {+ expect(isActivityMessageType(type), type).toBe(wasActivity(type));+ }+ });++ it('harness input-turn identity (messageSearchRole type branch)', () => {+ for (const type of PROBE_TYPES) {+ // Neutral author/source so the type test alone decides the role.+ const match = { author: 'agent', source: 'agent', type };+ expect(messageSearchRole(match), type).toBe(wasHarnessInputType(type) ? 'automated' : 'agent');+ expect(specFor(type).inputAuthors.includes('harness'), type).toBe(wasHarnessInputType(type));+ }+ });++ it('visible terminal replies (isTerminalAgentMessage), across authors and events', () => {+ const metadataCases: Array<Record<string, unknown> | null | undefined> = [+ undefined,+ null,+ {},+ { event: 'backend_failure' },+ { event: 'activity_completed' },+ { event: 42 },+ ];+ for (const type of PROBE_TYPES) {+ for (const author of ['agent', 'user', 'system', 'harness']) {+ for (const metadata of metadataCases) {+ const message: TerminalCandidate = { author, type, metadata };+ expect(isTerminalAgentMessage(message), `${author}/${type}/${JSON.stringify(metadata)}`).toBe(+ wasTerminalAgentMessage(message),+ );+ }+ }+ }+ });++ it('keeps silent out of the visible-terminal set even though it is terminal', () => {+ // ``silent`` carries ``activityRole: terminal`` for activity bookkeeping but is+ // not transcript-visible, which is why the visible-terminal predicate is the+ // intersection of the two properties rather than the role alone.+ expect(specFor('silent').activityRole).toBe('terminal');+ expect(specFor('silent').transcript).toBe(false);+ expect(isTerminalAgentMessage({ author: 'agent', type: 'silent' })).toBe(false);+ });+});diff --git a/ui/src/lib/messageTypes.ts b/ui/src/lib/messageTypes.tsnew file mode 100644index 000000000..74d0ec304--- /dev/null+++ b/ui/src/lib/messageTypes.ts@@ -0,0 +1,43 @@+// The Web UI half of the message-type policy catalog. This reads the SAME tracked+// file as ``vibe/message_types.py`` — there is deliberately no TypeScript copy of+// the type names or their properties. Vite inlines the JSON at build time, so the+// browser bundle carries the values with no runtime coupling to the Python package.+//+// Property NAMES are derived from the catalog's ``defaults`` block via ``keyof``,+// so renaming a property in the JSON fails ``tsc -b`` at every call site instead of+// silently reading ``undefined``. Value VALIDATION is not repeated here: the Python+// loader is the validating authority for this file (it raises on an unknown property,+// a wrong value kind, or an unsupported enum member) and its tests gate CI.+import catalog from '../../../vibe/message_types.json';++// ``defaults`` declares every public property exactly once, which makes it the+// natural source for the property-name set.+type CatalogDefaults = typeof catalog.defaults;++// Empty JSON arrays infer as ``never[]``; the catalog's list properties are all+// lists of strings, so widen them and freeze everything else as-is.+type SpecValue<T> = T extends readonly unknown[] ? readonly string[] : T;++export type MessageTypeProperty = keyof CatalogDefaults;++export type MessageTypeSpec = {+ readonly [K in MessageTypeProperty]: SpecValue<CatalogDefaults[K]>;+};++const DEFAULT_SPEC: MessageTypeSpec = catalog.defaults;++// Catalog order is the JSON's key order (``Object.entries`` on string keys, then a+// ``Map``), matching the ordering the Python reader relies on.+const TYPE_SPECS: ReadonlyMap<string, MessageTypeSpec> = new Map(+ Object.entries(catalog.types).map(([messageType, overrides]): [string, MessageTypeSpec] => [+ messageType,+ { ...DEFAULT_SPEC, ...overrides },+ ]),+);++/** Resolved spec for *messageType*; unknown types receive the catalog defaults. */+export const specFor = (messageType: string): MessageTypeSpec =>+ TYPE_SPECS.get(messageType) ?? DEFAULT_SPEC;++/** Declared message types in catalog order (the enumeration tests assert against). */+export const messageTypeNames = (): readonly string[] => [...TYPE_SPECS.keys()];diff --git a/ui/vite.config.ts b/ui/vite.config.tsindex d6e73352b..bedac5674 100644--- a/ui/vite.config.ts+++ b/ui/vite.config.ts@@ -36,6 +36,19 @@ export default defineConfig({},},server: {+ fs: {+ // ``src/lib/messageTypes.ts`` imports the repo-root ``vibe/message_types.json``+ // policy catalog so the Web UI and the Python readers share one declaration.+ // ``ui/package-lock.json`` makes Vite infer ``ui/`` as the workspace root, which+ // would put that file outside the dev server's default allow list; production+ // builds inline the JSON and are unaffected. Allow the UI root plus that one+ // file — not their common ancestor, which would serve the rest of the checkout+ // over ``/@fs/`` to anything that can reach the dev server.+ allow: [+ fileURLToPath(new URL('.', import.meta.url)),+ fileURLToPath(new URL('../vibe/message_types.json', import.meta.url)),+ ],+ },proxy: {'/config': backendProxy(),'/session': backendProxy(),