Merge pull request #956 from samcharles93/feat/vue-shadcn-migration

Feat/vue shadcn migration
This commit is contained in:
sam authored and GitHub committed 2026-09-20 23:11:43 +10:00
commit af16b2bb34
518 files changed
+23553 -16388

No files matched your search

+6
View File
@@ -95,6 +95,12 @@ linters:
exclusions:
generated: lax
warn-unused: true
# npm dependencies are not this module's code. `flatted`, pulled in
# transitively by the dashboard toolchain, ships a Go implementation
# alongside its JavaScript, and linting a vendored third-party file fails
# the gate on complexity nobody here can fix.
paths:
- ui/node_modules
presets:
- comments
- std-error-handling
+10 -5
View File
@@ -201,14 +201,19 @@ tasks:
- bash tools/uidist.sh check
test:ui:
desc: Run the dashboard's node tests (DOM-building primitives)
desc: Type-check the dashboard (no unit tests during the Vue migration)
dir: ui
# Without this, a fresh clone fails the gate on a missing jsdom rather
# than a real test failure: ui/node_modules is gitignored and nothing
# else in `task check` installs it.
# The Preact suite was dropped with the Preact app in the shadcn-vue
# migration; tests come back when there is behaviour worth pinning rather
# than a port to re-assert. Until then vue-tsc is the gate that would
# actually catch a broken component, and an empty `npm test` would pass
# vacuously.
#
# ui:deps so a fresh clone fails on a real error rather than on a missing
# node_modules, which is gitignored and installed by nothing else.
deps: [ui:deps]
cmds:
- npm test
- npm run typecheck
dev:
desc: "Develop: archied live-reload + archie-gateway + archie-state-store + archie-ui + Vite HMR together. Open http://localhost:5173"
+1 -1
View File
@@ -89,7 +89,7 @@ was not told about.
### Web UI (chat-render.js, chat-tools.js)
A dashboard_navigate tool call renders as a **clickable chip**: an anchor with
href="#/tasks" and the label. Because the app routes on location.hash, the chip is a
href="/tasks" and the label. The chip is a
real link that works from any page once the chat is a global presence. The chip is
styled as an action, not a code line, so it visibly invites a click.
+114
View File
@@ -0,0 +1,114 @@
# Dashboard navigation groups + Configuration split -- decision
**Status:** Approved for implementation
**Date:** 2026-09-20
**Beads issue:** `archie-core-ocfm`
**Related:** `archie-core-gl96` (Logs absent from the nav -- subsumed here),
`archie-core-ggqo` (Configuration's page width -- moot once it splits)
## Problem
`ui/src/main.jsx` declares eleven navigable routes in one flat bar. Three of
them (Skills, Curators, Channels) are capability-gated and hidden on the
reference deployment, so the eight items normally visible are the best case,
not the worst: a composition that serves every section wraps the bar. Logs is
declared but was never given a nav entry at all, reachable only from a
dashboard link.
The labels compound it. "Event inspector", "Field mappings" and "Playbook
bindings" are three long labels for three faces of one subject, and they sit
beside "Dashboard" and "Tasks" as though they were peers of equal weight.
Configuration is the other half. One route renders roughly ten sections --
update status, work lifecycle, identity, budgets, storage, listen address,
repositories, models and providers, configuration sources, plus the operator
cards rehomed in `archie-core-tf20` -- in a 4021px page with no in-page
navigation. There is no way to send someone to Repositories.
## Decision
Five top-level nav items. Dashboard is a link; the rest are dropdowns.
| Group | Items |
|---|---|
| Dashboard | (link, `/`) |
| Work | Tasks, Workflows |
| Agent | Skills, Curators |
| Events | Inspector, Mappings, Bindings |
| System | Status, Logs, Appearance, Task settings, Models & providers, Repositories, Channels, Advanced |
Items are renamed because the group now carries the context: "Event inspector"
becomes "Inspector" under Events, and so on. A group renders only if at least
one of its children survives capability gating, and a group left with one
child still renders as a dropdown -- a bar whose shape changes per deployment
is harder to learn than one with a predictable skeleton.
### Route map
Configuration dissolves into real routes. Anchors into one long page were
rejected: they leave the 4021px page intact and a deep link lands the reader
mid-scroll with no context above it.
| Was | Becomes | Content |
|---|---|---|
| `/settings` | `/system/status` | Update status, configuration sources, daemon listen address |
| -- | `/system/appearance` | Theme, and the density/motion preferences that follow it |
| `/settings` | `/system/tasks` | Work lifecycle: statuses, operator actions, budgets |
| `/settings` | `/system/models` | Model roles, providers |
| `/settings` | `/system/repos` | Repositories and their per-repo gate overrides |
| `/settings` | `/system/advanced` | Identity, storage and sandboxing, dangerous actions |
| `/captures` | `/captures` | unchanged; label becomes "Inspector" |
| `/mappings` | `/mappings` | unchanged; label becomes "Mappings" |
| `/bindings` | `/bindings` | unchanged; label becomes "Bindings" |
`/settings` is kept as a permanent redirect to `/system/status`. It is the URL
in existing bookmarks, in `dashboardPages` (`internal/gateway/dashboard_tools.go`,
which the chat agent navigates by), and in prior conversation history; breaking
it to save one route entry is not a trade worth making.
`dashboardPages` gains the new routes in the same change. That registry is
guarded by `TestDashboardPagesRegistryCoversEveryRoute`, so a route added here
and forgotten there fails the build -- which is how the deleted `/chat` entry
was caught.
### Dropdown behaviour
Each item carries a one-line description shown as a hover tooltip, using
shadcn-vue's `Tooltip` rather than the `title` attribute, so it is keyboard
reachable on focus and styled with the rest of the menu. Touch gets no tooltip,
so no item may depend on one to be identifiable.
The menu is shadcn-vue's `DropdownMenu` (Reka UI underneath), which already
supplies the roving focus, ArrowDown/ArrowUp movement, Escape-closes-and-
restores-focus, and outside-pointerdown behaviour this would otherwise hand-
roll. It opens on click, never on hover -- hover-opened menus on a control
plane are a misclick away from a destructive page. The trigger keeps
`aria-current` styling when any of its children is the active route, so the bar
still says where you are.
This section was written against the Preact dashboard; the decisions above
survive the Vue migration unchanged, only the primitive supplying them
changed.
### Explicitly not in scope
- No change to what any page renders, beyond which route renders it. The
Configuration split moves sections between files; it does not redesign them.
- `/system/appearance` ships with the theme control moved out of the topbar
icon and nothing else. The density and motion preferences named above are the
reason the page exists as a page rather than a section, not part of this
change.
- Mobile keeps the existing scrollable row of top-level items; groups expand
in place rather than opening a floating menu. Nested floating menus on a
phone are a separate problem.
## Consequences
The bar goes from eleven items to five, and stops depending on capability
gating to fit. Logs gets a home. Configuration becomes six linkable pages, and
`archie-core-ggqo`'s question about its page width answers itself, because no
single page is long enough for the cap to matter.
The cost is a real routing change with redirects to maintain, and a nav that
now needs keyboard and screen-reader behaviour it did not need as a row of
links. Both are paid once.
+102
View File
@@ -0,0 +1,102 @@
# Dashboard port: what the agent delivers
**Status:** Active working agreement
**Date:** 2026-09-20
**Beads:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation)
**Reads with:** `docs/prds/vue-migration-checklist.md` (the item-by-item),
`docs/prds/dashboard-navigation-groups.md` (the approved nav design)
This is the standard the port is held to. The checklist says what to port; this
says how, and what counts as done. It exists because the first attempt ported
the flat topbar verbatim and invented a palette, both of which had already been
decided elsewhere.
## The deliverable
The Preact dashboard, rebuilt in Vue 3 with shadcn-vue, feature complete
against the checklist, gate clean, with `ui/dist` rebuilt and committed in the
same commit as the source it was built from.
## Non-negotiables
- **Vue 3 + shadcn-vue (Reka UI, Tailwind v4, Lucide).** A component that
exists in shadcn-vue is not hand-rolled. Add it with the CLI
(`npx shadcn-vue@latest add <name>`), do not paste it in.
- **History routing.** `createWebHistory`, `base: "/"`. No hash routing.
`src/legacy-hash-redirect.ts` handles old `#/path` links and stays.
- **No test port.** 43 Preact test files are deliberately dropped.
`task test:ui` is a `vue-tsc` typecheck. Write a test when there is a real
failure to pin, not to re-assert a port.
- **Do not downgrade TypeScript.** The target is TS 7 native, not TS 5.
- **`ui/dist` is law.** Never hand-edit it, never omit it, never revert it.
- **`task check` is the gate.** Not an assembled substitute for it.
- **Beads, not markdown TODOs**, for anything that outlives the change.
- **Conventional commits**, scoped `feat(webui):`. Commit gate-clean work
without asking. Do not push without being told.
## Componentisation
One component, one job, one file. A surface is composed from named components,
not assembled inside a single large file. The topbar is the worked example and
the required shape:
```
components/topbar/
Topbar.vue composes the header, owns nothing else
Brand.vue Logo + BrandName, links to /
Logo.vue
BrandName.vue
Nav.vue reads the nav model, renders links and groups
NavTrigger.vue the shared top-level control, link or dropdown trigger
NavGroup.vue one dropdown
NavItem.vue one item inside a dropdown, with its tooltip
SearchBar.vue
SupportLink.vue
ThemeToggle.vue
ProfileDropdown.vue
```
The same rule applies to every page ported after it. If a file is doing the
work of four named things, it is four files. Data and behaviour that more than
one component needs lives in `src/lib/`, not passed down through a chain of
props.
## Ordering
Build the navigation restructure during the port, not after it. Porting the
flat eleven-item bar first and restructuring later means writing the topbar
twice and touching the Go route registry twice. The approved design is five
top-level items (Dashboard, Work, Agent, Events, System), items renamed because
their group carries the context, per-item descriptions shown as hover tooltips,
Configuration split into `/system/*`, `/settings` kept as a redirect, and Logs
finally given a nav entry.
## Design authority
- The approved documents win. Where a document decides something, implement it
rather than re-deciding it.
- **Do not invent a visual direction.** Palette, typography and density are the
maintainer's call. A palette change is its own request, never a side effect
of a port.
- Contrast is AA against every surface the foreground lands on, hover states
included. The corrected values (`--fg-subtle`, the dark
`--primary-foreground`) came from a measured failure and must survive.
- `color-scheme` follows the theme so the UA paints controls, scrollbars and
overscroll to match.
## Code style
Comment the non-obvious why: an invariant, a trap, a measurement, a contract
another file depends on. Do not narrate what the code plainly does, do not
explain a choice that was never in question, and do not write migration phase
history into a diff. That history belongs in the commit message.
## Done, per surface
1. Renders with real data against `task dev`, not just typechecks.
2. Keyboard reachable, focus visible, and the nav announces where you are.
3. Works at 1440x900 and at 720px wide, with nothing clipped and no horizontal
page scroll.
4. Empty, loading, failed and unconfigured (501) states all say something true.
A section that cannot load says so; it does not render blank.
5. `task check` passes, `ui/dist` rebuilt, committed together.
+4 -4
View File
@@ -38,7 +38,7 @@ that has since moved on.
| R5 | Log pane filters by attempt, stage and level; absence stays distinct from an unreadable deployment | `logging.Query.Stage` + `ReadTaskLogRequest.stage = 9`; the pane keeps `disabled` and `found=false` apart |
| R6 | Retry is reachable from the run view and produces a new attempt shown as a new run | Existing retry action, labelled as a NEW run whose confirm states the previous attempt's commits are discarded |
| R7 | Raw JSON of the task record and its events for the selected attempt | `GET /api/tasks/{id}/debug` |
| R8 | Deep-linkable, reload-safe per-task detail page that keeps existing URLs working | `#/tasks/{id}` route beside the existing `#/tasks?task=N` and `#/tasks?status=...` |
| R8 | Deep-linkable, reload-safe per-task detail page that keeps existing URLs working | `/tasks/{id}` route beside the existing `/tasks?task=N` and `/tasks?status=...` |
| R9 | Design polish: hierarchy, tokens, both themes, responsive rail, a11y, loading/empty/error states | UI lane; measured at 480px and 700px in both themes |
| R10 | Documentation of record | This document plus `docs/architecture/observability.md` |
| R11 | Red-first tests for every new behaviour, full gate, `task ui`, forced `go build ./...`, `go test -race` on touched packages | Per lane; the anti-cost-cutting requirement lives here |
@@ -228,8 +228,8 @@ rendering rule, not a caveat in a comment:
## Route and compatibility
`#/tasks/{id}` is the detail route; it is deep-linkable and reload-safe.
`#/tasks?task=N` and `#/tasks?status=...` keep working and keep their existing
`/tasks/{id}` is the detail route; it is deep-linkable and reload-safe.
`/tasks?task=N` and `/tasks?status=...` keep working and keep their existing
behaviour, including the nav highlight. The debug view is why the raw view
exists at all: the task list response is capped, so a client-side join has no
row for an older task, and a debug view that silently hid events would be worse
@@ -282,7 +282,7 @@ than useless.
stating the previous attempt's commits are discarded.
7. The log stage filter narrows to stage-bound lines and the pane states the
coverage limit; `disabled` and `found=false` remain distinguishable.
8. `#/tasks/{id}` survives reload, and `#/tasks?task=N` / `#/tasks?status=...`
8. `/tasks/{id}` survives reload, and `/tasks?task=N` / `/tasks?status=...`
are unchanged.
9. The debug view returns the task record and its unfiltered events, each
carrying `attempt`.
+270
View File
@@ -0,0 +1,270 @@
# Preact → Vue 3 + shadcn-vue migration checklist
**Status:** In progress
**Date:** 2026-09-20
**Bead:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation restructure)
**Bootstrap commit:** `e18fb8b2`
The Preact dashboard was deleted, not ported incrementally. This is the list of
what has to exist again, what must not be lost on the way, and the contracts
that break silently if missed.
Deleted source is recoverable at `git show e18fb8b2^:ui/src/<path>`. Every
claim below was cross-checked against that tree; where a number is a live
measurement rather than something recoverable from git, it says so.
## Invariants that outlive the framework
These are not features; they are things other processes depend on. Breaking one
does not show up as a broken page.
- [ ] **Embed contract.** `ui/embed.go` embeds a committed `ui/dist`. The build
must keep unhashed `assets/index.{js,css}`: dist/ lives in git, and
hashed names orphan a file on every rebuild.
- [ ] **Route registry.** `internal/gateway/dashboard_tools.go` hand-copies the
route table and `TestDashboardPagesRegistryCoversEveryRoute` parses
`ui/src/router/index.ts` to hold them in step. The parser needs
`const routes = [` on its own line, `path: "..."` on a single line per
route, and `nav: false` on any entry the registry should skip. That guard
caught a stale `/chat` entry earlier today.
- [ ] **Mutation headers.** Every POST/PATCH/DELETE must send **both**
`X-Archie-CSRF: 1` and `Content-Type: application/json`. The server
returns 403 without the first and 415 without the second
(`internal/webui/api_tasks.go:376`, `authorizeTaskMutation`). GET sends
neither. This is the single most likely thing to silently break every
write after the port.
- [x] **History routing.** `createWebHistory`, `base: "/"`. Legacy `#/path`
links are rewritten by `src/legacy-hash-redirect.ts`. The chat navigate
chip should emit `/tasks`; the Go side already stores bare paths.
- [ ] **Capability gating.** `GET /api/capabilities`
(`internal/webui/api_capabilities.go:20`) returns a `sections` map of ten
booleans: chat, logs, skills, curators, channels, captures, mappings,
bindings, and workflows/settings which are always true. A route whose
section is false must be hidden, not rendered empty. **Fail open**: on a
failed or null response hide nothing — the old client used a bare
`.catch(() => {})` for exactly this. A page that says "unavailable" is
recoverable; a nav entry that vanished is not.
- [ ] **`LOG_LEVELS`** in `base/log-row.jsx` is a wire contract, not a display
list: the CSV level filter is matched server-side by `splitCSV` in
`internal/webui/api_tasks_logs.go`. A value mismatch breaks filtering
with no error.
- [ ] **SSE lifecycle.** Three streams, all `id: <n>\ndata: <json>\n\n` except
chat which omits the id:
`/events` (task lifecycle, `sse.go:37`, supports `?since=` and
`Last-Event-ID` resume), `/api/logs/stream` (`api_logs.go:80`, same
resume protocol), `/api/chat/stream` (`api_chat.go:399`, frames typed
delta/tool/media/navigate). Each must be closed on unmount or the app
leaks a connection per navigation. Preact used an `archie:teardown`
event; Vue should use `onUnmounted`.
> **On tests.** Per Sam's call, the 43-file suite was not ported and tests
> return when there is behaviour worth pinning. Flagging one exception for when
> that moment comes: the deleted `ui/test/api-client.test.js` classified every
> API method as mutation/read/stream/url and asserted the right headers per
> class. It is the only cheap guard on the CSRF contract above. (It did **not**
> text-scan for a second `fetch()` — that check was deliberately removed
> upstream for testing the file's wording rather than its behaviour.)
## Phase 1 — Foundation
- [x] **Theme.** `css/tokens.css` was a complete two-theme semantic token set
(`--fg-subtle`, `--accent`, `--ok/warn/danger`, surfaces, shadows). Mapped
onto Tailwind v4's `@theme` in `src/style.css`; the second system was not
kept.
- [x] **`color-scheme`.** `[data-theme="dark"] { color-scheme: dark }` and the
light equivalent. Without it the UA paints light scrollbars and light
native controls inside the dark app. Fixed today; trivially lost.
- [x] **Contrast values.** The violet palette moved these off the values pinned
here, so they were recomputed against its own backgrounds instead of
carried: `--fg-subtle` `#A99DBD` dark (7.67:1, AAA) / `#6E6577` light
(4.87:1, AA), and `--fg-muted` `#B9AECB` / `#635B6B` (9.28:1 and 5.70:1).
The invariant the pin existed for holds; the values are the palette's.
- [x] **API client** (`base/api.jsx` → `src/lib/api.ts`). Keep `ApiError`
carrying `status`, and the 401/4xx/5xx classification callers branch on
(`classifyActionError`). `GET /api/bindings/{id}` and
`GET /api/mappings/{id}` exist server-side but were never called — do not
add clients for them without a reason.
- [x] **App shell** — the real source is `main.jsx` (410 lines), not just CSS.
Beyond the topbar and outlet it carries:
- [x] **Jump-to search**: Enter navigates to the first nav label matching the
typed prefix; Escape closes the field and calls `preventDefault` so it
does not also close the chat panel, which has its own Escape handler.
- [x] **`soon: true` nav entries** — greyed, labelled, non-navigable. An
affordance, not dead code.
- [x] **`loadTaskMeta()` at boot**, which re-renders the mounted route once
`/api/task-meta` lands so freeze-dried defaults are replaced.
- [x] **Route keying**: keyed on path + params but deliberately **not** the
query string, so a query-only change (a task-detail tab switch) does
not remount and lose state, while two different `:id`s do get fresh
instances.
- [x] `.shell` has `backdrop-filter`, making it a containing block for
`position: fixed` — the chat launcher must render outside it.
- [ ] **CSS inventory.** `layout.css` was reassessed rather than ported whole.
The command bar is a Vue component styled with Tailwind like every other
surface inside the shell, so it emits none of that file's `.topbar`,
`.nav`, `.topbar-search` or `.icon-btn` classes: only the frame those
rules bounded is kept (`body` canvas, `.shell`, `.main`, and the 900px
collapse), and the topbar/nav rules with their 1500px and 1270px
breakpoints were deleted as unconsumed. The command bar's own responsive
behaviour is the components' business, so "port from this file" applies
to the frame and, later, the chat dock, not to class names. Still to
port, when the pages that use them exist: `card.css`
(`.card`/`.grid-2`/`.grid-4`), `page.css`
(`.page-head`/`.page-title`/`.page-sub`/`.page-actions`), `pill.css` (the
ok/warn/danger/info/idle definitions a Badge port must match), and the
chat dock and morph Phases 3 and 5 describe. `base.css`,
`responsive.css` and `_main.css`'s import order are ported.
- [x] **Theme toggle** and its persistence.
## Phase 2 — Shared primitives
| Was | Is |
|---|---|
| `base/pill.jsx` | `Badge`, with five status variants (`ok`, `warn`, `danger`, `info`, `idle`) over the palette's status tokens |
| `base/statTile.jsx` | `base/StatTile.vue`: full `Card` composition (`CardHeader`, `CardTitle`, `CardDescription`, `CardAction`, `CardContent`), `base/Sparkline.vue`, and the `goodDirection` trend logic |
| `base/icons.jsx` | **Not ported as a module.** Its string-keyed lookup is the pattern shadcn-vue's rules name as wrong, so icons come from `@lucide/vue` at the call site |
| `base/gauge.jsx` | `base/Gauge.vue` and `base/SegmentBar.vue`, both ported. The gauge's `aria-label` announces the rounded percentage, which closes `86au` |
| `base/log-row.jsx` | `base/LogRow.vue` over `lib/log.ts` (`LOG_LEVELS`, `levelKind`, `shortTime`, `fmtValue`) |
| `base/format.jsx` | `lib/format.ts` (`ago`, `compact`) |
| `base/task-meta.jsx` | `lib/task-meta.ts`; Vue's reactivity replaces the manual boot-time re-render the Preact module needed |
Two decisions worth not re-litigating:
- The pill's dot did not come across to `Badge`. The Badge's own shape is the
affordance, and the same variant now covers things that are not status pills
(a trend indicator), where a dot reads as noise.
- The five bespoke glyphs (`dashboard`, `mappings`, `bindings`, `curators`,
`memory`) are not drawn yet because nothing consumes them: the navigation is
text with tooltips. If a page needs one, it becomes its own component at that
point rather than a glyph table waiting for a caller.
- [x] **Copy verbatim.** `dashboard/activity-detail.ts`, `chat/command-scroll.ts`,
`workflows/workflow-rows.ts`, `logs/logs-empty.ts`, and `lib/stream-state.ts`.
- [x] `base/uuid.jsx` → `src/lib/uuid.ts`.
- [x] `routing.jsx` is superseded by vue-router. Not ported.
## Phase 3 — Pages
In dependency order. Each is `git show e18fb8b2^:ui/src/<folder>/`. File counts
verified against the deletion diff.
Ported as named components, not as one file per page: see
`docs/prds/dashboard-port-brief.md#componentisation`. A page file composes and
holds nothing, shared state lives in a module beside it, and a lookup that maps
a string to a component is not written.
- [x] **Dashboard.** Health row, Throughput tiles, Token outlook, Live activity
table, the time-of-day `greeting()`, and the click-through from an
activity row to its task. The setup panel branches on the state machine
rather than on "is setup present", which had shown a 100% checklist where
the complete state belongs.
- [x] **Tasks.** List, filters, row actions, detail page with tab bar, stage
rail, changed files, attempt config, task logs, timeline, debug view.
Both interaction contracts survive: detail `tab`/`attempt` is written with
`router.replace` (never a hash, and replace so a tab click adds no history
entry and does not remount), and the list's reduced-motion-aware
scroll-to-row reveal for deep links. `1q89`'s column priority is applied.
One deliberate deviation: the list's inline timeline expansion is gone,
since the row now opens `/tasks/:id` and that page owns the timeline; the
phone layout's stacked cards are not reproduced and the table scrolls
inside its own container instead.
- [ ] **Chat.** In progress.
- [x] **Configuration**, split into the six `/system/*` routes the approved
design names, with the editable-vs-read-only dual mode intact: this
composition serves a published snapshot, so the pages say they are
read-only rather than rendering controls that cannot work.
- [x] **Logs.** Filters, live tail, pause. A 503 on the stream renders as
"Log stream unavailable" with the reason, not as a permanent
"reconnecting".
- [x] **Event inspector / captures.**
- [x] **Field mappings**, including the mapping editor. Its `mappingPreview`
`capture_id` is a number: the wire type is int64 and a JSON string is
rejected.
- [x] **Playbook bindings**, including the binding editor.
- [x] **Workflows**, keeping the "No stage data yet" state and omitting the
Start-work form when the endpoint serves no definitions (`3tij`).
- [x] **Skills**, **Curators**, **Channels.** Capability-gated and hidden on the
reference deployment, so all three were verified by their own empty state.
Every page was rendered against the running daemon at 1440x900 and 720px, with
no horizontal page scroll at either width.
## Phase 4 — Navigation restructure
Approved in `docs/prds/dashboard-navigation-groups.md`; build it during the
port rather than porting the flat bar first.
- [x] Five top-level items: Dashboard, Work, Agent, Events, System.
- [x] Rename under their group: Inspector, Mappings, Bindings.
- [x] Per-item hover tooltips carrying a one-line description.
- [x] Configuration splits into `/system/{status,appearance,tasks,models,repos,advanced}`.
- [x] `/settings` redirects to `/system/status` — it is in bookmarks and in the
Go route registry.
- [x] Add Logs to the nav. It was never in it.
- [x] Preserve the `soon:` entry treatment.
- [x] The theme control moves off the topbar and onto `/system/appearance`. Two
switches for one preference is two places to look and one of them to be
wrong; `components/topbar/ThemeToggle.vue` is deleted, not orphaned.
- [x] Update `dashboard_tools.go` for every new route in the same change. The
registry already carried all sixteen, so its parity test has been passing
throughout; it is the check that a route cannot be added here and
forgotten there.
## Phase 5 — Behaviour shipped today that a naive port loses
All of this landed in the last few hours and exists only in the deleted tree.
The implementation source for nearly all of it is
`git show e18fb8b2^:ui/src/css/layout.css` plus `main.jsx` and `chat/chat.jsx`.
- [ ] **Chat is a FAB, not a route.** No `/chat`, no nav entry, no topbar icon.
- [ ] **The panel grows out of the launcher**: collapsed to a pill over the
button, expanding with scale, border-radius and position interpolating
together; contents fade in after the shape arrives.
- [ ] **No scrim, no scroll lock.** The page stays readable and clickable.
- [ ] **No close button** — the FAB is the only toggle, and stays visible on
mobile where the panel becomes a sheet.
- [ ] Escape closes the panel **and returns focus to the launcher**; the dock
carries `aria-expanded`/`aria-controls`/`aria-hidden`.
- [ ] Header shows the open conversation's name (`panelTitle`).
- [ ] New chat = `message-circle-plus`, in the header.
- [ ] Slash palette is the only command surface; it floats above the input and
scrolls to keep the arrow-key selection visible.
- [ ] Settings popover closes on outside pointerdown and focus-out.
- [ ] Stop renders only while streaming; composer stays writeable and focused
during a send.
- [ ] Bubbles carry no speaker label.
- [ ] **Topbar cannot clip.** The nav is the only shrinkable region; search
collapses below 1500px; nav wraps below 1270px; sheet mode at 720px;
edge-to-edge at 900px. Previously the utility cluster was unreachable
between 1221px and ~1582px: measured at 1440x900, `.topbar-end` ended at
x=1515 against a shell edge of 1409, so 106px carrying the avatar, theme
toggle and documentation button was clipped with no scroll affordance.
That figure is a live measurement, not recoverable from git.
- [ ] **Live activity detail is clamped** to one line with the full payload on
the title. Unclamped it made the dashboard 7,481px tall.
- [ ] **HEALTH cards take their own height** (`align-items: start`).
- [ ] **Workflow rows merge** definitions with statistics.
- [ ] **Log stream reports `unavailable`** from `readyState`, not a permanent
"reconnecting".
- [ ] **Unconfigured capabilities say so** (501 → "Not configured on this
deployment") rather than rendering nothing.
- [ ] **Operator cards on Configuration**: update install/defer, dangerous
action approvals. Both absent when their endpoint 501s.
## Known-open, carry forward
Open beads against the old UI that the port should satisfy rather than
reintroduce: `1q89` (tasks column priority, wrapping row actions), `to2y`
(three empty-state treatments; Field mappings dead-ends), `gl96` (Logs missing
from nav), `86au` (gauge `aria-label` announces an unrounded percentage),
`6m8r` (mobile KPI cards push content below the fold; 89 sub-44px targets),
`ggqo` (config page width — moot once Configuration splits), `3tij`
(`/api/workflows` serves no definitions, so "Start work" never renders),
`oif3` (Reload Telegram, blocked on `ry4k`).
## Not doing
- Porting the 43 test files. Tests return when there is behaviour worth pinning
rather than a port to re-assert. `task test:ui` is a `vue-tsc` typecheck
meanwhile. See the note under Invariants for the one exception worth
reconsidering first.
+10 -5
View File
@@ -29,15 +29,20 @@ type DashboardPage struct {
var dashboardPages = []DashboardPage{
{Path: "/", Label: "Dashboard", Description: "The control room: what Archie is working on, what needs you, and token spend."},
{Path: "/tasks", Label: "Tasks", Description: "Issues Archie has picked up and where they stand: the work queue."},
{Path: "/logs", Label: "Logs", Description: "The daemon log stream, filterable by level and component."},
{Path: "/workflows", Label: "Workflows", Description: "The routed workflows (bootstrap, implement, tdd, feasibility) and their run history."},
{Path: "/skills", Label: "Skills", Description: "The SKILL.md capabilities Archie can activate."},
{Path: "/curators", Label: "Curators", Description: "The scheduled passes that curate Archie's memory and captures."},
{Path: "/captures", Label: "Event inspector", Description: "Captured inbound events for inspection."},
{Path: "/mappings", Label: "Field mappings", Description: "How inbound event fields map onto internal ones."},
{Path: "/bindings", Label: "Playbook bindings", Description: "How captured events are bound to the workflows they start."},
{Path: "/skills", Label: "Skills", Description: "The SKILL.md capabilities Archie can activate."},
{Path: "/workflows", Label: "Workflows", Description: "The routed workflows (bootstrap, implement, tdd, feasibility) and their run history."},
{Path: "/curators", Label: "Curators", Description: "The scheduled passes that curate Archie's memory and captures."},
{Path: "/logs", Label: "Logs", Description: "The daemon log stream, filterable by level and component."},
{Path: "/channels", Label: "Channels", Description: "Inbound chat and notification channels (e.g. Telegram) and their state."},
{Path: "/settings", Label: "Configuration", Description: "Daemon configuration editable from the dashboard."},
{Path: "/system/status", Label: "Status", Description: "Update state, where the running configuration came from, and the daemon listen address."},
{Path: "/system/appearance", Label: "Appearance", Description: "Dashboard theme and display preferences."},
{Path: "/system/tasks", Label: "Task settings", Description: "Work lifecycle configuration: statuses, operator actions, and budgets."},
{Path: "/system/models", Label: "Models", Description: "Model roles and the providers backing them."},
{Path: "/system/repos", Label: "Repositories", Description: "Repositories Archie watches, and their per-repo gate overrides."},
{Path: "/system/advanced", Label: "Advanced", Description: "Identity, storage and sandboxing, and the dangerous actions."},
}
// DashboardPages returns a copy of the dashboard page registry.
+1 -1
View File
@@ -27,7 +27,7 @@ var routePathRe = regexp.MustCompile(`path:\s*"([^"]+)"`)
// "single source of truth" claim into something a test can hold.
func dashboardRoutesFromSource(t *testing.T) []string {
t.Helper()
path := filepath.Join("..", "..", "ui", "src", "main.jsx")
path := filepath.Join("..", "..", "ui", "src", "router", "index.ts")
src, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
+26
View File
@@ -0,0 +1,26 @@
{
"$schema": "https://shadcn-vue.com/schema.json",
"style": "reka-nova",
"font": "geist-sans",
"typescript": true,
"tailwind": {
"config": "",
"css": "src/style.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"pointer": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"composables": "@/composables"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -1
View File
@@ -1 +1,2 @@
:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#7d8b9e;--accent:#4c8dff;--accent-fg:#0d1014;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#636f82;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.visually-hidden,.sr-only{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{scrollbar-width:none;border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);flex:0 auto;align-items:center;gap:2px;min-width:0;margin:0 auto;padding:3px;display:flex;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);flex:none;display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{bordLine truncated
/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer theme{:root,:host{--font-sans:"Geist Variable", sans-serif;--color-black:#000;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-lg:32rem;--container-2xl:42rem;--container-3xl:48rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--tracking-wide:.025em;--tracking-widest:.1em;--leading-tight:1.25;--leading-snug:1.375;--leading-normal:1.5;--leading-relaxed:1.625;--radius-xs:.125rem;--radius-md:10px;--radius-4xl:2rem;--shadow-md:0 4px 6px -1px #0000001a, 0 2px 4px -2px #0000001a;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2sLine truncated
+19 -9
View File
@@ -1,10 +1,20 @@
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),I(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,ee(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=I(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&ne(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),re(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function M(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function P(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function F(e){return function(n){if(this.l){var r=thLine truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Me=class extends Error{constructor(e,t){super(e),this.status=t}};function Ne(e){let t=e instanceof Me?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Pe(e,t){let n=await fetch(e,t);if(!n.ok)throw new Me(await je(n),n.status);return n}async function G(e,{method:t=`GET`,body:n,timeoutMs:r=ke,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await Pe(e,o);return i?s.json():void 0}var K={summary:()=>G(`/api/summary`),tasks:()=>G(`/api/tasks`),taskMeta:()=>G(`/api/task-meta`),task:e=>G(`/api/tasks/${e}`),taskAttempts:e=>G(`/api/tasks/${e}/attempts`),taskChanges:(e,t)=>G(`/api/tasks/${e}/changes`+Ae(t)),taskDebug:(e,t)=>G(`/api/tasks/${e}/debug`+Ae(t)),taskAction:(e,t)=>G(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>G(`/api/setup`),capabilities:()=>G(`/api/capabilities`),workflows:()=>G(`/api/workflows`),workRequest:e=>G(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>G(`/api/skills`),channels:()=>G(`/api/channels`),curators:()=>G(`/api/curators`),channelReload:e=>G(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>G(`/api/config`),version:()=>G(`/api/version`),configUpdate:e=>G(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>G(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>G(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>G(`/api/logs`+Ae(e)),taskLogs:(e,t)=>G(`/api/tasks/${e}/logs`+Ae(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>G(`/api/captures`+Ae({limit:e})),mappings:()=>G(`/api/mappings`),mappingCreate:e=>G(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>G(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>G(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>G(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>G(`/api/bindings`),bindingCreate:e=>G(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>G(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>G(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>G(`/api/bindings/${e}/approve`,{method:`POST`}),chatSessions:()=>G(`/api/chat/sessions`),chatMessages:e=>G(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>G(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>G(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>G(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:De(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>G(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>G(`/api/chat/update`),chatUpdateDefer:e=>G(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>G(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>G(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>G(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>G(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>Pe(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function Fe(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Ie(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Oe(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Le(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var Re=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],ze=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? TLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>rt?`${n.slice(0,rt).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}function Z({text:e,kind:t=`idle`}){return q(`span`,{className:`pill pill-${t}`,children:e})}var at=`archie.setup-complete.dismissed.v1`;function ot(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(at),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function st(e=globalThis.localStorage){e?.setItem?.(at,`1`)}var ct=new Set([`waiting_human`,`parked`]);function lt(e=[]){let t=e.filter(e=>ct.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function ut({title:e,detail:t}){return q(`div`,{className:`empty`,children:[q(`div`,{className:`empty-title`,children:e}),t&&q(`div`,{children:t})]})}function dt(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function ft(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function pt(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function mt(){let[e,t]=H([]),[n,r]=H(`connecting`),[i,a]=H(`idle`),[o,s]=H(new Map),[c,l]=H(null),[u,d]=H(null),[f,p]=H(null),[m,h]=H(null),[g,_]=H(null),[,v]=H(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([K.summary(),K.setup().catch(()=>null),K.workflows().catch(()=>null),K.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};U(()=>(y(),Fe(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{st(),v(e=>!e)},x=u?.operator?`${ft()}, ${u.operator}`:ft(),C=null;if(g)C=q(`button`,{className:`btn btn-primary`,onClick:y,children:[q(J,{name:`refresh`,size:15}),` Retry`]});else if(m!==null){let e=lt(m),t=e.attention.count,n=e.running.count;C=q(S,{children:[t>0&&q(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[q(J,{name:`tasks`,size:15}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&q(`a`,{className:`btn`,href:e.running.href,children:[q(J,{name:`workflows`,size:15}),` `,n,` running`]}),q(`a`,{className:`btn`,href:`#/logs`,children:[q(J,{name:`logs`,size:15}),` Logs`]}),q(`button`,{className:`btn btn-primary`,onClick:y,children:[q(J,{name:`refresh`,size:15}),` Refresh`]})]})}let w=null;if(g)w=q(`div`,{className:`card`,children:q(ut,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=q(S,{children:[q(X,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),q(X,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),q(X,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),q(X,{label:`Tokens used`,value:$e(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:pt(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=ot(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=q(`div`,{className:`card setup`,children:[q(`div`,{className:`card-head`,children:[q(`div`,{children:[q(`h2`,{className:`card-title`,children:`Finish setting up`}),q(`p`,{className:`card-sub`,children:`Archie needs these before it can work on its own.`})]}),q(`span`,{className:`setup-pct`,children:[t,`%`]})]}),q(`div`,{className:`setup-bar`,children:q(`div`,{className:`setup-bar-fill`,style:{width:`${t}%`}})}),q(`ul`,{className:`setup-list`,children:u.steps.map((e,t)=>q(`li`,{className:`setup-step ${e.done?`done`:``}`,children:[q(`span`,{className:`setup-check`,children:e.done?q(J,{name:`check`,size:12}):``}),q(`div`,{children:[q(`div`,{className:`setup-step-title`,children:e.title}),e.detail&&q(`div`,{className:`setup-step-detail`,children:e.detail})]})]},t))})]})}else T=q(`div`,{className:`card setup setup-done`,children:q(`div`,{className:`card-head`,children:[q(`div`,{children:[q(`h2`,{className:`card-title`,children:`Setup complete`}),q(`p`,{className:`card-sub`,children:`Archie is configured and ready to work.`})]}),q(`div`,{className:`setup-complete-actions`,children:[q(`span`,{className:`setup-pct`,children:q(J,{name:`check`,size:16})}),q(`button`,{className:`icon-btn setup-dismiss`,type:`Line truncated
`),children:[q(`td`,{className:`strong`,children:e.label||e.id}),q(`td`,{className:`mono`,children:e.install_type||`—`}),q(`td`,{className:`mono`,children:e.running_version||`—`}),q(`td`,{className:`mono`,children:e.latest_available||`—`}),q(`td`,{children:q(Z,{text:er[e.status]||e.status,kind:tr[e.status]||`idle`})})]},e.id||e.label))})]})})})}function rr({title:e,sub:t,children:n}){return q(`div`,{className:`card cfg-section`,children:[q(`div`,{className:`card-head`,children:q(`div`,{children:[q(`h2`,{className:`card-title`,children:e}),q(`p`,{className:`card-sub`,children:t})]})}),n]})}function ir(e){return e?.error?e.error:e?.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`}function ar({data:e,onDefer:t,onInstall:n}){let r=e?.available||[];return r.length?q(rr,{title:`Updates`,sub:`Whether a newer release is available, and what to do about it.`,children:[q(`p`,{className:`cfg-note`,children:r.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)}),q(`div`,{className:`cfg-actions`,children:[q(`button`,{className:`btn`,type:`button`,onClick:()=>t?.(e.snapshot),children:`Defer`}),e.can_install&&q(`button`,{className:`btn btn-primary`,type:`button`,onClick:()=>n?.(e.snapshot),children:`Install update`})]})]}):q(rr,{title:`Updates`,sub:`Whether a newer release is available, and what to do about it.`,children:q(`p`,{className:`cfg-note`,children:ir(e)})})}var or=e=>e.Number??e.number,sr=e=>e.Label??e.label??`checkpoint`;function cr({data:e,onRequest:t,onDecide:n}){let[r,i]=H(``),[a,o]=H(``);if(e?.error)return q(rr,{title:`Dangerous actions`,sub:`Actions that need explicit approval before they run.`,children:q(`p`,{className:`cfg-note`,children:e.error})});let s=e?.pending||[];return q(rr,{title:`Dangerous actions`,sub:`Actions that need explicit approval before they run. Requesting one only queues it.`,children:[q(`div`,{className:`cfg-request-row`,children:[q(`select`,{"aria-label":`Checkpoint`,value:r,onChange:e=>i(e.target.value),children:[q(`option`,{value:``,children:`Select checkpoint`}),(e?.checkpoints||[]).map(e=>q(`option`,{value:String(or(e)),children:[or(e),` — `,sr(e)]},or(e)))]}),q(`button`,{className:`btn`,type:`button`,disabled:!r,onClick:()=>t?.(`rollback`,r),children:`Request rollback`})]}),q(`div`,{className:`cfg-request-row`,children:[q(`input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`,value:a,onInput:e=>o(e.target.value)}),q(`button`,{className:`btn`,type:`button`,disabled:!a.trim(),onClick:()=>t?.(`stop`,a),children:`Request stop`})]}),s.length?q(S,{children:s.map(e=>q(`div`,{className:`cfg-pending`,children:[q(`span`,{children:e.description}),q(`div`,{className:`cfg-actions`,children:[q(`button`,{className:`btn`,type:`button`,onClick:()=>n?.(e.id,`approve`),children:`Approve`}),q(`button`,{className:`btn`,type:`button`,onClick:()=>n?.(e.id,`permanent`),children:`Approve for 24h`}),q(`button`,{className:`btn`,type:`button`,onClick:()=>n?.(e.id,`deny`),children:`Deny`})]})]},e.id))}):q(`p`,{className:`cfg-note`,children:`No pending dangerous actions.`})]})}function Q({title:e,detail:t}){return q(`div`,{className:`empty`,children:[q(`div`,{className:`empty-title`,children:e}),t&&q(`div`,{children:t})]})}function $({title:e,sub:t,children:n}){return q(`div`,{className:`card cfg-section`,children:[q(`div`,{className:`card-head`,children:q(`div`,{children:[q(`h2`,{className:`card-title`,children:e}),q(`p`,{className:`card-sub`,children:t})]})}),n]})}function lr({origins:e}){return e?.length?q($,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:q(`div`,{className:`kv-list`,children:e.map((e,t)=>q(Xn,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):q($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:q(Q,{title:`Source provenance is unavailable.`})})}function ur(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function dr({data:e,error:t}){if(t)return q($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:q(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return q($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[q(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?q(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??Ke(e.id),n=e.kind??qe(e.id);return q(`div`,{className:`kv`,children:[q(`span`,{className:`kv-label`,children:e.id}),q(`span`,{className:`kv-value`,children:q(Z,{text:t,kind:n})})]},e.id)})}):q(Q,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),q(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?q(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=ur(e.kind);return q(`div`, Line truncated
`),i=[],a=null,o=null,s=0,c=()=>{i.length&&(n.push(q(`p`,{children:Qr(i.join(` `))},s++)),i=[])},l=()=>{if(!a)return;let e=a.items.map((e,t)=>q(`li`,{children:Qr(e)},t));n.push(a.tag===`ol`?q(`ol`,{children:e},s++):q(`ul`,{children:e},s++)),a=null};for(let e=0;e<r.length;e++){let t=r[e];if(t.startsWith("```")){c(),l(),o?(n.push(q(`pre`,{children:q(`code`,{children:o.join(`
`)})},s++)),o=null):o=[];continue}if(o){o.push(t);continue}let u=ei(t),d=e+1<r.length?ei(r[e+1]):null;if(u&&d&&ti(d)&&u.length===d.length){c(),l();let t=[];for(e+=2;e<r.length;e++){let n=ei(r[e]);if(!n||n.length!==u.length){e--;break}t.push(n)}n.push(q(`table`,{children:[q(`thead`,{children:q(`tr`,{children:u.map((e,t)=>q(`th`,{children:Qr(e)},t))})}),q(`tbody`,{children:t.map((e,t)=>q(`tr`,{children:e.map((e,t)=>q(`td`,{children:Qr(e)},t))},t))})]},s++));continue}if(!t.trim()){c(),l();continue}let f=t.match(/^(#{1,3})\s+(.+)$/);if(f){c(),l();let e=`h${f[1].length}`;n.push(q(e,{children:Qr(f[2])},s++));continue}let p=t.match(/^\s*[-*]\s+(.+)$/),m=t.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){c();let e=m?`ol`:`ul`;(!a||a.tag!==e)&&(l(),a={tag:e,items:[]}),a.items.push((p||m)[1]);continue}if(t.startsWith(`>`)){c(),l(),n.push(q(`blockquote`,{children:Qr(t.replace(/^>\s?/,``))},s++));continue}i.push(t)}return c(),l(),o&&n.push(q(`pre`,{children:q(`code`,{children:o.join(`
`)})},s++)),q(`div`,{className:t,children:n})}function ei(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function ti(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var ni=`archie.web.chat.channel`;function ri(){let e=localStorage.getItem(ni);return e||(e=De(),localStorage.setItem(ni,e)),e}function ii(e){return{text:e,sourceID:De()}}function ai(e){return{...e}}function oi(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?ai(e.turn):ii(r),isRetry:n}}function si({scrollTop:e,viewportHeight:t,optionTop:n,optionHeight:r}){if(r>=t||n<e)return n;let i=n+r;return i>e+t?i-t:e}function ci(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function li(e,t){if(!t)return`Archie`;let n=(e||[]).find(e=>e.session_id===t);return n?ci(n):`Archie`}function ui(){return location.hash.slice(1)||`/`}function di({open:e=!0}){let[t,n]=H([]),[r,i]=H(``),[a,o]=H([]),[s,c]=H(``),[l,u]=H(`Ready`),[d,f]=H(!1),[p,m]=H({}),[h,g]=H(``),[_,v]=H(``),[y,b]=H(``),[x,C]=H([]),[w,T]=H([]),[E,D]=H(0),[O,k]=H(!1),[A,j]=H(null),M=W(null),N=W(null),P=W(null),F=W(null),I=W(null),L=W(null),ee=W(d);ee.current=d,U(()=>{let e=e=>{let t=L.current;t?.open&&(e.target instanceof Node&&t.contains(e.target)||(t.open=!1))};return document.addEventListener(`pointerdown`,e),document.addEventListener(`focusin`,e),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`focusin`,e)}},[]),U(()=>{e&&N.current?.focus()},[e]),U(()=>{if(!O)return;let e=I.current,t=e?.children?.[E];!e||!t||(e.scrollTop=si({scrollTop:e.scrollTop,viewportHeight:e.clientHeight,optionTop:t.offsetTop,optionHeight:t.offsetHeight}))},[E,O]),U(()=>{M.current&&(M.current.scrollTop=M.current.scrollHeight)},[a,A]),U(()=>{R().catch(e=>{u(e.message||`Chat unavailable`)});let e=()=>{P.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),P.current?.abort()}},[]);async function R(){let e=await K.chatSessions(),t=e.sessions||[];n(t),m(e),g(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;v(a),b(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);C(o),!r&&t[0]&&await te(t[0].session_id,e,t)}async function te(e,t,n){let r=t||p;i(e),o([]),j(null);let a=r.active_personas?.[e]||r.active_persona||``;g(a);try{await K.chatMessage(ri(),`/resume ${e}`);let[t,n]=await Promise.all([K.chatMessages(e),K.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});o(i)}catch(e){u(e.message||`Could not load session messages`)}}async function ne(e){if(r)try{u(`Working…`);let t=await K.chatMessage(ri(),e);t.session_id&&i(t.session_id),u(t.reply||`Session updated`),await R(),(t.session_id||r)&&await te(t.session_id||r),F.current&&(F.current.open=!1)}catch(e){u(e.message||`Session action failed`)}}function re(e,t){let n=window.prompt(t);n?.trim()&&ne(`${e} ${n.trim()}`)}function ie(e){let t=e.target.value;g(t),!(!r||!t)&&K.chatPersona(r,t).then(()=>{m(e=>({...e,active_personas:{...e.active_personas||{},[r]:t}})),u(`Personality: ${t}`)}).catch(e=>{u(e.message||`Failed to set personality`)})}async function ae(e){let t=e.target.value;if(v(t),t)try{let e=await K.chatMessage(ri(),`/model --provider ${t}`);u(e.reply||`Provider updated`),await R()}catch(e){u(`Provider update failed: ${e.message||e}`)}}async function z(e){let t=e.target.value;if(b(t),t)try{let e=await K.chatMessage(ri(),`/model ${t}`);u(e.reply||`Model updated`),await R()}catch(e){u(`Model update failed: ${e.message||e}`)}}function B(){c(`/new`),le({textOverride:`/new`})}function oe(e){let t=e.target.value;c(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=x.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){T(t),D(0),k(!0);return}}k(!1),T([])}function se(e){let t=w[e];if(!t||!N.current)return;let n=N.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),s=`${r.slice(0,o)}${t.command} ${i}`;c(s),k(!1);let l=o+t.command.length+1;setTimeout(()=>{n.focus(),n.setSelectionRange(l,l)},0)}function ce(e){if(O&&w.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&w.some(e=>e.command===s.trim())){e.preventDefault(),k(!1),le();return}if(e.key===`ArrowDown`){e.preventDefault(),D(e=>(e+1)%w.length);return}if(e.key===`ArrowUp`){e.preventDefault(),D(e=>(e+w.length-1)%w.length);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),se(E);return}if(e.key===`Escape`){e.preventDefault(),k(!1); Line truncated
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=window.location.hash;if(n.startsWith(`#/`)){let e=n.slice(1);window.history.replaceState(null,``,e+window.location.search)}function r(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var i={},a=[],o=()=>{},s=()=>!1,c=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),l=e=>e.startsWith(`onUpdate:`),u=Object.assign,d=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},f=Object.prototype.hasOwnProperty,p=(e,t)=>f.call(e,t),m=Array.isArray,h=e=>ee(e)===`[object Map]`,g=e=>ee(e)===`[object Set]`,_=e=>ee(e)===`[object Date]`,v=e=>ee(e)===`[object RegExp]`,y=e=>typeof e==`function`,b=e=>typeof e==`string`,x=e=>typeof e==`symbol`,S=e=>typeof e==`object`&&!!e,C=e=>(S(e)||y(e))&&y(e.then)&&y(e.catch),w=Object.prototype.toString,ee=e=>w.call(e),te=e=>ee(e).slice(8,-1),ne=e=>ee(e)===`[object Object]`,re=e=>b(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ie=r(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),ae=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},oe=/-\w/g,se=ae(e=>e.replace(oe,e=>e.slice(1).toUpperCase())),ce=/\B([A-Z])/g,le=ae(e=>e.replace(ce,`-$1`).toLowerCase()),ue=ae(e=>e.charAt(0).toUpperCase()+e.slice(1)),T=ae(e=>e?`on${ue(e)}`:``),de=(e,t)=>!Object.is(e,t),fe=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},pe=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},me=e=>{let t=parseFloat(e);return isNaN(t)?e:t},he=e=>{let t=b(e)?Number(e):NaN;return isNaN(t)?e:t},ge,_e=()=>ge||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ve=r(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function ye(e){if(m(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=b(r)?Ce(r):ye(r);if(i)for(let e in i)t[e]=i[e]}return t}if(b(e)||S(e))return e}var be=/;(?![^(]*\))/g,xe=/:([^]+)/,Se=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function Ce(e){let t={};return e.replace(Se,e=>e.startsWith(`/*`)?``:e).split(be).forEach(e=>{if(e){let n=e.split(xe);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function E(e){let t=``;if(b(e))t=e;else if(m(e))for(let n=0;n<e.length;n++){let r=E(e[n]);r&&(t+=r+` `)}else if(S(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function we(e){if(!e)return null;let{class:t,style:n}=e;return t&&!b(t)&&(e.class=E(t)),n&&(e.style=ye(n)),e}var Te=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Ee=r(Te);Te+``;function De(e){return!!e||e===``}function Oe(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=Me(e[i],t[i],n);return r}function ke(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&Me(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Ae(e,t,n){let r=h(e),i=h(t);if(r||i||(r=g(e),i=g(t),r||i))return r&&i?ke(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=e.hasOwnProperty(r),a=t.hasOwnProperty(r);if(i&&!a||!i&&a||!Me(e[r],t[r],n))return!1}return String(e)===String(t)}function je(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function Me(e,t,n){if(e===t)return!0;let r=_(e),i=_(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=x(e),i=x(t),r||i?e===t:(r=m(e),i=m(t),r||i?r&&i?je(e,t,n,Oe):!1:(r=S(e),i=S(t),r||i?!r||!i?!1:je(e,t,n,Ae):String(e)===String(t))))}function Ne(e,t){return e.findIndex(e=>Me(e,t))}var Pe=e=>!!(e&&e.__v_isRef===!0),D=e=>b(e)?e:e==null?``:m(e)||S(e)&&(e.toString===w||!y(e.toString))?Pe(e)?D(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):h(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:g(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}Line truncated
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||c(a)&&!ie(a)||a[0]===`.`||t&&!ie(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ps(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&us(()=>{x&&Ps(x,n,t),l&&g.enter(e),h&&Tr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=js(d[t]),g=h.type===ps;e?(g&&!u&&t+1<p&&js(d[t+1]).type===ps&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,Ai(r,1)||bi()),n(null,h,r,null,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)s(n);else break}}let u=a(e),d=o(e);return s(e),n(null,t,d,u,r,i,Ci(d),c),r&&(r.vnode.el=t.el,Co(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=_e().requestIdleCallback||(e=>setTimeout(e,1)),Ii=_e().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Ri(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{b(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){y(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return M({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Rs;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Zn(t,e,13,!r)};if(s&&e.suspense||Gs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?B(r,{error:e}):null));let a=O(!1),c=O(),d=O(!!i),f,m;return ca(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Ki(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Gi(u,e);if(c.value&&r)return B(r,{error:c.value});if(n&& Line truncated
`))),e[Kl]=Ul(i);let a=r||i.props&&i.props.type===`number`;ul(e,t?`change`:`input`,t=>{t.target.composing||e[Kl](Jl(e.value,n,a))}),(n||a)&&ul(e,`change`,()=>{e.value=Jl(e.value,n,a)}),t||(ul(e,`compositionstart`,Wl),ul(e,`compositionend`,Gl),ul(e,`change`,Gl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[ql];delete e[ql],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Kl](Jl(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Kl]=Ul(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?me(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Xl={deep:!0,created(e,t,n){e[Kl]=Ul(n),ul(e,`change`,()=>{let t=e._modelValue,n=nu(e),r=e.checked,i=e[Kl];if(m(t)){let e=Ne(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(ru(e,r))})},mounted:Zl,beforeUpdate(e,t,n){e[Kl]=Ul(n),Zl(e,t,n)}};function Zl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Ne(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=Me(t,ru(e,!0))}e.checked!==i&&(e.checked=i)}var Ql={created(e,{value:t},n){e.checked=Me(t,n.props.value),e[Kl]=Ul(n),ul(e,`change`,()=>{e[Kl](nu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Kl]=Ul(r),t!==n&&(e.checked=Me(t,r.props.value))}},$l={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ul(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?me(nu(e)):nu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Kl](i)}finally{or(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Kl]=Ul(r)},mounted(e,{value:t}){tu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Kl]=Ul(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!eu(t,n[1],n[0]))&&tu(e,t)}};function eu(e,t,n){if(!n||m(e))return Me(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function tu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=nu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Ne(t,o)>-1}else a.selected=t.has(o)}else if(Me(nu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function nu(e){return`_value`in e?e._value:e.value}function ru(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var iu={created(e,t,n){ou(e,t,n,null,`created`)},mounted(e,t,n){ou(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){ou(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){ou(e,t,n,r,`updated`)}};function au(e,t){switch(e){case`SELECT`:return $l;case`TEXTAREA`:return Yl;default:switch(t){case`checkbox`:return Xl;case`radio`:return Ql;default:return Yl}}}function ou(e,t,n,r,i){let a=au(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function su(){Yl.getSSRProps=({value:e})=>({value:e}),Ql.getSSRProps=({value:e},t)=>{if(t.props&&Me(t.props.value,e))return{checked:!0}},Xl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},iu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=au(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var cu=[`ctrl`,`shift`,`alt`,`meta`],lu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>cu.some(n=>e[`${n}Key`]&&!t.includes(n))},uu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=lu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},du={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},fu=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=le(n.key);if(t.some(e=>e===r||du[e]===r))return e(n)}))},pu=u({patchProp:Sl},Sc),mu,hu=!1;function gu(){return mu||=Uo(pu)}function _u(){return mu=hu?mu:Wo(pu),hu=!0,mu}var vu=((...e)=>{gu().render(...e)}),yu=((...e)=>{_u().hydrate(...e)}),bu=((...e)=>{let t=gu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Cu(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,Su(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),xu=(( Line truncated
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Jf=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Yf(e){let t=e instanceof Jf?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Xf(e,t){let n=await fetch(e,t);if(!n.ok)throw new Jf(await qf(n),n.status);return n}async function Zf(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Gf,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Xf(e,s);return a?await c.json():void 0}var J={summary:()=>Zf(`/api/summary`),tasks:()=>Zf(`/api/tasks`),taskMeta:()=>Zf(`/api/task-meta`),task:e=>Zf(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Zf(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Zf(`/api/tasks/${encodeURIComponent(e)}/changes`+Kf(t)),taskDebug:(e,t)=>Zf(`/api/tasks/${encodeURIComponent(e)}/debug`+Kf(t)),taskAction:(e,t)=>Zf(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Zf(`/api/setup`),capabilities:()=>Zf(`/api/capabilities`),workflows:()=>Zf(`/api/workflows`),workRequest:e=>Zf(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Zf(`/api/skills`),channels:()=>Zf(`/api/channels`),curators:()=>Zf(`/api/curators`),channelReload:e=>Zf(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Zf(`/api/config`),version:()=>Zf(`/api/version`),configUpdate:e=>Zf(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>Zf(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>Zf(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>Zf(`/api/logs`+Kf(e)),taskLogs:(e,t)=>Zf(`/api/tasks/${encodeURIComponent(e)}/logs`+Kf(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>Zf(`/api/captures`+Kf({limit:e})),mappings:()=>Zf(`/api/mappings`),mappingCreate:e=>Zf(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Zf(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Zf(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Zf(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Zf(`/api/bindings`),bindingCreate:e=>Zf(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Zf(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Zf(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Zf(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Zf(`/api/chat/sessions`),chatMessages:e=>Zf(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Zf(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Zf(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Zf(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Wf(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Zf(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>Zf(`/api/chat/update`),chatUpdateDefer:e=>Zf(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>Zf(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>Zf(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Zf(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Zf(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Xf(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Qf(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function $f(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Uf(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var ep=`archie.web.chat.channel`;function tp(){let e=localStorage.getItem(ep);return e||(e=Wf(),localStorage.setItem(ep,e)),e}var np=/(?:^|\s)\/([^\s]*)$/,rp=/(?:^|\s)\/[^\s]*$/,ip=8;function ap(e,t,n){let r=t.slice(0,n).match(np);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,ip)}function op(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(rp),o=a<0?r.length:a+ +(r[a]===` `);return{text:`${r.slice(0,o)}$Line truncated
`);a=o.pop()||``;for(let e of o){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&i(n.session_id),n.type===`delta`&&(d+=n.text,j(e=>e?{...e,text:d}:null)),n.type===`tool`&&(l=[...l,n],j(e=>e?{...e,tools:l}:null)),n.type===`navigate`&&(l=[...l,n],j(e=>e?{...e,tools:l}:null)),n.type===`done`&&(p=!0,d||=n.text),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);o(e=>[...e,{from:`assistant`,text:d,tool_calls:l}]),j(null),u(`Ready`),await R()}catch(e){if(e.name===`AbortError`&&!m)j({text:`Turn stopped.`,tools:l,isError:!1,turn:r,isRetry:a}),u(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;j({text:t,tools:l,isError:!0,turn:ai(r),isRetry:a}),u(`Error — retry available`)}}finally{clearTimeout(h),P.current=null,f(!1),N.current&&N.current.focus()}}function V(){u(`Stopping…`),r&&K.chatCancel(r).catch(()=>{}),P.current?.abort()}let ue=p.models_by_provider||{},de=_&&ue[_]?ue[_]:p.models||[];return q(`div`,{className:`chat-panel-content`,children:[q(`div`,{className:`chat-drawer-head`,children:[q(`strong`,{className:`chat-panel-title`,children:li(t,r)}),q(`div`,{className:`chat-head-actions`,children:q(`button`,{className:`icon-btn chat-new`,type:`button`,title:`New chat`,"aria-label":`New chat`,onClick:B,children:q(J,{name:`message-circle-plus`})})})]}),q(`div`,{className:`chat-bar`,children:[q(`label`,{className:`chat-session-switch`,children:[q(`span`,{className:`sr-only`,children:`Conversation`}),q(`select`,{value:r,onChange:e=>te(e.target.value),disabled:!t.length,children:t.length?t.map(e=>q(`option`,{value:e.session_id,children:ci(e)},e.session_id)):q(`option`,{value:``,children:`No conversations yet`})})]}),q(`details`,{className:`chat-settings`,ref:L,children:[q(`summary`,{"aria-label":`Chat settings`,title:`Chat settings`,children:q(`span`,{"aria-hidden":`true`,children:`⚙`})}),q(`div`,{className:`chat-settings-body`,children:[q(`span`,{className:`chat-status`,children:l}),q(`label`,{children:[`Personality`,q(`select`,{className:`chat-select`,"aria-label":`Personality`,value:h,onChange:ie,children:[q(`option`,{value:``,children:`Default`}),(p.personas||[]).map(e=>q(`option`,{value:e,children:e},e))]})]}),(p.providers||[]).length>0&&q(`label`,{children:[`Provider`,q(`select`,{className:`chat-select`,"aria-label":`Provider`,value:_,onChange:ae,children:[q(`option`,{value:``,children:`Default`}),(p.providers||[]).map(e=>q(`option`,{value:e,children:e},e))]})]}),q(`label`,{children:[`Model`,q(`select`,{className:`chat-select`,"aria-label":`Model`,value:y,onChange:z,children:[q(`option`,{value:``,children:`Default`}),de.map(e=>q(`option`,{value:e,children:e},e))]})]})]})]})]}),q(`div`,{className:`chat-layout`,children:q(`section`,{className:`chat-workspace`,children:[q(`div`,{className:`chat-workspace-head`,children:q(`details`,{className:`chat-session-tools`,ref:F,hidden:!r,children:[q(`summary`,{children:`Session actions`}),q(`div`,{className:`chat-session-tool-list`,children:[q(`button`,{className:`btn`,type:`button`,onClick:()=>ne(`/retry`),children:`Retry`}),q(`button`,{className:`btn`,type:`button`,onClick:()=>ne(`/undo`),children:`Undo`}),q(`button`,{className:`btn`,type:`button`,onClick:()=>re(`/title`,`Session title`),children:`Rename`}),q(`button`,{className:`btn`,type:`button`,onClick:()=>re(`/branch`,`Branch name (optional)`),children:`Branch`}),q(`button`,{className:`btn`,type:`button`,onClick:()=>ne(`/compress --preview`),children:`Preview compression`})]})]})}),q(`div`,{className:`chat-transcript`,ref:M,children:!a.length&&!A?q(`div`,{className:`chat-empty-state`,children:[q(`span`,{className:`chat-empty-mark`,children:`A`}),q(`h2`,{children:`What are we working on?`}),q(`p`,{children:`Ask Archie anything, or start with one of these prompts.`}),q(`div`,{className:`chat-prompt-grid`,children:[q(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{c(`Summarise active tasks`),N.current?.focus()},children:`Summarise active tasks`}),q(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{c(`Show running agents`),N.current?.focus()},children:`Show running agents`}),q(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{c(`Check system status`),N.current?.focus()},children:`Check system status`})]})]}):q(S,{children:[a.map((e,t)=>{let n=e.from??e.From??``,r=e.text??e.Text??``,i=n!==`web`,a=e.tool_calls||e.ToolCalls||[];return q(`div`,{className:`chat-bubble-row ${i?`assistant`:`user`}`,children:q(`div`,{className:`chat-bubble`,children:i?q(S,{children:[a.length>0&&q(`div`,{className:`chat-tools`,children:a.map((e,t)=>{if(e.path)return q(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[q(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),q(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.Name||e.tool||`tool`,r=e.parameters||e.Parameters||``,i=e.summary||e.Summary||e.text||e.err||e.Err Line truncated
`);u=r.pop()||``;for(let e of r){let t=e.split(`
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(mp.value=n.session_id),n.type===`delta`&&(o+=n.text,yp.value=yp.value?{...yp.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],yp.value=yp.value?{...yp.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);hp.value=[...hp.value,{from:`assistant`,text:o,tool_calls:a}],yp.value=null,_p.value=`Ready`,await Pp()}catch(e){let t=e;t.name===`AbortError`&&!c?(yp.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},_p.value=`Stopped`):(yp.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?lp(r):void 0,isRetry:i},_p.value=`Error — retry available`)}finally{clearTimeout(l),Mp=null,vp.value=!1}}function qp(){_p.value=`Stopping…`,mp.value&&J.chatCancel(mp.value).catch(()=>{}),Np()}function Jp(){ia(()=>{Pp().catch(e=>{_p.value=e.message||`Chat unavailable`})}),ca(()=>{Np()})}var Yp=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Xp=M({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return q(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(I(),L(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":k(dp),onClick:i[0]||=e=>n(`toggle`)},[z(`span`,{"aria-hidden":`true`,class:E(r(!e.open))},[B(k(Qu),{size:22})],2),z(`span`,{"aria-hidden":`true`,class:E(r(e.open))},[B(k(pd),{size:22})],2)],8,Yp))}});function Zp(e){return typeof e==`string`?`'${e}'`:new tm().serialize(e)}var Qp=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,$p=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Qp.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function em(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&$p[n]?$p[n]:n+128,s=a<128&&$p[a]?$p[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var tm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?em(e,t):n===`number`&&r===`number`?e-t:em(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(em),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
`)].join(`
`))}return()=>i.value||r.value||o.value?ac(t.default({present:o.value})[0],{ref:e=>{let t=Pm(e);return t?.hasAttribute===void 0||(t?.hasAttribute(`data-reka-popper-content-wrapper`)?a.value=t.firstElementChild:a.value=t),t}}):null}}),Bh=M({name:`PrimitiveSlot`,inheritAttrs:!1,setup(e,{attrs:t,slots:n}){return()=>{if(!n.default)return null;let e=Um(n.default()),r=e.findIndex(e=>e.type!==ms);if(r===-1)return e;let i=e[r];delete i.props?.ref;let a=i.props?U(t,i.props):t,o=ks({...i,props:{}},a);return e.length===1?o:(e[r]=o,e)}}}),Vh=[`area`,`img`,`input`],X=M({name:`Primitive`,inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:`div`}},setup(e,{attrs:t,slots:n}){let r=e.asChild?`template`:e.as;return typeof r==`string`&&Vh.includes(r)?()=>ac(r,t):r===`template`?()=>ac(Bh,t,{default:n.default}):()=>ac(e.as,t,{default:n.default})}});function Hh(){let e=O();return{primitiveElement:e,currentElement:W(()=>[`#text`,`#comment`].includes(e.value?.$el.nodeName)?e.value?.$el.nextElementSibling:Pm(e))}}function Uh({type:e,defaultValue:t,modelValue:n}){let r=n||t;return n!==void 0||t!==void 0?Array.isArray(r)?`multiple`:`single`:e??`single`}function Wh({type:e,defaultValue:t,modelValue:n}){return e||Uh({type:e,defaultValue:t,modelValue:n})}function Gh({type:e,defaultValue:t}){return t===void 0?e===`single`?void 0:[]:t}function Kh(e,t){let n=W(()=>Wh(e)),r=Hm(e,`modelValue`,t,{defaultValue:Gh(e),passive:e.modelValue===void 0,deep:!0});function i(e){if(n.value===`single`)r.value=nm(e,r.value)?void 0:e;else{let t=Array.isArray(r.value)?[...r.value||[]]:[r.value].filter(Boolean);if(cm(t,e)){let n=t.findIndex(t=>nm(t,e));t.splice(n,1)}else t.push(e);r.value=t}}return{modelValue:r,changeModelValue:i,isSingle:W(()=>n.value===`single`)}}var[qh,Jh]=im(`DialogRoot`),Yh=M({inheritAttrs:!1,__name:`DialogRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1,default:!1},modal:{type:Boolean,required:!1,default:!0},unmountOnHide:{type:Boolean,required:!1,default:!0}},emits:[`update:open`],setup(e,{emit:t}){let n=e,r=Hm(n,`open`,t,{defaultValue:n.defaultOpen,passive:n.open===void 0}),i=O(),a=O(),{modal:o,unmountOnHide:s}=Dn(n);return Jh({open:r,modal:o,unmountOnHide:s,openModal:()=>{r.value=!0},onOpenChange:e=>{r.value=e},onOpenToggle:()=>{r.value=!r.value},contentId:``,titleId:``,descriptionId:``,triggerElement:i,contentElement:a}),(e,t)=>P(e.$slots,`default`,{open:k(r),close:()=>r.value=!1})}}),Xh=M({__name:`DialogClose`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1,default:`button`}},setup(e){let t=e;Y();let n=qh();return(e,r)=>(I(),R(k(X),U(t,{type:e.as===`button`?`button`:void 0,onClick:r[0]||=e=>k(n).onOpenChange(!1)}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`type`]))}}),Zh=`dismissableLayer.pointerDownOutside`,Qh=`dismissableLayer.focusOutside`;function $h(e,t){if(!(t instanceof Element))return!1;let n=t.closest(`[data-dismissable-layer]`),r=e.dataset.dismissableLayer===``?e:e.querySelector(`[data-dismissable-layer]`),i=Array.from(e.ownerDocument.querySelectorAll(`[data-dismissable-layer]`));return!!(n&&(r===n||i.indexOf(r)<i.indexOf(n)))}function eg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1),a=O(()=>{});return jr(o=>{if(!fm||!Sn(n))return;let s=async n=>{let o=n.target;if(t?.value&&o){if($h(t.value,o)){i.value=!1;return}if(n.target&&!i.value){let t={originalEvent:n};function i(){om(Zh,e,t)}n.pointerType===`touch`?(r.removeEventListener(`click`,a.value),a.value=i,r.addEventListener(`click`,a.value,{once:!0})):i()}else r.removeEventListener(`click`,a.value);i.value=!1}},c=window.setTimeout(()=>{r.addEventListener(`pointerdown`,s)},0);o(()=>{window.clearTimeout(c),r.removeEventListener(`pointerdown`,s),r.removeEventListener(`click`,a.value)})}),{onPointerDownCapture:()=>{Sn(n)&&(i.value=!0)}}}function tg(e,t,n=!0){let r=t?.value?.ownerDocument??globalThis?.document,i=O(!1);return jr(a=>{if(!fm||!Sn(n))return;let o=async n=>{if(!t?.value)return;await or(),await or();let r=n.target;t.value&&r&&!$h(t.value,r)&&n.target&&!i.value&&om(Qh,e,{originalEvent:n})};r.addEventListener(`focusin`,o),a(()=>r.removeEventListener(`focusin`,o))}),{onFocusCapture:()=>{Sn(n)&&(i.value=!0)},onBlurCapture:()=>{Sn(n)&&(i.value=!1)}}}var ng=M({__name:`DismissableLayer`,props:{disableOutsidePointerEvents:{type:Boolean,required:!1,default:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1},present:{type:Boolean,required:!1,default:!0}},emits:[`escapeKeyDown`,`pointerDownOutside`,`focusOutside`,`interactOutside`,`dismiss`],setup(e,{emit:t}){let n=e,r=t,{forwardRef:i,currentElement:a}=Y(),o=W(()=>a.value?.ownerDocument??globalThis.document),s=W(()=>Ym.layersRoot),c=W(()=>a.value?Array.from(s.value).indexOf(a.value):-1),l=W(()=>Ym.layersWithOutsidePointerEventsDisabled.size>0),u=W(()=>{let e=Array.from(s.value),[t]=[...Ym.layersWithOutsidePointerEventsDisabled].slice(-1),n=e.indexOf(t);return c.value>=n}),d=eg Line truncated
- a positive number
- less than the value passed to \`max\` (or ${jb} if no \`max\` prop is set)
- \`null\` or \`undefined\` if the progress is indeterminate.
Defaulting to \`null\`.`),null)}function Ib(e){return Pb(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${jb}\`.`),jb)}var Lb=M({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:jb},getValueLabel:{type:Function,required:!1,default:(e,t)=>Pb(e)?`${Math.round(e/t*jb)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;Y();let i=Hm(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Hm(n,`max`,r,{passive:n.max===void 0});j(()=>i.value,async e=>{let t=Fb(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),j(()=>n.max,e=>{let t=Ib(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=W(()=>sm(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Nb({modelValue:i,max:a,progressState:o}),(e,t)=>(I(),R(k(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":k(a),"aria-valuemin":0,"aria-valuenow":Pb(k(i))?k(i):void 0,"aria-valuetext":e.getValueText?.(k(i),k(a)),"aria-label":e.getValueLabel(k(i),k(a)),role:`progressbar`,"data-state":o.value,"data-value":k(i)??void 0,"data-max":k(a)},{default:A(()=>[P(e.$slots,`default`,{modelValue:k(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Rb=M({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Mb();return Y(),(e,r)=>(I(),R(k(X),U(t,{"data-state":k(n).progressState.value,"data-value":k(n).modelValue?.value??void 0,"data-max":k(n).max.value}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),[zb,Bb]=im(`ScrollAreaRoot`),Vb=M({__name:`ScrollAreaRoot`,props:{type:{type:String,required:!1,default:`hover`},dir:{type:String,required:!1},scrollHideDelay:{type:Number,required:!1,default:600},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e,{expose:t}){let n=e,r=O(0),i=O(0),a=O(),o=O(),s=O(),c=O(),l=O(!1),u=O(!1),{type:d,dir:f,scrollHideDelay:p}=Dn(n),m=ih(f);function h(){a.value?.scrollTo({top:0})}function g(){a.value?.scrollTo({top:0,left:0})}t({viewport:a,scrollTop:h,scrollTopLeft:g});let{forwardRef:_,currentElement:v}=Y();return Bb({type:d,dir:m,scrollHideDelay:p,scrollArea:v,viewport:a,onViewportChange:e=>{a.value=e||void 0},content:o,onContentChange:e=>{o.value=e},scrollbarX:s,scrollbarXEnabled:l,scrollbarY:c,scrollbarYEnabled:u,onScrollbarXChange:e=>{s.value=e||void 0},onScrollbarYChange:e=>{c.value=e||void 0},onScrollbarXEnabledChange:e=>{l.value=e},onScrollbarYEnabledChange:e=>{u.value=e},onCornerWidthChange:e=>{r.value=e},onCornerHeightChange:e=>{i.value=e}}),(e,t)=>(I(),R(k(X),{ref:k(_),"as-child":n.asChild,as:e.as,dir:k(m),style:ye({position:`relative`,"--reka-scroll-area-corner-width":`${r.value}px`,"--reka-scroll-area-corner-height":`${i.value}px`})},{default:A(()=>[P(e.$slots,`default`)]),_:3},8,[`as-child`,`as`,`dir`,`style`]))}}),Hb=M({__name:`ScrollAreaCornerImpl`,setup(e){let t=zb(),n=O(0),r=O(0),i=W(()=>!!n.value&&!!r.value);function a(){let e=t.scrollbarX.value?.offsetHeight||0;t.onCornerHeightChange(e),r.value=e}function o(){let e=t.scrollbarY.value?.offsetWidth||0;t.onCornerWidthChange(e),n.value=e}return Vm(t.scrollbarX.value,a),Vm(t.scrollbarY.value,o),j(()=>t.scrollbarX.value,a),j(()=>t.scrollbarY.value,o),(e,a)=>i.value?(I(),R(k(X),U({key:0,style:{width:`${n.value}px`,height:`${r.value}px`,position:`absolute`,right:k(t).dir.value===`ltr`?0:void 0,left:k(t).dir.value===`rtl`?0:void 0,bottom:0}},e.$parent?.$props),{default:A(()=>[P(e.$slots,`default`)]),_:3},16,[`style`])):H(`v-if`,!0)}}),Ub=M({__name:`ScrollAreaCorner`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,{forwardRef:n}=Y(),r=zb(),i=W(()=>!!r.scrollbarX.value&&!!r.scrollbarY.value),a=W(()=>r.type.value!==`scroll`&&i.value);return(e,r)=>a.value?(I(),R(Hb,U({key:0},t,{ref:k(n)}),{default:A(()=>[P(e.$slots,`default`)]),_:3},16)):H(`v-if`,!0)}});function Wb(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];let r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Gb(e){let t=Kb(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function Kb(e,t){let n=e/t;return Number.isNaN(n)?0:n}function qb(e,t=()=>{}){let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function i(){let a={left:e.scrollLeft,top:e.scrollTop},o=n.left!==a.left,s=n.top!==a.top;(o||s)&&t(),n=a,r=window.requestAnimationFrame(i)})(),()=>window.cancelAnimationFrame(r)}function Jb(e,t,n=`ltr`){let r=Gb(t),i=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,a=t.scrollbar.size-i,o=t.content-t.viewport,s=a-r,c=n===`ltr`?[0,o]:[o*-1,0],l=rm(e,c[0],c[1]);return Wb([0,o],[0,s])(l)}functLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:kw(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>kw(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=jw(c),u=e+1<n.length?jw(n[e+1]):null;if(l&&u&&Mw(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=jw(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>kw(e)),rows:r.map(e=>e.map(e=>kw(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:kw(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:kw(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function jw(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Mw(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var Nw={class:`[overflow-wrap:anywhere]`},Pw={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},Fw={class:`font-mono text-[0.85em]`},Iw={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},Lw={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},Rw={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},zw={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},Bw={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},Vw={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},Hw={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},Uw={key:8,class:`mb-2.5 last:mb-0`},Ww=M({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=W(()=>Aw(t.text));return(e,t)=>(I(),L(`div`,Nw,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(F,{key:t},[e.kind===`pre`?(I(),L(`pre`,Pw,[z(`code`,Fw,D(e.code),1)])):e.kind===`table`?(I(),L(`table`,Iw,[z(`thead`,null,[z(`tr`,null,[(I(!0),L(F,null,N(e.head,(e,t)=>(I(),L(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[B(Dw,{inline:e},null,8,[`inline`])]))),128))])]),z(`tbody`,null,[(I(!0),L(F,null,N(e.rows,(e,t)=>(I(),L(`tr`,{key:t},[(I(!0),L(F,null,N(e,(e,t)=>(I(),L(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[B(Dw,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(I(),L(`blockquote`,Lw,[B(Dw,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(I(),L(`h1`,Rw,[B(Dw,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(I(),L(`h2`,zw,[B(Dw,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(I(),L(`h3`,Bw,[B(Dw,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(I(),L(`ul`,Vw,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(Dw,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(I(),L(`ol`,Hw,[(I(!0),L(F,null,N(e.items,(e,t)=>(I(),L(`li`,{key:t},[B(Dw,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(I(),L(`p`,Uw,[B(Dw,{inline:e.inline},null,8,[`inline`])])):H(``,!0)],64))),128))]))}}),Gw={class:`truncate`},Kw=M({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return I(),R(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-primary transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:A(()=>[B(k(Vu),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),z(`span`,Gw,D(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),qw={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},Jw={class:`font-semibold text-foreground`},Yw={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},Xw=M({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=W(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=W(()=>t.tool.parameters||t.tool.Parameters||``),i=W(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=W(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(I(),R(Kw,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(I(),L(`div`,qw,[B(k(fd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),z(`span`,Jw,D(n.value),1),r.value?(I(),L(`code`,Yw,D(r.value),1)):H(``,!0),z(`span`,{class:E(k(q)(`text-fg-muted`,i.value&&`text-danger`))},D(a.value),3)]))}}),Zw={key:0,class:`mb-2 grid gap-0.5 text-xs`},Qw={key:2,class:`whitespace-pre-wrap`},$w=M({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(I(),L(`div`,{class:E([`flex`,e.assistant?`justify-start`:`justify-end`])},[z(`div`,{class:E(k(q)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(I(),L(`div`,Zw,[(I(!0),L(F,null,N(e.tools,(t,n)=>(I(),R(Xw,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):H(``,!0),e.assistant?(I(),R(Ww,{key:1,text:e.text},null,8,[`text`])):(I(),L(`div`,Qw,D(e.text),1)),P(t.$slots,`default`)],2)],2))}}),eT={class:`w-full self-center justify-self-center py-6 text-center`},tT={class:`grid gap-2`},nT=[`onClick`],rT=M({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(I(),L(`div`,eT,[t[0]||=z(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 pLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>LA?`${n.slice(0,LA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var zA=[`title`],BA=M({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=W(()=>sA(n.event)),a=W(()=>RA(n.event));function o(){i.value>0&&r(`open`,i.value)}return(e,t)=>(I(),R(k(CO),{class:E(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[fu(uu(o,[`prevent`]),[`enter`]),fu(uu(o,[`prevent`]),[`space`])]},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(n.event.kind||n.event.type||`event`),1)]),_:1}),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(i.value>0?`#${i.value}`:`—`),1)]),_:1}),B(k(Q),{class:`w-[55%] max-w-0`},{default:A(()=>[z(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},D(a.value.text),9,zA)]),_:1}),B(k(Q),null,{default:A(()=>[V(D(k($O)(n.event.at||Date.now())),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),VA=M({__name:`LiveActivityCard`,setup(e){let t=PT();function n(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(I(),R(k(iO),null,{default:A(()=>[B(k(lO),null,{default:A(()=>[B(k(uO),null,{default:A(()=>[...t[0]||=[V(`Live activity`,-1)]]),_:1}),B(k(sO),null,{default:A(()=>[...t[1]||=[V(`Last 50, newest first`,-1)]]),_:1}),B(k(aO),null,{default:A(()=>[B(k(TO),{variant:k(rA)},{default:A(()=>[V(D(k(nA)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),B(k(oO),null,{default:A(()=>[B(k(xO),null,{default:A(()=>[B(k(wO),null,{default:A(()=>[B(k(CO),null,{default:A(()=>[B(k($),null,{default:A(()=>[...t[2]||=[V(`Event`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[3]||=[V(`Task`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[4]||=[V(`Detail`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...t[5]||=[V(`When`,-1)]]),_:1})]),_:1})]),_:1}),B(k(SO),null,{default:A(()=>[k(tA).length?(I(!0),L(F,{key:1},N(k(tA),(e,t)=>(I(),R(BA,{key:t,event:e,onOpen:n},null,8,[`event`]))),128)):(I(),R(k(CO),{key:0},{default:A(()=>[B(k(Q),{colspan:`4`},{default:A(()=>[B(k(dO),null,{default:A(()=>[B(k(mO),null,{default:A(()=>[B(k(_O),null,{default:A(()=>[...t[6]||=[V(`Waiting for activity`,-1)]]),_:1}),B(k(pO),null,{default:A(()=>[...t[7]||=[V(`Events appear here as Archie works.`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1}))]),_:1})]),_:1})]),_:1})]),_:1}))}}),HA=M({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=NS(t,`class`);return(e,r)=>(I(),R(k(Lb),U({"data-slot":`progress`},k(n),{class:k(q)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:A(()=>[B(k(Rb),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transform: translateX(-${100-(t.modelValue??0)}%);`)},null,8,[`style`])]),_:1},16,[`class`]))}}),UA=`archie.setup-complete.dismissed.v1`;function WA(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(UA),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function GA(e=globalThis.localStorage){e?.setItem?.(UA,`1`)}var KA={class:`text-lg font-semibold text-primary`},qA={class:`flex flex-col gap-3`},JA={key:0,class:`mt-0.5 text-xs text-fg-subtle`},YA=M({__name:`SetupPanel`,setup(e){let t=O(WA(Zk.value));j(Zk,()=>{t.value=WA(Zk.value)});let n=W(()=>Zk.value?.steps??[]),r=W(()=>{let e=n.value.length;return e?Math.round((e-t.value.remaining.length)/e*100):0});function i(){GA(),t.value=WA(Zk.value)}return(e,a)=>t.value.kind===`incomplete`?(I(),R(k(iO),{key:0},{default:A(()=>[B(k(lO),null,{default:A(()=>[B(k(uO),null,{default:A(()=>[...a[0]||=[V(`Finish setting up`,-1)]]),_:1}),B(k(sO),null,{default:A(()=>[...a[1]||=[V(`Archie needs these before it can work on its own.`,-1)]]),_:1}),B(k(aO),null,{default:A(()=>[z(`span`,KA,D(r.value)+`%`,1)]),_:1})]),_:1}),B(k(oO),null,{default:A(()=>[B(k(HA),{"model-value":r.value,class:`mb-4`},null,8,[`model-value`]),z(`ul`,qA,[(I(!0),L(F,null,N(n.value,(e,t)=>(I(),L(`li`,{key:t,class:`flex items-start gap-3`},[z(`span`,{class:E([`mt-px grid size-[18px] flex-none place-items-center rounded-full border-[1.5px] border-border-strong text-xs text-fg-subtle`,e.done?`border-transparent bg-ok-soft text-ok`:``])},[e.done?(I(),R(k(Hu),{key:0,class:`size-3`})):H(``,!0)],2),z(`div`,null,[z(`div`,{class:E([`text-sm`,e.done?`text-fg-muted line-through`:``])},D(e.title),3),e.detail?(I(),L(`div`,JA,D(e.detail),1)):H(``,!0)])]))),128))])]),_:1})]),_:1})):t.value.kind===`complete`?(I(),R(k(iO),{key:1},{default:A(()=>[B(k(lO),null,{default:A(()=>[B(k(uO),null,{default:A(()=>[...a[2]||=[V(`Setup complete`,-1)]]),_:1}),B(k(sO),null,{default:A(()=>[...a[3]||=[V(`ArLine truncated
`)}return(e,i)=>k(MN)?(I(),R(_N,{key:0,title:`Update status`,description:`Not configured on this deployment, so there is nothing to check against.`})):k(jN)?(I(),R(k(iO),{key:1,class:`mb-4`},{default:A(()=>[B(k(oO),null,{default:A(()=>[B(k(dO),null,{default:A(()=>[B(k(mO),null,{default:A(()=>[B(k(_O),null,{default:A(()=>[...i[0]||=[V(`Update status unavailable`,-1)]]),_:1}),B(k(pO),null,{default:A(()=>[V(D(k(jN)),1)]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})):(I(),R(_N,{key:2,title:`Update status`,description:`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`},{default:A(()=>[k(AN).length?(I(),R(k(xO),{key:1},{default:A(()=>[B(k(wO),null,{default:A(()=>[B(k(CO),null,{default:A(()=>[B(k($),null,{default:A(()=>[...i[3]||=[V(`Component`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...i[4]||=[V(`Install type`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...i[5]||=[V(`Running`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...i[6]||=[V(`Latest available`,-1)]]),_:1}),B(k($),null,{default:A(()=>[...i[7]||=[V(`Status`,-1)]]),_:1})]),_:1})]),_:1}),B(k(SO),null,{default:A(()=>[(I(!0),L(F,null,N(k(AN),e=>(I(),R(k(CO),{key:e.id||e.label,title:r(e)},{default:A(()=>[B(k(Q),{class:`font-medium`},{default:A(()=>[V(D(e.label||e.id),1)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.install_type||`—`),1)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.running_version||`—`),1)]),_:2},1024),B(k(Q),{class:`font-mono`},{default:A(()=>[V(D(e.latest_available||`—`),1)]),_:2},1024),B(k(Q),null,{default:A(()=>[B(k(TO),{variant:n[e.status||``]||`idle`},{default:A(()=>[V(D(t[e.status||``]||e.status),1)]),_:2},1032,[`variant`])]),_:2},1024)]),_:2},1032,[`title`]))),128))]),_:1})]),_:1})):(I(),R(k(dO),{key:0},{default:A(()=>[B(k(mO),null,{default:A(()=>[B(k(_O),null,{default:A(()=>[...i[1]||=[V(`No components reported`,-1)]]),_:1}),B(k(pO),null,{default:A(()=>[...i[2]||=[V(`The configured update-check command returned nothing.`,-1)]]),_:1})]),_:1})]),_:1}))]),_:1}))}}),QP=M({__name:`SystemStatusPage`,setup(e){async function t(){await Promise.all([kN(),NN(),FN()])}return ia(t),(e,n)=>(I(),L(`div`,null,[B(MD,{title:`Status`,subtitle:`What archied is running with right now.`},{default:A(()=>[B(k(Z),{variant:`outline`,onClick:t},{default:A(()=>[B(k(rd),{"data-icon":`inline-start`}),n[0]||=V(` Refresh `,-1)]),_:1})]),_:1}),B(vP),B(ZP),B(XP),k(ON)?(I(),R(oP,{key:0})):(I(),L(F,{key:1},[B(KP),B(aP,{ids:k(eP)},null,8,[`ids`]),B(qP)],64))]))}}),$P=M({__name:`LifecycleActionList`,props:{actions:{}},setup(e){let t=e;function n(e){return e===`quiet`?`ghost`:e===`danger`?`destructive`:`outline`}return(e,r)=>(I(),L(F,null,[r[2]||=z(`h3`,{class:`mt-5 mb-2 text-sm font-semibold text-fg-muted`},`Actions`,-1),t.actions.length?(I(),R(yN,{key:1},{default:A(()=>[(I(!0),L(F,null,N(t.actions,e=>(I(),R($N,{key:e.id,label:e.id},{value:A(()=>[z(`span`,null,[B(k(Z),{variant:n(e.kind),size:`xs`,disabled:``},{default:A(()=>[V(D(e.label??e.id),1)]),_:2},1032,[`variant`])])]),_:2},1032,[`label`]))),128))]),_:1})):(I(),R(k(dO),{key:0},{default:A(()=>[B(k(mO),null,{default:A(()=>[B(k(_O),null,{default:A(()=>[...r[0]||=[V(`No actions reported`,-1)]]),_:1}),B(k(pO),null,{default:A(()=>[...r[1]||=[V(`The server did not return any operator actions.`,-1)]]),_:1})]),_:1})]),_:1}))],64))}}),eF=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],tF=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quiet`,confirm:`Archive the local record for "{title}"?`},{id:`open_pr`,label:`Open PR`,kind:`link`},{id:`open_issue`,label:`Open issue`,kind:`link`}],nF=vn([...eF]),rF=vn([...tF]),iF=W(()=>new Map(nF.value.map(e=>[e.id,e]))),aF=W(()=>new Map(rF.value.map(e=>[e.id,e])));async function oF(){try{let e=await J.taskMeta();Array.isArray(e?.statuses)&&(nF.value=e.statuses),Array.isArray(e?.actions)&&(rF.value=e.actions)}catch{}}function sF(e){return iF.value.get(e)?.label||e||`Unknown`}function cF(e){return iF.value.get(e)?.kind||`idle`}function lF(){return nF.value}function uF(){return nF.value.map(e=>e.id)}function dF(){return new Line truncated
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+21 -7
View File
@@ -1,12 +1,26 @@
<!doctype html>
<html lang="en" data-theme="dark">
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<title>Archie</title>
<script type="module" crossorigin src="./assets/index.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index.css">
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>archie-ui</title>
<script>
// Set before the first paint so a reload does not flash the wrong
// palette. Kept in sync with src/lib/theme.ts; a blocked localStorage
// falls back to dark, which is the default theme.
(function () {
var theme = "dark";
try {
if (localStorage.getItem("archie.theme") === "light") theme = "light";
} catch (e) {
/* default stands */
}
document.documentElement.dataset.theme = theme;
})();
</script>
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index.css">
</head>
<body>
<div id="app"></div>
+20 -6
View File
@@ -1,13 +1,27 @@
<!doctype html>
<html lang="en" data-theme="dark">
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<title>Archie</title>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>archie-ui</title>
<script>
// Set before the first paint so a reload does not flash the wrong
// palette. Kept in sync with src/lib/theme.ts; a blocked localStorage
// falls back to dark, which is the default theme.
(function () {
var theme = "dark";
try {
if (localStorage.getItem("archie.theme") === "light") theme = "light";
} catch (e) {
/* default stands */
}
document.documentElement.dataset.theme = theme;
})();
</script>
</head>
<body>
<div id="app"></div>
<script type="module" src="./src/main.jsx"></script>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+5778 -1368
View File
File diff suppressed because it is too large. Load diff
+24 -8
View File
@@ -1,19 +1,35 @@
{
"name": "archie-dashboard",
"name": "archie-ui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "node --import ./test/register.js --test \"test/*.test.js\""
"build": "vue-tsc -b && vite build",
"preview": "vite preview",
"typecheck": "vue-tsc --build --force"
},
"dependencies": {
"preact": "^10.26.0"
"@fontsource-variable/geist": "^5.3.0",
"@lucide/vue": "^1.47.0",
"@tailwindcss/vite": "^4.3.3",
"@vueuse/core": "^15.0.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"reka-ui": "^2.10.4",
"tailwind-merge": "^3.7.0",
"tailwindcss": "^4.3.3",
"tw-animate-css": "^1.4.0",
"vue": "^3.5.42",
"vue-router": "^5.3.1"
},
"devDependencies": {
"@preact/preset-vite": "^2.10.0",
"@testing-library/preact": "^3.2.4",
"jsdom": "^30.0.1",
"vite": "^8.0.0"
"@types/node": "^24.13.6",
"@vitejs/plugin-vue": "^6.0.8",
"@vue/tsconfig": "^0.9.1",
"shadcn-vue": "^2.8.2",
"typescript": "~6.0.2",
"vite": "^8.3.0",
"vue-tsc": "^3.3.11"
}
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+64
View File
@@ -0,0 +1,64 @@
<script setup lang="ts">
import { onMounted } from "vue";
import ChatLauncher from "@/chat/ChatLauncher.vue";
import Topbar from "@/components/topbar/Topbar.vue";
import { TooltipProvider } from "@/components/ui/tooltip";
import { hidden, loadCapabilities } from "@/lib/capabilities";
import { loadTaskMeta } from "@/lib/task-meta";
onMounted(() => {
// Asked for once, after the shell is up: the nav paints immediately and
// loses the entries this process cannot back a moment later, rather than
// holding the page behind a request. A failed read hides nothing.
void loadCapabilities();
// The lifecycle vocabulary -- status labels, pill severity, "needs you"
// grouping, and the operator actions -- is served by /api/task-meta. Asked
// for once, after the shell is up: the freeze-dried defaults paint
// immediately and this replaces them, so a catalogue change on the server
// reaches the browser without a UI release. loadTaskMeta never throws (a
// failed read keeps the defaults), so it needs no catch here.
void loadTaskMeta();
});
</script>
<template>
<TooltipProvider :delay-duration="350">
<!--
One contained, rounded surface floating on the canvas `body` carries:
framing the workspace gives the panels an edge to sit against, and lets
the light behind read through rather than stopping at the first opaque
card. The frame is a desktop affordance, so at the narrow breakpoint it
goes edge to edge instead of insetting a rounded card on a phone.
`backdrop-filter` makes this a containing block for `position: fixed`,
so the chat launcher has to render outside this element.
-->
<div
class="flex min-h-[calc(100vh-2rem)] flex-col overflow-hidden rounded-xl border border-[var(--hairline)] bg-[var(--workspace)] shadow-[var(--shadow-workspace)] backdrop-blur-[28px] backdrop-saturate-[1.2] max-[900px]:min-h-screen max-[900px]:rounded-none max-[900px]:border-0 max-[900px]:shadow-none"
>
<Topbar :hidden="hidden" />
<main class="w-full flex-1 overflow-x-hidden p-8 max-[900px]:p-4">
<!--
Keyed on the path and its parameters but not the query: a query-only
change is an entry state, so the page keeps the operator's filters,
while two different :id values get fresh instances -- without that
the second id diffs the first one in place and the previous task's
open tab stays open on the next (W11).
-->
<RouterView v-slot="{ Component, route }">
<component :is="Component" :key="route.path" />
</RouterView>
</main>
</div>
<!--
Outside the shell on purpose: the frame above carries `backdrop-filter`,
which makes it a containing block for `position: fixed`, so a launcher
nested inside it would anchor to the shell rather than the viewport and
ride off the bottom of a long page.
-->
<ChatLauncher />
</TooltipProvider>
</template>
+75
View File
@@ -0,0 +1,75 @@
<script setup lang="ts">
import { computed } from "vue";
/**
* Arc gauge for a single headline percentage.
*
* A percentage that decides whether you need to act deserves more than a line
* of text: the arc is readable at a glance from across a room, which a number
* is not. Colour follows the value, so "is this bad" is answered before the
* digits are read.
*/
const props = withDefaults(defineProps<{ value: number | string; label: string; size?: number }>(), {
size: 168,
});
const pct = computed(() => Math.max(0, Math.min(100, Number(props.value) || 0)));
const rounded = computed(() => Math.round(pct.value));
const stroke = computed(() => (pct.value >= 90 ? "var(--ok)" : pct.value >= 70 ? "var(--warn)" : "var(--danger)"));
// 240-degree arc, opening downward, so the value reads left-to-right.
const R = 62;
const SWEEP = 240;
const START = 150;
const circumference = 2 * Math.PI * R * (SWEEP / 360);
function arc(from: number, deg: number): string {
const cx = props.size / 2;
const cy = props.size / 2;
const a0 = (from * Math.PI) / 180;
const a1 = ((from + deg) * Math.PI) / 180;
const large = deg > 180 ? 1 : 0;
return [
`M ${cx + R * Math.cos(a0)} ${cy + R * Math.sin(a0)}`,
`A ${R} ${R} 0 ${large} 1 ${cx + R * Math.cos(a1)} ${cy + R * Math.sin(a1)}`,
].join(" ");
}
</script>
<template>
<div class="relative grid place-items-center">
<!--
The label announces the rounded value. It used to announce the raw one, so
a screen reader read "71.38461538461539%" before the same figure was
shown rounded.
-->
<svg
class="block w-full max-w-[200px]"
:viewBox="`0 0 ${props.size} ${props.size * 0.78}`"
role="img"
:aria-label="`${props.label}: ${rounded}%`"
>
<path
:d="arc(START, SWEEP)"
fill="none"
stroke="var(--border)"
stroke-width="12"
stroke-linecap="round"
/>
<path
:d="arc(START, SWEEP)"
fill="none"
:stroke="stroke"
stroke-width="12"
stroke-linecap="round"
:stroke-dasharray="circumference"
:stroke-dashoffset="circumference * (1 - pct / 100)"
class="transition-[stroke-dashoffset] duration-[600ms] ease-[cubic-bezier(0.4,0,0.2,1)]"
/>
</svg>
<div class="absolute top-[52%] -translate-y-1/2 text-center">
<div class="text-2xl font-semibold tracking-[-0.03em]">{{ rounded }}%</div>
<div class="text-xs text-fg-muted">{{ props.label }}</div>
</div>
</div>
</template>
+33
View File
@@ -0,0 +1,33 @@
<script setup lang="ts">
import { fmtValue, LEVEL_COLOR, levelKind, shortTime, type LogEntry } from "@/lib/log";
/**
* Shared log-entry rendering. Both the daemon-wide log page and a task's own
* attempt log render the same entry shape, so the row lives here rather than
* being duplicated a second time.
*/
const props = defineProps<{ entry: LogEntry }>();
const fields = () => Object.entries(props.entry.fields ?? {});
</script>
<template>
<div
class="grid grid-cols-[62px_52px_1fr] items-baseline gap-3 border-b border-border px-1 py-2 hover:bg-accent"
>
<span class="font-mono text-fg-subtle">{{ shortTime(props.entry.time) }}</span>
<span class="text-[10px] font-semibold tracking-[0.04em]" :class="LEVEL_COLOR[levelKind(props.entry.level)]">
{{ (props.entry.level || "info").toUpperCase() }}
</span>
<span class="flex min-w-0 flex-wrap items-baseline gap-2">
<span class="break-words text-foreground">{{ props.entry.message || props.entry.msg || "" }}</span>
<span
v-for="[k, v] in fields()"
:key="k"
class="max-w-full truncate rounded-sm bg-muted px-2 text-fg-muted"
>
<span class="text-fg-subtle after:opacity-60 after:content-['=']">{{ k }}</span>{{ fmtValue(v) }}
</span>
</span>
</div>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
/**
* The head every page opens with: what the page is, in a line, and the actions
* that belong to it. A component rather than per-page markup because every page
* has one, and hand-built copies drift.
*/
defineProps<{ title: string; subtitle?: string }>();
</script>
<template>
<div class="mb-6 flex flex-wrap items-start justify-between gap-5">
<div>
<h1 class="text-2xl font-semibold tracking-[-0.02em]">{{ title }}</h1>
<p v-if="subtitle" class="mt-1 text-sm text-fg-muted">{{ subtitle }}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<slot />
</div>
</div>
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { computed } from "vue";
import { STATUS_FILL, type StatusKind } from "@/lib/status";
/**
* Segmented proportional bar with a legend.
*
* Used for budget composition -- what is spent, committed and still free --
* because three related quantities are easier to compare in one bar than in
* three separate numbers.
*/
const props = defineProps<{
segments: Array<{ label: string; value: number; kind?: StatusKind }>;
}>();
const total = computed(() => props.segments.reduce((a, s) => a + (s.value || 0), 0) || 1);
const partWidth = (value: number) => `${((value / total.value) * 100).toFixed(1)}%`;
const fill = (kind?: StatusKind) => STATUS_FILL[kind ?? "idle"];
</script>
<template>
<div>
<div class="flex h-[10px] gap-[2px] overflow-hidden rounded-full bg-border">
<span
v-for="s in props.segments.filter((s) => s.value > 0)"
:key="s.label"
class="block h-full"
:class="fill(s.kind)"
:style="`width:${partWidth(s.value)}`"
:title="`${s.label}: ${s.value}`"
/>
</div>
<div class="mt-3 flex flex-wrap gap-4">
<span
v-for="s in props.segments"
:key="s.label"
class="inline-flex items-center gap-2 text-xs text-fg-muted"
>
<span class="size-2 rounded-full" :class="fill(s.kind)" />
{{ s.label }}
</span>
</div>
</div>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { computed } from "vue";
/**
* Inline SVG sparkline. Shows shape, not exact values: the tile's headline
* number carries the precision.
*/
const props = withDefaults(
defineProps<{ series: number[]; stroke?: string; width?: number; height?: number }>(),
{ stroke: "var(--ok)", width: 220, height: 34 },
);
const points = computed(() => {
const max = Math.max(...props.series, 1);
const min = Math.min(...props.series, 0);
const span = max - min || 1;
const step = props.series.length > 1 ? props.width / (props.series.length - 1) : props.width;
return props.series
.map(
(v, i) =>
`${(i * step).toFixed(1)},${(props.height - ((v - min) / span) * props.height).toFixed(1)}`,
)
.join(" ");
});
</script>
<template>
<svg
class="mt-3 block h-[34px] w-full"
:viewBox="`0 0 ${props.width} ${props.height}`"
preserveAspectRatio="none"
aria-hidden="true"
>
<polyline
:points="points"
fill="none"
:stroke="props.stroke"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
vector-effect="non-scaling-stroke"
/>
</svg>
</template>
+63
View File
@@ -0,0 +1,63 @@
<script setup lang="ts">
import { TrendingDown, TrendingUp } from "@lucide/vue";
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import Sparkline from "./Sparkline.vue";
/**
* A KPI tile: label, big value, trend against a stated comparison window, and
* a sparkline. The comparison line is not decoration -- a number without a
* baseline cannot be acted on, so `compare` is required.
*
* trend > 0 renders as an increase. `goodDirection` says whether that is good,
* because rising latency and rising success rate are not the same news.
*
* The headline value is rendered whatever its type, including 0 and "": a tile
* that showed a label and a comparison line with no number above them read as
* a broken dashboard on every fresh install.
*/
const props = withDefaults(
defineProps<{
label: string;
value: string | number;
unit?: string;
trend?: number | null;
compare: string;
series?: number[];
goodDirection?: "up" | "down";
}>(),
{ series: () => [], goodDirection: "up" },
);
const dir = computed(() => (props.trend == null ? null : props.trend >= 0 ? "up" : "down"));
const good = computed(() => (dir.value == null ? null : dir.value === props.goodDirection));
const trendIcon = computed(() => (dir.value === "up" ? TrendingUp : TrendingDown));
const trendLabel = computed(() => `${Math.abs(props.trend ?? 0).toFixed(1)}%`);
</script>
<template>
<Card>
<CardHeader>
<CardTitle>{{ props.label }}</CardTitle>
<CardDescription v-if="props.compare">{{ props.compare }}</CardDescription>
<CardAction v-if="dir">
<Badge :variant="good ? 'ok' : 'danger'">
<component :is="trendIcon" />
{{ trendLabel }}
</Badge>
</CardAction>
</CardHeader>
<CardContent>
<div class="text-3xl font-semibold tracking-[-0.03em]">
{{ props.value }}<span v-if="props.unit" class="ml-1 text-lg text-fg-muted">{{ props.unit }}</span>
</div>
<Sparkline
v-if="props.series.length > 1"
:series="props.series"
:stroke="good === false ? 'var(--danger)' : 'var(--ok)'"
/>
</CardContent>
</Card>
</template>
-197
View File
@@ -1,197 +0,0 @@
// Single place that knows how to talk to archied. Every feature folder goes
// through api.* below, and every api.* method goes through send(), so the CSRF
// header, the Content-Type, the request timeout, and the error shape live in
// this one file. ui/test/api-client.test.js asserts that: it fails if a second
// fetch() call appears here, and it fails if any method omits a header the
// server requires.
import { randomUUID } from "./uuid.jsx";
import { streamStateFor } from "./stream-state.js";
// DEFAULT_TIMEOUT_MS bounds a request so a daemon that accepts the connection
// but never answers cannot leave the UI in a loading state with no way back.
// The retry affordances rely on fetch settling, so bound it.
const DEFAULT_TIMEOUT_MS = 15000;
// qs builds a query string, omitting empty values so the server sees an
// absent filter rather than an empty one.
function qs(params) {
const q = new URLSearchParams();
for (const [k, v] of Object.entries(params || {})) {
if (v !== "" && v != null) q.set(k, v);
}
const s = q.toString();
return s ? `?${s}` : "";
}
// errorMessage prefers what the server actually said. archied answers these
// with http.Error, i.e. a plain-text reason -- "task is not awaiting
// approval", "max retries reached (3/3)", "Content-Type must be
// application/json" -- and discarding it in favour of "409 Conflict" throws
// away the only part an operator can act on.
async function errorMessage(res) {
try {
const body = (await res.text()).trim();
if (body) return body.split("\n")[0].slice(0, 200);
} catch {
// Body already consumed or unreadable; fall through to the status.
}
return `${res.status} ${res.statusText}`;
}
export class ApiError extends Error {
constructor(message, status) {
super(message);
this.status = status;
}
}
// classifyActionError turns a failed operator action into a rendering
// decision. archied's own handlers already return distinguishable status
// codes for a refused mutation (400/403/409/415 -- bad input, missing CSRF,
// cross-origin, conflicting state, a body that is not JSON) versus a broken
// one (5xx, or no status at all when fetch itself failed -- network drop,
// timeout); 401 additionally means the session -- archied's own token cookie,
// or an upstream forward-auth proxy sitting in front of it -- has expired
// rather than that the action was rejected or the daemon is unwell.
export function classifyActionError(err) {
const status = err instanceof ApiError ? err.status : undefined;
const message = err?.message || "Action failed";
if (status === 401) return { kind: "session-expired", message };
if (status >= 400 && status < 500) return { kind: "refused", message };
return { kind: "broken", message };
}
// send is the only fetch() in the dashboard. It converts a non-ok response
// into an ApiError carrying the server's own explanation and a usable status,
// and hands the raw Response back so the streaming caller can read the body
// itself.
async function send(path, init) {
const res = await fetch(path, init);
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
return res;
}
// request performs a JSON request. Every mutating method must declare a JSON
// body: archied's handlers run authorizeTaskMutation first, and it answers 415
// unless Content-Type is application/json -- including for a mutation that has
// no body to send, because that requirement is what makes a simple cross-origin
// form post inexpressible. Sending the header on every mutation, rather than
// only where a payload happens to exist, is what keeps a bodyless DELETE or
// approve from being refused.
async function request(path, { method = "GET", body, timeoutMs = DEFAULT_TIMEOUT_MS, parse = true } = {}) {
const headers = { Accept: "application/json" };
const init = { method, headers, signal: AbortSignal.timeout(timeoutMs) };
if (method !== "GET") {
headers["Content-Type"] = "application/json";
headers["X-Archie-CSRF"] = "1";
}
if (body !== undefined) init.body = JSON.stringify(body);
const res = await send(path, init);
return parse ? res.json() : undefined;
}
export const api = {
summary: () => request("/api/summary"),
tasks: () => request("/api/tasks"),
taskMeta: () => request("/api/task-meta"),
task: (id) => request(`/api/tasks/${id}`),
taskAttempts: (id) => request(`/api/tasks/${id}/attempts`),
taskChanges: (id, params) => request(`/api/tasks/${id}/changes` + qs(params)),
taskDebug: (id, params) => request(`/api/tasks/${id}/debug` + qs(params)),
taskAction: (id, action) => request(`/api/tasks/${id}/action`, { method: "POST", body: { action } }),
setup: () => request("/api/setup"),
capabilities: () => request("/api/capabilities"),
workflows: () => request("/api/workflows"),
workRequest: (workRequest) => request("/api/work-requests", { method: "POST", body: workRequest }),
skills: () => request("/api/skills"),
channels: () => request("/api/channels"),
curators: () => request("/api/curators"),
channelReload: (id) => request(`/api/channels/${encodeURIComponent(id)}/reload`, { method: "POST", body: {} }),
config: () => request("/api/config"),
version: () => request("/api/version"),
configUpdate: (updates) => request("/api/config", { method: "PATCH", body: { updates } }),
configRepoUpdate: (owner, name, field, value) =>
request(`/api/config/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`, { method: "PATCH", body: { field, value } }),
configReset: (key) => request("/api/config/reset", { method: "POST", body: { key } }),
logs: (params) => request("/api/logs" + qs(params)),
taskLogs: (id, params) => request(`/api/tasks/${id}/logs` + qs(params)),
// A download is a navigation, not a fetch: the browser must own the
// Content-Disposition filename and stream the body to disk rather than hold
// a whole log in memory. The URL builder is the client-side contract, and
// base/log-row's sibling module keeps it beside the panel that uses it.
taskLogDownloadURL: (id, attempt) => `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`),
captures: (limit) => request("/api/captures" + qs({ limit })),
mappings: () => request("/api/mappings"),
mappingCreate: (mapping) => request("/api/mappings", { method: "POST", body: mapping }),
mappingUpdate: (id, mapping) => request(`/api/mappings/${id}`, { method: "PATCH", body: mapping }),
// A delete answers 204, so there is no body to parse.
mappingDelete: (id) => request(`/api/mappings/${id}`, { method: "DELETE", parse: false }),
mappingPreview: (captureId, fields) => request("/api/mappings/preview", { method: "POST", body: { capture_id: captureId, fields } }),
bindings: () => request("/api/bindings"),
bindingCreate: (binding) => request("/api/bindings", { method: "POST", body: binding }),
bindingUpdate: (id, binding) => request(`/api/bindings/${id}`, { method: "PATCH", body: binding }),
bindingDelete: (id) => request(`/api/bindings/${id}`, { method: "DELETE", parse: false }),
bindingApprove: (id) => request(`/api/bindings/${id}/approve`, { method: "POST" }),
chatSessions: () => request("/api/chat/sessions"),
chatMessages: (id) => request(`/api/chat/sessions/${encodeURIComponent(id)}/messages`),
chatTurns: (id) => request(`/api/chat/sessions/${encodeURIComponent(id)}/turns`),
chatCancel: (sessionID) => request("/api/chat/cancel", { method: "POST", body: { session_id: sessionID } }),
chatMessage: (channelID, text) =>
request("/api/chat/message", {
method: "POST",
body: { channel_id: channelID, source_id: randomUUID(), text, page: location.hash.slice(1) || "/" },
}),
chatPersona: (sessionID, name) => request("/api/chat/persona", { method: "POST", body: { session_id: sessionID, name } }),
chatUpdate: () => request("/api/chat/update"),
chatUpdateDefer: (snapshot) => request("/api/chat/update/defer", { method: "POST", body: { snapshot } }),
// Installing restarts archied, so it is allowed far longer than a normal
// request before the UI gives up.
chatUpdateInstall: (snapshot) => request("/api/chat/update/install", { method: "POST", body: { snapshot }, timeoutMs: 120000 }),
chatDangerous: () => request("/api/chat/dangerous"),
chatDangerousRequest: (kind, spec) =>
request(`/api/chat/dangerous/${encodeURIComponent(kind)}`, { method: "POST", body: { spec } }),
chatDangerousDecision: (id, decision) =>
request(`/api/chat/dangerous/${encodeURIComponent(id)}/decision`, { method: "POST", body: { decision } }),
// A server-sent event stream cannot be parsed as JSON and outlives a normal
// request, so the caller owns the abort controller and the timeout, and
// reads the body itself. Only the URL, headers, and failure shape are shared.
chatStream: (payload, { signal } = {}) =>
send("/api/chat/stream", {
method: "POST",
headers: { Accept: "text/event-stream", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
body: JSON.stringify(payload),
signal,
}),
};
/**
* Subscribe to archied's event stream. Returns an unsubscribe function.
* Reconnection is the browser's job via EventSource, but a closed stream is
* surfaced to the caller so the UI can show it rather than silently freezing.
*/
export function subscribeEvents(onEvent, onStateChange) {
const src = new EventSource("/events");
src.onopen = () => onStateChange?.("live");
src.onerror = () => onStateChange?.("reconnecting");
src.onmessage = (e) => {
try {
onEvent(JSON.parse(e.data));
} catch {
/* a malformed frame should not kill the stream */
}
};
return () => src.close();
}
export function subscribeLogs(onEntry, onStateChange) {
const src = new EventSource("/api/logs/stream");
src.onopen = () => onStateChange?.("live");
// onerror fires both for a drop the browser will retry and for one it has
// given up on; readyState is what tells them apart.
src.onerror = () => onStateChange?.(streamStateFor(src.readyState));
src.onmessage = (event) => {
try { onEntry(JSON.parse(event.data)); } catch { /* malformed log frame */ }
};
return () => src.close();
}
-90
View File
@@ -1,90 +0,0 @@
import { h } from "preact";
/**
* Arc gauge for a single headline percentage.
*
* A percentage that decides whether you need to act deserves more than a line
* of text -- the arc is readable at a glance from across a room, which a
* number is not. Colour follows the value, so "is this bad" is answered before
* the digits are read.
*/
export function Gauge({ value, label, size = 168 }) {
const pct = Math.max(0, Math.min(100, Number(value) || 0));
const stroke = pct >= 90 ? "var(--ok)" : pct >= 70 ? "var(--warn)" : "var(--danger)";
// 240-degree arc, opening downward, so the value reads left-to-right.
const r = 62;
const cx = size / 2;
const cy = size / 2;
const sweep = 240;
const start = 150;
const circumference = 2 * Math.PI * r * (sweep / 360);
const arc = (from, deg) => {
const a0 = (from * Math.PI) / 180;
const a1 = ((from + deg) * Math.PI) / 180;
const large = deg > 180 ? 1 : 0;
return [
`M ${cx + r * Math.cos(a0)} ${cy + r * Math.sin(a0)}`,
`A ${r} ${r} 0 ${large} 1 ${cx + r * Math.cos(a1)} ${cy + r * Math.sin(a1)}`,
].join(" ");
};
return (
<div className="gauge-wrap">
<svg className="gauge" viewBox={`0 0 ${size} ${size * 0.78}`} role="img" aria-label={`${label}: ${pct}%`}>
<path d={arc(start, sweep)} fill="none" stroke="var(--border)" stroke-width="12" stroke-linecap="round" />
<path
d={arc(start, sweep)}
fill="none"
stroke={stroke}
stroke-width="12"
stroke-linecap="round"
stroke-dasharray={circumference}
stroke-dashoffset={circumference * (1 - pct / 100)}
className="gauge-value"
/>
</svg>
<div className="gauge-center">
<div className="gauge-pct">{`${Math.round(pct)}%`}</div>
<div className="gauge-label">{label}</div>
</div>
</div>
);
}
/**
* Segmented proportional bar with a legend.
*
* segments: [{ label, value, kind }] where kind maps to a status token.
* Used for budget composition -- what is spent, committed and still free --
* because three related quantities are easier to compare in one bar than in
* three separate numbers.
*/
export function SegmentBar({ segments }) {
const total = segments.reduce((a, s) => a + (s.value || 0), 0) || 1;
return (
<div>
<div className="segbar">
{segments
.filter((s) => s.value > 0)
.map((s) => (
<span
key={s.label}
className={`segbar-part segbar-${s.kind || "idle"}`}
style={`width:${((s.value / total) * 100).toFixed(1)}%`}
title={`${s.label}: ${s.value}`}
/>
))}
</div>
<div className="segbar-legend">
{segments.map((s) => (
<span className="segbar-key" key={s.label}>
<span className={`segbar-dot segbar-${s.kind || "idle"}`} />
{s.label}
</span>
))}
</div>
</div>
);
}
-64
View File
@@ -1,64 +0,0 @@
import { h } from "preact";
/**
* Icon set.
*
* A single stroked 24-grid system rather than Unicode glyphs: glyphs render at
* different weights and baselines per platform, cannot inherit stroke width,
* and have no consistent optical size. Every icon here shares the same grid,
* stroke and cap style, so a row of them lines up.
*/
const paths = {
dashboard: '<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>',
chat: '<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v7a2.5 2.5 0 0 1-2.5 2.5H11l-4.5 4v-4.1A2.5 2.5 0 0 1 4 12.5z"/><path d="M8 8h8M8 11h5"/>',
tasks: '<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>',
logs: '<path d="M4 5h16M4 10h16M4 15h10M4 20h7"/>',
skills: '<path d="M12 3l2.6 5.6 6.1.8-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.4l6.1-.8z"/>',
workflows: '<path d="M4 7h6a3 3 0 0 1 3 3v4a3 3 0 0 0 3 3h4"/><path d="M17 4l3 3-3 3"/><path d="M7 21l-3-3 3-3"/>',
memory: '<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>',
channels: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>',
curators: '<circle cx="12" cy="12" r="8"/><path d="M12 8v4l3 2"/>',
captures: '<path d="M12 3v11M12 14l-4-4M12 14l4-4"/><path d="M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4"/>',
mappings: '<circle cx="5" cy="7" r="2"/><circle cx="5" cy="17" r="2"/><circle cx="19" cy="12" r="2"/><path d="M7 7l10 5M7 17l10-5"/>',
bindings: '<rect x="3" y="9" width="8" height="6" rx="2.5"/><rect x="13" y="9" width="8" height="6" rx="2.5"/><path d="M9 12h6"/>',
settings: '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>',
search: '<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>',
moon: '<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>',
sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>',
refresh: '<path d="M20 11a8 8 0 1 0-1.2 5.2"/><path d="M20 4v7h-7"/>',
bell: '<path d="M18 9a6 6 0 1 0-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M13.7 20a2 2 0 0 1-3.4 0"/>',
trendUp: '<path d="M4 17L10 11l4 4 6-6"/><path d="M14 7h6v6"/>',
trendDown: '<path d="M4 7l6 6 4-4 6 6"/><path d="M14 17h6v-6"/>',
check: '<path d="M4.5 12.5l5 5 10-11"/>',
close: '<path d="M6 6l12 12M18 6L6 18"/>',
"message-circle-plus": '<path d="M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"/><path d="M8 12h8"/><path d="M12 8v8"/>',
help: '<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.4"/><path d="M12 17.2h.01"/>',
};
/**
* Icon draws one glyph from the set. size is the rendered box; the grid is
* always 24 so stroke weight stays optically consistent at any size.
*
* The glyph bodies are the `paths` strings above, injected as raw SVG. They are
* in-repo constants and Preact cannot turn markup into elements, so re-authoring
* twenty multi-element glyphs as JSX would trade a data table for code without
* changing a single drawn pixel.
*/
export function Icon({ name, size = 18, className = "" }) {
return (
<svg
viewBox="0 0 24 24"
width={size}
height={size}
fill="none"
stroke="currentColor"
stroke-width="1.6"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
className={`ico ${className}`.trim()}
dangerouslySetInnerHTML={{ __html: paths[name] || paths.dashboard }}
/>
);
}
-65
View File
@@ -1,65 +0,0 @@
import { h } from "preact";
/**
* Shared log-entry rendering. Both the daemon-wide log page
* (ui/src/logs/logs.jsx) and a task's own attempt log
* (ui/src/tasks/task-logs.jsx) render the same Entry shape from
* internal/logging, so the row markup lives here rather than being
* duplicated a second time -- see CLAUDE.md's "extract to base on the
* second distinct consumer".
*/
// The level filter vocabulary. Server-side level filtering takes a CSV of
// levels (`splitCSV` in internal/webui/api_tasks_logs.go), so the combined
// options are a wire concern too, not a display choice. It lives here because
// both the daemon log page and a task attempt's log pane filter by level.
export const LOG_LEVELS = [
{ value: "", label: "All levels" },
{ value: "ERROR", label: "Errors" },
{ value: "WARN,ERROR", label: "Warnings and errors" },
{ value: "INFO,WARN,ERROR", label: "Info and above" },
{ value: "DEBUG", label: "Debug only" },
];
export function levelKind(level) {
switch ((level || "").toUpperCase()) {
case "ERROR":
return "danger";
case "WARN":
return "warn";
case "DEBUG":
return "idle";
default:
return "info";
}
}
export function LogRow({ entry }) {
const fields = entry.fields || {};
return (
<div className={`log-row log-${levelKind(entry.level)}`}>
<span className="log-time mono">{shortTime(entry.time)}</span>
<span className="log-level">{(entry.level || "info").toUpperCase()}</span>
<span className="log-body">
<span className="log-msg">{entry.message || entry.msg || ""}</span>
{Object.entries(fields).map(([k, v]) => (
<span className="log-field" key={k}>
<span className="log-field-key">{k}</span>
{String(fmtValue(v))}
</span>
))}
</span>
</div>
);
}
export function fmtValue(v) {
if (v == null) return "";
return typeof v === "object" ? JSON.stringify(v) : v;
}
export function shortTime(value) {
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) return "--:--:--";
return d.toTimeString().slice(0, 8);
}
-13
View File
@@ -1,13 +0,0 @@
import { h } from "preact";
/**
* Status pill: a small labeled badge whose color follows a semantic kind
* (ok/warn/danger/info/idle -- see css/pill.css). Extracted from 11
* independent, byte-identical local copies (tasks, logs, mappings,
* captures, settings, update-status, skills, dashboard, memory, channels,
* curators) per organisation.md's "extract on the second distinct
* consumer" rule -- archie-core-mlro.
*/
export function Pill({ text, kind = "idle" }) {
return <span className={`pill pill-${kind}`}>{text}</span>;
}
-68
View File
@@ -1,68 +0,0 @@
import { h } from "preact";
import { Icon } from "./icons.jsx";
/**
* A KPI tile: label, big value, trend against a stated comparison window, and
* a sparkline. The comparison line is not decoration -- a number without a
* baseline cannot be acted on, so `compare` is required.
*
* trend > 0 renders as an increase. `goodDirection` says whether that is good,
* because rising latency and rising success rate are not the same news.
*
* The headline value is rendered whatever its type, including 0 and "": a tile
* that showed a label and a comparison line with no number above them read as
* a broken dashboard on every fresh install.
*/
export function StatTile({ label, value, unit, trend, compare, series = [], goodDirection = "up" }) {
const dir = trend == null ? null : trend >= 0 ? "up" : "down";
const good = dir == null ? null : dir === goodDirection;
return (
<div className="card stat">
<div className="stat-head">
<span className="stat-label">{label}</span>
{dir ? (
<span className={`stat-trend ${good ? "up" : "down"}`}>
<Icon name={dir === "up" ? "trendUp" : "trendDown"} size={13} />
{`${Math.abs(trend).toFixed(1)}%`}
</span>
) : null}
</div>
<div className="stat-value">
{value}
{unit ? <span className="stat-unit">{unit}</span> : null}
</div>
{compare ? <div className="stat-compare">{compare}</div> : null}
{series.length > 1 ? <Sparkline series={series} stroke={good === false ? "var(--danger)" : "var(--ok)"} /> : null}
</div>
);
}
/**
* Inline SVG sparkline. Shows shape, not exact values -- the tile's headline
* number carries the precision.
*/
export function Sparkline({ series, stroke = "var(--ok)", width = 220, height = 34 }) {
const max = Math.max(...series, 1);
const min = Math.min(...series, 0);
const span = max - min || 1;
const step = series.length > 1 ? width / (series.length - 1) : width;
const points = series
.map((v, i) => `${(i * step).toFixed(1)},${(height - ((v - min) / span) * height).toFixed(1)}`)
.join(" ");
return (
<svg className="spark" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" aria-hidden="true">
<polyline
points={points}
fill="none"
stroke={stroke}
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
vector-effect="non-scaling-stroke"
/>
</svg>
);
}
+152
View File
@@ -0,0 +1,152 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import {
draftFromBinding,
emptyDraft,
type Binding,
type BindingDraft,
type MappingOption,
type WorkflowOption,
} from "./binding-draft";
/**
* The binding editor: name, the matcher source senders POST to, the field
* mapping, the workflow, an optional repo pin, and the shared secret their
* signature is checked against.
*/
const props = defineProps<{
/** null is a new binding; a binding is an edit. */
binding: Binding | null;
mappings: MappingOption[];
workflows: WorkflowOption[];
saving: boolean;
error: string | null;
}>();
const open = defineModel<boolean>("open", { required: true });
const emit = defineEmits<{ save: [draft: BindingDraft] }>();
// The draft is re-seeded on every open, so an edit that was cancelled -- or a
// save that failed -- never leaks into the next binding's form.
const draft = ref<BindingDraft>(emptyDraft());
watch(
open,
(isOpen) => {
if (isOpen) draft.value = props.binding ? draftFromBinding(props.binding) : emptyDraft();
},
{ immediate: true },
);
const title = computed(() => (props.binding ? "Edit binding" : "New binding"));
const secretHint = computed(() =>
props.binding
? "Leave blank to keep the current secret."
: "Senders sign with this via HMAC-SHA256.",
);
</script>
<template>
<Dialog v-model:open="open">
<!-- Seven fields make this taller than a short window; the dialog itself
scrolls rather than clipping its own Save button. -->
<DialogContent class="max-h-[85vh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>{{ title }}</DialogTitle>
<DialogDescription>
A binding is not armed until it is approved, and editing one drops it back to pending approval.
</DialogDescription>
</DialogHeader>
<Alert v-if="props.error" variant="destructive">
<AlertTitle>Could not save</AlertTitle>
<AlertDescription>{{ props.error }}</AlertDescription>
</Alert>
<form @submit.prevent="emit('save', draft)">
<FieldGroup>
<Field>
<FieldLabel for="binding-name">Name</FieldLabel>
<Input id="binding-name" v-model="draft.name" />
</Field>
<Field>
<FieldLabel for="binding-source">Source</FieldLabel>
<Input id="binding-source" v-model="draft.source" />
<FieldDescription>The path segment senders POST to, for example "sentry".</FieldDescription>
</Field>
<Field>
<FieldLabel for="binding-mapping">Field mapping</FieldLabel>
<Select v-model="draft.mappingId">
<SelectTrigger id="binding-mapping" class="w-full">
<SelectValue placeholder="Pick a saved mapping" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="mapping in props.mappings" :key="mapping.id" :value="String(mapping.id)">
{{ mapping.name }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel for="binding-workflow">Workflow</FieldLabel>
<Select v-model="draft.workflow">
<SelectTrigger id="binding-workflow" class="w-full">
<SelectValue placeholder="Pick a workflow" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="workflow in props.workflows" :key="workflow.id" :value="workflow.id">
{{ workflow.name }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field>
<div class="grid grid-cols-2 items-start gap-3">
<Field>
<FieldLabel for="binding-owner">Pinned owner</FieldLabel>
<Input id="binding-owner" v-model="draft.owner" />
</Field>
<Field>
<FieldLabel for="binding-repo">Pinned repo</FieldLabel>
<Input id="binding-repo" v-model="draft.repo" />
</Field>
</div>
<FieldDescription>
Optional. A pin is both halves or neither, so leave both blank to use the single configured repo.
</FieldDescription>
</Field>
<Field>
<FieldLabel for="binding-secret">Shared secret</FieldLabel>
<Input id="binding-secret" v-model="draft.secret" type="password" autocomplete="off" />
<FieldDescription>{{ secretHint }}</FieldDescription>
</Field>
</FieldGroup>
<DialogFooter class="mt-4">
<Button type="button" variant="outline" @click="open = false">Cancel</Button>
<Button type="submit" :disabled="props.saving">
<Spinner v-if="props.saving" data-icon="inline-start" />
{{ props.saving ? "Saving" : "Save" }}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { Check, Pencil, Trash2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { TableCell, TableRow } from "@/components/ui/table";
import BindingStatusBadge from "./BindingStatusBadge.vue";
import { matcherSource, repoPin, type Binding } from "./binding-draft";
/** One saved binding's summary row. */
const props = defineProps<{ binding: Binding }>();
const emit = defineEmits<{
edit: [binding: Binding];
approve: [binding: Binding];
delete: [binding: Binding];
}>();
</script>
<template>
<TableRow>
<TableCell class="font-medium">{{ props.binding.name }}</TableCell>
<TableCell class="font-mono text-fg-muted">{{ matcherSource(props.binding) }}</TableCell>
<TableCell>{{ props.binding.workflow || "—" }}</TableCell>
<TableCell class="font-mono text-fg-muted">{{ repoPin(props.binding) }}</TableCell>
<TableCell><BindingStatusBadge :status="props.binding.status" /></TableCell>
<TableCell>
<div class="flex items-center justify-end gap-1">
<Button variant="outline" size="sm" @click="emit('edit', props.binding)">
<Pencil data-icon="inline-start" />
Edit
</Button>
<!-- Only a pending binding can be approved. A draft is not a state you
approve from and an armed binding is already firing, so the button
would be a no-op -- or worse, a misleading one. -->
<Button v-if="props.binding.status === 'pending_approval'" size="sm" @click="emit('approve', props.binding)">
<Check data-icon="inline-start" />
Approve
</Button>
<Button variant="outline" size="sm" @click="emit('delete', props.binding)">
<Trash2 data-icon="inline-start" />
Delete
</Button>
</div>
</TableCell>
</TableRow>
</template>
+13
View File
@@ -0,0 +1,13 @@
<script setup lang="ts">
import { Badge } from "@/components/ui/badge";
import { statusKind, statusLabel } from "./binding-draft";
/** A binding's lifecycle state: draft, pending approval, or armed. The
* colour ramp is shared with every other status in the dashboard, so the
* same colour means the same thing here as it does on a task. */
const props = defineProps<{ status?: string }>();
</script>
<template>
<Badge :variant="statusKind(props.status)">{{ statusLabel(props.status) }}</Badge>
</template>
+112
View File
@@ -0,0 +1,112 @@
<script setup lang="ts">
import { Plus, RefreshCw } from "@lucide/vue";
import { onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import BindingEditor from "./BindingEditor.vue";
import BindingsTable from "./BindingsTable.vue";
import DeleteBindingDialog from "./DeleteBindingDialog.vue";
import type { Binding, BindingDraft } from "./binding-draft";
import { useBindings } from "./use-bindings";
/**
* Playbook bindings (t2db.8): tie a matcher + payload mapping + workflow
* together, with a draft -> pending_approval -> armed state machine so nothing
* self-arms. See docs/architecture/bindings.md and
* docs/prds/payload-field-mapping.md. Owner/Repo optionally pin a multi-repo
* deployment's dispatch target (archie-core-t2db.8's backend fix, commit
* ac42f64).
*/
const {
bindings,
mappings,
workflows,
failure,
actionFailure,
saving,
saveFailure,
load,
resetSaveFailure,
save,
approve,
remove,
} = useBindings();
const editorOpen = ref(false);
// null is a new binding; a binding is an edit.
const editing = ref<Binding | null>(null);
const deleting = ref<Binding | null>(null);
onMounted(load);
function startCreate(): void {
editing.value = null;
resetSaveFailure();
editorOpen.value = true;
}
function startEdit(binding: Binding): void {
editing.value = binding;
resetSaveFailure();
editorOpen.value = true;
}
async function handleSave(draft: BindingDraft): Promise<void> {
// The editor stays open on failure so the server's reason and the fields it
// is about are still on screen together.
if (await save(draft)) editorOpen.value = false;
}
async function handleDelete(binding: Binding): Promise<void> {
deleting.value = null;
await remove(binding);
}
</script>
<template>
<div>
<PageHeader
title="Playbook bindings"
subtitle="Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire."
>
<Button v-if="failure" @click="load">
<RefreshCw data-icon="inline-start" />
Retry
</Button>
<Button v-else @click="startCreate">
<Plus data-icon="inline-start" />
New binding
</Button>
</PageHeader>
<!-- A mutation that failed leaves the list on screen accurate, so its
failure sits beside the list rather than replacing it. -->
<Alert v-if="actionFailure" variant="destructive" class="mb-4">
<AlertTitle>That did not take effect</AlertTitle>
<AlertDescription>{{ actionFailure.message }}</AlertDescription>
</Alert>
<BindingsTable
:bindings="bindings"
:failure="failure"
@edit="startEdit"
@approve="approve"
@delete="deleting = $event"
/>
<BindingEditor
v-model:open="editorOpen"
:binding="editing"
:mappings="mappings"
:workflows="workflows"
:saving="saving"
:error="saveFailure"
@save="handleSave"
/>
<DeleteBindingDialog :binding="deleting" @confirm="handleDelete" @cancel="deleting = null" />
</div>
</template>
+86
View File
@@ -0,0 +1,86 @@
<script setup lang="ts">
import { computed } from "vue";
import { Card, CardContent } from "@/components/ui/card";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import BindingRow from "./BindingRow.vue";
import type { Binding } from "./binding-draft";
import type { LoadFailure } from "./use-bindings";
const props = defineProps<{
/** null means loading, [] means loaded and empty. */
bindings: Binding[] | null;
failure: LoadFailure | null;
}>();
const emit = defineEmits<{
edit: [binding: Binding];
approve: [binding: Binding];
delete: [binding: Binding];
}>();
const loading = computed(() => props.bindings === null);
const rows = computed(() => props.bindings ?? []);
// The failure description is the daemon's own words. "bindings not configured"
// answers a deployment with no binding store wired, and the operator can act on
// that, where a blanket "cannot reach archied" would be false about a daemon
// that answered.
const failureTitle = computed(() =>
props.failure?.kind === "unconfigured" ? "Bindings are not configured" : "Cannot reach archied",
);
</script>
<template>
<Empty v-if="props.failure">
<EmptyHeader>
<EmptyTitle>{{ failureTitle }}</EmptyTitle>
<EmptyDescription>{{ props.failure.message }}</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="!loading && !rows.length">
<EmptyHeader>
<EmptyTitle>No bindings yet</EmptyTitle>
<EmptyDescription>
Create one from a saved field mapping to turn a captured webhook into a workflow.
</EmptyDescription>
</EmptyHeader>
</Empty>
<Card v-else>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
<TableHead>Source</TableHead>
<TableHead>Workflow</TableHead>
<TableHead>Repo pin</TableHead>
<TableHead>Status</TableHead>
<TableHead />
</TableRow>
</TableHeader>
<TableBody>
<template v-if="loading">
<TableRow v-for="row in 3" :key="row">
<TableCell v-for="col in 6" :key="col"><Skeleton class="h-4 w-full" /></TableCell>
</TableRow>
</template>
<template v-else>
<BindingRow
v-for="binding in rows"
:key="binding.id"
:binding="binding"
@edit="emit('edit', $event)"
@approve="emit('approve', $event)"
@delete="emit('delete', $event)"
/>
</template>
</TableBody>
</Table>
</CardContent>
</Card>
</template>
+49
View File
@@ -0,0 +1,49 @@
<script setup lang="ts">
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import type { Binding } from "./binding-draft";
/** Confirming a delete, and nothing else. A binding cannot be recovered, so
* the action is behind a dialog rather than a click. */
const props = defineProps<{ binding: Binding | null }>();
const emit = defineEmits<{ confirm: [binding: Binding]; cancel: [] }>();
// The binding is handed back by value so the confirmation stands on its own:
// the dialog closes on the click, and the caller must not have to re-read
// state that the close has already cleared.
function confirm(): void {
if (props.binding) emit("confirm", props.binding);
}
// Reka closes the dialog on the action click, so this is what tells the caller
// to forget the pending binding -- whether the delete happened or not.
function onOpenChange(open: boolean): void {
if (!open) emit("cancel");
}
</script>
<template>
<AlertDialog :open="props.binding !== null" @update:open="onOpenChange">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete "{{ props.binding?.name }}"?</AlertDialogTitle>
<AlertDialogDescription>
It stops dispatching immediately and cannot be recovered. Captured events for its source keep
arriving; they just stop starting tasks.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" @click="confirm">Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</template>
+132
View File
@@ -0,0 +1,132 @@
/**
* The bindings vocabulary: the wire shapes the daemon returns, the draft the
* editor form edits, and the status ramp the list renders. Pure, so it reads
* (and would test) without the page's fetch wiring -- the same split
* binding-editor.jsx had from bindings.jsx in the Preact build.
*/
/**
* A binding as GET /api/bindings returns it. Secret is never returned: the
* daemon strips it from every read, and a blank secret on update is its
* server-side "keep the current one".
*/
export interface Binding {
id: number;
name: string;
matcher?: { source?: string };
mapping_id?: number;
workflow?: string;
/** A pin is a complete owner/repo pair or not a pin at all. */
owner?: string;
repo?: string;
status?: string;
version?: number;
}
/** The fields of GET /api/mappings this page needs. */
export interface MappingOption {
id: number;
name: string;
}
/** One entry of GET /api/workflows' `definitions`. */
export interface WorkflowOption {
id: string;
name: string;
enabled?: boolean;
}
/** The Badge variants a binding status maps onto. */
export type StatusKind = "ok" | "warn" | "idle";
const STATUS_LABELS: Record<string, string> = {
draft: "draft",
pending_approval: "pending approval",
armed: "armed",
};
const STATUS_KINDS: Record<string, StatusKind> = {
draft: "idle",
pending_approval: "warn",
armed: "ok",
};
/** A status the daemon grows later renders as itself in the neutral kind,
* rather than as an unlabelled pill. */
export function statusLabel(status?: string): string {
if (!status) return "unknown";
return STATUS_LABELS[status] ?? status;
}
export function statusKind(status?: string): StatusKind {
return STATUS_KINDS[status ?? ""] ?? "idle";
}
/**
* The editor's field state. mappingId is the select's string value because a
* select's model is its option values; the store's mapping_id is a number.
*/
export interface BindingDraft {
id: number | null;
name: string;
source: string;
mappingId: string;
workflow: string;
owner: string;
repo: string;
secret: string;
}
export function emptyDraft(): BindingDraft {
return {
id: null,
name: "",
source: "",
mappingId: "",
workflow: "",
owner: "",
repo: "",
secret: "",
};
}
export function draftFromBinding(binding: Binding): BindingDraft {
return {
id: binding.id,
name: binding.name,
source: binding.matcher?.source || "",
mappingId: binding.mapping_id ? String(binding.mapping_id) : "",
workflow: binding.workflow || "",
owner: binding.owner || "",
repo: binding.repo || "",
// Deliberately blank: the secret is never sent to the browser, and an
// empty one on update keeps whatever the sender already signs with.
secret: "",
};
}
/** The body POST /api/bindings and PATCH /api/bindings/{id} both accept. A
* blank mapping is 0, which the store rejects -- a binding with no mapping
* could never be dispatched. */
export function bindingPayload(draft: BindingDraft): Record<string, unknown> {
return {
name: draft.name,
matcher: { source: draft.source },
mapping_id: Number(draft.mappingId) || 0,
workflow: draft.workflow,
owner: draft.owner,
repo: draft.repo,
secret: draft.secret,
};
}
/** The repo pin a row shows, or an em dash when the binding takes the
* single-configured-repo default. */
export function repoPin(binding: Binding): string {
return binding.owner && binding.repo ? `${binding.owner}/${binding.repo}` : "—";
}
/** The matcher source a row shows: the path segment senders POST to. */
export function matcherSource(binding: Binding): string {
return binding.matcher?.source || "—";
}
-46
View File
@@ -1,46 +0,0 @@
import { h } from "preact";
import { Pill } from "../base/pill.jsx";
/**
* Pure rendering logic for the bindings editor, split out from
* bindings.jsx so it is unit-testable without the page's fetch wiring,
* mirroring mappings/mapping-editor.jsx.
*/
const STATUS_LABELS = {
draft: "draft",
pending_approval: "pending approval",
armed: "armed",
};
const STATUS_KINDS = {
draft: "idle",
pending_approval: "warn",
armed: "ok",
};
/** Renders a binding's Status as a labeled pill -- draft/pending_approval/armed. */
export function StatusPill({ status }) {
return <Pill text={STATUS_LABELS[status] || status} kind={STATUS_KINDS[status] || "idle"} />;
}
/** One saved binding's summary row for the bindings list. */
export function BindingRow({ binding: b, onEdit, onApprove, onDelete }) {
const repoPin = b.owner && b.repo ? `${b.owner}/${b.repo}` : "—";
return (
<tr>
<td>{b.name}</td>
<td className="mono">{b.matcher?.source || "—"}</td>
<td>{b.workflow}</td>
<td className="mono">{repoPin}</td>
<td><StatusPill status={b.status} /></td>
<td>
<button className="btn btn-small" type="button" onClick={() => onEdit?.(b)}>Edit</button>
{b.status === "pending_approval" && (
<button className="btn btn-small btn-primary" type="button" onClick={() => onApprove?.(b)}>Approve</button>
)}
<button className="btn btn-small" type="button" onClick={() => onDelete?.(b)}>Delete</button>
</td>
</tr>
);
}
-32
View File
@@ -1,32 +0,0 @@
/* Playbook binding editor: tie a matcher, a field mapping, and a
workflow together, gated by an explicit approval state machine. */
.binding-form {
margin-bottom: var(--sp-4);
padding: var(--sp-4);
}
.binding-form-row {
display: flex;
flex-direction: column;
gap: var(--sp-1);
margin-bottom: var(--sp-3);
font-size: var(--text-sm);
color: var(--fg-subtle);
}
.binding-input,
.binding-select {
padding: var(--sp-2);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--bg-raised);
color: var(--fg);
font: inherit;
}
.binding-error {
color: var(--danger, #e5484d);
font-size: var(--text-sm);
margin-bottom: var(--sp-3);
}
-221
View File
@@ -1,221 +0,0 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./bindings.css";
import { api } from "../base/api.jsx";
import { BindingRow } from "./binding-editor.jsx";
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
/**
* Playbook bindings (t2db.8): tie a matcher + payload mapping + workflow
* together, with a draft -> pending_approval -> armed state machine so
* nothing self-arms. See docs/architecture/bindings.md and
* docs/prds/payload-field-mapping.md. Owner/Repo optionally pin a
* multi-repo deployment's dispatch target (archie-core-t2db.8's backend
* fix, commit ac42f64).
*/
export function bindingsPage(query) {
return <BindingsApp query={query} />;
}
function emptyEditor() {
return {
id: null,
name: "",
source: "",
mappingId: "",
workflow: "",
owner: "",
repo: "",
secret: "",
actionError: null,
};
}
function BindingsApp({ query }) {
const [bindings, setBindings] = useState([]);
const [mappings, setMappings] = useState([]);
const [workflows, setWorkflows] = useState([]);
const [loadError, setLoadError] = useState(null);
const [editor, setEditor] = useState(null);
const load = async () => {
try {
const [bRes, mRes, wRes] = await Promise.all([api.bindings(), api.mappings(), api.workflows()]);
setBindings(bRes.bindings || []);
setMappings(mRes.mappings || []);
setWorkflows((wRes.definitions || []).filter((d) => d.enabled));
setLoadError(null);
} catch (err) {
setLoadError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
const startCreate = () => {
setEditor(emptyEditor());
};
const startEdit = (b) => {
setEditor({
id: b.id,
name: b.name,
source: b.matcher?.source || "",
mappingId: b.mapping_id ? String(b.mapping_id) : "",
workflow: b.workflow || "",
owner: b.owner || "",
repo: b.repo || "",
secret: "",
actionError: null,
});
};
const cancel = () => setEditor(null);
const save = async () => {
const body = {
name: editor.name,
matcher: { source: editor.source },
mapping_id: Number(editor.mappingId) || 0,
workflow: editor.workflow,
owner: editor.owner,
repo: editor.repo,
secret: editor.secret,
};
try {
if (editor.id) {
await api.bindingUpdate(editor.id, body);
} else {
await api.bindingCreate(body);
}
setEditor(null);
await load();
} catch (err) {
setEditor((prev) => ({ ...prev, actionError: String(err.message || err) }));
}
};
const approve = async (b) => {
try {
await api.bindingApprove(b.id);
await load();
} catch (err) {
setLoadError(String(err.message || err));
}
};
const remove = async (b) => {
if (!window.confirm(`Delete binding "${b.name}"?`)) return;
try {
await api.bindingDelete(b.id);
await load();
} catch (err) {
setLoadError(String(err.message || err));
}
};
const renderList = () => (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Playbook bindings</h1>
<p className="page-sub">Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.</p>
</div>
<div className="page-actions">
<button className="btn btn-primary" type="button" onClick={startCreate}>New binding</button>
</div>
</div>
{loadError ? (
<Empty title="Cannot reach archied" detail={loadError} />
) : bindings.length ? (
<div className="card">
<div className="table-scroll">
<table className="table">
<thead>
<tr>
{["Name", "Source", "Workflow", "Repo pin", "Status", ""].map((h, i) => (
<th key={i}>{h}</th>
))}
</tr>
</thead>
<tbody>
{bindings.map((b) => (
<BindingRow key={b.id} binding={b} onEdit={() => startEdit(b)} onApprove={() => approve(b)} onDelete={() => remove(b)} />
))}
</tbody>
</table>
</div>
</div>
) : (
<Empty title="No bindings yet" detail="Create one from a saved field mapping to turn a captured webhook into a workflow." />
)}
</div>
);
const renderEditor = () => (
<div>
<div className="page-head">
<div>
<h1 className="page-title">{editor.id ? "Edit binding" : "New binding"}</h1>
</div>
<div className="page-actions">
<button className="btn" type="button" onClick={cancel}>Cancel</button>
<button className="btn btn-primary" type="button" onClick={save}>Save</button>
</div>
</div>
{editor.actionError && <div className="binding-error">{editor.actionError}</div>}
<div className="card binding-form">
<label className="binding-form-row">
Name
<input className="binding-input" value={editor.name} onInput={(e) => setEditor((p) => ({ ...p, name: e.target.value }))} />
</label>
<label className="binding-form-row">
Source (the path segment senders POST to, e.g. "sentry")
<input className="binding-input" value={editor.source} onInput={(e) => setEditor((p) => ({ ...p, source: e.target.value }))} />
</label>
<label className="binding-form-row">
Field mapping
<select className="binding-select" value={editor.mappingId} onChange={(e) => setEditor((p) => ({ ...p, mappingId: e.target.value }))}>
<option value="">— pick a saved mapping —</option>
{mappings.map((m) => (
<option key={m.id} value={m.id}>{m.name}</option>
))}
</select>
</label>
<label className="binding-form-row">
Workflow
<select className="binding-select" value={editor.workflow} onChange={(e) => setEditor((p) => ({ ...p, workflow: e.target.value }))}>
<option value="">— pick a workflow —</option>
{workflows.map((w) => (
<option key={w.id} value={w.id}>{w.name}</option>
))}
</select>
</label>
<label className="binding-form-row">
Repo pin -- owner (optional; leave both blank for the single-configured-repo default)
<input className="binding-input" value={editor.owner} onInput={(e) => setEditor((p) => ({ ...p, owner: e.target.value }))} />
</label>
<label className="binding-form-row">
Repo pin -- repo
<input className="binding-input" value={editor.repo} onInput={(e) => setEditor((p) => ({ ...p, repo: e.target.value }))} />
</label>
<label className="binding-form-row">
Shared secret ({editor.id ? "leave blank to keep the current secret" : "senders sign with this via HMAC-SHA256"})
<input className="binding-input" type="password" value={editor.secret} onInput={(e) => setEditor((p) => ({ ...p, secret: e.target.value }))} />
</label>
</div>
</div>
);
return editor ? renderEditor() : renderList();
}
+126
View File
@@ -0,0 +1,126 @@
import { ref } from "vue";
import { api, ApiError } from "@/lib/api";
import {
bindingPayload,
type Binding,
type BindingDraft,
type MappingOption,
type WorkflowOption,
} from "./binding-draft";
/**
* Why the page has nothing to show. "unconfigured" is a daemon with no
* bindings store wired (501/503) -- the feature is off, which reads very
* differently from a daemon that answered badly.
*/
export type LoadFailureKind = "unconfigured" | "failed";
export interface LoadFailure {
kind: LoadFailureKind;
message: string;
}
function failureFor(err: unknown): LoadFailure {
const message = err instanceof Error && err.message ? err.message : String(err);
const status = err instanceof ApiError ? err.status : undefined;
return { kind: status === 501 || status === 503 ? "unconfigured" : "failed", message };
}
/**
* The bindings page's data: the three lists the list and the editor read, the
* load that fills them, and the three mutations. Every mutation goes through
* api.* so the CSRF and Content-Type headers are sent -- a bare fetch is
* refused 403/415 by archied's mutation guard.
*/
export function useBindings() {
// null means loading, [] means loaded and empty.
const bindings = ref<Binding[] | null>(null);
const mappings = ref<MappingOption[]>([]);
const workflows = ref<WorkflowOption[]>([]);
const failure = ref<LoadFailure | null>(null);
// A failed mutation is not a failed load: the list on screen is still
// accurate, so it keeps rendering and the failure lands beside it.
const actionFailure = ref<LoadFailure | null>(null);
const saving = ref(false);
const saveFailure = ref<string | null>(null);
async function load(): Promise<void> {
failure.value = null;
try {
const [b, m, w] = await Promise.all([
api.bindings<{ bindings?: Binding[] }>(),
api.mappings<{ mappings?: MappingOption[] }>(),
api.workflows<{ definitions?: WorkflowOption[] }>(),
]);
bindings.value = b.bindings || [];
mappings.value = m.mappings || [];
// Only enabled definitions are offerable: binding to a disabled one
// would persist a binding that can never dispatch.
workflows.value = (w.definitions || []).filter((d) => d.enabled);
} catch (err) {
failure.value = failureFor(err);
bindings.value = null;
}
}
function resetSaveFailure(): void {
saveFailure.value = null;
}
/** True when the binding was written, so the caller knows to close. */
async function save(draft: BindingDraft): Promise<boolean> {
saving.value = true;
saveFailure.value = null;
try {
const body = bindingPayload(draft);
if (draft.id) {
await api.bindingUpdate(String(draft.id), body);
} else {
await api.bindingCreate(body);
}
await load();
return true;
} catch (err) {
saveFailure.value = err instanceof Error && err.message ? err.message : String(err);
return false;
} finally {
saving.value = false;
}
}
async function approve(binding: Binding): Promise<void> {
actionFailure.value = null;
try {
await api.bindingApprove(String(binding.id));
await load();
} catch (err) {
actionFailure.value = failureFor(err);
}
}
async function remove(binding: Binding): Promise<void> {
actionFailure.value = null;
try {
await api.bindingDelete(String(binding.id));
await load();
} catch (err) {
actionFailure.value = failureFor(err);
}
}
return {
bindings,
mappings,
workflows,
failure,
actionFailure,
saving,
saveFailure,
load,
resetSaveFailure,
save,
approve,
remove,
};
}
-18
View File
@@ -1,18 +0,0 @@
// Which dashboard sections the serving process can actually back.
//
// From the UI cutover the dashboard is served by one composition: the
// extracted UI service, which holds two remote contracts (Gateway ChatContract
// and the State Store) and no daemon runtime handles. A section with nothing
// behind it still answers -- an empty list, a "disabled" marker, a 501 -- and
// the browser cannot tell that from a quiet deployment. GET /api/capabilities
// says which sections are backed here, and the nav drops the rest
// (archie-core-8cda.5.4).
// hiddenRoutes returns the paths whose section the server reported it cannot
// serve. An unreported section stays visible: a page that says "unavailable"
// is recoverable, a navigation entry that silently vanished is not, so an
// older server or a failed capabilities read shows everything.
export function hiddenRoutes(sections, routes) {
if (!sections) return [];
return routes.filter((r) => r.section && sections[r.section] === false).map((r) => r.path);
}
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { RefreshCw } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { load } from "./state";
/** Read the list again, for an operator who does not want to wait for the
* stream to invalidate it. */
</script>
<template>
<Button variant="outline" @click="load">
<RefreshCw data-icon="inline-start" />
Refresh
</Button>
</template>
+52
View File
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { ago } from "@/lib/format";
import CapturePayload from "./CapturePayload.vue";
import { selected, type Capture } from "./state";
/**
* One capture's payload and headers, opened from its row. A side panel rather
* than a taller row: a payload runs to thousands of characters, and the list
* has to stay a list while it is read.
*/
const open = computed({
get: () => selected.value !== null,
set: (value: boolean) => {
if (!value) selected.value = null;
},
});
// What the panel renders. The list drops the selection as soon as this sheet
// reports closed, and the panel stays mounted through the close animation, so
// reading the shared ref would blank it halfway out. Nothing goes stale here:
// a stored capture is never rewritten.
const shown = ref<Capture | null>(null);
watch(selected, (next) => {
if (next) shown.value = next;
});
</script>
<template>
<Sheet v-model:open="open">
<SheetContent class="w-full gap-0 sm:max-w-2xl">
<SheetHeader>
<SheetTitle>{{ shown?.source || "Unknown source" }}</SheetTitle>
<SheetDescription>
{{ ago(shown?.received_at) }} · {{ shown?.content_type || "no content type" }}
</SheetDescription>
</SheetHeader>
<Separator />
<ScrollArea class="min-h-0 flex-1">
<div class="flex flex-col gap-5 p-4">
<CapturePayload label="Payload" :raw="shown?.body" />
<CapturePayload label="Headers" :raw="shown?.headers" />
</div>
</ScrollArea>
</SheetContent>
</Sheet>
</template>
+30
View File
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { computed } from "vue";
import { prettyPrint } from "./capture-payload";
/**
* One labelled block of a capture: its body or its headers, as text. Both are
* stored as strings, valid JSON or not, so both go through the same reader.
*/
const props = defineProps<{ label: string; raw?: string }>();
const text = computed(() => prettyPrint(props.raw));
</script>
<template>
<section class="min-w-0">
<h3 class="mb-2 text-xs font-semibold tracking-[0.05em] text-fg-subtle uppercase">{{ label }}</h3>
<!--
Wrap rather than scroll sideways: a captured payload is mostly long
unbroken tokens (URLs, hashes, base64), and one of those on a single line
would push the panel's contents past its edge instead of being read.
-->
<p v-if="!text" class="text-sm text-fg-muted">(empty)</p>
<pre
v-else
class="rounded-sm border border-border-strong bg-muted p-3 font-mono text-xs whitespace-pre-wrap wrap-break-word"
>{{ text }}</pre
>
</section>
</template>
+52
View File
@@ -0,0 +1,52 @@
<script setup lang="ts">
import { ChevronRight } from "@lucide/vue";
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import { TableCell, TableRow } from "@/components/ui/table";
import { ago } from "@/lib/format";
import { selected, type Capture } from "./state";
/**
* One captured event. The row is the control, not a button sitting in one
* cell: opening the payload is the row's whole job, and a keyboard user has to
* reach what a mouse user clicks -- which is why it is focusable and both
* Enter and Space open it.
*/
const props = defineProps<{ capture: Capture }>();
const isSelected = computed(() => selected.value?.id === props.capture.id);
// The name is set here because role="button" makes the cells presentational:
// what a screen reader reads is this, not five unrelated columns.
const label = computed(() => `View the payload received from ${props.capture.source || "an unknown source"}`);
function open(): void {
selected.value = props.capture;
}
</script>
<template>
<TableRow
:data-state="isSelected ? 'selected' : undefined"
role="button"
tabindex="0"
aria-haspopup="dialog"
:aria-label="label"
class="cursor-pointer focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
@click="open"
@keydown.enter.prevent="open"
@keydown.space.prevent="open"
>
<TableCell class="font-mono">{{ props.capture.source || "(unknown)" }}</TableCell>
<TableCell :title="props.capture.received_at || ''">{{ ago(props.capture.received_at) }}</TableCell>
<!-- A stored capture carries no claim from a binding, so this reads Unbound
for every row: the column is where a claim would appear, not a state a
reader can act on today. -->
<TableCell><Badge variant="idle">Unbound</Badge></TableCell>
<TableCell class="font-mono">{{ props.capture.content_type || "—" }}</TableCell>
<TableCell class="text-right">
<ChevronRight class="size-4 text-fg-subtle" />
</TableCell>
</TableRow>
</template>
+13
View File
@@ -0,0 +1,13 @@
<script setup lang="ts">
import { Badge } from "@/components/ui/badge";
import { streamKind, streamState } from "./state";
/**
* The state of the stream that is supposed to be adding to this list. Without
* it a list that has stopped updating looks exactly like a quiet one.
*/
</script>
<template>
<Badge :variant="streamKind">{{ streamState }}</Badge>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import CapturesList from "./CapturesList.vue";
/** The captured events panel, with the note that qualifies everything inside
* it: what an operator reads here has already been through redaction. */
</script>
<template>
<Card>
<CardHeader>
<CardTitle>Recent captures</CardTitle>
<CardDescription>Newest first. Headers and payloads are redacted before they are stored.</CardDescription>
</CardHeader>
<CardContent>
<CapturesList />
</CardContent>
</Card>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import CaptureActions from "./CaptureActions.vue";
import CaptureStatus from "./CaptureStatus.vue";
/** The page's title, and what belongs beside it: where the stream has got to,
* and a way to ask for the list again. */
</script>
<template>
<div class="mb-5 flex flex-wrap items-start justify-between gap-5">
<div>
<h1 class="text-3xl font-semibold tracking-[-0.03em]">Event inspector</h1>
<p class="mt-2 text-sm text-fg-muted">Real inbound payloads archie has captured, most recent first.</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<CaptureStatus />
<CaptureActions />
</div>
</div>
</template>
+66
View File
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { Inbox, TriangleAlert } from "@lucide/vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";
import { Skeleton } from "@/components/ui/skeleton";
import { Table, TableBody, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import CaptureRow from "./CaptureRow.vue";
import { captures, enabled, error, loading } from "./state";
/**
* The captures, or the one thing that stands in for them: a read that failed,
* a deployment with no capture storage, a first read still in flight, or a
* window with nothing in it yet.
*/
// The receiver's path, held as a string rather than typed into the template:
// its source segment is angle-bracketed, which a template parser reads as a
// tag.
const webhookHint = "Point a webhook at /webhooks/capture/<source> and it will show up here.";
</script>
<template>
<!-- A failed read is about this page's request, not about capture, so it says
what the server said rather than borrowing an empty state. -->
<Alert v-if="error" variant="destructive">
<TriangleAlert />
<AlertTitle>Cannot reach archied</AlertTitle>
<AlertDescription>{{ error }}</AlertDescription>
</Alert>
<Empty v-else-if="!enabled">
<EmptyHeader>
<EmptyMedia variant="icon"><Inbox /></EmptyMedia>
<EmptyTitle>Capture is not configured</EmptyTitle>
<EmptyDescription>This deployment has no capture storage wired up.</EmptyDescription>
</EmptyHeader>
</Empty>
<div v-else-if="loading" class="flex flex-col gap-2">
<Skeleton v-for="row in 5" :key="row" class="h-9 w-full" />
</div>
<Empty v-else-if="!captures.length">
<EmptyHeader>
<EmptyMedia variant="icon"><Inbox /></EmptyMedia>
<EmptyTitle>No captures yet</EmptyTitle>
<EmptyDescription>{{ webhookHint }}</EmptyDescription>
</EmptyHeader>
</Empty>
<Table v-else>
<TableHeader>
<TableRow>
<TableHead>Source</TableHead>
<TableHead>Received</TableHead>
<TableHead>Binding</TableHead>
<TableHead>Content type</TableHead>
<TableHead class="w-10"><span class="sr-only">Payload</span></TableHead>
</TableRow>
</TableHeader>
<TableBody>
<CaptureRow v-for="capture in captures" :key="capture.id" :capture="capture" />
</TableBody>
</Table>
</template>
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import CaptureDetailSheet from "./CaptureDetailSheet.vue";
import CapturesCard from "./CapturesCard.vue";
import CapturesHeader from "./CapturesHeader.vue";
import { useCaptures } from "./state";
/**
* Event inspector (t2db.2): the operator-facing half of capture. Recent
* inbound events, newest first, with the full redacted payload explorable from
* each row -- see docs/prds/event-capture-storage.md for what the backend
* guarantees (retention, redaction, disk bounds). Composes the page; it holds
* no state of its own.
*/
useCaptures();
</script>
<template>
<CapturesHeader />
<CapturesCard />
<CaptureDetailSheet />
</template>
+13
View File
@@ -0,0 +1,13 @@
// prettyPrint indents valid JSON so a captured payload can be read as a
// structure rather than a line. A payload that is not JSON is returned as it
// arrived: the receiver stores whatever it is sent, JSON or not
// (docs/prds/webhook-intake-security.md), and the non-JSON case is the one an
// operator most needs to see.
export function prettyPrint(raw: string | undefined): string {
if (!raw) return "";
try {
return JSON.stringify(JSON.parse(raw), null, 2);
} catch {
return raw;
}
}
-75
View File
@@ -1,75 +0,0 @@
import { h, Fragment } from "preact";
import { ago } from "../base/format.jsx";
import { Pill } from "../base/pill.jsx";
/**
* One captured event's summary row, plus its expandable detail row when
* expanded is true. Split out from captures.js so it can be unit tested
* without the page's fetch/SSE wiring, mirroring tasks/task-row.js.
*/
export function CaptureRow({ capture: c, expanded, onToggle }) {
const handleKeyDown = (e) => {
if (e.key !== "Enter" && e.key !== " ") return;
e.preventDefault();
onToggle(e);
};
return (
<Fragment>
<tr
className="capture-row"
tabIndex="0"
aria-expanded={String(expanded)}
onClick={onToggle}
onKeyDown={handleKeyDown}
>
<td className="mono">{c.source || "(unknown)"}</td>
<td title={c.received_at || ""}>{ago(c.received_at)}</td>
<td><Pill text="Unbound" kind="idle" /></td>
<td className="mono">{c.content_type || "—"}</td>
<td>
<button className="btn btn-small" type="button">
{expanded ? "Hide" : "View"}
</button>
</td>
</tr>
{expanded && <CaptureDetailRow capture={c} />}
</Fragment>
);
}
export function CaptureDetailRow({ capture: c }) {
return (
<tr className="capture-detail-row">
<td colSpan="5">
<div className="capture-detail">
<div className="capture-detail-section">
<div className="capture-detail-title">Payload</div>
<PayloadView raw={c.body} />
</div>
<div className="capture-detail-section">
<div className="capture-detail-title">Headers</div>
<PayloadView raw={c.headers} />
</div>
</div>
</td>
</tr>
);
}
function PayloadView({ raw }) {
if (!raw) return <div className="capture-empty">(empty)</div>;
return <pre className="capture-payload">{prettyPrint(raw)}</pre>;
}
// prettyPrint indents valid JSON for readability; a non-JSON payload (the
// capture endpoint stores whatever arrives, JSON or not, per
// docs/prds/webhook-intake-security.md) is shown as-is rather than failing
// to render.
export function prettyPrint(raw) {
try {
return JSON.stringify(JSON.parse(raw), null, 2);
} catch {
return raw;
}
}
-61
View File
@@ -1,61 +0,0 @@
/* Event inspector: captured payloads, explorable per row. */
.capture-row {
cursor: pointer;
}
.capture-row:hover {
background: var(--bg-raised);
}
.capture-row:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.capture-detail-row td {
padding: var(--sp-3) var(--sp-3) var(--sp-4);
border-bottom: 1px solid var(--border);
}
.capture-detail {
display: grid;
gap: var(--sp-4);
grid-template-columns: 1fr 1fr;
}
.capture-detail-section {
min-width: 0;
}
.capture-detail-title {
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--fg-subtle);
margin-bottom: var(--sp-2);
}
.capture-payload {
background: var(--bg-raised);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
padding: var(--sp-3);
font-family: var(--font-mono);
font-size: var(--text-xs);
white-space: pre-wrap;
word-break: break-word;
max-height: 24rem;
overflow: auto;
}
.capture-empty {
color: var(--fg-muted);
font-size: var(--text-sm);
}
@media (max-width: 640px) {
.capture-detail {
grid-template-columns: 1fr;
}
}
-122
View File
@@ -1,122 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./captures.css";
import { api, subscribeEvents } from "../base/api.jsx";
import { CaptureRow } from "./capture-row.jsx";
import { Pill } from "../base/pill.jsx";
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
/**
* Event inspector (t2db.2): the operator-facing half of capture. Recent
* inbound events, newest first, with the full redacted payload explorable
* per row -- see docs/prds/event-capture-storage.md for what the backend
* guarantees (retention, redaction, disk bounds).
*
* Live updates ride the same /events SSE stream every other page uses
* (Server.emit publishes a "capture" kind event on every successful
* capture) rather than polling, so a captured event appears here without a
* manual refresh. That event is deliberately lightweight (id + source only,
* no payload -- see handleCapture's comment on why): it is treated purely
* as an invalidation signal, triggering a refetch of the authoritative list
* rather than being merged into local state directly.
*/
export function capturesPage(query) {
return <CapturesApp query={query} />;
}
function CapturesApp({ query }) {
const [captures, setCaptures] = useState([]);
const [expandedId, setExpandedId] = useState(null);
const [loadError, setLoadError] = useState(null);
const [enabled, setEnabled] = useState(true);
const [streamState, setStreamState] = useState({ text: "connecting", kind: "idle" });
const load = async () => {
try {
const res = await api.captures(100);
setEnabled(res.enabled !== false);
setCaptures(res.captures || []);
setLoadError(null);
} catch (err) {
setLoadError(String(err.message || err));
}
};
useEffect(() => {
load();
const unsubscribe = subscribeEvents(
(event) => {
if (event.kind !== "capture") return;
load();
},
(state) => {
setStreamState({
text: state,
kind: state === "live" ? "ok" : "warn",
});
}
);
return () => unsubscribe();
}, []);
const renderRows = () => {
if (loadError) {
return <Empty title="Cannot reach archied" detail={loadError} />;
}
if (!enabled) {
return <Empty title="Capture is not configured" detail="This deployment has no capture storage wired up." />;
}
if (!captures.length) {
return <Empty title="No captures yet" detail="Point a webhook at /webhooks/capture/<source> and it will show up here." />;
}
return (
<div className="table-scroll">
<table className="table">
<thead>
<tr>
{["Source", "Received", "Binding", "Content type", ""].map((h, i) => (
<th key={i}>{h}</th>
))}
</tr>
</thead>
<tbody>
{captures.map((c) => (
<CaptureRow
key={c.id}
capture={c}
expanded={expandedId === c.id}
onToggle={() => setExpandedId(expandedId === c.id ? null : c.id)}
/>
))}
</tbody>
</table>
</div>
);
};
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Event inspector</h1>
<p className="page-sub">Real inbound payloads archie has captured, most recent first.</p>
</div>
<div className="page-actions">
<Pill text={streamState.text} kind={streamState.kind} />
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="card">
{renderRows()}
</div>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
import { computed, onMounted, onUnmounted, ref } from "vue";
import { api, subscribeEvents } from "@/lib/api";
import type { StatusKind } from "@/lib/status";
import type { StreamState } from "@/lib/stream-state";
/**
* The event inspector's shared state.
*
* The list, the stream's state beside it and the sheet that shows one
* capture's payload all read it, so it lives in a module rather than being
* threaded down through a chain of props.
*/
/**
* One captured inbound event as the daemon stored it. Headers and body are
* already redacted (webhookguard.RedactPayload runs before InsertCapture), so
* what the page prints is what the store holds.
*/
export interface Capture {
id: number;
received_at?: string;
source?: string;
remote_addr?: string;
content_type?: string;
headers?: string;
body?: string;
authenticated?: boolean;
}
interface CapturesResponse {
captures?: Capture[];
enabled?: boolean;
}
// How many captures the list asks for. This is a recent-events window, not a
// log: retention and the disk bound are the daemon's (see
// docs/prds/event-capture-storage.md), so an operator looking for something
// older is looking in the wrong place rather than scrolling further.
const LIST_LIMIT = 100;
export const captures = ref<Capture[]>([]);
export const enabled = ref(true);
export const error = ref<string | null>(null);
export const loading = ref(true);
export const streamState = ref<StreamState | "connecting">("connecting");
/**
* The open row's capture, or null. Held by value rather than by id: the list
* is re-read on every capture event, so resolving an id again would close the
* sheet under an operator reading a capture that has just aged out of the
* window.
*/
export const selected = ref<Capture | null>(null);
/** The stream's state as a badge kind. A stream still connecting and one that
* has given up are different answers, so they do not share a tone. */
export const streamKind = computed<StatusKind>(() => {
if (streamState.value === "live") return "ok";
return streamState.value === "unavailable" ? "danger" : "warn";
});
/**
* load re-reads the list. It runs once on mount and again on every capture
* event, so it deliberately never re-enters the loading state: the skeletons
* are for a page with nothing on it yet, and a live refresh that put them back
* would replace the rows an operator is reading several times a minute.
*/
export async function load(): Promise<void> {
try {
const res = await api.captures<CapturesResponse>(LIST_LIMIT);
enabled.value = res.enabled !== false;
captures.value = res.captures || [];
error.value = null;
} catch (err) {
// The server's own message is the only part of a failure an operator can
// act on, so it is what the list says instead of the captures.
error.value = (err as Error).message || String(err);
} finally {
loading.value = false;
}
}
function handleEvent(raw: unknown): void {
// The "capture" event on /events carries the id and source only, no payload
// (see handleCapture), so it is an invalidation signal rather than data: it
// says a capture exists, and the authoritative list -- the only place the
// redacted payload lives -- is asked for again. Merging it into local state
// instead would put a row in the list with nothing behind it.
if ((raw as { kind?: string } | null)?.kind !== "capture") return;
void load();
}
let unsubscribe: (() => void) | undefined;
/** Owns the initial read and the live stream that invalidates it, for the
* page's lifetime. */
export function useCaptures(): void {
onMounted(() => {
void load();
unsubscribe = subscribeEvents(handleEvent, (state) => {
streamState.value = state;
});
});
onUnmounted(() => unsubscribe?.());
}
+64
View File
@@ -0,0 +1,64 @@
<script lang="ts">
/** A conversational front-end, as /api/channels serialises it. */
export interface Channel {
id?: string;
name: string;
state?: string;
configured?: boolean;
description?: string;
detail?: string;
reload_supported?: boolean;
}
</script>
<script setup lang="ts">
import { RefreshCw } from "@lucide/vue";
import { computed, ref } from "vue";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import type { StatusKind } from "@/lib/status";
const props = defineProps<{ channel: Channel }>();
const emit = defineEmits<{ reload: [id: string] }>();
// In-flight state rather than mutating the button's disabled attribute: the
// element is re-rendered by Vue, so a DOM write would be discarded.
const reloading = ref(false);
function tone(state: string | undefined, configured: boolean | undefined): StatusKind {
if (state === "running") return "ok";
if (state === "failed" || state === "degraded") return "warn";
return configured ? "idle" : "idle";
}
const label = computed(() => props.channel.state || (props.channel.configured ? "configured" : "stopped"));
async function reload() {
reloading.value = true;
try {
emit("reload", props.channel.id || props.channel.name.toLowerCase());
} finally {
reloading.value = false;
}
}
</script>
<template>
<Card>
<CardHeader>
<CardTitle>{{ props.channel.name }}</CardTitle>
<CardDescription v-if="props.channel.description">{{ props.channel.description }}</CardDescription>
<Badge :variant="tone(props.channel.state, props.channel.configured)">{{ label }}</Badge>
</CardHeader>
<CardContent>
<p v-if="props.channel.detail" class="mb-3 text-sm text-fg-muted">{{ props.channel.detail }}</p>
<Button v-if="props.channel.reload_supported" variant="outline" :disabled="reloading" @click="reload">
<RefreshCw data-icon="inline-start" />
Reload
</Button>
<p v-else class="text-sm text-fg-subtle">Reload requires a daemon restart for this adapter.</p>
</CardContent>
</Card>
</template>
+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">
import { RefreshCw } from "@lucide/vue";
import { onMounted, ref } from "vue";
import PageHeader from "@/base/PageHeader.vue";
import { Button } from "@/components/ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { api } from "@/lib/api";
import ChannelCard, { type Channel } from "./ChannelCard.vue";
/** The conversational front-ends Archie can be reached through. */
const channels = ref<Channel[]>([]);
const error = ref<string | null>(null);
async function load() {
try {
const res = await api.channels<{ channels?: Channel[] }>();
channels.value = res?.channels || [];
error.value = null;
} catch (err) {
error.value = String((err as Error).message || err);
}
}
/** Reload, then re-read: the adapter's new state is what the card shows, so a
* failed reload surfaces as the state it failed to leave. */
async function reload(id: string) {
try {
await api.channelReload(id);
} catch {
// Reported by the refreshed state below.
}
await load();
}
onMounted(load);
</script>
<template>
<div>
<PageHeader
title="Channels"
subtitle="The conversational front-ends Archie can be reached through."
>
<Button variant="outline" @click="load">
<RefreshCw data-icon="inline-start" />
Refresh
</Button>
</PageHeader>
<div class="grid grid-cols-1 gap-4 min-[1080px]:grid-cols-[repeat(auto-fit,minmax(340px,1fr))]">
<Empty v-if="error">
<EmptyHeader>
<EmptyTitle>Cannot reach archied</EmptyTitle>
<EmptyDescription>{{ error }}</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="!channels.length">
<EmptyHeader>
<EmptyTitle>No channels configured</EmptyTitle>
<EmptyDescription>
Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.
</EmptyDescription>
</EmptyHeader>
</Empty>
<ChannelCard v-for="channel in channels" v-else :key="channel.id || channel.name" :channel="channel" @reload="reload" />
</div>
</div>
</template>
-19
View File
@@ -1,19 +0,0 @@
/* Channels-only styles. */
.channel-card {
display: flex;
flex-direction: column;
gap: var(--sp-1);
}
.channel-desc {
color: var(--fg-muted);
font-size: var(--text-sm);
margin: 0;
}
.channel-detail {
color: var(--fg-subtle);
font-size: var(--text-xs);
margin: 0;
}
-101
View File
@@ -1,101 +0,0 @@
import { h } from "preact";
import { useState, useEffect } from "preact/hooks";
import "./channels.css";
import { api } from "../base/api.jsx";
import { Pill } from "../base/pill.jsx";
export function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function stateTone(state, configured) {
if (state === "running") return "ok";
if (state === "failed" || state === "degraded") return "warn";
return configured ? "idle" : "idle";
}
function ChannelsApp() {
const [channels, setChannels] = useState([]);
const [error, setError] = useState(null);
const load = async () => {
try {
const res = await api.channels();
setChannels(res?.channels || []);
setError(null);
} catch (err) {
setError(String(err.message || err));
}
};
useEffect(() => {
load();
}, []);
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Channels</h1>
<p className="page-sub">The conversational front-ends Archie can be reached through.</p>
</div>
<div className="page-actions">
<button className="btn" onClick={load}>Refresh</button>
</div>
</div>
<div className="grid grid-2">
{error ? (
<Empty title="Cannot reach archied" detail={error} />
) : channels.length === 0 ? (
<Empty
title="No channels configured"
detail="Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard."
/>
) : (
channels.map(channel => (
<div className="card channel-card" key={channel.id || channel.name}>
<div className="card-head">
<h3 className="card-title">{channel.name}</h3>
<Pill
text={channel.state || (channel.configured ? "configured" : "stopped")}
kind={stateTone(channel.state, channel.configured)}
/>
</div>
<p className="channel-desc">{channel.description}</p>
<p className="channel-detail">{channel.detail}</p>
{channel.reload_supported ? (
<button
className="btn"
onClick={async (event) => {
event.currentTarget.disabled = true;
try {
await api.channelReload(channel.id || channel.name.toLowerCase());
await load();
} catch (err) {
// skip
} finally {
if (event.currentTarget) event.currentTarget.disabled = false;
}
}}
>
Reload
</button>
) : (
<p className="channel-detail">Reload requires a daemon restart for this adapter.</p>
)}
</div>
))
)}
</div>
</div>
);
}
export function channelsPage(query) {
return <ChannelsApp query={query} />;
}
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
import ChatSessionList from "./ChatSessionList.vue";
import ChatSettings from "./ChatSettings.vue";
/**
* One row for everything that is not the conversation: which conversation is
* open, and the controls that are consulted rather than used constantly.
*/
</script>
<template>
<div class="flex items-center gap-2 border-b px-3 py-2">
<ChatSessionList />
<ChatSettings />
</div>
</template>
+43
View File
@@ -0,0 +1,43 @@
<script setup lang="ts">
import { cn } from "@/lib/utils";
import ChatMarkdown from "./ChatMarkdown.vue";
import ChatToolCall from "./ChatToolCall.vue";
import type { ChatToolCall as ToolCall } from "./state";
/**
* One message, from either side of the conversation. There is no speaker
* label: which side of the panel it sits on, and its fill, are what say who is
* talking. A trailing action arrives through the slot, so the retry the
* transcript offers belongs to the bubble rather than beside it.
*/
withDefaults(
defineProps<{
text: string;
tools?: ToolCall[];
assistant?: boolean;
/** The turn is still arriving: a tool call with no outcome is running. */
streaming?: boolean;
}>(),
{ tools: () => [], assistant: false, streaming: false },
);
</script>
<template>
<div class="flex" :class="assistant ? 'justify-start' : 'justify-end'">
<div
:class="
cn(
'max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]',
assistant ? 'bg-muted' : 'bg-primary/15',
)
"
>
<div v-if="assistant && tools.length" class="mb-2 grid gap-0.5 text-xs">
<ChatToolCall v-for="(tool, i) in tools" :key="i" :tool="tool" :streaming="streaming" />
</div>
<ChatMarkdown v-if="assistant" :text="text" />
<div v-else class="whitespace-pre-wrap">{{ text }}</div>
<slot />
</div>
</div>
</template>
+150
View File
@@ -0,0 +1,150 @@
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { applyCommand, isExactCommand } from "./commands";
import ChatSlashPalette from "./ChatSlashPalette.vue";
import {
closeCommandMenu,
commandMatches,
commandSelection,
commandSpecs,
composerText,
isCommandMenuOpen,
isSending,
moveCommandSelection,
sendMessage,
stopTurn,
syncCommandMenu,
} from "./state";
/**
* The composer: the text, the palette that completes a slash command, and the
* two actions. It stays writeable and focused while a turn is in flight --
* stopping is not the only thing an operator may want to do next -- so Stop is
* an addition to the row, never a replacement for Send.
*
* The textarea is stripped back to bare text inside the shell that carries the
* border and the fill: the field's own chrome would draw a second box inside
* the first. `bg-transparent!` beats the field's dark fill, which the dark
* variant would otherwise re-apply over the shell. It grows with what is typed
* and stops at `max-h-40`, so a long draft scrolls rather than eating the
* transcript above it.
*/
const props = defineProps<{ open: boolean }>();
const field = ref<{ $el: HTMLTextAreaElement } | null>(null);
function focus(): void {
field.value?.$el?.focus();
}
defineExpose({ focus });
// The panel stays mounted so the session survives navigation, so opening it is
// a prop change rather than a mount: focus the composer on that edge.
watch(
() => props.open,
(open) => {
if (open) void nextTick(focus);
},
);
// A finished turn leaves the caret in the composer, where the next message is
// typed, rather than on the button that sent the last one.
watch(isSending, (sending, wasSending) => {
if (wasSending && !sending) void nextTick(focus);
});
function onInput(event: Event): void {
const input = event.target as HTMLTextAreaElement;
composerText.value = input.value;
syncCommandMenu(input.value, input.selectionStart ?? input.value.length);
}
function choose(index: number): void {
const spec = 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;
closeCommandMenu();
void nextTick(() => {
input.focus();
input.setSelectionRange(cursor, cursor);
});
}
function onKeydown(event: KeyboardEvent): void {
const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey;
if (isCommandMenuOpen.value && commandMatches.value.length) {
// 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 && isExactCommand(commandSpecs.value, composerText.value)) {
event.preventDefault();
closeCommandMenu();
void sendMessage();
return;
}
if (event.key === "ArrowDown") {
event.preventDefault();
moveCommandSelection(1);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
moveCommandSelection(-1);
return;
}
if (event.key === "Enter" && plain) {
event.preventDefault();
choose(commandSelection.value);
return;
}
if (event.key === "Escape") {
// Consumed here: dismissing the palette must not also close the panel.
event.preventDefault();
closeCommandMenu();
return;
}
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
void sendMessage();
}
}
</script>
<template>
<div class="border-t p-3">
<div class="relative flex items-end gap-2 rounded-xl border border-border-strong bg-muted px-3 py-2.5">
<Textarea
ref="field"
:model-value="composerText"
rows="3"
placeholder="Message Archie, or type / for commands"
aria-label="Message Archie"
class="max-h-40 min-h-11 flex-1 resize-none border-0 bg-transparent! px-0 py-1 text-sm focus-visible:ring-0"
@input="onInput"
@keydown="onKeydown"
/>
<ChatSlashPalette
v-if="isCommandMenuOpen && commandMatches.length"
:matches="commandMatches"
:selection="commandSelection"
@choose="choose"
/>
<div class="flex flex-none items-center gap-2">
<!-- Only while a turn is arriving: a Stop with nothing to stop is a
button that lies about what the panel is doing. -->
<Button v-if="isSending" variant="outline" size="sm" @click="stopTurn">Stop</Button>
<Button size="sm" :disabled="isSending || !composerText.trim()" @click="sendMessage()">Send</Button>
</div>
</div>
</div>
</template>
+35
View File
@@ -0,0 +1,35 @@
<script setup lang="ts">
/**
* 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.
*/
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>
<div class="w-full self-center justify-self-center py-6 text-center">
<span
aria-hidden="true"
class="mx-auto mb-3 grid size-9 place-items-center rounded-xl border border-border-strong font-bold text-primary"
>A</span
>
<h2 class="text-lg font-semibold tracking-[-0.02em]">What are we working on?</h2>
<p class="mt-2 mb-4 text-sm text-fg-muted">Ask Archie anything, or start with one of these prompts.</p>
<div class="grid gap-2">
<button
v-for="prompt in PROMPTS"
:key="prompt"
type="button"
class="rounded-full border border-border bg-muted px-3 py-2 text-left text-sm text-fg-muted transition-colors hover:border-border-strong hover:text-foreground"
@click="emit('prompt', prompt)"
>
{{ prompt }}
</button>
</div>
</div>
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { MessageCircle, X } from "@lucide/vue";
import { cn } from "@/lib/utils";
import { CHAT_PANEL_ID } from "./state";
/**
* The launcher: the one control that opens and closes the panel, which is why
* there is no close button inside it.
*
* Both glyphs are stacked and cross-faded, so the button keeps one size and the
* swap cannot reflow the dock. It stays visible while the panel is open -- and
* on a phone, where the panel becomes a sheet above it, that visibility is the
* only way out.
*/
defineProps<{ open: boolean }>();
const emit = defineEmits<{ toggle: [] }>();
// Stacked in one cell, so switching glyphs changes opacity and rotation rather
// than layout.
function glyph(visible: boolean): string {
return cn(
"col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]",
visible ? "opacity-100" : "-rotate-45 scale-[0.7] opacity-0",
);
}
</script>
<template>
<button
type="button"
class="relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0"
:aria-label="open ? 'Close chat' : 'Chat with Archie'"
:title="open ? 'Close chat' : 'Chat with Archie'"
:aria-expanded="open"
:aria-controls="CHAT_PANEL_ID"
@click="emit('toggle')"
>
<span aria-hidden="true" :class="glyph(!open)">
<MessageCircle :size="22" />
</span>
<span aria-hidden="true" :class="glyph(open)">
<X :size="22" />
</span>
</button>
</template>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { MessageCirclePlus } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { panelTitle } from "./session";
import { currentSession, newChat, sessions } from "./state";
/**
* The panel's head: which conversation is open, and the one action that always
* applies to it.
*
* There is no close button. The launcher stays visible while the panel is open
* and is the single control that opens and closes it, so a second one here
* would be a duplicate that can drift out of step.
*/
</script>
<template>
<div class="flex items-center justify-between gap-2 border-b px-4 py-3">
<strong class="truncate text-sm font-semibold">{{ panelTitle(sessions, currentSession) }}</strong>
<Button variant="ghost" size="icon-sm" class="flex-none" title="New chat" aria-label="New chat" @click="newChat">
<MessageCirclePlus />
</Button>
</div>
</template>
+35
View File
@@ -0,0 +1,35 @@
<script setup lang="ts">
import type { ChatInline } from "./markdown";
/** One inline run: the spans of a paragraph, a heading or a table cell. */
defineProps<{ inline: ChatInline[] }>();
</script>
<template>
<template v-for="(span, i) in inline" :key="i">
<img
v-if="span.kind === 'image'"
:src="span.src"
:alt="span.alt"
loading="lazy"
class="my-1 block max-h-96 max-w-full cursor-pointer rounded-md border border-border bg-card object-contain"
/>
<del v-else-if="span.kind === 'del'">{{ span.text }}</del>
<strong v-else-if="span.kind === 'strong'">{{ span.text }}</strong>
<code
v-else-if="span.kind === 'code'"
class="rounded bg-foreground/10 px-1 py-0.5 font-mono text-[0.9em]"
>{{ span.text }}</code
>
<a
v-else-if="span.kind === 'link'"
:href="span.href"
target="_blank"
rel="noreferrer"
class="text-primary underline-offset-4 hover:underline"
>{{ span.text }}</a
>
<em v-else-if="span.kind === 'em'">{{ span.text }}</em>
<template v-else>{{ span.text }}</template>
</template>
</template>
+67
View File
@@ -0,0 +1,67 @@
<script setup lang="ts">
import { onUnmounted, ref, watch } from "vue";
import ChatFab from "./ChatFab.vue";
import ChatPanel from "./ChatPanel.vue";
import { escapeOwnedByLayer } from "./state";
/**
* Chat is a floating launcher and the panel it opens, not a route: the operator
* asks Archie about the page they are already on, so navigating must not close
* it and opening it must not replace the work that prompted the question.
*
* Deliberately not a modal: no scrim, no body scroll lock, no focus trap. The
* page stays readable, scrollable and clickable while the panel is open, which
* is what "ask about this page" requires.
*
* It hosts a single panel instance, so the session and its stream survive
* navigation rather than being rebuilt per page.
*
* This element is mounted outside the app shell: `.shell`'s backdrop-filter
* makes it a containing block for `position: fixed`, so a launcher nested
* inside it would anchor to the shell and ride off the bottom of a long page.
*/
const open = ref(false);
const fab = ref<{ $el: HTMLButtonElement } | null>(null);
function close(): void {
open.value = false;
// Focus goes back to the control that opened the panel; otherwise a keyboard
// user who dismisses it lands at the top of the document.
fab.value?.$el?.focus();
}
function toggle(): void {
if (open.value) close();
else open.value = true;
}
function onKeydown(event: KeyboardEvent): void {
// A focused control (the composer dismissing its palette, or the topbar
// search) already handled Escape via preventDefault; closing the panel too
// would make that menu impossible to dismiss on its own.
if (event.defaultPrevented || event.key !== "Escape") return;
// The same rule for a layer that owns Escape by being open rather than by
// holding focus: a popover portalled out of the panel listens on document
// too, and the panel registered its own handler first, so the flag is what
// keeps the innermost layer's dismissal from taking the panel with it.
if (escapeOwnedByLayer()) return;
close();
}
watch(open, (isOpen) => {
if (isOpen) document.addEventListener("keydown", onKeydown);
else document.removeEventListener("keydown", onKeydown);
});
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
</script>
<template>
<div
class="fixed right-6 bottom-6 z-40 max-[720px]:right-4 max-[720px]:bottom-4"
>
<ChatPanel :open="open" />
<ChatFab ref="fab" :open="open" @toggle="toggle" />
</div>
</template>
+74
View File
@@ -0,0 +1,74 @@
<script setup lang="ts">
import { computed } from "vue";
import ChatInline from "./ChatInline.vue";
import { parseMarkdown } from "./markdown";
/**
* A reply rendered as semantic HTML: headings, lists, quotes, fenced code,
* tables, inline emphasis. The parse is a computed, so a reply that grows a
* token at a time re-renders from the text it now has rather than accumulating
* markup.
*/
const props = defineProps<{ text: string }>();
const blocks = computed(() => parseMarkdown(props.text));
</script>
<template>
<div class="[overflow-wrap:anywhere]">
<template v-for="(block, i) in blocks" :key="i">
<pre
v-if="block.kind === 'pre'"
class="my-2 overflow-auto rounded-md border border-border bg-background/60 p-3"
><code class="font-mono text-[0.85em]">{{ block.code }}</code></pre>
<table v-else-if="block.kind === 'table'" class="my-3 w-full border-collapse text-[0.92em]">
<thead>
<tr>
<th
v-for="(cell, c) in block.head"
:key="c"
class="border border-border bg-muted px-2 py-1.5 text-left font-semibold"
>
<ChatInline :inline="cell" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, r) in block.rows" :key="r">
<td v-for="(cell, c) in row" :key="c" class="border border-border px-2 py-1.5 text-left">
<ChatInline :inline="cell" />
</td>
</tr>
</tbody>
</table>
<blockquote
v-else-if="block.kind === 'blockquote'"
class="my-2 border-l-[3px] border-primary pl-3 text-fg-muted"
>
<ChatInline :inline="block.inline" />
</blockquote>
<h1 v-else-if="block.kind === 'h1'" class="mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]">
<ChatInline :inline="block.inline" />
</h1>
<h2 v-else-if="block.kind === 'h2'" class="mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]">
<ChatInline :inline="block.inline" />
</h2>
<h3 v-else-if="block.kind === 'h3'" class="mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]">
<ChatInline :inline="block.inline" />
</h3>
<ul v-else-if="block.kind === 'ul'" class="my-2.5 flex list-disc flex-col gap-1 pl-5">
<li v-for="(item, n) in block.items" :key="n"><ChatInline :inline="item" /></li>
</ul>
<ol v-else-if="block.kind === 'ol'" class="my-2.5 flex list-decimal flex-col gap-1 pl-5">
<li v-for="(item, n) in block.items" :key="n"><ChatInline :inline="item" /></li>
</ol>
<p v-else-if="block.kind === 'p'" class="mb-2.5 last:mb-0"><ChatInline :inline="block.inline" /></p>
</template>
</div>
</template>
+26
View File
@@ -0,0 +1,26 @@
<script setup lang="ts">
import { ArrowUpRight } from "@lucide/vue";
/**
* A dashboard_navigate result: a clickable chip that routes the operator to a
* dashboard page. It is an action, not evidence, so it is styled as a button
* rather than a muted log line, and it visibly invites a click. It is the only
* clickable navigation surface in the transcript.
*
* A RouterLink rather than a `#/path` anchor: history routing means the server
* stores bare paths, and an anchor would reload the whole app to change one
* segment.
*/
defineProps<{ path: string; label?: string }>();
</script>
<template>
<RouterLink
:to="path"
:title="`Go to ${label || path}`"
class="inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-primary transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
>
<ArrowUpRight aria-hidden="true" class="size-3.5 shrink-0" />
<span class="truncate">{{ label || path }}</span>
</RouterLink>
</template>
+88
View File
@@ -0,0 +1,88 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import ChatBar from "./ChatBar.vue";
import ChatComposer from "./ChatComposer.vue";
import ChatHeader from "./ChatHeader.vue";
import ChatSessionActions from "./ChatSessionActions.vue";
import ChatTranscript from "./ChatTranscript.vue";
import { CHAT_PANEL_ID, composerText, currentSession, useChat } from "./state";
/**
* The panel: the shape that grows out of the launcher, holding the
* conversation. It composes the head, the bar, the transcript and the composer,
* and owns nothing but the morph and the composer's focus.
*
* It stays mounted while closed, so the session and any turn in flight survive
* a navigation. `inert` is what keeps an invisible panel out of the tab order
* and out of the pointer's way.
*/
const props = defineProps<{ open: boolean }>();
useChat();
const composer = ref<InstanceType<typeof ChatComposer> | null>(null);
/**
* The panel's shape.
*
* Closed, it is collapsed to a small round shape sitting exactly over the
* button; open, it is the full panel beside it. Scaling from the bottom-right
* corner and translating by the launcher's own width is what makes the button
* appear to become the panel, rather than a panel merely fading in next to it:
* scale, border-radius and position interpolate together. The contents fade in
* separately, below, once the shape has arrived.
*
* On a phone the sheet rises from the launcher instead of opening beside it, so
* the closed shape travels down toward the button rather than sideways. Those
* two values (56px launcher, 0.75rem gap) are the dock's own geometry; the
* launcher and every offset here are built from them.
*/
const panelShape = computed(() =>
props.open
? "pointer-events-auto rounded-lg opacity-100 [transform:none] [transition:opacity_160ms_cubic-bezier(0.4,0,0.2,1),transform_260ms_cubic-bezier(0.22,1,0.36,1),border-radius_260ms_cubic-bezier(0.22,1,0.36,1)]"
: "pointer-events-none rounded-full opacity-0 [transform:translateX(calc(56px_+_0.75rem))_scale(0.16)] max-[720px]:[transform:translateY(calc(56px_+_0.75rem))_scale(0.16)] [transition:opacity_140ms_cubic-bezier(0.4,0,0.2,1),transform_200ms_cubic-bezier(0.4,0,1,1),border-radius_200ms_cubic-bezier(0.4,0,1,1)]",
);
// The contents follow the shape rather than stretching with it: they fade in
// once the panel is most of the way open, so the morph reads as a container
// opening instead of a page being scaled up.
const contentFade = computed(() =>
props.open
? "opacity-100 transition-opacity duration-[160ms] ease-linear delay-[120ms]"
: "opacity-0 transition-opacity duration-[120ms] ease-linear",
);
function usePrompt(text: string): void {
composerText.value = text;
composer.value?.focus();
}
</script>
<template>
<aside
:id="CHAT_PANEL_ID"
aria-label="Chat with Archie"
:aria-hidden="open ? undefined : 'true'"
class="pointer-events-none absolute bottom-0 right-[calc(56px_+_0.75rem)] h-[min(640px,calc(100vh_-_3rem))] w-[min(440px,calc(100vw_-_56px_-_0.75rem_-_3rem))] max-[720px]:fixed max-[720px]:bottom-[calc(1rem_+_56px_+_0.75rem)] max-[720px]:left-4 max-[720px]:right-4 max-[720px]:h-[min(72vh,calc(100vh_-_2rem_-_56px_-_0.75rem))] max-[720px]:w-auto"
>
<div
:class="
panelShape +
' h-full w-full overflow-hidden border bg-popover shadow-[var(--shadow-md)] origin-bottom-right'
"
:inert="open ? undefined : true"
>
<!-- The conversation takes the rest of the column: without `min-h-0` on
the transcript it sizes to its content instead, and the composer
floats above dead space. -->
<div :class="contentFade + ' flex h-full min-h-0 flex-col overflow-hidden'">
<ChatHeader />
<ChatBar />
<ChatSessionActions v-if="currentSession" />
<ChatTranscript @prompt="usePrompt" />
<ChatComposer ref="composer" :open="open" />
</div>
</div>
</aside>
</template>
+47
View File
@@ -0,0 +1,47 @@
<script setup lang="ts">
import { ref } from "vue";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { promptSessionCommand, runSessionCommand, useEscapeLayer } from "./state";
/**
* The commands that act on the conversation itself rather than on what is being
* said: retry the last turn, undo it, rename the conversation, branch it, or
* look at what compressing it would drop.
*
* Each one is the same command the server accepts from any other channel, so
* this is a set of buttons over the slash surface rather than a second way to
* do the work. The popover closes as the command goes, because its answer comes
* back into the transcript and the status line, not into the menu.
*/
const open = ref(false);
useEscapeLayer(open);
function run(command: string): void {
open.value = false;
void runSessionCommand(command);
}
function prompt(command: string, message: string): void {
open.value = false;
promptSessionCommand(command, message);
}
</script>
<template>
<div class="flex items-center border-b px-3 py-1.5 text-xs">
<Popover v-model:open="open">
<PopoverTrigger as-child>
<Button variant="ghost" size="xs" class="text-fg-muted">Session actions</Button>
</PopoverTrigger>
<PopoverContent align="start" class="flex w-[min(22rem,72vw)] flex-wrap gap-1.5">
<Button variant="outline" size="sm" @click="run('/retry')">Retry</Button>
<Button variant="outline" size="sm" @click="run('/undo')">Undo</Button>
<Button variant="outline" size="sm" @click="prompt('/title', 'Session title')">Rename</Button>
<Button variant="outline" size="sm" @click="prompt('/branch', 'Branch name (optional)')">Branch</Button>
<Button variant="outline" size="sm" @click="run('/compress --preview')">Preview compression</Button>
</PopoverContent>
</Popover>
</div>
</template>
+36
View File
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { sessionTitle } from "./session";
import { currentSession, selectSession, sessions } from "./state";
/**
* Which conversation is open, and how to switch. A select rather than a list:
* the panel is small, and choosing between a handful of conversations is a
* control, not a place to be.
*
* reka-ui refuses an empty string as an item value -- it is how the component
* spells "nothing selected" -- and a session id is never empty, so the ids pass
* through unchanged.
*/
</script>
<template>
<div class="min-w-0 flex-1">
<Select
:model-value="currentSession"
:disabled="!sessions.length"
@update:model-value="selectSession(String($event))"
>
<SelectTrigger size="sm" class="w-full" aria-label="Conversation">
<SelectValue placeholder="No conversations yet" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="session in sessions" :key="session.session_id" :value="session.session_id">
{{ sessionTitle(session) }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
</template>
+108
View File
@@ -0,0 +1,108 @@
<script setup lang="ts">
import { Settings } from "@lucide/vue";
import { computed, ref } from "vue";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
currentModels,
selectedModel,
selectedPersona,
selectedProvider,
selectorData,
setModel,
setPersona,
setProvider,
statusText,
useEscapeLayer,
} from "./state";
/**
* The chat's own settings, folded away: what the panel is doing right now, and
* the three selectors the server offers.
*
* A Popover rather than a disclosure menu: it closes on an outside pointerdown
* and on focus leaving it, which is what a control that opens over the
* transcript has to do. It portals out of the panel, so the panel's overflow
* cannot clip it.
*
* reka-ui refuses an empty string as an item value (that is how it spells
* "nothing selected") while the wire reads an absent value as "use the
* default", so the sentinel converts at this boundary and the state below keeps
* the empty string.
*/
const DEFAULT = "__default__";
const open = ref(false);
useEscapeLayer(open);
const personaValue = computed(() => selectedPersona.value || DEFAULT);
const providerValue = computed(() => selectedProvider.value || DEFAULT);
const modelValue = computed(() => selectedModel.value || DEFAULT);
function clear(value: unknown): string {
return value === DEFAULT ? "" : String(value ?? "");
}
</script>
<template>
<Popover v-model:open="open">
<PopoverTrigger as-child>
<Button variant="ghost" size="icon-sm" aria-label="Chat settings" title="Chat settings">
<Settings />
</Button>
</PopoverTrigger>
<PopoverContent align="end" class="grid w-64 gap-3">
<span class="text-xs text-fg-subtle">{{ statusText }}</span>
<Field class="gap-1">
<FieldLabel class="text-xs text-fg-muted">Personality</FieldLabel>
<Select :model-value="personaValue" @update:model-value="setPersona(clear($event))">
<SelectTrigger size="sm" class="w-full" aria-label="Personality">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="DEFAULT">Default</SelectItem>
<SelectItem v-for="name in selectorData.personas || []" :key="name" :value="name">{{ name }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field v-if="(selectorData.providers || []).length" class="gap-1">
<FieldLabel class="text-xs text-fg-muted">Provider</FieldLabel>
<Select :model-value="providerValue" @update:model-value="setProvider(clear($event))">
<SelectTrigger size="sm" class="w-full" aria-label="Provider">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="DEFAULT">Default</SelectItem>
<SelectItem v-for="provider in selectorData.providers || []" :key="provider" :value="provider">
{{ provider }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
<Field class="gap-1">
<FieldLabel class="text-xs text-fg-muted">Model</FieldLabel>
<Select :model-value="modelValue" @update:model-value="setModel(clear($event))">
<SelectTrigger size="sm" class="w-full" aria-label="Model">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="DEFAULT">Default</SelectItem>
<SelectItem v-for="model in currentModels" :key="model" :value="model">{{ model }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</Field>
</PopoverContent>
</Popover>
</template>
+60
View File
@@ -0,0 +1,60 @@
<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { commandScrollTop } from "./command-scroll";
import type { ChatCommandSpec } from "./state";
/**
* 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.
*/
const props = defineProps<{ matches: ChatCommandSpec[]; selection: number }>();
const emit = defineEmits<{ choose: [index: number] }>();
const menu = ref<HTMLElement | null>(null);
// Arrow keys move the selection, and the list scrolls so the highlight stays
// visible once the matches run past the rows that fit. The arithmetic is
// command-scroll.ts's; this only applies what it returns. flush: 'post' so the
// option being measured is the one just selected, not the one leaving.
watch(
() => [props.selection, props.matches.length],
async () => {
await nextTick();
const el = menu.value;
const option = el?.children[props.selection] as HTMLElement | undefined;
if (!el || !option) return;
el.scrollTop = commandScrollTop({
scrollTop: el.scrollTop,
viewportHeight: el.clientHeight,
optionTop: option.offsetTop,
optionHeight: option.offsetHeight,
});
},
{ flush: "post" },
);
</script>
<template>
<div
ref="menu"
role="listbox"
aria-label="Commands"
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"
>
<button
v-for="(spec, index) in matches"
:key="spec.command"
type="button"
role="option"
:aria-selected="index === selection"
class="grid grid-cols-[minmax(8rem,14rem)_1fr] items-center gap-2.5 rounded-md border border-transparent px-2.5 py-2 text-left text-fg-muted hover:bg-muted hover:text-foreground aria-selected:border-border aria-selected:bg-muted aria-selected:text-foreground"
@mousedown.prevent
@click="emit('choose', index)"
>
<code class="truncate text-foreground">{{ spec.command }}</code>
<span class="truncate">{{ spec.description || spec.usage || "" }}</span>
</button>
</div>
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { Wrench } from "@lucide/vue";
import { computed } from "vue";
import { cn } from "@/lib/utils";
import ChatNavChip from "./ChatNavChip.vue";
import type { ChatToolCall } from "./state";
/**
* One tool call: the name, the parameters it was given, and what came back.
*
* A quiet log line rather than the point of the reply: it is evidence for the
* answer under it, so it is smaller and dimmer than the text it produced, and
* a failed call is the only thing here that raises its voice. An empty list
* renders nothing, so a turn that called no tools looks untouched.
*/
const props = defineProps<{
tool: ChatToolCall;
/** The turn is still arriving, so a call with no outcome yet is running. */
streaming?: boolean;
}>();
const name = computed(() => props.tool.name || props.tool.Name || props.tool.tool || "tool");
const parameters = computed(() => props.tool.parameters || props.tool.Parameters || "");
const failed = computed(() => Boolean(props.tool.err || props.tool.Err || props.tool.failed));
// A recorded turn reports its outcome in summary, a live frame in text, and a
// failure may only carry the error. Which words stand in for silence depends on
// whether the turn is still going: "running…" is true mid-turn and a lie after.
const summary = computed(() => {
const reported = props.tool.summary || props.tool.Summary || props.tool.text || props.tool.err || props.tool.Err;
if (reported) return reported;
if (!props.streaming) return "done";
return failed.value ? "failed" : "running…";
});
</script>
<template>
<ChatNavChip v-if="tool.path" :path="tool.path" :label="tool.label" />
<div v-else class="flex items-baseline gap-1.5 [overflow-wrap:anywhere]">
<Wrench aria-hidden="true" class="size-3.5 shrink-0 self-center text-fg-subtle" />
<span class="font-semibold text-foreground">{{ name }}</span>
<code v-if="parameters" class="font-mono text-[0.95em] text-fg-subtle">{{ parameters }}</code>
<span :class="cn('text-fg-muted', failed && 'text-danger')">{{ summary }}</span>
</div>
</template>
+82
View File
@@ -0,0 +1,82 @@
<script setup lang="ts">
import { computed } from "vue";
import { Button } from "@/components/ui/button";
import {
MessageScroller,
MessageScrollerButton,
MessageScrollerContent,
MessageScrollerItem,
MessageScrollerProvider,
MessageScrollerViewport,
} from "@/components/ui/message-scroller";
import ChatBubble from "./ChatBubble.vue";
import ChatEmptyState from "./ChatEmptyState.vue";
import { messages, sendMessage, streamingTurn, type ChatMessage } from "./state";
/**
* The conversation: the messages so far, the turn still arriving, and what the
* panel says before either exists.
*
* The scroller follows the tail, and stops following the moment the reader
* scrolls up rather than yanking them back on every streamed token. That is
* what MessageScroller is for, so it is used rather than re-derived: an
* earlier version set scrollTop from a watcher, which has neither the
* "reader scrolled away" state nor a way back down.
*/
const emit = defineEmits<{ prompt: [text: string] }>();
function parts(message: ChatMessage) {
const from = message.from ?? message.From ?? "";
// Anything this browser's composer did not send is Archie's answer.
return {
text: message.text ?? message.Text ?? "",
tools: message.tool_calls || message.ToolCalls || [],
assistant: from !== "web",
};
}
const bubbles = computed(() => messages.value.map(parts));
</script>
<template>
<MessageScrollerProvider auto-scroll default-scroll-position="end">
<MessageScroller class="min-h-0 flex-1">
<MessageScrollerViewport>
<MessageScrollerContent class="gap-4 p-4">
<ChatEmptyState v-if="!bubbles.length && !streamingTurn" @prompt="emit('prompt', $event)" />
<template v-else>
<MessageScrollerItem v-for="(bubble, i) in bubbles" :key="i" :message-id="`m${i}`">
<ChatBubble :text="bubble.text" :tools="bubble.tools" :assistant="bubble.assistant" />
</MessageScrollerItem>
<!-- The live turn is a bubble like any other, so what arrives is
rendered by the same rules as what was already there. It is the
scroll anchor while it streams. -->
<MessageScrollerItem v-if="streamingTurn" message-id="streaming" scroll-anchor>
<ChatBubble
:text="streamingTurn.text || '…'"
:tools="streamingTurn.tools"
assistant
streaming
>
<Button
v-if="streamingTurn.isError && streamingTurn.turn"
variant="outline"
size="sm"
class="mt-2"
@click="sendMessage({ turn: streamingTurn.turn })"
>
Retry
</Button>
</ChatBubble>
</MessageScrollerItem>
</template>
</MessageScrollerContent>
</MessageScrollerViewport>
<MessageScrollerButton />
</MessageScroller>
</MessageScrollerProvider>
</template>
+17
View File
@@ -0,0 +1,17 @@
import { randomUUID } from "@/lib/uuid";
const CHANNEL_KEY = "archie.web.chat.channel";
/**
* The browser's chat identity. The server keys a conversation on the channel
* alone (the browser has no threading), so this is persisted: a reload rejoins
* the conversation instead of starting a second one beside it.
*/
export function channelID(): string {
let id = localStorage.getItem(CHANNEL_KEY);
if (!id) {
id = randomUUID();
localStorage.setItem(CHANNEL_KEY, id);
}
return id;
}
-24
View File
@@ -1,24 +0,0 @@
import { randomUUID } from "../base/uuid.jsx";
export function newChatTurn(text) {
return { text, sourceID: randomUUID() };
}
export function retryChatTurn(turn) {
return { ...turn };
}
// resolveTurn decides what to send: a real retry descriptor's original turn,
// or a fresh turn built from the composer text. `retry` is untrusted here --
// a DOM event handler bound as `el.onclick = sendMessage` (rather than
// `() => sendMessage()`) hands the click's MouseEvent to this function as
// `retry`, and a MouseEvent is truthy but has no `.turn`. Only an object
// carrying a `turn.text` string counts as a genuine retry; anything else
// (including no argument) falls back to the composer text instead of
// throwing on a missing property.
export function resolveTurn(retry, composerValue) {
const isRetry = !!(retry && typeof retry === "object" && retry.turn && typeof retry.turn.text === "string");
const text = isRetry ? retry.turn.text : composerValue.trim();
const turn = isRetry ? retryChatTurn(retry.turn) : newChatTurn(text);
return { text, turn, isRetry };
}
-12
View File
@@ -1,12 +0,0 @@
import { randomUUID } from "../base/uuid.jsx";
const CHANNEL_KEY = "archie.web.chat.channel";
export function channelID() {
let id = localStorage.getItem(CHANNEL_KEY);
if (!id) {
id = randomUUID();
localStorage.setItem(CHANNEL_KEY, id);
}
return id;
}
-15
View File
@@ -1,15 +0,0 @@
// updateUnavailableMessage decides what -- if anything -- refreshUpdate should
// show when fetching /api/chat/update fails.
//
// A 501 means the release-update-check feature simply isn't configured for
// this deployment (chat.telegram.update_check_command is unset) -- a normal
// state, the same category as an unconfigured chat channel, not a fetch
// failure. It gets no visible banner: callers should render nothing.
//
// Any other error (network failure, 500, ...) is a genuine problem and gets a
// clear, fixed human message -- never the raw fetch error text, which leaks
// implementation detail like literal HTTP status codes into the UI.
export function updateUnavailableMessage(err) {
if (err?.status === 501) return null;
return "Could not check for updates.";
}
-226
View File
@@ -1,226 +0,0 @@
/* The panel's own column. ChatApp is mounted in a ~440px launcher panel, never
on a page, so there is one column and every row earns its height
(archie-core-hesx). */
.chat-panel-content {
display: grid;
/* header, bar, then the conversation takes the rest: without the third
track the transcript sized to its content and left the composer floating
above dead space. */
grid-template-rows: auto auto minmax(0, 1fr);
flex: 1 1 auto;
min-height: 0;
overflow: hidden;
}
/* One row for everything that is not the conversation: which conversation,
a new one, and the model controls folded away behind a disclosure. */
.chat-bar {
display: flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-bottom: 1px solid var(--border);
}
.chat-session-switch {
flex: 1 1 auto;
min-width: 0;
}
.chat-session-switch select {
width: 100%;
background: var(--surface-hover);
color: var(--fg);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
font: inherit;
font-size: var(--text-sm);
}
.chat-new,
.chat-settings > summary {
flex: none;
}
.chat-settings {
position: relative;
flex: none;
}
.chat-settings > summary {
display: grid;
place-items: center;
width: 32px;
height: 32px;
border-radius: var(--radius-sm);
color: var(--fg-muted);
cursor: pointer;
list-style: none;
}
.chat-settings > summary::-webkit-details-marker {
display: none;
}
.chat-settings > summary:hover {
background: var(--surface-hover);
color: var(--fg);
}
/* Opens over the transcript rather than pushing it down: the panel is short
and the conversation should not jump when the controls are consulted. */
.chat-settings-body {
position: absolute;
top: calc(100% + var(--sp-2));
right: 0;
z-index: 2;
display: grid;
gap: var(--sp-3);
width: 15rem;
padding: var(--sp-3);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-md);
box-shadow: var(--shadow-md);
}
.chat-settings-body label {
display: grid;
gap: var(--sp-1);
font-size: var(--text-xs);
color: var(--fg-muted);
}
.chat-settings-body .chat-select {
width: 100%;
}
.chat-layout {
display: grid;
min-height: 0;
overflow: hidden;
}
.chat-workspace {
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
min-width: 0;
overflow: hidden;
}
.chat-workspace-head {
display: flex;
align-items: center;
gap: var(--sp-2);
padding: var(--sp-2) var(--sp-3);
border-bottom: 1px solid var(--border);
font-size: var(--text-xs);
}
.chat-update-panel { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin: 0 0 .75rem; padding: .7rem .9rem; border: 1px solid var(--border); border-radius: .75rem; color: var(--fg-muted); font-size: .8rem; }
.chat-update-panel > div:first-child { display: grid; gap: .2rem; }
.chat-update-panel strong { color: var(--fg); }
.chat-update-actions { display: flex; gap: .45rem; flex-shrink: 0; }
.chat-dangerous-panel { flex: 0 0 auto; margin: 0 0 .75rem; padding: .8rem .9rem; border: 1px solid color-mix(in srgb, var(--danger) 45%, var(--border)); border-radius: .75rem; }
.chat-dangerous-head, .chat-dangerous-controls, .chat-dangerous-pending { display: flex; align-items: center; justify-content: space-between; gap: .6rem; }
.chat-dangerous-head { margin-bottom: .7rem; }
.chat-dangerous-controls { align-items: stretch; flex-wrap: wrap; }
.chat-dangerous-controls > div { display: flex; gap: .45rem; flex: 1 1 18rem; }
.chat-dangerous-input { min-width: 0; flex: 1; padding: .5rem .65rem; background: var(--surface-hover); color: var(--fg); border: 1px solid var(--border-strong); border-radius: .5rem; font: inherit; }
.chat-dangerous-pending-list { display: grid; gap: .45rem; margin-top: .75rem; }
.chat-dangerous-pending { padding-top: .55rem; border-top: 1px solid var(--border); color: var(--fg-muted); font-size: .8rem; }
.chat-session-list { display: grid; gap: .35rem; margin-top: 1rem; }
.chat-session { display: grid; gap: .25rem; text-align: left; background: transparent; color: var(--fg-muted); border: 1px solid transparent; border-radius: .65rem; padding: .7rem; cursor: pointer; }
.chat-session:hover, .chat-session.active { background: var(--surface-hover); color: var(--fg); border-color: var(--border-strong); }
.chat-session span { font-size: .72rem; }
.chat-session-tools { position: relative; margin-left: .6rem; color: var(--fg-muted); font-size: .78rem; }
.chat-session-tools summary { cursor: pointer; }
.chat-session-tool-list { position: absolute; z-index: 2; right: 0; top: calc(100% + .45rem); display: flex; flex-wrap: wrap; gap: .35rem; width: min(22rem, 72vw); padding: .55rem; background: var(--surface); border: 1px solid var(--border-strong); border-radius: .65rem; box-shadow: 0 .7rem 2rem color-mix(in srgb, #000 30%, transparent); }
.chat-select { background: var(--surface-hover); color: var(--fg); border: 1px solid var(--border-strong); border-radius: .5rem; padding: .5rem .65rem; }
.chat-transcript { overflow: auto; padding: var(--sp-4); display: grid; align-content: start; gap: var(--sp-4); }
.chat-empty-state { align-self: center; justify-self: center; width: 100%; padding: var(--sp-5) 0; text-align: center; }
.chat-empty-mark { display: grid; place-items: center; width: 2.2rem; height: 2.2rem; margin: 0 auto var(--sp-3); border: 1px solid var(--border-strong); border-radius: .8rem; color: var(--accent); font-weight: 700; }
.chat-empty-state h2 { margin: 0; font-size: var(--text-lg); letter-spacing: -.02em; }
.chat-empty-state p { margin: var(--sp-2) 0 var(--sp-4); color: var(--fg-muted); font-size: var(--text-sm); }
.chat-prompt-grid { display: grid; gap: var(--sp-2); }
.chat-prompt { padding: var(--sp-2) var(--sp-3); font-size: var(--text-sm); text-align: left; border: 1px solid var(--border); border-radius: 999px; background: var(--surface-hover); color: var(--fg-muted); cursor: pointer; }
.chat-prompt:hover { color: var(--fg); border-color: var(--border-strong); }
.chat-bubble-row { display: flex; }
.chat-bubble-row.user { justify-content: flex-end; }
.chat-bubble { max-width: min(78ch, 86%); padding: .8rem 1rem; border-radius: .85rem; background: var(--surface-hover); line-height: 1.5; }
.chat-bubble-row.user .chat-bubble { background: color-mix(in srgb, var(--accent) 18%, var(--surface)); }
.chat-bubble-meta { font-size: .7rem; color: var(--fg-muted); margin-bottom: .3rem; }
.chat-bubble-text { white-space: pre-wrap; overflow-wrap: anywhere; }
.chat-bubble-text p { margin: 0 0 .7rem; }
.chat-bubble-text p:last-child { margin-bottom: 0; }
.chat-bubble-text h1, .chat-bubble-text h2, .chat-bubble-text h3 { margin: .2rem 0 .6rem; line-height: 1.2; letter-spacing: -.02em; }
.chat-bubble-text h1 { font-size: 1.25rem; }
.chat-bubble-text h2 { font-size: 1.1rem; }
.chat-bubble-text h3 { font-size: 1rem; }
.chat-bubble-text ul, .chat-bubble-text ol { margin: .25rem 0 .75rem; padding-left: 1.35rem; }
.chat-bubble-text blockquote { margin: .5rem 0; padding: .35rem .75rem; border-left: 3px solid var(--accent); color: var(--fg-muted); }
.chat-bubble-text code { padding: .1rem .3rem; border-radius: .3rem; background: color-mix(in srgb, var(--fg) 10%, transparent); font-size: .9em; }
.chat-bubble-text pre { margin: .6rem 0; padding: .75rem; overflow: auto; border: 1px solid var(--border); border-radius: .5rem; background: color-mix(in srgb, var(--surface) 75%, #000); }
.chat-bubble-text pre code { padding: 0; background: transparent; }
.chat-bubble-text a { color: var(--accent); }
.chat-media-img { max-width: 100%; max-height: 24rem; border-radius: .5rem; margin: .4rem 0; display: block; border: 1px solid var(--border); object-fit: contain; background: var(--surface); cursor: pointer; }
.chat-bubble-text table { width: 100%; margin: .7rem 0; border-collapse: collapse; font-size: .92em; }
.chat-bubble-text th, .chat-bubble-text td { padding: .45rem .6rem; text-align: left; border: 1px solid var(--border); }
.chat-bubble-text th { color: var(--fg); background: color-mix(in srgb, var(--surface) 70%, transparent); font-weight: 700; }
/* Tool activity: a quiet log above the answer it produced. It is deliberately
smaller and dimmer than the reply -- it is evidence, not the point. An empty
list renders nothing, so a turn that called no tools looks untouched. */
.chat-tools { display: grid; gap: .2rem; margin-bottom: .5rem; font-size: .78rem; }
.chat-tools:empty { display: none; }
.chat-tool { display: flex; gap: .4rem; align-items: baseline; color: var(--fg-muted); overflow-wrap: anywhere; }
.chat-tool-name { color: var(--fg); font-weight: 600; }
.chat-tool.failed .chat-tool-summary { color: var(--danger); }
/* A dashboard_navigate result: a clickable chip that routes the operator to a
dashboard page. It is an action, not evidence, so it is styled as a button
beside the tool list rather than a muted log line, and it visibly invites a
click. It is the only clickable navigation surface in the transcript. */
.chat-nav-chip {
display: inline-flex;
align-items: center;
gap: .4rem;
padding: .4rem .7rem;
border-radius: 999px;
border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--border));
background: var(--accent-soft);
color: var(--accent);
font-size: .82rem;
font-weight: 600;
cursor: pointer;
transition: background var(--transition), border-color var(--transition), color var(--transition);
}
.chat-nav-chip:hover {
border-color: var(--accent);
background: color-mix(in srgb, var(--accent) 16%, var(--surface));
}
.chat-nav-chip:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.chat-nav-chip-icon { font-size: .8rem; line-height: 1; }
.chat-compose { padding: var(--sp-3); border-top: 1px solid var(--border); }
/* Text and actions share one row: the buttons sit at the right of the input,
not on a line of their own under it. */
.chat-composer-shell { position: relative; display: flex; align-items: flex-end; gap: var(--sp-2); padding: .7rem .8rem; background: var(--surface-hover); border: 1px solid var(--border-strong); border-radius: .9rem; }
.chat-composer { flex: 1 1 auto; min-width: 0; min-height: 2.6rem; resize: none; box-sizing: border-box; background: transparent; color: var(--fg); border: 0; padding: .25rem 0; font: inherit; }
.chat-composer:focus { outline: 0; }
.chat-command-menu { position: absolute; z-index: 3; right: .8rem; bottom: calc(100% - .25rem); left: .8rem; display: grid; gap: .15rem; max-height: 18rem; overflow: auto; padding: .35rem; background: var(--surface); border: 1px solid var(--border-strong); border-radius: .7rem; box-shadow: 0 .7rem 2rem color-mix(in srgb, #000 30%, transparent); }
.chat-command-menu[hidden] { display: none; }
.chat-command-option { display: grid; grid-template-columns: minmax(8rem, 14rem) 1fr; gap: .65rem; align-items: center; padding: .5rem .6rem; text-align: left; color: var(--fg-muted); background: transparent; border: 1px solid transparent; border-radius: .45rem; cursor: pointer; }
.chat-command-option:hover, .chat-command-option[aria-selected="true"] { color: var(--fg); background: var(--surface-hover); border-color: var(--border); }
.chat-command-option code { color: var(--fg); }
.chat-compose-actions { display: flex; align-items: center; flex: none; gap: var(--sp-2); }
.chat-hint, .chat-empty { color: var(--fg-muted); font-size: .78rem; }
.chat-command-help { color: var(--fg-muted); font-size: .78rem; margin-right: auto; }
.chat-command-help summary { cursor: pointer; }
.chat-command-list { min-width: min(34rem, 70vw); max-width: 40rem; padding-top: .4rem; line-height: 1.45; }
.chat-command-item { display: grid; grid-template-columns: minmax(10rem, 16rem) 1fr; gap: .7rem; padding: .3rem 0; }
.chat-command-item code { color: var(--fg); }
@media (max-width: 520px) { .chat-update-panel { align-items: flex-start; flex-direction: column; } }
-810
View File
@@ -1,810 +0,0 @@
import { h, Fragment } from "preact";
import { useState, useEffect, useRef } from "preact/hooks";
import { api } from "../base/api.jsx";
import { Icon } from "../base/icons.jsx";
import { ChatMarkdown } from "./markdown.jsx";
import { channelID } from "./chat-state.jsx";
import { newChatTurn, retryChatTurn, resolveTurn } from "./chat-retry.jsx";
import { commandScrollTop } from "./command-scroll.js";
import { panelTitle, sessionTitle } from "./chat-render.jsx";
import "./chat.css";
function currentPage() {
return location.hash.slice(1) || "/";
}
export function ChatApp({ open = true }) {
const [sessions, setSessions] = useState([]);
const [currentSession, setCurrentSession] = useState("");
const [messages, setMessages] = useState([]);
const [composerText, setComposerText] = useState("");
const [statusText, setStatusText] = useState("Ready");
const [isSending, setIsSending] = useState(false);
const [selectorData, setSelectorData] = useState({});
const [selectedPersona, setSelectedPersona] = useState("");
const [selectedProvider, setSelectedProvider] = useState("");
const [selectedModel, setSelectedModel] = useState("");
const [commandSpecs, setCommandSpecs] = useState([]);
const [commandMatches, setCommandMatches] = useState([]);
const [commandSelection, setCommandSelection] = useState(0);
const [isCommandMenuOpen, setIsCommandMenuOpen] = useState(false);
const [streamingTurn, setStreamingTurn] = useState(null);
// streamingTurn: { text: string, tools: [], isError: bool, turn: object, isRetry: bool }
const transcriptRef = useRef(null);
const composerRef = useRef(null);
const activeControllerRef = useRef(null);
const sessionToolsRef = useRef(null);
const commandMenuRef = useRef(null);
const settingsRef = useRef(null);
const isSendingRef = useRef(isSending);
isSendingRef.current = isSending;
useEffect(() => {
const closeSettings = (event) => {
const details = settingsRef.current;
if (!details?.open) return;
if (event.target instanceof Node && details.contains(event.target)) return;
details.open = false;
};
document.addEventListener("pointerdown", closeSettings);
document.addEventListener("focusin", closeSettings);
return () => {
document.removeEventListener("pointerdown", closeSettings);
document.removeEventListener("focusin", closeSettings);
};
}, []);
// The panel stays mounted so the session survives navigation, so opening it
// is a prop change rather than a mount: focus the composer on that edge.
useEffect(() => {
if (open) composerRef.current?.focus();
}, [open]);
// Arrow keys move the palette selection; the list scrolls so the highlight
// stays visible once the matches run past the visible rows.
useEffect(() => {
if (!isCommandMenuOpen) return;
const menu = commandMenuRef.current;
const option = menu?.children?.[commandSelection];
if (!menu || !option) return;
menu.scrollTop = commandScrollTop({
scrollTop: menu.scrollTop,
viewportHeight: menu.clientHeight,
optionTop: option.offsetTop,
optionHeight: option.offsetHeight,
});
}, [commandSelection, isCommandMenuOpen]);
// Auto scroll transcript to bottom on new messages or streaming tokens
useEffect(() => {
if (transcriptRef.current) {
transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight;
}
}, [messages, streamingTurn]);
useEffect(() => {
refreshSessions().catch((err) => {
setStatusText(err.message || "Chat unavailable");
});
const onTeardown = () => {
activeControllerRef.current?.abort();
};
window.addEventListener("archie:teardown", onTeardown);
return () => {
window.removeEventListener("archie:teardown", onTeardown);
activeControllerRef.current?.abort();
};
}, []);
async function refreshSessions() {
const data = await api.chatSessions();
const sessionList = data.sessions || [];
setSessions(sessionList);
setSelectorData(data);
setSelectedPersona(data.active_persona || "");
const provs = data.providers || [];
const activeProv = data.active_provider || provs[0] || "";
setSelectedProvider(activeProv);
setSelectedModel(data.active_model || "");
const specs = (data.commands || []).map((item) =>
typeof item === "string" ? { command: item, usage: item, description: "" } : item
);
setCommandSpecs(specs);
if (!currentSession && sessionList[0]) {
await selectSession(sessionList[0].session_id, data, sessionList);
}
}
async function selectSession(id, dataOverride, listOverride) {
const data = dataOverride || selectorData;
setCurrentSession(id);
setMessages([]);
setStreamingTurn(null);
const activePersona = data.active_personas?.[id] || data.active_persona || "";
setSelectedPersona(activePersona);
try {
await api.chatMessage(channelID(), `/resume ${id}`);
const [msgs, turns] = await Promise.all([api.chatMessages(id), api.chatTurns(id)]);
const byAssistantMessage = new Map();
for (const turn of turns || []) {
const assistantID = turn.assistant_message_id || turn.AssistantMessageID;
if (assistantID) byAssistantMessage.set(assistantID, turn);
}
const hydrated = (msgs || []).map((message) => {
const messageID = message.message_id || message.MessageID;
const turn = byAssistantMessage.get(messageID);
return turn ? { ...message, tool_calls: turn.tool_calls || turn.ToolCalls || [] } : message;
});
setMessages(hydrated);
} catch (err) {
setStatusText(err.message || "Could not load session messages");
}
}
async function runSessionCommand(command) {
if (!currentSession) return;
try {
setStatusText("Working…");
const result = await api.chatMessage(channelID(), command);
if (result.session_id) setCurrentSession(result.session_id);
setStatusText(result.reply || "Session updated");
await refreshSessions();
if (result.session_id || currentSession) {
await selectSession(result.session_id || currentSession);
}
if (sessionToolsRef.current) sessionToolsRef.current.open = false;
} catch (err) {
setStatusText(err.message || "Session action failed");
}
}
function promptSessionCommand(command, message) {
const value = window.prompt(message);
if (value?.trim()) runSessionCommand(`${command} ${value.trim()}`);
}
function handlePersonaChange(e) {
const val = e.target.value;
setSelectedPersona(val);
if (!currentSession || !val) return;
api.chatPersona(currentSession, val).then(() => {
setSelectorData((prev) => ({
...prev,
active_personas: { ...(prev.active_personas || {}), [currentSession]: val },
}));
setStatusText(`Personality: ${val}`);
}).catch((err) => {
setStatusText(err.message || "Failed to set personality");
});
}
async function handleProviderChange(e) {
const prov = e.target.value;
setSelectedProvider(prov);
if (!prov) return;
try {
const result = await api.chatMessage(channelID(), `/model --provider ${prov}`);
setStatusText(result.reply || "Provider updated");
await refreshSessions();
} catch (err) {
setStatusText(`Provider update failed: ${err.message || err}`);
}
}
async function handleModelChange(e) {
const mod = e.target.value;
setSelectedModel(mod);
if (!mod) return;
try {
const result = await api.chatMessage(channelID(), `/model ${mod}`);
setStatusText(result.reply || "Model updated");
await refreshSessions();
} catch (err) {
setStatusText(`Model update failed: ${err.message || err}`);
}
}
function handleNewChat() {
setComposerText("/new");
sendMessage({ textOverride: "/new" });
}
function handleComposerInput(e) {
const val = e.target.value;
setComposerText(val);
const before = val.slice(0, e.target.selectionStart);
const match = before.match(/(?:^|\s)\/([^\s]*)$/);
if (match) {
const query = match[1].toLowerCase();
const matches = commandSpecs.filter((spec) => {
const haystack = `${spec.command} ${spec.description}`.toLowerCase();
return haystack.includes(query);
}).slice(0, 8);
if (matches.length) {
setCommandMatches(matches);
setCommandSelection(0);
setIsCommandMenuOpen(true);
return;
}
}
setIsCommandMenuOpen(false);
setCommandMatches([]);
}
function chooseCommand(index) {
const spec = commandMatches[index];
if (!spec || !composerRef.current) return;
const input = composerRef.current;
const before = input.value.slice(0, input.selectionStart);
const after = input.value.slice(input.selectionStart);
const start = before.search(/(?:^|\s)\/[^\s]*$/);
const tokenStart = start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
const nextVal = `${before.slice(0, tokenStart)}${spec.command} ${after}`;
setComposerText(nextVal);
setIsCommandMenuOpen(false);
const cursor = tokenStart + spec.command.length + 1;
setTimeout(() => {
input.focus();
input.setSelectionRange(cursor, cursor);
}, 0);
}
function handleComposerKeyDown(event) {
if (isCommandMenuOpen && commandMatches.length) {
if (
event.key === "Enter" &&
!event.shiftKey &&
!event.ctrlKey &&
!event.metaKey &&
commandMatches.some((spec) => spec.command === composerText.trim())
) {
event.preventDefault();
setIsCommandMenuOpen(false);
sendMessage();
return;
}
if (event.key === "ArrowDown") {
event.preventDefault();
setCommandSelection((prev) => (prev + 1) % commandMatches.length);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
setCommandSelection((prev) => (prev + commandMatches.length - 1) % commandMatches.length);
return;
}
if (event.key === "Enter" && !event.shiftKey && !event.ctrlKey && !event.metaKey) {
event.preventDefault();
chooseCommand(commandSelection);
return;
}
if (event.key === "Escape") {
event.preventDefault();
setIsCommandMenuOpen(false);
return;
}
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
sendMessage();
}
}
async function sendMessage(retryOpts = null) {
const explicitText = retryOpts?.textOverride;
const rawVal = explicitText !== undefined ? explicitText : composerText;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawVal);
if (!text || isSendingRef.current) return;
setIsCommandMenuOpen(false);
setIsSending(true);
setStatusText(isRetry ? "Retrying…" : "Thinking…");
if (!isRetry) {
setMessages((prev) => [...prev, { from: "web", text }]);
setComposerText("");
}
let activeTools = [];
setStreamingTurn({ text: "", tools: [], isError: false, turn, isRetry });
let streamedText = "";
let finished = false;
let timedOut = false;
let timeoutId = null;
try {
const controller = new AbortController();
activeControllerRef.current = controller;
timeoutId = setTimeout(() => {
timedOut = true;
controller.abort();
}, 120000);
const response = await api.chatStream(
{
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
},
{ signal: controller.signal },
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
for (;;) {
const { value, done } = await reader.read();
buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
const frames = buffer.split("\n\n");
buffer = frames.pop() || "";
for (const frame of frames) {
const line = frame.split("\n").find((part) => part.startsWith("data: "));
if (!line) continue;
const event = JSON.parse(line.slice(6));
if (event.session_id) setCurrentSession(event.session_id);
if (event.type === "delta") {
streamedText += event.text;
setStreamingTurn((prev) => (prev ? { ...prev, text: streamedText } : null));
}
if (event.type === "tool") {
activeTools = [...activeTools, event];
setStreamingTurn((prev) => (prev ? { ...prev, tools: activeTools } : null));
}
if (event.type === "navigate") {
activeTools = [...activeTools, event];
setStreamingTurn((prev) => (prev ? { ...prev, tools: activeTools } : null));
}
if (event.type === "done") {
finished = true;
if (!streamedText) {
streamedText = event.text;
}
}
if (event.type === "error") throw new Error(event.text);
}
if (done) break;
}
if (!finished) throw new Error("chat stream ended before completion");
// Commit finished message into transcript
setMessages((prev) => [
...prev,
{
from: "assistant",
text: streamedText,
tool_calls: activeTools,
},
]);
setStreamingTurn(null);
setStatusText("Ready");
await refreshSessions();
} catch (err) {
if (err.name === "AbortError" && !timedOut) {
setStreamingTurn({
text: "Turn stopped.",
tools: activeTools,
isError: false,
turn,
isRetry,
});
setStatusText("Stopped");
} else {
const failedText = `Unable to complete that turn: ${err.message || err}`;
setStreamingTurn({
text: failedText,
tools: activeTools,
isError: true,
turn: retryChatTurn(turn),
isRetry,
});
setStatusText("Error — retry available");
}
} finally {
clearTimeout(timeoutId);
activeControllerRef.current = null;
setIsSending(false);
if (composerRef.current) composerRef.current.focus();
}
}
function handleStop() {
setStatusText("Stopping…");
if (currentSession) {
void api.chatCancel(currentSession).catch(() => {});
}
activeControllerRef.current?.abort();
}
const groupedModels = selectorData.models_by_provider || {};
const currentModels =
selectedProvider && groupedModels[selectedProvider]
? groupedModels[selectedProvider]
: selectorData.models || [];
return (
<div className="chat-panel-content">
<div className="chat-drawer-head">
<strong className="chat-panel-title">{panelTitle(sessions, currentSession)}</strong>
<div className="chat-head-actions">
<button className="icon-btn chat-new" type="button" title="New chat" aria-label="New chat" onClick={handleNewChat}>
<Icon name="message-circle-plus" />
</button>
</div>
</div>
<div className="chat-bar">
<label className="chat-session-switch">
<span className="sr-only">Conversation</span>
<select
value={currentSession}
onChange={(e) => selectSession(e.target.value)}
disabled={!sessions.length}
>
{!sessions.length ? (
<option value="">No conversations yet</option>
) : (
sessions.map((session) => (
<option key={session.session_id} value={session.session_id}>
{sessionTitle(session)}
</option>
))
)}
</select>
</label>
<details className="chat-settings" ref={settingsRef}>
<summary aria-label="Chat settings" title="Chat settings">
<span aria-hidden="true">⚙</span>
</summary>
<div className="chat-settings-body">
<span className="chat-status">{statusText}</span>
<label>
Personality
<select
className="chat-select"
aria-label="Personality"
value={selectedPersona}
onChange={handlePersonaChange}
>
<option value="">Default</option>
{(selectorData.personas || []).map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
</label>
{(selectorData.providers || []).length > 0 && (
<label>
Provider
<select
className="chat-select"
aria-label="Provider"
value={selectedProvider}
onChange={handleProviderChange}
>
<option value="">Default</option>
{(selectorData.providers || []).map((provider) => (
<option key={provider} value={provider}>
{provider}
</option>
))}
</select>
</label>
)}
<label>
Model
<select
className="chat-select"
aria-label="Model"
value={selectedModel}
onChange={handleModelChange}
>
<option value="">Default</option>
{currentModels.map((model) => (
<option key={model} value={model}>
{model}
</option>
))}
</select>
</label>
</div>
</details>
</div>
<div className="chat-layout">
<section className="chat-workspace">
<div className="chat-workspace-head">
<details
className="chat-session-tools"
ref={sessionToolsRef}
hidden={!currentSession}
>
<summary>Session actions</summary>
<div className="chat-session-tool-list">
<button
className="btn"
type="button"
onClick={() => runSessionCommand("/retry")}
>
Retry
</button>
<button
className="btn"
type="button"
onClick={() => runSessionCommand("/undo")}
>
Undo
</button>
<button
className="btn"
type="button"
onClick={() => promptSessionCommand("/title", "Session title")}
>
Rename
</button>
<button
className="btn"
type="button"
onClick={() => promptSessionCommand("/branch", "Branch name (optional)")}
>
Branch
</button>
<button
className="btn"
type="button"
onClick={() => runSessionCommand("/compress --preview")}
>
Preview compression
</button>
</div>
</details>
</div>
{/* Transcript */}
<div className="chat-transcript" ref={transcriptRef}>
{!messages.length && !streamingTurn ? (
<div className="chat-empty-state">
<span className="chat-empty-mark">A</span>
<h2>What are we working on?</h2>
<p>Ask Archie anything, or start with one of these prompts.</p>
<div className="chat-prompt-grid">
<button
className="chat-prompt"
type="button"
onClick={() => {
setComposerText("Summarise active tasks");
composerRef.current?.focus();
}}
>
Summarise active tasks
</button>
<button
className="chat-prompt"
type="button"
onClick={() => {
setComposerText("Show running agents");
composerRef.current?.focus();
}}
>
Show running agents
</button>
<button
className="chat-prompt"
type="button"
onClick={() => {
setComposerText("Check system status");
composerRef.current?.focus();
}}
>
Check system status
</button>
</div>
</div>
) : (
<Fragment>
{messages.map((message, idx) => {
const from = message.from ?? message.From ?? "";
const text = message.text ?? message.Text ?? "";
const isAssistant = from !== "web";
const tools = message.tool_calls || message.ToolCalls || [];
return (
<div
key={idx}
className={`chat-bubble-row ${isAssistant ? "assistant" : "user"}`}
>
<div className="chat-bubble">
{isAssistant ? (
<Fragment>
{tools.length > 0 && (
<div className="chat-tools">
{tools.map((tool, tIdx) => {
if (tool.path) {
return (
<a
key={tIdx}
className="chat-nav-chip"
href={`#${tool.path}`}
title={`Go to ${tool.label || tool.path}`}
>
<span className="chat-nav-chip-icon" aria-hidden="true">
↗
</span>
<span className="chat-nav-chip-label">
{tool.label || tool.path}
</span>
</a>
);
}
const name = tool.name || tool.Name || tool.tool || "tool";
const parameters = tool.parameters || tool.Parameters || "";
const summary =
tool.summary ||
tool.Summary ||
tool.text ||
tool.err ||
tool.Err ||
"done";
const failed = Boolean(tool.err || tool.Err || tool.failed);
return (
<div
key={tIdx}
className={`chat-tool ${failed ? "failed" : ""}`}
>
<span className="chat-tool-icon">🔧</span>
<span className="chat-tool-name">{name}</span>
{parameters && (
<code className="chat-tool-parameters">{parameters}</code>
)}
<span className="chat-tool-summary">{summary}</span>
</div>
);
})}
</div>
)}
<ChatMarkdown text={text} />
</Fragment>
) : (
<div className="chat-bubble-text">{text}</div>
)}
</div>
</div>
);
})}
{/* Live streaming assistant turn */}
{streamingTurn && (
<div className="chat-bubble-row assistant">
<div className="chat-bubble">
{streamingTurn.tools?.length > 0 && (
<div className="chat-tools">
{streamingTurn.tools.map((tool, tIdx) => {
if (tool.path) {
return (
<a
key={tIdx}
className="chat-nav-chip"
href={`#${tool.path}`}
title={`Go to ${tool.label || tool.path}`}
>
<span className="chat-nav-chip-icon" aria-hidden="true">
↗
</span>
<span className="chat-nav-chip-label">
{tool.label || tool.path}
</span>
</a>
);
}
const name = tool.name || tool.tool || "tool";
const parameters = tool.parameters || "";
const summary = tool.summary || tool.text || (tool.failed ? "failed" : "running…");
const failed = Boolean(tool.failed);
return (
<div
key={tIdx}
className={`chat-tool ${failed ? "failed" : ""}`}
>
<span className="chat-tool-icon">🔧</span>
<span className="chat-tool-name">{name}</span>
{parameters && (
<code className="chat-tool-parameters">{parameters}</code>
)}
<span className="chat-tool-summary">{summary}</span>
</div>
);
})}
</div>
)}
<ChatMarkdown text={streamingTurn.text || "…"} />
{streamingTurn.isError && (
<button
className="btn chat-retry"
type="button"
onClick={() => sendMessage({ turn: streamingTurn.turn })}
>
Retry
</button>
)}
</div>
</div>
)}
</Fragment>
)}
</div>
{/* Composer */}
<div className="chat-compose">
<div className="chat-composer-shell">
<textarea
ref={composerRef}
className="chat-composer"
rows={3}
placeholder="Message Archie, or type / for commands"
aria-label="Message Archie"
value={composerText}
onInput={handleComposerInput}
onKeyDown={handleComposerKeyDown}
/>
{isCommandMenuOpen && commandMatches.length > 0 && (
<div
className="chat-command-menu"
ref={commandMenuRef}
role="listbox"
aria-label="Commands"
>
{commandMatches.map((spec, index) => (
<button
key={spec.command}
type="button"
role="option"
aria-selected={String(index === commandSelection)}
className="chat-command-option"
onMouseDown={(e) => e.preventDefault()}
onClick={() => chooseCommand(index)}
>
<code>{spec.command}</code>
<span>{spec.description || spec.usage || ""}</span>
</button>
))}
</div>
)}
<div className="chat-compose-actions">
{isSending && (
<button className="btn" type="button" onClick={handleStop}>
Stop
</button>
)}
<button
className="btn btn-primary"
type="button"
disabled={isSending || !composerText.trim()}
onClick={() => sendMessage()}
>
Send
</button>
</div>
</div>
</div>
</section>
</div>
</div>
);
}
@@ -6,13 +6,26 @@
// arithmetic and worth testing on its own, so the effect only applies what
// this returns.
/** The palette's scroll geometry and the selected option's position in it. */
export interface CommandScrollGeometry {
scrollTop: number;
viewportHeight: number;
optionTop: number;
optionHeight: number;
}
/**
* commandScrollTop returns the scrollTop that brings the selected option fully
* into view, or the current scrollTop when it is already visible. Mirrors
* `scrollIntoView({ block: "nearest" })`: it moves the minimum distance, and
* scrolls up for an option above the viewport, down for one below.
*/
export function commandScrollTop({ scrollTop, viewportHeight, optionTop, optionHeight }) {
export function commandScrollTop({
scrollTop,
viewportHeight,
optionTop,
optionHeight,
}: CommandScrollGeometry): number {
// An option taller than the viewport cannot be shown whole. Align its top,
// which holds the command itself; aligning the bottom would scroll the name
// out of sight and leave only the tail of its description.
+52
View File
@@ -0,0 +1,52 @@
import type { ChatCommandSpec } 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 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]*$/;
/** 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[], value: string, caret: number): ChatCommandSpec[] {
const match = value.slice(0, caret).match(OPEN_TOKEN);
if (!match) return [];
const query = match[1].toLowerCase();
return specs
.filter((spec) => `${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(query))
.slice(0, MAX_MATCHES);
}
/**
* applyCommand replaces the token being completed with the chosen command and
* returns the cursor position just after it, ready for the next word.
*/
export function applyCommand(value: string, caret: number, command: string): { text: string; cursor: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const start = before.search(ANY_TOKEN);
const tokenStart = start < 0 ? before.length : start + (before[start] === " " ? 1 : 0);
return {
text: `${before.slice(0, tokenStart)}${command} ${after}`,
cursor: tokenStart + command.length + 1,
};
}
/**
* isExactCommand reports whether the composer already holds a command and
* nothing else. Enter then sends it rather than completing it, so a command
* typed in full is never re-entered by the palette that was offering it.
*/
export function isExactCommand(specs: ChatCommandSpec[], value: string): boolean {
const trimmed = value.trim();
return specs.some((spec) => spec.command === trimmed);
}
@@ -1,76 +1,77 @@
import { h } from "preact";
/**
* Chat markdown.
*
* Telegram-style rich blocks -- headings, lists, quotes, fenced code, tables,
* inline emphasis/links/images -- rendered as semantic HTML. It is a
* component rather than a DOM builder so a streamed reply can be diffed: the
* transcript re-renders on every frame, and diffing is what stops the whole
* bubble being rebuilt each time the answer grows.
* inline emphasis/links/images -- parsed into a tree that ChatMarkdown renders
* as semantic HTML. The parse is separate from the render so a streamed reply
* can be re-rendered on every frame without re-deciding what the text means.
*/
/** One span of an inline run: what a paragraph's text breaks down into. */
export type ChatInline =
| { kind: "text"; text: string }
| { kind: "strong"; text: string }
| { kind: "em"; text: string }
| { kind: "del"; text: string }
| { kind: "code"; text: string }
| { kind: "link"; text: string; href: string }
| { kind: "image"; alt: string; src: string };
/** One block of the document. Lists carry their items as inline runs. */
export type ChatBlock =
| { kind: "p" | "h1" | "h2" | "h3" | "blockquote"; inline: ChatInline[] }
| { kind: "ul" | "ol"; items: ChatInline[][] }
| { kind: "pre"; code: string }
| { kind: "table"; head: ChatInline[][]; rows: ChatInline[][][] };
const INLINE =
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
// inlineMarkdown returns the children of one line: plain text and the element
// each matched span becomes, in order.
function inlineMarkdown(text) {
const children = [];
function inlineMarkdown(text: string): ChatInline[] {
const children: ChatInline[] = [];
let cursor = 0;
let key = 0;
for (const match of String(text).matchAll(INLINE)) {
if (match.index > cursor) children.push(text.slice(cursor, match.index));
if (match.index > cursor) children.push({ kind: "text", text: text.slice(cursor, match.index) });
const value = match[0];
if (value.startsWith("![")) {
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
if (img) {
children.push(
<img className="chat-media-img" src={img[2]} alt={img[1] || "Image"} loading="lazy" key={key++} />,
);
}
if (img) children.push({ kind: "image", alt: img[1] || "Image", src: img[2] });
} else if (value.startsWith("~~")) {
children.push(<del key={key++}>{value.slice(2, -2)}</del>);
children.push({ kind: "del", text: value.slice(2, -2) });
} else if (value.startsWith("**") || value.startsWith("__")) {
children.push(<strong key={key++}>{value.slice(2, -2)}</strong>);
children.push({ kind: "strong", text: value.slice(2, -2) });
} else if (value.startsWith("`")) {
children.push(<code key={key++}>{value.slice(1, -1)}</code>);
children.push({ kind: "code", text: value.slice(1, -1) });
} else if (value.startsWith("[")) {
const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);
if (link) {
children.push(
<a href={link[2]} target="_blank" rel="noreferrer" key={key++}>
{link[1]}
</a>,
);
}
if (link) children.push({ kind: "link", text: link[1], href: link[2] });
} else {
children.push(<em key={key++}>{value.slice(1, -1)}</em>);
children.push({ kind: "em", text: value.slice(1, -1) });
}
cursor = match.index + value.length;
}
if (cursor < text.length) children.push(text.slice(cursor));
if (cursor < text.length) children.push({ kind: "text", text: text.slice(cursor) });
return children;
}
export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
const blocks = [];
export function parseMarkdown(text: string | null | undefined): ChatBlock[] {
const blocks: ChatBlock[] = [];
const lines = String(text || "").split("\n");
let paragraph = [];
let list = null;
let code = null;
let key = 0;
let paragraph: string[] = [];
let list: { tag: "ul" | "ol"; items: string[] } | null = null;
let code: string[] | null = null;
const flushParagraph = () => {
if (paragraph.length) {
blocks.push(<p key={key++}>{inlineMarkdown(paragraph.join(" "))}</p>);
blocks.push({ kind: "p", inline: inlineMarkdown(paragraph.join(" ")) });
paragraph = [];
}
};
const flushList = () => {
if (!list) return;
const items = list.items.map((item, i) => <li key={i}>{inlineMarkdown(item)}</li>);
blocks.push(list.tag === "ol" ? <ol key={key++}>{items}</ol> : <ul key={key++}>{items}</ul>);
blocks.push({ kind: list.tag, items: list.items.map((item) => inlineMarkdown(item)) });
list = null;
};
@@ -80,11 +81,7 @@ export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
flushParagraph();
flushList();
if (code) {
blocks.push(
<pre key={key++}>
<code>{code.join("\n")}</code>
</pre>,
);
blocks.push({ kind: "pre", code: code.join("\n") });
code = null;
} else {
code = [];
@@ -105,7 +102,7 @@ export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
) {
flushParagraph();
flushList();
const rows = [];
const rows: string[][] = [];
for (index += 2; index < lines.length; index++) {
const cells = tableCells(lines[index]);
if (!cells || cells.length !== headerCells.length) {
@@ -114,26 +111,11 @@ export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
}
rows.push(cells);
}
blocks.push(
<table key={key++}>
<thead>
<tr>
{headerCells.map((cell, i) => (
<th key={i}>{inlineMarkdown(cell)}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, r) => (
<tr key={r}>
{row.map((cell, c) => (
<td key={c}>{inlineMarkdown(cell)}</td>
))}
</tr>
))}
</tbody>
</table>,
);
blocks.push({
kind: "table",
head: headerCells.map((cell) => inlineMarkdown(cell)),
rows: rows.map((row) => row.map((cell) => inlineMarkdown(cell))),
});
continue;
}
if (!line.trim()) {
@@ -145,8 +127,7 @@ export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
if (heading) {
flushParagraph();
flushList();
const Tag = `h${heading[1].length}`;
blocks.push(<Tag key={key++}>{inlineMarkdown(heading[2])}</Tag>);
blocks.push({ kind: `h${heading[1].length}` as "h1" | "h2" | "h3", inline: inlineMarkdown(heading[2]) });
continue;
}
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
@@ -158,31 +139,25 @@ export function ChatMarkdown({ text, className = "chat-bubble-text" }) {
flushList();
list = { tag, items: [] };
}
list.items.push((bullet || ordered)[1]);
list.items.push((bullet || ordered)![1]);
continue;
}
if (line.startsWith(">")) {
flushParagraph();
flushList();
blocks.push(<blockquote key={key++}>{inlineMarkdown(line.replace(/^>\s?/, ""))}</blockquote>);
blocks.push({ kind: "blockquote", inline: inlineMarkdown(line.replace(/^>\s?/, "")) });
continue;
}
paragraph.push(line);
}
flushParagraph();
flushList();
if (code) {
blocks.push(
<pre key={key++}>
<code>{code.join("\n")}</code>
</pre>,
);
}
if (code) blocks.push({ kind: "pre", code: code.join("\n") });
return <div className={className}>{blocks}</div>;
return blocks;
}
function tableCells(line) {
function tableCells(line: string): string[] | null {
const value = String(line || "").trim();
if (!value.includes("|")) return null;
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
@@ -190,6 +165,6 @@ function tableCells(line) {
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
}
function isTableSeparator(cells) {
function isTableSeparator(cells: string[]): boolean {
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
}
@@ -1,13 +1,6 @@
/**
* Chat presentation helpers that are not components.
*
* The bubble row markup that used to live here is gone with the imperative DOM
* layer: `assistantBubble`/`chatBubble` were a parallel, unreachable renderer
* (nothing in `src/` called them except the equally unreachable chat-tools
* helpers), and chat.jsx builds those rows as JSX itself.
*/
import type { ChatSession } from "./state";
export function sessionTitle(session) {
export function sessionTitle(session: ChatSession): string {
return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
}
@@ -16,7 +9,7 @@ export function sessionTitle(session) {
* session switcher sits below it, so the header says which conversation is
* open rather than repeating the product name.
*/
export function panelTitle(sessions, currentSession) {
export function panelTitle(sessions: ChatSession[], currentSession: string): string {
if (!currentSession) return "Archie";
const session = (sessions || []).find((item) => item.session_id === currentSession);
return session ? sessionTitle(session) : "Archie";
+462
View File
@@ -0,0 +1,462 @@
import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
import { api } from "@/lib/api";
import { channelID } from "./channel";
import { matchesFor } from "./commands";
import { resolveTurn, retryChatTurn, type ChatTurn, type RetryOptions } from "./turn";
/**
* The chat panel's shared state.
*
* The launcher and the panel are separate components and the panel survives a
* navigation, so the conversation lives in a module rather than in either one.
* Everything the server answers with is read here; the components decide how it
* looks.
*/
/** One web conversation, as GET /api/chat/sessions lists it. */
export interface ChatSession {
session_id: string;
title?: string;
branch_name?: string;
}
/** One slash command the server will accept. */
export interface ChatCommandSpec {
command: string;
usage?: string;
description?: 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`.
*/
export interface ChatToolCall {
id?: string;
name?: string;
tool?: string;
parameters?: string;
summary?: string;
text?: string;
failed?: boolean;
/** A dashboard_navigate result: the page to route to, instead of a tool line. */
path?: string;
label?: string;
// The same view reaches the browser from more than one composition, so an
// outcome may arrive under either spelling. `err`/`Err` is also how a failed
// call reports itself: it is a result, not a missing one.
Name?: string;
Parameters?: string;
Summary?: string;
Err?: string;
err?: string;
}
/** One message in the transcript, from either side. */
export interface ChatMessage {
from?: string;
text?: string;
tool_calls?: ChatToolCall[];
// The same view reaches the browser from more than one composition, so both
// spellings are read rather than assuming one serialiser.
From?: string;
Text?: string;
ToolCalls?: ChatToolCall[];
message_id?: string;
MessageID?: string;
}
/** A turn in flight: what it is showing, and what to resend if it fails. */
export interface StreamingTurn {
text: string;
tools: ChatToolCall[];
isError: boolean;
turn?: ChatTurn;
isRetry: boolean;
}
/** Everything the selectors on the panel read, from one sessions read. */
export interface ChatSelectorData {
personas?: string[];
providers?: string[];
models?: string[];
models_by_provider?: Record<string, string[]>;
active_persona?: string;
active_personas?: Record<string, string>;
active_provider?: string;
active_model?: string;
commands?: Array<ChatCommandSpec | string>;
}
/**
* The id the launcher points its `aria-controls` at and the panel answers to.
* Both read it here so the pair cannot drift apart.
*/
export const CHAT_PANEL_ID = "chat-panel";
/**
* One `data: {...}` frame of the chat stream. The server always emits `text`,
* empty or not: the browser concatenates it, so a missing key would put the
* string "undefined" into the transcript on a turn whose reply is empty.
*/
interface ChatStreamFrame extends ChatToolCall {
type?: string;
text: string;
session_id?: string;
}
/** A turn that never settles must not hold the composer closed forever. */
const STREAM_TIMEOUT_MS = 120000;
export const sessions = ref<ChatSession[]>([]);
export const currentSession = ref("");
export const messages = ref<ChatMessage[]>([]);
export const composerText = ref("");
export const statusText = ref("Ready");
export const isSending = ref(false);
export const streamingTurn = ref<StreamingTurn | null>(null);
export const selectorData = ref<ChatSelectorData>({});
export const selectedPersona = ref("");
export const selectedProvider = ref("");
export const selectedModel = ref("");
export const commandSpecs = ref<ChatCommandSpec[]>([]);
export const commandMatches = ref<ChatCommandSpec[]>([]);
export const commandSelection = ref(0);
export const isCommandMenuOpen = ref(false);
export const currentModels = computed(() => {
const grouped = selectorData.value.models_by_provider || {};
const provider = selectedProvider.value;
return provider && grouped[provider] ? grouped[provider] : selectorData.value.models || [];
});
/**
* How many layers inside the panel currently own Escape -- an open popover, a
* select inside one.
*
* The panel's own Escape defers to them. Dismissing a menu must not also throw
* away the conversation the menu was opened over, and a layer that dismissed
* both would make the panel impossible to keep open while consulting it.
*/
const openLayers = ref(0);
/** Registers a toggleable layer inside the panel, for as long as it is mounted. */
export function useEscapeLayer(open: Ref<boolean>): void {
watch(open, (isOpen) => {
openLayers.value += isOpen ? 1 : -1;
});
onUnmounted(() => {
if (open.value) openLayers.value -= 1;
});
}
export function escapeOwnedByLayer(): boolean {
return openLayers.value > 0;
}
let activeController: AbortController | null = null;
// The send path holds a stream loop that outlives the click that started it; a
// module-level controller is what a Stop, or an unmount, aborts.
function abortActiveTurn(): void {
activeController?.abort();
}
export async function refreshSessions(): Promise<void> {
const data = await api.chatSessions<ChatSelectorData & { sessions?: ChatSession[] }>();
const sessionList = data.sessions || [];
sessions.value = sessionList;
selectorData.value = data;
selectedPersona.value = data.active_persona || "";
const providers = data.providers || [];
selectedProvider.value = data.active_provider || providers[0] || "";
selectedModel.value = data.active_model || "";
commandSpecs.value = (data.commands || []).map((item) =>
typeof item === "string" ? { command: item, usage: item, description: "" } : item,
);
if (!currentSession.value && sessionList[0]) {
// Vue's reactivity makes the assignment above readable here immediately, so
// the read that selects the first conversation needs no data threaded into
// it the way the Preact tree had to pass its own copy.
await selectSession(sessionList[0].session_id);
}
}
export async function selectSession(id: string): Promise<void> {
if (!id) return;
const data = selectorData.value;
currentSession.value = id;
messages.value = [];
streamingTurn.value = null;
selectedPersona.value = data.active_personas?.[id] || data.active_persona || "";
try {
// Resuming is the server's own command, so the transcript read below is of
// a conversation the server considers current rather than a stale one.
await api.chatMessage(channelID(), `/resume ${id}`);
const [msgs, turns] = await Promise.all([api.chatMessages<ChatMessage[]>(id), api.chatTurns<ChatTurnView[]>(id)]);
const byAssistantMessage = new Map<string, ChatTurnView>();
for (const turn of turns || []) {
const assistantID = turn.assistant_message_id || turn.AssistantMessageID;
if (assistantID) byAssistantMessage.set(assistantID, turn);
}
// Tool calls belong to the turn, not the message, so a reopened
// conversation gets its transcript back with the evidence in place.
messages.value = (msgs || []).map((message) => {
const messageID = message.message_id || message.MessageID;
const turn = messageID ? byAssistantMessage.get(messageID) : undefined;
return turn ? { ...message, tool_calls: turn.tool_calls || turn.ToolCalls || [] } : message;
});
} catch (err) {
statusText.value = (err as Error).message || "Could not load session messages";
}
}
/** One recorded turn, as GET /api/chat/sessions/{id}/turns returns it. */
interface ChatTurnView {
assistant_message_id?: string;
AssistantMessageID?: string;
tool_calls?: ChatToolCall[];
ToolCalls?: ChatToolCall[];
}
export async function runSessionCommand(command: string): Promise<void> {
if (!currentSession.value) return;
try {
statusText.value = "Working…";
const result = await api.chatMessage<{ session_id?: string; reply?: string }>(channelID(), command);
if (result.session_id) currentSession.value = result.session_id;
statusText.value = result.reply || "Session updated";
await refreshSessions();
if (result.session_id || currentSession.value) {
await selectSession(result.session_id || currentSession.value);
}
} catch (err) {
statusText.value = (err as Error).message || "Session action failed";
}
}
// Rename and branch take a value the server has no form for, so the browser's
// own prompt is the input: a modal built for two commands would be more UI than
// the two commands are worth.
export function promptSessionCommand(command: string, message: string): void {
const value = window.prompt(message);
if (value?.trim()) void runSessionCommand(`${command} ${value.trim()}`);
}
export function setPersona(name: string): void {
selectedPersona.value = name;
const session = currentSession.value;
if (!session || !name) return;
api
.chatPersona(session, name)
.then(() => {
const data = selectorData.value;
selectorData.value = {
...data,
active_personas: { ...(data.active_personas || {}), [session]: name },
};
statusText.value = `Personality: ${name}`;
})
.catch((err: Error) => {
statusText.value = err.message || "Failed to set personality";
});
}
export async function setProvider(provider: string): Promise<void> {
selectedProvider.value = provider;
if (!provider) return;
try {
const result = await api.chatMessage<{ reply?: string }>(channelID(), `/model --provider ${provider}`);
statusText.value = result.reply || "Provider updated";
await refreshSessions();
} catch (err) {
statusText.value = `Provider update failed: ${(err as Error).message || err}`;
}
}
export async function setModel(model: string): Promise<void> {
selectedModel.value = model;
if (!model) return;
try {
const result = await api.chatMessage<{ reply?: string }>(channelID(), `/model ${model}`);
statusText.value = result.reply || "Model updated";
await refreshSessions();
} catch (err) {
statusText.value = `Model update failed: ${(err as Error).message || err}`;
}
}
export function newChat(): void {
composerText.value = "/new";
void sendMessage({ textOverride: "/new" });
}
/** Opens the palette for the slash 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;
return;
}
isCommandMenuOpen.value = false;
commandMatches.value = [];
}
export function closeCommandMenu(): void {
isCommandMenuOpen.value = false;
}
export function moveCommandSelection(delta: number): void {
const length = commandMatches.value.length;
if (!length) return;
commandSelection.value = (commandSelection.value + delta + length) % length;
}
/** The page the operator asked from, so an answer can be about what they saw. */
function currentPage(): string {
return location.pathname + location.search || "/";
}
export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
const explicitText = retryOpts?.textOverride;
const rawValue = explicitText !== undefined ? explicitText : composerText.value;
const { text, turn, isRetry } = resolveTurn(retryOpts, rawValue);
if (!text || isSending.value) return;
closeCommandMenu();
isSending.value = true;
statusText.value = isRetry ? "Retrying…" : "Thinking…";
if (!isRetry) {
messages.value = [...messages.value, { from: "web", text }];
composerText.value = "";
}
let activeTools: ChatToolCall[] = [];
streamingTurn.value = { text: "", tools: [], isError: false, turn, isRetry };
let streamedText = "";
let finished = false;
let timedOut = false;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
try {
const controller = new AbortController();
activeController = controller;
timeoutId = setTimeout(() => {
timedOut = true;
controller.abort();
}, STREAM_TIMEOUT_MS);
const response = await api.chatStream(
{
channel_id: channelID(),
source_id: turn.sourceID,
text: turn.text,
page: currentPage(),
},
{ signal: controller.signal },
);
const body = response.body;
if (!body) throw new Error("the chat stream returned no body");
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = "";
// Drained to completion: the stream is read until the reader reports done,
// and a turn that ends without a `done` frame is a failed turn rather than
// a short one. Reading only some frames leaves the producer writing into a
// stream nobody collects.
for (;;) {
const { value, done } = await reader.read();
buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
const frames = buffer.split("\n\n");
buffer = frames.pop() || "";
for (const frame of frames) {
const line = frame.split("\n").find((part) => part.startsWith("data: "));
if (!line) continue;
const event = JSON.parse(line.slice(6)) as ChatStreamFrame;
if (event.session_id) currentSession.value = event.session_id;
if (event.type === "delta") {
streamedText += event.text;
streamingTurn.value = streamingTurn.value ? { ...streamingTurn.value, text: streamedText } : 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.
if (event.type === "tool" || event.type === "navigate") {
activeTools = [...activeTools, event];
streamingTurn.value = streamingTurn.value ? { ...streamingTurn.value, tools: activeTools } : null;
}
if (event.type === "done") {
finished = true;
if (!streamedText) streamedText = event.text || "";
}
if (event.type === "error") throw new Error(event.text);
}
if (done) break;
}
if (!finished) throw new Error("chat stream ended before completion");
messages.value = [...messages.value, { from: "assistant", text: streamedText, tool_calls: activeTools }];
streamingTurn.value = null;
statusText.value = "Ready";
await refreshSessions();
} catch (err) {
const failed = err as Error;
if (failed.name === "AbortError" && !timedOut) {
streamingTurn.value = { text: "Turn stopped.", tools: activeTools, isError: false, turn, isRetry };
statusText.value = "Stopped";
} else {
streamingTurn.value = {
text: `Unable to complete that turn: ${failed.message || failed}`,
tools: activeTools,
isError: true,
turn: turn ? retryChatTurn(turn) : undefined,
isRetry,
};
statusText.value = "Error — retry available";
}
} finally {
clearTimeout(timeoutId);
activeController = null;
isSending.value = false;
}
}
export function stopTurn(): void {
statusText.value = "Stopping…";
if (currentSession.value) {
void api.chatCancel(currentSession.value).catch(() => {});
}
abortActiveTurn();
}
/**
* Owns the first sessions read and the teardown of an in-flight turn for the
* panel's lifetime. The panel is mounted once beside the outlet and stays
* mounted while it is closed, so opening it is a prop change rather than a
* mount and the conversation survives a navigation.
*/
export function useChat(): void {
onMounted(() => {
refreshSessions().catch((err: Error) => {
statusText.value = err.message || "Chat unavailable";
});
});
onUnmounted(() => {
abortActiveTurn();
});
}
+42
View File
@@ -0,0 +1,42 @@
import { randomUUID } from "@/lib/uuid";
/**
* What a send puts on the wire: the text, and the source id the server keys
* the turn on so a retry of the same turn is recognisable as one.
*/
export interface ChatTurn {
text: string;
sourceID: string;
}
export function newChatTurn(text: string): ChatTurn {
return { text, sourceID: randomUUID() };
}
export function retryChatTurn(turn: ChatTurn): ChatTurn {
return { ...turn };
}
/** A retry descriptor as the transcript holds it, or nothing for a fresh send. */
export interface RetryOptions {
textOverride?: string;
turn?: ChatTurn;
}
// resolveTurn decides what to send: a real retry descriptor's original turn,
// or a fresh turn built from the composer text. `retry` is untrusted here --
// a DOM event handler bound as `el.onclick = sendMessage` (rather than
// `() => sendMessage()`) hands the click's MouseEvent to this function as
// `retry`, and a MouseEvent is truthy but has no `.turn`. Only an object
// carrying a `turn.text` string counts as a genuine retry; anything else
// (including no argument) falls back to the composer text instead of
// throwing on a missing property.
export function resolveTurn(
retry: RetryOptions | null | undefined,
composerValue: string,
): { text: string; turn: ChatTurn; isRetry: boolean } {
const isRetry = !!(retry && typeof retry === "object" && retry.turn && typeof retry.turn.text === "string");
const text = isRetry ? retry.turn!.text : composerValue.trim();
const turn = isRetry ? retryChatTurn(retry.turn!) : newChatTurn(text);
return { text, turn, isRetry };
}
+11
View File
@@ -0,0 +1,11 @@
<script setup lang="ts">
import Logo from "./Logo.vue";
import BrandName from "./BrandName.vue";
</script>
<template>
<RouterLink to="/" class="flex items-center gap-2 rounded-md px-1 py-1 outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50">
<Logo />
<BrandName class="hidden sm:inline" />
</RouterLink>
</template>
+3
View File
@@ -0,0 +1,3 @@
<template>
<span class="text-[15px] font-semibold tracking-tight">Archie</span>
</template>
+17
View File
@@ -0,0 +1,17 @@
<script setup lang="ts">
withDefaults(defineProps<{ size?: number }>(), { size: 22 });
</script>
<template>
<svg
:width="size"
:height="size"
viewBox="0 0 24 24"
fill="none"
aria-hidden="true"
class="text-primary shrink-0"
>
<path d="M12 2.5 21 20h-4.1L12 10.6 7.1 20H3l9-17.5Z" fill="currentColor" />
<path d="M8.6 16.2h6.8" stroke="var(--background)" stroke-width="1.6" stroke-linecap="round" />
</svg>
</template>
Loaded 100 of 518 files, more files were not shown because too many files have changed in this diff. Show more