fix(webui): multiplex dashboard live updates over one stream
This commit is contained in:
25 files changed
+835
-322
No files matched your search
@@ -106,7 +106,7 @@
|
||||
"url": "/dev/development/",
|
||||
"title": "Development guides",
|
||||
"section": "Development",
|
||||
"body": "# Development guides\n\nChecklists for changing Archie, one page per area. Each names every place a\nchange must reach, so a feature that works in one layer does not silently stop\nat the next. A change that spans areas starts on the page for the area it\nbegins in, which points to the others. The pages point at the documents that\nown the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than\nrestating them.\n\n| Area | Covers |\n| ---------------------------------------------- | -------------------------------------------------------------------------------- |\n| [Frontend UI](/dev/development/frontend-ui/) | Anything under `ui/`, and the dashboard's API routes |\n| [Agent](/dev/development/agent/) | The agent container, its image, profiles, tools and workspace |\n| [Workflows](/dev/development/workflows/) | Workflow definitions and step types |\n| [Daemon](/dev/development/daemon/) | Task statuses, fields and the brief; sources, event types, mappings and bindings |\n| [State Store](/dev/development/state-store/) | Stored fields, tables, RPCs and errors |\n| [Control plane and settings](/dev/development/control-plane/) | Settings in `config.toml` or the dashboard |\n| [Processes and wiring](/dev/development/wiring/) | Where code goes, processes, plugin engines, channels, NATS subjects |\n| [Merging work](/dev/development/merging-work/) | Merging a lane or a branch |\n\n## Every change\n\n- Write the failing test first for anything with logic, branching or a\n contract, and check it fails on an assertion, not a compile error.\n- Test through the path production uses. A test that sets a value directly on\n the consumer proves nothing about the layers that normally deliver it.\n- Run `task check` and let its exit status decide the commit:\n `task check \u0026\u0026 git commit ...`. `task test` passes `-short`, which skips the\n process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`\n too when a change crosses a process or the database.\n- Regenerate, never hand-edit, generated output: `task proto:generate`,\n `go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,\n `task ui`, `task docs:artifact`. `task proto:check` compares against the git\n index, so stage regenerated contracts before running it.\n- Stage by path, or read `git status` before `git add -A`. Tests that start\n embedded NATS or write logs must use `t.TempDir()`; anything they leave in the\n tree gets committed. `task check` also adds linter-tool lines to `go.sum`\n (bead 1e37); restore `go.sum` before committing unless you changed a\n dependency.\n- A change to `docs/prds/` or `docs/architecture/` carries the regenerated\n `docs/data/generated/dev-docs.json`, and PRD edits follow\n `docs/prds/RULES.md` and pass `task docs:prds`.\n"
|
||||
"body": "# Development guides\n\nChecklists for changing Archie, one page per area. Each names every place a\nchange must reach, so a feature that works in one layer does not silently stop\nat the next. A change that spans areas starts on the page for the area it\nbegins in, which points to the others. The pages point at the documents that\nown the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than\nrestating them.\n\n| Area | Covers |\n| ---------------------------------------------- | -------------------------------------------------------------------------------- |\n| [Frontend UI](/dev/development/frontend-ui/) | Anything under `ui/`, and the dashboard's API routes |\n| [Agent](/dev/development/agent/) | The agent container, its image, profiles, tools and workspace |\n| [Workflows](/dev/development/workflows/) | Workflow definitions and step types |\n| [Daemon](/dev/development/daemon/) | Task statuses, fields and the brief; sources, event types, mappings and bindings |\n| [State Store](/dev/development/state-store/) | Stored fields, tables, RPCs and errors |\n| [Control plane and settings](/dev/development/control-plane/) | Settings in `config.toml` or the dashboard |\n| [Processes and wiring](/dev/development/wiring/) | Where code goes, processes, plugin engines, channels, NATS subjects |\n| [Merging work](/dev/development/merging-work/) | Merging a lane or a branch |\n\n## Every change\n\n- Write the failing test first for anything with logic, branching or a\n contract, and check it fails on an assertion, not a compile error.\n- Test through the path production uses. A test that sets a value directly on\n the consumer proves nothing about the layers that normally deliver it.\n- Run `task check` and let its exit status decide the commit:\n `task check \u0026\u0026 git commit ...`. `task test` passes `-short`, which skips the\n process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`\n too when a change crosses a process or the database.\n- Regenerate, never hand-edit, generated output: `task proto:generate`,\n `go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,\n `task ui`, `task docs:artifact`. `task proto:check` compares against the git\n index, so stage regenerated contracts before running it.\n- Stage by path, or read `git status` before `git add -A`. Tests that start\n embedded NATS or write logs must use `t.TempDir()`; anything they leave in the\n tree gets committed. `task check` also adds linter-tool lines to `go.sum`\n (bead 1e37); restore `go.sum` before committing unless you changed a\n dependency.\n- A change to `docs/prds/`, `docs/architecture/` **or `docs/development/`**\n carries the regenerated `docs/data/generated/dev-docs.json`: run\n `task docs:artifact` (not `task docs:check`, which checks contracts only).\n PRD edits also follow `docs/prds/RULES.md` and pass `task docs:prds`.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/development/agent/",
|
||||
@@ -118,7 +118,7 @@
|
||||
"url": "/dev/development/control-plane/",
|
||||
"title": "Control plane and settings",
|
||||
"section": "Development",
|
||||
"body": "# Control plane and settings\n\nAuthority: `docs/architecture/configuration.md`. The wiring matrix, the\ndecoded-but-unwired ledger and the three shapes an unwired field takes are in\n`.agents/skills/archie-config-and-flags`.\n\nA field that parses is not a field that works. Before adding one, name the code\nthat reads it and the path the value takes to get there.\n\n## Decide what kind of setting it is\n\n- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,\n `work_dir`). It stays in the file, is checked by `validateBootstrap` in\n `internal/infrastructure/configuration/validate.go`, and the runtime overlay\n refuses changes to it.\n- **Database-owned** (repository policies, scheduling, tools, plugins,\n channels, containers). The file only seeds it. Once the State Store holds the\n control-plane resource, the stored document is layered over the file\n (`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is\n checked by `validateDatabaseOwned` and by the resource's validator.\n- **Worker-carried.** A value the agent container needs travels in\n `config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it\n as an environment variable the daemon did not already define, and never carry\n a secret this way.\n\n## Adding a database-owned field\n\n1. Add it to the struct the resource's `Document` names in\n `internal/app/controlplane/operational_settings.go`. The resource's JSON\n schema and the dashboard's Advanced settings editor are generated from that\n type, so no UI work is needed for the editor itself.\n2. Stored documents use Go field names as keys (`Image`, `MaxConcurrency`).\n Give the field no `json` tag unless its neighbours have one.\n3. A map or a nested struct needs its layering checked. `json.Unmarshal`\n merges into an existing map, so a stored map would add to the file's rather\n than replace it. A field the stored document omits keeps the file's value\n (a document stored before the field existed). Add a case to\n `internal/app/controlplane/runtime_config_test.go` for both.\n4. Validate it in one function both sides call, and add a case to\n `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in\n `validators_agree_test.go`, so the file and the resource cannot disagree.\n5. Decide whether it reloads: it does only if every consumer re-reads it from\n `config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything\n not on it requires a restart.\n6. If the settings page shows it as a plain field, add it to\n `internal/webui/config_schema.go` and the view in `api_config.go`.\n\n## Every new field\n\n- Test through the layering: build the effective config the way boot does,\n not by setting the field on the consumer.\n- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`\n only when a profile there needs a value different from the default.\n- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.\n- Secrets are `SecretRef`s resolved through the secret registry. Never inspect\n a resolved value, even in a test.\n- Reject a configuration that sets a field with no consumer rather than\n accepting and ignoring it (per-identity `forge.intake` is the precedent).\n"
|
||||
"body": "# Control plane and settings\n\nAuthority: `docs/architecture/configuration.md`. The wiring matrix, the\ndecoded-but-unwired ledger and the three shapes an unwired field takes are in\n`.agents/skills/archie-config-and-flags`.\n\nA field that parses is not a field that works. Before adding one, name the code\nthat reads it and the path the value takes to get there.\n\n## Decide what kind of setting it is\n\n- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,\n `work_dir`). It stays in the file, is checked by `validateBootstrap` in\n `internal/infrastructure/configuration/validate.go`, and the runtime overlay\n refuses changes to it.\n- **Database-owned** (repository policies, scheduling, tools, plugins,\n channels, containers). The file only seeds it. Once the State Store holds the\n control-plane resource, the stored document is layered over the file\n (`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is\n checked by `validateDatabaseOwned` and by the resource's validator.\n- **Worker-carried.** A value the agent container needs travels in\n `config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it\n as an environment variable the daemon did not already define, and never carry\n a secret this way.\n\n## Adding a database-owned field\n\n1. Add it to the struct the resource's `Document` names in\n `internal/app/controlplane/operational_settings.go`. The resource's JSON\n schema and the dashboard's Advanced settings editor are generated from that\n type, so no UI work is needed for the editor itself.\n2. Stored documents use Go field names as keys (`Image`, `MaxConcurrency`).\n Give the field no `json` tag unless its neighbours have one.\n3. A map or a nested struct needs its layering checked. `json.Unmarshal`\n merges into an existing map, so a stored map would add to the file's rather\n than replace it. A field the stored document omits keeps the file's value\n (a document stored before the field existed). Add a case to\n `internal/app/controlplane/runtime_config_test.go` for both.\n4. Validate it in one function both sides call, and add a case to\n `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in\n `validators_agree_test.go`, so the file and the resource cannot disagree.\n5. Decide whether it reloads: it does only if every consumer re-reads it from\n `config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything\n not on it requires a restart.\n6. If the settings page shows it as a plain field, add it to\n `internal/webui/config_schema.go` and the view in `api_config.go`.\n7. A generic catalog resource (`replace` command, not domain-managed, no\n query service) is watched **once per archie-ui process** by `webui.RunLive`,\n then published to every browser through `/api/stream`. Do not add an\n EventSource per resource to a settings store or a gRPC Watch per HTTP client.\n The control-plane server polls `Resource` every 250ms per upstream Watch;\n verify watch count is independent of client count and that late clients get\n the hub's current value (`internal/webui/live_hub_test.go`, real server over\n bufconn). Reopens resume after the last delivered version and charge failed\n attempts; accepting a gRPC stream does not establish its health.\n\n## Every new field\n\n- Test through the layering: build the effective config the way boot does,\n not by setting the field on the consumer.\n- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`\n only when a profile there needs a value different from the default.\n- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.\n- Secrets are `SecretRef`s resolved through the secret registry. Never inspect\n a resolved value, even in a test.\n- Reject a configuration that sets a field with no consumer rather than\n accepting and ignoring it (per-identity `forge.intake` is the precedent).\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/development/daemon/",
|
||||
@@ -130,7 +130,7 @@
|
||||
"url": "/dev/development/frontend-ui/",
|
||||
"title": "Frontend UI",
|
||||
"section": "Development",
|
||||
"body": "# Frontend UI\n\nAuthority: `.agents/skills/archie-web-ui` (stack facts, design-system rules,\ntone and accessibility). This page covers what a change must reach, not how it\nshould look.\n\n## Adding or changing a feature\n\n1. The feature lives in `ui/src/\u003cfeature\u003e/`. Move a helper to `ui/src/base/`\n only when a second feature needs it.\n2. Keep wire shapes, draft state and payload building in a plain `.ts` module\n beside the components (`ui/src/bindings/binding-draft.ts` is the pattern),\n and test it in `ui/test/*.test.ts`. Components stay thin.\n3. Every mutation goes through `api.*` in `ui/src/lib/api`, which sends the\n CSRF and Content-Type headers the server's mutation guard requires. A bare\n `fetch` is refused.\n4. A value the server also describes (task statuses, actions, workflow inputs)\n comes from the server. Keep a local default only so the first render works,\n and keep it in step (`ui/src/lib/task-meta.ts`).\n5. Run `task ui`, `task test:ui` and `cd ui \u0026\u0026 npm run typecheck`. Commit the\n regenerated `ui/dist/`; the Go binaries embed it.\n\n## Adding an API route\n\n1. The handler goes in the `internal/webui/api_\u003cconcern\u003e.go` file for its\n concern. Check the request fully on the server; the UI's checks are only a\n convenience.\n2. A mutation calls `authorizeTaskMutation` first.\n3. A route whose store is not configured answers 503, and\n `internal/app/archieui/degraded_routes_test.go` pins what each route\n returns without its contract. Add the route there.\n4. The dashboard runs in its own process (`archie-ui`) and must not link the\n daemon or the workflow engine (`cmd/archie-ui/architecture_test.go`). Reach\n stored data through `storecontract` interfaces wired in\n `internal/app/archieui/compose.go`.\n5. Settings that live in a control-plane resource need no new route: the\n Advanced settings page edits every resource from its generated schema.\n"
|
||||
"body": "# Frontend UI\n\nAuthority: `.agents/skills/archie-web-ui` (stack facts, design-system rules,\ntone and accessibility). This page covers what a change must reach, not how it\nshould look.\n\n## Adding or changing a feature\n\n1. The feature lives in `ui/src/\u003cfeature\u003e/`. Move a helper to `ui/src/base/`\n only when a second feature needs it.\n2. Keep wire shapes, draft state and payload building in a plain `.ts` module\n beside the components (`ui/src/bindings/binding-draft.ts` is the pattern),\n and test it in `ui/test/*.test.ts`. Components stay thin.\n3. Every mutation goes through `api.*` in `ui/src/lib/api`, which sends the\n CSRF and Content-Type headers the server's mutation guard requires. A bare\n `fetch` is refused.\n4. A value the server also describes (task statuses, actions, workflow inputs)\n comes from the server. Keep a local default only so the first render works,\n and keep it in step (`ui/src/lib/task-meta.ts`).\n5. Run `task ui`, `task test:ui` and `cd ui \u0026\u0026 npm run typecheck`. Commit the\n regenerated `ui/dist/`; the Go binaries embed it. A fresh git worktree has\n no ignored `ui/node_modules`: run `cd ui \u0026\u0026 npm ci` before these commands.\n6. **One long-lived browser connection:** `ui/src/lib/api.ts` has the only\n `new EventSource`, owned by `stores/live-updates.ts`. Feature stores consume\n topics with `live.subscribe(topic, callback)`; do not open a page-owned SSE\n stream. Logs alone opt in while mounted, replacing that same EventSource\n with `?topics=logs\u0026since=\u003clast cursor\u003e`; a browser's `Last-Event-ID` only\n survives its own automatic reconnect, not a newly constructed EventSource.\n Task and log topics resume by cursor; control-plane, identity and apply-status\n topics replay the latest snapshot. Test a fetch and same-origin navigation\n after visiting Settings and Logs: the UI process serves HTTP/1.1 and six\n persistent streams can starve every later browser request.\n\n## Adding an API route\n\n1. The handler goes in the `internal/webui/api_\u003cconcern\u003e.go` file for its\n concern. Check the request fully on the server; the UI's checks are only a\n convenience.\n2. A mutation calls `authorizeTaskMutation` first.\n3. A route whose store is not configured answers 503, and\n `internal/app/archieui/degraded_routes_test.go` pins what each route\n returns without its contract. Add the route there.\n4. The dashboard runs in its own process (`archie-ui`) and must not link the\n daemon or the workflow engine (`cmd/archie-ui/architecture_test.go`). Reach\n stored data through `storecontract` interfaces wired in\n `internal/app/archieui/compose.go`.\n5. Settings that live in a control-plane resource need no new route: the\n Advanced settings page edits every resource from its generated schema.\n6. For a new live topic, add one process-wide producer to `internal/webui`'s\n `RunLive` and fan it through the `/api/stream` hub; `internal/app/archieui/run.go`\n starts the producers with the process context. Never create an upstream\n watch or poller in an HTTP handler. A slow client must reconnect for cursor\n and snapshot repair rather than silently lose an update. Prove the producer\n with several browser clients against the real peer, not just a scripted\n stream; `live_hub_test.go` is the example.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/development/merging-work/",
|
||||
|
||||
@@ -44,6 +44,15 @@ that reads it and the path the value takes to get there.
|
||||
not on it requires a restart.
|
||||
6. If the settings page shows it as a plain field, add it to
|
||||
`internal/webui/config_schema.go` and the view in `api_config.go`.
|
||||
7. A generic catalog resource (`replace` command, not domain-managed, no
|
||||
query service) is watched **once per archie-ui process** by `webui.RunLive`,
|
||||
then published to every browser through `/api/stream`. Do not add an
|
||||
EventSource per resource to a settings store or a gRPC Watch per HTTP client.
|
||||
The control-plane server polls `Resource` every 250ms per upstream Watch;
|
||||
verify watch count is independent of client count and that late clients get
|
||||
the hub's current value (`internal/webui/live_hub_test.go`, real server over
|
||||
bufconn). Reopens resume after the last delivered version and charge failed
|
||||
attempts; accepting a gRPC stream does not establish its health.
|
||||
|
||||
## Every new field
|
||||
|
||||
|
||||
@@ -18,7 +18,18 @@ should look.
|
||||
comes from the server. Keep a local default only so the first render works,
|
||||
and keep it in step (`ui/src/lib/task-meta.ts`).
|
||||
5. Run `task ui`, `task test:ui` and `cd ui && npm run typecheck`. Commit the
|
||||
regenerated `ui/dist/`; the Go binaries embed it.
|
||||
regenerated `ui/dist/`; the Go binaries embed it. A fresh git worktree has
|
||||
no ignored `ui/node_modules`: run `cd ui && npm ci` before these commands.
|
||||
6. **One long-lived browser connection:** `ui/src/lib/api.ts` has the only
|
||||
`new EventSource`, owned by `stores/live-updates.ts`. Feature stores consume
|
||||
topics with `live.subscribe(topic, callback)`; do not open a page-owned SSE
|
||||
stream. Logs alone opt in while mounted, replacing that same EventSource
|
||||
with `?topics=logs&since=<last cursor>`; a browser's `Last-Event-ID` only
|
||||
survives its own automatic reconnect, not a newly constructed EventSource.
|
||||
Task and log topics resume by cursor; control-plane, identity and apply-status
|
||||
topics replay the latest snapshot. Test a fetch and same-origin navigation
|
||||
after visiting Settings and Logs: the UI process serves HTTP/1.1 and six
|
||||
persistent streams can starve every later browser request.
|
||||
|
||||
## Adding an API route
|
||||
|
||||
@@ -35,3 +46,10 @@ should look.
|
||||
`internal/app/archieui/compose.go`.
|
||||
5. Settings that live in a control-plane resource need no new route: the
|
||||
Advanced settings page edits every resource from its generated schema.
|
||||
6. For a new live topic, add one process-wide producer to `internal/webui`'s
|
||||
`RunLive` and fan it through the `/api/stream` hub; `internal/app/archieui/run.go`
|
||||
starts the producers with the process context. Never create an upstream
|
||||
watch or poller in an HTTP handler. A slow client must reconnect for cursor
|
||||
and snapshot repair rather than silently lose an update. Prove the producer
|
||||
with several browser clients against the real peer, not just a scripted
|
||||
stream; `live_hub_test.go` is the example.
|
||||
@@ -37,6 +37,7 @@ restating them.
|
||||
tree gets committed. `task check` also adds linter-tool lines to `go.sum`
|
||||
(bead 1e37); restore `go.sum` before committing unless you changed a
|
||||
dependency.
|
||||
- A change to `docs/prds/` or `docs/architecture/` carries the regenerated
|
||||
`docs/data/generated/dev-docs.json`, and PRD edits follow
|
||||
`docs/prds/RULES.md` and pass `task docs:prds`.
|
||||
- A change to `docs/prds/`, `docs/architecture/` **or `docs/development/`**
|
||||
carries the regenerated `docs/data/generated/dev-docs.json`: run
|
||||
`task docs:artifact` (not `task docs:check`, which checks contracts only).
|
||||
PRD edits also follow `docs/prds/RULES.md` and pass `task docs:prds`.
|
||||
@@ -47,10 +47,6 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
|
||||
name: "daemon log feed", method: http.MethodGet, path: "/api/logs",
|
||||
want: http.StatusOK, emptyJSON: `"disabled":true`,
|
||||
},
|
||||
{
|
||||
name: "daemon log stream", method: http.MethodGet, path: "/api/logs/stream",
|
||||
want: http.StatusServiceUnavailable,
|
||||
},
|
||||
{
|
||||
// Task logs are a State Store read contract now
|
||||
// (archie-core-iaqx), so the route answers with real data
|
||||
|
||||
@@ -75,6 +75,9 @@ func Run(ctx context.Context, options Options) error {
|
||||
log.Error("event pump stopped; the activity feed will only show history", "err", err)
|
||||
}
|
||||
}()
|
||||
liveCtx, stopLive := context.WithCancel(ctx)
|
||||
defer stopLive()
|
||||
go srv.RunLive(liveCtx)
|
||||
|
||||
listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", opts.Listen)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -38,16 +39,23 @@ type applyStatusView struct {
|
||||
// process is running. A process with no apply-status wiring renders an empty
|
||||
// page rather than failing: that is a deployment fact, not an error.
|
||||
func (s *Server) handleApplyStatus(w http.ResponseWriter, r *http.Request) {
|
||||
view := applyStatusView{Records: []applyStatusRecord{}, Processes: applystatus.Processes()}
|
||||
if s.ApplyStatus == nil {
|
||||
writeJSON(w, view)
|
||||
return
|
||||
}
|
||||
records, err := s.ApplyStatus.ListApplyStatus(r.Context())
|
||||
view, err := s.readApplyStatus(r.Context())
|
||||
if err != nil {
|
||||
http.Error(w, "apply status unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
writeJSON(w, view)
|
||||
}
|
||||
|
||||
func (s *Server) readApplyStatus(ctx context.Context) (applyStatusView, error) {
|
||||
view := applyStatusView{Records: []applyStatusRecord{}, Processes: applystatus.Processes()}
|
||||
if s.ApplyStatus == nil {
|
||||
return view, nil
|
||||
}
|
||||
records, err := s.ApplyStatus.ListApplyStatus(ctx)
|
||||
if err != nil {
|
||||
return view, err
|
||||
}
|
||||
now := s.clock()
|
||||
for _, record := range records {
|
||||
view.Records = append(view.Records, applyStatusRecord{
|
||||
@@ -55,7 +63,7 @@ func (s *Server) handleApplyStatus(w http.ResponseWriter, r *http.Request) {
|
||||
Error: record.Error, ReportedAt: record.ReportedAt, State: applyState(record, now),
|
||||
})
|
||||
}
|
||||
writeJSON(w, view)
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// applyState reads staleness before the error: a process that stopped
|
||||
|
||||
@@ -4,10 +4,7 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -126,51 +123,6 @@ func (s *Server) handleControlPlaneCommand(w http.ResponseWriter, r *http.Reques
|
||||
writeJSON(w, controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
|
||||
}
|
||||
|
||||
func (s *Server) handleControlPlaneWatch(w http.ResponseWriter, r *http.Request) {
|
||||
if s.ControlPlane == nil {
|
||||
http.Error(w, "control plane unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
after, err := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
||||
if err != nil && r.URL.Query().Get("after") != "" {
|
||||
http.Error(w, "invalid after version", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
stream, err := s.ControlPlane.Watch(r.Context(), &controlpb.WatchRequest{Kind: r.PathValue("kind"), AfterVersion: after})
|
||||
if err != nil {
|
||||
writeControlPlaneError(w, err)
|
||||
return
|
||||
}
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
// Headers go out now: the browser marks the stream live on them, and an
|
||||
// unchanged resource may send nothing for hours.
|
||||
w.WriteHeader(http.StatusOK)
|
||||
flusher.Flush()
|
||||
for {
|
||||
response, recvErr := stream.Recv()
|
||||
if errors.Is(recvErr, io.EOF) || r.Context().Err() != nil {
|
||||
return
|
||||
}
|
||||
if recvErr != nil {
|
||||
return
|
||||
}
|
||||
payload, marshalErr := json.Marshal(controlPlaneResourceResponse{Resource: controlPlaneResourceView(response.Resource)})
|
||||
if marshalErr != nil {
|
||||
return
|
||||
}
|
||||
if _, err = w.Write(append(append([]byte("data: "), payload...), '\n', '\n')); err != nil {
|
||||
return
|
||||
}
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
func controlPlaneResourceView(resource *controlpb.Resource) controlPlaneResource {
|
||||
if resource == nil {
|
||||
return controlPlaneResource{}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -59,31 +60,18 @@ func (f *controlPlaneClientStub) Watch(context.Context, *controlpb.WatchRequest,
|
||||
return f.watch, f.err
|
||||
}
|
||||
|
||||
// idleWatch is a watch stream with nothing to deliver: Recv blocks until the
|
||||
// request ends, as a real stream does while the resource is unchanged.
|
||||
type idleWatch struct {
|
||||
grpc.ClientStream
|
||||
done <-chan struct{}
|
||||
}
|
||||
|
||||
func (w idleWatch) Recv() (*controlpb.WatchResponse, error) {
|
||||
<-w.done
|
||||
return nil, context.Canceled
|
||||
}
|
||||
|
||||
// TestControlPlaneWatchOpensBeforeTheFirstChange: a browser marks an event
|
||||
// stream live when its headers arrive. Holding them until the first change
|
||||
// leaves every settings card reading "Connecting" on an unchanged resource.
|
||||
func TestControlPlaneWatchOpensBeforeTheFirstChange(t *testing.T) {
|
||||
server := httptest.NewServer((&Server{ControlPlane: &controlPlaneClientStub{watch: idleWatch{done: t.Context().Done()}}}).Handler())
|
||||
// The multiplexed stream answers before any topic changes. An unchanged
|
||||
// resource must not leave the connection pill at Connecting indefinitely.
|
||||
func TestLiveStreamOpensBeforeTheFirstChange(t *testing.T) {
|
||||
server := httptest.NewServer((&Server{Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler)}).Handler())
|
||||
t.Cleanup(server.Close)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/control-plane/watch/workflow-execution-settings", nil)
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/stream", nil)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("watch did not answer before its first change: %v", err)
|
||||
t.Fatalf("stream did not answer before its first change: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if got := response.Header.Get("Content-Type"); got != "text/event-stream" {
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
@@ -34,48 +33,6 @@ func (s *Server) handleIdentitiesList(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, map[string]any{"identities": values})
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentitiesWatch(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Identities == nil {
|
||||
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
var previous string
|
||||
for {
|
||||
values, err := s.Identities.List(r.Context())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if values == nil {
|
||||
values = []identity.Identity{}
|
||||
}
|
||||
payload, err := json.Marshal(map[string]any{"identities": values})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if current := string(payload); current != previous {
|
||||
if _, err = w.Write(append(append([]byte("data: "), payload...), '\n', '\n')); err != nil {
|
||||
return
|
||||
}
|
||||
flusher.Flush()
|
||||
previous = current
|
||||
}
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleIdentityCreate(w http.ResponseWriter, r *http.Request) {
|
||||
var request identityRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
@@ -77,37 +76,6 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleLogStream(w http.ResponseWriter, r *http.Request) {
|
||||
if s.LogFeed == nil {
|
||||
http.Error(w, "live daemon log feed unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
entries := s.LogFeed.Subscribe(r.Context())
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case entry, ok := <-entries:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
_, _ = w.Write([]byte("id: " + strconv.FormatInt(entry.ID, 10) + "\ndata: " + string(data) + "\n\n"))
|
||||
flusher.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mergeComponents(history []string, live []logging.Entry) []string {
|
||||
seen := make(map[string]struct{}, len(history))
|
||||
for _, component := range history {
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
// liveUpdate is one topic's payload. Only durable tasks and the bounded log
|
||||
// feed have replay cursors; resource and identity topics replay their latest
|
||||
// snapshot on every connection instead.
|
||||
type liveUpdate struct {
|
||||
topic string
|
||||
data any
|
||||
}
|
||||
|
||||
type liveSubscriber struct {
|
||||
updates chan liveUpdate
|
||||
stale chan struct{}
|
||||
}
|
||||
|
||||
func (s *Server) publish(update liveUpdate, key string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if key != "" {
|
||||
if s.latest == nil {
|
||||
s.latest = make(map[string]liveUpdate)
|
||||
}
|
||||
if previous, ok := s.latest[key]; ok && reflect.DeepEqual(previous.data, update.data) {
|
||||
return
|
||||
}
|
||||
s.latest[key] = update
|
||||
}
|
||||
for subscriber := range s.conns {
|
||||
select {
|
||||
case subscriber.updates <- update:
|
||||
default:
|
||||
// The client cannot consume a complete stream. Disconnect it so
|
||||
// EventSource reconnects and replays cursors + latest snapshots.
|
||||
delete(s.conns, subscriber)
|
||||
close(subscriber.stale)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// registerSSEConn subscribes before taking a snapshot. Updates published
|
||||
// during catch-up land in the channel; snapshots describe the same point in
|
||||
// time as registration and are sent before the channel is drained.
|
||||
func (s *Server) registerSSEConn() (<-chan liveUpdate, []liveUpdate, <-chan struct{}, func()) {
|
||||
subscriber := &liveSubscriber{updates: make(chan liveUpdate, 64), stale: make(chan struct{})}
|
||||
s.mu.Lock()
|
||||
if s.conns == nil {
|
||||
s.conns = make(map[*liveSubscriber]struct{})
|
||||
}
|
||||
s.conns[subscriber] = struct{}{}
|
||||
keys := make([]string, 0, len(s.latest))
|
||||
for key := range s.latest {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
slices.Sort(keys)
|
||||
snapshot := make([]liveUpdate, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
snapshot = append(snapshot, s.latest[key])
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return subscriber.updates, snapshot, subscriber.stale, func() {
|
||||
s.mu.Lock()
|
||||
delete(s.conns, subscriber)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// RunLive owns the process-wide producers. A browser never creates an upstream
|
||||
// watch or poller, and a late browser gets the last observed values from the
|
||||
// hub. The caller's context owns all producers and their retry timers.
|
||||
func (s *Server) RunLive(ctx context.Context) {
|
||||
if s.Identities != nil {
|
||||
go s.pollIdentities(ctx)
|
||||
}
|
||||
if s.ApplyStatus != nil {
|
||||
go s.pollApplyStatus(ctx)
|
||||
}
|
||||
if s.ControlPlane == nil {
|
||||
return
|
||||
}
|
||||
delay := 250 * time.Millisecond
|
||||
for ctx.Err() == nil {
|
||||
catalog, err := s.ControlPlane.Catalog(ctx, &controlpb.CatalogRequest{})
|
||||
if err == nil {
|
||||
for _, resource := range catalog.Resources {
|
||||
if resource.ApplyMode == "domain-managed" || resource.QueryService != "" || !slices.Contains(resource.Commands, "replace") {
|
||||
continue
|
||||
}
|
||||
go s.watchResource(ctx, resource.Kind)
|
||||
}
|
||||
return
|
||||
}
|
||||
s.logLive("control-plane catalog unavailable; retrying", "retry_in", delay, "err", err)
|
||||
if !waitLive(ctx, delay) {
|
||||
return
|
||||
}
|
||||
delay = min(2*delay, 30*time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) watchResource(ctx context.Context, kind string) {
|
||||
const minDelay, maxDelay = 250 * time.Millisecond, 30 * time.Second
|
||||
var version int64
|
||||
delay := minDelay
|
||||
for ctx.Err() == nil {
|
||||
started := time.Now()
|
||||
progressed := false
|
||||
stream, err := s.ControlPlane.Watch(ctx, &controlpb.WatchRequest{Kind: kind, AfterVersion: version})
|
||||
if err == nil {
|
||||
for ctx.Err() == nil {
|
||||
response, recvErr := stream.Recv()
|
||||
if recvErr != nil {
|
||||
err = recvErr
|
||||
break
|
||||
}
|
||||
if resource := response.GetResource(); resource != nil && resource.Version > version {
|
||||
version = resource.Version
|
||||
progressed = true
|
||||
s.publish(liveUpdate{topic: "control-plane", data: controlPlaneResourceResponse{Resource: controlPlaneResourceView(resource)}}, "control-plane/"+kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
// Acceptance alone is not health: the State Store can accept a gRPC
|
||||
// stream then fail its first read. Charge attempts that end without an
|
||||
// update before twice the prospective retry delay (keepWatch rule).
|
||||
failedDelay := min(2*delay, maxDelay)
|
||||
if progressed || time.Since(started) >= 2*failedDelay {
|
||||
delay = minDelay
|
||||
} else {
|
||||
delay = failedDelay
|
||||
}
|
||||
s.logLive("control-plane watch ended; reconnecting", "kind", kind, "after_version", version, "retry_in", delay, "err", err)
|
||||
if !waitLive(ctx, delay) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) pollIdentities(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
values, err := s.Identities.List(ctx)
|
||||
if err == nil {
|
||||
if values == nil {
|
||||
values = []identity.Identity{}
|
||||
}
|
||||
s.publish(liveUpdate{topic: "identities", data: map[string]any{"identities": values}}, "identities")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) pollApplyStatus(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
// Compute staleness as the existing HTTP projection does, but publish
|
||||
// only when the visible value changes, not on every poll.
|
||||
view, err := s.readApplyStatus(ctx)
|
||||
if err == nil {
|
||||
s.publish(liveUpdate{topic: "apply-status", data: view}, "apply-status")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitLive(ctx context.Context, delay time.Duration) bool {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) logLive(message string, args ...any) {
|
||||
if s.Log != nil {
|
||||
s.Log.Warn(message, args...)
|
||||
} else {
|
||||
slog.Default().Warn(message, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// marshalLiveFrame keeps every topic's shape in one wire envelope. A topic's
|
||||
// existing payload stays intact inside data, including raw resource JSON.
|
||||
func marshalLiveFrame(update liveUpdate) ([]byte, error) {
|
||||
return json.Marshal(struct {
|
||||
Topic string `json:"topic"`
|
||||
Data any `json:"data"`
|
||||
}{update.topic, update.data})
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/controlplane"
|
||||
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/workflowsteps"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
type liveResourceStore struct{ controlplane.ResourceStore }
|
||||
|
||||
func (*liveResourceStore) Resource(_ context.Context, kind string) (storecontract.Resource, error) {
|
||||
if kind == controlplane.PersonasKind {
|
||||
return storecontract.Resource{Kind: kind, Version: 1, Value: []byte(`{"default":"archie","personas":[]}`)}, nil
|
||||
}
|
||||
return storecontract.Resource{}, storecontract.ErrResourceNotFound
|
||||
}
|
||||
|
||||
// The real control-plane server (not a scripted Recv) must keep one upstream
|
||||
// Watch per generic kind independently of how many browser streams connect.
|
||||
// Its 250ms Resource poll runs once per kind, not once per browser.
|
||||
func TestLiveHubSharesRealControlPlaneWatches(t *testing.T) {
|
||||
steps, err := workflowsteps.NewManager()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upstream, err := controlplane.NewServer(&liveResourceStore{}, steps)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var watches atomic.Int32
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
grpcServer := grpc.NewServer(grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
if info.FullMethod == controlpb.ControlPlaneService_Watch_FullMethodName {
|
||||
watches.Add(1)
|
||||
}
|
||||
return handler(srv, stream)
|
||||
}))
|
||||
controlpb.RegisterControlPlaneServiceServer(grpcServer, upstream)
|
||||
go func() { _ = grpcServer.Serve(listener) }()
|
||||
t.Cleanup(func() { grpcServer.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///controlplane", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
|
||||
return listener.DialContext(ctx)
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
srv := &Server{ControlPlane: controlpb.NewControlPlaneServiceClient(conn), Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler)}
|
||||
go srv.RunLive(ctx)
|
||||
catalog, err := upstream.Catalog(ctx, &controlpb.CatalogRequest{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
generic := 0
|
||||
for _, descriptor := range catalog.Resources {
|
||||
if descriptor.ApplyMode != "domain-managed" && descriptor.QueryService == "" {
|
||||
generic++
|
||||
}
|
||||
}
|
||||
waitUntil(t, func() bool { return int(watches.Load()) == generic })
|
||||
waitUntil(t, func() bool {
|
||||
srv.mu.Lock()
|
||||
defer srv.mu.Unlock()
|
||||
_, ok := srv.latest["control-plane/"+controlplane.PersonasKind]
|
||||
return ok
|
||||
})
|
||||
|
||||
httpServer := httptest.NewServer(srv.Handler())
|
||||
defer httpServer.Close()
|
||||
for range 3 {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, httpServer.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line, err := readTopic(bufio.NewScanner(response.Body), "control-plane")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var frame struct {
|
||||
Data controlPlaneResourceResponse `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame.Data.Resource.Kind != controlplane.PersonasKind || frame.Data.Resource.Version != 1 {
|
||||
t.Fatalf("late subscriber got %+v", frame.Data.Resource)
|
||||
}
|
||||
_ = response.Body.Close()
|
||||
}
|
||||
if got := int(watches.Load()); got != generic {
|
||||
t.Fatalf("%d upstream watches after three clients, want %d", got, generic)
|
||||
}
|
||||
}
|
||||
|
||||
func readTopic(scanner *bufio.Scanner, topic string) (string, error) {
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if !strings.HasPrefix(line, "data: ") {
|
||||
continue
|
||||
}
|
||||
data := strings.TrimPrefix(line, "data: ")
|
||||
var frame struct {
|
||||
Topic string `json:"topic"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &frame); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if frame.Topic == topic {
|
||||
return data, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("stream ended before topic " + topic)
|
||||
}
|
||||
|
||||
func waitUntil(t *testing.T, ready func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if ready() {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("live producer did not become ready")
|
||||
}
|
||||
|
||||
type countedIdentities struct {
|
||||
identity.Repository
|
||||
reads atomic.Int32
|
||||
}
|
||||
|
||||
func (f *countedIdentities) List(context.Context) ([]identity.Identity, error) {
|
||||
f.reads.Add(1)
|
||||
return []identity.Identity{identity.System()}, nil
|
||||
}
|
||||
|
||||
func TestIdentitiesPollOnceForSeveralClients(t *testing.T) {
|
||||
identities := &countedIdentities{}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
srv := &Server{Store: &fakeEventStore{}, Log: slog.New(slog.DiscardHandler), Identities: identities}
|
||||
go srv.RunLive(ctx)
|
||||
waitUntil(t, func() bool { return identities.reads.Load() >= 1 })
|
||||
server := httptest.NewServer(srv.Handler())
|
||||
defer server.Close()
|
||||
for range 3 {
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+"/api/stream", nil)
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if _, err := readTopic(bufio.NewScanner(response.Body), "identities"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
waitUntil(t, func() bool { return identities.reads.Load() >= 2 })
|
||||
if got := identities.reads.Load(); got != 2 {
|
||||
t.Fatalf("%d identity reads with three clients, want 2 (one per poll tick)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlowLiveSubscriberIsDisconnectedForSnapshotReplay(t *testing.T) {
|
||||
srv := &Server{}
|
||||
_, _, stale, unregister := srv.registerSSEConn()
|
||||
defer unregister()
|
||||
for i := range 65 {
|
||||
srv.Broadcast(events.Event{ID: int64(i + 1), At: testAt})
|
||||
}
|
||||
select {
|
||||
case <-stale:
|
||||
default:
|
||||
t.Fatal("full subscriber was not disconnected: its dropped updates cannot be replayed until reconnect")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLiveStreamReplaysLogsOnlyWhenRequestedAndResumesBothCursors(t *testing.T) {
|
||||
feed := logging.NewFeed(20)
|
||||
// Feed's production writer stamps IDs; drive it through its public slog handler.
|
||||
log := slog.New(logging.NewFeedHandler(slog.NewTextHandler(new(bytes.Buffer), nil), feed))
|
||||
log.Info("before")
|
||||
srv := &Server{Store: &fakeEventStore{all: []events.Event{{ID: 1, At: testAt}, {ID: 2, At: testAt}}}, Log: slog.New(slog.DiscardHandler), LogFeed: feed}
|
||||
base := httptest.NewServer(srv.Handler())
|
||||
defer base.Close()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
get := func(path string) *http.Response {
|
||||
t.Helper()
|
||||
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, base.URL+path, nil)
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
// A task-only connection must not subscribe to log traffic.
|
||||
plain := get("/api/stream")
|
||||
defer plain.Body.Close()
|
||||
withLogs := get("/api/stream?topics=logs")
|
||||
line, err := readTopic(bufio.NewScanner(withLogs.Body), "logs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var frame struct {
|
||||
Data logging.Entry `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &frame); err != nil || frame.Data.ID != 1 {
|
||||
t.Fatalf("log replay = %q, %v", line, err)
|
||||
}
|
||||
_ = withLogs.Body.Close()
|
||||
log.Info("after")
|
||||
cursor := streamCursors{Tasks: cursor(1), Logs: 1}.id()
|
||||
resumed := get("/api/stream?topics=logs&since=" + cursor)
|
||||
defer resumed.Body.Close()
|
||||
reader := bufio.NewScanner(resumed.Body)
|
||||
line, err = readTopic(reader, "tasks")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var taskFrame struct {
|
||||
Data events.Event `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &taskFrame); err != nil || taskFrame.Data.ID != 2 {
|
||||
t.Fatalf("resumed task = %q, %v", line, err)
|
||||
}
|
||||
line, err = readTopic(reader, "logs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(line), &frame); err != nil || frame.Data.ID != 2 {
|
||||
t.Fatalf("resumed log = %q, %v", line, err)
|
||||
}
|
||||
}
|
||||
@@ -195,8 +195,9 @@ type Server struct {
|
||||
// When Cfg is present, Cfg.Get().Web.TrustForwardedHeaders is also checked.
|
||||
TrustForwardedHeaders bool
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[chan events.Event]struct{}
|
||||
mu sync.Mutex
|
||||
conns map[*liveSubscriber]struct{}
|
||||
latest map[string]liveUpdate
|
||||
}
|
||||
|
||||
func (s *Server) trustForwardedHeaders() bool {
|
||||
@@ -223,17 +224,9 @@ type EventPublisher interface {
|
||||
Publish(events.Event)
|
||||
}
|
||||
|
||||
// Broadcast fans an (ID-stamped) event out to every connected SSE
|
||||
// client; stalled clients drop events rather than blocking the caller.
|
||||
// Broadcast delivers a persisted task event through the shared stream hub.
|
||||
func (s *Server) Broadcast(e events.Event) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for c := range s.conns {
|
||||
select {
|
||||
case c <- e:
|
||||
default:
|
||||
}
|
||||
}
|
||||
s.publish(liveUpdate{topic: "tasks", data: e}, "")
|
||||
}
|
||||
|
||||
func (s *Server) registerCoreRoutes(mux *http.ServeMux) {
|
||||
@@ -292,15 +285,12 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/control-plane/resources/{kind}", s.handleControlPlaneQuery)
|
||||
mux.HandleFunc("GET /api/control-plane/resources/{kind}/history", s.handleControlPlaneHistory)
|
||||
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", s.handleControlPlaneCommand)
|
||||
mux.HandleFunc("GET /api/control-plane/watch/{kind}", s.handleControlPlaneWatch)
|
||||
mux.HandleFunc("GET /api/control-plane/audit", s.handleAudit)
|
||||
mux.HandleFunc("GET /api/identities", s.handleIdentitiesList)
|
||||
mux.HandleFunc("GET /api/identities/watch", s.handleIdentitiesWatch)
|
||||
mux.HandleFunc("POST /api/identities", s.handleIdentityCreate)
|
||||
mux.HandleFunc("POST /api/identities/{id}/{command}", s.handleIdentityCommand)
|
||||
mux.HandleFunc("GET /api/config", s.handleConfig)
|
||||
mux.HandleFunc("GET /api/logs", s.handleLogs)
|
||||
mux.HandleFunc("GET /api/logs/stream", s.handleLogStream)
|
||||
}
|
||||
|
||||
func (s *Server) registerChatRoutes(mux *http.ServeMux) {
|
||||
|
||||
+127
-52
@@ -2,12 +2,14 @@ package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// sseBacklogPageSize bounds one EventsSince fetch during catch-up.
|
||||
@@ -30,61 +32,79 @@ func sseVisible(e events.Event) bool {
|
||||
return !sseNoiseKinds[e.Kind]
|
||||
}
|
||||
|
||||
// handleSSE streams events: catch-up from the store (?since=<event id>, or
|
||||
// the Last-Event-ID header on a reconnect), then live from the broadcast
|
||||
// hub.
|
||||
// handleSSE serves task history, latest resource snapshots, and optional
|
||||
// live logs over one connection. Append-only topics resume from independent
|
||||
// cursors; state topics replay their latest value on each connection.
|
||||
func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
stream, ok := newSSEStream(s.Store, s.Log, w, sseSince(r))
|
||||
cursors := sseCursors(r)
|
||||
stream, ok := newSSEStream(s.Store, s.Log, w, cursors.Tasks)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
stream.logsSince = cursors.Logs
|
||||
|
||||
// Register before reading the backlog. An event published between the
|
||||
// backlog read and subscription would otherwise be lost permanently.
|
||||
conn, unregister := s.registerSSEConn()
|
||||
conn, snapshot, stale, unregister := s.registerSSEConn()
|
||||
defer unregister()
|
||||
var logs <-chan logging.Entry
|
||||
if r.URL.Query().Get("topics") == "logs" && s.LogFeed != nil {
|
||||
logs = s.LogFeed.Subscribe(r.Context())
|
||||
}
|
||||
// Headers make an idle stream live before any resource changes.
|
||||
w.WriteHeader(http.StatusOK)
|
||||
stream.fl.Flush()
|
||||
|
||||
if !stream.catchUp(r.Context(), "") {
|
||||
return
|
||||
}
|
||||
stream.drain(r.Context(), conn)
|
||||
for _, update := range snapshot {
|
||||
if !stream.sendLive(update) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.URL.Query().Get("topics") == "logs" && !stream.sendLogSnapshot(s.LogFeed) {
|
||||
return
|
||||
}
|
||||
stream.drain(r.Context(), conn, stale, logs)
|
||||
}
|
||||
|
||||
// sseSince resolves the cursor a client wants to resume after. A valid
|
||||
// Last-Event-ID header -- how EventSource itself resumes a dropped
|
||||
// connection -- takes precedence over the ?since= query parameter, which
|
||||
// only matters for a client's very first connection. An absent or unparseable
|
||||
// cursor degrades to "from the beginning": a browser holding a legacy integer
|
||||
// id (the pre-cursor id: field) or garbage must not break the feed, exactly
|
||||
// as a failed ParseInt yielded 0 before the cursor became a string.
|
||||
func sseSince(r *http.Request) string {
|
||||
since := r.URL.Query().Get("since")
|
||||
// sseSince is the task-only cursor view retained for legacy clients/tests.
|
||||
// Native reconnects prefer Last-Event-ID; deliberate reconnects use ?since=.
|
||||
// An invalid or pre-cursor integer degrades to replay from the beginning.
|
||||
func sseSince(r *http.Request) string { return sseCursors(r).Tasks }
|
||||
|
||||
type streamCursors struct {
|
||||
Tasks string `json:"tasks"`
|
||||
Logs int64 `json:"logs"`
|
||||
}
|
||||
|
||||
// EventSource only sends Last-Event-ID on reconnects it owns. A deliberate
|
||||
// reconnect (entering/leaving Logs) supplies the same token in ?since=.
|
||||
func sseCursors(r *http.Request) streamCursors {
|
||||
value := r.URL.Query().Get("since")
|
||||
if header := r.Header.Get("Last-Event-ID"); header != "" {
|
||||
since = header
|
||||
value = header
|
||||
}
|
||||
if _, _, ok := storecontract.ParseEventCursor(since); !ok {
|
||||
return ""
|
||||
var cursors streamCursors
|
||||
if data, err := base64.RawURLEncoding.DecodeString(value); err == nil {
|
||||
_ = json.Unmarshal(data, &cursors)
|
||||
} else if _, _, ok := storecontract.ParseEventCursor(value); ok {
|
||||
cursors.Tasks = value // legacy task cursor
|
||||
}
|
||||
return since
|
||||
if _, _, ok := storecontract.ParseEventCursor(cursors.Tasks); !ok {
|
||||
cursors.Tasks = ""
|
||||
}
|
||||
if cursors.Logs < 0 {
|
||||
cursors.Logs = 0
|
||||
}
|
||||
return cursors
|
||||
}
|
||||
|
||||
// registerSSEConn subscribes a channel to Broadcast and returns the
|
||||
// function that unsubscribes it.
|
||||
func (s *Server) registerSSEConn() (chan events.Event, func()) {
|
||||
c := make(chan events.Event, 64)
|
||||
s.mu.Lock()
|
||||
if s.conns == nil {
|
||||
s.conns = map[chan events.Event]struct{}{}
|
||||
}
|
||||
s.conns[c] = struct{}{}
|
||||
s.mu.Unlock()
|
||||
|
||||
return c, func() {
|
||||
s.mu.Lock()
|
||||
delete(s.conns, c)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
func (c streamCursors) id() string {
|
||||
encoded, _ := json.Marshal(c)
|
||||
return base64.RawURLEncoding.EncodeToString(encoded)
|
||||
}
|
||||
|
||||
// sseStream renders one client's event-stream response: an SSE frame per
|
||||
@@ -92,11 +112,12 @@ func (s *Server) registerSSEConn() (chan events.Event, func()) {
|
||||
// running "since" cursor that deduplicates the backlog against live
|
||||
// broadcasts covering the same event.
|
||||
type sseStream struct {
|
||||
store storecontract.TaskStore
|
||||
log *slog.Logger
|
||||
w http.ResponseWriter
|
||||
fl http.Flusher
|
||||
since string
|
||||
store storecontract.TaskStore
|
||||
log *slog.Logger
|
||||
w http.ResponseWriter
|
||||
fl http.Flusher
|
||||
since string
|
||||
logsSince int64
|
||||
}
|
||||
|
||||
// newSSEStream builds a stream over w, reporting false if w cannot be
|
||||
@@ -114,12 +135,44 @@ func newSSEStream(st storecontract.TaskStore, log *slog.Logger, w http.ResponseW
|
||||
// send writes one event as an SSE frame. It reports false on a write
|
||||
// error, meaning the connection is gone and the caller must stop.
|
||||
func (s *sseStream) send(e events.Event) bool {
|
||||
body, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
s.log.Error("sse event marshal failed", "error", err, "event_id", e.ID)
|
||||
return s.writeLive(liveUpdate{topic: "tasks", data: e}, streamCursors{Tasks: storecontract.EventCursor(e.At, e.ID), Logs: s.logsSince}.id())
|
||||
}
|
||||
|
||||
func (s *sseStream) sendLogSnapshot(feed *logging.Feed) bool {
|
||||
if feed == nil {
|
||||
return s.sendLive(liveUpdate{topic: "logs-status", data: map[string]bool{"available": false}})
|
||||
}
|
||||
for _, entry := range feed.Snapshot() {
|
||||
if !s.sendLog(entry) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *sseStream) sendLog(entry logging.Entry) bool {
|
||||
if entry.ID <= s.logsSince {
|
||||
return true
|
||||
}
|
||||
if !s.writeLive(liveUpdate{topic: "logs", data: entry}, streamCursors{Tasks: s.since, Logs: entry.ID}.id()) {
|
||||
return false
|
||||
}
|
||||
if _, err := s.w.Write([]byte("id: " + storecontract.EventCursor(e.At, e.ID) + "\ndata: " + string(body) + "\n\n")); err != nil {
|
||||
s.logsSince = entry.ID
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *sseStream) sendLive(update liveUpdate) bool { return s.writeLive(update, "") }
|
||||
|
||||
func (s *sseStream) writeLive(update liveUpdate, id string) bool {
|
||||
body, err := marshalLiveFrame(update)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
prefix := ""
|
||||
if id != "" {
|
||||
prefix = "id: " + id + "\n"
|
||||
}
|
||||
if _, err := s.w.Write([]byte(prefix + "data: " + string(body) + "\n\n")); err != nil {
|
||||
return false
|
||||
}
|
||||
s.fl.Flush()
|
||||
@@ -190,25 +243,47 @@ func (s *sseStream) sendPage(backlog []events.Event, target string) (reachedTarg
|
||||
// first fills any persisted gap ahead of it, then is delivered directly if
|
||||
// catch-up did not already cover it -- both paths go through the same
|
||||
// since-based deduplication.
|
||||
func (s *sseStream) drain(ctx context.Context, conn <-chan events.Event) {
|
||||
func (s *sseStream) drain(ctx context.Context, conn <-chan liveUpdate, stale <-chan struct{}, logs <-chan logging.Entry) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case e := <-conn:
|
||||
cursor := storecontract.EventCursor(e.At, e.ID)
|
||||
if cursor <= s.since {
|
||||
case <-stale:
|
||||
return
|
||||
case entry, ok := <-logs:
|
||||
if !ok {
|
||||
logs = nil
|
||||
continue
|
||||
}
|
||||
if !s.catchUp(ctx, cursor) {
|
||||
if !s.sendLog(entry) {
|
||||
return
|
||||
}
|
||||
if cursor > s.since {
|
||||
if sseVisible(e) && !s.send(e) {
|
||||
case update := <-conn:
|
||||
if update.topic == "tasks" {
|
||||
e, ok := update.data.(events.Event)
|
||||
if ok && !s.relayTask(ctx, e) {
|
||||
return
|
||||
}
|
||||
s.since = cursor
|
||||
} else if !s.sendLive(update) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sseStream) relayTask(ctx context.Context, e events.Event) bool {
|
||||
cursor := storecontract.EventCursor(e.At, e.ID)
|
||||
if cursor <= s.since {
|
||||
return true
|
||||
}
|
||||
if !s.catchUp(ctx, cursor) {
|
||||
return false
|
||||
}
|
||||
if cursor > s.since {
|
||||
if sseVisible(e) && !s.send(e) {
|
||||
return false
|
||||
}
|
||||
s.since = cursor
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -171,6 +172,25 @@ func TestSSEStreamCatchUpPagesAcrossMultipleFetches(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Every task frame identifies its topic so one EventSource can dispatch it
|
||||
// without interpreting the event's domain payload.
|
||||
func TestSSETaskFrameCarriesTopic(t *testing.T) {
|
||||
stream, rec := newTestSSEStream("")
|
||||
if !stream.send(events.Event{ID: 1, At: testAt, Kind: events.KindTaskQueued}) {
|
||||
t.Fatal("send failed")
|
||||
}
|
||||
line := strings.Split(rec.Body.String(), "\n")[1]
|
||||
var frame struct {
|
||||
Topic string `json:"topic"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame.Topic != "tasks" {
|
||||
t.Fatalf("topic = %q, want tasks", frame.Topic)
|
||||
}
|
||||
}
|
||||
|
||||
// A target landing exactly on the last event of a full page must still be
|
||||
// recognised as reached, not mistaken for "page not yet exhausted, fetch
|
||||
// another".
|
||||
@@ -229,6 +249,16 @@ func TestSSEStreamSendPageSkipsNoiseKindsButAdvancesSince(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEMultiTopicCursorHeaderWinsOverDeliberateReconnectURL(t *testing.T) {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet,
|
||||
"/api/stream?topics=logs&since="+streamCursors{Tasks: cursor(1), Logs: 4}.id(), nil)
|
||||
request.Header.Set("Last-Event-ID", streamCursors{Tasks: cursor(2), Logs: 5}.id())
|
||||
got := sseCursors(request)
|
||||
if got.Tasks != cursor(2) || got.Logs != 5 {
|
||||
t.Fatalf("cursors = %+v, want tasks 2 and logs 5 from native reconnect", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSESinceDegradesUnparseableCursorToBeginning is the legacy-cursor
|
||||
// tolerance guard: a browser holding the pre-cursor integer id: field, or a
|
||||
// ?since= carrying garbage, must resume from the beginning rather than error
|
||||
|
||||
Vendored
+5
-5
@@ -1,8 +1,8 @@
|
||||
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)}})();function n(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var r={},i=[],a=()=>{},o=()=>!1,s=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),c=e=>e.startsWith(`onUpdate:`),l=Object.assign,u=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},d=Object.prototype.hasOwnProperty,f=(e,t)=>d.call(e,t),p=Array.isArray,m=e=>C(e)===`[object Map]`,h=e=>C(e)===`[object Set]`,g=e=>C(e)===`[object Date]`,_=e=>C(e)===`[object RegExp]`,v=e=>typeof e==`function`,y=e=>typeof e==`string`,b=e=>typeof e==`symbol`,x=e=>typeof e==`object`&&!!e,ee=e=>(x(e)||v(e))&&v(e.then)&&v(e.catch),S=Object.prototype.toString,C=e=>S.call(e),te=e=>C(e).slice(8,-1),ne=e=>C(e)===`[object Object]`,re=e=>y(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ie=n(`,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)),de=ae(e=>e?`on${ue(e)}`:``),w=(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=y(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=n(`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(p(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=y(r)?Ce(r):ye(r);if(i)for(let e in i)t[e]=i[e]}return t}if(y(e)||x(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 T(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;n<e.length;n++){let r=T(e[n]);r&&(t+=r+` `)}else if(x(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&&!y(t)&&(e.class=T(t)),n&&(e.style=ye(n)),e}var Te=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,Ee=n(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=m(e),i=m(t);if(r||i||(r=h(e),i=h(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=g(e),i=g(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=b(e),i=b(t),r||i?e===t:(r=p(e),i=p(t),r||i?r&&i?je(e,t,n,Oe):!1:(r=x(e),i=x(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),E=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===S||!v(e.toString))?Pe(e)?E(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}:b(t)?Ie(t):x(t)&&!p(t)&&!ne(t)?String(t):t,Ie=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Le(e){return e==null?`initial`:tLine 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`)||s(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,s,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,Ci(d),s),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)=>{y(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){v(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 j({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?z(r,{error:e}):null));let a=D(!1),c=D(),d=D(!!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 z(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(p(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(h(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(p(t))i=Ne(t,r.props.value)>-1;else if(h(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?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(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||p(e))return Me(e,t);if(h(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=p(t);if(!n||r||h(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(p(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(h(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=l({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;!v(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 Fp;function Ip(e){Fp=e}var Lp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function Rp(e){let t=e instanceof Lp?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 zp(e,t){let n=await fetch(e,t);if(Fp?.(n.status===401),!n.ok)throw new Lp(await Pp(n),n.status);return n}async function q(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Mp,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 zp(e,s);return a?await c.json():void 0}var J={health:()=>q(`/health/detailed`),summary:()=>q(`/api/summary`),tasks:()=>q(`/api/tasks`),taskMeta:()=>q(`/api/task-meta`),task:e=>q(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>q(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/changes`+Np(t)),taskDebug:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/debug`+Np(t)),taskAction:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>q(`/api/setup`),capabilities:()=>q(`/api/capabilities`),workflows:()=>q(`/api/workflows`),workRequest:e=>q(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>q(`/api/skills`),channels:()=>q(`/api/channels`),curators:()=>q(`/api/curators`),channelReload:e=>q(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>q(`/api/config`),logs:e=>q(`/api/logs`+Np(e)),taskLogs:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/logs`+Np(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>q(`/api/version`),updateSnapshot:()=>q(`/api/chat/update`),updateInstall:e=>q(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>q(`/api/captures`+Np({limit:e})),eventTypes:()=>q(`/api/event-types`),eventTypeCreate:e=>q(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>q(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>q(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>q(`/api/mappings`),mappingCreate:e=>q(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>q(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>q(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>q(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>q(`/api/bindings`),bindingCreate:e=>q(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>q(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>q(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>q(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),sources:()=>q(`/api/sources`),sourceCreate:e=>q(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>q(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>q(`/api/sources/${encodeURIComponent(e)}/approve-unsigned`,{method:`POST`}),sourceSecret:e=>q(`/api/sources/${encodeURIComponent(e)}/secret`,{method:`POST`}),chatSessions:()=>q(`/api/chat/sessions`),chatMessages:e=>q(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>q(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>q(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>q(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:jp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>q(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>q(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>q(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>q(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>zp(`/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 Bp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Vp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Ap(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Hp=`archie.web.chat.channel`;function Up(){let e=localStorage.getItem(Hp);return e||(e=jp(),localStorage.setItem(Hp,e)),e}var Wp=/(?:^|\s)\/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(p(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(h(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(p(t))i=Ne(t,r.props.value)>-1;else if(h(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?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(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||p(e))return Me(e,t);if(h(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=p(t);if(!n||r||h(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(p(e)){if(t.props&&Ne(e,t.props.value)>-1)return{checked:!0}}else if(h(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=l({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;!v(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 Ip;function Lp(e){Ip=e}var Rp=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function zp(e){let t=e instanceof Rp?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 Bp(e,t){let n=await fetch(e,t);if(Ip?.(n.status===401),!n.ok)throw new Rp(await Fp(n),n.status);return n}async function q(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Np,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 Bp(e,s);return a?await c.json():void 0}var J={health:()=>q(`/health/detailed`),summary:()=>q(`/api/summary`),tasks:()=>q(`/api/tasks`),taskMeta:()=>q(`/api/task-meta`),task:e=>q(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>q(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/changes`+Pp(t)),taskDebug:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/debug`+Pp(t)),taskAction:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>q(`/api/setup`),capabilities:()=>q(`/api/capabilities`),workflows:()=>q(`/api/workflows`),workRequest:e=>q(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>q(`/api/skills`),channels:()=>q(`/api/channels`),curators:()=>q(`/api/curators`),channelReload:e=>q(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>q(`/api/config`),logs:e=>q(`/api/logs`+Pp(e)),taskLogs:(e,t)=>q(`/api/tasks/${encodeURIComponent(e)}/logs`+Pp(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>q(`/api/version`),updateSnapshot:()=>q(`/api/chat/update`),updateInstall:e=>q(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>q(`/api/captures`+Pp({limit:e})),eventTypes:()=>q(`/api/event-types`),eventTypeCreate:e=>q(`/api/event-types`,{method:`POST`,body:e}),eventTypeUpdate:(e,t)=>q(`/api/event-types/${encodeURIComponent(e)}`,{method:`PUT`,body:t}),eventTypeDelete:e=>q(`/api/event-types/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappings:()=>q(`/api/mappings`),mappingCreate:e=>q(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>q(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>q(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>q(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>q(`/api/bindings`),bindingCreate:e=>q(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>q(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>q(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>q(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),sources:()=>q(`/api/sources`),sourceCreate:e=>q(`/api/sources`,{method:`POST`,body:{path:e}}),sourceSigning:(e,t)=>q(`/api/sources/${encodeURIComponent(e)}/signing`,{method:`POST`,body:{signed:t}}),sourceApproveUnsigned:e=>q(`/api/sources/${encodeURIComponent(e)}/approve-unsigned`,{method:`POST`}),sourceSecret:e=>q(`/api/sources/${encodeURIComponent(e)}/secret`,{method:`POST`}),chatSessions:()=>q(`/api/chat/sessions`),chatMessages:e=>q(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>q(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>q(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>q(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:Mp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>q(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>q(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>q(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>q(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Bp(`/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 Vp(e,t,n=``,r=!1){let i=new EventSource(jp(n,r));return i.onopen=()=>t(`live`),i.onerror=()=>t(Ap(i.readyState)),i.onmessage=t=>{try{e(JSON.parse(t.data),t.lastEventId)}catch{}},()=>i.close()}var Hp=`archie.web.chat.channel`;function Up(){let e=localStorage.getItem(Hp);return e||(e=Mp(),localStorage.setItem(Hp,e)),e}var Wp=/(?:^|\s)\/([^\s]*)$/,Gp=/(?:^|\s)\/[^\s]*$/,Kp=8;function qp(e,t,n){let r=t.slice(0,n).match(Wp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description?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&&(nm.value=n.session_id),n.type===`delta`&&(o+=n.text,sm.value=sm.value?{...sm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],sm.value=sm.value?{...sm.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`);rm.value=[...rm.value,{from:`assistant`,text:o,tool_calls:a}],sm.value=null,am.value=`Ready`,await Sm()}catch(e){let t=e;t.name===`AbortError`&&!c?(sm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},am.value=`Stopped`):(sm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Zp(r):void 0,isRetry:i},am.value=`Error — retry available`)}finally{clearTimeout(l),bm=null,om.value=!1}}function Fm(){am.value=`Stopping…`,nm.value&&J.chatCancel(nm.value).catch(()=>{}),xm()}function Im(){ia(()=>{Sm().catch(e=>{am.value=e.message||`Chat unavailable`})}),ca(()=>{xm()})}var Lm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Rm=j({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return K(`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)=>(F(),I(`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":O($p),onClick:i[0]||=e=>n(`toggle`)},[R(`span`,{"aria-hidden":`true`,class:T(r(!e.open))},[z(O(Ld),{size:22})],2),R(`span`,{"aria-hidden":`true`,class:T(r(e.open))},[z(O(ef),{size:22})],2)],8,Lm))}});function zm(e){return typeof e==`string`?`'${e}'`:new Um().serialize(e)}var Bm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Vm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Bm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Hm(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&&Vm[n]?Vm[n]:n+128,s=a<128&&Vm[a]?Vm[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 Um=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Hm(e,t):n===`number`&&r===`number`?e-t:Hm(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(Hm),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
|
||||
@@ -15,6 +15,6 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
|
||||
Defaulting to \`null\`.`),null)}function jx(e){return kx(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 \`${Ex}\`.`),Ex)}var Mx=j({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:Ex},getValueLabel:{type:Function,required:!1,default:(e,t)=>kx(e)?`${Math.round(e/t*Ex)}%`: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=Th(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=Th(n,`max`,r,{passive:n.max===void 0});A(()=>i.value,async e=>{let t=Ax(e,n.max);t!==e&&(await or(),i.value=t)},{immediate:!0}),A(()=>n.max,e=>{let t=jx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=U(()=>Ym(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Ox({modelValue:i,max:a,progressState:o}),(e,t)=>(F(),L(O(X),{"as-child":e.asChild,as:e.as,"aria-valuemax":O(a),"aria-valuemin":0,"aria-valuenow":kx(O(i))?O(i):void 0,"aria-valuetext":e.getValueText?.(O(i),O(a)),"aria-label":e.getValueLabel(O(i),O(a)),role:`progressbar`,"data-state":o.value,"data-value":O(i)??void 0,"data-max":O(a)},{default:k(()=>[N(e.$slots,`default`,{modelValue:O(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Nx=j({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=Dx();return Y(),(e,r)=>(F(),L(O(X),H(t,{"data-state":O(n).progressState.value,"data-value":O(n).modelValue?.value??void 0,"data-max":O(n).max.value}),{default:k(()=>[N(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Px=[` `,`Enter`,`ArrowUp`,`ArrowDown`],Fx=[` `,`Enter`];function Ix(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>Lx(e,t,n)):Lx(e,t,n)}function Lx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Wm(e,t)}function Rx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var zx=[`value`],[Bx,Vx]=Km(`SelectRoot`),Hx=j({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=Dn(n),c=Th(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=Th(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=D(),d=D(),f=D({x:0,y:0}),p=U(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Ym(c.value));N_({isProvider:!0});let m=Vh(s),h=Kh(u),g=D(new Set),_=U(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>Lx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Ix(e,t.value,n.by))}return Vx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(F(),L(O(K_),null,{default:k(()=>[N(e.$slots,`default`,{modelValue:O(c),open:O(l)}),O(h)&&e.name?(F(),L(Ux,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:O(o),required:O(i),name:e.name,autocomplete:e.autocomplete,disabled:O(a),value:O(c)},{default:k(()=>[O(Ym)(O(c))?(F(),I(`option`,{key:0,value:e.nullableValue},null,8,zx)):V(`v-if`,!0),(F(!0),I(P,null,M(Array.from(g.value),e=>(F(),I(`option`,H({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):V(`v-if`,!0)]),_:3}))}}),Ux=j({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=D(),r=Bx();A(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:hT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>hT(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=_T(c),u=e+1<n.length?_T(n[e+1]):null;if(l&&u&&vT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=_T(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>hT(e)),rows:r.map(e=>e.map(e=>hT(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:hT(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:hT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function _T(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 vT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var yT={class:`[overflow-wrap:anywhere]`},bT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},xT={class:`font-mono text-[0.85em]`},ST={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},CT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},wT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},TT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},ET={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},DT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},OT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},kT={key:8,class:`mb-2.5 last:mb-0`},AT=j({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=U(()=>gT(t.text));return(e,t)=>(F(),I(`div`,yT,[(F(!0),I(P,null,M(n.value,(e,t)=>(F(),I(P,{key:t},[e.kind===`pre`?(F(),I(`pre`,bT,[R(`code`,xT,E(e.code),1)])):e.kind===`table`?(F(),I(`table`,ST,[R(`thead`,null,[R(`tr`,null,[(F(!0),I(P,null,M(e.head,(e,t)=>(F(),I(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[z(pT,{inline:e},null,8,[`inline`])]))),128))])]),R(`tbody`,null,[(F(!0),I(P,null,M(e.rows,(e,t)=>(F(),I(`tr`,{key:t},[(F(!0),I(P,null,M(e,(e,t)=>(F(),I(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[z(pT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(F(),I(`blockquote`,CT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(F(),I(`h1`,wT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(F(),I(`h2`,TT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(F(),I(`h3`,ET,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(F(),I(`ul`,DT,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(pT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(F(),I(`ol`,OT,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(pT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(F(),I(`p`,kT,[z(pT,{inline:e.inline},null,8,[`inline`])])):V(``,!0)],64))),128))]))}}),jT={class:`truncate`},MT=j({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return F(),L(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-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:k(()=>[z(O(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,jT,E(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),NT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},PT={class:`font-semibold text-foreground`},FT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},IT=j({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=U(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=U(()=>t.tool.parameters||t.tool.Parameters||``),i=U(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=U(()=>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?(F(),L(MT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(F(),I(`div`,NT,[z(O($d),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),R(`span`,PT,E(n.value),1),r.value?(F(),I(`code`,FT,E(r.value),1)):V(``,!0),R(`span`,{class:T(O(K)(`text-fg-muted`,i.value&&`text-danger`))},E(a.value),3)]))}}),LT={key:0,class:`mb-2 grid gap-0.5 text-xs`},RT={key:2,class:`whitespace-pre-wrap`},zT=j({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(F(),I(`div`,{class:T([`flex`,e.assistant?`justify-start`:`justify-end`])},[R(`div`,{class:T(O(K)(`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?(F(),I(`div`,LT,[(F(!0),I(P,null,M(e.tools,(t,n)=>(F(),L(IT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):V(``,!0),e.assistant?(F(),L(AT,{key:1,text:e.text},null,8,[`text`])):(F(),I(`div`,RT,E(e.text),1)),N(t.$slots,`default`)],2)],2))}}),BT={class:`w-full self-center justify-self-center py-6 text-center`},VT={class:`grid gap-2`},HT=[`onClick`],UT=j({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(F(),I(`div`,BT,[t[0]||=R(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>cA?`${n.slice(0,cA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var uA=[`title`],dA=j({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=U(()=>Vk(n.event)),a=U(()=>lA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=U(()=>n.event.at?fO(n.event.at):`—`);return(e,t)=>(F(),L(O(cO),{class:T(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:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[B(E(n.event.kind||n.event.type||`event`),1)]),_:1}),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(i.value>0?`#${i.value}`:`—`),1)]),_:1}),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},E(a.value.text),9,uA)]),_:1}),z(O(Q),null,{default:k(()=>[B(E(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function fA(e,t){return`${e}:${t??0}`}function pA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=fA(lA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var mA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},hA={class:`max-h-[28rem] overflow-y-auto`},gA=[`aria-expanded`,`aria-label`,`onClick`],_A=[`title`],vA=j({__name:`LiveActivityCard`,setup(e){let t=fE(),{activity:n,streamKind:r,streamState:i}=od(mk()),a=rn(new Set),o=U(()=>pA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return lA(e.representative)}function u(e){return e.representative.at?fO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(F(),L(O(QD),null,{default:k(()=>[z(O(rO),null,{default:k(()=>[z(O(iO),null,{default:k(()=>[...t[0]||=[B(`Live activity`,-1)]]),_:1}),z(O($D),null,{default:k(()=>[z(O(zO),{variant:O(r)},{default:k(()=>[B(E(O(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),z(O(eO),null,{default:k(()=>[R(`div`,mA,[R(`div`,hA,[z(O(oO),null,{default:k(()=>[z(O(dO),{class:`sticky top-0 z-10 bg-card`},{default:k(()=>[z(O(cO),null,{default:k(()=>[z(O($),null,{default:k(()=>[...t[1]||=[B(`Event`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[2]||=[B(`Task`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[3]||=[B(`Detail`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[4]||=[B(`When`,-1)]]),_:1})]),_:1})]),_:1}),z(O(sO),null,{default:k(()=>[O(n).length?V(``,!0):(F(),L(O(cO),{key:0},{default:k(()=>[z(O(Q),{colspan:`4`},{default:k(()=>[z(O(jO),null,{default:k(()=>[z(O(PO),null,{default:k(()=>[z(O(LO),null,{default:k(()=>[...t[5]||=[B(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),O(n).length?(F(!0),I(P,{key:1},M(o.value,e=>(F(),I(P,{key:e.key},[e.count===1?(F(),L(dA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(F(),I(P,{key:1},[z(O(cO),{class:T(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[R(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(F(),L(O(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(F(),L(O(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),B(` `+E(e.label)+` `,1),z(O(zO),{variant:`idle`},{default:k(()=>[B(`×`+E(e.count),1)]),_:2},1024)],8,gA)]),_:2},1024),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},E(l(e).text),9,_A)]),_:2},1024),z(O(Q),null,{default:k(()=>[B(E(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(F(!0),I(P,{key:0},M(e.events,(t,n)=>(F(),L(dA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):V(``,!0)],64))],64))),128)):V(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),yA=j({__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=sC(t,`class`);return(e,r)=>(F(),L(O(Mx),H({"data-slot":`progress`},O(n),{class:O(K)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:k(()=>[z(O(Nx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
|
||||
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function Yj(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function Xj(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function Zj(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function Qj(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}function $j(e,t){return t?e.filter(e=>e.event_type_id===t):[]}function eM(e){return(e?.repository??`required`)!==`none`}function tM(e,t){return e.filter(e=>t===`any`||e.type===`any`||e.type===t)}function nM(e,t){switch(t){case`string`:return e;case`number`:return e.trim()!==``&&!Number.isNaN(Number(e))?Number(e):e;case`bool`:return e===`true`||e!==`false`&&e;default:try{return JSON.parse(e)}catch{return e}}}var rM={pending_approval:`pending approval`,armed:`armed`},iM={pending_approval:`warn`,armed:`ok`};function aM(e){return e?rM[e]??e:`unknown`}function oM(e){return iM[e??``]??`idle`}function sM(){return{id:null,name:``,eventTypeId:``,mappingId:``,filter:``,workflow:``,owner:``,repo:``,repoParam:``,inputs:{}}}function cM(e,t){let n=t.find(t=>t.id===e.mapping_id);return{id:e.id,name:e.name,eventTypeId:n?.event_type_id||``,mappingId:e.mapping_id||``,filter:e.filter||``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,repoParam:e.repo_param||``,inputs:Object.fromEntries(Object.entries(e.inputs??{}).map(([e,t])=>[e,{param:t.param??``,value:t.param?``:typeof t.value==`string`?t.value:JSON.stringify(t.value)}]))}}function lM(e,t,n){let r=t.find(t=>t.id===e.eventTypeId),i=n?.inputs??{},a={};for(let[t,n]of Object.entries(i)){let r=e.inputs[t];r?.param?a[t]={param:r.param}:r&&r.value!==``&&(a[t]={value:nM(r.value,n.type)})}let o=eM(n);return{name:e.name,matcher:{source:r?.source||``},mapping_id:e.mappingId,filter:e.filter.trim(),workflow:e.workflow,owner:o&&!e.repoParam?e.owner:``,repo:o&&!e.repoParam?e.repo:``,repo_param:o?e.repoParam:``,inputs:a}}function uM(e){return e.repo_param?`from ${e.repo_param}`:e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`}function dM(e,t){return t.find(t=>t.id===e.mapping_id)?.event_type_id}var fM={class:`font-mono`},pM={class:`text-fg-muted`},mM={class:`grid grid-cols-2 items-start gap-3`},hM={class:`grid grid-cols-2 items-start gap-3`},gM=`__constant__`,_M=`__none__`,vM=j({__name:`BindingEditor`,props:Va({binding:{},mappings:{},eventTypes:{},workflows:{},saving:{type:Boolean},error:{}},{open:{type:Boolean,required:!0},openModifiers:{}}),emits:Va([`save`],[`update:open`]),setup(e,{emit:t}){let n=e,r=lo(e,`open`),i=t,a=D(sM());A(r,e=>{e&&(a.value=n.binding?cM(n.binding,n.mappings):sM())},{immediate:!0});let o=U(()=>$j(n.mappings,a.value.eventTypeId));A(()=>a.value.eventTypeId,()=>{o.value.some(e=>e.id===a.value.mappingId)||(a.value.mappingId=``)});let s=U(()=>n.workflows.find(e=>e.id===a.value.workflow)),c=U(()=>Object.entries(s.value?.inputs??{}).sort(([e],[t])=>e.localeCompare(t))),l=U(()=>n.mappings.find(e=>e.id===a.value.mappingId)?.fields??[]),u=U(()=>tM(l.value,`string`));function d(e){return a.value.inputs[e]??={param:``,value:``},a.value.inputs[e]}function f(e){return d(e).param||gM}function p(e,t){d(e).param=t===gM?``:String(t)}let m=U({get:()=>a.value.repoParam||_M,set:e=>{a.value.repoParam=e===_M?``:e}}),h=U(()=>n.binding?`Edit binding`:`New binding`);return(e,t)=>(F(),L(O(Vj),{open:r.value,"onUpdate:open":t[10]||=e=>r.value=e},{default:k(()=>[z(O(Uj),{class:`max-h-[85vh] overflow-y-auto sm:max-w-lg`},{default:k(()=>[z(O(Kj),null,{default:k(()=>[z(O(qj),null,{default:k(()=>[B(E(h.value),1)]),_:1}),z(O(Wj),null,{default:k(()=>[...t[11]||=[B(` A binding is not armed until it is approved, and editing one drops it back to pending approval. `,-1)]]),_:1})]),_:1}),R(`form`,{onSubmit:t[9]||=uu(e=>i(`save`,a.value),[`prevent`])},[z(O(HC),null,{default:k(()=>[z(O(BC),null,{default:k(()=>[z(O(WC),{for:`binding-name`},{default:k(()=>[...t[12]||=[B(`Name`,-1)]]),_:1}),z(O(WO),{id:`binding-name`,modelValue:a.value.name,"onUpdate:modelValue":t[0]||=e=>a.value.name=e},null,8,[`modelValue`])]),_:1}),z(O(BC),null,{default:k(()=>[z(O(WC),{for:`binding-event-type`},{default:k(()=>[...t[13]||=[B(`Event type`,-1)]]),_:1}),z(O(qS),{modelValue:a.value.eventTypeId,"onUpdate:modelValue":t[1]||=e=>a.value.eventTypeId=e},{default:k(()=>[z(O(kC),{id:`binding-event-type`,class:`w-full`},{default:k(()=>[z(O(AC),{placeholder:`Pick an event type`})]),_:1}),z(O(CC),null,{default:k(()=>[z(O(wC),null,{default:k(()=>[(F(!0),I(P,null,M(n
Line truncated
|
||||
`)}),t}function _T(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 vT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var yT={class:`[overflow-wrap:anywhere]`},bT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},xT={class:`font-mono text-[0.85em]`},ST={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},CT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},wT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},TT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},ET={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},DT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},OT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},kT={key:8,class:`mb-2.5 last:mb-0`},AT=j({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=U(()=>gT(t.text));return(e,t)=>(F(),I(`div`,yT,[(F(!0),I(P,null,M(n.value,(e,t)=>(F(),I(P,{key:t},[e.kind===`pre`?(F(),I(`pre`,bT,[R(`code`,xT,E(e.code),1)])):e.kind===`table`?(F(),I(`table`,ST,[R(`thead`,null,[R(`tr`,null,[(F(!0),I(P,null,M(e.head,(e,t)=>(F(),I(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[z(pT,{inline:e},null,8,[`inline`])]))),128))])]),R(`tbody`,null,[(F(!0),I(P,null,M(e.rows,(e,t)=>(F(),I(`tr`,{key:t},[(F(!0),I(P,null,M(e,(e,t)=>(F(),I(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[z(pT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(F(),I(`blockquote`,CT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(F(),I(`h1`,wT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(F(),I(`h2`,TT,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(F(),I(`h3`,ET,[z(pT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(F(),I(`ul`,DT,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(pT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(F(),I(`ol`,OT,[(F(!0),I(P,null,M(e.items,(e,t)=>(F(),I(`li`,{key:t},[z(pT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(F(),I(`p`,kT,[z(pT,{inline:e.inline},null,8,[`inline`])])):V(``,!0)],64))),128))]))}}),jT={class:`truncate`},MT=j({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ha(`RouterLink`);return F(),L(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-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:k(()=>[z(O(bd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),R(`span`,jT,E(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),NT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},PT={class:`font-semibold text-foreground`},FT={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},IT=j({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=U(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=U(()=>t.tool.parameters||t.tool.Parameters||``),i=U(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=U(()=>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?(F(),L(MT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(F(),I(`div`,NT,[z(O($d),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),R(`span`,PT,E(n.value),1),r.value?(F(),I(`code`,FT,E(r.value),1)):V(``,!0),R(`span`,{class:T(O(K)(`text-fg-muted`,i.value&&`text-danger`))},E(a.value),3)]))}}),LT={key:0,class:`mb-2 grid gap-0.5 text-xs`},RT={key:2,class:`whitespace-pre-wrap`},zT=j({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(F(),I(`div`,{class:T([`flex`,e.assistant?`justify-start`:`justify-end`])},[R(`div`,{class:T(O(K)(`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?(F(),I(`div`,LT,[(F(!0),I(P,null,M(e.tools,(t,n)=>(F(),L(IT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):V(``,!0),e.assistant?(F(),L(AT,{key:1,text:e.text},null,8,[`text`])):(F(),I(`div`,RT,E(e.text),1)),N(t.$slots,`default`)],2)],2))}}),BT={class:`w-full self-center justify-self-center py-6 text-center`},VT={class:`grid gap-2`},HT=[`onClick`],UT=j({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(F(),I(`div`,BT,[t[0]||=R(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>cA?`${n.slice(0,cA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var uA=[`title`],dA=j({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=U(()=>Vk(n.event)),a=U(()=>lA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=U(()=>n.event.at?fO(n.event.at):`—`);return(e,t)=>(F(),L(O(cO),{class:T(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:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[B(E(n.event.kind||n.event.type||`event`),1)]),_:1}),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(i.value>0?`#${i.value}`:`—`),1)]),_:1}),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},E(a.value.text),9,uA)]),_:1}),z(O(Q),null,{default:k(()=>[B(E(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function fA(e,t){return`${e}:${t??0}`}function pA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=fA(lA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var mA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},hA={class:`max-h-[28rem] overflow-y-auto`},gA=[`aria-expanded`,`aria-label`,`onClick`],_A=[`title`],vA=j({__name:`LiveActivityCard`,setup(e){let t=fE(),{activity:n,streamKind:r,streamState:i}=od(gO()),a=rn(new Set),o=U(()=>pA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return lA(e.representative)}function u(e){return e.representative.at?fO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(F(),L(O(QD),null,{default:k(()=>[z(O(rO),null,{default:k(()=>[z(O(iO),null,{default:k(()=>[...t[0]||=[B(`Live activity`,-1)]]),_:1}),z(O($D),null,{default:k(()=>[z(O(UO),{variant:O(r)},{default:k(()=>[B(E(O(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),z(O(eO),null,{default:k(()=>[R(`div`,mA,[R(`div`,hA,[z(O(oO),null,{default:k(()=>[z(O(dO),{class:`sticky top-0 z-10 bg-card`},{default:k(()=>[z(O(cO),null,{default:k(()=>[z(O($),null,{default:k(()=>[...t[1]||=[B(`Event`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[2]||=[B(`Task`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[3]||=[B(`Detail`,-1)]]),_:1}),z(O($),null,{default:k(()=>[...t[4]||=[B(`When`,-1)]]),_:1})]),_:1})]),_:1}),z(O(sO),null,{default:k(()=>[O(n).length?V(``,!0):(F(),L(O(cO),{key:0},{default:k(()=>[z(O(Q),{colspan:`4`},{default:k(()=>[z(O(FO),null,{default:k(()=>[z(O(RO),null,{default:k(()=>[z(O(VO),null,{default:k(()=>[...t[5]||=[B(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),O(n).length?(F(!0),I(P,{key:1},M(o.value,e=>(F(),I(P,{key:e.key},[e.count===1?(F(),L(dA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(F(),I(P,{key:1},[z(O(cO),{class:T(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),fu(uu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:k(()=>[z(O(Q),{class:`font-medium`},{default:k(()=>[R(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:uu(t=>s(e.key),[`stop`])},[c(e)?(F(),L(O(Sd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(F(),L(O(wd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),B(` `+E(e.label)+` `,1),z(O(UO),{variant:`idle`},{default:k(()=>[B(`×`+E(e.count),1)]),_:2},1024)],8,gA)]),_:2},1024),z(O(Q),{class:`font-mono`},{default:k(()=>[B(E(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),z(O(Q),{class:`w-[55%] max-w-0`},{default:k(()=>[R(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},E(l(e).text),9,_A)]),_:2},1024),z(O(Q),null,{default:k(()=>[B(E(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(F(!0),I(P,{key:0},M(e.events,(t,n)=>(F(),L(dA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):V(``,!0)],64))],64))),128)):V(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),yA=j({__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=sC(t,`class`);return(e,r)=>(F(),L(O(Mx),H({"data-slot":`progress`},O(n),{class:O(K)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:k(()=>[z(O(Nx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ye(`transLine truncated
|
||||
`)){let e=n.indexOf(`:`);if(e<=0)continue;let r=n.slice(0,e).trim();r&&(t[r]=n.slice(e+1).trim())}return t}function Yj(e,t){if(!e.event_type)return{label:`Unidentified`,identified:!1};let n=t.find(t=>t.id===e.event_type);return{label:n?n.name:`Deleted type`,identified:!0}}function Xj(e,t){if(!e)return`No event type`;let n=t.find(t=>t.id===e);return n?`${n.source} / ${n.name}`:`Deleted type`}function Zj(e){let t=[...(e.headers||[]).map(e=>`${e.name} = ${e.value}`),...(e.payload||[]).map(e=>e.op===`present`?`${e.path} present`:`${e.path} = ${e.value??``}`)];return t.length?t.join(` · `):`any event`}function Qj(e){return{headers:(e.headers||[]).filter(e=>e.name.trim()!==``).map(e=>({name:e.name.trim(),value:e.value})),payload:(e.payload||[]).filter(e=>e.path.trim()!==``).map(e=>e.op===`present`?{path:e.path.trim(),op:e.op}:{path:e.path.trim(),op:e.op,value:e.value??``})}}function $j(e,t){return t?e.filter(e=>e.event_type_id===t):[]}function eM(e){return(e?.repository??`required`)!==`none`}function tM(e,t){return e.filter(e=>t===`any`||e.type===`any`||e.type===t)}function nM(e,t){switch(t){case`string`:return e;case`number`:return e.trim()!==``&&!Number.isNaN(Number(e))?Number(e):e;case`bool`:return e===`true`||e!==`false`&&e;default:try{return JSON.parse(e)}catch{return e}}}var rM={pending_approval:`pending approval`,armed:`armed`},iM={pending_approval:`warn`,armed:`ok`};function aM(e){return e?rM[e]??e:`unknown`}function oM(e){return iM[e??``]??`idle`}function sM(){return{id:null,name:``,eventTypeId:``,mappingId:``,filter:``,workflow:``,owner:``,repo:``,repoParam:``,inputs:{}}}function cM(e,t){let n=t.find(t=>t.id===e.mapping_id);return{id:e.id,name:e.name,eventTypeId:n?.event_type_id||``,mappingId:e.mapping_id||``,filter:e.filter||``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,repoParam:e.repo_param||``,inputs:Object.fromEntries(Object.entries(e.inputs??{}).map(([e,t])=>[e,{param:t.param??``,value:t.param?``:typeof t.value==`string`?t.value:JSON.stringify(t.value)}]))}}function lM(e,t,n){let r=t.find(t=>t.id===e.eventTypeId),i=n?.inputs??{},a={};for(let[t,n]of Object.entries(i)){let r=e.inputs[t];r?.param?a[t]={param:r.param}:r&&r.value!==``&&(a[t]={value:nM(r.value,n.type)})}let o=eM(n);return{name:e.name,matcher:{source:r?.source||``},mapping_id:e.mappingId,filter:e.filter.trim(),workflow:e.workflow,owner:o&&!e.repoParam?e.owner:``,repo:o&&!e.repoParam?e.repo:``,repo_param:o?e.repoParam:``,inputs:a}}function uM(e){return e.repo_param?`from ${e.repo_param}`:e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`}function dM(e,t){return t.find(t=>t.id===e.mapping_id)?.event_type_id}var fM={class:`font-mono`},pM={class:`text-fg-muted`},mM={class:`grid grid-cols-2 items-start gap-3`},hM={class:`grid grid-cols-2 items-start gap-3`},gM=`__constant__`,_M=`__none__`,vM=j({__name:`BindingEditor`,props:Va({binding:{},mappings:{},eventTypes:{},workflows:{},saving:{type:Boolean},error:{}},{open:{type:Boolean,required:!0},openModifiers:{}}),emits:Va([`save`],[`update:open`]),setup(e,{emit:t}){let n=e,r=lo(e,`open`),i=t,a=D(sM());A(r,e=>{e&&(a.value=n.binding?cM(n.binding,n.mappings):sM())},{immediate:!0});let o=U(()=>$j(n.mappings,a.value.eventTypeId));A(()=>a.value.eventTypeId,()=>{o.value.some(e=>e.id===a.value.mappingId)||(a.value.mappingId=``)});let s=U(()=>n.workflows.find(e=>e.id===a.value.workflow)),c=U(()=>Object.entries(s.value?.inputs??{}).sort(([e],[t])=>e.localeCompare(t))),l=U(()=>n.mappings.find(e=>e.id===a.value.mappingId)?.fields??[]),u=U(()=>tM(l.value,`string`));function d(e){return a.value.inputs[e]??={param:``,value:``},a.value.inputs[e]}function f(e){return d(e).param||gM}function p(e,t){d(e).param=t===gM?``:String(t)}let m=U({get:()=>a.value.repoParam||_M,set:e=>{a.value.repoParam=e===_M?``:e}}),h=U(()=>n.binding?`Edit binding`:`New binding`);return(e,t)=>(F(),L(O(Vj),{open:r.value,"onUpdate:open":t[10]||=e=>r.value=e},{default:k(()=>[z(O(Uj),{class:`max-h-[85vh] overflow-y-auto sm:max-w-lg`},{default:k(()=>[z(O(Kj),null,{default:k(()=>[z(O(qj),null,{default:k(()=>[B(E(h.value),1)]),_:1}),z(O(Wj),null,{default:k(()=>[...t[11]||=[B(` A binding is not armed until it is approved, and editing one drops it back to pending approval. `,-1)]]),_:1})]),_:1}),R(`form`,{onSubmit:t[9]||=uu(e=>i(`save`,a.value),[`prevent`])},[z(O(HC),null,{default:k(()=>[z(O(BC),null,{default:k(()=>[z(O(WC),{for:`binding-name`},{default:k(()=>[...t[12]||=[B(`Name`,-1)]]),_:1}),z(O(JO),{id:`binding-name`,modelValue:a.value.name,"onUpdate:modelValue":t[0]||=e=>a.value.name=e},null,8,[`modelValue`])]),_:1}),z(O(BC),null,{default:k(()=>[z(O(WC),{for:`binding-event-type`},{default:k(()=>[...t[13]||=[B(`Event type`,-1)]]),_:1}),z(O(qS),{modelValue:a.value.eventTypeId,"onUpdate:modelValue":t[1]||=e=>a.value.eventTypeId=e},{default:k(()=>[z(O(kC),{id:`binding-event-type`,class:`w-full`},{default:k(()=>[z(O(AC),{placeholder:`Pick an event type`})]),_:1}),z(O(CC),null,{default:k(()=>[z(O(wC),null,{default:k(()=>[(F(!0),I(P,null,M(n
Line truncated
|
||||
+19
-28
@@ -2,8 +2,9 @@
|
||||
// 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.
|
||||
import { streamStateFor, type StreamState } from "./stream-state";
|
||||
import { randomUUID } from "./uuid";
|
||||
import { streamStateFor, type StreamState } from "./stream-state.ts";
|
||||
import { streamURL } from "./stream-url.ts";
|
||||
import { randomUUID } from "./uuid.ts";
|
||||
|
||||
// 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.
|
||||
@@ -318,38 +319,28 @@ export const api = {
|
||||
* 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 interface StreamFrame {
|
||||
topic: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
/** One EventSource per tab. Re-creating it on Logs entry/exit carries the
|
||||
* last multi-topic cursor in ?since; native reconnects use Last-Event-ID. */
|
||||
export function subscribeEvents(
|
||||
onEvent: (event: unknown) => void,
|
||||
onStateChange?: (state: StreamState) => void,
|
||||
onFrame: (frame: StreamFrame, cursor: string) => void,
|
||||
onStateChange: (state: StreamState) => void,
|
||||
cursor = "",
|
||||
logs = false,
|
||||
): () => void {
|
||||
const src = new EventSource("/api/stream");
|
||||
src.onopen = () => onStateChange?.("live");
|
||||
src.onerror = () => onStateChange?.("reconnecting");
|
||||
src.onmessage = (e) => {
|
||||
const src = new EventSource(streamURL(cursor, logs));
|
||||
src.onopen = () => onStateChange("live");
|
||||
src.onerror = () => onStateChange(streamStateFor(src.readyState));
|
||||
src.onmessage = (event) => {
|
||||
try {
|
||||
onEvent(JSON.parse(e.data));
|
||||
onFrame(JSON.parse(event.data) as StreamFrame, event.lastEventId);
|
||||
} catch {
|
||||
/* a malformed frame should not kill the stream */
|
||||
}
|
||||
};
|
||||
return () => src.close();
|
||||
}
|
||||
|
||||
export function subscribeLogs(
|
||||
onEntry: (entry: unknown) => void,
|
||||
onStateChange?: (state: StreamState) => void,
|
||||
): () => void {
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// A deliberate EventSource replacement does not inherit Last-Event-ID from
|
||||
// its predecessor. Carry the last multi-topic token in the new URL instead.
|
||||
export function streamURL(cursor: string, logs: boolean): string {
|
||||
const params = new URLSearchParams();
|
||||
if (cursor) params.set("since", cursor);
|
||||
if (logs) params.set("topics", "logs");
|
||||
return `/api/stream${params.size ? `?${params}` : ""}`;
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export function logsEmptyDetail(
|
||||
streamState: string,
|
||||
): string {
|
||||
if (streamState === "unavailable") {
|
||||
return "The log stream will reconnect automatically.";
|
||||
return "This process is not delivering live daemon logs.";
|
||||
}
|
||||
if (durableUnavailable) {
|
||||
return "This deployment keeps no durable history. Live daemon logs appear here while the page is open.";
|
||||
|
||||
+17
-5
@@ -1,6 +1,7 @@
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from "vue";
|
||||
|
||||
import { api, subscribeLogs } from "@/lib/api";
|
||||
import { api } from "@/lib/api";
|
||||
import { useLiveUpdatesStore } from "@/stores/live-updates";
|
||||
import type { LogEntry } from "@/lib/log";
|
||||
import type { StatusKind } from "@/lib/status";
|
||||
import type { StreamState } from "@/lib/stream-state";
|
||||
@@ -138,6 +139,7 @@ let unsubscribe: (() => void) | undefined;
|
||||
/** Owns the initial read, the re-reads a filter change causes, and the live
|
||||
* stream, for the page's lifetime. */
|
||||
export function useLogs(): void {
|
||||
const live = useLiveUpdatesStore();
|
||||
onMounted(() => {
|
||||
// A mount opens a new stream against a fresh read, so the tail starts
|
||||
// unpaused, connecting, and without the lines the previous visit's stream
|
||||
@@ -149,11 +151,21 @@ export function useLogs(): void {
|
||||
liveTick.value += 1;
|
||||
|
||||
void loadLogs();
|
||||
unsubscribe = subscribeLogs(handleEntry, (state) => {
|
||||
streamState.value = state;
|
||||
});
|
||||
unsubscribe = live.subscribe("logs", handleEntry);
|
||||
streamState.value = live.streamState;
|
||||
});
|
||||
onUnmounted(() => unsubscribe?.());
|
||||
onUnmounted(() => {
|
||||
unsubscribe?.();
|
||||
unsubscribe = undefined;
|
||||
});
|
||||
watch(() => live.streamState, (state) => {
|
||||
streamState.value = state;
|
||||
});
|
||||
// A process without a LogFeed cannot deliver live entries.
|
||||
const stopStatus = live.subscribe("logs-status", (data) => {
|
||||
if (!(data as { available: boolean }).available) streamState.value = "unavailable";
|
||||
});
|
||||
onUnmounted(stopStatus);
|
||||
|
||||
// Every filter is a server-side one -- the request carries it -- so a change
|
||||
// to any of them is a new read, not a re-filter of what is already here.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, reactive, ref } from "vue";
|
||||
import { computed, onScopeDispose, reactive, ref, watch } from "vue";
|
||||
import { useLiveUpdatesStore } from "./live-updates.ts";
|
||||
|
||||
export interface ResourceDescriptor {
|
||||
kind: string;
|
||||
@@ -229,7 +230,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
const catalog = ref<ResourceDescriptor[]>([]);
|
||||
const catalogError = ref("");
|
||||
const states = reactive<Record<string, ResourceState>>({});
|
||||
const streams = new Map<string, EventSource>();
|
||||
const live = useLiveUpdatesStore();
|
||||
const applyStatus = ref<ApplyStatusResponse>({ records: [], processes: [] });
|
||||
|
||||
const genericResources = computed(() =>
|
||||
@@ -247,7 +248,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
loading: false,
|
||||
saving: false,
|
||||
conflict: false,
|
||||
stream: "connecting",
|
||||
stream: live.streamState === "live" ? "live" : "connecting",
|
||||
};
|
||||
return states[kind];
|
||||
}
|
||||
@@ -278,28 +279,22 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
}
|
||||
}
|
||||
|
||||
function watchResource(kind: string): void {
|
||||
if (streams.has(kind)) return;
|
||||
const state = stateFor(kind);
|
||||
const after = state.resource?.version ?? 0;
|
||||
const stream = new EventSource(
|
||||
`/api/control-plane/watch/${encodeURIComponent(kind)}?after=${after}`,
|
||||
);
|
||||
stream.onopen = () => {
|
||||
state.stream = "live";
|
||||
};
|
||||
stream.onerror = () => {
|
||||
state.stream = "reconnecting";
|
||||
};
|
||||
stream.onmessage = (event) => {
|
||||
try {
|
||||
apply((JSON.parse(event.data) as ResourceResponse).resource);
|
||||
} catch {
|
||||
state.error = "Invalid live update";
|
||||
}
|
||||
};
|
||||
streams.set(kind, stream);
|
||||
}
|
||||
const stopResource = live.subscribe("control-plane", (data) => {
|
||||
const resource = (data as ResourceResponse).resource;
|
||||
if (resource?.kind) apply(resource);
|
||||
});
|
||||
const stopStatus = live.subscribe("apply-status", (data) => {
|
||||
applyStatus.value = data as ApplyStatusResponse;
|
||||
});
|
||||
const stopConnection = watch(() => live.streamState, (state) => {
|
||||
for (const resource of Object.values(states))
|
||||
resource.stream = state === "live" ? "live" : "reconnecting";
|
||||
});
|
||||
onScopeDispose(() => {
|
||||
stopResource();
|
||||
stopStatus();
|
||||
stopConnection();
|
||||
});
|
||||
|
||||
/** Re-read on every load and after each save, so the page reflects what the
|
||||
* processes did with the edit rather than what was stored. A failure leaves
|
||||
@@ -333,12 +328,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
catalog.value = response.resources ?? [];
|
||||
catalogError.value = "";
|
||||
await loadApplyStatus();
|
||||
await Promise.all(
|
||||
genericResources.value.map(async ({ kind }) => {
|
||||
await loadResource(kind);
|
||||
watchResource(kind);
|
||||
}),
|
||||
);
|
||||
await Promise.all(genericResources.value.map(({ kind }) => loadResource(kind)));
|
||||
} catch (error) {
|
||||
catalogError.value = String((error as Error).message || error);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { onScopeDispose, ref } from "vue";
|
||||
import { useLiveUpdatesStore } from "./live-updates";
|
||||
|
||||
export interface Identity {
|
||||
id: string;
|
||||
@@ -27,7 +28,8 @@ export const useIdentitiesStore = defineStore("identities", () => {
|
||||
const identities = ref<Identity[]>([]);
|
||||
const error = ref("");
|
||||
const busy = ref("");
|
||||
let stream: EventSource | undefined;
|
||||
const live = useLiveUpdatesStore();
|
||||
let stop: (() => void) | undefined;
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
@@ -40,25 +42,11 @@ export const useIdentitiesStore = defineStore("identities", () => {
|
||||
}
|
||||
}
|
||||
function watch(): void {
|
||||
if (stream) return;
|
||||
if (stop) return;
|
||||
void load();
|
||||
stream = new EventSource("/api/identities/watch");
|
||||
stream.onmessage = (event) => {
|
||||
try {
|
||||
identities.value = (
|
||||
JSON.parse(event.data) as { identities: Identity[] }
|
||||
).identities;
|
||||
error.value = "";
|
||||
} catch {
|
||||
error.value = "Invalid live update";
|
||||
}
|
||||
};
|
||||
stream.onerror = () => {
|
||||
error.value = "Identity updates disconnected";
|
||||
};
|
||||
onScopeDispose(() => {
|
||||
stream?.close();
|
||||
stream = undefined;
|
||||
stop = live.subscribe("identities", (data) => {
|
||||
identities.value = (data as { identities: Identity[] }).identities;
|
||||
error.value = "";
|
||||
});
|
||||
}
|
||||
async function create(
|
||||
@@ -100,5 +88,6 @@ export const useIdentitiesStore = defineStore("identities", () => {
|
||||
busy.value = "";
|
||||
}
|
||||
}
|
||||
onScopeDispose(() => stop?.());
|
||||
return { identities, error, busy, watch, create, command };
|
||||
});
|
||||
@@ -8,14 +8,14 @@ import {
|
||||
type ComputedRef,
|
||||
} from "vue";
|
||||
|
||||
import { setAuthenticationStateHandler, subscribeEvents } from "@/lib/api";
|
||||
import { setAuthenticationStateHandler, subscribeEvents, type StreamFrame } from "../lib/api.ts";
|
||||
import type { StatusKind } from "@/lib/status";
|
||||
import type { StreamState } from "@/lib/stream-state";
|
||||
import {
|
||||
resourcesForEvent,
|
||||
type LiveEvent,
|
||||
type LiveResource,
|
||||
} from "./live-events";
|
||||
} from "./live-events.ts";
|
||||
|
||||
export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
const streamState = ref<StreamState | "connecting">("connecting");
|
||||
@@ -30,6 +30,9 @@ export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
updates: 0,
|
||||
});
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
let cursor = "";
|
||||
let logsReaders = 0;
|
||||
const listeners = new Map<string, Set<(data: unknown) => void>>();
|
||||
|
||||
const streamKind: ComputedRef<StatusKind> = computed(() => {
|
||||
if (streamState.value === "live") return "ok";
|
||||
@@ -42,15 +45,41 @@ export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
for (const resource of resourcesForEvent(event)) revisions[resource] += 1;
|
||||
}
|
||||
|
||||
function handleFrame(frame: StreamFrame, lastEventId: string): void {
|
||||
if (lastEventId) cursor = lastEventId;
|
||||
if (frame.topic === "tasks") receive(frame.data);
|
||||
for (const listener of listeners.get(frame.topic) ?? []) listener(frame.data);
|
||||
}
|
||||
|
||||
function connect(): void {
|
||||
unsubscribe?.();
|
||||
streamState.value = "connecting";
|
||||
unsubscribe = subscribeEvents(handleFrame, (state) => {
|
||||
streamState.value = state;
|
||||
if (state === "live") connectionRevision.value += 1;
|
||||
}, cursor, logsReaders > 0);
|
||||
}
|
||||
|
||||
function initialize(): void {
|
||||
if (unsubscribe) return;
|
||||
setAuthenticationStateHandler((required) => {
|
||||
authenticationRequired.value = required;
|
||||
});
|
||||
unsubscribe = subscribeEvents(receive, (state) => {
|
||||
streamState.value = state;
|
||||
if (state === "live") connectionRevision.value += 1;
|
||||
});
|
||||
connect();
|
||||
}
|
||||
|
||||
/** Subscriptions are local callbacks, not browser connections. Only Logs
|
||||
* changes the upstream topic set and intentionally reconnects the stream. */
|
||||
function subscribe(topic: string, listener: (data: unknown) => void): () => void {
|
||||
const callbacks = listeners.get(topic) ?? new Set<(data: unknown) => void>();
|
||||
callbacks.add(listener);
|
||||
listeners.set(topic, callbacks);
|
||||
if (topic === "logs" && ++logsReaders === 1) connect();
|
||||
return () => {
|
||||
callbacks.delete(listener);
|
||||
if (callbacks.size === 0) listeners.delete(topic);
|
||||
if (topic === "logs" && --logsReaders === 0) connect();
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -62,6 +91,7 @@ export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
streamState,
|
||||
initialize,
|
||||
receive,
|
||||
subscribe,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { streamURL } from "../src/lib/stream-url.ts";
|
||||
import { logsEmptyDetail } from "../src/logs/logs-empty.ts";
|
||||
|
||||
test("deliberate topic reconnect carries the last cursor rather than starting over", () => {
|
||||
const token = "eyJ0YXNrcyI6IjIwMjYtMDEtMDEiLCJsb2dzIjoyfQ";
|
||||
assert.equal(streamURL("", false), "/api/stream");
|
||||
const onLogs = streamURL(token, true);
|
||||
assert.equal(new URL(onLogs, "http://archie-ui").searchParams.get("topics"), "logs");
|
||||
assert.equal(new URL(onLogs, "http://archie-ui").searchParams.get("since"), token);
|
||||
const offLogs = streamURL(token, false);
|
||||
assert.equal(new URL(offLogs, "http://archie-ui").searchParams.get("topics"), null);
|
||||
assert.equal(new URL(offLogs, "http://archie-ui").searchParams.get("since"), token);
|
||||
});
|
||||
|
||||
test("unavailable logs do not promise an automatic reconnect when no feed exists", () => {
|
||||
assert.equal(logsEmptyDetail(true, "unavailable"), "This process is not delivering live daemon logs.");
|
||||
});
|
||||
Reference in new issue
Block a user