Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

refactor: remove dashboard implementation and web assets

Jaana Doganc0d8e5bf10c2
diff --git a/cmd/ax/dashboard.go b/cmd/ax/dashboard.go
deleted file mode 100644
index 5762964..0000000
--- a/cmd/ax/dashboard.go
+++ /dev/null
@@ -1,475 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package main
-
-import (
- "context"
- "database/sql"
- _ "embed"
- "encoding/json"
- "fmt"
- "log/slog"
- "net"
- "net/http"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "time"
-
- "github.com/google/ax/cmd/ax/internal/cliutil"
- "github.com/google/ax/internal/controller/eventlog"
- "github.com/google/ax/proto"
- "github.com/spf13/cobra"
- _ "modernc.org/sqlite"
-)
-
-//go:embed web/index.html
-var dashboardHTML string
-
-var (
- dashboardAddr string
- dashboardConfigFile string
-)
-
-var dashboardCmd = &cobra.Command{
- Use: "dashboard",
- Short: "Start the AX Dashboard",
- Long: `Start a local HTTP server to display AX conversations and executions dashboard.`,
- RunE: runDashboard,
-}
-
-func init() {
- dashboardCmd.Flags().StringVar(&dashboardAddr, "addr", "localhost:8080", "Server address to listen on")
- dashboardCmd.Flags().StringVar(&dashboardConfigFile, "config", "ax.yaml", "Path to YAML configuration file")
-}
-
-type ConversationResponse struct {
- ID string `json:"id"`
- Agent string `json:"agent"`
- Status string `json:"status"`
- LastStep int32 `json:"last_step"`
- Duration string `json:"duration"`
-}
-
-func runDashboard(cmd *cobra.Command, args []string) error {
- ctx := cmd.Context()
- slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
-
- cfg, err := newConfig(cmd, dashboardConfigFile)
- if err != nil {
- return err
- }
-
- dbPath := cfg.EventLog.SQLiteConfig.Filename
- slog.InfoContext(ctx, "Opening event log database", slog.String("path", dbPath))
-
- if err := os.MkdirAll(filepath.Dir(dbPath), 0755); err != nil {
- return fmt.Errorf("failed to create database directory: %w", err)
- }
-
- db, err := sql.Open("sqlite", dbPath)
- if err != nil {
- return fmt.Errorf("failed to open sqlite database: %w", err)
- }
- defer db.Close()
-
- // Verify database connection
- if err := db.PingContext(ctx); err != nil {
- return fmt.Errorf("failed to ping database: %w", err)
- }
-
- // Create tables if they don't exist (to avoid crashes on fresh setup)
- if _, err := db.Exec(`
- CREATE TABLE IF NOT EXISTS conversation_log (
- conversation_id TEXT NOT NULL,
- seq INTEGER NOT NULL,
- payload TEXT NOT NULL,
- PRIMARY KEY (conversation_id, seq)
- )`); err != nil {
- return fmt.Errorf("failed to initialize conversation_log table: %w", err)
- }
-
- if _, err := db.Exec(`
- CREATE TABLE IF NOT EXISTS execution_log (
- exec_id TEXT NOT NULL,
- payload TEXT NOT NULL,
- timestamp DATETIME NOT NULL
- )`); err != nil {
- return fmt.Errorf("failed to initialize execution_log table: %w", err)
- }
-
- if _, err := db.Exec(`CREATE INDEX IF NOT EXISTS idx_execution_log_exec_id ON execution_log(exec_id)`); err != nil {
- return fmt.Errorf("failed to create index on execution_log: %w", err)
- }
-
- // Setup API handlers
- mux := http.NewServeMux()
- mux.HandleFunc("/api/conversations", func(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- convs, err := fetchConversations(r.Context(), db)
- if err != nil {
- slog.ErrorContext(r.Context(), "Failed to fetch conversations", slog.Any("error", err))
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(convs); err != nil {
- slog.ErrorContext(r.Context(), "Failed to encode conversations response", slog.Any("error", err))
- }
- })
-
- mux.HandleFunc("/api/trace", func(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodGet {
- http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
- return
- }
-
- convID := r.URL.Query().Get("conversation")
- if convID == "" {
- http.Error(w, "Missing conversation ID", http.StatusBadRequest)
- return
- }
-
- data, err := loadTraceData(r.Context(), cfg, convID)
- if err != nil {
- slog.ErrorContext(r.Context(), "Failed to load trace data", slog.String("conversation_id", convID), slog.Any("error", err))
- http.Error(w, "Internal server error", http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(data); err != nil {
- slog.ErrorContext(r.Context(), "Failed to encode trace data response", slog.Any("error", err))
- }
- })
-
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- fmt.Fprint(w, dashboardHTML)
- })
-
- listener, err := net.Listen("tcp", dashboardAddr)
- if err != nil {
- return fmt.Errorf("failed to bind server to %s: %w", dashboardAddr, err)
- }
- defer listener.Close()
-
- addr := listener.Addr().String()
- host, port, err := net.SplitHostPort(addr)
- if err == nil && (host == "::" || host == "0.0.0.0" || host == "" || host == "[::]") {
- addr = fmt.Sprintf("localhost:%s", port)
- }
- url := fmt.Sprintf("http://%s", addr)
-
- slog.InfoContext(ctx, "AX Dashboard started", slog.String("url", url))
-
- go openBrowser(url)
-
- server := &http.Server{
- Handler: mux,
- }
-
- return server.Serve(listener)
-}
-
-func fetchConversations(ctx context.Context, db *sql.DB) ([]ConversationResponse, error) {
- query := `
-SELECT
- c.conversation_id,
- c.last_step,
- c.state,
- e.agent_id,
- e.start_time,
- e.end_time
-FROM (
- SELECT conversation_id, step AS last_step,
- json_extract(payload, '$.exec_id') AS exec_id,
- json_extract(payload, '$.state') AS state
- FROM conversation_log
- WHERE (conversation_id, step) IN (
- SELECT conversation_id, MAX(step)
- FROM conversation_log
- GROUP BY conversation_id
- )
-) c
-LEFT JOIN (
- SELECT
- exec_id,
- json_extract(payload, '$.agent_id') AS agent_id,
- MIN(timestamp) AS start_time,
- MAX(timestamp) AS end_time
- FROM execution_log
- GROUP BY exec_id
-) e ON c.exec_id = e.exec_id;
-`
- rows, err := db.QueryContext(ctx, query)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- convs := []ConversationResponse{}
- for rows.Next() {
- var id string
- var lastStep int32
- var state string
- var agentID sql.NullString
- var startTimeStr, endTimeStr sql.NullString
-
- err := rows.Scan(&id, &lastStep, &state, &agentID, &startTimeStr, &endTimeStr)
- if err != nil {
- return nil, err
- }
-
- agent := "unknown"
- if agentID.Valid && agentID.String != "" {
- agent = agentID.String
- // Strip special prefix if it starts with "__"
- if len(agent) > 2 && agent[:2] == "__" {
- agent = agent[2:]
- }
- }
-
- durationStr := "N/A"
- if startTimeStr.Valid && endTimeStr.Valid {
- startTime, err1 := parseSQLiteTime(startTimeStr.String)
- endTime, err2 := parseSQLiteTime(endTimeStr.String)
- if err1 == nil && err2 == nil {
- duration := endTime.Sub(startTime)
- durationStr = fmt.Sprintf("%.1fs", duration.Seconds())
- } else {
- slog.WarnContext(ctx, "Failed to parse sqlite timestamps", slog.String("start", startTimeStr.String), slog.String("end", endTimeStr.String), slog.Any("err1", err1), slog.Any("err2", err2))
- }
- }
-
- status := state
- if len(status) > 6 && status[:6] == "STATE_" {
- status = status[6:]
- }
- if status == "PENDING" {
- status = "RUNNING"
- }
-
- convs = append(convs, ConversationResponse{
- ID: id,
- Agent: agent,
- Status: status,
- LastStep: lastStep,
- Duration: durationStr,
- })
- }
-
- return convs, nil
-}
-
-func parseSQLiteTime(s string) (time.Time, error) {
- layouts := []string{
- time.RFC3339Nano,
- time.RFC3339,
- "2006-01-02 15:04:05.999999999-07:00",
- "2006-01-02 15:04:05.999999999",
- "2006-01-02 15:04:05.999999999 -0700 MST",
- "2006-01-02 15:04:05",
- }
- var err error
- var t time.Time
- for _, layout := range layouts {
- t, err = time.Parse(layout, s)
- if err == nil {
- return t, nil
- }
- }
- return time.Time{}, err
-}
-
-func openBrowser(url string) {
- var err error
- switch runtime.GOOS {
- case "linux":
- err = exec.Command("xdg-open", url).Start()
- case "windows":
- err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
- case "darwin":
- err = exec.Command("open", url).Start()
- }
- if err != nil {
- fmt.Printf("Failed to open browser: %v\n", err)
- }
-}
-
-type Text struct {
- Text string `json:"text"`
-}
-
-type Approval struct {
- Approved bool `json:"approved"`
-}
-
-type Confirmation struct {
- ID string `json:"id"`
- Question string `json:"question,omitempty"`
- Approval *Approval `json:"approval,omitempty"`
-}
-
-type Content struct {
- Role string `json:"role"`
- Text *Text `json:"text,omitempty"`
- Confirmation *Confirmation `json:"confirmation,omitempty"`
-}
-
-type ExecutionEvent struct {
- ExecID string `json:"exec_id"`
- AgentID string `json:"agent_id"`
- Inputs []Content `json:"inputs"`
- Outputs []Content `json:"outputs"`
- State string `json:"state"`
- Timestamp time.Time `json:"timestamp"`
-}
-
-type ExecTrace struct {
- ExecID string `json:"exec_id"`
- AgentID string `json:"agent_id"`
- Events []ExecutionEvent `json:"events"`
-}
-
-type TraceData struct {
- ConversationID string `json:"conversation_id"`
- RootExecID string `json:"root_exec_id"`
- Execs []ExecTrace `json:"execs"`
-}
-
-func loadTraceData(ctx context.Context, cfg *cliutil.Config, convID string) (*TraceData, error) {
- events, rootExecID, execIDs, err := fetch(ctx, cfg, convID)
- if err != nil {
- return nil, err
- }
-
- // TODO(jbd): Trace view incorrectly displays graph executions. We are not
- // changing the EventLog interface to fix this because the executor is being
- // removed soon in favor of a linear execution model. We will adopt a different
- // style of visualization once that's done.
- return &TraceData{
- ConversationID: convID,
- RootExecID: rootExecID,
- Execs: buildExecTraces(execIDs, events),
- }, nil
-}
-
-func fetch(ctx context.Context, cfg *cliutil.Config, convID string) ([]*proto.ConversationEvent, string, []string, error) {
- evLog, err := eventlog.OpenSQLiteEventLog(cfg.EventLog.SQLiteConfig.Filename)
- if err != nil {
- return nil, "", nil, fmt.Errorf("could not open sqlite eventlog: %w", err)
- }
- defer evLog.Close()
-
- convEvents, err := evLog.Events(ctx, convID)
- if err != nil {
- return nil, "", nil, fmt.Errorf("failed to query conversation events: %w", err)
- }
-
- var execIDs []string
- seen := make(map[string]bool)
- for _, ev := range convEvents {
- if ev.ExecId != "" && !seen[ev.ExecId] {
- execIDs = append(execIDs, ev.ExecId)
- seen[ev.ExecId] = true
- }
- }
-
- if len(execIDs) == 0 {
- return nil, "", nil, fmt.Errorf("no executions found for conversation: %s", convID)
- }
-
- // Use the first execID as the rootExecID as requested by user
- rootExecID := execIDs[0]
-
- return convEvents, rootExecID, execIDs, nil
-}
-
-func buildExecTraces(execIDs []string, events []*proto.ConversationEvent) []ExecTrace {
- execsMap := make(map[string][]ExecutionEvent)
- harnessIDs := make(map[string]string)
-
- for _, protoEv := range events {
- exID := protoEv.ExecId
- if protoEv.HarnessId != "" {
- harnessIDs[exID] = protoEv.HarnessId
- }
- ev := extractExecutionEvent(exID, protoEv)
- execsMap[exID] = append(execsMap[exID], ev)
- }
-
- var execs []ExecTrace
- for _, execID := range execIDs {
- if evs, ok := execsMap[execID]; ok {
- agentID := harnessIDs[execID]
- execs = append(execs, ExecTrace{
- ExecID: execID,
- AgentID: agentID,
- Events: evs,
- })
- }
- }
-
- return execs
-}
-
-func extractMsgs(protoContents []*proto.Message) []Content {
- var results []Content
- for _, c := range protoContents {
- content := Content{Role: c.Role}
- msgContent := c.GetContent()
- if msgContent == nil {
- continue
- }
- if textC := msgContent.GetText(); textC != nil {
- content.Text = &Text{Text: textC.Text}
- } else if conf := msgContent.GetConfirmation(); conf != nil {
- content.Confirmation = &Confirmation{
- ID: conf.Id,
- Question: conf.Question,
- }
- if app := conf.GetApproval(); app != nil {
- content.Confirmation.Approval = &Approval{Approved: app.Approved}
- } else if dec := conf.GetDecline(); dec != nil {
- content.Confirmation.Approval = &Approval{Approved: !dec.Declined}
- }
- }
- results = append(results, content)
- }
- return results
-}
-
-func extractExecutionEvent(execID string, protoEv *proto.ConversationEvent) ExecutionEvent {
- ev := ExecutionEvent{
- ExecID: execID,
- AgentID: protoEv.HarnessId,
- }
-
- ev.State = fmt.Sprint(protoEv.State)
- if protoEv.HarnessId != "" {
- ev.Inputs = extractMsgs(protoEv.Messages)
- } else {
- ev.Outputs = extractMsgs(protoEv.Messages)
- }
-
- return ev
-}
diff --git a/cmd/ax/dashboard_test.go b/cmd/ax/dashboard_test.go
deleted file mode 100644
index ea5ceab..0000000
--- a/cmd/ax/dashboard_test.go
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2026 Google LLC
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package main
-
-import (
- "context"
- "database/sql"
- "testing"
- "time"
-
- _ "modernc.org/sqlite"
-)
-
-func TestFetchConversations(t *testing.T) {
- // Create an in-memory SQLite database for testing
- db, err := sql.Open("sqlite", ":memory:")
- if err != nil {
- t.Fatalf("failed to open in-memory db: %v", err)
- }
- defer db.Close()
-
- // Initialize the schema
- schema := `
- CREATE TABLE conversation_log (
- conversation_id TEXT,
- step INTEGER,
- timestamp DATETIME,
- payload TEXT
- );
-
- CREATE TABLE execution_log (
- exec_id TEXT,
- timestamp DATETIME,
- payload TEXT
- );
- `
- if _, err := db.Exec(schema); err != nil {
- t.Fatalf("failed to create schema: %v", err)
- }
-
- // Insert test data
- // Conversation 1: Only conversation_log (V2 execution without execution_log)
- _, err = db.Exec(`
- INSERT INTO conversation_log (conversation_id, step, timestamp, payload)
- VALUES ('conv-1', 1, ?, '{"exec_id": "exec-1", "state": "STATE_PENDING"}')
- `, time.Now().Format(time.RFC3339))
- if err != nil {
- t.Fatalf("failed to insert conv-1: %v", err)
- }
-
- // Conversation 2: Both conversation_log and execution_log (V1 execution)
- now := time.Now()
- start := now.Add(-5 * time.Second)
- end := now
-
- _, err = db.Exec(`
- INSERT INTO conversation_log (conversation_id, step, timestamp, payload)
- VALUES ('conv-2', 5, ?, '{"exec_id": "exec-2", "state": "STATE_COMPLETED"}')
- `, end.Format(time.RFC3339))
- if err != nil {
- t.Fatalf("failed to insert conv-2: %v", err)
- }
-
- _, err = db.Exec(`
- INSERT INTO execution_log (exec_id, timestamp, payload)
- VALUES
- ('exec-2', ?, '{"agent_id": "my-agent"}'),
- ('exec-2', ?, '{"agent_id": "my-agent"}')
- `, start.Format(time.RFC3339), end.Format(time.RFC3339))
- if err != nil {
- t.Fatalf("failed to insert exec-2: %v", err)
- }
-
- // Fetch the conversations
- ctx := context.Background()
- convs, err := fetchConversations(ctx, db)
- if err != nil {
- t.Fatalf("fetchConversations failed: %v", err)
- }
-
- if len(convs) != 2 {
- t.Fatalf("expected 2 conversations, got %d", len(convs))
- }
-
- // Create a map for easy lookup
- convMap := make(map[string]ConversationResponse)
- for _, c := range convs {
- convMap[c.ID] = c
- }
-
- // Check conv-1
- c1, ok := convMap["conv-1"]
- if !ok {
- t.Fatalf("conv-1 not found")
- }
- if c1.Status != "RUNNING" { // STATE_PENDING -> RUNNING
- t.Errorf("conv-1 expected status RUNNING, got %q", c1.Status)
- }
- if c1.Agent != "unknown" {
- t.Errorf("conv-1 expected agent unknown, got %q", c1.Agent)
- }
- if c1.Duration != "N/A" {
- t.Errorf("conv-1 expected duration N/A, got %q", c1.Duration)
- }
- if c1.LastStep != 1 {
- t.Errorf("conv-1 expected last_step 1, got %d", c1.LastStep)
- }
-
- // Check conv-2
- c2, ok := convMap["conv-2"]
- if !ok {
- t.Fatalf("conv-2 not found")
- }
- if c2.Status != "COMPLETED" { // STATE_COMPLETED -> COMPLETED
- t.Errorf("conv-2 expected status COMPLETED, got %q", c2.Status)
- }
- if c2.Agent != "my-agent" {
- t.Errorf("conv-2 expected agent my-agent, got %q", c2.Agent)
- }
- // Duration should be roughly 5.0s
- if c2.Duration != "5.0s" {
- t.Errorf("conv-2 expected duration 5.0s, got %q", c2.Duration)
- }
- if c2.LastStep != 5 {
- t.Errorf("conv-2 expected last_step 5, got %d", c2.LastStep)
- }
-}
diff --git a/cmd/ax/main.go b/cmd/ax/main.go
index acc9833..fddaf08 100644
--- a/cmd/ax/main.go
+++ b/cmd/ax/main.go
@@ -46,8 +46,6 @@ and run the controller server.`,
func init() {
rootCmd.AddCommand(execCmd)
rootCmd.AddCommand(serveCmd)
-
- rootCmd.AddCommand(dashboardCmd)
}
func connect(server string) (*grpc.ClientConn, error) {
diff --git a/cmd/ax/web/index.html b/cmd/ax/web/index.html
deleted file mode 100644
index 1f69c0c..0000000
--- a/cmd/ax/web/index.html
+++ /dev/null
@@ -1,1242 +0,0 @@
-<!--
-Copyright 2026 Google LLC
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-
-<!DOCTYPE html>
-<html lang="en">
-<head>
-<meta charset="UTF-8">
-<meta name="viewport" content="width=device-width, initial-scale=1.0">
-<title>AX Dashboard</title>
-<link rel="preconnect" href="https://fonts.googleapis.com">
-<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Fira+Code:wght@400;500&display=swap" rel="stylesheet">
-<style>
-:root {
- --bg-page: #0b0f19;
- --bg-card: #161b26;
- --bg-card-hover: #1e2538;
- --border-color: rgba(255, 255, 255, 0.08);
- --text-primary: #f3f4f6;
- --text-secondary: #9ca3af;
- --text-muted: #6b7280;
-
- --color-success: #10b981;
- --color-success-bg: rgba(16, 185, 129, 0.15);
- --color-warning: #f59e0b;
- --color-warning-bg: rgba(245, 158, 11, 0.15);
- --color-danger: #ef4444;
- --color-danger-bg: rgba(239, 68, 68, 0.15);
-
- --color-accent: #6366f1;
- --color-accent-hover: #4f46e5;
- --color-accent-bg: rgba(99, 102, 241, 0.15);
-}
-
-* {
- box-sizing: border-box;
- margin: 0;
- padding: 0;
-}
-
-body {
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
- background-color: var(--bg-page);
- color: var(--text-primary);
- height: 100vh;
- display: flex;
- flex-direction: column;
- overflow: hidden;
-}
-
-/* Header */
-.hdr {
- background: rgba(11, 15, 25, 0.8);
- backdrop-filter: blur(12px);
- border-bottom: 1px solid var(--border-color);
- padding: 16px 24px;
- display: flex;
- align-items: center;
- justify-content: space-between;
- flex-shrink: 0;
- z-index: 10;
-}
-
-.hdr-left {
- display: flex;
- align-items: center;
- gap: 12px;
-}
-
-.hdr-logo {
- font-size: 24px;
- color: var(--color-accent);
- font-weight: 700;
- animation: pulse 2s infinite;
-}
-
-@keyframes pulse {
- 0% { transform: scale(1); opacity: 0.9; }
- 50% { transform: scale(1.05); opacity: 1; text-shadow: 0 0 10px rgba(99, 102, 241, 0.5); }
- 100% { transform: scale(1); opacity: 0.9; }
-}
-
-.hdr h1 {
- font-size: 18px;
- font-weight: 600;
- letter-spacing: -0.025em;
-}
-
-.hdr-status {
- display: flex;
- align-items: center;
- gap: 8px;
- font-size: 13px;
- color: var(--text-secondary);
-}
-
-.status-dot {
- width: 8px;
- height: 8px;
- background-color: var(--color-success);
- border-radius: 50%;
- box-shadow: 0 0 8px var(--color-success);
-}
-
-.status-dot.loading {
- background-color: var(--color-warning);
- box-shadow: 0 0 8px var(--color-warning);
- animation: blink 1s infinite alternate;
-}
-
-@keyframes blink {
- from { opacity: 0.4; } to { opacity: 1; }
-}
-
-/* Layout Container */
-.layout {
- display: flex;
- flex: 1;
- overflow: hidden;
- position: relative;
-}
-
-/* Dashboard View */
-.view-panel {
- flex: 1;
- display: flex;
- flex-direction: column;
- padding: 24px;
- overflow-y: auto;
- gap: 24px;
- transition: transform 0.3s ease, opacity 0.3s ease;
-}
-
-.view-panel.hidden {
- display: none;
-}
-
-/* Metrics Row */
-.metrics-row {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
- gap: 16px;
-}
-
-.metric-card {
- background: var(--bg-card);
- border: 1px solid var(--border-color);
- border-radius: 12px;
- padding: 20px;
- display: flex;
- align-items: center;
- justify-content: space-between;
- transition: transform 0.2s, border-color 0.2s;
-}
-
-.metric-card:hover {
- transform: translateY(-2px);
- border-color: rgba(255, 255, 255, 0.15);
-}
-
-.metric-info h3 {
- font-size: 13px;
- color: var(--text-secondary);
- font-weight: 500;
- margin-bottom: 6px;
- text-transform: uppercase;
- letter-spacing: 0.05em;
-}
-
-.metric-value {
- font-size: 28px;
- font-weight: 700;
-}
-
-.metric-icon {
- width: 44px;
- height: 44px;
- border-radius: 10px;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 20px;
-}
-
-.metric-card.active .metric-icon { background: var(--color-warning-bg); color: var(--color-warning); }
-.metric-card.completed .metric-icon { background: var(--color-success-bg); color: var(--color-success); }
-.metric-card.failed .metric-icon { background: var(--color-danger-bg); color: var(--color-danger); }
-.metric-card.total .metric-icon { background: var(--color-accent-bg); color: var(--color-accent); }
-
-/* Controls (Search & Filter) */
-.controls-bar {
- display: flex;
- gap: 16px;
- align-items: center;
- flex-wrap: wrap;
-}
-
-.search-wrapper {
- flex: 1;
- min-width: 260px;
- position: relative;
-}
-
-.search-input {
- width: 100%;
- background: var(--bg-card);
- border: 1px solid var(--border-color);
- color: var(--text-primary);
- padding: 12px 16px;
- border-radius: 8px;
- font-size: 14px;
- outline: none;
- transition: border-color 0.2s;
-}
-
-.search-input:focus {
- border-color: var(--color-accent);
-}
-
-.filter-select {
- background: var(--bg-card);
- border: 1px solid var(--border-color);
- color: var(--text-primary);
- padding: 12px 16px;
- border-radius: 8px;
- font-size: 14px;
- outline: none;
- cursor: pointer;
- min-width: 150px;
-}
-
-.filter-select:focus {
- border-color: var(--color-accent);
-}
-
-.refresh-control {
- display: flex;
- align-items: center;
- gap: 8px;
- font-size: 13px;
- color: var(--text-secondary);
- user-select: none;
- cursor: pointer;
-}
-
-.refresh-control input {
- cursor: pointer;
-}
-
-/* Conversations List Table */
-.table-card {
- background: var(--bg-card);
- border: 1px solid var(--border-color);
- border-radius: 12px;
- overflow: hidden;
-}
-
-.conv-table {
- width: 100%;
- border-collapse: collapse;
- text-align: left;
-}
-
-.conv-table th {
- padding: 14px 20px;
- background: rgba(255, 255, 255, 0.02);
- border-bottom: 1px solid var(--border-color);
- color: var(--text-secondary);
- font-size: 12px;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.05em;
-}
-
-.conv-table td {
- padding: 16px 20px;
- border-bottom: 1px solid var(--border-color);
- font-size: 14px;
- vertical-align: middle;
-}
-
-.conv-table tr:last-child td {
- border-bottom: none;
-}
-
-.conv-table tr:hover td {
- background: rgba(255, 255, 255, 0.01);
-}
-
-.conv-id {
- font-family: 'Fira Code', monospace;
- font-weight: 500;
-}
-
-.agent-badge-table {
- font-family: 'Fira Code', monospace;
- font-size: 12px;
- padding: 4px 8px;
- border-radius: 6px;
- background: rgba(255, 255, 255, 0.05);
- color: var(--text-primary);
- border: 1px solid var(--border-color);
-}
-
-/* Status Badges */
-.badge {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-size: 11px;
- font-weight: 600;
- padding: 4px 10px;
- border-radius: 9999px;
- text-transform: uppercase;
- letter-spacing: 0.05em;
-}
-
-.badge-running { background: var(--color-warning-bg); color: var(--color-warning); }
-.badge-completed { background: var(--color-success-bg); color: var(--color-success); }
-.badge-failed { background: var(--color-danger-bg); color: var(--color-danger); }
-
-.badge-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background-color: currentColor;
-}
-
-.btn-trace {
- background: var(--color-accent-bg);
- color: #a5b4fc;
- border: 1px solid rgba(99, 102, 241, 0.3);
- padding: 6px 12px;
- border-radius: 6px;
- font-size: 12px;
- font-weight: 500;
- cursor: pointer;
- transition: all 0.2s;
- display: inline-flex;
- align-items: center;
- gap: 4px;
-}
-
-.btn-trace:hover {
- background: var(--color-accent);
- color: #fff;
- border-color: var(--color-accent);
-}
-
-.empty-state {
- padding: 48px;
- text-align: center;
- color: var(--text-secondary);
-}
-
-.empty-state-icon {
- font-size: 32px;
- margin-bottom: 12px;
-}
-
-/* Trace View Panel (Slides In) */
-.trace-panel {
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background-color: var(--bg-page);
- z-index: 20;
- display: flex;
- flex-direction: column;
- padding: 24px;
- overflow-y: auto;
- gap: 20px;
- transform: translateX(100%);
- opacity: 0;
- transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
-}
-
-.trace-panel.active {
- transform: translateX(0);
- opacity: 1;
-}
-
-.trace-header-row {
- display: flex;
- align-items: center;
- justify-content: space-between;
- border-bottom: 1px solid var(--border-color);
- padding-bottom: 16px;
- flex-shrink: 0;
-}
-
-.btn-back {
- background: transparent;
- border: 1px solid var(--border-color);
- color: var(--text-primary);
- padding: 8px 16px;
- border-radius: 8px;
- font-size: 14px;
- font-weight: 500;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 8px;
- transition: background 0.2s;
-}
-
-.btn-back:hover {
- background: rgba(255, 255, 255, 0.05);
-}
-
-.trace-title-info {
- text-align: right;
-}
-
-.trace-title-info h2 {
- font-size: 16px;
- font-weight: 600;
- margin-bottom: 4px;
-}
-
-.trace-title-info p {
- font-family: 'Fira Code', monospace;
- font-size: 13px;
- color: var(--text-secondary);
-}
-
-/* Timeline component */
-.timeline-card {
- background: var(--bg-card);
- border: 1px solid var(--border-color);
- border-radius: 12px;
- padding: 20px;
-}
-
-.timeline-title {
- font-size: 12px;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: var(--text-secondary);
- margin-bottom: 16px;
-}
-
-.tl-rows {
- display: flex;
- flex-direction: column;
- gap: 10px;
-}
-
-.tl-row {
- display: flex;
- align-items: center;
- gap: 16px;
-}
-
-.tl-label {
- width: 140px;
- flex-shrink: 0;
- font-size: 12px;
- font-family: 'Fira Code', monospace;
- color: var(--text-secondary);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.tl-track {
- flex: 1;
- height: 24px;
- background: rgba(255, 255, 255, 0.03);
- border-radius: 6px;
- position: relative;
- border: 1px solid rgba(255, 255, 255, 0.03);
-}
-
-.tl-bar {
- height: 100%;
- border-radius: 5px;
- position: absolute;
- display: flex;
- align-items: center;
- padding: 0 8px;
- min-width: 8px;
- cursor: pointer;
- transition: filter 0.2s;
-}
-
-.tl-bar:hover {
- filter: brightness(1.2);
-}
-
-.tl-bar span {
- font-size: 11px;
- font-weight: 600;
- color: #fff;
- white-space: nowrap;
- overflow: hidden;
- text-shadow: 0 1px 2px rgba(0,0,0,0.5);
-}
-
-.tl-bar.c0 { background: #818cf8; }
-.tl-bar.c1 { background: #34d399; }
-.tl-bar.c2 { background: #fbbf24; }
-.tl-bar.c3 { background: #c084fc; }
-.tl-bar.c4 { background: #f87171; }
-.tl-bar.c5 { background: #2dd4bf; }
-.tl-bar.c6 { background: #f472b6; }
-
-/* Execution Details Cards */
-.exec-list {
- display: flex;
- flex-direction: column;
- gap: 16px;
-}
-
-.exec-card {
- background: var(--bg-card);
- border: 1px solid var(--border-color);
- border-radius: 12px;
- overflow: hidden;
-}
-
-.exec-card-hdr {
- padding: 16px 20px;
- display: flex;
- align-items: center;
- gap: 12px;
- cursor: pointer;
- user-select: none;
- background: rgba(255, 255, 255, 0.01);
- border-bottom: 1px solid var(--border-color);
-}
-
-.exec-card-hdr:hover {
- background: rgba(255, 255, 255, 0.02);
-}
-
-.expand-ico {
- color: var(--text-secondary);
- font-size: 12px;
- transition: transform 0.2s;
- flex-shrink: 0;
-}
-
-.exec-card-hdr.collapsed .expand-ico {
- transform: rotate(-90deg);
-}
-
-.exec-card-body.hidden {
- display: none;
-}
-
-.exec-name {
- font-family: 'Fira Code', monospace;
- font-size: 14px;
- font-weight: 600;
-}
-
-.agent-badge {
- font-size: 12px;
- padding: 4px 10px;
- border-radius: 6px;
- background: rgba(99, 102, 241, 0.1);
- color: #a5b4fc;
- border: 1px solid rgba(99, 102, 241, 0.2);
- font-family: 'Fira Code', monospace;
-}
-
-.exec-card-hdr .badge {
- margin-left: auto;
-}
-
-.event {
- border-top: 1px solid var(--border-color);
-}
-
-.event:first-child {
- border-top: none;
-}
-
-.state-evt {
- padding: 10px 20px;
- font-size: 12px;
- color: var(--text-secondary);
- font-style: italic;
- background: rgba(255, 255, 255, 0.005);
- display: flex;
- align-items: center;
- gap: 10px;
-}
-
-.state-evt .etime {
- font-family: 'Fira Code', monospace;
- color: var(--text-muted);
-}
-
-.evt-meta {
- padding: 12px 20px 4px;
- display: flex;
- align-items: center;
- gap: 10px;
-}
-
-.etime {
- font-size: 12px;
- color: var(--text-muted);
- font-family: 'Fira Code', monospace;
-}
-
-.evt-section-label {
- font-size: 10px;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: var(--text-muted);
-}
-
-.content-list {
- padding: 4px 20px 14px;
- display: flex;
- flex-direction: column;
- gap: 8px;
-}
-
-.content-item {
- border-radius: 8px;
- overflow: hidden;
- border: 1px solid var(--border-color);
-}
-
-.role-user { border-color: rgba(99, 102, 241, 0.2); }
-.role-user .c-hdr { background: rgba(99, 102, 241, 0.08); color: #818cf8; }
-.role-user .c-body { background: rgba(99, 102, 241, 0.02); }
-
-.role-model { border-color: rgba(16, 185, 129, 0.2); }
-.role-model .c-hdr { background: rgba(16, 185, 129, 0.08); color: #34d399; }
-.role-model .c-body { background: rgba(16, 185, 129, 0.02); }
-
-.role-agent { border-color: rgba(45, 212, 191, 0.2); }
-.role-agent .c-hdr { background: rgba(45, 212, 191, 0.08); color: #2dd4bf; }
-.role-agent .c-body { background: rgba(45, 212, 191, 0.02); }
-
-.role-assistant { border-color: rgba(192, 132, 252, 0.2); }
-.role-assistant .c-hdr { background: rgba(192, 132, 252, 0.08); color: #c084fc; }
-.role-assistant .c-body { background: rgba(192, 132, 252, 0.02); }
-
-.role-unspecified, .role-unknown { border-color: var(--border-color); }
-.role-unspecified .c-hdr, .role-unknown .c-hdr { background: rgba(255, 255, 255, 0.04); color: var(--text-secondary); }
-.role-unspecified .c-body, .role-unknown .c-body { background: rgba(255, 255, 255, 0.005); }
-
-.c-hdr {
- font-size: 10px;
- font-weight: 700;
- padding: 4px 12px;
- text-transform: uppercase;
- letter-spacing: 0.05em;
-}
-
-.c-body {
- padding: 10px 12px;
- font-size: 13px;
- line-height: 1.6;
-}
-
-.txt {
- white-space: pre-wrap;
- word-break: break-word;
-}
-
-.txt pre {
- background: #090d16;
- color: #e2e8f0;
- padding: 12px;
- border-radius: 6px;
- overflow-x: auto;
- font-size: 12px;
- line-height: 1.5;
- margin: 6px 0;
- font-family: 'Fira Code', monospace;
- border: 1px solid var(--border-color);
-}
-
-.txt code {
- font-family: 'Fira Code', monospace;
-}
-
-.conf-q {
- background: rgba(245, 158, 11, 0.05);
- border: 1px solid rgba(245, 158, 11, 0.2);
- border-radius: 6px;
- padding: 8px 12px;
- font-size: 13px;
- color: #fbbf24;
-}
-
-.conf-q::before {
- content: "? ";
- font-weight: 700;
- color: #fbbf24;
-}
-
-.conf-approved {
- font-size: 12px;
- color: var(--color-success);
- font-weight: 600;
- display: flex;
- align-items: center;
- gap: 6px;
-}
-.conf-approved::before {
- content: "βœ“";
- font-size: 14px;
-}
-
-.conf-denied {
- font-size: 12px;
- color: var(--color-danger);
- font-weight: 600;
- display: flex;
- align-items: center;
- gap: 6px;
-}
-.conf-denied::before {
- content: "βœ—";
- font-size: 14px;
-}
-
-/* Custom Scrollbar */
-::-webkit-scrollbar {
- width: 8px;
- height: 8px;
-}
-::-webkit-scrollbar-track {
- background: var(--bg-page);
-}
-::-webkit-scrollbar-thumb {
- background: rgba(255, 255, 255, 0.1);
- border-radius: 4px;
-}
-::-webkit-scrollbar-thumb:hover {
- background: rgba(255, 255, 255, 0.2);
-}
-</style>
-</head>
-<body>
-
-<!-- Header -->
-<div class="hdr">
- <div class="hdr-left">
- <span class="hdr-logo">⬑</span>
- <h1>AX Dashboard</h1>
- </div>
- <div class="hdr-status">
- <span class="status-dot" id="status-dot"></span>
- <span id="status-text">Connected</span>
- </div>
-</div>
-
-<div class="layout">
- <!-- Dashboard Main Panel -->
- <div class="view-panel" id="dashboard-view">
- <!-- Metrics Row -->
- <div class="metrics-row">
- <div class="metric-card total">
- <div class="metric-info">
- <h3>Total</h3>
- <div class="metric-value" id="metric-total">0</div>
- </div>
- <div class="metric-icon">Ξ£</div>
- </div>
- <div class="metric-card active">
- <div class="metric-info">
- <h3>Active</h3>
- <div class="metric-value" id="metric-active">0</div>
- </div>
- <div class="metric-icon">⚑</div>
- </div>
- <div class="metric-card completed">
- <div class="metric-info">
- <h3>Completed</h3>
- <div class="metric-value" id="metric-completed">0</div>
- </div>
- <div class="metric-icon">βœ“</div>
- </div>
- <div class="metric-card failed">
- <div class="metric-info">
- <h3>Failed</h3>
- <div class="metric-value" id="metric-failed">0</div>
- </div>
- <div class="metric-icon">βœ—</div>
- </div>
- </div>
-
- <!-- Controls -->
- <div class="controls-bar">
- <div class="search-wrapper">
- <input type="text" id="search-input" class="search-input" placeholder="Search conversations by ID or Agent...">
- </div>
- <select id="filter-select" class="filter-select">
- <option value="ALL">All Statuses</option>
- <option value="RUNNING">Running</option>
- <option value="COMPLETED">Completed</option>
- <option value="FAILED">Failed</option>
- </select>
- <label class="refresh-control">
- <input type="checkbox" id="poll-enable" checked>
- Live Polling (3s)
- </label>
- </div>
-
- <!-- Table Card -->
- <div class="table-card">
- <table class="conv-table" id="conv-table">
- <thead>
- <tr>
- <th>Conversation ID</th>
- <th>Agent</th>
- <th>Status</th>
- <th>Last Step</th>
- <th>Duration</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody id="conv-tbody">
- <!-- Dynamically populated rows -->
- </tbody>
- </table>
- <div id="empty-state" class="empty-state" style="display: none;">
- <div class="empty-state-icon">πŸ”</div>
- <div>No conversations found matching criteria.</div>
- </div>
- </div>
- </div>
-
- <!-- Trace View Panel -->
- <div class="trace-panel" id="trace-view">
- <div class="trace-header-row">
- <button class="btn-back" onclick="closeTraceView()">
- ← Back to Dashboard
- </button>
- <div class="trace-title-info">
- <h2 id="trace-title">Execution Trace</h2>
- <p id="trace-conv-id"></p>
- </div>
- </div>
-
- <!-- Timeline Card -->
- <div class="timeline-card" id="timeline-card">
- <div class="timeline-title">Execution Timeline</div>
- <div class="tl-rows" id="tl-rows">
- <!-- Dynamically populated timeline bars -->
- </div>
- </div>
-
- <!-- Execution Details Cards List -->
- <div class="exec-list" id="exec-list">
- <!-- Dynamically populated cards -->
- </div>
- </div>
-</div>
-
-<script>
-// State Management
-let conversations = [];
-let pollInterval = null;
-let activeConversationId = null;
-
-// DOM Elements
-const searchInput = document.getElementById('search-input');
-const filterSelect = document.getElementById('filter-select');
-const pollEnable = document.getElementById('poll-enable');
-const convTbody = document.getElementById('conv-tbody');
-const emptyState = document.getElementById('empty-state');
-const statusDot = document.getElementById('status-dot');
-const statusText = document.getElementById('status-text');
-
-const metricTotal = document.getElementById('metric-total');
-const metricActive = document.getElementById('metric-active');
-const metricCompleted = document.getElementById('metric-completed');
-const metricFailed = document.getElementById('metric-failed');
-
-// Initial Load & Polling setup
-function init() {
- fetchConversations();
- setupPolling();
-
- searchInput.addEventListener('input', renderDashboard);
- filterSelect.addEventListener('change', renderDashboard);
- pollEnable.addEventListener('change', setupPolling);
-}
-
-// Fetch lists of conversations from the API
-async function fetchConversations() {
- try {
- statusDot.className = 'status-dot loading';
- statusText.textContent = 'Updating...';
-
- const response = await fetch('/api/conversations');
- if (!response.ok) throw new Error('API request failed');
- conversations = await response.json() || [];
-
- statusDot.className = 'status-dot';
- statusText.textContent = 'Connected';
-
- updateMetrics();
- renderDashboard();
- } catch (error) {
- console.error('Error fetching conversations:', error);
- statusDot.className = 'status-dot loading';
- statusText.textContent = 'Connection Error';
- }
-}
-
-function setupPolling() {
- if (pollInterval) {
- clearInterval(pollInterval);
- pollInterval = null;
- }
-
- if (pollEnable.checked) {
- pollInterval = setInterval(() => {
- // If we are looking at a trace, poll that trace, otherwise poll the main list
- if (activeConversationId) {
- fetchTrace(activeConversationId, true);
- } else {
- fetchConversations();
- }
- }, 3000);
- }
-}
-
-function updateMetrics() {
- metricTotal.textContent = conversations.length;
- metricActive.textContent = conversations.filter(c => c.status === 'RUNNING' || c.status === 'PENDING').length;
- metricCompleted.textContent = conversations.filter(c => c.status === 'COMPLETED').length;
- metricFailed.textContent = conversations.filter(c => c.status === 'FAILED').length;
-}
-
-function renderDashboard() {
- const query = searchInput.value.toLowerCase().trim();
- const filter = filterSelect.value;
-
- const filtered = conversations.filter(c => {
- const matchesSearch = c.id.toLowerCase().includes(query) || c.agent.toLowerCase().includes(query);
- const matchesFilter = filter === 'ALL' || c.status === filter;
- return matchesSearch && matchesFilter;
- });
-
- if (filtered.length === 0) {
- convTbody.innerHTML = '';
- emptyState.style.display = 'block';
- return;
- }
-
- emptyState.style.display = 'none';
-
- convTbody.innerHTML = filtered.map(c => {
- let statusClass = 'badge-running';
- if (c.status === 'COMPLETED') statusClass = 'badge-completed';
- if (c.status === 'FAILED') statusClass = 'badge-failed';
-
- return `
- <tr>
- <td class="conv-id">${esc(c.id)}</td>
- <td><span class="agent-badge-table">${esc(c.agent)}</span></td>
- <td>
- <span class="badge ${statusClass}">
- <span class="badge-dot"></span>
- ${esc(c.status)}
- </span>
- </td>
- <td>${c.last_step}</td>
- <td>${esc(c.duration)}</td>
- <td>
- <button class="btn-trace" onclick="openTraceView('${esc(c.id)}')">
- πŸ“Š View Trace
- </button>
- </td>
- </tr>
- `;
- }).join('');
-}
-
-// Trace Details Fetching and Rendering
-async function openTraceView(conversationId) {
- activeConversationId = conversationId;
- document.getElementById('trace-conv-id').textContent = conversationId;
- document.getElementById('exec-list').innerHTML = '<div style="padding: 20px; text-align: center; color: var(--text-secondary);">Loading execution trace...</div>';
- document.getElementById('tl-rows').innerHTML = '';
- document.getElementById('timeline-card').style.display = 'none';
-
- document.getElementById('trace-view').classList.add('active');
- document.getElementById('dashboard-view').classList.add('hidden');
-
- await fetchTrace(conversationId);
-}
-
-function closeTraceView() {
- activeConversationId = null;
- document.getElementById('trace-view').classList.remove('active');
- document.getElementById('dashboard-view').classList.remove('hidden');
- fetchConversations(); // Update list immediately when coming back
-}
-
-async function fetchTrace(conversationId, quiet = false) {
- try {
- if (!quiet) {
- statusDot.className = 'status-dot loading';
- statusText.textContent = 'Loading Trace...';
- }
-
- const response = await fetch(`/api/trace?conversation=${conversationId}`);
- if (!response.ok) throw new Error('Failed to load trace');
-
- const traceData = await response.json();
-
- statusDot.className = 'status-dot';
- statusText.textContent = 'Connected';
-
- renderTrace(traceData);
- } catch (error) {
- console.error('Error fetching trace:', error);
- if (!quiet) {
- document.getElementById('exec-list').innerHTML = `<div style="padding: 20px; text-align: center; color: var(--color-danger);">Failed to load trace: ${esc(error.message)}</div>`;
- }
- }
-}
-
-// Ported trace rendering logic from trace.go
-function esc(s){
- if(s==null)return '';
- return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
-}
-
-function fmtTime(ts){
- const d=new Date(ts);
- return d.toLocaleTimeString('en-US',{hour12:false,hour:'2-digit',minute:'2-digit',second:'2-digit',fractionalSecondDigits:3});
-}
-
-const BT=String.fromCharCode(96);
-const FENCE=BT+BT+BT;
-const reSplit=new RegExp('('+FENCE+'(?:[^\\n]*)?\\n[\\s\\S]*?'+FENCE+')');
-const reMatch=new RegExp('^'+FENCE+'([^\\n]*)?\\n([\\s\\S]*)'+FENCE+'$');
-function renderText(raw){
- const parts=raw.split(reSplit);
- return parts.map(part=>{
- const m=part.match(reMatch);
- if(m){return '<pre><code>'+esc(m[2])+'</code></pre>';}
- return '<span class="txt">'+esc(part)+'</span>';
- }).join('');
-}
-
-function renderContent(c){
- const role=c.role||'unknown';
- let body='';
- if(c.text){
- body='<div class="c-body"><div class="txt">'+renderText(c.text.text)+'</div></div>';
- } else if(c.confirmation){
- const cf=c.confirmation;
- if(cf.question){
- body='<div class="c-body"><div class="conf-q">'+esc(cf.question)+'</div></div>';
- } else if(cf.approval!=null){
- const cls=cf.approval.approved?'conf-approved':'conf-denied';
- body='<div class="c-body"><div class="'+cls+'"></div></div>';
- }
- }
- if(!body)return '';
- return '<div class="content-item role-'+esc(role)+'"><div class="c-hdr">'+esc(role)+'</div>'+body+'</div>';
-}
-
-function renderEvent(ev){
- const time=fmtTime(ev.timestamp);
- const hasIn=ev.inputs&&ev.inputs.length>0;
- const hasOut=ev.outputs&&ev.outputs.length>0;
-
- if(!hasIn&&!hasOut&&ev.state){
- return `<div class="event"><div class="state-evt"><span class="etime">${esc(time)}</span>State β†’ ${esc(ev.state)}</div></div>`;
- }
-
- let html=`<div class="event"><div class="evt-meta"><span class="etime">${esc(time)}</span></div>`;
- if(hasIn){
- html+='<div class="content-list">';
- ev.inputs.forEach(c=>{html+=renderContent(c);});
- html+='</div>';
- }
- if(hasOut){
- html+='<div class="content-list">';
- ev.outputs.forEach(c=>{html+=renderContent(c);});
- html+='</div>';
- }
- html+='</div>';
- return html;
-}
-
-function getLastState(events){
- for(let i=events.length-1;i>=0;i--){
- if(events[i].state)return events[i].state;
- }
- return null;
-}
-
-function renderTrace(data) {
- if (!data.execs || data.execs.length === 0) {
- document.getElementById('exec-list').innerHTML = '<div style="padding: 20px; text-align: center; color: var(--text-secondary);">No executions recorded for this conversation yet.</div>';
- document.getElementById('timeline-card').style.display = 'none';
- return;
- }
-
- // Save currently expanded card IDs before clearing the list
- const expandedCardIds = new Set();
- document.querySelectorAll('.exec-card').forEach(card => {
- const hdr = card.querySelector('.exec-card-hdr');
- if (hdr && !hdr.classList.contains('collapsed')) {
- expandedCardIds.add(card.id);
- }
- });
-
- // If this is the first load (e.g. no cards in DOM yet), expand the root card by default
- const isFirstLoad = document.querySelectorAll('.exec-card').length === 0;
- if (isFirstLoad && data.root_exec_id) {
- expandedCardIds.add(`card-${data.root_exec_id}`);
- }
-
- // Build timeline
- const execTimes=data.execs.map(e=>{
- const ts=e.events.map(ev=>new Date(ev.timestamp).getTime());
- const start=ts.length?Math.min(...ts):null;
- const end=ts.length?Math.max(...ts):null;
- return{execID:e.exec_id,start,end};
- });
- execTimes.sort((a,b)=>{
- if(a.start==null)return 1;
- if(b.start==null)return -1;
- return a.start-b.start;
- });
- let minT=null,maxT=null;
- execTimes.forEach(({start,end})=>{
- if(start!=null){
- if(minT==null||start<minT)minT=start;
- if(maxT==null||end>maxT)maxT=end;
- }
- });
- const span=maxT-minT||1;
-
- document.getElementById('timeline-card').style.display = 'block';
-
- let tlHtml = '';
- execTimes.forEach(({execID,start,end},i)=>{
- const shortName=execID===data.root_exec_id?'root':execID.slice(data.root_exec_id.length+1);
- const left=start!=null?((start-minT)/span*100).toFixed(2):0;
- const width=start!=null?Math.max((end-start)/span*100,0.4).toFixed(2):0;
- const dur=end-start;
- const durStr=dur<1000?dur+'ms':(dur/1000).toFixed(2)+'s';
- const colorCls='c'+(i%7);
- tlHtml+=`
- <div class="tl-row">
- <div class="tl-label" title="${esc(execID)}">${esc(shortName)}</div>
- <div class="tl-track">
- <div class="tl-bar ${colorCls}" style="left:${left}%;width:${width}%;" title="${esc(durStr)}" onclick="scrollToCard('${esc(execID)}')">
- <span>${esc(durStr)}</span>
- </div>
- </div>
- </div>
- `;
- });
- document.getElementById('tl-rows').innerHTML = tlHtml;
-
- // Render execution details cards
- let execListHtml = '';
- data.execs.forEach((exec,i)=>{
- const shortName=exec.exec_id===data.root_exec_id?'root':exec.exec_id.slice(data.root_exec_id.length+1);
- const lastState=getLastState(exec.events);
-
- let statusClass = 'badge-running';
- if (lastState === 'STATE_COMPLETED') statusClass = 'badge-completed';
- if (lastState === 'STATE_FAILED') statusClass = 'badge-failed';
-
- const stateBadge=lastState?`<span class="badge ${statusClass}"><span class="badge-dot"></span>${esc(lastState.replace('STATE_',''))}</span>`:'';
-
- const cardId = `card-${exec.exec_id}`;
- const isExpanded = expandedCardIds.has(cardId);
- const hdrClass = isExpanded ? '' : 'collapsed';
- const bodyClass = isExpanded ? 'exec-card-body-content' : 'exec-card-body-content hidden';
- const bodyWrapperClass = isExpanded ? '' : 'hidden';
-
- execListHtml+=`
- <div class="exec-card" id="${esc(cardId)}">
- <div class="exec-card-hdr ${hdrClass}" onclick="toggleCard(this)">
- <span class="expand-ico">β–Ό</span>
- <span class="exec-name">${esc(shortName)}</span>
- <span class="agent-badge">${esc(exec.agent_id||'β€”')}</span>
- ${stateBadge}
- </div>
- <div class="exec-card-body ${bodyWrapperClass}">
- <div class="${bodyClass}">
- ${exec.events.map(ev => renderEvent(ev)).join('')}
- </div>
- </div>
- </div>
- `;
- });
-
- document.getElementById('exec-list').innerHTML = execListHtml;
-}
-
-function scrollToCard(execID){
- const el=document.getElementById('card-'+execID);
- if(!el)return;
- const hdr=el.querySelector('.exec-card-hdr');
- const body=el.querySelector('.exec-card-body');
- if(hdr&&hdr.classList.contains('collapsed')){
- hdr.classList.remove('collapsed');
- body.classList.remove('hidden');
- }
- el.scrollIntoView({behavior:'smooth',block:'start'});
-}
-
-function toggleCard(hdr){
- hdr.classList.toggle('collapsed');
- hdr.nextElementSibling.classList.toggle('hidden');
-}
-
-// Initial boot
-window.onload = init;
-</script>
-</body>
-</html>