Merge pull request #848 from samcharles93/feat/state-store-task-log-download
feat(staterpc): read task logs through the State Store and make them downloadable
This commit is contained in:
commit
2fd0f23971
30 files changed
+2317
-387
No files matched your search
@@ -259,8 +259,9 @@ Methods are named after the store methods so the mapping is unambiguous. `workfl
|
||||
| Dispatch | `ArmedBindingsForSource`, `RecordDispatch`, `ListUndispatchedCaptures` |
|
||||
| BindingTaskCreator | `EnqueueBindingTask` |
|
||||
| Config snapshot | `PutConfigSnapshot`, `GetConfigSnapshot` |
|
||||
| Task log | `ReadTaskLog`, `StreamTaskLogContent` |
|
||||
|
||||
That is **42 unique RPCs** across one service (the `TaskEvents.Close` method is dropped).
|
||||
That is **44 unique RPCs** across one service (the `TaskEvents.Close` method is dropped).
|
||||
`Close()` is **excluded** from the wire (it is server lifecycle, not a client call) — see §11.
|
||||
|
||||
The config-snapshot pair was added by `archie-core-ymut` (see
|
||||
@@ -271,6 +272,19 @@ neither. `ConfigSnapshot.document` is opaque to this contract — the store neit
|
||||
validates it, and `schema` names the projection so a reader can refuse a shape it does not
|
||||
understand.
|
||||
|
||||
The task-log pair was added by `archie-core-iaqx` (see `docs/prds/ui-service-boundary.md`'s
|
||||
route inventory). It is the one surface whose payload is not a row: the store service reads
|
||||
them out of the state directory it owns with `internal/logging`'s own reader, so the wire
|
||||
carries `logging.Entry`/`logging.Query` values and neither side restates the JSONL format.
|
||||
`ReadTaskLog` returns a decoded page and `StreamTaskLogContent` returns the raw bytes
|
||||
server-streamed, because a log file rotates at 20 MB — past gRPC's 4 MiB unary cap — and the
|
||||
same reasoning that made `StreamCaptures` supersede `ListCaptures` applies. `found=false` with
|
||||
no error means the attempt has no log; a service with no reader answers `Unavailable` instead,
|
||||
and the two answers are load-bearing for the dashboard: only the second is a deployment
|
||||
condition, and the panel that collapsed them told operators task logging was switched off when
|
||||
it was not. The Go facade is `storecontract.TaskLogStore` (2 methods), carried by
|
||||
`*staterpc.Client` alongside the rest.
|
||||
|
||||
### Domain types and `values.go` mapping
|
||||
|
||||
`values.go` maps proto ⇄ these types. The task model for the **agent** path is the domain-owned
|
||||
@@ -638,7 +652,7 @@ an explicit operator decision.
|
||||
(`workflow.Store` + `workflow.Task`/`Status`/`Source`, per dependency rules #2 and #7);
|
||||
daemon/webui store surfaces stay **producer-owned** in `internal/store`. `store.WorkflowStore`
|
||||
is superseded by `workflow.Store`.
|
||||
- **One `StateStore` gRPC service** (42 RPCs, grouped by contract) + narrow Go consumer facades
|
||||
- **One `StateStore` gRPC service** (44 RPCs, grouped by contract) + narrow Go consumer facades
|
||||
(≤8) on `staterpc.Client` — mirrors the single-`ChatService` precedent.
|
||||
- **Domain type relocation** (`Task`/`Status`/`Source` → `internal/domain/workflow`) is a
|
||||
Phase 2 prerequisite, pulled forward from migration-decisions §4 (minimal bound,
|
||||
|
||||
@@ -65,7 +65,8 @@ cutover.
|
||||
| `/api/chat/*` | Gateway `ChatContract` and its versioned client | contract seam exists; DTO and stream parity remain |
|
||||
| `/api/tasks/*`, `/api/workflows`, `/api/setup` | State Store read/action contracts plus an explicit execution/admin action contract | State Store adapter exists; UI-facing narrow surface remains |
|
||||
| `/events` | State Store `EventsSince`, polled by one UI-process pump feeding `Server.Broadcast` | RESOLVED (`archie-core-za9f`): see migration-decisions, "Dashboard live event delivery". No new RPC; replay cursor and drop-recovery are the existing `since` watermark in `sse.go` |
|
||||
| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract |
|
||||
| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract. The per-task log routes moved off this row: see `/api/tasks/*` above |
|
||||
| `/api/tasks/{id}/logs`, `/api/tasks/{id}/logs/download` | State Store task-log read contract (`TaskLogStore`: `ReadTaskLog` + `StreamTaskLogContent`), read by the UI process from the service that owns the state directory | RESOLVED (`archie-core-iaqx`): the UI process composes `TaskLogStore` from its own State Store client and serves the attempt log as JSON (`found` distinguishes "no log for this attempt" from "this process cannot read logs") and as a `Content-Disposition` attachment named `task-<id>-attempt-<n>.log`. The daemon's in-process registry is wired as the server-side reader in `internal/app/archied/state_store.go` only (`staterpc.Deps.TaskLogs`), so no process opens another process's log files |
|
||||
| `/api/captures`, `/api/mappings`, `/api/bindings` | State Store contracts, with webhook verification owned by Work Intake/Messaging | RESOLVED (cutover, `archie-core-8cda.5.4`): the UI process composes CaptureStore/MappingStore/BindingStore and mounts the `captureintake.Receiver` from its own State Store client; the daemon's binding-dispatch loop keeps consuming captures from the same store |
|
||||
| `/api/config` (read) | daemon-published `ConfigView` snapshot, read over the State Store contract | RESOLVED (`archie-core-ymut`): see migration-decisions, "Dashboard configuration page" |
|
||||
| `/api/config` (write), `/api/config/reset`, `/api/config/repos/*` | a configuration write contract; the daemon stays the policy owner | DESCOPED for Phase 3 (`archie-core-ymut`), NOT abandoned: 503 in the UI process, SPA hides the controls, editing is config.toml plus reload. Dashboard editing is a tracked feature (`archie-core-1786637498420-327`) and its transport is `archie-core-j28m`; the handlers and their func-field seams on `webui.Server` are kept for it |
|
||||
|
||||
@@ -125,6 +125,22 @@ func (b *boot) openStateStore(ctx context.Context) error {
|
||||
// degrades that group rather than aborting boot.
|
||||
func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants}
|
||||
// Task logs live in the state directory, which this process owns, and the
|
||||
// dashboard process owns no such directory -- so this is where a task-log
|
||||
// read is served from (docs/prds/ui-service-boundary.md). The reader is
|
||||
// the daemon's own registry, built over the same state-directory
|
||||
// derivation this process uses for its SQLite file; both resolve from the
|
||||
// same configured DBPath, so they agree on where archie keeps its state.
|
||||
//
|
||||
// The nil check is on the registry, not on the interface it is assigned
|
||||
// to: a nil *logging.TaskRegistry stored in this field produces a non-nil
|
||||
// interface holding a nil pointer, which the server's own
|
||||
// `deps.TaskLogs == nil` guard would not catch. Leaving the field unset is
|
||||
// what makes the RPC answer Unavailable -- the honest "this process cannot
|
||||
// read logs" -- instead of depending on nil-receiver behaviour to notice.
|
||||
if b.taskLogs != nil {
|
||||
deps.TaskLogs = b.taskLogs
|
||||
}
|
||||
if cs, ok := b.st.(storecontract.CaptureStore); ok {
|
||||
deps.Captures = cs
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
@@ -98,6 +100,35 @@ func TestServeStateStoreServesContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreDepsServeTaskLogs proves the standalone State Store process is
|
||||
// where a task-log read is served from: the daemon process holds no dashboard
|
||||
// listener any more, so the service the UI process dials is the only place this
|
||||
// contract can have a server-side reader, and it must be the daemon's own
|
||||
// registry over the state directory.
|
||||
//
|
||||
// Without this wiring the RPC exists and answers Unavailable for every task,
|
||||
// which the dashboard reports as "this process cannot read logs" -- honest, but
|
||||
// still not a working download (archie-core-iaqx).
|
||||
func TestStateStoreDepsServeTaskLogs(t *testing.T) {
|
||||
b := newBootstrap()
|
||||
logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
b.taskLogs = logs
|
||||
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if deps.TaskLogs == nil {
|
||||
t.Fatal("stateStoreDeps leaves TaskLogs nil; the State Store process is the only server-side reader the dashboard can reach")
|
||||
}
|
||||
if deps.TaskLogs != storecontract.TaskLogStore(logs) {
|
||||
t.Fatalf("TaskLogs = %T, want the daemon's own registry over the state directory", deps.TaskLogs)
|
||||
}
|
||||
// A boot without a registry must not fabricate one: an empty reader would
|
||||
// answer found=false for every attempt, which reads as "the attempt has no
|
||||
// log" rather than "this process cannot read logs".
|
||||
if plain := (&boot{}).stateStoreDeps(&staterpc.TaskGrants{}); plain.TaskLogs != nil {
|
||||
t.Errorf("TaskLogs = %T with no registry on the boot, want nil so the RPC reports unavailability", plain.TaskLogs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStateStoreDataSurvivesRestart is the .4.7 restart/recovery check: a
|
||||
// task written by one archie-state-store process must still be there for a
|
||||
// fresh process opening the same archie.db path, proving b.openStateStore
|
||||
|
||||
@@ -38,12 +38,17 @@ type deps struct {
|
||||
// UpdateRepoField: the configuration owner stays the daemon. The read
|
||||
// crosses as the snapshot ConfigSource renders; the write routes answer
|
||||
// 503 and the page hides their controls (archie-core-ymut).
|
||||
// - LogFeed, TaskLogs, Events, Channels, ReloadChannel, Curators, Memory,
|
||||
// - LogFeed, Events, Channels, ReloadChannel, Curators, Memory,
|
||||
// Workflows, WorkRequests, RunningVersions, Chat.Updates,
|
||||
// UpdateReportPath: no contract exists for these yet.
|
||||
// Defining one amends the owning service's contract first
|
||||
// (docs/prds/ui-service-boundary.md:205-207); the route migration is
|
||||
// archie-core-8cda.5.3.
|
||||
// - TaskLogs: wired below from the store client's TaskLogStore contract.
|
||||
// Task log files live in the state directory the State Store owns, so this
|
||||
// process reads one attempt's log over that contract rather than opening
|
||||
// the file itself -- which would only work on a single host and is exactly
|
||||
// what the boundary forbids (archie-core-iaqx).
|
||||
// - Captures, CaptureIntake, CaptureMaxEvents: wired below. From the
|
||||
// cutover change (archie-core-8cda.5.4) this process is the only
|
||||
// listener serving POST /webhooks/capture/{source}: the receiver is a
|
||||
@@ -77,10 +82,31 @@ func compose(d deps) *webui.Server {
|
||||
if d.Chat != nil {
|
||||
srv.Chat = &webui.ChatService{Contract: d.Chat}
|
||||
}
|
||||
// The task-log read crosses the State Store contract: the files live in
|
||||
// the state directory that process owns, so this one asks for the log
|
||||
// rather than opening a path (docs/prds/ui-service-boundary.md). Withholding
|
||||
// it would degrade a page that has an owner, and would leave the dashboard
|
||||
// claiming task logging was not enabled -- see wireTaskLogs.
|
||||
wireTaskLogs(d, srv)
|
||||
wireCaptureSurfaces(d, srv)
|
||||
return srv
|
||||
}
|
||||
|
||||
// wireTaskLogs attaches the task-log read when the store client carries the
|
||||
// contract, and logs the absence when it does not: a store without it leaves
|
||||
// the page reporting that this process cannot read logs, which is true, rather
|
||||
// than that the attempt has none, which it cannot know.
|
||||
func wireTaskLogs(d deps, srv *webui.Server) {
|
||||
logs, ok := d.Store.(storecontract.TaskLogStore)
|
||||
if !ok {
|
||||
if d.Store != nil {
|
||||
d.Log.Warn("task logs unavailable: state store does not implement TaskLogStore")
|
||||
}
|
||||
return
|
||||
}
|
||||
srv.TaskLogs = logs
|
||||
}
|
||||
|
||||
// wireCaptureSurfaces attaches the capture read and the intake receiver.
|
||||
// Both resolve from d.Store's contracts: CaptureStore backs the inspector's
|
||||
// list and the mapping preview's scan window, BindingDispatcher resolves the
|
||||
|
||||
@@ -88,7 +88,6 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
|
||||
"Memory": srv.Memory,
|
||||
"Channels": srv.Channels,
|
||||
"LogFeed": srv.LogFeed,
|
||||
"TaskLogs": srv.TaskLogs,
|
||||
"WorkRequests": srv.WorkRequests,
|
||||
}
|
||||
for name, handle := range unwired {
|
||||
@@ -105,6 +104,16 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
|
||||
if srv.Mappings == nil || srv.Bindings == nil {
|
||||
t.Error("Mappings/Bindings are unwired; both are State Store contracts the composed client implements")
|
||||
}
|
||||
// TaskLogs is the same shape as Mappings/Bindings -- the store client
|
||||
// carries TaskLogStore -- and it is the one that used to answer "task
|
||||
// logging was not enabled for this run" for every attempt in a deployment
|
||||
// where logging is unconditional (archie-core-iaqx).
|
||||
if srv.TaskLogs == nil {
|
||||
t.Error("TaskLogs is unwired; the State Store client implements TaskLogStore, so leaving it nil degrades a page that has an owner")
|
||||
}
|
||||
if _, ok := srv.TaskLogs.(*staterpc.Client); !ok {
|
||||
t.Errorf("TaskLogs = %T, want the remote *staterpc.Client: the UI process owns no state directory to read a log file from", srv.TaskLogs)
|
||||
}
|
||||
if srv.UpdateReportPath != "" {
|
||||
t.Error("UpdateReportPath is set; host-local update relay stays with the daemon")
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
@@ -51,11 +52,13 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
|
||||
want: http.StatusServiceUnavailable,
|
||||
},
|
||||
{
|
||||
// The task exists; its logs do not, because the files live on
|
||||
// the daemon's host. "disabled" is the same answer the daemon
|
||||
// gives when task logging is off, and the page already reads it.
|
||||
// Task logs are a State Store read contract now
|
||||
// (archie-core-iaqx), so the route answers with real data
|
||||
// rather than the degrade. The task exists and its attempt
|
||||
// has no log file, which is the found=false answer -- the
|
||||
// page says the attempt has no log, not that logging is off.
|
||||
name: "per-task logs", method: http.MethodGet, path: "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs",
|
||||
want: http.StatusOK, emptyJSON: `"disabled":true`,
|
||||
want: http.StatusOK, emptyJSON: `"found":false`,
|
||||
},
|
||||
{
|
||||
name: "release version and update flow", method: http.MethodGet, path: "/api/version",
|
||||
@@ -159,8 +162,17 @@ func composeUIProcess(t *testing.T) (*webui.Server, int64) {
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
// The task-log reader lives on the state-directory side of the boundary:
|
||||
// the State Store process holds a registry over the directory it owns, and
|
||||
// the dashboard reads through it (archie-core-iaqx). Nothing is written to
|
||||
// it here, so every attempt reads as found=false.
|
||||
logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) {
|
||||
staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)})
|
||||
staterpc.RegisterServer(r, staterpc.Deps{
|
||||
Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st,
|
||||
TaskLogs: logs, Log: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
})
|
||||
t.Cleanup(stop)
|
||||
client, closeClient, err := staterpc.Dial(target, "")
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package archieui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/webui"
|
||||
)
|
||||
|
||||
// TestUIProcessReadsTaskLogsOverTheStateStoreContract is the dashboard bug,
|
||||
// pinned end to end: the extracted UI process serves GET /api/tasks/{id}/logs
|
||||
// and has no way to read a task's persisted log at all, because the only reader
|
||||
// it ever had was a daemon-local file handle. The page therefore answered "Task
|
||||
// logging is optional and was not enabled for this run" for every attempt of
|
||||
// every task, on a deployment where task logging is unconditional and the files
|
||||
// exist.
|
||||
//
|
||||
// The fix is a State Store read contract, so this drives the real thing: a log
|
||||
// file written on the state-directory side, a gRPC server over it, a dashboard
|
||||
// composed exactly as the UI process composes one, and an HTTP request through
|
||||
// the composed handler.
|
||||
func TestUIProcessReadsTaskLogsOverTheStateStoreContract(t *testing.T) {
|
||||
srv, taskID, wantAttempt := composeUIProcessWithLog(t)
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
path := "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs"
|
||||
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+path, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("request: %v", err)
|
||||
}
|
||||
resp, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
var body struct {
|
||||
Entries []logging.Entry `json:"entries"`
|
||||
Attempt int `json:"attempt"`
|
||||
Found bool `json:"found"`
|
||||
File string `json:"file"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, raw)
|
||||
}
|
||||
if !body.Found {
|
||||
t.Errorf("found = false for an attempt whose log exists on the state-directory side (%s)", raw)
|
||||
}
|
||||
if body.Attempt != wantAttempt {
|
||||
t.Errorf("attempt = %d, want %d (the task's current attempt, resolved without a query param)", body.Attempt, wantAttempt)
|
||||
}
|
||||
if len(body.Entries) != 1 || body.Entries[0].Message != "gate failed" {
|
||||
t.Fatalf("entries = %+v, want the one entry the log holds", body.Entries)
|
||||
}
|
||||
if got, ok := body.Entries[0].Fields["component"]; !ok || got != "gate" {
|
||||
t.Errorf("entry fields = %+v, want the structured component field to survive the hop", body.Entries[0].Fields)
|
||||
}
|
||||
// The path is reported, not used: the UI process must not be able to open
|
||||
// it, and the page only names where the log came from.
|
||||
if !strings.HasSuffix(body.File, "attempt-"+strconv.Itoa(wantAttempt)+".jsonl") {
|
||||
t.Errorf("file = %q, want the attempt's own log path", body.File)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUIProcessServesTaskLogDownload drives the download endpoint through the
|
||||
// real composition: the bytes arrive over the contract, and the response is an
|
||||
// attachment named for the attempt rather than an SPA page.
|
||||
//
|
||||
// A GET that falls through to the asset handler answers 200 with HTML, which
|
||||
// is why this asserts the attachment headers and the content, not the status.
|
||||
func TestUIProcessServesTaskLogDownload(t *testing.T) {
|
||||
srv, taskID, wantAttempt := composeUIProcessWithLog(t)
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
path := "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs/download"
|
||||
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+path, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("request: %v", err)
|
||||
}
|
||||
resp, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
wantName := "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(wantAttempt) + ".log"
|
||||
if got := resp.Header.Get("Content-Disposition"); got != `attachment; filename="`+wantName+`"` {
|
||||
t.Errorf("Content-Disposition = %q, want the attempt's own filename %q (status %d, body %s)", got, wantName, resp.StatusCode, raw)
|
||||
}
|
||||
if !strings.Contains(string(raw), "gate failed") {
|
||||
t.Errorf("download body = %s, want the attempt's own log content", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUIProcessReportsMissingTaskLogsHonestly pins the second half of the fix:
|
||||
// with the reader wired and no log on disk, the page must be able to say that
|
||||
// the ATTEMPT has no log. It is a different claim from "this process cannot
|
||||
// read logs", and only the second one is about the operator's configuration.
|
||||
func TestUIProcessReportsMissingTaskLogsHonestly(t *testing.T) {
|
||||
srv, taskID := composeUIProcess(t)
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
defer ts.Close()
|
||||
|
||||
path := "/api/tasks/" + strconv.FormatInt(taskID, 10) + "/logs"
|
||||
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+path, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("request: %v", err)
|
||||
}
|
||||
resp, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
|
||||
var body struct {
|
||||
Disabled bool `json:"disabled"`
|
||||
Found bool `json:"found"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, raw)
|
||||
}
|
||||
if body.Disabled {
|
||||
t.Fatalf("disabled = true for a process that can read task logs (%s); the page turns that into \"logging was not enabled for this run\"", raw)
|
||||
}
|
||||
if body.Found {
|
||||
t.Errorf("found = true for an attempt with no log file (%s)", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// composeUIProcessWithLog is composeUIProcess plus one real log on the
|
||||
// state-directory side: a gRPC server whose task-log reader holds an attempt's
|
||||
// file, so the dashboard's read has to cross the wire to see anything.
|
||||
func composeUIProcessWithLog(t *testing.T) (*webui.Server, int64, int) {
|
||||
t.Helper()
|
||||
st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "tasks.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatalf("open store: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
|
||||
task, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "a task", "body", "implement", "")
|
||||
if err != nil {
|
||||
t.Fatalf("seed task: %v", err)
|
||||
}
|
||||
|
||||
// The state directory the State Store process owns. The dashboard never
|
||||
// learns this path: it asks the contract for the log.
|
||||
logs := logging.NewTaskRegistry(filepath.Join(t.TempDir(), "logs", "tasks"), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
if err := logs.Open(task.ID, task.Attempt); err != nil {
|
||||
t.Fatalf("open task log: %v", err)
|
||||
}
|
||||
logs.Write(task.ID, logging.Entry{
|
||||
Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"},
|
||||
})
|
||||
if err := logs.Close(task.ID); err != nil {
|
||||
t.Fatalf("close task log: %v", err)
|
||||
}
|
||||
|
||||
target, stop := serveGRPC(t, func(r grpc.ServiceRegistrar) {
|
||||
staterpc.RegisterServer(r, staterpc.Deps{
|
||||
Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st,
|
||||
TaskLogs: logs, Log: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
})
|
||||
t.Cleanup(stop)
|
||||
client, closeClient, err := staterpc.Dial(target, "")
|
||||
if err != nil {
|
||||
t.Fatalf("dial state store: %v", err)
|
||||
}
|
||||
t.Cleanup(closeClient)
|
||||
|
||||
options := Options{Listen: "127.0.0.1:0", DependencyTimeout: defaultDependencyTimeout}
|
||||
srv := compose(deps{
|
||||
Options: options,
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Store: client,
|
||||
Health: newReadinessRegistry(options, client, nil),
|
||||
})
|
||||
return srv, task.ID, task.Attempt
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -45,6 +45,8 @@ const (
|
||||
StateStoreService_TokensByDay_FullMethodName = "/state.v1.StateStoreService/TokensByDay"
|
||||
StateStoreService_PutConfigSnapshot_FullMethodName = "/state.v1.StateStoreService/PutConfigSnapshot"
|
||||
StateStoreService_GetConfigSnapshot_FullMethodName = "/state.v1.StateStoreService/GetConfigSnapshot"
|
||||
StateStoreService_ReadTaskLog_FullMethodName = "/state.v1.StateStoreService/ReadTaskLog"
|
||||
StateStoreService_StreamTaskLogContent_FullMethodName = "/state.v1.StateStoreService/StreamTaskLogContent"
|
||||
StateStoreService_InsertCapture_FullMethodName = "/state.v1.StateStoreService/InsertCapture"
|
||||
StateStoreService_ListCaptures_FullMethodName = "/state.v1.StateStoreService/ListCaptures"
|
||||
StateStoreService_StreamCaptures_FullMethodName = "/state.v1.StateStoreService/StreamCaptures"
|
||||
@@ -114,6 +116,17 @@ type StateStoreServiceClient interface {
|
||||
// configuration page").
|
||||
PutConfigSnapshot(ctx context.Context, in *PutConfigSnapshotRequest, opts ...grpc.CallOption) (*PutConfigSnapshotResponse, error)
|
||||
GetConfigSnapshot(ctx context.Context, in *GetConfigSnapshotRequest, opts ...grpc.CallOption) (*GetConfigSnapshotResponse, error)
|
||||
// Task log: one task attempt's persisted log. Task log files live in the
|
||||
// state directory this process owns, so the dashboard reads them over this
|
||||
// contract rather than opening them itself
|
||||
// (docs/prds/ui-service-boundary.md).
|
||||
ReadTaskLog(ctx context.Context, in *ReadTaskLogRequest, opts ...grpc.CallOption) (*ReadTaskLogResponse, error)
|
||||
// StreamTaskLogContent returns one attempt's log verbatim, one chunk per
|
||||
// message, for a download. A log file is unbounded input (it rotates at
|
||||
// DefaultMaxSizeMB), so a unary response would exceed gRPC's 4MiB message
|
||||
// cap on a real log -- the same reason ListCaptures was superseded by
|
||||
// StreamCaptures.
|
||||
StreamTaskLogContent(ctx context.Context, in *StreamTaskLogContentRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamTaskLogContentResponse], error)
|
||||
// Capture
|
||||
InsertCapture(ctx context.Context, in *InsertCaptureRequest, opts ...grpc.CallOption) (*InsertCaptureResponse, error)
|
||||
// Deprecated: Do not use.
|
||||
@@ -419,6 +432,35 @@ func (c *stateStoreServiceClient) GetConfigSnapshot(ctx context.Context, in *Get
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ReadTaskLog(ctx context.Context, in *ReadTaskLogRequest, opts ...grpc.CallOption) (*ReadTaskLogResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ReadTaskLogResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ReadTaskLog_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) StreamTaskLogContent(ctx context.Context, in *StreamTaskLogContentRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamTaskLogContentResponse], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[0], StateStoreService_StreamTaskLogContent_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[StreamTaskLogContentRequest, StreamTaskLogContentResponse]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StateStoreService_StreamTaskLogContentClient = grpc.ServerStreamingClient[StreamTaskLogContentResponse]
|
||||
|
||||
func (c *stateStoreServiceClient) InsertCapture(ctx context.Context, in *InsertCaptureRequest, opts ...grpc.CallOption) (*InsertCaptureResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(InsertCaptureResponse)
|
||||
@@ -442,7 +484,7 @@ func (c *stateStoreServiceClient) ListCaptures(ctx context.Context, in *ListCapt
|
||||
|
||||
func (c *stateStoreServiceClient) StreamCaptures(ctx context.Context, in *StreamCapturesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamCapturesResponse], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[0], StateStoreService_StreamCaptures_FullMethodName, cOpts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[1], StateStoreService_StreamCaptures_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -602,7 +644,7 @@ func (c *stateStoreServiceClient) ListUndispatchedCaptures(ctx context.Context,
|
||||
|
||||
func (c *stateStoreServiceClient) StreamUndispatchedCaptures(ctx context.Context, in *StreamUndispatchedCapturesRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[StreamUndispatchedCapturesResponse], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[1], StateStoreService_StreamUndispatchedCaptures_FullMethodName, cOpts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StateStoreService_ServiceDesc.Streams[2], StateStoreService_StreamUndispatchedCaptures_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -677,6 +719,17 @@ type StateStoreServiceServer interface {
|
||||
// configuration page").
|
||||
PutConfigSnapshot(context.Context, *PutConfigSnapshotRequest) (*PutConfigSnapshotResponse, error)
|
||||
GetConfigSnapshot(context.Context, *GetConfigSnapshotRequest) (*GetConfigSnapshotResponse, error)
|
||||
// Task log: one task attempt's persisted log. Task log files live in the
|
||||
// state directory this process owns, so the dashboard reads them over this
|
||||
// contract rather than opening them itself
|
||||
// (docs/prds/ui-service-boundary.md).
|
||||
ReadTaskLog(context.Context, *ReadTaskLogRequest) (*ReadTaskLogResponse, error)
|
||||
// StreamTaskLogContent returns one attempt's log verbatim, one chunk per
|
||||
// message, for a download. A log file is unbounded input (it rotates at
|
||||
// DefaultMaxSizeMB), so a unary response would exceed gRPC's 4MiB message
|
||||
// cap on a real log -- the same reason ListCaptures was superseded by
|
||||
// StreamCaptures.
|
||||
StreamTaskLogContent(*StreamTaskLogContentRequest, grpc.ServerStreamingServer[StreamTaskLogContentResponse]) error
|
||||
// Capture
|
||||
InsertCapture(context.Context, *InsertCaptureRequest) (*InsertCaptureResponse, error)
|
||||
// Deprecated: Do not use.
|
||||
@@ -800,6 +853,12 @@ func (UnimplementedStateStoreServiceServer) PutConfigSnapshot(context.Context, *
|
||||
func (UnimplementedStateStoreServiceServer) GetConfigSnapshot(context.Context, *GetConfigSnapshotRequest) (*GetConfigSnapshotResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetConfigSnapshot not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ReadTaskLog(context.Context, *ReadTaskLogRequest) (*ReadTaskLogResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ReadTaskLog not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) StreamTaskLogContent(*StreamTaskLogContentRequest, grpc.ServerStreamingServer[StreamTaskLogContentResponse]) error {
|
||||
return status.Error(codes.Unimplemented, "method StreamTaskLogContent not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) InsertCapture(context.Context, *InsertCaptureRequest) (*InsertCaptureResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method InsertCapture not implemented")
|
||||
}
|
||||
@@ -1346,6 +1405,35 @@ func _StateStoreService_GetConfigSnapshot_Handler(srv interface{}, ctx context.C
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ReadTaskLog_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ReadTaskLogRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ReadTaskLog(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ReadTaskLog_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ReadTaskLog(ctx, req.(*ReadTaskLogRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_StreamTaskLogContent_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(StreamTaskLogContentRequest)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StateStoreServiceServer).StreamTaskLogContent(m, &grpc.GenericServerStream[StreamTaskLogContentRequest, StreamTaskLogContentResponse]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StateStoreService_StreamTaskLogContentServer = grpc.ServerStreamingServer[StreamTaskLogContentResponse]
|
||||
|
||||
func _StateStoreService_InsertCapture_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(InsertCaptureRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -1785,6 +1873,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "GetConfigSnapshot",
|
||||
Handler: _StateStoreService_GetConfigSnapshot_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ReadTaskLog",
|
||||
Handler: _StateStoreService_ReadTaskLog_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "InsertCapture",
|
||||
Handler: _StateStoreService_InsertCapture_Handler,
|
||||
@@ -1855,6 +1947,11 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "StreamTaskLogContent",
|
||||
Handler: _StateStoreService_StreamTaskLogContent_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
{
|
||||
StreamName: "StreamCaptures",
|
||||
Handler: _StateStoreService_StreamCaptures_Handler,
|
||||
|
||||
@@ -18,12 +18,14 @@ package storecontract
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// TaskStore is the full store surface the daemon needs.
|
||||
@@ -160,6 +162,27 @@ type BindingTaskCreator interface {
|
||||
EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*task.Task, error)
|
||||
}
|
||||
|
||||
// TaskLogStore reads one task attempt's persisted log. Deliberately separate
|
||||
// from TaskQueries: the log is not a row, it is a file the logging package
|
||||
// owns the format of, and a process that can read the task board should not
|
||||
// have to acquire a log reader to do it. The dashboard's UI process is the
|
||||
// consumer this exists for -- it holds no daemon-local file handle, so the
|
||||
// read crosses the State Store contract (docs/prds/ui-service-boundary.md).
|
||||
//
|
||||
// Found=false with a nil error is the not-found convention every read here
|
||||
// uses, and it is load-bearing: "this attempt has no log" is not "this
|
||||
// process cannot read logs". The second one is an error
|
||||
// (logging.ErrTaskLogsUnavailable), because a caller that conflates them
|
||||
// reports a configuration change where none is needed.
|
||||
type TaskLogStore interface {
|
||||
// TaskLog returns a page of one attempt's decoded log. attempt 0 selects
|
||||
// the task's current attempt.
|
||||
TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error)
|
||||
// TaskLogContent writes one attempt's log verbatim to w, for a download.
|
||||
// found is false, with a nil error, when the attempt has no log file.
|
||||
TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (found bool, err error)
|
||||
}
|
||||
|
||||
// CapturedEvent is one unbound inbound webhook capture: no workflow binding,
|
||||
// no forge/task association -- just what arrived, from where, and when.
|
||||
// See docs/prds/event-capture-storage.md.
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// Client is the single remote adapter wrapping one StateStoreServiceClient,
|
||||
@@ -36,6 +37,7 @@ func (c *Client) Close() error { return nil }
|
||||
var (
|
||||
_ task.Store = (*Client)(nil)
|
||||
_ storecontract.TaskStore = (*Client)(nil)
|
||||
_ storecontract.TaskLogStore = (*Client)(nil)
|
||||
_ storecontract.CaptureStore = (*Client)(nil)
|
||||
_ storecontract.MappingStore = (*Client)(nil)
|
||||
_ storecontract.BindingStore = (*Client)(nil)
|
||||
@@ -417,6 +419,58 @@ func (c *Client) EnqueueBindingTask(ctx context.Context, owner, repo, title, bod
|
||||
return taskValue(r.Task), nil
|
||||
}
|
||||
|
||||
// Task log
|
||||
|
||||
// TaskLog reads one task attempt's decoded log over the wire. found=false with
|
||||
// a nil error is the attempt-has-no-log answer; a process with no reader at
|
||||
// all comes back as an unavailable error, not as an empty page, so a caller
|
||||
// can tell the two apart.
|
||||
func (c *Client) TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error) {
|
||||
r, err := c.client.ReadTaskLog(ctx, taskLogRequestProto(taskID, attempt, q))
|
||||
if err != nil {
|
||||
return logging.TaskLogPage{}, unmapError(err)
|
||||
}
|
||||
if !r.Found {
|
||||
return logging.TaskLogPage{
|
||||
Entries: []logging.Entry{},
|
||||
Components: []string{},
|
||||
}, nil
|
||||
}
|
||||
return logging.TaskLogPage{
|
||||
Entries: mapValues(r.Entries, taskLogEntryValue),
|
||||
Truncated: r.Truncated,
|
||||
File: r.File,
|
||||
Found: true,
|
||||
Components: r.Components,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// TaskLogContent streams one attempt's log verbatim into w, for a download.
|
||||
// found is false, with a nil error, when the attempt has no log file.
|
||||
func (c *Client) TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (bool, error) {
|
||||
stream, err := c.client.StreamTaskLogContent(ctx, &pb.StreamTaskLogContentRequest{TaskId: taskID, Attempt: int64(attempt)})
|
||||
if err != nil {
|
||||
return false, unmapError(err)
|
||||
}
|
||||
found := false
|
||||
for {
|
||||
r, err := stream.Recv()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return found, nil
|
||||
}
|
||||
if err != nil {
|
||||
return found, unmapError(err)
|
||||
}
|
||||
found = found || r.Found
|
||||
if len(r.Chunk) == 0 {
|
||||
continue
|
||||
}
|
||||
if _, err := w.Write(r.Chunk); err != nil {
|
||||
return found, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func derefTasks(in []*pb.Task) []task.Task {
|
||||
if in == nil {
|
||||
return nil
|
||||
|
||||
@@ -31,13 +31,31 @@ type contract interface {
|
||||
store.ConfigSnapshotStore
|
||||
}
|
||||
|
||||
// taskLogContract is the task-log read group, driven separately because it is
|
||||
// not a *store.Store surface: the reader is internal/logging's own registry,
|
||||
// which owns the log format, so the local side of this contract is a registry
|
||||
// rather than a store.
|
||||
type taskLogContract interface {
|
||||
store.TaskLogStore
|
||||
}
|
||||
|
||||
func remoteContract(t *testing.T, local *store.Store) contract {
|
||||
t.Helper()
|
||||
return remoteTaskStore(t, local, nil)
|
||||
}
|
||||
|
||||
// remoteTaskStore serves local behind a bufconn listener with a task-log
|
||||
// reader attached, and returns a client for it. The reader is a parameter
|
||||
// because the log files are internal/logging's, not the store's: this contract
|
||||
// fronts a reader rather than a table.
|
||||
func remoteTaskStore(t *testing.T, local *store.Store, logs store.TaskLogStore) *Client {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, Deps{
|
||||
Tasks: local, Captures: local, Mappings: local, Bindings: local,
|
||||
BindingDispatcher: local, BindingTaskCreator: local, ConfigSnapshots: local,
|
||||
TaskLogs: logs,
|
||||
})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// Unavailable-capability errors, mirroring gatewayrpc's missing-session-store
|
||||
@@ -30,10 +33,23 @@ var (
|
||||
errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable")
|
||||
errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable")
|
||||
errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable")
|
||||
// errTaskLogsUnavailable is the "this process cannot read task logs at
|
||||
// all" answer, and it is deliberately distinct from a found=false read
|
||||
// result: only the first is a deployment matter. A dashboard that receives
|
||||
// this reports that the log cannot be read here; it must never turn it
|
||||
// into "task logging was not enabled for this run", which is what the
|
||||
// absent-handle path used to do.
|
||||
errTaskLogsUnavailable = status.Error(codes.Unavailable, msgTaskLogsUnavailable)
|
||||
)
|
||||
|
||||
func timeSeconds(s int64) time.Duration { return time.Duration(s) * time.Second }
|
||||
|
||||
// taskLogChunkBytes bounds one streamed message. A log file rotates at
|
||||
// logging.DefaultMaxSizeMB, well past gRPC's 4MiB unary cap, so the download
|
||||
// is served in pieces (the same reason StreamCaptures superseded ListCaptures)
|
||||
// and the pieces must be small enough to carry.
|
||||
const taskLogChunkBytes = 256 << 10
|
||||
|
||||
// Deps groups the store surfaces the StateStore service fronts. TaskStore is
|
||||
// required; the rest are optional (nil disables that group's RPCs, returning
|
||||
// codes.Unavailable) exactly as their daemon-side consumers already treat a
|
||||
@@ -47,7 +63,14 @@ type Deps struct {
|
||||
Bindings storecontract.BindingStore
|
||||
BindingDispatcher storecontract.BindingDispatcher
|
||||
BindingTaskCreator storecontract.BindingTaskCreator
|
||||
Log *slog.Logger
|
||||
// TaskLogs reads one task attempt's persisted log out of the state
|
||||
// directory this process owns. Optional, and nil is the honest default for
|
||||
// a store service that shares no state directory with the daemon:
|
||||
// ReadTaskLog then answers codes.Unavailable, which the dashboard reports
|
||||
// as "this process cannot read logs" rather than as "this attempt has no
|
||||
// log". Conflating those two is the bug this contract exists to fix.
|
||||
TaskLogs storecontract.TaskLogStore
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
type server struct {
|
||||
@@ -565,6 +588,117 @@ func (s *server) EnqueueBindingTask(ctx context.Context, r *pb.EnqueueBindingTas
|
||||
return &pb.EnqueueBindingTaskResponse{Task: taskProto(t)}, nil
|
||||
}
|
||||
|
||||
// Task log
|
||||
|
||||
func (s *server) taskLogs() (storecontract.TaskLogStore, error) {
|
||||
if s.deps.TaskLogs == nil {
|
||||
return nil, errTaskLogsUnavailable
|
||||
}
|
||||
return s.deps.TaskLogs, nil
|
||||
}
|
||||
|
||||
func (s *server) ReadTaskLog(ctx context.Context, r *pb.ReadTaskLogRequest) (*pb.ReadTaskLogResponse, error) {
|
||||
logs, err := s.taskLogs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, err := logs.TaskLog(ctx, r.TaskId, int(r.Attempt), taskLogQueryValue(r))
|
||||
if err != nil {
|
||||
// A store that cannot read its own state directory keeps its own
|
||||
// identity: this is unavailability, not a missing log, and a caller
|
||||
// has to be able to tell them apart.
|
||||
if errors.Is(err, logging.ErrTaskLogsUnavailable) {
|
||||
return nil, errTaskLogsUnavailable
|
||||
}
|
||||
return nil, s.logErr("ReadTaskLog", err)
|
||||
}
|
||||
if !page.Found {
|
||||
return &pb.ReadTaskLogResponse{Attempt: r.Attempt}, nil
|
||||
}
|
||||
return &pb.ReadTaskLogResponse{
|
||||
Entries: mapValues(page.Entries, taskLogEntryProto),
|
||||
Truncated: page.Truncated,
|
||||
Attempt: r.Attempt,
|
||||
Found: true,
|
||||
Components: page.Components,
|
||||
File: page.File,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StreamTaskLogContent sends one attempt's log verbatim, one chunk per
|
||||
// message, for a download. A single reply reports found=false with no chunks:
|
||||
// the attempt has no log file, which is a normal state rather than a failure.
|
||||
func (s *server) StreamTaskLogContent(r *pb.StreamTaskLogContentRequest, stream pb.StateStoreService_StreamTaskLogContentServer) error {
|
||||
logs, err := s.taskLogs()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The chunking the client sees is owned by the reader that writes into
|
||||
// this buffer, so the wire never holds a whole log to re-slice it.
|
||||
buf := &chunkWriter{stream: stream, attempt: r.Attempt}
|
||||
found, err := logs.TaskLogContent(stream.Context(), r.TaskId, int(r.Attempt), buf)
|
||||
if err != nil {
|
||||
if errors.Is(err, logging.ErrTaskLogsUnavailable) {
|
||||
return errTaskLogsUnavailable
|
||||
}
|
||||
return s.logErr("StreamTaskLogContent", err)
|
||||
}
|
||||
if err := buf.flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
// A found log with no bytes still reports found: an attempt whose file is
|
||||
// empty did produce a log, and found is what tells the download it may
|
||||
// write an empty file rather than answer 404.
|
||||
if found && buf.sent {
|
||||
return nil
|
||||
}
|
||||
return stream.Send(&pb.StreamTaskLogContentResponse{Attempt: r.Attempt, Found: found})
|
||||
}
|
||||
|
||||
// chunkWriter packs everything a log reader writes into stream-sized messages
|
||||
// on its way through. It exists so the read can be one io.CopyBuffer of the
|
||||
// file into this writer: the reader keeps its own chunk size, and the bytes
|
||||
// are never all held at once.
|
||||
type chunkWriter struct {
|
||||
stream pb.StateStoreService_StreamTaskLogContentServer
|
||||
attempt int64
|
||||
pending []byte
|
||||
// sent records whether any chunk reached the client, which is how the
|
||||
// caller tells "the file was empty" from "the file was read".
|
||||
sent bool
|
||||
}
|
||||
|
||||
func (w *chunkWriter) Write(p []byte) (int, error) {
|
||||
w.pending = append(w.pending, p...)
|
||||
for len(w.pending) >= taskLogChunkBytes {
|
||||
if err := w.emit(w.pending[:taskLogChunkBytes]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
w.pending = w.pending[taskLogChunkBytes:]
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (w *chunkWriter) emit(chunk []byte) error {
|
||||
w.sent = true
|
||||
// The slice is copied into the message: the reader's buffer is reused
|
||||
// across writes and must not be aliased by a message in flight.
|
||||
return w.stream.Send(&pb.StreamTaskLogContentResponse{
|
||||
Chunk: bytes.Clone(chunk),
|
||||
Attempt: w.attempt,
|
||||
Found: true,
|
||||
})
|
||||
}
|
||||
|
||||
func (w *chunkWriter) flush() error {
|
||||
if len(w.pending) == 0 {
|
||||
return nil
|
||||
}
|
||||
chunk := w.pending
|
||||
w.pending = nil
|
||||
return w.emit(chunk)
|
||||
}
|
||||
|
||||
func mappingProtoPtr(m *mapping.Mapping) *pb.Mapping {
|
||||
if m == nil {
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// TestTaskLogContract drives the task-log read group through both adapters,
|
||||
// matching the §11 conformance requirement the rest of this package already
|
||||
// satisfies: the same battery runs against the local reader (a
|
||||
// *logging.TaskRegistry over this process's own state directory) and against
|
||||
// the remote *Client.
|
||||
//
|
||||
// The two answers this pins as DIFFERENT are the point of the contract. A
|
||||
// process with no reader reports unavailability; an attempt with no log file
|
||||
// reports found=false with no error. A caller that cannot tell those apart
|
||||
// tells an operator task logging is switched off when it is not.
|
||||
func TestTaskLogContract(t *testing.T) {
|
||||
for _, mode := range []string{"local", "grpc"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
baseDir := filepath.Join(t.TempDir(), "logs", "tasks")
|
||||
reader := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
const taskID = 7
|
||||
if err := reader.Open(taskID, 0); err != nil {
|
||||
t.Fatalf("open sink: %v", err)
|
||||
}
|
||||
reader.Write(taskID, logging.Entry{Level: "INFO", Message: "starting", Fields: map[string]any{"component": "daemon"}})
|
||||
reader.Write(taskID, logging.Entry{Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"}})
|
||||
if err := reader.Close(taskID); err != nil {
|
||||
t.Fatalf("close sink: %v", err)
|
||||
}
|
||||
|
||||
var c taskLogContract = reader
|
||||
if mode == "grpc" {
|
||||
c = remoteTaskStore(t, store.OpenTest(t), reader)
|
||||
}
|
||||
|
||||
t.Run("a page carries the decoded entries and their fields", func(t *testing.T) {
|
||||
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLog: %v", err)
|
||||
}
|
||||
if !page.Found {
|
||||
t.Fatal("Found = false for an attempt whose log exists")
|
||||
}
|
||||
if len(page.Entries) != 2 {
|
||||
t.Fatalf("entries = %d, want 2", len(page.Entries))
|
||||
}
|
||||
if page.Entries[1].Message != "gate failed" || page.Entries[1].Level != "ERROR" {
|
||||
t.Errorf("entry = %+v, want the ERROR line the sink wrote", page.Entries[1])
|
||||
}
|
||||
if got, _ := page.Entries[0].Fields["component"].(string); got != "daemon" {
|
||||
t.Errorf("fields = %+v, want the structured component to survive the hop", page.Entries[0].Fields)
|
||||
}
|
||||
if !strings.HasSuffix(page.File, "attempt-0.jsonl") {
|
||||
t.Errorf("file = %q, want the attempt's own path", page.File)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("filters and the limit cross the wire", func(t *testing.T) {
|
||||
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{Levels: []string{"ERROR"}})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLog: %v", err)
|
||||
}
|
||||
if len(page.Entries) != 1 || page.Entries[0].Message != "gate failed" {
|
||||
t.Fatalf("level filter = %+v, want just the ERROR line", page.Entries)
|
||||
}
|
||||
page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Component: "daemon"})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLog: %v", err)
|
||||
}
|
||||
if len(page.Entries) != 1 || page.Entries[0].Message != "starting" {
|
||||
t.Fatalf("component filter = %+v, want just the daemon line", page.Entries)
|
||||
}
|
||||
page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Contains: "gate"})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLog: %v", err)
|
||||
}
|
||||
if len(page.Entries) != 1 || page.Entries[0].Message != "gate failed" {
|
||||
t.Fatalf("contains filter = %+v, want just the gate line", page.Entries)
|
||||
}
|
||||
page, err = c.TaskLog(ctx, taskID, 0, logging.Query{Limit: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLog: %v", err)
|
||||
}
|
||||
if len(page.Entries) != 1 || !page.Truncated {
|
||||
t.Fatalf("limit = 1 gave %d entries (truncated %v), want one and a truncated marker", len(page.Entries), page.Truncated)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("components list what the log actually contains", func(t *testing.T) {
|
||||
page, err := c.TaskLog(ctx, taskID, 0, logging.Query{})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLog: %v", err)
|
||||
}
|
||||
if len(page.Components) != 2 || page.Components[0] != "daemon" || page.Components[1] != "gate" {
|
||||
t.Fatalf("components = %v, want the sorted distinct set", page.Components)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an attempt with no log is found=false, not an error", func(t *testing.T) {
|
||||
page, err := c.TaskLog(ctx, taskID, 99, logging.Query{})
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLog for a missing attempt = %v, want no error", err)
|
||||
}
|
||||
if page.Found {
|
||||
t.Error("Found = true for an attempt with no log file")
|
||||
}
|
||||
if len(page.Entries) != 0 {
|
||||
t.Errorf("entries = %+v, want none", page.Entries)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("content is the file verbatim, and found is false when there is none", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
found, err := c.TaskLogContent(ctx, taskID, 0, &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLogContent: %v", err)
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("found = false for an attempt whose log exists")
|
||||
}
|
||||
body := buf.String()
|
||||
if !strings.Contains(body, "gate failed") || !strings.Contains(body, "starting") {
|
||||
t.Fatalf("content = %q, want the raw log lines", body)
|
||||
}
|
||||
// Byte-for-byte: the contract transports the log, it does not
|
||||
// re-encode it. Every line must still parse as the package's
|
||||
// own JSONL.
|
||||
for line := range strings.Lines(strings.TrimSpace(body)) {
|
||||
if _, ok := loggingTailDecodes(t, line); !ok {
|
||||
t.Fatalf("line %q does not decode as the logging package's own format", line)
|
||||
}
|
||||
}
|
||||
|
||||
buf.Reset()
|
||||
found, err = c.TaskLogContent(ctx, taskID, 99, &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskLogContent for a missing attempt = %v, want no error", err)
|
||||
}
|
||||
if found || buf.Len() != 0 {
|
||||
t.Errorf("found = %v with %d bytes, want false and nothing", found, buf.Len())
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestTaskLogContractWithoutAReaderIsUnavailable pins the other half of the
|
||||
// distinction, and the one the dashboard's misleading message came from: a
|
||||
// service with no task-log reader at all must say UNAVAILABLE rather than
|
||||
// answer an empty page. An empty page is indistinguishable from an attempt
|
||||
// that has no log, and the dashboard rendered that as "task logging is
|
||||
// optional and was not enabled for this run".
|
||||
func TestTaskLogContractWithoutAReaderIsUnavailable(t *testing.T) {
|
||||
local := store.OpenTest(t)
|
||||
// remoteContract leaves Deps.TaskLogs nil, which is what a store service
|
||||
// sharing no state directory with the daemon looks like.
|
||||
c := remoteContract(t, local)
|
||||
logs, ok := c.(taskLogContract)
|
||||
if !ok {
|
||||
t.Fatalf("remote client does not carry the task-log contract (%T)", c)
|
||||
}
|
||||
|
||||
if _, err := logs.TaskLog(t.Context(), 1, 0, logging.Query{}); !errors.Is(err, logging.ErrTaskLogsUnavailable) {
|
||||
t.Errorf("TaskLog without a reader = %v, want ErrTaskLogsUnavailable; an empty page here is what the dashboard read as \"logging was not enabled\"", err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if _, err := logs.TaskLogContent(t.Context(), 1, 0, &buf); !errors.Is(err, logging.ErrTaskLogsUnavailable) {
|
||||
t.Errorf("TaskLogContent without a reader = %v, want ErrTaskLogsUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
// loggingTailDecodes reports whether one line is a record the logging package
|
||||
// can decode, using that package's own reader rather than a second opinion
|
||||
// about its format.
|
||||
func loggingTailDecodes(t *testing.T, line string) (logging.Entry, bool) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "one.jsonl")
|
||||
if err := os.WriteFile(path, []byte(line+"\n"), 0o600); err != nil {
|
||||
t.Fatalf("write temp log: %v", err)
|
||||
}
|
||||
res, err := logging.Tail(path, logging.Query{})
|
||||
if err != nil {
|
||||
t.Fatalf("Tail: %v", err)
|
||||
}
|
||||
if len(res.Entries) != 1 {
|
||||
return logging.Entry{}, false
|
||||
}
|
||||
return res.Entries[0], true
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
func timestamp(t time.Time) *timestamppb.Timestamp {
|
||||
@@ -245,6 +246,12 @@ const (
|
||||
msgBindingTransition = "binding transition rejected"
|
||||
msgAlreadyDispatched = "already dispatched"
|
||||
msgInternal = "state store: internal error"
|
||||
// msgTaskLogsUnavailable is the public phrase for "this service has no
|
||||
// task-log reader". It is a wire contract like the sentinels above: the
|
||||
// client rehydrates logging.ErrTaskLogsUnavailable from (Unavailable, this
|
||||
// message), and a caller depends on that to tell "this process cannot read
|
||||
// logs" from "this attempt has no log".
|
||||
msgTaskLogsUnavailable = "task log reader unavailable"
|
||||
)
|
||||
|
||||
// mapError converts a store sentinel error into a structured gRPC status
|
||||
@@ -301,6 +308,12 @@ func mapError(err error) error {
|
||||
// *status.Error whose code is DeadlineExceeded or Canceled, so we rehydrate
|
||||
// those back to the standard context sentinels -- otherwise the consumer
|
||||
// would (wrongly) park a task that was merely interrupted.
|
||||
//
|
||||
// Unavailable carries one message this package owns: the absent task-log
|
||||
// reader. It is rehydrated for the same reason the error sentinels are --
|
||||
// the dashboard's whole bug was rendering "this process cannot read logs" as
|
||||
// "the attempt has no log", and only the typed error makes that distinction
|
||||
// available to a caller.
|
||||
func unmapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
@@ -314,6 +327,19 @@ func unmapError(err error) error {
|
||||
return context.Canceled
|
||||
case codes.DeadlineExceeded:
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
if sentinel := sentinelForStatus(st); sentinel != nil {
|
||||
return sentinel
|
||||
}
|
||||
return fmt.Errorf("state store: %s: %w", st.Message(), err)
|
||||
}
|
||||
|
||||
// sentinelForStatus maps a status to the store or logging sentinel it stands
|
||||
// for, matched on (code, exact canonical message) -- those message constants
|
||||
// are part of the wire contract (§4). A code whose message is not one this
|
||||
// package defines returns nil, so the caller falls back to the wrapped form.
|
||||
func sentinelForStatus(st *status.Status) error {
|
||||
switch st.Code() {
|
||||
case codes.FailedPrecondition:
|
||||
switch st.Message() {
|
||||
case msgStaleTransition:
|
||||
@@ -334,8 +360,12 @@ func unmapError(err error) error {
|
||||
if st.Message() == msgAlreadyDispatched {
|
||||
return storecontract.ErrAlreadyDispatched
|
||||
}
|
||||
case codes.Unavailable:
|
||||
if st.Message() == msgTaskLogsUnavailable {
|
||||
return logging.ErrTaskLogsUnavailable
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("state store: %s: %w", st.Message(), err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// configSnapshotProto and configSnapshotValue carry the dashboard's
|
||||
@@ -359,3 +389,46 @@ func configSnapshotValue(snapshot *pb.ConfigSnapshot) storecontract.ConfigSnapsh
|
||||
PublishedAt: timeValue(snapshot.PublishedAt),
|
||||
}
|
||||
}
|
||||
|
||||
// taskLogEntryProto and taskLogEntryValue mirror internal/logging.Entry, whose
|
||||
// Fields map crosses as a JSON object string exactly as events.Event.Data does
|
||||
// (see eventDataJSON above). The logging package owns that format end to end;
|
||||
// this is a transport of it, not a second definition.
|
||||
func taskLogEntryProto(e logging.Entry) *pb.TaskLogEntry {
|
||||
return &pb.TaskLogEntry{
|
||||
Id: e.ID, Time: timestamp(e.Time), Level: e.Level, Msg: e.Message,
|
||||
FieldsJson: eventDataJSON(e.Fields),
|
||||
}
|
||||
}
|
||||
|
||||
func taskLogEntryValue(e *pb.TaskLogEntry) logging.Entry {
|
||||
if e == nil {
|
||||
return logging.Entry{}
|
||||
}
|
||||
return logging.Entry{
|
||||
ID: e.Id, Time: timeValue(e.Time), Level: e.Level, Message: e.Msg,
|
||||
Fields: eventDataValue(e.FieldsJson),
|
||||
}
|
||||
}
|
||||
|
||||
// taskLogRequestProto is the client half of the ReadTaskLog mapping and
|
||||
// taskLogQueryValue the server half: the whole logging.Query crosses, not a
|
||||
// subset of it, so a filter cannot silently stop working at the boundary.
|
||||
func taskLogRequestProto(taskID int64, attempt int, q logging.Query) *pb.ReadTaskLogRequest {
|
||||
return &pb.ReadTaskLogRequest{
|
||||
TaskId: taskID, Attempt: int64(attempt), Limit: int64(q.Limit),
|
||||
Levels: q.Levels, Component: q.Component, Contains: q.Contains,
|
||||
Since: timestamp(q.Since), Until: timestamp(q.Until),
|
||||
}
|
||||
}
|
||||
|
||||
func taskLogQueryValue(r *pb.ReadTaskLogRequest) logging.Query {
|
||||
return logging.Query{
|
||||
Levels: r.Levels,
|
||||
Component: r.Component,
|
||||
Contains: r.Contains,
|
||||
Limit: int(r.Limit),
|
||||
Since: timeValue(r.Since),
|
||||
Until: timeValue(r.Until),
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,11 @@ package logging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -65,6 +68,88 @@ type Result struct {
|
||||
Truncated bool `json:"truncated"`
|
||||
// File is the path read, for the UI to show where this came from.
|
||||
File string `json:"file"`
|
||||
// Found reports whether the file existed. False with a nil error is not a
|
||||
// failure: a caller asking for a log that has no file yet, or one whose
|
||||
// attempt produced no output, must be told that rather than shown an empty
|
||||
// page indistinguishable from a log that is genuinely empty. This is also
|
||||
// what separates "there is no log for this attempt" from "this process
|
||||
// cannot read logs at all" -- two conditions that a reader has to report
|
||||
// differently because only the second is a configuration matter.
|
||||
Found bool `json:"found"`
|
||||
}
|
||||
|
||||
// TaskLogPage is one task attempt's log as a task-log reader returns it: the
|
||||
// page Tail selected, whether the attempt has a file at all, and the distinct
|
||||
// components present in the file's tail so a filter is built from what is
|
||||
// actually there rather than a hardcoded list that drifts.
|
||||
type TaskLogPage struct {
|
||||
Result
|
||||
Components []string `json:"components"`
|
||||
}
|
||||
|
||||
// ErrTaskLogsUnavailable reports that this process cannot read task logs at
|
||||
// all -- no reader is configured here. It is deliberately not the same answer
|
||||
// as "this attempt has no log" (Result.Found = false): a caller that conflates
|
||||
// them tells an operator task logging is switched off when it is not, which is
|
||||
// the bug this error exists to prevent.
|
||||
var ErrTaskLogsUnavailable = errors.New("logging: task log reader unavailable")
|
||||
|
||||
// taskLogChunkBytes bounds one write a TaskLogContent makes, so a reader that
|
||||
// pushes into a bounded transport emits chunks that transport can carry.
|
||||
// io.Copy would otherwise hand it reads of its own choosing.
|
||||
const taskLogChunkBytes = 256 << 10
|
||||
|
||||
// TaskLog reads one task attempt's persisted log from this registry. A nil
|
||||
// registry (task logging not configured for this process) reports
|
||||
// ErrTaskLogsUnavailable, never an empty page: a process that cannot read logs
|
||||
// must say so rather than implicate the attempt. Safe to call on a nil
|
||||
// receiver, like every other method here.
|
||||
func (r *TaskRegistry) TaskLog(_ context.Context, taskID int64, attempt int, q Query) (TaskLogPage, error) {
|
||||
if r == nil {
|
||||
return TaskLogPage{}, ErrTaskLogsUnavailable
|
||||
}
|
||||
res, err := Tail(TaskLogPath(r.baseDir, taskID, attempt), q)
|
||||
if err != nil {
|
||||
return TaskLogPage{}, err
|
||||
}
|
||||
page := TaskLogPage{Result: res, Components: []string{}}
|
||||
// The filter list is a convenience: failing to build it must not cost the
|
||||
// caller their entries. Components only reads the tail this page already
|
||||
// read, so its error is the same "treat as empty" case the daemon-wide
|
||||
// handler has always applied -- it is dropped deliberately, not missed.
|
||||
if res.Found {
|
||||
if components, err := Components(res.File); err == nil {
|
||||
page.Components = components
|
||||
}
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// TaskLogContent writes one task attempt's log to w exactly as it is on disk,
|
||||
// for a caller that wants the file rather than a decoded page. found is false,
|
||||
// with a nil error, when the attempt has no log file -- a normal state for an
|
||||
// attempt that produced no output, and not an error. A nil registry reports
|
||||
// ErrTaskLogsUnavailable, matching TaskLog.
|
||||
//
|
||||
// The content is streamed rather than returned as one slice because a log file
|
||||
// is unbounded input (it rotates at DefaultMaxSizeMB), and a caller moving it
|
||||
// across a transport with a message-size limit needs it in pieces.
|
||||
func (r *TaskRegistry) TaskLogContent(_ context.Context, taskID int64, attempt int, w io.Writer) (bool, error) {
|
||||
if r == nil {
|
||||
return false, ErrTaskLogsUnavailable
|
||||
}
|
||||
f, err := os.Open(TaskLogPath(r.baseDir, taskID, attempt))
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("logging: open task log: %w", err)
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
if _, err := io.CopyBuffer(w, f, make([]byte, taskLogChunkBytes)); err != nil {
|
||||
return false, fmt.Errorf("logging: read task log: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// PageResult is what a single forward-paged call returns.
|
||||
@@ -293,6 +378,19 @@ func Tail(path string, q Query) (Result, error) {
|
||||
limit = MaxTailLines
|
||||
}
|
||||
|
||||
// found is read before readLines so an absent file is reported as such
|
||||
// rather than only as an empty entry list -- see Result.Found. It is a
|
||||
// Stat rather than a second readWindow: readLines reads the whole scan
|
||||
// window, and doing that twice per Tail call would double the cost of
|
||||
// every log view for one boolean.
|
||||
if strings.TrimSpace(path) != "" {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
res.Found = true
|
||||
} else if !os.IsNotExist(err) {
|
||||
return Result{}, fmt.Errorf("logging: stat %s: %w", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
matches := make([]Entry, 0, limit)
|
||||
truncated, _, ok, err := readLines(path, q, 0, func(e Entry, _ int64) bool {
|
||||
if len(matches) == limit {
|
||||
|
||||
@@ -25,6 +25,7 @@ type (
|
||||
TaskRetryer = storecontract.TaskRetryer
|
||||
TaskQueries = storecontract.TaskQueries
|
||||
TaskEvents = storecontract.TaskEvents
|
||||
TaskLogStore = storecontract.TaskLogStore
|
||||
CaptureStore = storecontract.CaptureStore
|
||||
ConfigSnapshotStore = storecontract.ConfigSnapshotStore
|
||||
MappingStore = storecontract.MappingStore
|
||||
|
||||
@@ -56,7 +56,12 @@ type daemonActions struct {
|
||||
// cfg is the daemon's configuration, held by the stand-in daemon
|
||||
// rather than by the dashboard: retry caps are the task owner's
|
||||
// policy and the dashboard does not hold configuration.
|
||||
cfg *config.Holder
|
||||
cfg *config.Holder
|
||||
// logs is the daemon's own task-log registry. Archiving removes a
|
||||
// task's log files, and that is the daemon's cleanup over the state
|
||||
// directory it owns -- the dashboard reads logs through a contract and
|
||||
// has no directory to remove anything from.
|
||||
logs *logging.TaskRegistry
|
||||
issues *recordingCloser
|
||||
stopper *recordingTaskStopper
|
||||
// scopes records the identity each action arrived with, one per call.
|
||||
@@ -97,10 +102,10 @@ func (d *daemonActions) closeIssue() func(context.Context, string, string, int,
|
||||
}
|
||||
|
||||
func (d *daemonActions) removeLogs() func(int64) error {
|
||||
if d.srv.TaskLogs == nil {
|
||||
if d.logs == nil {
|
||||
return nil
|
||||
}
|
||||
return d.srv.TaskLogs.Remove
|
||||
return d.logs.Remove
|
||||
}
|
||||
|
||||
func (d *daemonActions) publish() func(events.Event) {
|
||||
@@ -701,11 +706,17 @@ func TestArchiveRemovesOnlyOneTerminalTask(t *testing.T) {
|
||||
// logging: without this, an archived task's log files (and every rotated
|
||||
// generation under it) would accumulate on disk forever, since nothing else
|
||||
// in the system ever visits a task again once it leaves the active board.
|
||||
//
|
||||
// The removal is the task owner's, not the dashboard's: the log files live in
|
||||
// the state directory, which the daemon owns, so the stand-in daemon holds the
|
||||
// registry the way the real one does. The dashboard reads logs through a
|
||||
// contract and has no directory to remove anything from.
|
||||
func TestArchiveRemovesTheTaskLogDirectory(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
operatorActions(t, srv).logs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "done", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -715,11 +726,11 @@ func TestArchiveRemovesTheTaskLogDirectory(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := srv.TaskLogs.Open(task.ID, task.Attempt); err != nil {
|
||||
if err := logs.Open(task.ID, task.Attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.TaskLogs.Write(task.ID, logging.Entry{Message: "line"})
|
||||
if err := srv.TaskLogs.Close(task.ID); err != nil {
|
||||
logs.Write(task.ID, logging.Entry{Message: "line"})
|
||||
if err := logs.Close(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := logging.TaskLogDir(baseDir, task.ID)
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
|
||||
// TestHandleTaskLogsDistinguishesNoLogForTheAttempt covers the dashboard's
|
||||
// misleading report. A process that HAS a task-log reader and an attempt that
|
||||
// genuinely has no file on disk is a different answer from a process that
|
||||
// cannot read logs at all, and only the second one is "logging is not enabled
|
||||
// here". The response has to carry that difference or the page cannot state it.
|
||||
func TestHandleTaskLogsDistinguishesNoLogForTheAttempt(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// No log is ever opened for this task: the reader works, the attempt has
|
||||
// no file.
|
||||
|
||||
w := getTaskLogs(t, srv, task.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
var body struct {
|
||||
Disabled bool `json:"disabled"`
|
||||
Found bool `json:"found"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode response: %v (%s)", err, w.Body)
|
||||
}
|
||||
if body.Disabled {
|
||||
t.Error("disabled = true for a process that has a task-log reader; that is the report the page turns into \"logging was not enabled for this run\"")
|
||||
}
|
||||
if body.Found {
|
||||
t.Error("found = true for an attempt with no log file on disk")
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), `"found"`) {
|
||||
t.Errorf("body = %s, want an explicit found marker so the page can say the attempt has no log rather than that logging is off", w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsDownloadServesTheAttemptLog pins the deliverable: the
|
||||
// endpoint hands back the attempt's log as a file download. The route falling
|
||||
// through to the SPA asset handler would answer 200 with an HTML page, so this
|
||||
// asserts on the attachment headers and the body, not merely on the status.
|
||||
func TestHandleTaskLogsDownloadServesTheAttemptLog(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
logs := logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
srv.TaskLogs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := logs.Open(task.ID, task.Attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logs.Write(task.ID, logging.Entry{Level: "ERROR", Message: "gate failed"})
|
||||
if err := logs.Close(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d, body %s", url, w.Code, w.Body)
|
||||
}
|
||||
wantName := "task-" + strconv.FormatInt(task.ID, 10) + "-attempt-" + strconv.Itoa(task.Attempt) + ".log"
|
||||
if got := w.Header().Get("Content-Disposition"); got != `attachment; filename="`+wantName+`"` {
|
||||
t.Errorf("Content-Disposition = %q, want an attachment named %q", got, wantName)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "gate failed") {
|
||||
t.Errorf("download body = %s, want the attempt's own log content", w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsDownloadWithoutALogAnswersNotFound keeps the download
|
||||
// honest: there is nothing to attach, so it says so rather than handing back a
|
||||
// zero-byte file that looks like a successful download of nothing.
|
||||
func TestHandleTaskLogsDownloadWithoutALogAnswersNotFound(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(t.TempDir(), logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("GET %s with no log = %d, want 404", url, w.Code)
|
||||
}
|
||||
// The response is an error, not a file. Attachment headers are written
|
||||
// before the read (the body streams, so the size is unknown up front), and
|
||||
// leaving them on a 404 hands the caller a .log attachment containing only
|
||||
// the error text.
|
||||
if got := w.Header().Get("Content-Disposition"); got != "" {
|
||||
t.Errorf("Content-Disposition = %q on a 404, want it cleared so the error is not presented as a download", got)
|
||||
}
|
||||
if got := w.Header().Get("Content-Type"); strings.Contains(got, "ndjson") {
|
||||
t.Errorf("Content-Type = %q on a 404, want the error content type rather than the log's", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskLogsDownloadWithoutAReaderAnswersServiceUnavailable is the
|
||||
// degradation the boundary permits: a process with no task-log contract answers
|
||||
// 503 rather than 404, because "I cannot read logs" and "there is no log" are
|
||||
// not the same claim.
|
||||
func TestHandleTaskLogsDownloadWithoutAReaderAnswersServiceUnavailable(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
url := "/api/tasks/" + strconv.FormatInt(task.ID, 10) + "/logs/download"
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
body, _ := io.ReadAll(w.Result().Body)
|
||||
t.Fatalf("GET %s without a reader = %d (%s), want 503", url, w.Code, body)
|
||||
}
|
||||
// Same rule as the 404: an unavailable reader is an error, not a file.
|
||||
if got := w.Header().Get("Content-Disposition"); got != "" {
|
||||
t.Errorf("Content-Disposition = %q on a 503, want it cleared so the error is not presented as a download", got)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -16,84 +19,213 @@ import (
|
||||
// Attempt from the store, since that is what a human or Archie's own chat
|
||||
// tool means by "why did task N park?" almost every time: the most recent
|
||||
// run, not an arbitrary earlier retry.
|
||||
//
|
||||
// Two outcomes are kept apart on purpose, because only one of them is about
|
||||
// the operator's configuration. A process with no task-log reader cannot say
|
||||
// anything about an attempt, so it reports disabled and the page explains that
|
||||
// this process cannot read logs. A process WITH a reader and an attempt with
|
||||
// no log file reports found=false, which the page states as no log recorded
|
||||
// for the attempt. Collapsing the second into the first is what made the
|
||||
// dashboard claim "task logging is optional and was not enabled for this run"
|
||||
// for every attempt of every task in a deployment where logging is
|
||||
// unconditional.
|
||||
func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
id, attempt, ok := s.taskLogTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
task, err := s.Store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
reader := s.taskLogReader()
|
||||
if reader == nil {
|
||||
writeDisabledTaskLogs(w, attempt)
|
||||
return
|
||||
}
|
||||
|
||||
q := r.URL.Query()
|
||||
attempt := task.Attempt
|
||||
if raw := strings.TrimSpace(q.Get("attempt")); raw != "" {
|
||||
attempt, err = strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
http.Error(w, "bad attempt", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
path := s.TaskLogs.Path(id, attempt)
|
||||
if path == "" {
|
||||
// Not an error: task logging is optional, same convention as
|
||||
// handleLogs for the daemon-wide log.
|
||||
writeJSON(w, map[string]any{
|
||||
"entries": []logging.Entry{},
|
||||
"file": "",
|
||||
"disabled": true,
|
||||
"attempt": attempt,
|
||||
})
|
||||
limit, ok := taskLogLimit(w, q.Get("limit"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
limit := logging.DefaultTailLines
|
||||
if raw := strings.TrimSpace(q.Get("limit")); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
http.Error(w, "bad limit", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case parsed <= 0:
|
||||
limit = logging.DefaultTailLines
|
||||
case parsed > logging.MaxTailLines:
|
||||
limit = logging.MaxTailLines
|
||||
default:
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
result, err := logging.Tail(path, logging.Query{
|
||||
page, err := reader.TaskLog(r.Context(), id, attempt, logging.Query{
|
||||
Levels: splitCSV(q.Get("level")),
|
||||
Component: strings.TrimSpace(q.Get("component")),
|
||||
Contains: strings.TrimSpace(q.Get("q")),
|
||||
Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
// A reader that exists but cannot read here is still a statement about
|
||||
// this process rather than about the attempt, so it keeps the disabled
|
||||
// answer instead of claiming the attempt has no log.
|
||||
if errors.Is(err, logging.ErrTaskLogsUnavailable) {
|
||||
writeDisabledTaskLogs(w, attempt)
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
components, err := logging.Components(path)
|
||||
if err != nil {
|
||||
s.Log.Warn("task log components unavailable", "task_id", id, "err", err)
|
||||
components = []string{}
|
||||
}
|
||||
|
||||
writeJSON(w, map[string]any{
|
||||
"entries": result.Entries,
|
||||
"truncated": result.Truncated,
|
||||
"file": result.File,
|
||||
"components": components,
|
||||
"entries": page.Entries,
|
||||
"truncated": page.Truncated,
|
||||
"file": page.File,
|
||||
"components": page.Components,
|
||||
"attempt": attempt,
|
||||
// found is the distinction the page needs: a reader answering with no
|
||||
// entries because the file is absent is not a reader that is absent.
|
||||
"found": page.Found,
|
||||
})
|
||||
}
|
||||
|
||||
// handleTaskLogDownload serves one task attempt's log verbatim as a file
|
||||
// download -- the log itself rather than a decoded view of it, because an
|
||||
// operator who asks for a download wants to read it in their own tooling or
|
||||
// hand it to someone else.
|
||||
//
|
||||
// The conditions stay apart here too. A process with no reader answers 503,
|
||||
// not 404: "there is no log for this attempt" is a claim only a process that
|
||||
// can look is in a position to make.
|
||||
func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) {
|
||||
id, attempt, ok := s.taskLogTarget(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
reader := s.taskLogReader()
|
||||
if reader == nil {
|
||||
http.Error(w, logging.ErrTaskLogsUnavailable.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
// Headers are set before the read because the body streams straight from
|
||||
// the reader into the response: a log file is unbounded input, so
|
||||
// buffering it to size the response would defeat the reason the reader
|
||||
// streams at all. The attempt's own name is known up front.
|
||||
//
|
||||
// Everything after this point must therefore CLEAR them before writing an
|
||||
// error, never add to them: a 404 still carrying `Content-Disposition:
|
||||
// attachment` is a browser download of the error text under a .log
|
||||
// filename, and the NDJSON type would misdescribe it too.
|
||||
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+taskLogFilename(id, attempt)+`"`)
|
||||
|
||||
clearAttachment := func() {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.Header().Del("Content-Disposition")
|
||||
}
|
||||
|
||||
found, err := reader.TaskLogContent(r.Context(), id, attempt, w)
|
||||
if err != nil {
|
||||
if errors.Is(err, logging.ErrTaskLogsUnavailable) {
|
||||
clearAttachment()
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
// Once a 200 and a body are on the wire there is no status left to
|
||||
// send, so a failure partway through is logged where an operator can
|
||||
// find it rather than silently truncating the file.
|
||||
s.logf("task log download failed", "task", id, "attempt", attempt, "err", err)
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
clearAttachment()
|
||||
http.Error(w, "no log recorded for this attempt", http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
// taskLogTarget resolves the {id} path value and the task it names, returning
|
||||
// the attempt to read: the "attempt" query parameter when the request names
|
||||
// one, otherwise the task's current Attempt. It answers the request itself and
|
||||
// reports false when either step fails.
|
||||
func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
return 0, 0, false
|
||||
}
|
||||
task, err := s.Store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return 0, 0, false
|
||||
}
|
||||
if task == nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
attempt = task.Attempt
|
||||
if raw := strings.TrimSpace(r.URL.Query().Get("attempt")); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
http.Error(w, "bad attempt", http.StatusBadRequest)
|
||||
return 0, 0, false
|
||||
}
|
||||
attempt = parsed
|
||||
}
|
||||
return id, attempt, true
|
||||
}
|
||||
|
||||
// taskLogLimit bounds a page the way handleLogs bounds the daemon-wide read:
|
||||
// the limit is caller-supplied and a log file is unbounded, so a request must
|
||||
// not be able to pull an arbitrary amount of it into memory.
|
||||
func taskLogLimit(w http.ResponseWriter, raw string) (int, bool) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return logging.DefaultTailLines, true
|
||||
}
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
http.Error(w, "bad limit", http.StatusBadRequest)
|
||||
return 0, false
|
||||
}
|
||||
switch {
|
||||
case parsed <= 0:
|
||||
return logging.DefaultTailLines, true
|
||||
case parsed > logging.MaxTailLines:
|
||||
return logging.MaxTailLines, true
|
||||
default:
|
||||
return parsed, true
|
||||
}
|
||||
}
|
||||
|
||||
// writeDisabledTaskLogs is the "this process cannot read task logs" answer,
|
||||
// the same convention handleLogs uses for the daemon-wide log: an optional
|
||||
// capability that is absent here must not turn "why did this task park?" into
|
||||
// a 500 for every task.
|
||||
func writeDisabledTaskLogs(w http.ResponseWriter, attempt int) {
|
||||
writeJSON(w, map[string]any{
|
||||
"entries": []logging.Entry{},
|
||||
"file": "",
|
||||
"disabled": true,
|
||||
"attempt": attempt,
|
||||
})
|
||||
}
|
||||
|
||||
// taskLogFilename names a downloaded attempt's log. It carries the task and
|
||||
// the attempt because an operator downloading two attempts of the same task
|
||||
// must not end up with one file overwriting the other, and the attempt is the
|
||||
// one identifier the log's own path would have given them.
|
||||
func taskLogFilename(taskID int64, attempt int) string {
|
||||
return "task-" + strconv.FormatInt(taskID, 10) + "-attempt-" + strconv.Itoa(attempt) + ".log"
|
||||
}
|
||||
|
||||
// taskLogReader is the task-log read capability this process has, or nil when
|
||||
// it has none. The seam is a narrow interface rather than a concrete registry
|
||||
// so the same handlers serve both processes: the daemon holds a registry over
|
||||
// its own state directory, the dashboard holds the State Store client. A
|
||||
// consumer-owned seam is the difference between the dashboard degrading
|
||||
// honestly and the dashboard opening another process's files.
|
||||
func (s *Server) taskLogReader() TaskLogSource {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.TaskLogs
|
||||
}
|
||||
|
||||
// TaskLogSource is the read seam the task-log handlers consume. It is the
|
||||
// logging package's own reader contract, so a registry and a remote client
|
||||
// satisfy it without either one restating the log format -- the package that
|
||||
// owns the format also owns the shape of a read of it.
|
||||
type TaskLogSource interface {
|
||||
// TaskLog returns a page of one attempt's decoded log.
|
||||
TaskLog(ctx context.Context, taskID int64, attempt int, q logging.Query) (logging.TaskLogPage, error)
|
||||
// TaskLogContent writes one attempt's log verbatim to w, for a download.
|
||||
TaskLogContent(ctx context.Context, taskID int64, attempt int, w io.Writer) (bool, error)
|
||||
}
|
||||
@@ -14,7 +14,8 @@ func TestHandleTaskLogsReturnsEntriesForLatestAttemptByDefault(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
srv.TaskLogs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -24,13 +25,13 @@ func TestHandleTaskLogsReturnsEntriesForLatestAttemptByDefault(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := srv.TaskLogs.Open(task.ID, task.Attempt); err != nil {
|
||||
if err := logs.Open(task.ID, task.Attempt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv.TaskLogs.Write(task.ID, logging.Entry{
|
||||
logs.Write(task.ID, logging.Entry{
|
||||
Level: "ERROR", Message: "gate failed", Fields: map[string]any{"component": "gate"},
|
||||
})
|
||||
if err := srv.TaskLogs.Close(task.ID); err != nil {
|
||||
if err := logs.Close(task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -58,7 +59,8 @@ func TestHandleTaskLogsHonoursExplicitAttempt(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
baseDir := t.TempDir()
|
||||
srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
logs := logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{})
|
||||
srv.TaskLogs = logs
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -43,10 +43,16 @@ type Server struct {
|
||||
// LogFeed is the daemon diagnostic stream. It is separate from Events,
|
||||
// which contains persisted task lifecycle activity only.
|
||||
LogFeed *logging.Feed
|
||||
// TaskLogs holds each task's persisted log output. Archiving a task
|
||||
// removes its log files here too, via TaskLogs.Remove -- nil (task
|
||||
// logging not configured) makes that a no-op.
|
||||
TaskLogs *logging.TaskRegistry
|
||||
// TaskLogs reads each task's persisted log output. Composition gives this
|
||||
// process whichever implementation it can use: the daemon (whose state
|
||||
// directory holds the files) its own *logging.TaskRegistry, and the
|
||||
// dashboard process, which owns no such directory, the State Store client
|
||||
// -- the read crosses a contract rather than opening a file
|
||||
// (docs/prds/ui-service-boundary.md). Nil means this process has no
|
||||
// task-log capability at all, which the handlers report as disabled rather
|
||||
// than as "the attempt has no log": those are different claims and only one
|
||||
// of them is about configuration.
|
||||
TaskLogs TaskLogSource
|
||||
|
||||
// UpdateConfig applies a set of dotted-path config updates through
|
||||
// the same validate-persist-publish path as reload (wired by the
|
||||
@@ -238,6 +244,7 @@ func (s *Server) registerTaskRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs/download", s.handleTaskLogDownload)
|
||||
}
|
||||
|
||||
func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
|
||||
|
||||
@@ -53,6 +53,18 @@ service StateStoreService {
|
||||
rpc PutConfigSnapshot(PutConfigSnapshotRequest) returns (PutConfigSnapshotResponse);
|
||||
rpc GetConfigSnapshot(GetConfigSnapshotRequest) returns (GetConfigSnapshotResponse);
|
||||
|
||||
// Task log: one task attempt's persisted log. Task log files live in the
|
||||
// state directory this process owns, so the dashboard reads them over this
|
||||
// contract rather than opening them itself
|
||||
// (docs/prds/ui-service-boundary.md).
|
||||
rpc ReadTaskLog(ReadTaskLogRequest) returns (ReadTaskLogResponse);
|
||||
// StreamTaskLogContent returns one attempt's log verbatim, one chunk per
|
||||
// message, for a download. A log file is unbounded input (it rotates at
|
||||
// DefaultMaxSizeMB), so a unary response would exceed gRPC's 4MiB message
|
||||
// cap on a real log -- the same reason ListCaptures was superseded by
|
||||
// StreamCaptures.
|
||||
rpc StreamTaskLogContent(StreamTaskLogContentRequest) returns (stream StreamTaskLogContentResponse);
|
||||
|
||||
// Capture
|
||||
rpc InsertCapture(InsertCaptureRequest) returns (InsertCaptureResponse);
|
||||
// ListCaptures is superseded by StreamCaptures (kept, unmodified, so an
|
||||
@@ -372,6 +384,64 @@ message GetConfigSnapshotResponse {
|
||||
bool found = 2;
|
||||
}
|
||||
|
||||
// TaskLogEntry mirrors internal/logging.Entry: one decoded log line. fields
|
||||
// carries every remaining key as a JSON object string, the same way Event
|
||||
// carries its data, so structured context survives the hop without this
|
||||
// contract having to know what a call site attached.
|
||||
message TaskLogEntry {
|
||||
int64 id = 1;
|
||||
google.protobuf.Timestamp time = 2;
|
||||
string level = 3;
|
||||
string msg = 4;
|
||||
string fields_json = 5;
|
||||
}
|
||||
|
||||
// ReadTaskLog returns a page of one task attempt's decoded log. attempt is the
|
||||
// attempt the caller resolved (the dashboard sends the task's current attempt
|
||||
// when the request omitted one). levels, component, contains, since and until
|
||||
// carry the whole query the logging package's Tail accepts -- the wire mirrors
|
||||
// that query rather than a subset of it, so a filter cannot silently stop
|
||||
// working by crossing the boundary. limit is caller-capped
|
||||
// (docs/prds/state-store-contract.md §8: the log cap is 2000).
|
||||
message ReadTaskLogRequest {
|
||||
int64 task_id = 1;
|
||||
int64 attempt = 2;
|
||||
int64 limit = 3;
|
||||
repeated string levels = 4;
|
||||
string component = 5;
|
||||
string contains = 6;
|
||||
google.protobuf.Timestamp since = 7;
|
||||
google.protobuf.Timestamp until = 8;
|
||||
}
|
||||
// found=false is not an error: the task has no log file for that attempt.
|
||||
// That is a different condition from a process that cannot read logs at all
|
||||
// (codes.Unavailable), and the dashboard reports them differently.
|
||||
message ReadTaskLogResponse {
|
||||
repeated TaskLogEntry entries = 1;
|
||||
bool truncated = 2;
|
||||
int64 attempt = 3;
|
||||
bool found = 4;
|
||||
repeated string components = 5;
|
||||
// file is the path read, so the page can name where the log came from. It
|
||||
// is the state directory's own layout, reported to an already-authenticated
|
||||
// operator; no caller is expected to open it.
|
||||
string file = 6;
|
||||
}
|
||||
|
||||
// StreamTaskLogContent returns one attempt's log verbatim, for a download. The
|
||||
// bytes are the file's own JSONL, not a re-encoding of it: this contract
|
||||
// transports the log, it does not restate the format. found=false, with no
|
||||
// chunks, means the attempt has no log file -- not an error.
|
||||
message StreamTaskLogContentRequest {
|
||||
int64 task_id = 1;
|
||||
int64 attempt = 2;
|
||||
}
|
||||
message StreamTaskLogContentResponse {
|
||||
bytes chunk = 1;
|
||||
int64 attempt = 2;
|
||||
bool found = 3;
|
||||
}
|
||||
|
||||
message InsertCaptureRequest {
|
||||
CapturedEvent capture = 1;
|
||||
int64 retention_seconds = 2;
|
||||
|
||||
Vendored
+8
-8
@@ -1,16 +1,16 @@
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),te(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,re(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=te(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&ie(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=ee(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),L(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function ee(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function M(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function N(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||M(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||M(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function P(e){return function(n){if(this.l){var rLine truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var de=class extends Error{constructor(e,t){super(e),this.status=t}};function fe(e){let t=e instanceof de?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function pe(e,t){let n=await fetch(e,t);if(!n.ok)throw new de(await ue(n),n.status);return n}async function R(e,{method:t=`GET`,body:n,timeoutMs:r=ce,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await pe(e,o);return i?s.json():void 0}var z={summary:()=>R(`/api/summary`),tasks:()=>R(`/api/tasks`),taskMeta:()=>R(`/api/task-meta`),task:e=>R(`/api/tasks/${e}`),taskAction:(e,t)=>R(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>R(`/api/setup`),capabilities:()=>R(`/api/capabilities`),workflows:()=>R(`/api/workflows`),workRequest:e=>R(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>R(`/api/skills`),channels:()=>R(`/api/channels`),curators:()=>R(`/api/curators`),channelReload:e=>R(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>R(`/api/config`),version:()=>R(`/api/version`),configUpdate:e=>R(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>R(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>R(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>R(`/api/logs`+le(e)),taskLogs:(e,t)=>R(`/api/tasks/${e}/logs`+le(t)),captures:e=>R(`/api/captures`+le({limit:e})),mappings:()=>R(`/api/mappings`),mappingCreate:e=>R(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>R(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>R(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>R(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>R(`/api/bindings`),bindingCreate:e=>R(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>R(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>R(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>R(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>R(`/api/memory`),chatSessions:()=>R(`/api/chat/sessions`),chatMessages:e=>R(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>R(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>R(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>R(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:se(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>R(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>R(`/api/chat/update`),chatUpdateDefer:e=>R(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>R(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>R(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>R(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>R(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>pe(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function B(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function me(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function he(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var ge=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],_e=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quLine truncated
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),te(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,re(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=te(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&L(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=ee(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),R(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function ee(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function M(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function N(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||M(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||M(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function P(e){return function(n){if(this.l){var r=Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var ue=class extends Error{constructor(e,t){super(e),this.status=t}};function de(e){let t=e instanceof ue?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function fe(e,t){let n=await fetch(e,t);if(!n.ok)throw new ue(await le(n),n.status);return n}async function z(e,{method:t=`GET`,body:n,timeoutMs:r=se,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await fe(e,o);return i?s.json():void 0}var B={summary:()=>z(`/api/summary`),tasks:()=>z(`/api/tasks`),taskMeta:()=>z(`/api/task-meta`),task:e=>z(`/api/tasks/${e}`),taskAction:(e,t)=>z(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>z(`/api/setup`),capabilities:()=>z(`/api/capabilities`),workflows:()=>z(`/api/workflows`),workRequest:e=>z(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>z(`/api/skills`),channels:()=>z(`/api/channels`),curators:()=>z(`/api/curators`),channelReload:e=>z(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>z(`/api/config`),version:()=>z(`/api/version`),configUpdate:e=>z(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>z(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>z(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>z(`/api/logs`+ce(e)),taskLogs:(e,t)=>z(`/api/tasks/${e}/logs`+ce(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>z(`/api/captures`+ce({limit:e})),mappings:()=>z(`/api/mappings`),mappingCreate:e=>z(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>z(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>z(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>z(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>z(`/api/bindings`),bindingCreate:e=>z(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>z(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>z(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>z(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>z(`/api/memory`),chatSessions:()=>z(`/api/chat/sessions`),chatMessages:e=>z(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>z(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>z(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>z(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:oe(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>z(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>z(`/api/chat/update`),chatUpdateDefer:e=>z(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>z(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>z(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>z(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>z(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>fe(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function V(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function pe(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function me(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var he=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],ge=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`ALine truncated
|
||||
<path d="${c(150,240)}" fill="none" stroke="var(--border)"
|
||||
stroke-width="12" stroke-linecap="round"/>
|
||||
<path d="${c(150,240)}" fill="none" stroke="${i}"
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${s}"
|
||||
stroke-dashoffset="${s*(1-r/100)}"
|
||||
class="gauge-value"/>`,H(`div.gauge-wrap`,l,H(`div.gauge-center`,H(`div.gauge-pct`,`${Math.round(r)}%`),H(`div.gauge-label`,t)))}function et(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return H(`div`,H(`div.segbar`,...e.filter(e=>e.value>0).map(e=>H(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),H(`div.segbar-legend`,...e.map(e=>H(`span.segbar-key`,H(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var tt=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--tt,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}function Z({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}var nt=`archie.setup-complete.dismissed.v1`;function rt(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(nt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function it(e=globalThis.localStorage){e?.setItem?.(nt,`1`)}var at=new Set([`waiting_human`,`parked`]);function ot(e=[]){let t=e.filter(e=>at.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function st({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function ct(e){return X(st,{node:Ze(e)})}function lt(e){return X(st,{node:$e(e)})}function ut({segments:e}){return X(st,{node:et(e)})}function dt({name:e,opts:t}){return X(st,{node:W(e,t)})}function ft({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pt(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function mt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function ht(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function gt(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,a]=q(`idle`),[o,s]=q(new Map),[c,l]=q(null),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[,v]=q(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([z.summary(),z.setup().catch(()=>null),z.workflows().catch(()=>null),z.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};J(()=>(y(),B(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{it(),v(e=>!e)},x=u?.operator?`${mt()}, ${u.operator}`:mt(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=ot(m),t=e.attention.count,n=e.running.count;C=X(S,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(dt,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(dt,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(dt,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(ft,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=X(S,{children:[X(ct,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(ct,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(ct,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(ct,{label:`Tokens used`,value:Oe(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:ht(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=rt(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children:
Line truncated
|
||||
`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Z,{text:pn[e.status]||e.status,kind:mn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function gn({origins:e}){return e?.length?X($,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(ln,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function _n(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function vn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??Se(e.id),n=e.kind??Ce(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Z,{text:t,kind:n})})]},e.id)})}):X(Q,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=_n(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function yn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(!1),[o,s]=q(null),[c,l]=q(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await z.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function bn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await z.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function xn({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X($,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(yn,{r:e,field:`allow_concuLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(H(`p`,fr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(H(`pre`,H(`code`,a.join(`
|
||||
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=mr(c),u=e+1<n.length?mr(n[e+1]):null;if(l&&u&&hr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=mr(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=H(`tbody`);for(let e of r)i.append(H(`tr`,...e.map(e=>H(`td`,fr(e)))));t.append(H(`table`,H(`thead`,H(`tr`,...l.map(e=>H(`th`,fr(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(H(`h${d[1].length}`,fr(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.tagName.toLowerCase()!==e)&&(s(),i=H(e)),i.append(H(`li`,fr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(H(`blockquote`,fr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(H(`pre`,H(`code`,a.join(`
|
||||
`)))),t}function mr(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 hr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var gr=`archie.web.chat.channel`;function _r(){let e=localStorage.getItem(gr);return e||(e=se(),localStorage.setItem(gr,e)),e}function vr(e){return{text:e,sourceID:se()}}function yr(e){return{...e}}function br(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?yr(e.turn):vr(r),isRetry:n}}function xr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Sr(e){return e?.status===501?null:`Could not check for updates.`}function Cr(){return location.hash.slice(1)||`/`}function wr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(pr(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Tr(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q([]),[o,s]=q(``),[c,l]=q(`Ready`),[u,d]=q(!1),[f,p]=q({}),[m,h]=q(``),[g,_]=q(``),[v,y]=q(``),[b,x]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,ee]=q(null),[M,N]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),ie=Y(null),L=Y(null),ae=Y(null),oe=Y(null),se=Y(null),ce=Y(u);ce.current=u,J(()=>{ie.current&&(ie.current.scrollTop=ie.current.scrollHeight)},[i,F]),J(()=>{B().catch(e=>{l(e.message||`Chat unavailable`)}),le();let e=()=>{ae.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ae.current?.abort()}},[]);async function le(){try{let e=await z.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=Sr(e);A(t?{error:t}:null)}}async function ue(){if(j)try{await z.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function de(){if(j)try{l(`Installing…`);let e=await z.chatUpdateInstall(j);ee(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function fe(){try{let e=await z.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function pe(e,t){if(t)try{await z.chatDangerousRequest(e,t),l(`Approval requested`),await fe()}catch(e){l(e.message||`Could not request action`)}}async function R(e,t){try{await z.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await fe()}catch(e){l(e.message||`Approval failed`)}}async function B(){let e=await z.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await fe(),!n&&r[0]&&await me(r[0].session_id,e,r)}async function me(e,t,n){let i=t||f;r(e),a([]),I(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await z.chatMessage(_r(),`/resume ${e}`);let[t,n]=await Promise.all([z.chatMessages(e),z.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function he(e){if(n)try{l(`Working…`);let t=await z.chatMessage(_r(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await B(),(t.session_id||n)&&await me(t.session_id||n),oe.current&&(oe.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function ge(e,t){let n=window.prompt(t);n?.trim()&&he(`${e} ${n.trim()}`)}function _e(e){let t=e.target.value;h(t),!(!n||!t)&&z.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function ve(e){let t=e.target.value;if(_(t),t)try{let e=await z.chatMessage(_r(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await B()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ye(e){let t=e.target.value;if(y(t),t)try{let e=await z.chatMessage(_r(),`/model ${t}`);l(e.reply||`Model updated`),await B()}catch(e){l(`Model update failed: ${e.message||e}`)}}function be(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),V({textOverride:`/restart`}))}function xe(){s(`/new`),V({textOverride:`/new`})}function Se(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function Ce(e){let t=C[e];if(!t||!L.current)return;let n=L.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.se
Line truncated
|
||||
class="gauge-value"/>`,U(`div.gauge-wrap`,l,U(`div.gauge-center`,U(`div.gauge-pct`,`${Math.round(r)}%`),U(`div.gauge-label`,t)))}function et(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return U(`div`,U(`div.segbar`,...e.filter(e=>e.value>0).map(e=>U(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),U(`div.segbar-legend`,...e.map(e=>U(`span.segbar-key`,U(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var tt=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--tt,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}function Z({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}var nt=`archie.setup-complete.dismissed.v1`;function rt(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(nt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function it(e=globalThis.localStorage){e?.setItem?.(nt,`1`)}var at=new Set([`waiting_human`,`parked`]);function ot(e=[]){let t=e.filter(e=>at.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function st({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function ct(e){return X(st,{node:Ze(e)})}function lt(e){return X(st,{node:$e(e)})}function ut({segments:e}){return X(st,{node:et(e)})}function dt({name:e,opts:t}){return X(st,{node:W(e,t)})}function ft({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pt(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function mt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function ht(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function gt(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,a]=q(`idle`),[o,s]=q(new Map),[c,l]=q(null),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[,v]=q(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([B.summary(),B.setup().catch(()=>null),B.workflows().catch(()=>null),B.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};J(()=>(y(),V(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{it(),v(e=>!e)},x=u?.operator?`${mt()}, ${u.operator}`:mt(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=ot(m),t=e.attention.count,n=e.running.count;C=X(S,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(dt,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(dt,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(dt,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(ft,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=X(S,{children:[X(ct,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(ct,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(ct,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(ct,{label:`Tokens used`,value:Oe(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:ht(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=rt(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children:
Line truncated
|
||||
`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Z,{text:mn[e.status]||e.status,kind:hn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function _n({origins:e}){return e?.length?X($,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(un,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function vn(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function yn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??xe(e.id),n=e.kind??Se(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Z,{text:t,kind:n})})]},e.id)})}):X(Q,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=vn(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function bn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(!1),[o,s]=q(null),[c,l]=q(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await B.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function xn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await B.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function Sn({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X($,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(bn,{r:e,field:`allow_concuLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(U(`p`,pr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(U(`pre`,U(`code`,a.join(`
|
||||
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=hr(c),u=e+1<n.length?hr(n[e+1]):null;if(l&&u&&gr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=hr(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=U(`tbody`);for(let e of r)i.append(U(`tr`,...e.map(e=>U(`td`,pr(e)))));t.append(U(`table`,U(`thead`,U(`tr`,...l.map(e=>U(`th`,pr(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(U(`h${d[1].length}`,pr(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.tagName.toLowerCase()!==e)&&(s(),i=U(e)),i.append(U(`li`,pr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(U(`blockquote`,pr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(U(`pre`,U(`code`,a.join(`
|
||||
`)))),t}function hr(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 gr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var _r=`archie.web.chat.channel`;function vr(){let e=localStorage.getItem(_r);return e||(e=oe(),localStorage.setItem(_r,e)),e}function yr(e){return{text:e,sourceID:oe()}}function br(e){return{...e}}function xr(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?br(e.turn):yr(r),isRetry:n}}function Sr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Cr(e){return e?.status===501?null:`Could not check for updates.`}function wr(){return location.hash.slice(1)||`/`}function Tr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(mr(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Er(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q([]),[o,s]=q(``),[c,l]=q(`Ready`),[u,d]=q(!1),[f,p]=q({}),[m,h]=q(``),[g,_]=q(``),[v,y]=q(``),[b,x]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,ee]=q(null),[M,N]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),L=Y(null),R=Y(null),ie=Y(null),ae=Y(null),oe=Y(null),se=Y(u);se.current=u,J(()=>{L.current&&(L.current.scrollTop=L.current.scrollHeight)},[i,F]),J(()=>{V().catch(e=>{l(e.message||`Chat unavailable`)}),ce();let e=()=>{ie.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ie.current?.abort()}},[]);async function ce(){try{let e=await B.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=Cr(e);A(t?{error:t}:null)}}async function le(){if(j)try{await B.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function ue(){if(j)try{l(`Installing…`);let e=await B.chatUpdateInstall(j);ee(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function de(){try{let e=await B.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function fe(e,t){if(t)try{await B.chatDangerousRequest(e,t),l(`Approval requested`),await de()}catch(e){l(e.message||`Could not request action`)}}async function z(e,t){try{await B.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await de()}catch(e){l(e.message||`Approval failed`)}}async function V(){let e=await B.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await de(),!n&&r[0]&&await pe(r[0].session_id,e,r)}async function pe(e,t,n){let i=t||f;r(e),a([]),I(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await B.chatMessage(vr(),`/resume ${e}`);let[t,n]=await Promise.all([B.chatMessages(e),B.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function me(e){if(n)try{l(`Working…`);let t=await B.chatMessage(vr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await V(),(t.session_id||n)&&await pe(t.session_id||n),ae.current&&(ae.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function he(e,t){let n=window.prompt(t);n?.trim()&&me(`${e} ${n.trim()}`)}function ge(e){let t=e.target.value;h(t),!(!n||!t)&&B.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function _e(e){let t=e.target.value;if(_(t),t)try{let e=await B.chatMessage(vr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await V()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ve(e){let t=e.target.value;if(y(t),t)try{let e=await B.chatMessage(vr(),`/model ${t}`);l(e.reply||`Model updated`),await V()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ye(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),H({textOverride:`/restart`}))}function be(){s(`/new`),H({textOverride:`/new`})}function xe(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function Se(e){let t=C[e];if(!t||!R.current)return;let n=R.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search
Line truncated
|
||||
|
||||
`);o=a.pop()||``;for(let e of a){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&r(n.session_id),n.type===`delta`&&(f+=n.text,I(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),I(null),l(`Ready`),await B()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:u,isError:!0,turn:yr(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ae.current=null,d(!1),L.current&&L.current.focus()}}function Te(){l(`Stopping…`),n&&z.chatCancel(n).catch(()=>{}),ae.current?.abort()}let H=f.models_by_provider||{},Ee=g&&H[g]?H[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:be,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:le,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:_e,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:ve,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:ye,children:[X(`option`,{value:``,children:`Model`}),Ee.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:ue,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:de,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&M&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:P,onChange:e=>te(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(M.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`stop`,ne),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(M.pending||[]).length?M.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>R(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>R(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>R(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:xe,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>me(e.session_id),children:[X(`strong`,{children:xr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will aLine truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&r(n.session_id),n.type===`delta`&&(f+=n.text,I(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),I(null),l(`Ready`),await V()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:u,isError:!0,turn:br(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ie.current=null,d(!1),R.current&&R.current.focus()}}function we(){l(`Stopping…`),n&&B.chatCancel(n).catch(()=>{}),ie.current?.abort()}let U=f.models_by_provider||{},Te=g&&U[g]?U[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:ye,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ce,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:ge,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:_e,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:ve,children:[X(`option`,{value:``,children:`Model`}),Te.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:le,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:ue,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&M&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:P,onChange:e=>te(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(M.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`stop`,ne),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(M.pending||[]).length?M.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:be,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>pe(e.session_id),children:[X(`strong`,{children:Sr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will aLine truncated
|
||||
@@ -112,6 +112,11 @@ export const api = {
|
||||
configReset: (key) => request("/api/config/reset", { method: "POST", body: { key } }),
|
||||
logs: (params) => request("/api/logs" + qs(params)),
|
||||
taskLogs: (id, params) => request(`/api/tasks/${id}/logs` + qs(params)),
|
||||
// A download is a navigation, not a fetch: the browser must own the
|
||||
// Content-Disposition filename and stream the body to disk rather than hold
|
||||
// a whole log in memory. The URL builder is the client-side contract, and
|
||||
// base/log-row's sibling module keeps it beside the panel that uses it.
|
||||
taskLogDownloadURL: (id, attempt) => `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`),
|
||||
captures: (limit) => request("/api/captures" + qs({ limit })),
|
||||
mappings: () => request("/api/mappings"),
|
||||
mappingCreate: (mapping) => request("/api/mappings", { method: "POST", body: mapping }),
|
||||
|
||||
@@ -10,7 +10,14 @@ function LogRowNode({ entry }) {
|
||||
return <div ref={ref} style={{ display: 'contents' }} />;
|
||||
}
|
||||
|
||||
export function TaskLogPanel({ state, onRetry }) {
|
||||
// Task-log download URL. The attempt is named explicitly so a download matches
|
||||
// the attempt the panel is showing rather than whatever is current by the time
|
||||
// the operator clicks.
|
||||
export function taskLogDownloadURL(id, attempt) {
|
||||
return `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`);
|
||||
}
|
||||
|
||||
export function TaskLogPanel({ state, onRetry, taskId }) {
|
||||
if (state === undefined) {
|
||||
return <div className="task-log-loading">Loading attempt log…</div>;
|
||||
}
|
||||
@@ -22,28 +29,54 @@ export function TaskLogPanel({ state, onRetry }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// A reader exists in this process but the attempt has no log file. That is a
|
||||
// fact about the attempt, and saying "logging was not enabled" here (which
|
||||
// this panel used to do) told the operator to go and change a setting that
|
||||
// was already correct.
|
||||
if (state.found === false && !state.disabled) {
|
||||
return (
|
||||
<div className="empty">
|
||||
<div className="empty-title">No log recorded for this attempt</div>
|
||||
<div>This attempt produced no output, or it has not started writing yet.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// This process cannot read task logs at all. That IS about the deployment,
|
||||
// and it is the only case where the panel may say so.
|
||||
if (state.disabled) {
|
||||
return (
|
||||
<div className="empty">
|
||||
<div className="empty-title">No persisted log for this attempt</div>
|
||||
<div>Task logging is optional and was not enabled for this run.</div>
|
||||
<div>This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const entries = state.entries || [];
|
||||
const download = taskId != null ? taskLogDownloadURL(taskId, state.attempt) : null;
|
||||
const footer = download ? (
|
||||
<a className="btn btn-small task-log-download" href={download} download>Download log</a>
|
||||
) : null;
|
||||
|
||||
if (!entries.length) {
|
||||
return (
|
||||
<div className="empty">
|
||||
<div className="empty-title">Nothing recorded</div>
|
||||
<div>This attempt's log file has no entries matching the current filter.</div>
|
||||
{footer}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="log-list task-log-list">
|
||||
{entries.map((entry, i) => (
|
||||
<LogRowNode key={i} entry={entry} />
|
||||
))}
|
||||
</div>
|
||||
<>
|
||||
<div className="log-list task-log-list">
|
||||
{entries.map((entry, i) => (
|
||||
<LogRowNode key={i} entry={entry} />
|
||||
))}
|
||||
</div>
|
||||
{footer}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -359,7 +359,7 @@ function TasksApp({ query }) {
|
||||
</button>
|
||||
</div>
|
||||
{logsExpandedForTask && (
|
||||
<TaskLogPanel state={logCache.get(t.id)} onRetry={() => loadTaskLogs(t.id)} />
|
||||
<TaskLogPanel state={logCache.get(t.id)} taskId={t.id} onRetry={() => loadTaskLogs(t.id)} />
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
@@ -69,6 +69,14 @@ const READS = [
|
||||
// separately rather than folded into either inventory above.
|
||||
const STREAMS = ["chatStream"];
|
||||
|
||||
// URL builders make no request at all: they hand a browser navigation to a
|
||||
// route the server serves as a file download, so the browser owns the
|
||||
// Content-Disposition filename and streams the body to disk. They are listed
|
||||
// separately because asserting a fetch contract on them would be wrong, and
|
||||
// leaving them out of this suite entirely is how an unclassified method
|
||||
// slipped through before.
|
||||
const URLS = ["taskLogDownloadURL"];
|
||||
|
||||
let calls = [];
|
||||
|
||||
function stubFetch(respond) {
|
||||
@@ -135,6 +143,19 @@ test("the chat stream posts its payload and asks for an event stream", async ()
|
||||
assert.equal(init.body, JSON.stringify({ text: "hi" }));
|
||||
});
|
||||
|
||||
// A URL builder must not fetch: the browser has to own the navigation for the
|
||||
// server's Content-Disposition filename to apply. A fetch here would consume
|
||||
// the attachment and lose its name.
|
||||
test("the task-log download URL is built, not fetched", async () => {
|
||||
stubFetch(() => {
|
||||
throw new Error("a download URL must not be fetched by the client");
|
||||
});
|
||||
|
||||
assert.equal(api.taskLogDownloadURL(7, 2), "/api/tasks/7/logs/download?attempt=2");
|
||||
assert.equal(api.taskLogDownloadURL(7, null), "/api/tasks/7/logs/download");
|
||||
assert.equal(calls.length, 0, "building a download URL must not make a request");
|
||||
});
|
||||
|
||||
test("a bodyless DELETE resolves on 204 without parsing a body", async () => {
|
||||
stubFetch(() => ({
|
||||
ok: true,
|
||||
@@ -175,6 +196,7 @@ test("every api method is classified by this suite", () => {
|
||||
...MUTATIONS.map(([name]) => name),
|
||||
...READS.map(([name]) => name),
|
||||
...STREAMS,
|
||||
...URLS,
|
||||
]);
|
||||
const actual = Object.keys(api).filter((key) => typeof api[key] === "function");
|
||||
const unclassified = actual.filter((name) => !classified.has(name)).sort();
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { render, cleanup } from "@testing-library/preact";
|
||||
import { TaskLogPanel } from "../src/tasks/task-logs.jsx";
|
||||
import { TaskLogPanel, taskLogDownloadURL } from "../src/tasks/task-logs.jsx";
|
||||
|
||||
function renderPanel(state, opts = {}) {
|
||||
const { container, unmount } = render(<TaskLogPanel state={state} onRetry={opts.onRetry} />);
|
||||
const { container, unmount } = render(<TaskLogPanel state={state} onRetry={opts.onRetry} taskId={opts.taskId} />);
|
||||
return { root: container, unmount };
|
||||
}
|
||||
|
||||
@@ -24,20 +24,37 @@ test("fetch failure renders a retry control", () => {
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("disabled response (task logging not enabled) renders a placeholder, not a crash", () => {
|
||||
// The panel used to answer every failed read with "Task logging is optional
|
||||
// and was not enabled for this run", which was false in a deployment where
|
||||
// logging is unconditional: the dashboard simply could not read the log. The
|
||||
// two conditions are now stated differently, and this pins that they stay so.
|
||||
test("a reader that is absent says the dashboard cannot read logs, not that logging is off", () => {
|
||||
const { root, unmount } = renderPanel({ disabled: true, entries: [] });
|
||||
assert.match(root.textContent, /No persisted log/);
|
||||
assert.doesNotMatch(
|
||||
root.textContent,
|
||||
/not enabled for this run/,
|
||||
"this text blames a configuration setting for a process that simply cannot read logs",
|
||||
);
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("an attempt with a reader but no log file is not reported as disabled", () => {
|
||||
const { root, unmount } = renderPanel({ found: false, entries: [], attempt: 0 });
|
||||
assert.match(root.textContent, /No log recorded for this attempt/);
|
||||
assert.doesNotMatch(root.textContent, /was not enabled for this run/);
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("empty entries render a placeholder distinct from the disabled state", () => {
|
||||
const { root, unmount } = renderPanel({ disabled: false, entries: [] });
|
||||
const { root, unmount } = renderPanel({ disabled: false, found: true, entries: [], attempt: 0 });
|
||||
assert.match(root.textContent, /Nothing recorded/);
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("entries render one row per entry with fields visible, surfacing stage/token detail", () => {
|
||||
const { root, unmount } = renderPanel({
|
||||
found: true,
|
||||
entries: [
|
||||
{
|
||||
time: "2026-01-01T00:00:00Z",
|
||||
@@ -64,3 +81,25 @@ test("entries render one row per entry with fields visible, surfacing stage/toke
|
||||
assert.match(root.textContent, /iteration/);
|
||||
unmount();
|
||||
});
|
||||
|
||||
// The download is the feature the panel was missing: an operator who wants the
|
||||
// log in their own tooling had no way to get it.
|
||||
test("the download link points at the attempt being shown", () => {
|
||||
assert.equal(taskLogDownloadURL(42, 3), "/api/tasks/42/logs/download?attempt=3");
|
||||
// No attempt yet resolved: let the server pick the task's current one.
|
||||
assert.equal(taskLogDownloadURL(42, null), "/api/tasks/42/logs/download");
|
||||
});
|
||||
|
||||
test("a panel with entries offers the download for that attempt", () => {
|
||||
const { root, unmount } = renderPanel({ found: true, attempt: 3, entries: [{ level: "info", msg: "hi" }] }, { taskId: 42 });
|
||||
const link = root.querySelector(".task-log-download");
|
||||
assert.ok(link, "a download control should render when the attempt has a log");
|
||||
assert.equal(link.getAttribute("href"), "/api/tasks/42/logs/download?attempt=3");
|
||||
unmount();
|
||||
});
|
||||
|
||||
test("a panel for an attempt with no log offers no download", () => {
|
||||
const { root, unmount } = renderPanel({ found: false, attempt: 0, entries: [] }, { taskId: 42 });
|
||||
assert.equal(root.querySelector(".task-log-download"), null, "there is nothing to download");
|
||||
unmount();
|
||||
});
|
||||
Reference in new issue
Block a user